Gershgorin discs Theorem

Question:
Let $i_0\in \{1,\ldots ,n\},\alpha >0$. Then$$K_{i_0}:=\left \{z\in \mathbb{C}:|z-a_{i_0i_0}|\leq \alpha \sum \limits _{j=1 \\ j\neq i_0}^n|a_{i_0j}|\right \}$$has exactly one eigenvalue if and only if$$K_{i_0}\cap \left \{z\in\mathbb{C}:|z-a_{ii}|\leq \frac{|a_{ii_0}|}{\alpha}+\sum \limits _{j=1 \\ j\neq i,i_0}^n |a_{i_0j}|\right \}=\varnothing \quad \forall i\in \{1,\ldots ,n\}\setminus \{i_0\}.$$

I have no idea how to prove this. I know about Gershgorin discs and that all eigenvalues are in the discs and I have found a few proves about the amount of eigenvalues of disjointed discs but not with exactly one eigenvalue and $\alpha$. Thanks for any help!
Comment: Uh...the title is really misleading here, enough that I assumed you meant something entirely different until I actually read what you wrote carefully. This is "Gerschgorin-like" but not especially so. The top disk is only a Gerschgorin disk when $\alpha=1$ and even then the bottom disks are *not* Gerschgorin disks. In any case I am curious what happens with $\begin{bmatrix} 0 & 1/3 \\ 2/3 & 1 \end{bmatrix}$, which is a counterexample to the "naive" statement of this type.
Comment: Never mind, checking that means this whole thing is just nonsense. Clearly it is possible for $K_{i_0}$ to only contain one eigenvalue, just take a diagonal matrix with distinct eigenvalues. But the second statement is *trivial* in the 2x2 case because the sum is just empty. So something is going wrong here.
Comment: @Ian hmm okay, thank you for your help!!
Comment: @Ian yeah we just had Gershgorin circles and this seemed to be very close to it, I'm sorry that I mislead you by this title!
Comment: Assuming this problem was given to you, I wonder what the correct version of the problem actually is. As I said, this version is definitely not correct.
Comment: @Ian there was a mistake: I made an edit
Comment: That's not completely nonsensical like the other version (and is also much more similar to the usual Gerschgorin than the other version). But it still can't be true as is, at least not if $\alpha$ is just whatever positive number you want. Take $\alpha=1$, look at $\begin{bmatrix} 0 & 1/3 \\ 2/3 & 1 \end{bmatrix}$ and then consider $i_0=1,i=2$. The disk at the top is $B_{1/3}(0)$, which only contains one eigenvalue, but the disk at the bottom is $B_{2/3}(1)$, and they have a point in common, namely $1/3$.
Answer: This just isn't true, at least if $\alpha$ can be anything.
As a whole family of counterexamples, look at $A=\begin{bmatrix} 0 & x \\ 2x & 1 \end{bmatrix}$. The eigenvalues are $\frac{1 \pm \sqrt{1+8x^2}}{2}$ and you have $K_1=B_{\alpha x}(0)$. Say the lower type of disk is denoted $J_{i,i_0}$, then you have $J_{2,1}=B_{2x/\alpha}(1)$. $K_1 \cap J_{2,1}$ is nonempty if $\alpha x \geq 1-2x/\alpha$ i.e. $-1 \geq x(-2/\alpha-\alpha)$ i.e. $x \geq \frac{1}{2/\alpha+\alpha}$.
So now the question is, can that happen while $K_1$ contains exactly one eigenvalue? This amounts to asking for the following three inequalities: $-\alpha x \leq \frac{1-\sqrt{1+8x^2}}{2},x \geq \frac{1}{2/\alpha+\alpha},\frac{1+\sqrt{1+8x^2}}{2}>\alpha x$. For $\alpha=1$ these are all true if $x \in [1/3,1]$.

Gershgorin discs Theorem


`scale` in R with no normal distribution

Question: The function called scale, in R, does the same of subtracting the mean and dividing by the sd each element.
So the scale function allows to take in count differente parameter with different scale.
# Manually scaling
   (x - mean(x)) / sd(x)
# Default scaling
   scale(x)
But, does it make sense scale a variable if it doesn't have a normal distribution?
Andrea
Comment: @German "In general" the answer is yes!  When the units in which we measure a variable are arbitrary--pounds or drams, angstroms or parsecs--then scaling the variable is an essential mechanism to convert between units. Only when the units have intrinsic meaning (such as counts) would the meaningfulness of scaling be questionable.
Comment: I think I would agree with you, @German, understanding that by "z-score" you mean computing a standardized value *with the intention of referring it to a standard Normal distribution.*  But the current question appears to comprise a large set of more benign applications, ranging from standardizing regression residuals, to understanding correlation in terms of mean products of standardized variables, to stabilizing numerical algorithms, and many more situations where the Normal distribution is neither used nor considered relevant.
Comment: I'm not sure if this is the issue, but keep in mind that, if you've got data, you can compute the mean and standard deviation. Then you can subtract the mean from each point and divide by the standard deviation. Now you've got a new data set with mean 0 and standard deviation 1, which is often helpful and the reason we do scaling in the first place.

As User7598 noted, scaling doesn't change many of the other useful things we want to know about that data, so it's a nice way to make your data more digestible without altering it in a bigger way (like doing a log transform).
Comment: This is not a good question for stackoverflow since it is not a coding question.
Comment: It depends on your purpose. In general answer is no. But for representation - why not.
Comment: @whuber for any skewed distribution the answer is no. And it has nothing to do with pounds or parsecs, skewed distribution + z-scores = misinterpretation. I had spent quite a lot of time trying to explain why $-2 \sigma != 2\sigma$ for skewed case (and for real data it is somehow more often)
Comment: @whuber you're saying this because you understand what this transformation means. But in real life people think: $z-score(RV) \sim \mathcal N$ and the distribution of $RV$ can be arbitrary. Really, so many things were done wrong because of this (at least from my practice) so I am surprised that you said this. I've seen z-scores of bimodal RVs, skewed RVs, discrete RVs. IDK. You have more experience than I.
Comment: @German The question asks whether an operation "makes sense."  You can't hold me responsible for those who independently do something nonsensical with the results or misinterpret them.  Regardless, I cannot see any justification for your claim that standardizing data from a skewed distribution makes no sense.  Even then it is of great conceptual, practical, and computational value.
Comment: @whuber that's what I meant. People do not apply z-scores for fun, they test for significance. I.e., $3 \sigma = $significance. They overestimate effect from one side and underestimate effect from another. Z-scores are OK for representation, from my point of view, and for nothing else.
Comment: @whuber I agree, but I would try to consider other variance-stabilizing transformations (and then, after such transformation, z-scores are OK). However, I would say that z-scores are OK if the statistician is too lazy to think about the data.
Answer: Scaling a variable is a linear transformation and it will not change the distribution of the variable so it does not matter if the variable has a non-normal distribution.
You can confirm this by generating non-normally distributed data in R, such as: X=rnorm(10000,10,5)^2. Then, scale the variable "X" X.z = scale(x)
Comparing the two histograms: hist(X) vs. hist(X.z) you'll see the distributions are unchanged.
EDIT: As noted in the comments, scaling does influence the interpretation of the parameters when doing many statistical analyses (regression, PCA etc) so the decision to scale should be based on how you want to interpret your parameters.
However, scaling will not change the underlying distribution of the variable nor will it influence (positively or negatively) the violations of model assumptions. For example, an assumption of linear regression is normality of the residuals scaling a raw variable will not affect this normality.
Comment: Although the *shapes* of distributions are unchanged by scaling, the *distributions* themselves are definitely changed. This might sound like a nit-pick until you contemplate operations like scaling a Poisson distribution: suddenly it's no longer a Poisson distribution at all.
Comment: If isn't a normal distribution, it isn't right to apply a scaling before a Principal Component Analisys process.


Como adicionar 1 quilômetro a uma coordenada Google Maps?

Question: Como poderia adicionar 1 km (ou mil metros) a uma coordenada google maps para determinar uma área?
Exemplo:
Raio formado pelos pontos A e B:
Ponto A = Latitude:-22.91009, Longetude: -43.107499.
Ponto B = Latitude(A)+VALOR, Longetude(B)+VALOR.
Porém a distância de A até B seria em quilômetros ou metros.
Answer: Supondo que você calculasse o raio pelo teorema de Pitágoras, não seria em quilômetros nem metros e sim em graus. Nesse caso você teria que fazer a diferença entre as latitudes de A e B e a diferença entre as longitudes de A e B. Se a distância latitudinal entre A e B fosse 10° e a distância longitudinal fosse 30°, pelo teorema de Pitágoras teríamos:

10^2 + 30^2 = X^2 => √¯ 10^2 + 30^2 = 31,62

Considerando que 1° de latitude são cerca de 110 km e 1° de longitude varia de 110 km na linha do equador a 0 km nos pólos *1 e supondo que você estivesse na linha do equador, o raio seria de 3478 km.
Comment: sua resposta é muito boa, mas fiz umas pesquisas e vou complementar ela!! Me ajudou a entender alguns pontos!! Obrigado
Comment: faltou complementar ela aqui @TiagoAmaral


Trouble using hiera in masterless setup and getting values set for classes

Question: I am running a masterless puppet setup that applies the puppet changes in the following manner.
puppet apply /tmp/puppet/manifests/site.pp --modulepath=/tmp/puppet/modules --hiera_config=/tmp/puppet/hiera.yaml

I have been trying to work in hiera to handle the different types of nodes we have and as a starting point have been trying to use a custom fact that is set on the nodes.  This fact is nodetype and in this example is set to a value of diskless.
Facter on the node recognizes this fact.
# facter -y | grep nodetype
nodetype: diskless

And hiera.yaml contains the following
---
:backends:
  - yaml
:yaml:
  :datadir: /tmp/puppet/data
:hierarchy:
  - node/%{::nodetype}

And at /tmp/puppet/data/node/diskless.yaml there is
---
cluster: blues

Though after doing so I try to double check that hiera is then setting variables as needed but it doesn't seem to work.
hiera -y diskless.yaml cluster
nil

Is there a better way to debug the problem.  I am sure it is something simple, though it would be disappointing if hiera doesn't (or can't) operate in this use case.
Cheers
Edit 1:
Additional debugging
hiera cluster '::nodetype=diskless' -d
DEBUG: Fri Oct 31 16:54:01 -0400 2014: Hiera YAML backend starting
DEBUG: Fri Oct 31 16:54:01 -0400 2014: Looking up cluster in YAML backend
DEBUG: Fri Oct 31 16:54:01 -0400 2014: Looking for data source defaults
DEBUG: Fri Oct 31 16:54:01 -0400 2014: Cannot find datafile /var/lib/hiera/defaults.yaml, skipping
DEBUG: Fri Oct 31 16:54:01 -0400 2014: Looking for data source global
DEBUG: Fri Oct 31 16:54:01 -0400 2014: Cannot find datafile /var/lib/hiera/global.yaml, skipping
nil

Edit 2:
It appears setting the flag --hiera-config does nothing and one needs to symlink /etc/hiera.yaml to the hiera.yaml config you wish to use.
Edit 3:
After symlinking /etc/hiera.yaml to /tmp/puppet/hiera.yaml I was able to lookup hiera variables but was not able to use them in puppet manifests in the expected way.  Instead I had to call hiera like so directly
$networking_config    = hiera('networking::network::networking_config','no')

Terribly confusing
Answer: Try this:
hiera cluster '::nodetype=diskless'

See fact-sources documentation
Comment: @Wilshire What's the output if you add `-d` to that command?
Comment: Debug shows hiera searching /var/lib/hiera but the hiera.yaml in your original question has ':datadir: /tmp/puppet/data'.  Command line hiera uses /etc/hiera.yaml but puppet by default uses /etc/puppet/hiera.yaml.  Normally those are symlinked but if not that might explain what you're seeing.
Comment: I don't know which hiera.yaml puppet was using but your tests with hiera from the command line were using /etc/hiera.yaml (as shown by the debug output).
Comment: Unfortunately that also returns nil just as 'hiera -y diskless.yaml cluster' returned nil.
Comment: Adding the information to the question
Comment: @Ian You mention /etc/hiera.yaml and it does exist but why would puppet be even looking at it when I specify where the hiera.yaml file is with the --hiera-config flag?  I do see that there is a template /etc/hiera.yaml file so I went ahead and symlinked that to the copy of hiera.yaml it should be using (/tmp/puppet/hiera.yaml) and it seems to work now.  I guess --hiera-config just gets ignored.
Comment: @Wilshire Where'd you find that option, `puppet.conf`??  According to the [docs](https://docs.puppetlabs.com/hiera/1/command_line.html#options), for the `hiera` command, it's `-c` or `--config`, not `--hiera_config`.
Comment: Fairly certain is was from a puppet book that I got a while back, before hiera was baked in with Puppet and was still something you had to grab from a third party source.  Unfortunately the -c and --config doesn't help.


Cordova processMessage failed: Stack: undefined (and) Error: illegal access

Question: I'm trying to get this GCM regId via PushPlugin.
I can't find any documentation per 'illegal access' error message... sounds almost like a permissions thing. The JS function onNotificationGCM pings a log message, indicating it's execution...
Error message:
<code>processMessage failed: Stack: undefined
processMessage failed: Error: illegal access
processMessage failed: Message: Jjavascript:onNotificationGCM({\"regid\":\"APA91bGQkVTa6KGBQzNz9spnYgYEL6RSJKyyoNh5GnhrkD04wVgm1detXbuATLRC_Evjduv4NCPZWzw_Q-ilEl4U_XBjibiSHPgzWEoO0_VBqB6HT_TDNMsJoxoGZu1ZXyFZNDXQawCJxv5KcQiCp7zmbaICt9n4TQ\",\"event\":\"registered\"})
</code>
Answer: Well, go figure. It seems that I was attempting to parse a JS object with JSON.parse, which--a discovery also made via this article--throws these 'Illegal access' errors. Once I made sure the passed in msg was a string before parsing JSON, the errors disappeared and regId was handled successfully. w00t.
Comment: Can you give an answer for this? (http://stackoverflow.com/questions/25967691/reference-error-onnotification-is-not-defined-in-push-notification-cordova-andro)
Comment: Make sure you're sending the right thing via gcm. It was a while ago when I had this problem, but at first glance it looks like I was trying to feed onNotificationGCM a JavaScript object rather than a JSON.stringify(..) version of the object.


ftp_rawlist returns false on ProFTPd server

Question:
I have a ProFTPd on a linux server (ProFTPd version 1.33 on Debian Linux 6.0.7 Linux 2.6.32-042stab078.27 on x86_64) that lets access to some users to their home directories.
I also have another FTP server on a Mac OS X Server.

If I use solution (2), I'm able to perform ftp_rawlist to have a raw list of all directories and files.
If I use solution (1), ftp_rawlist ALWAYS returns FALSE, even if the directory is not empty.
Users have permission to do anything they want inside their home directories on both servers (get directory listing, create and delete files, etc...). NO limits at all.
I really can't uderstand why I always get false on ProFTPd.
I gave a look around internet and discovered that there were some bugs on that function, but on previous versions of PHP. I'm running PHP version 5.3.3-7+squeeze16 and there are no bugs reported for this version.
Answer: Try to use passive mode
ftp_pasv($conn, true);

Usually you need passive mode if your FTP server is behind firewall, what is passive mode you can read here - What is the difference between active and passive FTP?
Comment: Usually you need `passive mode` if your `FTP` server is behind firewall, what is passive mode you can read here - http://stackoverflow.com/questions/1699145/what-is-the-difference-between-active-and-passive-ftp


Como passar parâmetros Json, para consumir uma API C#

Question: Estou tentando consumir uma API do PagSeguro de tranferência que pede para que seja passado o email de quem vai receber, o valor e a descrição, eu fiz de acordo com o modelo abaixo mas acho que não está correto.
Obs: apaguei o meu token e email na url da API.
public ActionResult FazerTransferencias()
{
    var uri = "https://ws.pagseguro.uol.com.br/transfer/authorize?email=&token=";
    WebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    request.Method = "POST";
    request.ContentType = "application/json";

    string receiverEmail = "firstname.lastname@example.com";
    string amount = "1.00";
    string description = "Transferência How2Code";

    String input = "{\"receiverEmail\":\"" + receiverEmail + "\",\"amount\":\"" + amount + "\",\"description\":\"" + description + "\"} ";

    using (var streamWriter = new StreamWriter(request.GetRequestStream()))
    {
        streamWriter.Write(input);
        streamWriter.Flush();
        streamWriter.Close();

        var httpResponse = (HttpWebResponse)request.GetResponse();

        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var result = streamReader.ReadToEnd();
            return Json("Retornou");
        }
    }

Documentação da API: https://dev.pagseguro.uol.com.br/reference#solicitando-autorização-1
ao debugar o código a api retorno o erro 500.
detalhe na conta não tem dinheiro esse erro séria por esse motivo, ou é algum erro no código mesmo.
Comment: dá erro em qual linha? vejo um problema ai no seu código: o `StreamReader` deveria ser aberto após o using do `StreamWriter`
Comment: O erro aparece nessa linha var httpResponse = (HttpWebResponse)request.GetResponse(); , após o StreamWriter.Close();
Comment: tentou colocar isso depois de terminar o StreamReader?
Comment: E qual é a descrição do erro 500?
Answer: Tenta fazer algo assim. É mais simples e deve funcionar:
public string FazerTransferencias()
{
    var data = new
    {
        receiverEmail = "firstname.lastname@example.com",
        amount = 1,
        description = "Transferência How2Code"
    };

    string email = "email@example.com";
    string token = "12345";
    var result = new HttpClient().PostAsJsonAsync($"https://ws.pagseguro.uol.com.br/transfer/authorize?email={email}&token={token}", data).Result;
    return result.Content.ReadAsAsync<string>().Result;
}


User will get the dialog when the user first time login to the portal. and i want to check terms & condition checkbox only first time

Question: I am working on one project. and in this project, I have created an account from the master portal. and set a password for it. when users first-time log in to the portal they will get a dialog for terms & conditions. and I want to check the checkbox only one time.
This is my login method:
@pytest.fixture()
def PracticeLogin(setup):
    driver = setup
    driver.get(loginSheet.cell(3, 2).value)
    driver.implicitly_wait(5)
    login = LoginScreen(driver)
    login.SetUsername(loginSheet.cell(3, 3).value)
    login.SetPassword(loginSheet.cell(3, 4).value)
    login.SignIn()
    if "Terms & Policies" in driver.page_source:
        driver.find_element(By.XPATH, '//div[@class="modal-dialog"]//*[@class="checkbox checkbox-success"]').click()
        driver.find_element(By.XPATH, Locators.continueButton).click()
    driver.implicitly_wait(10)

I am getting NoSuchElementException
This is the portal URL
Email: email@example.com
Pass: Test@2020

Comment: We can not clearly answer here since you do not share a link to that page or it's HTML
Comment: Put a print inside this `if "Terms & Policies" in driver.page_source:` and see if the code flow is going there or not
Comment: `NoSuchElementException` is very vague error as well, Please post the full error stack trace.
Comment: @Prophet I have modified my question please check it
Comment: What code line gives the `NoSuchElementException` error?
Comment: `driver.find_element(By.XPATH, '//div[@class="modal-dialog"]//*[@class="checkbox checkbox-success"]').click()` For this line
Comment: If i will remove `in driver.page_source:` from `if "Terms & Policies" in driver.page_source:`. it will click on the checkbox and login success but when I will login second time it will return  `NoSuchElementException` for this line `"driver.find_element(By.XPATH, '//div[@class="modal-dialog"]//*[@class="checkbox checkbox-success"]').click()`
Comment: Try adding some sleep delay after `login.SignIn()` and let me know if it helped
Comment: @Prophet not helped. I have debugged the issue it does not go under the if statement.
Comment: @Prophet i have done in Cypress like that `cy.get('body').then($element => {
  if ($element.text().includes('Continue')) {
   cy.clickOnElementUsingXpath(patientPageSelectors.CheckBox)
   cy.clickOnElementUsingText(practiceData.continueButton)
  }
 })` it will work perfectly.
Comment: I'm not familiar with Cypress, but please let me know if my answer guess was correct?
Comment: Yes, Your and is working.  but when I log in a second time it will take some time to execute the command after login.
Comment: We can decrease the  `implicitly_wait` timeout, that's not a problem. It should be long enough to 100% catch the pop-up on it's first appearance even your internet is slow, the web site is busy etc but not too much on other hand to pass it for non-first runs
Answer: Please try this:
@pytest.fixture()
def PracticeLogin(setup):
    driver = setup
    driver.get(loginSheet.cell(3, 2).value)
    driver.implicitly_wait(5)
    login = LoginScreen(driver)
    login.SetUsername(loginSheet.cell(3, 3).value)
    login.SetPassword(loginSheet.cell(3, 4).value)
    login.SignIn()
    checkboxes = driver.find_elements(By.XPATH, '//div[@class="modal-dialog"]//*[@class="checkbox checkbox-success"]')
    if checkboxes:
        checkboxes[0].click()
        driver.find_element(By.XPATH, Locators.continueButton).click()

Comment: Thank you, it will work perfectly, but when I log in a second time it will take some time to execute the command after login. and can you please explain this?


Ruby/Rails - force subclasses to override specific methods?

Question: I'm wondering if there is a way to force a subclass to override a method from its parent method in either Ruby or Rails (in Java you would do this with an abstract class/method).
Let's say I have the following classes:
class Pet
end

class Dog < Pet
  def collar_color
    "red"
  end
end

class Cat < Pet
end

dog = Dog.new
dog.collar_color
==> red

cat = Cat.new
cat.collar_color
==> NoMethodError

In this example I would never instantiate a Pet object, but it exists to serve as a way to collect common methods to common classes. But let's say I want to ensure that all subclasses of Pet override the collar_color method. Is there a way to do that? Could I achieve it through testing in some way? Assume I don't want a default defined in the parent class.
My real-life use case is a collection of classes that all have polymorphic ownership of another class. If I have a display page of the owned class, then one of the owner classes not having a method could leave me with a NoMethodError problem.
Answer: No, there is no way to enforce this.
I can guarantee you, whatever idea you can come up with, it will break in some way.
First off: doing this statically is out of the question. Determining whether a method is overridden or not is known to be equivalent to solving the Halting Problem.
So, you have to do it dynamically. But even that is going to be problematic.
For example: you could implement the inherited hook and check whether every class that inherits from Pet implements the method. But, that will prevent someone from inheriting their own abstract class. (Also, there is no guarantee when the inherited hook will run – it could run when the class is opened, i.e. before the methods are defined.)
Also, even if you can check that the method exists at the point where a class inherits Pet, the method can still be removed again later, so you don't get any guarantees. And, of course, they can just provide a dummy method, in order to get around your protection.
You could create default implementations of the methods that just raise an Exception, but there is no need to do that: if you don't create a default implementation, that will already raise a NoMethodError exception anyway. (If you do go down this route, do not use NotImplementedError. Instead, use a custom exception that inherits from RuntimeError.)
There are examples of this in the core library: for example, the Enumerable mixin depends on an abstract method each that must be implemented by subclasses. And the way this is handled is by simply documenting that fact:

Usage
To use module Enumerable in a collection class:

Include it:
include Enumerable

Implement method #each which must yield successive elements of the collection. The method will be called by almost any Enumerable method.

That is actually the way any type-related issues have been dealt with in Ruby since the beginning. Since Ruby does not have types, typing only happens in the programmer's head and type information is only written down in documentation.
There always were informal third-party type annotation languages that were used by various IDEs. More recently, two type annotation languages have been introduced: RBI, a third-party type annotation language used by the Sorbet type checker, and RBS, a type annotation language that is part of Ruby proper.
As far as I know, RBS has no way of expressing abstract methods, but RBI does:
class Pet
  extend T::Sig
  extend T::Helpers
  interface!

  sig {abstract.returns(String)}
  def collar_color; end
end

This will give you a type error if there is object instantiated from a subclass that does not at some point in the inheritance chain define the method. But, of course, only if the user of the code actually type-checks the code using a type-checker like Sorbet. If the user of the code does not type-check it, they will not get a type error.
Comment: You can use the `inherited` hook to register the class in a list of classes to be checked at some later point, though. But hey, I *did* write that it would be problematic and break :-D
Comment: The `inherited` hook won't help much – it runs the moment you open the class body, i.e. before any method is defined.
Comment: @Stefan: Actually, I think it's even worse. If I remember some of the discussions correctly, *there is no guarantee*. So, it *could* run at the beginning, but it *could* also run at the end, or even halfway through. (Currently, all implementors run it at the beginning, but that is an implementation detail, not part of the [contract](https://rubydoc.info/stdlib/core/Class:inherited). I believe it would be perfectly legal to run it in parallel on a different thread.)
Comment: That's right, and even `ruby/spec` doesn't test the point of invocation. Besides, it would be perfectly fine to reopen the class to add the missing methods later on. The existence of a subclass (or object in general) doesn't imply that it is "complete" or won't change anymore.
Comment: @JörgWMittag Love your answer. What are your thoughts about a set of model tests they can each have that are essentially `assert_respond_to Object, collar_color`?
Answer: Ruby has relatively few keywords but it provides the basic building blocks to implement something that vaguely resembles abstract classes or methods.
In its simplest form you just raise an error in the parent "abstract" method:
class AbstractMethodError < StandardError
  def initialize(klass, m)
    super("Expected #{klass} to implement #{m}")
  end
end

class Pet
  def collar_color
    raise AbstractMethodError.new(self.class, __method__)
  end
end

class Cat < Pet

end

Cat.new.collar_color # Expected Cat to implement collar_color (AbstractMethodError)

__method__ is a magic variable that contains the name of the current method.
You can make this a bit more elegant by creating a class method that defines the "abstract method":
module Abstractions
  def abstract_method(name)
    define_method(name) do
      raise AbstractMethodError.new(self.class, __method__)
    end
  end
end

class Pet
  extend Abstractions
  abstract_method :collar_color
end

However Ruby is a dynamic langauge and you don't have a compile time check so this will only give a slightly more obvious error message when the method  is called. It doesn't actually give any guarentees that subclasses implement the method.
That is down to testing or using type checkers like Sorbet or RBS. In general it might be helpful when learning to forget everything you think you know about Object Oriented Programming and learn the Ruby way. It has a very different design philophy compared to Java - instead of abstract methods and interfaces you use duck typing to see if the object responds to that method.
Comment: I normally go with the built-in `NotImplementedError`
Comment: This is the usual approach. However, the error would only be raised if the method is actually called, just like the `NoMethodError` the OP already gets.
Comment: @Stefan that's were tests come in. You could I guess create a class instance variable in the parent that contains the names of all the "abstract" methods and then loop through the decendendants to see if they have implemented all those methods but it feels so un-Rubyeske and silly to even contemplate it.
Comment: @SergioTulentsev: `NotImplementedError` is for platform-specific code that cannot be supported on the current platform, such as, for example, writing to the filesystem in code running in a browser or `fork`ing on Windows. Also, `NotImplementedError` does not inherit from `StandardError`, so it will not be caught by a default `rescue` block. There is a current Feature Request to widen its scope, though: https://bugs.ruby-lang.org/issues/18915 But widening the scope will not change the inheritance chain, it's purely a documentation change.
Answer: Just define the default method implementation in the abstract class by raising Not implemented error or something. By doing that you also clarifies in your class design that when others / you want to inherit the Pet class they need to override collar_color method. Clarity is a good think and there is no benefit in not defining a default method in the abstract class.
Or if you want to achieve that by testing you can create a test case for Pet class that check if its descendants is defining their own collar_color method or not. I think Rails / Ruby 3.1 have .descendants methods defined or you can just google them.

# Pet_spec.rb
describe "descendants must implement collar_color" do
  it "should not throw error" do
    descendants = Pet.descendants
    descendants.each do |descendant|
      expect { descendant.new.collar_color }.to.not raise_error
    end
  end
end
Comment: Do *not* `raise` `NotImplementedError`. `NotImplementedError` is for *platform-specific code that cannot be supported on the current platform*, such as, for example, writing to the filesystem in Opal or `fork`ing on Windows. Also, `NotImplementedError` does not inherit from `StandardError`, so it will not be caught by a default `rescue` block.


Seeking answers of Magento certification question is on-topic or off-topic?

Question: I can see some questions which are asking in our site typically about Magento certification questions such as this and this.
Is this an on-topic?
In my opinion, if this question is actually from the Magento certification exam, then it should be closed as off-topic as it destroys the credibility of the exam. If this question is a model question, then it should be on-topic as we can see the questioner asking for reasoning.
So I am a little bit confused. What is your thought on this?
Comment: Summoning @benmarks on this.
Comment: Rajeev, i agree with your points but Ben Mark is the best person for this question.
Answer: Posting exam questions and their possible answers would be a violation of the terms that are agreed to before a test is taken.
Questions like that should not only be closed but should also be deleted by a moderator.
Conversely, if the StackExchange question simply asks about the general topic covered in the exam question, there is no problem. Also, if the question is provided as one of the sample questions in Magento's study guide, it would be less problematic, but still a violation of copyright.
Comment: Yes, unfortunately, if those are real test questions, they would have been posted completely disregarding that agreement.
Comment: I think when we start certification exam at that time we agree some terms and condition, in that also it is mentioned that we can not disclose exam questions as it is


probability of having picked a specific basket

Question: We have two identical baskets. In both of them there are 10 balls. In basket 1 there are 7 blue balls and 3 red balls. In basket 2 there are 3 blue balls and 7 red balls.
One chooses one of these baskets, picks 5 balls from there and finds that 2 of them were red. What is the probability that the chosen basket is the basket 2?
Let's denote
A = "The basket is basket 1.", B = "The basket is basket 2." and C = "2 of the picked 5 balls are red.".
Then (I guess)
$$\mathbb{P}\left(A\right)=\mathbb{P}\left(B\right)=1/2 ,$$
$$\mathbb{P}\left(C\right)=\frac{\binom{7}{3}\binom{3}{2}}{\binom{10}{5}}+\frac{\binom{3}{3}\binom{7}{2}}{\binom{10}{5}}=\frac{1}{2} ,$$
and therefore the asked probability would be
$$ \mathbb{P}\left(B\mid C\right)=\frac{\mathbb{P}\left(B\cap C\right)}{\mathbb{P}\left(C\right)}=\frac{\frac{\binom{3}{3}\binom{7}{2}}{\binom{10}{5}}}{1/2}=\frac{1/12}{1/2}=\frac{1}{6}.$$
Especially I am not sure about the probability of C. Is this logic correct? I guess that Bayesian theorem could be applied at some point.
Comment: your answer is correct but you should have written $P(C) = \dfrac{1}{4}$ and $P(B \cap C)$ should have been $\dfrac{1}{24}$
Answer: The marginal probability $\Pr[C]$ you computed is not correct, because the law of total probability is
$$\Pr[C] = \Pr[C \mid A]\Pr[A] + \Pr[C \mid B]\Pr[B] = \frac{\binom{7}{3}\binom{3}{2}}{\binom{10}{5}} \cdot \frac{1}{2} + \frac{\binom{3}{3}\binom{7}{2}}{\binom{10}{5}} \cdot \frac{1}{2} = \frac{1}{4}.$$  Just because $\Pr[A] = \Pr[B] = 1/2$ prior to observing the result, does not mean it can be ignored.
Then the posterior calculation of $\Pr[B \mid C]$ is $$\Pr[B \mid C] = \frac{\Pr[C \mid B]\Pr[B]}{\Pr[C]} = \frac{\frac{\binom{3}{3}\binom{7}{2}}{\binom{10}{5}} \cdot \frac{1}{2}}{\frac{1}{4}} = \frac{1}{6}.$$
In this case, you obtained the correct answer, but had the prior probability of choosing Basket 1 versus Basket 2 not been equal, you'd get a wrong answer.


Contour Websocket annotation not working on Ingress resource

Question: I have a Contour Ingress controller setup on my Kubernetes instance. I have also setup an Ingress resource together with an HTTProxy resource, per the Contour specification:
Ingress
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: common-api-ingress
  annotations:
    ingress.kubernetes.io/tls-minimum-version: "1.2"
spec:
  ingressClassName: contour
  tls:
  - hosts:
      - dev.mycompany.com
    secretName: dev.mycompany.com-tls
  rules:
  - host: dev.mycompany.com
    http:
      paths:
      - path: /api
        pathType: Prefix
        backend:
          service:
            name: my-service
            port:
              number: 80
      - path: /swagger
        pathType: Prefix
        backend:
          service:
            name: my-service
            port:
              number: 80

HTTProxy
apiVersion: projectcontour.io/v1
kind: HTTPProxy
metadata:
  name: signalr-proxy
spec:
  virtualhost:
    fqdn: dev.mycompany.com
    tls:
      secretName: dev.mycompany.com-tls
  routes:
    - conditions:
      - prefix: /api/notificationhub
      enableWebsockets: true # Setting this to true enables websocket for all paths that match /websocket
      services:
        - name: my-service
          port: 80

This configuration is working as expected and when I open the Chrome developer tools for my UI I see the following log on the Console tab:
config vundefined loaded
main.56e2cc4e6f9f283a998a.js:2 [01-003] redirecting...
main.56e2cc4e6f9f283a998a.js:2 Connection to signalR has been established....
2.b4c26156c9f4449d4bbf.js:2 Resetting cache..

I have decided to discard Contour's custom HTTPProxy resource and remain with a plain Ingress resource. To do that I deleted the HTTPProxy resource provided earlier, and on the Ingress resource I added the annotation that enables websocket traffic. The updated Ingress resource is given below:
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: common-api-ingress
  annotations:
    ingress.kubernetes.io/tls-minimum-version: "1.2"
    projectcontour.io/websocket-routes: /api/notificationhub/
spec:
  ingressClassName: contour
  tls:
  - hosts:
      - dev.mycompany.com
    secretName: dev.mycompany.com-tls
  rules:
  - host: dev.mycompany.com
    http:
      paths:
      - path: /api/notificationhub/
        pathType: Prefix
        backend:
          service:
            name: my-service
            port:
              number: 80
      - path: /swagger
        pathType: Prefix
        backend:
          service:
            name: my-service
            port:
              number: 80

When I deploy this update I get the following error in the Chrome developer tools console:
config vundefined loaded
main.56e2cc4e6f9f283a998a.js:2 [01-002] redirecting...
main.56e2cc4e6f9f283a998a.js:2 ERROR e
Wn @ main.56e2cc4e6f9f283a998a.js:2
main.56e2cc4e6f9f283a998a.js:2 Connection to signalR has been established....
api/UserSettings/:1     Failed to load resource: the server responded with a status of 405 ()
2.b4c26156c9f4449d4bbf.js:2 Resetting cache...

Visual:

The Contour deployment has the following set of pods:
kubectl -n projectcontour get pods
NAME                                         READY   STATUS    RESTARTS       AGE
contour-controller-contour-b5d6fdxxx-xxxxx   1/1     Running   1 (3d1h ago)   112d
contour-controller-contour-b5d6fdxxx-xx8x8   1/1     Running   1 (17d ago)    150d
contour-controller-contour-b5d6fdxxx-xxxxx   1/1     Running   2 (3d1h ago)   150d
contour-controller-envoy-ncxxx               2/2     Running   0              10d
contour-controller-envoy-wcxxx               2/2     Running   0              150d
contour-controller-envoy-wxxxx             2/2     Running   0              150d
contour-controller-envoy-xkxxx               2/2     Running   2 (69d ago)    146d

However I have another Ingress resource for Grafana that uses websockets and its working perfectly. The Helm values.yaml file is provided below:
adminPassword: "*xxa]{xxxxxxxxxxx"
grafana.ini:
  server:
    root_url: https://dev.mycompany.com/-/grafana
    serve_from_sub_path: true
  smtp:
    enabled: true
    host: mail2.mycompany.com:25
    from_address: firstname.lastname@example.com
    skip_verify: true
ingress:
  enabled: true
  ingressClassName: contour
  annotations:
    projectcontour.io/websocket-routes: /-/grafana/
  hosts:
    - dev.mycompany.com
  path: /-/grafana/
  tls:
  - hosts:
      - dev.mycompany.com
    secretName: dev.mycompany.com-tls
persistence:
  enabled: true

What am I missing ?
Answer: I was configuring the websocket route incorrectly. All I needed was to add a separate path for the websocket route itself:
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: common-api-ingress
  annotations:
    ingress.kubernetes.io/tls-minimum-version: "1.2"
    projectcontour.io/websocket-routes: /api/notificationhub
spec:
  ingressClassName: contour
  tls:
  - hosts:
      - dev.mycompany.com
    secretName: dev.mycompany.com-tls
  rules:
  - host: dev.mycompany.com
    http:
      paths:
      - path: /api
        pathType: Prefix
        backend:
          service:
            name: my-service
            port:
              number: 80
      - path: /api/notificationhub
        pathType: Prefix
        backend:
          service:
            name: my-service
            port:
              number: 80
      - path: /swagger
        pathType: Prefix
        backend:
          service:
            name: my-service
            port:
              number: 80


PayPal is redirect to success page, but it's not making the money transaction (and no webhook or IPN notification)

Question: it's some days that i am trying to solve a paypal issue. I'm working with the PayPal PHP SDK, my envoirment is a Linux Server (Ubuntu 16) with Php 7.2 installed and running Laravel 5.6.
I installed through composer the paypal php sdk and i integrated 'successfuly' in the code. When i try to run the code, i get back the link for make the payment (usually where u redirect the user) so it's working fine, no problem about the first request or api credential.
The problem is that, if you go to the pay link and i made the payment, it will redirect the payer to the success page of my website but i am not getting any transaction in my account (the buyer and the reciver) and also i am not getting any webhook or IPN notify (also like, user have to money or user profile is not verified, just nothing).
What i already tryed:

switching on live api and try with real paypal profile, but i got the same issue. So this is not the problem. (on paypal sdk github someone has a problem on sandbox).
Using a Laravel Packege (same issue).

This is my code (but i don't think the problem is this one):
<code>$_api_context = new ApiContext(new OAuthTokenCredential(
'CLIENT_ID','SECRET'));
    $_api_context->setConfig(array(
        'mode' => env('PAYPAL_MODE', 'sandbox'),
        'log.LogEnabled' => true,
        'log.FileName' => 'PayPal.log',
        'log.LogLevel' => 'DEBUG'
    ));

    $payer = new Payer();
    $payer->setPaymentMethod('paypal');
    $item_1 = new Item();
    $item_1->setName('Item 1') /** item name **/
    ->setCurrency('USD')
        ->setQuantity(1)
        ->setPrice('3'); /** unit price **/

    $item_list = new ItemList();
    $item_list->setItems(array($item_1));
    $amount = new Amount();
    $amount->setCurrency('USD')
        ->setTotal('3');
    $transaction = new Transaction();
    $transaction->setAmount($amount)
        ->setItemList($item_list)
        ->setDescription('Your transaction description');

    $redirect_urls = new RedirectUrls();

    $redirect_urls->setReturnUrl('https://XXXXXXX.ngrok.io/success') /** Specify return URL **/
    ->setCancelUrl('https://XXXXX.ngrok.io/error');

    $payment = new Payment();
    $payment->setIntent('Sale')
        ->setPayer($payer)
        ->setRedirectUrls($redirect_urls)
        ->setTransactions(array($transaction));

    //dd($payment);
    try {
        $payment->create($_api_context);
    } catch (\PayPal\Exception\PPConnectionException $ex) {
        dd($ex);

    }

    foreach ($payment->getLinks() as $link) {
        if ($link->getRel() == 'approval_url') {
            $redirect_url = $link->getHref();
            break;
        }
    }
    $approvalUrl = $payment->getApprovalLink();

    dd($redirect_url,$_api_context,$paypal,$paymentGateway,$approvalUrl,$payment->getId());
</code>
Answer: UPDATE
I tryed to sent money form sandbox account (personal) to the business account that own the api, and the ipn is working correctly.
Answer: For anyone that will have the same problem, u should execute the payment after the user is redirected to your success page.
Answer: I did not find where you set post request send your server to save your transactions.
Try like this way ..
code..
<code><script>
    paypal.Buttons({
        createOrder: function(data, actions) {
        return actions.order.create({
            purchase_units: [{
            amount: {
                value: '{{$form_data->net_amount}}'
            }
            }]
        });
        },
        onApprove: function(data, actions) {
            console.log('data');
            console.log(data);
        return actions.order.capture().then(function(details) {
            console.log(details);
            alert('Transaction completed by ' + details.payer.name.given_name);
            // Call your server to save the transaction
            return fetch('/paypal-transaction-complete', {
            method: 'post',
            headers: {
                'content-type': 'application/json'
            },
            body: JSON.stringify({
                orderID: data.orderID,
                userDetail: details,
                bookingId: '{{$form_data->id}}',
                _token: '{{csrf_token()}}'
            })
            }).then(function(){
                location.reload();
            });
        });
        }
    }).render('#paypal-button-container');
</script>
</code>


Independent and Identically distributed assumption in Maximum likelihood estimation

Question: I was reading about Maximum likelihood estimation from various sources on the internet and I noticed that MLE makes an assumption about the data known as IID but I didn't completely understand why is it necessary to make this assumption? Are there any other assumptions that MLE makes?
Comment: It isn't necessary. MLE maximizes a wide array of likelihoods. Your sources are assuming iid because it is a reasonable modeling assumption in a particular setting. If your model assumes the data are iid, it is easy to write down the likelihood and then use MLE to estimate the unknown parameters.
Comment: ... it's reasonable and it's **extremely convenient**, because it implies that the overall likelihood of the data set is the product of the likelihoods of the individual observations (independent), which all have the same form (identically distributed) $\to$ log-likelihood is the *sum* of individual LLs ...
Comment: Consider a time series model like an AR(1) process. Then the order of the data matter, and your likelihood is a product of conditional densities, not marginal densities. If you have three data points, you could write the likelihood as $p(x_3 \mid x_2) p(x_2 \mid x_1) p(x_1)$. MLE would have no problem with this, but we are not assuming the data are iid.
Comment: Possible duplicate of [What does it mean by independently and identically distributed random variables?](https://stats.stackexchange.com/questions/253861/what-does-it-mean-by-independently-and-identically-distributed-random-variables)
Comment: @Taylor I didn't quite understand 'wide array of likelihoods'. Can you name a few?
Comment: @BenBolker can you please write an answer to this question explaining from a general and mathematical point of view?
Comment: not now (I gave the partial answer in a comment because I don't have time to write a real/full answer at the moment)
Comment: @BenBolker Alright, Please trying answering this question whenever you have some spare time.
Answer: Assuming independence is not necessary for maximum likelihood estimation (ML) (or other likelihood based methods). But if independence is a reasonable assumption, then it makes ML easy to implement, since the log likelihood is simply the sum of the individual log likelihoods.  But there are lots of examples where ML is used without Independence: time series with ARMA (or ARIMA) models, spatial models including spatial dependence, mixed models where there are correlation between observations within some groups, others.
When is it reasonable to assume independence? is discussed already multiple times on this site, see for example Are "random sample" and "iid random variable" synonyms?   or    Independence of events in real-life data
Comment: @guy I tired looking for the same on the internet but couldn't get any. It would be great if you can share any references for the same.
Comment: How does it makes ML easy to implement. Can you edit your answer and explain how it makes the maths easy?
Comment: Will try tomorrow!
Comment: Can you share any link for now? Or any reference or book?
Comment: It's worth pointing out that the theory for MLE is easiest to develop for iid data. So it makes sense for textbooks to focus on this case.
Comment: It allows the joint distribution become a product, thats why it is convenient!


Finite abelian $p$-group with only one subgroup size $p$ is cyclic

Question: My goal is to prove this:

If $G$ is a finite abelian $p$-group with a unique subgroup of size $p$,
  then $G$ is cyclic.

I tried to prove this by induction on $n$, where $|G| = p^n$ but was not able to get very far with it at all (look at the edit history of this post to see the dead ends). Does anyone have any ideas for a reasonably elementary proof of this theorem?
Comment: Have you prove that $G/H$ verifies the induction hypothesis?
Comment: Well $G/H$ has size $p^n$, which is finite and of a size the hypothesis applies to, and it is abelian because $G$ is assumed to be abelian. So it seems to satisfy the induction hypothesis.
Comment: One part of the induction hypothesis is that it has a unique subgroup of order $p$.
Comment: @Iasafro I've added an argument for that, see the edit above.
Comment: You have made a circular argument. You cannot conlude that $G/H$ has a unique subgroup of order $p$ by applying that it is cyclic, i.e. that has a unique generator $gH$, since $G/H$ being cyclic is a consecuence of the induction hypothesis, that is, of having $G/H$ a unique subgroup of order $p$. In brief, being cyclic has to be a consecuence of $G/H$ having a unique subgroup of order $p$ and not in the other sense.
Comment: @Iasafro Indeed :( Perhaps induction is not the best way, or I haven't applied it correctly. I'll settle for any method of proof at this point.
Answer: Assume $G$ is a finite abelian $p$-group with a unique subgroup of order $p$. I claim that if $a,b\in G$, then either $a\in\langle b\rangle$ or $b\in\langle a\rangle$. This will show that $G$ is cyclic, by considering all elements of $G$ one at a time.
Let $a,b\in G$; by exchanging $a$ and $b$ if necessary, we may assume that $|a|\leq |b|$, and we aim to prove that $a\in\langle b\rangle$. If $|a|\leq p$, then $\langle a\rangle$ is contained in the unique subgroup of order $p$, and hence is contained in $\langle b\rangle$, and we are done. So say $|a|=p^k$, $|b|=p^{\ell}$, $1\lt k\leq \ell$.
Let $t$ be the smallest nonnegative integer such that $a^{p^t}\in\langle b\rangle$. Note that since $a^{p^{k-1}}$ and $b^{p^{\ell-1}}$ are both of order $p$, the fact that $G$ has a unique subgroup of order $p$ means that $\langle a^{p^{k-1}}\rangle = \langle b^{p^{\ell-1}}\rangle$, so $t\leq k-1$; that is, $a^{p^t}\neq 1$. And since $a^{p^{t}}$ is of order $p^{k-t}$, we must have $\langle b^{p^{\ell-k+t}}\rangle = \langle a^{p^{t}}\rangle$. Let $u$ be such that $a^{p^{t}} = b^{up^{\ell-k+t}}$.
Now consider $x=ab^{-up^{\ell-k}}$. Note that since $k\leq \ell$, this makes sense. What is the order of $x$? If $x^{p^r}=1$, then $a^{p^r} = b^{up^{\ell-k+r}}\in\langle b\rangle$, so $r\geq t$ by the minimality of $t$. And
$$x^{p^t} = a^{p^t}b^{-up^{\ell -k + t}}  = b^{up^{\ell-k+t}}b^{-up^{\ell-k+t}} = 1.$$
So $x$ is of order $p^t$.
If $t\gt 0$, then $x^{p^{t-1}}$ has order $p$, so $x^{p^{t-1}}\in \langle b\rangle$. But
$$x^{p^{t-1}} = a^{p^{t-1}}b^{-up^{\ell-k+t-1}},$$
so the fact this lies in $\langle b\rangle$ means that $a^{p^{t-1}}\in\langle b\rangle$. The minimality of $t$ makes this impossible.
Therefore, $t=0$, which means $x=1$. Thus, $a^{p^0} = a\in\langle b\rangle$, as desired.

Added. The above argument shows that an abelian group $A$ in which every element has order a power of $p$ and that contains a unique subgroup of order $p$ is locally cyclic; that is, any finitely generated subgroup of $A$ is cyclic. This includes some groups that are not finite or finitely generated, e.g. the Prüfer $p$-groups.
Comment: "And since $a^{p^{t}}$ is of order $p^{k-t}$, we must have $\langle b^{p^{\ell-k+t}}\rangle = \langle a^{p^{t}}\rangle$." Can you explain why that is true?
Comment: @StefanWalter:  Remember that $a^{p^t}\in\langle b\rangle$. It generates the unique subgroup of order $p^{k-t}$ (cyclic groups have unique subgroups of any given order dividing the size of the group). Now, $b$ is of order $p^{\ell}$, so $b^{p^{\ell-k+t}}$ *also* generates a subgroup of $\langle b\rangle$ of order $p^{k-t}$. Since there is only one such subgroup, $\langle b^{p^{\ell-k+t}}\rangle = \langle a^{p^t}\rangle$.
Comment: Ok, thank you very much!
Answer: A nice characterization of finite cyclic groups $G$ is:

Given any integer $m$, the number of solutions to $x^m=1$ in $G$ is at
  most $m$.

The proof is easy, and is mostly counting.  If your group $G$ was non-cyclic, it would fail the above, so there is some $m$ with $G$ having more than $m$ solutions to $x^m=1$; let's call these solutions $\lbrace x_1,\ldots,x_k\rbrace$. Let's also make sure we pick the smallest $m$ that works. Of course, $G$ is a p-group, so $m$ is a multiple of $p$, say $m=np$. Can you show the collection $\lbrace x_1^n,\ldots,x_k^n\rbrace$ has more than $p$ distinct elements? And do you see how that contradicts your hypothesis?
Answer: I will you give an answer that use more or less elementary techniques. (I will use additive notation.)
We will proceed by counter implication, i.e. showing that when $G$ is not cyclic then there are at least two subgroups of order $p$. Let $h$ be an element of $G$ which has maximum order $p^n$, and let $H=\langle h\rangle$. Now, when considering
$$G/H$$
we have that since $G$ is not cyclic it is not trivial. So there is an element $g+H$ of order $p$ -obtaining this element is trivial since $G/H$ is an abelian $p$-group, given a non-identity element $g_0+H$ of order $p^r$ take $g+H=p^{r-1}(g_0+H$)-.
Now, we have that
$$p(g+H)=H$$
i.e. that for some $a\in\mathbb{N}_0$ and $k$ coprime to $p$
$$pg=kp^a h$$
First, we have to note that $kh$ is also a generator of $H$ since $k$ is coprime to the order of $h$. So, we have that
$$pg=p^a(kh)$$
has order $p^{n-a}$, which implies since $g$ is not $0_G$ that the order of $g$ is $p^{n-a+1}$. Thus, we must have $a\geq 1$ in order to not having $g$ grater order than $h$ in contradiction with the choice of $h$, which is one element of maximum order in $G$.
From here, we can take
$$g_0=g+(p^{n-a}-k)p^{a-1}h\not\in H$$
since $g\not\in H$. And obtaining that
$$pg_0=p(g+(p^{n-a}-k)p^{a-1}h)=pg+(p^{n-a}-k)p^{a}h=kp^a h+(p^{n-a}-k)p^{a}h=p^n h=0_G$$
which means that $g_0$ is an element of ordr $p$, i.e. that
$$\langle g_0\rangle$$
is a subgroups of order $p$ distinct from
$$\langle p^{n-1}h\rangle$$
as desired.
Finally, counterimplication gives the desired statement, i.e. that a finite abelian $p$-group with an unique subgroup of order $p$ is neccesarily cyclic.
Comment: If you use `\langle` and `\rangle` instead of `<` and `>`, then $\LaTeX$ gives the proper spacing; compare $\langle g_0\rangle$ with $$.
Comment: I am intrigued - why the additive notation?
Comment: @ArturoMagidin: Thanks for the advice.
Comment: @user1729: Well, the group is abelian. Normally, in abelian cases I  like to use additive notations.
Comment: Sorry, I didn't read that bit! I thought the group was non-abelian, and then additive notation would have been...odd...
Comment: @user1729: Don't worry, but well my first book in group theory by Alexandrov funnily used additive notation with all groups -now, they have change that in today's versions-.


How do I let users cancel their account with JWT / JSON:API?

Question: I am making an Ionic app with Drupal as the backend.  Users log in via JWT.  I'm using JSON:API to send data to Ionic.  Now I want to allow users to cancel their accounts in the app (by JSON:API) instead of forcing them to log into the Drupal website and cancel there.
How can I do that?
Answer: This method uses the JSON:API Resources module.
It assumes:

Upon cancellation, blocking the user is OK.  (Admins will manually delete the accounts completely later.)
Logged-in users will simply make a GET request to www.example.com/jsonapi/MYMODULE/cancelaccount to cancel their accounts (the app will provide an "Are you sure?" dialog and so forth).

There is probably a better way to do this but I am sharing my solution here because a Google search didn't reveal anything on this topic.
What to do
First, create a custom module.
Then, in MYMODULE.routing.yml:
MYMODULE.user_cancel:
  path: '/%jsonapi%/MYMODULE/cancelaccount'
  defaults:
    _jsonapi_resource: Drupal\MYMODULE\Resource\MYMODULEUserCancel
  requirements:
    # Give all authenticated users permission.
    _permission: 'view own commerce_order'
  options:
    no_cache: 'TRUE

Next, in MYMODULE/src/Resource/MYMODULEUserCancel.php:
<?php

namespace Drupal\MYMODULE\Resource;

use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Logger\LoggerChannelFactory;
use Drupal\Core\Session\AccountInterface;
use Drupal\jsonapi\JsonApiResource\LinkCollection;
use Drupal\jsonapi\JsonApiResource\ResourceObject;
use Drupal\jsonapi\JsonApiResource\ResourceObjectData;
use Drupal\jsonapi\ResourceResponse;
use Drupal\jsonapi\ResourceType\ResourceType;
use Drupal\jsonapi\ResourceType\ResourceTypeAttribute;
use Drupal\jsonapi_resources\Resource\EntityQueryResourceBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Route;

/**
 * Processes a request for a collection containing a user's article nodes.
 *
 * @internal
 */
class MYMODULEUserCancel extends EntityQueryResourceBase implements ContainerInjectionInterface {

  /**
   * The current user account.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected AccountInterface $currentUser;

  /**
   * Logger factory.
   *
   * @var \Drupal\Core\Logger\LoggerChannelFactory
   */
  protected $loggerFactory;

  /**
   * Constructs a new EntityResourceBase object.
   *
   * @param \Drupal\Core\Session\AccountInterface $account
   *   The current user.
   * @param \Drupal\Core\Logger\LoggerChannelFactory $logger_factory
   *   The Watchdog logger.
   */
  public function __construct(AccountInterface $account, LoggerChannelFactory $logger_factory) {
    $this->currentUser = $account;
    $this->loggerFactory = $logger_factory->get('MYMODULE');
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('current_user'),
      $container->get('logger.factory'),
    );
  }

  /**
   * Process the resource request.
   *
   * Code example:
   * https://git.drupalcode.org/project/jsonapi_resources/tree/9.x-1.x/tests/modules/jsonapi_resources_test/src/Resource.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The request.
   * @param \Drupal\jsonapi\ResourceType\ResourceType[] $resource_types
   *   The route resource types.
   *
   * @return \Drupal\jsonapi\ResourceResponse
   *   The response.
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  public function process(Request $request, array $resource_types): ResourceResponse {
    $uid = $this->currentUser->id();
    // Make sure that we do not try to cancel user 1 or anonymous.
    if ($uid !== 1 && $uid !== 0) {
      $user_storage = $this->entityTypeManager->getStorage('user');
      $current_user = $user_storage->load($uid);
      // See: https://drupal.stackexchange.com/a/204422.
      // Send the user the "account blocked" confirmation email.
      _user_mail_notify('status_blocked', $current_user);
      $current_user->set('status', FALSE);
      $current_user->save();
      $this->loggerFactory->notice("User account for UID @uid cancelled by JSON:API.", [
        '@uid' => $current_user->id(),
      ]);
    }

    // Some data to return with JSON:API.
    $custom_field_data = [
      'cancelled' => TRUE,
    ];

    $links = new LinkCollection([]);
    $resource_type = reset($resource_types);
    // To disable caching, set metadata.
    $cacheability = new CacheableMetadata();
    $cacheability->setCacheMaxAge(1);
    $primary_data = new ResourceObject(
      $cacheability,
      $resource_type,
      $current_user->uuid(),
      NULL,
      $custom_field_data,
      $links
    );
    $top_level_data = new ResourceObjectData([$primary_data], 2);
    $response = $this->createJsonapiResponse($top_level_data, $request, 201, []);
    $response->addCacheableDependency($cacheability);

    return $response;
  }

  /**
   * {@inheritdoc}
   */
  public function getRouteResourceTypes(Route $route, string $route_name): array {
    $fields = [
      'drupalUid' => new ResourceTypeAttribute('drupalUid'),
      'status' => new ResourceTypeAttribute('status'),
    ];
    $resource_type = new ResourceType('current_user', 'current_user', NULL, FALSE, TRUE, TRUE, FALSE, $fields);
    // @todo Add role entities as a relatable resource type.
    $resource_type->setRelatableResourceTypes([]);
    return [$resource_type];
  }

}


How to get last frame from video?

Question: I want last frame of video and my code is shown below:
let asset : AVURLAsset = AVURLAsset(URL: videoURL, options: nil)
    let generate : AVAssetImageGenerator = AVAssetImageGenerator(asset: asset)
    generate.appliesPreferredTrackTransform = true

    var err : NSError? = nil
    var lastFrameTime = Int64(CMTimeGetSeconds(asset.duration))
    let time : CMTime = CMTimeMake(lastFrameTime, 30)
    let imgRef : CGImageRef = generate.copyCGImageAtTime(time, actualTime: nil, error: &err)
    let img : UIImage = UIImage(CGImage: imgRef)!

But I am not getting last frame , I am getting first frame, provide me solution for this.
Answer: I used Pooja's code as a starting point but it doesn't get the last frame. it gets something close to the last frame. Here is my solution for getting the actual last frame. If frame accuracy is important, then you have to use:
imageGenerator.requestedTimeToleranceBefore = kCMTimeZero
imageGenerator.requestedTimeToleranceAfter = kCMTimeZero

Be aware that it may take longer to generate this frame accurate last frame so you probably want to do it on a background thread.
Here is the code I am using:
let imageGenerator = AVAssetImageGenerator(asset: asset!)
imageGenerator.appliesPreferredTrackTransform = true
imageGenerator.requestedTimeToleranceAfter = kCMTimeZero
imageGenerator.requestedTimeToleranceBefore = kCMTimeZero

let composition = AVVideoComposition(propertiesOfAsset: asset!)
let time = CMTimeMakeWithSeconds(asset!.duration.seconds, composition.frameDuration.timescale)

do {
    let imageRef = try imageGenerator.copyCGImageAtTime(time, actualTime: nil)
}
catch let error as NSError {
    print("Image generation failed with error \(error)")
}

Hope this helps.
Answer: You can get last frame of video in Objective-C as mentioned below:-
    AVURLAsset *asset = [AVURLAsset URLAssetWithURL:videoURL options:nil];
    AVAssetImageGenerator *generate = [AVAssetImageGenerator assetImageGeneratorWithAsset:asset];
    generate.appliesPreferredTrackTransform = YES;

    NSError *error;

    int64_t lastFrameTime = CMTimeGetSeconds(asset.duration)*60.0;
    CMTime time = CMTimeMake(lastFrameTime, 2);
    CGImageRef imgRef = [generate copyCGImageAtTime:time actualTime:nil error:&error];
    UIImage *image = [UIImage imageWithCGImage:imgRef];

Comment: Please post relevant code the OP has asked the question about Swift I don't see how objective c code can help.
Answer: I have solved this , to get only last frame from video the code is following:
  let asset : AVURLAsset = AVURLAsset(URL: videoURL, options: nil)
    let generate : AVAssetImageGenerator = AVAssetImageGenerator(asset: asset)
    generate.appliesPreferredTrackTransform = true

    var err : NSError? = nil
    var lastFrameTime = Int64(CMTimeGetSeconds(asset.duration)*60.0)
    let time : CMTime = CMTimeMake(lastFrameTime, 2)
    let imgRef : CGImageRef = generate.copyCGImageAtTime(time, actualTime: nil, error: &err)
    let img : UIImage = UIImage(CGImage: imgRef)!

This is how I get last image of video in img variable.
Comment: here why you are using hard code value 2 of preferredTimeScale?
Comment: I am still getting the first frame
Answer: The accepted answer produce the first frame.
This code works (objective-c)
AVAsset* asset = [AVAsset assetWithURL:videoURL];
AVAssetImageGenerator *generate = [AVAssetImageGenerator assetImageGeneratorWithAsset:asset];
generate.requestedTimeToleranceAfter = kCMTimeZero;
generate.requestedTimeToleranceBefore = kCMTimeZero;
generate.appliesPreferredTrackTransform = YES;

NSError *error;
CMTime time = asset.duration;
CGImageRef imgRef = [generate copyCGImageAtTime:time actualTime:nil error:&error];
UIImage *image = [UIImage imageWithCGImage:imgRef];

The main lines here are :
generate.requestedTimeToleranceAfter = kCMTimeZero;
generate.requestedTimeToleranceBefore = kCMTimeZero;

and
CMTime time = asset.duration;

Answer: Finally, I got the last frame from the video after a lot of attempts.
let imageGenerator = AVAssetImageGenerator(asset: asset)
imageGenerator.appliesPreferredTrackTransform = true

// Make sure you set the next two properties.
// It didn't work for me without this two parameters!
imageGenerator.requestedTimeToleranceBefore = .zero
imageGenerator.requestedTimeToleranceAfter = .positiveInfinity

let lastFrameTime = Int64(CMTimeGetSeconds(asset.duration) * 60)
time = CMTime(value: lastFrameTime, timescale: 2)

guard let imageRef = try? imageGenerator.copyCGImage(at: time, actualTime: nil) else {
    return
}

let thumbnailImage = UIImage(cgImage: imageRef)

How to get last frame from video?


How likely are the following events?

Question: Assume that in a married couple there is a probability of 0.8 that the
husband will still be alive in 20 years while the wife has a somewhat higher probability, 0.9. How likely
are the following events?

Both are still alive in 20 years.
$0.8 * 0.9=0.72$
Neither of them is still alive in 20 years.
$0.2*0.1=0.02$
At least one of them is still alive in 20 years.
  I'm not sure how to attempt the last part of the question. Any guidance will be appreciated. Do I minus the end result by 1?  So it would be $0.8+0.9-1=0.7$

Is it correct?
Comment: Assuming independence as you have, it would be $1-0.02$ since they cannot both die
Comment: The "subtract $1$" part is definitely _not_ correct. What if the husband had probability $0.4$ to be alive and the wife has probability $0.5$? What do you get for the "probability both are alive" in that case?
Comment: There is a solution with $0.8 + 0.9 - (\mathrm{something})$. It's explained in the answers and probably also in your textbook or course notes if you reviewed them. There is also an easier method suggested in the answers.
Answer: The probability of at least one of them being a live means that they are not both dead. What is the probability that they are not both dead?
Comment: @Leucippus It's clearly meant to be a hint.
Answer: Let $A$ be the event that the husband lives, and $B$ the event that the wife does, and assume these have independence.
Then the event that both are alive is $A\cap B$, that both are dead is $A^\complement\cap B^\complement$, and that at least one is alive is $A\cup B$.
You have been provided that $\def\P{\operatorname{\mathsf P}}\P(A)=0.8, \P(B)=0.9$.
And have correctly used $\P(A\cap B)=\P(A)\P(B)$ and $\P(A^\complement\cap B^\complement)=(1-\P(A))(1-\P(B))$

You claim $\P(A\cup B)=\P(A)+\P(B)-1$ however, this is not true.
In fact, $$\begin{align}\P(A\cup B)&=1-\P((A\cup B)^\complement)\\&=1-\P(A^\complement\cap B^\complement)\\&=1-(1-\P(A))(1-\P(B))\\&=1-(1-\P(A)-\P(B)+\P(A)\P(B))\\&=\P(A)+\P(B)-\P(A\cap B)\end{align}$$

How likely are the following events?


Is there a way to dynamically apply a CSS to a menu that includes the taxonomy term of the current page

Question: For example, if I have page nodes with a vocabulary called "issues", which has terms, such as "budget", "education" and "foreign policies", and there's a menu titled "Information", I want to be able to add a class to that menu link for each page, such as "budget-info", "education-info" and "foreign-policies-info", dynamically.  I assume I can throw in a JS behavior, but if there's a module that does this so the user can manage the class names assigned to each menu, especially that handles tokens and/or PHP so you can throw in part of the current url, that would be better. Note that I don't want to create a menu from taxonomy terms, but a standard item in the main menu with a custom class name applied which is comprised of a combination of a manually supplied name, and a taxonomy term that comes from current node.
Thanks!!
Answer: You could probably use Field Formatter CSS Class in some form or fashion, that can add a class to the node based on a taxonomy term, etc.


Replace E-Mails in Webform 8 when dumping to test stage

Question: We sanititze our dumps from production to test so that no newsletter subscriptions, form submissions or ohter things get into the test environement and bad things happen :D
Is there a simple way to get the E-Mails configured in webforms automatically replaced too?
As the number of forms and drupal sites will grow (100+), its a bit hard to handle with drush or sql.
Answer: This link covers drush sql:sanitize, including how to extend it with your own custom sanitizations: https://www.hashbangcode.com/article/drupal-9-sanitising-data-drush
Comment: A good point. Already use drush sql:sanitize. Have to check out how to extend it and replace the e-mails in the config blobs.


Cloud service web role trace statements are not writing to file but writing to logs table

Question: Cloud service web role trace statements are not writing to file but writing to logs table,I read through the many blogs and configured all config files but still  am not able to find why these trace statements are not writing to file as well as container also not created.  I checked the connection string which is correct. Please suggest if any one has IDEA on this.  really struck up here also please suggest is there any other logging framework can be used in cloud service web role c#. My requirement is to capture all trace statements in a log file and update these statements in a blob. and this blob should be taken backup on next day and another log file should be generated in the blob
Answer: Trace logs are always written to WADLogsTable table in your diagnostics storage account. If your requirement is to persist them in blob storage, there are two things you could do:

Let them persist in table storage and then every day read data from this table, create a CSV file of that data, and save it in blob storage. Once the blob is saved, you can delete the entries from table.
Implement your own trace logs collection logic using something like NLog and have it persist in blob storage. Azure CAT team has an excellent project where they make use of NLog to collect and persist diagnostics data in blob storage. You can read more about this project here: http://social.technet.microsoft.com/wiki/contents/articles/18146.windows-azure-telemetry-basics-and-troubleshooting.aspx.
Comment: Thank you for the reply.I did not find where they are storing in the blob stuff. could you please point me the exact way of doing, I am really struck up here.
Comment: Are you looking for details on #1 or #2 I mentioned above?
Comment: I need details for #2. Please suggest. I need to achive a functionality like capture all trace statements and write to a log file and post the log file to azure container as a blob. The blob should rollover on daily basis.
Comment: Thank you Gaurav, but the link which you provided says "page does not exist". Can you check the link once again, or if possible please post the code.
Comment: Try this link: https://code.msdn.microsoft.com/windowsazure/Cloud-Service-Fundamentals-4ca72649.
Comment: This link also says page does not exist.


/etc/network/interfaces file almost empty

Question: I have a Ubuntu 14.04.1 Server system where the interface em1 is bounded to a bridge:
ifconfig em1

em1       Link encap:Ethernet  direcciónHW c4:34:6b:ae:ea:a8
          ACTIVO DIFUSIÓN FUNCIONANDO MULTICAST  MTU:1500  Métrica:1
          Paquetes RX:677380321 errores:0 perdidos:0 overruns:0 frame:0
          Paquetes TX:396179860 errores:0 perdidos:0 overruns:0 carrier:0
          colisiones:0 long.colaTX:1000
          Bytes RX:839163556407 (839.1 GB)  TX bytes:372594438191 (372.5 GB)
          Interrupción:64 Memoria:fb800000-fbffffff

ifconfig br0

br0       Link encap:Ethernet  direcciónHW c4:34:6b:ae:ea:a8
          Direc. inet:10.128.3.64  Difus.:10.128.255.255  Másc:255.255.0.0
          Dirección inet6: fe80::c634:6bff:feae:eaa8/64 Alcance:Enlace
          ACTIVO DIFUSIÓN FUNCIONANDO MULTICAST  MTU:1500  Métrica:1
          Paquetes RX:147880064 errores:0 perdidos:2217 overruns:0 frame:0
          Paquetes TX:189723115 errores:0 perdidos:0 overruns:0 carrier:0
          colisiones:0 long.colaTX:0
          Bytes RX:797220818733 (797.2 GB)  TX bytes:225007583950 (225.0 GB)

The network is fine but I cannot find the configuration of either the interface or the bridge in the file /etc/network/interfaces whose content is this now (I configured both the interface and the bridge through interfaces file):
# The loopback network interface
auto lo
iface lo inet loopback

I checked is there's some process related to Network Manager but I don't find it.
In addition, the content of the directory /etc/network is this:
ls /etc/network
if-down.d  if-post-down.d  if-pre-up.d  if-up.d  interfaces     interfaces.1479200968  interfaces.1479201325  interfaces.1479203373  run

Not a single file in this directory has configuration of the interfaces.
When could I find the current configuration of the network?
Thank you very much
Comment: The interfaces file is supposed to source files in `interfaces.d/`, and that's typically where automatic configurations put interface data (as individual files for interfaces is easier to manage automatically). When you say that the `/etc/interfaces` file is "this now", do you mean that you filled it with information but now it has nothing? Also, what are the contents of `interfaces.1479200968`,  `interfaces.1479201325`, and  `interfaces.1479203373`? I suspect you'll probably find your configuration in there.
Comment: Yes,I filled interfaces file with the configuration but now for some reason it has the content I've put in my first message. The three files interfaces.* have the same content as interfaces that is "auto lo iface lo inet loopback"
Answer: This is normal By default an Ubuntu desktop system usesNetwork Manager to manage network connections automatically and dynamically. This does not require (and in fact typically requires there not be) entries detailing configuration of your physical interfaces in /etc/network/interfaces.
Sources:-
https://help.ubuntu.com/community
https://help.ubuntu.com/community/NetworkManager
https://help.ubuntu.com/community/NetworkManager#Issues
Comment: Hi, as far as I know Network Manager is not running. There isn't any package related to Network Manager and there isn't any directories for Network Manager within /etc.
Comment: is your internet working now ?
Comment: Hi yes, internet works (it never failed) but my problem is that I cannot find the current network configuration (and my system doesn't run NetworkManager).


Swift seemingly strange behavior in `init` while setting up UI

Question: In the required init of my UIViewinheriting class, I'm trying to initialize a member variable and then set up the view's subviews with the data from the member variable (i.e. text). Consider the following pseudo-code which successfully loads the UI with the variable's data:
class Event {
    var title: String?
}

class A: UIView {

    let event: Event! {
        didSet {
            self.title_label.text = event.title
        }
    }

    required init(event: Event) {
        super.init(frame: CGRect(...))
        self.setupUI(with: event)
    }

    func setupUI(with event: Event) {
        self.event = event
        self.addSubview(title_label)
        self.constrainTitleLabel()
    }

    let title_label: UILabel = {
        let label = UILabel()
        ...
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()

    ...
}

However, if I move the initialization of event from the function to init, the UI no longer displays the variable's data:
class A: UIView {

    let event: Event! {
        didSet {
            self.title_label.text = event.title
        }
    }

    required init(event: Event) {
        super.init(frame: CGRect(...))
        self.event = event
        self.setupUI(with: event)
    }

    func setupUI(with event: Event) {
        self.addSubview(title_label)
        self.constrainTitleLabel()
    }

    let title_label: UILabel = {
        let label = UILabel()
        ...
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()

    ...
}

Why doesn't the second way set title_label.text properly? I'm pretty sure this is sufficiently close to my own code, but if there isn't actually a problem with this code then I've missed something that I've done. Thanks.
Comment: Where is `title_label` created? This is the problem when you don't share *actual code*, bits are missing
Comment: I'll add it if that will help
Comment: You still haven't shown where you actually *allocate* `title_label`; my suspicion is that you are doing so after you have already set `event`, so the setter doesn't set the label
Comment: @Paulw11 sorry I actually had to leave my computer.
Comment: @Paulw11 Updated, finally.
Comment: It seems to me that your required init() ... you should be setting 'event' before the call to super() (the 2 phase initialization - your local properties should be assigned before calling super).
Comment: Okay, but why does the first way work when I still initialize `event` after `super.init`?
Answer: didSet observers are not called for values set from init.

The willSet and didSet observers of superclass properties are called when a property is set in a subclass initializer, after the superclass initializer has been called. They are not called while a class is setting its own properties, before the superclass initializer has been called.

(from Properties).
Unfortunately, the documentation is not completely correct. See bug SR-1118. The observers are never called when the value is set from init.
Comment: So the first way I showed works because `self.event = event` isn't _directly_ called inside `init` but rather in a function call, whereas in the second way, it was called inside `init`? And `didSet` gets called for that function but not for `init`?
Comment: @ArchieGertsman Exactly. You can verify simply by putting a `print` in `didSet`.


Devo adotar o padrão de nomenclatura do meu framework ou legado da equipe?

Question: Aqui na empresa, todos seguem um padrão nos projetos:

Todas as tabelas devem ser nomeadas no singular. Exemplos: "usuario", "evento", "categoria".

E também:

A primary key principal é nomeada assim: "nome_da_tabela_id". Exemplos: "usuario_id", "evento_id". As demais colunas devem ser nomeadas com as três primeiras letras do nome da tabela, e o nome do campo. Exemplo: "usu_nome", "usu_endereco".

Acontece que vamos adotar o uso de frameworks como Laravel e CakePHP nos sistemas, e eles têm uma nomenclatura default para nomes de tabelas e colunas que eu queria aproveitar.
Pergunta
Vale a pena seguir desta forma, e inserir o nome das tabelas manualmente nas classes dos frameworks, ou estas não são boas práticas? Quais são as boas práticas, com base nos exemplos de literatura e estudos de caso?
Este banco de dados será modelado para um novo sistema, não dependendo assim de compatibilidade com outros sistemas.
Comment: Estou levando esta discussão para o meta: http://meta.br.stackoverflow.com/questions/482 @BetaSystems-RodrigoDuarte
Answer: Se um determinado framework tem um padrão, seguir este padrão sempre vai te dar menos trabalho do que ficar adaptando ele a alguma realidade.
No seu caso, se o Laravel e CakePHP possuem um formato de nomeclatura para tabelas e colunas, alterar este padrão para algo customizado seu vai gerar um trabalho extra (toda vez que você for utilizar algo automático do framework, terá que lembrar de ir configurar alguma coisa manualmente). E isto é uma fonte potencial de bugs.
Se a norma da sua empresa for mesmo inflexível, ou justificada por algum outro motivo (ex.: quantidade de código legado, reuso das tabelas/colunas em outros códigos), você então não terá escolha, mas deixe registrado esta alteração do default do framework.
Answer: Olha,
Eu sigo "as boas práticas" da Microsoft:
Tabelas

Pluralizadas
Primeira letra maiúsculas para cada palavra (CamelCase)
Sem <code>_</code> ou qualquer outro símbolo

Campos

Nome da tabela somado à palavra "Id" (ex.: TabelaId)
Primeira letra maiúscula para cada palavra (CamelCase)

Essas são as práticas que eu uso, sendo boas ou não, pra mim facilita muito e fica bem legível tudo, código, base e afins.
Este é um manual da Microsoft, onde está boa parte do que eu falei e muito mais. Nesse manual, eles tiraram a pluralização.
Outra coisa, sobre o que você disse dos frameworks, Laravel e CakePHP, e eu esqueci de comentar é que é mais fácil você seguir o padrão do que alterá-lo, mas se a empresa pede, ou você acha que o padrão deles torna difícil a leitura do projeto/banco, é melhor você adotar outro padrão, o que melhor convier para você ou sua empresa.

Outro artigo interessante: http://architects.dzone.com/articles/20-database-design-best
Comment: Acho que sei por que eles tiraram a pluralização... Isso dá uma mão-de-obra danada, e quando entra localização no meio a coisa fica pior ainda. Lembro do Ruby on Rails (que usa [CoC](http://pt.wikipedia.org/wiki/Conven%C3%A7%C3%A3o_sobre_configura%C3%A7%C3%A3o)), havia um bug no método de pluralização, e eles tiveram que **manter o bug** porque consertá-lo ia quebrar vários códigos legados! Vou te falar, o principal motivo pelo qual nunca me aproximei demais do RoR foi essa convenção - e sua inflexibilidade para contornar.
Comment: Você tem alguma referencia para esse material?
Comment: Cara, em mãos não, mas vou procurar e atualizo aqui.
Comment: Então, no .NET, quem usa essa pluralização, por default, é o Entity Framework, se você fizer por CodeFirst e não setar como false a opção da pluralização, ele vai criar todas as tabelas com pluralização, claro que funciona perfeitamente em inglês; mas não consigo enxergar muitos problemas com o SQL e .NET, mas entendo o ponto que você abordou.


FontAwesome - Manual Stacking

Question: I am trying to manually stack Soundcloud icon and show it on a square as it is with fa-facebook-square, but my Soundcloud icon get created under the square.
This is my code so far:

Soundcloud

Facebook

Preview: http://jsfiddle.net/gvdr7889/
If there is any other alternative/easier way, I am open for your suggestions.
Answer: Instead of setting margin-top and margin-left, use top and left.  I used 5px and 7px, but you can adjust it to get the positioning you like.
http://jsfiddle.net/gvdr7889/1/
Comment: Always display the icon in a parent element with `position: relative`, and you should be good.  http://jsfiddle.net/gvdr7889/2/
Comment: Looks cool in the jsfiddle however, in my case, social icons are located in a different section, so giving it a manual top & left would mess things up. Do you have any other suggestion?
Comment: Or, set `margin-top: -15px; margin-left: -5px;`.  http://jsfiddle.net/gvdr7889/3/
Answer: Look at this fiddle.
What I've done is change it so that the div you made is the background, which has the orange-red color, the size and the border radius. Then the normal fa-soundcloud fa-1x fa-inverse in it in white. Might have to play around with the sizes and colors, but it seems to me like that is what you're looking for.
There is also a Github issue requesting a proper soundcloud-square icon, I'd suggest letting them know you want it too over there

FontAwesome - Manual Stacking


Intuition behind PCA decorrelation and whitening

Question: 1) Is there an intuitive explanation for why data becomes correlated once rotated into the principal component basis?
2) Is there any intuitive explanation behind why rotation doesn't affect the whitening of data?
Specifically, I want to understand why $x_{ZCA} = U x_{PCA}$ where $x_{PCA} = D^{-1/2} U$ for the eigen decomposition of $X X^T$ works.
Answer: 1) I don't what you mean.
2)  The definition of whitening is that $E(XX^T)$ is the identity where $X$ is a vector-valued random variable.  Any rotation by $U$ of that $X$ will also be whitened since, by definition, the transpose of a rotation vector is its inverse.
Comment: @learning https://arxiv.org/abs/1512.00809 is an accessible source.
Comment: 1) I mean, when I do $x_{pca} = U^T \ x$, how does this make $x$ decorrelated?


slow transition between images on JavaScript slideshow? (especially using chrome)

Question: I've developed a website, 'www.malenemicha.com'. It seems like the JavaScripts are running very slow, when I scroll through the images and when I try to access the subpage 'www.malenemicha.com/portfolio'.
Google Chrome is much slower than the other browsers. Could this be a JavaScript issue?
I've used profiling tools on the website, and it seems like the code is fine.
I've also used validator, and every html code seems to be valid.
Please, can anybody help regarding this problem?
Thank you
Answer: Perhaps its your huge image files.
http://www.imageoptimizer.net/
With all these profiling tools, analyzers, and all your bedazzled tests, I think you overloooked the fact that the site loads like 20MB of data, quite the payload.
Comment: And why is Chrome much slower than the rest of the browsers?
Comment: Thank you very much for your reply. But I've seen lots of websites with much more images running much faster. Mostly this is flash based websites. Do you think that JQuery is unable to run this amount of images?


How to install JIRA-SERVER on OPEN-SHIFT (docker-image)

Question: Im trying to installing jira-server via docker-image on openshift.
I pulled the image from docker-desktop for windows. Added simple dockerfile includes USER ROOT etc.
When trying to deploy the pod. I get error and pod enters to loop.
The errror is: Permission Error in diffrent locations.
Tried many times to relocate the jira-home directory but without success.
(Trying to install on closed network)
Thanks for helping!
Comment: Welcome to StackOverflow! Can you provide a more detailed list of the steps you did (e.g. I've got no idea what image tag you used) please?
Answer: Short Answer
The official Atlassian Images are incompatible with Kubernetes Derivatives /e.g. Openshift as they violate some key concepts.
In Openshift for example, containers are running with arbitrary user ids, which means a nameless user is executing the processes in the container.
This is a safety mechanism, prevents containers running as root and limits the risk of escaping the container gaining privileges on the cluster host.
Solution
You do need to rebuild the image from scratch.
Furthermore, the behaviour of the startup python script trying to modify file system permissions need to be removed.

Clone official Repo
https://bitbucket.org/atlassian-docker/docker-atlassian-jira/src/master/

Modify the Dockerfile and add to the UserGroup creation Step:

RUN groupadd --gid ${RUN_GID} ${RUN_GROUP} \
    ...
    && chown -R ${RUN_USER}:${RUN_GROUP}            ${JIRA_HOME} \

    # make the image compatible to run as an arbitrary uid
    && chgrp -R 0 /etc/container_id \
    && chmod -R g=u /etc/container_id  \
    && chmod -R 460 /etc/container_id  \
    && chgrp -R 0 ${JIRA_INSTALL_DIR} \
    && chmod -R g=u ${JIRA_INSTALL_DIR} \
    && chgrp -R 0 ${JIRA_HOME} \
    && chmod -R g=u ${JIRA_HOME}

Modify the gen_cfg function from entrypoint_helpers.py and remove the else clause at the end.
The necessary permissions have already been set in step2.

def gen_cfg(tmpl, target, user='root', group='root', mode=0o644, overwrite=True):
    if not overwrite and os.path.exists(target):
        logging.info(f"{target} exists; skipping.")
        return

    logging.info(f"Generating {target} from template {tmpl}")
    cfg = jenv.get_template(tmpl).render(env)
    try:
        with open(target, 'w') as fd:
            fd.write(cfg)
    except (OSError, PermissionError):
        logging.warning(f"Container not started as root. Bootstrapping skipped for '{target}'")
    # else:
        # set_perms(target, user, group, mode)

Rebuild the image using the --build-arg JIRA_VERSION= --build-arg ARTEFACT_NAME
Run and Enjoy

Detail inspection
Firing up the atlassian images, user root is the first to enter, doing modifications (chown...) and later dropping down to user "jira".
All these operations are not possible in openshift.
In most cases, building a new Dockerfile starting from the official image and modifing permissions of the needed files and folders before deploying to a cluster is the solution,
but to make things worse, atlassian choose to "mount" the necessary directories as VOLUME.
They have even referenced the issue in their comments.
VOLUME ["${JIRA_HOME}"] # Must be declared after setting perms

After the volume mount, the permissions can only be modified persistently at runtime.
This forces them to rebuild and set permissions after container startup, using a python function in the entrypoint_helpers.py.
This is also the place, where the container fails with several "permission denied"s.
Would be glad to issue a pull request on this, but unfortunatelly they are hosted on bitbucket.


Can software traffic generator generate 100 Mbps traffic?

Question: Can software traffic generators like iperf etc can generate 100mbps traffic?
else is there any software generators which can produce such high rates ?
Regards,
Mithun
Answer: Yes, iPerf can easily max out even Gb connections.  The example above by mkudlacek is, in fact, a maxed out connection, minus losses to TCP overhead.

------------------------------------------------------------
Client connecting to proton.cw, TCP port 5001
TCP window size: 16.0 KByte (default)
------------------------------------------------------------
[  3] local 10.2.0.16 port 40045 connected with 10.2.0.2 port 5001
[  3]  0.0-10.0 sec  1.09 GBytes    940 Mbits/sec
Comment: @James Not for small packets, it will not ;)
Comment: iperf will easily do 10 gbit
Comment: Good point, I only use it for testing bulk data throughput
Comment: On a sufficiently fast computer iperf can easily do 100mbps.  I never was able to come close to saturating a 1GB link on a old 400mhz box though.  It hit 100% CPU at about 450gbps.
Comment: what is the recommended configuration of PC to generate 100Mbps ?Because I am seeing 100% CPU utilization for 3 flows of 1 Mbps streams
Answer: Iperf will generate up to a Gigabit or so, depending on hardware. If you want to max out 10 Gbit connections (or above), or use smaller than MTU packets you will have to use kernel modules such as pktgen.
Answer: it almost can, here's the proof:
<code>------------------------------------------------------------
Server listening on TCP port 5001
TCP window size: 85.3 KByte (default)
------------------------------------------------------------
[  4] local 10.0.0.2 port 5001 connected with 10.0.0.5 port 46844
[ ID] Interval       Transfer     Bandwidth
[  4]  0.0- 4.5 sec  50.0 MBytes  94.1 Mbits/sec
</code>
Computers are connected via 100MBps LAN.
Best regards,
  Martin


Spherical Data?

Question: I am current using cluster analysis. Hierarchical clustering using the ward method appears to be the best method I have found. I read that this method is good for spherical data. I do not know what this is. I tried to look it up but could not find out exactly what spherical data is. I have ordinal data which I am guessing is not spherical data.
Comment: "I read" is fairly vague. Please provide references.
Comment: an example of spherical data are geographical data that data are on the surface of an sphere. a famous example is spherical regression http://www.jstor.org/stable/30042073?seq=1#page_scan_tab_contents
Answer: Let's think in three dimensions for clarity of exposition.
By "spherical" the cluster analysis references refer to a situation when you have several volley balls in the space: each cluster has a roughly round shape. This is an ideal situation, as real word clusters may look more like the balls used in  rugby/American football that are longer in some dimensions more than in other dimensions, and the longest axes may be oriented differently in space. (R mclust package is probably the best tool to deal with these.) Clusters may have other shapes, like bananas or snakes or donuts. For those complicated geometries, single linkage (that contracts or shrinks the space very severely) is probably one of the few methods that work.
If the clusters are approximately round and well isolated from one another, then pretty much every method will identify them.

Spherical Data?


PHP: Interactive Contact form not working

Question: Why is this form not working?
I'm creating a form that sends messages to users.
The user email comes from the database.
The query that searches the database is influenced by some data sent previously to the browser.
The problem at the moment is:
When one clicks to submit, nothing really happens.
Got a file called mini-contact.php with the following:
Script to proccess the form:
<?php
var_dump($_POST);
error_reporting(E_ALL);
$company=$_GET['company'];
$sql = "SELECT * FROM companies WHERE companies.companyID= '$company'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
    $row = mysqli_fetch_assoc($result);
    $companyemail = $row['Email_Address'];
    if(isset($_POST['submit'])){
        $to = "firstname.lastname@example.com"; // this is your Email address
        $from = $_POST['email']; // this is the sender's Email address
        $first_name = $_POST['first_name'];
        $last_name = $_POST['last_name'];
        $subject = $_POST['subject'];
        $subject2 = "Copy of your form submission";
        $message = $first_name . " " . $last_name . " wrote the following:" . "\n\n" . $_POST['message'];
        $message2 = "Here is a copy of your message " . $first_name . "\n\n" . $_POST['message'];

        $header = "From:" . $from;
        $header.= "MIME-Version: 1.0\r\n";
        $header.= "Content-Type: text/html; charset=ISO-8859-1\r\n";
        $header.= "X-Priority: 1\r\n";

        $header2 = "From:" . $to;
        $header2.= "MIME-Version: 1.0\r\n";
        $header2.= "Content-Type: text/html; charset=ISO-8859-1\r\n";
        $header2.= "X-Priority: 1\r\n";

        $status1 = mail($to,$subject,$message,$header);
        $status2 = mail($from,$subject2,$message2,$header2); // sends a copy of the message to the sender

        if($status1 and $status2){
            $first_name = $_POST['first_name'];
            echo 'Mail Sent. Thank you' . $first_name . ', we will contact you shortly.';
        } else {
            echo '
Something went wrong, Please try again!
';
        }
// You can also use header('Location: thank_you.php'); to redirect to another page.
}
}
?>

The actual form:
<form id="contact-form" method="post" action="">

                      First Name *
                      <input type="text" name="first_name" class="form-control" placeholder="Please enter your first name" required="required" data-error="First name is required.">

                        Last Name *
                        <input type="text" name="last_name" class="form-control" placeholder="Please enter your last name" required="required" data-error="Last name is required.">

                              Email *
                              <input type="email" name="email" class="form-control" placeholder="Please enter your email" required="required" data-error="Valid email is required.">

                              Phone
                              <input type="tel" name="phone" class="form-control" placeholder="Please enter your phone">

                              Subject
                              <input type="text" name="subject" class="form-control" placeholder="Example: Service Request ">

                              Message *
                              <textarea name="message" class="form-control" placeholder="Please enter your message" rows="4" required="required" data-error=" Please enter your message."></textarea>

* These fields are required.

                            <input type="submit" class="btn btn-default caps" name="submit" value="Submit">

                    </form>

What am I doing wrong?
Thank you for your time
Comment: try putting `error_reporting(E_ALL);` at the top of your code.  You could be getting errors because your closing `}` on your `if` blocks are commented out.
Comment: thank you, that helped partially.
Was problem in the script, had the wrong page name, but now the form doesn't post
Comment: Are you getting any errors? Do you see anything in Developer tools?
Comment: Also, try putting `var_dump($_POST)` towards the top of your php and see if there is anything there.
Comment: As you can see, did some changes in the php.

Atm, the data gets posted into an array.
Still, the email doesn't get sent.
Also, the php.ini is well configured.

No errors are shown in the console

What can be the problem here?
Comment: do you know _which_ of the two mails is not sending? At the moment the program can't distinguish. Presumably either $status1 or $status2 (or both) is false? Or are they returning true, but the emails are not delivered? Even a "success" result from the `mail` function does not guarantee delivery of an email. Something else in the subsystem could be wrong. Or the mail could be sent, but never received (e.g. rejected as spam or otherwise lost). PS. You are telling the world your email address, maybe better to edit it for the purpose of the question.
Comment: think found the problem. Forgot to set the SMTP credentials, of course wouldn't work without it. Let me test it and will let you know asap
Comment: Don't put [solved] in the title, post an answer with the solution. Or, if it was a non-reproducible case (with the information given it sure looks like that), delete the question.
Comment: Forgot the SMPT credentials. Now it works fine
Answer: One needs to have SMPT properly configure so that it works.