Images can not be changed

Question: This seems strange to me, but everything worked fine before i made my site live. I set up all the content and made a backup. Uploaded everything to its server but now i can't change my images. When i remove the current image this comes up (see image) instead of being able to upload a new image

And console throws this error:

I have tried all the versions of jquery and my jquery_update in contrib is 7.x-2.7
Could it be something with the permissions? i have site/default/files-775
Comment: are you using ubuntu?
Comment: @NoSssweat, Not using ubuntu
Comment: I had a similar issue. I solved it by removing all PHP extensions not enabled on my dev setup from the hosting PHP configuration. I remember googling it and finding a post on this that mentioned the exact PHP extension, but can't remember which one. And is your PHP configured to upload files larger than 2MB? My error was thrown on uploading images via Media Ajax. Also error 500.
Comment: @J.Reynolds

none of that worked
Comment: it might be a permissions issue. Your sites folder needs to have read and write permission.
Answer: if you installed any module that alters with the drupal paths or jquery_update module version can cause the issue.
Answer: Make sure that before making the site live cache was disabled in development server.If not try disabling cache in live site.

Images can not be changed


Prevent the execution of "SET NAMES" on all nodes in MaxScale?

Question: Our current setup has multiple slave nodes and one remote master server located in a different datacenter (with a ~100ms latency)?
Is there any way to configure MaxScale to execute the 'SET NAMES' query (or any other session query) only on the slave it is actually going to read from?
A significant delay is introduced every time it has to wait for the master.
Answer: One option that might avoid this in some cases is lazy_connect that defers the creation of connections until they are needed.
Unfortunately, the way the feature behaves is that if there is a session command that modifies the state of the session and no connections are open, it picks the current master node as the server to execute it on. If you can execute a SELECT statement before the SET NAMES, this could still work in your case. If the SET NAMES or any other session command is the first command to be executed, you'll still pay the cost in latency.
The reason why lazy_connect does this is to avoid getting the "wrong" answer for the command: when a conflict in session command responses is detected, all servers that returned a different result than the one that was the "accepted answer" will get discarded as their state is no longer consistent.
There are a few improvements and feature requests in the MariaDB Jira to improve the functionality of readwritesplit when used in this sort of a read-mostly scenario:

https://jira.mariadb.org/browse/MXS-4669
https://jira.mariadb.org/browse/MXS-4390

I also filed a new feature request for improving the read-only behavior of lazy_connect in readwritesplit:

https://jira.mariadb.org/browse/MXS-4769
Comment: Thank you, but in the most probable usage case, the `SET NAMES` command is typically sent as the first command to the db server. Most PHP frameworks do this by default to switch to the UTF-8 character encoding. Ultimately, this render MaxScale almost unusable in read-mostly scenario with a 'slow' master server.
Comment: If you can, please comment on the MXS-4769 issue and describe your use-case and the problem you're facing. This way we know the problem is not just theoretical and that it affects an actual user of MaxScale.


What is the purpose of a zero fret on a guitar?

Question: Some guitars have an added fret just after the nut called a "zero fret":

What is the purpose of this? Is it to enhance playability at the bottom range of the instrument (by making the first fret easier to bend and push down)? If it is then why don't all guitars have it?
Answer: On a guitar with the usual bone or plastic nut, an open string can sound different than a fretted string.  This is due to the difference in how the string reacts to metal vs. bone or plastic.  A zero fret gives open strings the same tone as fretted strings.
A zero fret may also be easier/cheaper to manufacture than a traditional nut.  With a traditional nut, the string slots must be cut precisely to the right depth.  With a zero fret, the slots in the nut are cut deep without no need for precision.  The nut is only responsible for the horizontal separation between strings; the zero fret is only responsible for the height of an unfretted string.  It is presumably cheaper or easier to get the correct height with a zero fret than it is to cut nut slots to the correct depth.
Tuning may be easier with a zero fret, due to lessened friction with the nut (the nut slots can be cut wider when a zero-fret it used).
Over time, a wound string can wear down its slot in a traditional nut.  With a zero-fret, that wear transfers to the zero-fret instead.  It is possible that the zero-fret will last longer than a traditional nut would.
See also: Zero Fret (wikipedia)
Comment: And 50+ years on, any wear in the nut slots will make no difference. I have guitars that prove it (and those that prove the opposite!)
Comment: @Tim I added a paragraph about wear and replacement that I hope captures that.
Comment: So why aren't all guitars made that way? Is it aesthetics?
Comment: @EricO Sounds like a great question :)


Using multinomial regression's coefficients to derive predicted outcomes in C#

Question: I am attempting to use C# (and the alglib library) to calculate the predicted probability that an outcome ends up in one of five classes.  I have managed to calculate parameter estimates (i.e. slope and intercept values) for each outcome, using 1 group as a reference. However, I can't seem to figure out how to use these coefficients to calculate the predicted probability of each outcome on any given independent variable.
What is the operation needed to compute the probability for each outcome?
Comment: Sam, if you can compute all the other probabilities, then surely you can exploit the fact that they all must sum to unity!
Comment: Have you looked at the [equations for these probabilities](http://en.wikipedia.org/wiki/Multinomial_logistic_regression#As_a_log-linear_model)?
Comment: I actually have a pretty good idea at this point what needs to happen. My remaining question is how to compute the reference group probability.
Answer: The probability of any outcome $i$ in a multinomial logit model is
$$P_i=\dfrac{exp(X_i\beta)}{\sum_Jexp(X_j\beta)}$$
Where $\beta$ is a vector of estimated parameters, which you say you already have.
The $X$ vector is composed of two types of variables:

Generic variables, which vary across alternative. For these variables, you get exactly one estimated parameter for the entire model.
Alternative-specific variables, which are endemic to the
decision-maker. These variables create a different $\beta$ for each alternative.

The thing to remember is that $\beta_0=0$ for all of the alternative-specific parameters in the reference alternative, but not for the generic parameters. So in a model with three alternatives, one generic variable, and one alternative-specific variable, the utility equations ($X\beta$) are
$$U_0=(0)+ \beta_1x_1 + (0)$$
$$U_1=\beta_{01} + \beta_1x_1 + \beta_{21}x_2$$
$$U_2=\beta_{02} + \beta_1x_1 + \beta_{22}x_2$$
$\beta_1$ shows up in every equation because it is generic. $\beta_0$ and $\beta_2$ are different for each alternative (one a constant, the other a parameter), and are equal to zero for the reference alternative.
Comment: You can also, as whuber mentions above, rely on the fact that $P_0+P_1+P_2=1$, especially if you know two of the three.
Comment: How is the formula for $P_i$ derived?
Comment: There's a derivation here: http://eml.berkeley.edu/books/choice2nd/Ch03_p34-75.pdf


logarithmic big O proof

Question: I am asked to prove that
     $log^{log n}log n$ = O($2^{\sqrt n})$
I've tried so much and don't have any idea to solve it please help
thank you.
Comment: Not sure if this helps, but $\log(n)=\mathcal O(\sqrt n)$
Comment: Is that $(\log(\log(n)))^{\log(n)}$? If not, what is it?
Answer: $$f(n)=\log^{\log(n)}\log(n)$$
$$\log[f(n)]=\log(n)\log[\log(\log(n))]$$
and for $n>100$.
$$<\sqrt n$$
Thus, $\log[f(n)]=\mathcal O(\sqrt n)\implies f(n)=\mathcal O(a^{\sqrt n})$

logarithmic big O proof


How do I fix this Django/MySQL setup disaster?

Question: I've been searching through SO, forums, and blog posts for over 24 hours. Frankly, I have absolutely no idea what's going on anymore. This seems like a complicated issue, so I'll post as clearly as I can.
I am using Django, and am trying to switch from sqlite to mysql. I followed the instructions from this SO answer to do so: https://stackoverflow.com/a/3036241
When I run the last line, python manage.py loaddata datadump.json (or when I try to run python manage.py syncdb for that matter), I get the following error:
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Django-1.4-py2.7.egg/django/core/management/__init__.py", line 443, in execute_from_command_line
    utility.execute()
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Django-1.4-py2.7.egg/django/core/management/__init__.py", line 382, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Django-1.4-py2.7.egg/django/core/management/__init__.py", line 261, in fetch_command
    klass = load_command_class(app_name, subcommand)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Django-1.4-py2.7.egg/django/core/management/__init__.py", line 69, in load_command_class
    module = import_module('%s.management.commands.%s' % (app_name, name))
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Django-1.4-py2.7.egg/django/utils/importlib.py", line 35, in import_module
    __import__(name)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Django-1.4-py2.7.egg/django/core/management/commands/loaddata.py", line 13, in <module>
    from django.core import serializers
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Django-1.4-py2.7.egg/django/core/serializers/__init__.py", line 21, in <module>
    from django.core.serializers.base import SerializerDoesNotExist
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Django-1.4-py2.7.egg/django/core/serializers/base.py", line 7, in <module>
    from django.db import models
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Django-1.4-py2.7.egg/django/db/__init__.py", line 40, in <module>
    backend = load_backend(connection.settings_dict['ENGINE'])
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Django-1.4-py2.7.egg/django/db/__init__.py", line 34, in __getattr__
    return getattr(connections[DEFAULT_DB_ALIAS], item)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Django-1.4-py2.7.egg/django/db/utils.py", line 92, in __getitem__
    backend = load_backend(db['ENGINE'])
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Django-1.4-py2.7.egg/django/db/utils.py", line 24, in load_backend
    return import_module('.base', backend_name)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Django-1.4-py2.7.egg/django/utils/importlib.py", line 35, in import_module
    __import__(name)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Django-1.4-py2.7.egg/django/db/backends/mysql/base.py", line 16, in <module>
    raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e)
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb

So, I searched around to see how to solve this, and tried this:
pip install MySQL-python

As soon as I ran that line, I got the following error:
Downloading/unpacking MySQL-python
  Running setup.py egg_info for package MySQL-python
    sh: mysql_config: command not found
    Traceback (most recent call last):
      File "<string>", line 16, in <module>
      File "/var/folders/9q/bvqtzkbx1hg1934b36zgk0y40000gn/T/pip-build/MySQL-python/setup.py", line 18, in <module>
        metadata, options = get_config()
      File "setup_posix.py", line 43, in get_config
        libs = mysql_config("libs_r")
      File "setup_posix.py", line 25, in mysql_config
        raise EnvironmentError("%s not found" % (mysql_config.path,))
    EnvironmentError: mysql_config not found
    Complete output from command python setup.py egg_info:
    sh: mysql_config: command not found

Traceback (most recent call last):

  File "<string>", line 16, in <module>

  File "/var/folders/9q/bvqtzkbx1hg1934b36zgk0y40000gn/T/pip-build/MySQL-python/setup.py", line 18, in <module>

    metadata, options = get_config()

  File "setup_posix.py", line 43, in get_config

    libs = mysql_config("libs_r")

  File "setup_posix.py", line 25, in mysql_config

    raise EnvironmentError("%s not found" % (mysql_config.path,))

EnvironmentError: mysql_config not found

Tried it with easy_install, just to make sure. Same error.
So, then I tried to change the path to mysql_config in setup_posix.py, by following steps 5 and 6 from this SO answer: https://stackoverflow.com/a/1448476/1337422
When I moved on to step 7 of that answer, and ran sudo python setup.py build, I got the following error:
running build
running build_py
copying MySQLdb/release.py -> build/lib.macosx-10.3-fat-2.7/MySQLdb
running build_ext
building '_mysql' extension
gcc-4.0 -fno-strict-aliasing -fno-common -dynamic -g -O2 -DNDEBUG -g -O3 -Dversion_info=(1,2,4,'beta',4) -D__version__=1.2.4b4 -I/usr/local/mysql/include -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c _mysql.c -o build/temp.macosx-10.3-fat-2.7/_mysql.o -Os -g -fno-common -fno-strict-aliasing -arch x86_64
unable to execute gcc-4.0: No such file or directory
error: command 'gcc-4.0' failed with exit status 1

For this, I've found no cure.

By the way, I also followed the instructions on this answer: https://stackoverflow.com/a/1448446/1337422, and ran:
sudo port install py26-mysql
This appeared to have fixed nothing.
(I'm running on Mac OS 10.8.1)

I am so lost, and so hopeless at this point. I don't know where else to turn...help me out guys!
Answer: The clue is here:
unable to execute gcc-4.0: No such file or directory
error: command 'gcc-4.0' failed with exit status 1

You need to install the compiler...  I'm not a Mac user, but a quick Google came up with http://www.tech-recipes.com/rx/726/mac-os-x-install-gcc-compiler/ which might help
Looks like sudo port install gcc_select and then sudo port install gcc<nnn> is about the right lines...
Comment: I'm not certain, but I think it's already installed. When I run `gcc -v`, it returns `...Thread model: posix` `gcc version 4.2.1...`.
Comment: Based on your **edit**, I used `sudo port install gcc_select` to install. When I ran `sudo port install gcc`, it returned this error: `-bash: syntax error near unexpected token 'newline'` Any thoughts?
Comment: @sgarza62 Sorry - the `` should be the relevant version number...
Comment: All installed perfectly, but I'm still getting the same gcc-4.0 error :(
Comment: I'm outta ideas (and hungry) - what happens if you do `which gcc-4.0` ? (I assume `which` works on OSX)
Comment: I would buy you a sandwich if I could, thanks for all your help. If I type `which gcc-4.0`, nothing happens. However, if I type `which gcc`, it returns `/usr/bin/gcc`. Also, if I type `gcc`, it returns `i686-apple-darwin11-llvm-gcc-4.2: no input files`.
Comment: @sgarza62 Can you symlink gcc-4.0 to gcc (or search/replace gcc-4.0 with gcc throughout the build instructions)?
Comment: I followed the directions at http://www.question-defense.com/2010/03/30/how-to-switch-between-different-versions-of-gcc-and-g-in-backtrack-4-final-or-any-version-of-ubuntu to create a symlink (want it to use gcc-4.0), and it told me to `rm /usr/bin/gcc` first. Then I did this `ln -s /usr/bin/gcc-4.0 /usr/bin/gcc`. Now, when I type which gcc or which gcc-4.0, nothing happens at all. I think that may have made it worse...what a mess.


String para um array dentro de um loop - javascript/nodejs

Question: eu quero passar as strings de um arquivo txt para um array e assim que cada linha fosse passada para o array o programa iria executar ele normalmente, dai depois ele repetia e pegava a segunda string do arquivo txt. Tudo está sendo feito em javascript/nodejs só que ja faz 2 dias que estou parado nisso e não consigo sair do canto.
codigo do loop com o arquivo e o array:
function email_parser(){
var fs = require('fs');
var email_count = "";
var array = [];

var array = fs.readFileSync('email.txt').toString().split("rn");
for(var i = 0; i < array.length; i++) {
    email_count = array[i];
}}

e o estou chamando a variavel deste jeito
email = email_parser();

Obrigado!.
Answer: Estás a separar as linhas da maneira errada, tens de usar "\".
Testa assim:
.split(/\n/).map(line => line.trim());

Comment: Não funcionou :/
Comment: @jorleidedasilva tira o `.toString()`, o `. readFileSync` já te dá uma string.
Comment: @jorleidedasilva se ainda não conseguiste dá-me um exemplo do texto, ou coloca o ficheiro online para poder criar um exemplo para veres.


Cypress - check test failure in global afterEach

Question: Is there a possibility to check in global afterEach if test (it) failed?
Such global afterEach is located in support/index.js:
afterEach(() => {
  // check if test failed and perform some actions
})

Answer: You can use afterEach hook and remain in the scope of the Cypress context (where cy commands are available), for example:
afterEach(function() {
    if (this.currentTest.state === 'failed') {
        // your code
    }
});

Reference: https://github.com/cypress-io/cypress/discussions/15047
Or you can use test:after:run event and switch to node context (where any kind of node code can be executed outside of the scope of Cypress, like accessing database or file system), for example:
Cypress.on('test:after:run', (test, runnable) => {
    if (test.state === 'failed') {
        // your code
    }
});

Reference: https://docs.cypress.io/api/events/catalog-of-events#Cypress-Events
Answer: What you seek is the after:spec and is exposed via plug-ins. You'll have access to the spec and the results.
https://docs.cypress.io/api/plugins/after-spec-api#Syntax
Comment: You can't call any `cy` commands within these events, so they're somewhat useless depending on what you're trying to do (for example, taking a full-page screenshot of the failed test).
Comment: True and we don't know exactly what OP is looking to do within the global afterEach().
Answer: Accepted answer didn't work for me, however I figured out this solution:
  afterEach(() => {
    if(Cypress.state().test.state !== 'passed') {
      cy.task('log', "Test did not pass: " + Cypress.state().test.title);
    }
  });

Advantage of above solution is that you can use cy.task(..) unlike:
Cypress.on('test:after:run', (test, runnable) => {
    if (test.state === 'failed') {
        // your code
    }
});

Which can't use task.


Como fazer uma sequencia datas no python?

Question: Preciso criar um vetor de datas do 2018-01-01, 2020-01-11, sendo que as datas não podem ser continuas (eg 2018-01-01, 2018-01-02, 2018-01-03...) e inclua a extremidades.
O mais próximo que consegui foi:
import pandas as pd
date_list = pd.date_range(start='2018-01-01', end='2020-01-11', freq = '3M', closed= 'left')
date_list
Out[3]:
DatetimeIndex(['2018-01-31', '2018-04-30', '2018-07-31', '2018-10-31',
           '2019-01-31', '2019-04-30', '2019-07-31', '2019-10-31'],
          dtype='datetime64[ns]', freq='3M')

Entretanto ele não incluí as extremidades (2018-01-01, 2020-01-11).
Comment: Se elas não devem estar em sequência, como elas devem estar? Qual é a sequência completa que você deseja obter?
Answer: Márcio, veja se é isso que precisa.
import pandas as pd
import datetime

dRan = pd.date_range(start ='2018-01-01',

       end ='2020-01-11', periods = 13)

res = dRan.strftime('%d/%m/%Y')

print(res)

Comment: O parâmetro "M" considera sempre o Last Index para o retorno. Tente adaptar o "period" para seu projeto. Qualquer dúvida estamos aqui.


What types of question on regulation should be considered on-topic?

Question: This question asks about regulation in terms which include regulation on grounds of safety and prevention of nuclear proliferation.
We have a tag for regulation, but without any description.
It seems clear that questions on regulation for an economic purpose, eg to limit the price charged by a monopoly, are on-topic.  Where a question asks about regulation for a non-economic purpose, eg for health and safety, environmental protection or other reasons, should it still be regarded as on-topic?  Or should a question on non-economic regulation only be on-topic if it has a specific economic aspect, eg costs resulting from regulation, or encouragement of rent-seeking behaviour?
Answer:
health and safety, environmental protection or other reasons, should it still be regarded as on-topic?

My view is yes. As someone who has one MSc. in policy economics I can personally attest that health and safety regulation and environmental protection is part of policy economics.
Economics by widely used definition is:

"the science which studies human behaviour as a relationship between ends and scarce means which have alternative uses" (Robbins, 1935, p. 16).

The above is textbook definition of economics, and while we can have a debate on whats the demarcation of science I think it is fair to say that most people will accept the Robinson definition (its prevalence in textbooks should indicate mainstream acceptance).
Using the definition of economics we can have a look at some examples of what is economics and what isn't.

Example A:
For example:

how much does Pfizer vaccine reduce rate of infection?

is not economic question as it does not study  human behaviour as a relationship between ends and scarce means which have alternative uses
Question:

does vaccine mandate increase social welfare?

Is economic question. Social welfare is one of the many ends our society has, mandates are costly in terms of scarce resources such as political capital, or resources spent on vaccination stuff etc. So this is perfectly good economic question.

Example B:
For example,  lockdowns are primarily studied by economists specializing in economics of public health. This John Hopkins lockdown study was done by economist. Reducing spread of disease is also one of the ends humans strive for and lockdowns are not without cost the resources that go into implementing lockdowns could go elsewhere.
However, asking just if lockdowns reduce transmitting the virus without contrasting the transmission to costs to society just looking at transmitting itself is just epidemiology.

Example C:
For example, asking whether it is optimal for a country to have the same minimum health regulation for food (e.g. no chlorinated chicken) in every region is valid economic question. This is economic question, why should we waste resources implementing the same regulation in every region given our ends of promoting public health? Its not self evident that every region should have the same food regulation to maximize societal welfare.
Asking why chlorinated chicken is bad for your is not an economic question.


Azure ARM - Should Complete Deployment delete existing (child) Resources when omitted?

Question: During a Complete Resource Group deployment, the expectation is Resources will be deleted if they are not specified in the Template.
However in my case (deploying a RSG with a DNS Zone with CNAMEs), if the CNAMEs are specified via a copy/copyIndex iterator, the ones that are missing after the projection from the array parameter are not deleted.
I've got a basic template that should reproduce this issue.

Add CNAME records to the parameters file.
Deploy the Template (Complete) & verify the CNAMEs were created.
Remove 1 or more CNAME records from the parameters file.
Deploy the Template (Complete) & observe the removed CNAME Resources are not deleted.

I can't find any documentation that explains this behavioral caveat, so I'm not sure if this is a bug or expected behavior?

Edit / Follow-Up:
If I take a 'heavy-handed' approach of nuking the whole DNS Zone, then immediately re-deploying it with the new template, will this cause blips in DNS service, assuming there are no issues re-deploying and this operation takes place in under the TTL of the affected resources?
While this sounds reasonable, my gut tells me this will always be a race condition that cannot be guaranteed. ie:
- If 'a client' TTL expires immediately after I nuke the Zone, the DNS lookup will fail until the redeployment occurs and the record takes effect in Azure DNS.
But this raises questions:

If I delete the Zone, does Azure DNS still cache for the TTL?  Edit: The answer appears to be 'not really' based on content here:

Changes to existing DNS records can take a little longer, but should still be reflected on the Azure DNS name servers within 60 seconds

If I re-deploy the current version before nuking it, can I effectively reset that Azure DNS cache, if it exists?

Edit: Based on ^^^, this gives me <= (60 sec - TimeToRegisterInAzureDNS).
Answer: This is because the child resources are not actually resources, even though they are authored that way in the template.  The "mode" of deployment is handled at the platform layer by ARM and the only resource in the graph is the dnszone.
You might argue that the RP should then update the properties to remove the other cname (which would be independent of the deployment mode) from the dnszone resource... because if it doesn't the only recourse is to delete the entire record which may not be ideal.  Different RPs handle this different ways in ARM (unfortunately)... if you have a strong opinion about the behavior, you can open a uservoice request...
That help?
Comment: I was leery of getting this answer.  https://feedback.azure.com/forums/281804-azure-resource-manager/suggestions/33524908-remove-dns-zone-child-records-cnames-etc-with


Como injecto EJB's que chamam outros EJB's numa classe de teste JUnit?

Question: Estou a tentar testar uma classe em JUnit.
Acontece que a classe que estou a testar tem vários EJB's que chamam outros EJB's.
Como injecto numa classe de teste JUnit EJB's que chamam outros EJB's?
Obrigado.
Answer: A forma que recomendo de fazer um teste unitário em um EJB é instanciar o EJB a ser testado e mockar os EJBs que ele chama (ou seja, suas dependências). Dependendo da forma como o EJB está construído, talvez precise usar o método set dele para injetar as dependências ou, no pior caso, utilizar algum método de reflection para fazer a injeção por campo.
Por exemplo, veja o EJB abaixo:
@Stateless
public class PessoaEjb {

    private final EnderecoEjb enderecoEjb;

    @Inject
    public PessoaEjb(EnderecoEjb enderecoEjb) {
        this.enderecoEjb= enderecoEjb;
    }

    public PessoaEjb () {
        this.enderecoEjb = null;
    }

    public Pessoa validar(Pessoa pessoa) {
        if (pessoa.getNome() == null) {
            return new IllegalArgumentException("Nome inválido");
        }
        enderecoEjb.validar(pessoa.getEndereco());
        return pessoa;
    }
}

Um teste para ele ficaria algo como:
class PessoaEjbTest {

    @Test(expect = IllegalArgumentException.class)
    public void validar() {

        PessoaEjb pessoaEjb = new PessoaEjb(mock(EnderecoEjb.class)); // usei o Mockito aqui
        pessoaEjb.validar(new Pessoa(null));

    }

}


Questions about Moore–Penrose inverse

Question: I have some questions about Moore–Penrose inverse.

Let $A, P\in \mathbb{R}^{d\times d}$. Suppose $A$ is positive definite and $P$ is a projection matrix with $P^2=P, P^\top=P$. I try to prove that $A^{-1}-(PAP)^{-}$ is semi-positive definite. Here $B^-$ denotes the Moore–Penrose inverse of $B$. (I can prove it using some statistical methods. But how to verify it directly.)

Suppose $A_n\to A$ with $A_n$'s and $A$ being semi-positive definite. Do we have $A_n^- \to A^-$? (It holds when $A$ is positive definite.)

As pointing out by user1551, 2 is not true in general. Actually, I try to answer the following question. Suppose $A_n\to A$ with $A_n$'s and $A$ being positive definite, do we have $(PA_nP)^- \to (PAP)^-$? Here $P$ is a projection matrix with $P^2=P$ and $P^\top=P$.

Thanks.
Comment: If $P$ is a projection and $P^2 = I$, then $P = I$. Did you perhaps mean $P^2 = P$?
Comment: The answer to the second question is definitely negative. E.g. if $\{A_n\}$ is a sequence of positive scalars that converges to $A=0$, then $A_n^-\to+\infty\ne0=A^-$.
Comment: Yes, I mean $P^2=P$. Thanks for pointing out the typo.
Comment: Thanks for the answer to the second question.
Answer:
Yes. By a change of orthonormal basis, we may assume that $P$ and $A$ are partitioned as
$$
P=\pmatrix{I&0\\ 0&0}\text{ and }A=\pmatrix{X&Y\\ Y^T&Z}.
$$
Let $S$ be the Schur complement of $X$ in $A$ (i.e. $S=Z-Y^TX^{-1}Y$). Then
\begin{aligned}
A^{-1}
&=\pmatrix{X^{-1}+X^{-1}YS^{-1}Y^TX^{-1}&-X^{-1}YS^{-1}\\ -S^{-1}Y^TX^{-1}&S^{-1}}\\
&=\pmatrix{X^{-1}&0\\ 0&0}+\pmatrix{X^{-1}YS^{-1}Y^TX^{-1}&-X^{-1}YS^{-1}\\ -S^{-1}Y^TX^{-1}&S^{-1}}\\
&=(PAP)^-+\pmatrix{X^{-1}YS^{-1/2}\\ -S^{-1/2}}\pmatrix{S^{-1/2}Y^TX^{-1}&-S^{-1/2}}\\
&\succeq(PAP)^-.
\end{aligned}

No. E.g. when $\{A_n\}_{n\in\mathbb N}$ is a sequence of positive real numbers that converges to $A=0$, we have $A_n^-\to+\infty\ne0=A^-$ as $n\to\infty$.

Yes. Since $A_n\to A$, we have $PA_nP\to PAP$. As $P$ is an orthogonal projection and both $A_n$ and $A$ are positive definite, the range of $P$ is an invariant subspace as well as the column spaces of both $PA_nP$ and $PAP$, and the latter two matrices are nonsingular on the range of $P$. It follows that the inverse of $PA_nP$ on the range of $P$ converges to the inverse of $PAP$ on the range of $P$. Hence $(PA_nP)^-\to(PAP)^-$. In terms of block matrices, we mean the assumption
$$
A_n=\pmatrix{X_n&Y_n\\ Y_n^T&Z_n}\to A=\pmatrix{X&Y\\ Y^T&Z}
$$
implies that $X_n\to X$ and in turn
$$
(PA_nP)^-=\pmatrix{X_n^{-1}&0\\ 0&0}\to (PAP)^-=\pmatrix{X^{-1}&0\\ 0&0}
$$
when $n\to\infty$.
Comment: Thanks for the excellent answer!
Comment: Is Statement 2  true provided $A_n$ and $A$ have the same rank?
Comment: Statement 2 will be true if $A_n$ and $A$ have the same rank, I use the Davis-Kahan theorem to prove the convergence of the eigenvectors.

Questions about Moore–Penrose inverse


Example of a compact topological space $M$ such that $\mathcal M_1(M)$ is not compact.

Question: It is well known that if $(M,\tau)$ is a compact Hausdorff topological space then (by Riesz–Markov–Kakutani representation theorem + Banach–Alaoglu theorem) we have that the space
$$\mathcal M_1(M) :=\left\{\mu;\ \mu\ \text{is a }\tau\text{-Borel probability measure on }M\right\} $$
is compact in the weak$^*$ topology, $\textit{i.e}.$ the topology generated by the basis of neighborhoods
$$V(\mu;f_1,\ldots,f_n;\varepsilon):=\left\{\lambda\in\mathcal M_1(M);\ \left|\int f_i\  \mathrm{d}\mu - \int f_i\  \mathrm{d}\lambda\right|<\varepsilon, \ \forall \ i\in\{1,\ldots,n\}\right\}, $$
where $f_1,\ldots,f_n \in C^0_b(M)=\{g: M\to\mathbb R; \ g \text{ is a continuous bounded function}\}$.

My question: Is there an example of a compact topological space $M$, such that $\mathcal M_1(M)$ is not compact in the weak${^*}$ topology?

I have searched online but I was not able to find any reference for this problem. Moreover, I have tried to construct a counter-example but I have failed miserably.
Can anyone help me?
Comment: Do you mean if there is a *non-Hausdorff* compact topological space $M$ for which the weak-* compactness of the space of probability (Radon) measures on $M$ fails?

(by the way, continuous real-valued functions on a compact topological space are always bounded, even without the Hausdorff property)
Comment: I have only written continuous bounded function because  I was writting the general definition (if it was need for some reason). About the first question. When I say "Borel probability" I mean  a probability measure with respect to the $τ$ borel $σ$-algebra (the smallest $σ$-algebra that contains  $\tau$).
Comment: So, your underlying compact topological space $M$ is assumed to be Hausdorff, after all...?
Comment: No, $M$ is not Hausdorff. M is only compact. Like $Z_2$ with the topology $\{Z_2,∅\}$. There are some books that say $X$ is compact if $X$ is Hausdorff and if each of its open covers has a finite subcover. In my case, $X$ compact does not imply that $X$ is Hausdorff, it only means that each open cover has a finite subcover.
Comment: This should be stated more explicitly in the question, then, since this is absolutely critical. I've posted an answer below where I go through the steps of the proof  in a bit more detail in the Hausdorff case, so it may become clearer in which of those the Hausdorff property of $M$ may be necessary. The answer is supposed to be updated in the future if a counterexample shows up, even if the bounty is expired or granted to someone else.
Comment: I've just found out that the Hausdorff property is indeed not needed - one just takes a suitable Hausdorff quotient of $M$. I've updated my answer accordingly.
Answer: The answer to your question is no: $\mathcal{M}_1(M)$ is always weak-* compact, because one can always in a certain sense "recover" the Hausdorff property of $M$ as far as the properties of the space of continous functions on $M$ are concerned.
First of all, just a small remark: continuous real-valued functions whose domain $M$ is compact are always bounded, regardless of $M$ being Hausdorff or not. The proof is classical: let $M$ be a compact (being Hausdorff is not needed) topological space, $f:M\rightarrow\mathbb{R}$ continuous, and $\{U_j\ |\ j\in J\}$ be an open cover of $f(M)$. Since $f$ is continuous, $\{f^{-1}(U_j)\ |\ j\in J\}$ is an open cover of $M$. Since $M$ is compact, there is $I\subset J$ finite such that $\{f^{-1}(U_j)\ |\ j\in I\}$ is a subcover of $M$ and therefore $\{U_j\ |\ j\in I\}$ is a finite subcover of $\{U_j\ |\ j\in J\}$, hence $f(M)\subset\mathbb{R}$ is also compact. By the Heine-Borel theorem, $f(M)$ must be closed and bounded.
The (real) vector space $X=C(M,\mathbb{R})=C^0_b(M)$ of continuous ( $\Rightarrow$ bounded) (real valued) functions on a compact Hausdorff topological space $M$ is a Banach space when endowed with the supremum norm $\|f\|=\sup \{|f(x)|\ |\ x\in M \}$. The Hausdorff property of $M$ is also not needed to show completeness of $X$ in this norm - only the completeness of the codomain $\mathbb{R}$ is used. What is lost when one forfeits the Hausdorff property of $M$ is that one is no longer able to separate points of $M$ using continuous real-valued functions on it - more precisely, any (locally) compact Hausforff space is completely regular. However, the quotient space $\tilde{M}=M/\sim$ of $M$ modulo the equivalence relation $$x\sim y\Leftrightarrow f(x)=f(y)\text{ for all }f:M\rightarrow\mathbb{R}\text{ continuous}$$ is Hausdorff (and compact) with the quotient topology, is canonically homeomorphic to $M$ if the latter happens to be Hausdorff already (since then one can separate the points of $M$ with $X$ and therefore the equivalence class $[x]\in\tilde{M}$ of $x\in M$ modulo $\sim$ $$[x]=\{x'\in M\ |\ x'\sim x\}$$ equals $\{x\}$ for all $x\in M$), and we may identify $X=C(M,\mathbb{R})$ with $C(\tilde{M},\mathbb{R})$ (Edit: this can be done even if $M$ is not compact and always yields a completely regular - but then not necessarily compact - $\tilde{M}$, see e.g. Theorem 3.9, pp. 40-41 of the book by L. Gilman and M. Jerison, Rings of Continuous Functions, van Nostrand, 1960, as pointed in the answer to this MO question made by the OP's author, also linked in his comments below). Moreover, due to the compactness of $M$ and Hausdorffness of $\tilde{M}$ the quotient map $$M\ni x\mapsto[x]\in\tilde{M}$$ is even closed.
(Edit) The Riesz-Markov-Kakutani representation theorem, on its turn, actually holds even if $M$ is not Hausdorff (without uniqueness in this case, as pointed in the comments below). One is able to identify the topological dual $X'$ of $X$ with the space of signed, finite Baire measures on $M$ (recall that the Baire $\sigma$-algebra on $M$ is the $\sigma$-algebra $\mathfrak{Ba}(M)$ generated by the zero level sets of elements of $X=C(M,\mathbb{R})$, which is contained in the Borel $\sigma$-algebra $\mathfrak{Bo}(M)$ of $M$) see e.g. Lemma 8.25, pp. 293-295 of the book by V. Komornik, Lectures on Functional Analysis and the Lebesgue Integral, Springer-Verlag, 2016. This lemma relies only on a version of Dini's lemma (see e.g. Lemma 8.24, pp. 293 of the same book) and does not require the Hausdorff property. One can go even further and identify $X'$ with the space of signed, finite (but no longer necessarily regular) Borel measures on $M$ thanks to the Corollary to Theorem II.2.6.1, pp. 227-228 of the book by K. Fuchssteiner and W. Lusky, Convex Cones (North-Holland, 1981), as also pointed in the the answer to the aforementioned MO question. More precisely, the results quoted above tell us how to recover a measure from a positive linear functional on $X$ (which, by the way, happens to be continous). This measure, as pointed in the comments, is not necessarily unique - consider e.g. Dirac measures concentrated on distinct points of $[x]$ for some $x\in M$ with $[x]\neq\{x\}$. This happens, for instance, for $x\in M$ with $\{x\}\neq\overline{\{x\}}$ if $M$ is not $T_1$.
Conversely, any signed, finite Borel (resp. Baire) measure $\mu$ on $M$ yields an element of $X'$ once we identify each such $\mu$ with the associated integral, seen as a (bounded, hence continous) linear functional on $X$: $$\mu(f)=\int_M fd\mu\ ,$$ so that for each Borel (resp. Baire) subset $A\subset M$ we have
$$\mu(A)=\int_M\mathbb{1}_A d\mu\ ,\quad\mathbb{1}_A(x)=\begin{cases} 1 & (x\in A) \\ 0 & (x\not\in A) \end{cases}\ .$$ As discussed above and in the comments below, this map is no longer injective if $M$ is not Hausdorff. However, one can still identify each element of $X'$ with a unique signed Radon measure on $\tilde{M}$ by the standard Riesz-Markov-Kakutani representation theorem, of course.
The weak-* topology on $X'$ is just the locally convex vector topology of pointwise convergence, determined by the seminorms $$\|\mu\|_f=|\mu(f)|=\left|\int_M fd\mu\right|\ ,\quad f\in X\ ,$$ hence a fundamental system of neighborhoods of zero in $X'$ in this topology is given by the neighborhoods $V(\mu;f_1,\ldots,f_n;\epsilon)$ you wrote above.
Finally, the Banach-Alaoglu theorem is an abstract result for Banach spaces which states that the unit ball $$B=\{\mu\in X'\ |\ \|\mu\|=\sup\{|\mu(f)|\ |\ \|f\|\leq 1\}\leq 1\}$$ in the norm topology of the topological dual $X'$ of a Banach space $X$ is compact in the weak-* topology. In our particular example, probability measures on $M$ are just the elements of $X'$ satisfying $$0\leq f\in X\Rightarrow\mu(f)\geq 0\ ,\,\mu(1)=1\ ,$$ the set $\mathcal{M}_1(M)$ of which is a closed subset of $X'$ in the weak-* topology (hence also in the norm topology of $X'$). Since $$|\mu(f)|\leq\mu(|f|)\leq\mu(1)=1$$ for all $f\in X$ with $\|f\|\leq 1$, $\mathcal{M}_1(M)$ is a (weak-* closed) subset of $B$, hence it must be weak-* compact as well.
Comment: I think he wants to know if the same holds without the assumption of $(M,\tau)$ being Hausdorff. It is clear from your proof that you have used the property of being Hausdorff a lot. Do you know if the same is true without using it?
Comment: To make that a concrete example, if $M$ is the line with two origins $0$ and $0'$ then $\tilde{M} = \mathbb{R}$ (up to Homeomorphism). If the measure you get on $\tilde{M} = \mathbb{R}$ is $\delta_0$ then using the definition here $\psi^* \delta_0(\{0,0'\}) = \psi^* \delta_0(\{0\}) = \psi^* \delta_0(\{0'\}) = 1$ and so additivity clearly fails without further modification. [This mathoverflow answer](https://mathoverflow.net/a/122719/87850) claims that the right additional information to use is a family of probability measures on the fibers of $\psi$ but I haven't verified the details of it.
Comment: I'll add the above amendments to my answer when I can.
Comment: Interesting... however, I'd like to go through the details of that to see whether I could make my answer self-contained. I'll try to do that tomorrow.
Comment: Yeah, that's the problem. I do not know in which of the steps above (if any) the Hausdorff property of $M$ is necessary. This is not needed to show that continuous real valued functions on $M$ are bounded, though. In any case, the answer will need to be updated in the future if this turns out to be the case.
Comment: You use the Hausdorff property when you apply the Riesz-Markov-Kakutani representation theorem.
Comment: Ok, but is this necessary? In other words, is there a non-Hausdorff counterexample to the Riesz-Markov-Kakutani representation theorem? From there on, the arguments become abstract functional analysis, so I don't expect any further loopholes.
Comment: I know an easy example when the Riesz-Markov-Kakutani representation theorem fails. For example $M =``[0,1]$ with two origins". $M$ will be compact and non-Hausdorff, it is easy to see that if $f$ is continuous then $f(0) = f(0')$. Therefore if $G:C^0(M)\to\mathbb{R}$ is the functional $G(f) = f(0)$, $G(f) = \int f \mathrm{d} \delta_0 =  \int f \mathrm{d} \delta_{0'}$. So  we lose uniqueness, but this does not matter at all. What I do not know is if we lose surjetive I think that $\lambda (A) = \inf\{G(f);\ f\text{ is continuous and bounded}, \ f\geq 0, \ f(A) =1\}$.It will satisfy $G=\lambda$
Comment: About your proof. How do you pullback the measure on $M/∼$ to $M$?
Comment: Yes, uniqueness for the Riesz-Markov-Kakutani representation theorem is lost without the Hausdorff property, it is no longer an isomorphism between $C(M,\mathbb{R})^*$ and the space of signed Radon measures on $M$, but it's still surjective. The pullback of a Radon measure on $\tilde{M}$ to $M$ can be performed as follows: if $\psi:M\rightarrow\tilde{M}$ is the quotient map, then we know it's a continuous, open surjection. One then simply sets $\psi^*\mu(A)=\mu(\psi(A))$ for any open set $A$. This doesn't always work for any continuous map, of course, but for this particular one it does.
Comment: I think that $ψ^∗μ(A)=μ(ψ(A))$ is not a measure, for instance. Imagine that you have $U$ and $V$ such that $ψ(U)\cap ψ(V)\neq \emptyset$, but $U\cap V = \emptyset$. Then it is not clear if $ψ^∗μ(U\cup V)  = ψ^∗μ(U) + ψ^∗μ(V).$ I do not know how to overcome this issue.  You have said that the identification of the signed finite measures still surjective in $C(M, \mathbb{R})^∗$, even in the non-Hausdorff case. But I was not able to find a reference with such a result (only assuming Hausdorff and locally compact), do you know any?
Comment: (Continuing...) The resulting function $\psi^*\mu$ on the topology of $M$ is finite on $M$, zero on the empty subset and is countably subadditive, so it can be used to define an outer measure which then extends to a Borel measure on $M$ which has the same values on the topology of $M$ as $\psi^*\mu$. For the purposes of defining a linear functional on the space of continuous real valued functions on $M$, the ambiguity of this extension disappears since the set of points where a continuous real valued function does not vanish is always open and only $\psi^*\mu$ matters.
Comment: To be honest I am a bit confused about how we will use Caratheodory's theorem in order to get our measure on $M$. Which ring we will consider? (I am thinking to apply this theorem https://en.wikipedia.org/wiki/Carath%C3%A9odory%27s_extension_theorem).  Could someone enlighten me? We have that $\psi^*\mu(A\sqcup B) = \psi^*\mu(A)  + \psi^*\mu(B)$ for open sets. But is this enough? Since the open sets are not a ring (or an algebra) I am not sure how to proceed. Maybe $\nu(A) = \inf\{\psi^*\mu(B);\ A\subset B\subset M\}$ will do the job, I will check it.
Comment: There is a different, weaker form of Carathéodory's extension theorem which is the following: one can begin with a family $\mathscr{C}$ of subsets of $M$ such that $\varnothing\in\mathscr{C}$ and any $A\subset M$ is contained in a countable union of members of $\mathscr{C}$, and a $[0,+\infty]$-valued function $\tau$ on $\mathscr{C}$ with $\tau(\varnothing)=0$.If we define $$\mu^*(A)=\inf\left\{\sum^\infty_{n=1}\tau(C_n)\ \Bigg|\ C_n\in\mathscr{C}\ ,\,\cup^\infty_{n=1}C_n\supset A\right\}\ ,\,A\subset M\ ,$$ then one can show that $\mu^*$ is a (not necessarily regular) outer measure.
Comment: (1/2) I deleted some comments last night because I realised their contents was incorrect right before I slept and didn't have time to write corrected versions. The main point I realised is that $\psi^* \mu$ **need not** be additive on the topology of $M$ and therefore definitely need not extend to a measure.
Comment: (2/2)  For example, consider $M = \{1,2,3\}$ equipped with the topology $\{\emptyset, \{1\},\{2\},\{1,2\},\{1,2,3\}\}$. Since the only open set containing $3$ is the whole space, $C(M)$ contains only constant functions. Therefore $\tilde{M} = \{p\}$ so $\mu$ is a scalar multiple of a dirac measure. Then $$\psi^* \delta_p(\{1,2\}) = \psi^*\delta_p(\{1\}) = \psi^* \delta_p(\{2\})$$ means additivity fails on the open sets in this case so $\psi^* \delta_p$ defined only on open sets cannot extend to a measure.
Comment: The most important point that needs to be proved is this: If you have a (finite) Borel measure $\mu_X$ on the Hausdorffication $X$ of $M$, is there a Borel measure $\mu_M$ on $M$ so that $\pi_*(\mu_M)=\mu_X$? This is the same question as whether or not every positive functional on $C(M)$ is induced by integration along a Borel measure.
Comment: https://mathoverflow.net/questions/360560/riesz-markov-kakutani-representation-theorem-for-compact-non-hausdorff-spaces/360576?noredirect=1#comment908498_360576 I think that this question on MO finishes all discussion and provide us a reference on how to do the extension that we want.


Last Of Type / Last Child with Classes?

Question: Is it possible to select the 2nd warranty-box class with CSS alone? I've tried combinations of last-of-type and last-child, but I haven't come up with anything that works.
From what I can tell, the "row" and "columns" wrappers break the sibling style relationships last-of-type and last-child depend on.
I've tried combinations of like .warranty .warranty-box:last-of-type but I seem to only be selecting either both of them or neither.
My brain hurts at this point.

All New Homes Include

7-Year Warranty*

107 Point Final Inspection

CSP (Customer Service Program)

Delivery Anywhere in Ohio**

Base Set Installation

Roll on/Beams-Guide System Set

Central Air Conditioning

Gutters and Downspouts

Pre-Existing Homes Include

1, 2, or 3-Year Warranty on Qualified Homes*

107 Point Final Inspection

Central Air Conditioning

Comment: the `first-`, `nth-`, and `last-` pseudo-selectors are relative to the element's parent, which in this case are the `.columns` divs.
Answer: You can get the last element by type and then target the class.
DEMO https://jsfiddle.net/2362mjox/1/
.warranty > div:last-of-type .warranty-box {
  background: red;
}

the code above will look for the last midiate div child of warranty
Comment: Thank you! I found it incredibly hard to find any references without just the _most basic_ of examples!
Comment: Note that this won't work if OP adds another div with .warranty-box after the 2nd one; in that instance it will select the recently-added 3rd div instead. For selecting a specific number element it is better to use `nth-child` or `nth-of-type` instead, so that future modifications after the fact are less likely to break.

Last Of Type / Last Child with Classes?


Uso correto do "goto" com o "if else"

Question: Estou com uma dúvida sobre o correto uso do "goto", fiz um pequeno exemplo que ilustra minha dúvida:
<?php
    $valor01=10;
    $valor02=8;
    if($valor01 > $valor02)
    {
        echo "valor01 é maior que valor02
";
    }
    else
    {
        goto rotulo;
    }

    rotulo:
    {
        echo "valor02 é maior que valor01";
    }
?>

Como fazer para que o rótulo só seja executado caso a condição do if não seja satisfeita?
Da forma como está o resultado é o seguinte:
valor01 é maior que valor02
valor02 é maior que valor01

Isso é possível?
Comment: O goto não é recomendado, por ser difícil de compreender quando o projeto fica maior.
Comment: [http://php.net/manual/en/images/0baa1b9fae6aec55bbb73037f3016001-xkcd-goto.png](http://php.net/manual/en/images/0baa1b9fae6aec55bbb73037f3016001-xkcd-goto.png)
Comment: E só pôr o código direto no else, sem goto. É pra isso mesmo que serve o else...
Comment: Neste teu exemplo não há o menor sentido usar `goto`, basta fazer a lógica dentro do `else`, de fato, creio que nunca precise usar este comando, visto que ele cria um código espaguete.
Comment: Plenamente possível é só fazer um teste de mesa que você descobrirá os trechos de seu código que serão executados. O comando goto existe por razões históricas. Era muito utilizado no estilo de programação da década de 1960 mas depois disso seu uso foi execrado por todos os problemas que causa. No seu caso é só colocar outro goto após o if pulando o trecho sob rotulo.
Comment: A resposta resolveu sua dúvida? Acha que pode aceitá-la? Veja o [tour] se não souber como faz. Isso ajudaria muito indicar que a solução foi útil para você. Também pode votar em qualquer pergunta ou resposta que achar útil no site todo (assim que aceitar ganhará privilégio para votar).
Comment: Se ainda assim for ealmente necessário, OOP, não use o goto, crie uma função e chame-a no else. Evoluimos.. hehe
Answer: Sim, existe, e muito mais simples:
<?php
    $valor01 = 10;
    $valor02 = 8;
    if ($valor01 > $valor02) echo "valor01 é maior que valor02
";
    else echo "valor02 é maior que valor01";
?>

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
O correto uso do goto é evitá-lo sempre que ele não traz vantagens claras e seu exemplo ele só traz desvantagens. E até me parece que está procurando um jeito de usar um goto e não querendo resolver um problema. Pra que complicar o que é simples?
Relacionada: Por que o uso de GOTO é considerado ruim?.
Comment: Maniero não se trata de tentar "reinventar a roda", ou tão pouco é "um jeito de usar goto e não querendo resolver um problema..."
Como disse, estou reaprendendo,vi a opção goto e quero entender mais a respeito dela,acredito que se foi incluída no PHP deve ter algum propósito.
O artigo que você recomendou eu já havia lido,porém acredito que seja sempre bom  ouvir mais opiniões a respeito.
O exemplo que citei é apenas para ilustrar uma hipótese,pois apesar de não ser especialista em PHP também não entendi direito o objetivo do uso da função.
Mas seja como for, obrigado pelo retorno.

Uso correto do "goto" com o "if else"


Having problem with TensorFlow not recognizing my GPU (NVIDIA 4090 RTX)

Question: For some reason my installation of TensorFlow on an Ubuntu Focal is not recognizing my GPU.
testTensorFlowTTS.py

2023-05-05 20:10:21.682174: I tensorflow/tsl/cuda/cudart_stub.cc:28] Could not find cuda drivers on your machine, GPU will not be used.
2023-05-05 20:10:21.704546: I tensorflow/tsl/cuda/cudart_stub.cc:28] Could not find cuda drivers on your machine, GPU will not be used.
2023-05-05 20:10:21.704838: I tensorflow/core/platform/cpu_feature_guard.cc:182] This TensorFlow binary is optimized to use available CPU instructions in performance-critical operations.
To enable the following instructions: AVX2 FMA, in other operations, rebuild TensorFlow with the appropriate compiler flags.
2023-05-05 20:10:22.134455: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Could not find TensorRT
<CTRL-D>
terminate called after throwing an instance of 'std::runtime_error'
  what():  random_device could not be read
Aborted (core dumped)

Script is simple test script...
#!/usr/bin/python3

import tensorflow as tf

import yaml
import numpy as np

import IPython.display as ipd

from transformers import pipeline

from tensorflow_tts.inference import TFAutoModel
from tensorflow_tts.inference import AutoConfig
from tensorflow_tts.inference import AutoProcessor

nvidia-smi

Sat May  6 07:05:33 2023
+---------------------------------------------------------------------------------------+
| NVIDIA-SMI 530.41.03              Driver Version: 530.41.03    CUDA Version: 12.1     |
|-----------------------------------------+----------------------+----------------------+
| GPU  Name                  Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf            Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|                                         |                      |               MIG M. |
|=========================================+======================+======================|
|   0  NVIDIA GeForce RTX 4090         Off| 00000000:41:00.0  On |                  Off |
|  0%   36C    P8               43W / 450W|    301MiB / 24564MiB |      1%      Default |
|                                         |                      |                  N/A |
+-----------------------------------------+----------------------+----------------------+

+---------------------------------------------------------------------------------------+
| Processes:                                                                            |
|  GPU   GI   CI        PID   Type   Process name                            GPU Memory |
|        ID   ID                                                             Usage      |
|=======================================================================================|
|    0   N/A  N/A      1514      G   /usr/lib/xorg/Xorg                           59MiB |
|    0   N/A  N/A      2384      G   /usr/lib/xorg/Xorg                           91MiB |
|    0   N/A  N/A      2547      G   ...39943991,1614355343741730628,131072      131MiB |
+---------------------------------------------------------------------------------------+

Oh, ran the script above and expected no errors.
Tried updating several tings.. including
python3 -m pip install nvidia-tensorrt
apt-get install nvidia-cuda-toolkit libnvvm

Comment: I am still working on the root problem, but for the record, pyTorch sees my GPU's.  I also ran the following: python3 -c 'import torch; print(torch.cuda.is_available())' which results in true.
Answer: Please go through this tensorflow official link to install tensorflow in your system and follow the step by step instructions.
Please make sure all the system requirements are satisfied as specified in the link and set the path for all the software.
Let us know if the issue still persists. Thank you.
Comment: But that link recommends using Conda, I am trying to install it in the base OS, prefer not to use Conda
Comment: Looking at my installation, using python 3.10, the latest pip install gives me version 18.104.22.168 of nvidia-cudnn-cu11, and have tensorflow 2.12.0 installed.
Comment: Could you please check if you have installed right version of CUDA and cuDNN for GPU support compatible to installed tensorflow , python version in your system. Please refer to this [tested build configurations](https://www.tensorflow.org/install/source#gpu) for the same and set the [system path](https://www.tensorflow.org/install/pip#step-by-step_instructions) for these software as mentioned in the link inside 4. GPU setup instructions.


What method should I use to model simplified performance

Question: I have the data of some build times.  These builds occur on a cloud and the runtime has been more varied than in the past.  One thing that could be occurring is an improper sharing of resources between clients.  To test this, I've downloading the dataset containing
Start Time
Agent ID
Length of Run

I want to test to see if when there are more machines running, the builds get slower.  What method should I use to do this?
Comment: I don't see how you can use these daya to discern how many machines are running.
Comment: Imagine two agents, AgentA AgentB.  AgentA starts at noon.  AgentB starts at 1:00 pm.  If I know they both ran for 2 hours each, then I can calculate what time periods they ran together.
Answer: Based on your answer to my question, I think you can construct an additional variable nComp in the dataset equal to the number of competitors associated with each observation. You probably should throw out the first few observations because you can expect there were competing agents active at the beginning that are not accounted for.
Then you can construct a scatterplot of LengthOfRun versus nComp. If it looks reasonably linear, then a simple linear regression should help you make an inference about the effect of number of competitors. If it's nonlinear, or the variability changes, you need a fancier regression model.
In addition, you could plot nComp versus other variables -- e.g. vs. StartTime to see if there is a trend.
Comment: Oh, thats a neat way to approach it.  I'll definitely try that.   I was originally thinking I would throw a non-linear model at lengths of time that had X agents running.  But your idea is a great step in just getting a picture of whats going on.


Is my SIM card faulty or is my provider annoying me?

Question: I'm trying to establish a PPP connection using pppd and AT Commands. This usually works fine with a SIM card of my local provider. However, I received a card from a friend that is living in Germany and I wanted to give it a try from Switzerland but I have a very strange behavior.
First I cannot activate the error message (AT+CMEE), I always get the error message "ERROR" despite I activated the full verbose previously (AT+CMEE=2). This commands works with my local provider SIM card ...
Then if I check the network status:
AT+CGREG?
+CGREG: 1,3

Believing the "3", this means "Registration denied".
When I try to attach or detach, I always have an error without more explanation (Despite AT+CMEE=2):
AT+CGATT=0
ERROR
AT+CGATT=1
ERROR
AT+CGATT?
+CGATT: 0

OK

I can send SMS with AT commands! Putting the SIM card in a phone, I cannot establish any call!
So is it possible to send SMS without the need to register to the network? Is it possible that error message reporting is deactivated on the SIM card? I'm wondering if this is a problem of configuration, a problem of the SIM card or a problem of provider...
Edit
If this could help someone. I tried to send an SMS when I'm detached from the network with my working SIM card, it works! Believing this website I guess my friend didn't pay the bill or my local network provider refuses me to use its network ...
Answer: Probably roaming of circuit switched data (GSM) is allowed. And roaming of GPRS service is not allowed.
AT+CGREG? returns status of GPRS registration.
AT+CREG? returns status of network registration (GSM/UMTS).
Try command:
 AT+CREG?

It probably will return 5 (Registered, roaming).
SMS message sending works because it does not need GPRS. Attach and +CGREG stuff are all for GPRS.
Comment: Thanks, you were right! Is it possible to establish a data connection through GSM without GPRS?
Comment: Yes, You can use circuit switched GSM-data (CSD or HSCSD) without GPRS.


Como trabalhar com Ajax com JQuery?

Question: Tenho a seguinte função:
function getJson() {

        $.ajaxSetup({
            async : false
        });

        $.getJSON(baseURL + "/ObterCursos",
                function(data) {
                        $.each(data, function(key, val) {
                            items.push({
                                "Codigo" : val.Codigo,
                                "Nome" : val.Nome
                            });
                });
        });
}

Na primeira vez que ela é chamada, demora um pouco para trazer os resultados, mas nas vezes seguintes ela funciona rapidamente. Mas descobri que se eu compilar esse código em um projeto Cordova, mesmo sendo chamada novamente e existindo valores diferentes sendo retornados da solicitação, esse método não atualiza os resultados. O que posso fazer para resolver isso?
Answer: Pode ser um problema relacionado com cache. Para testar/resolver podes fazer 2 coisas:
1- desliga o cache do Jquery. Coloca cache: false, no setup do ajax.
$.ajaxSetup({
    async : false,
    cache: false
});

2- coloca um timestamp na url para a url ser sempre diferente e forçar o browser a fazer o pedido sem cache.  Por exemplo:
var timestamp = new Date().getTime();
$.getJSON(baseURL + "/ObterCursos?ts=" + timestamp, function(data) {

Como trabalhar com Ajax com JQuery?


"Unrecognized selector sent to instance" when using custom table cell

Question: I have implemented a custom table cell and am receiveing a runtime error ("Unrecognized selector sent to instance") when the table enters cellForRowAtIndexPath. The error occur when trying to instantiate the custom cell. I have achieved this successfully before, but now the error won't go away. I have a prtotype cell and its custom class attribute is set to the custom cell UITableViewCell subclass. Here is the custom cell:
#import "FavoriteCell.h"

@implementation FavoriteCell
@synthesize lblGaugeID, lblMainTitle, bgImage;

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    bgImage = [UIImage imageNamed:@"tableCellBG.png"];
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        UIColor *transparentBG = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.0];
        UIColor *foregroundColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0];
        //UIColor *shadowColot = [UIColor colorWithWhite:0.75 alpha:1.0];

        CGSize size = self.contentView.frame.size;
        self.backgroundView = [[UIImageView alloc] initWithImage:bgImage];
        self.lblMainTitle = [[UILabel alloc] initWithFrame:CGRectMake(8.0, 0.5, size.width-16, size.height-40)];
        [self.lblMainTitle setFont:[UIFont systemFontOfSize:12.0]];
        [self.lblMainTitle setTextAlignment:NSTextAlignmentLeft];
        [self.lblMainTitle setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
        [self.lblMainTitle setBackgroundColor:transparentBG];

        self.lblGaugeID = [[UILabel alloc] initWithFrame:CGRectMake(20.0, 31.0, size.width-16, size.height-40)];
        [self.lblGaugeID setFont:[UIFont boldSystemFontOfSize:15.0]];
        [self.lblGaugeID setTextAlignment:NSTextAlignmentLeft];
        [self.lblGaugeID setTextColor:foregroundColor];
        [self.lblGaugeID setShadowOffset:CGSizeMake(0.2 , 0.2)];
        [self.lblGaugeID setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
        [self.lblGaugeID setBackgroundColor:transparentBG];

        [self.contentView addSubview:lblGaugeID];
        [self.contentView addSubview:lblMainTitle];
    }
    return self;
}

@end

and here is where it is instatiated (excerpted from my view controller class):
-(FavoriteCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellIdentifier = @"favoriteCell";
    FavoriteCell *cell = (FavoriteCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentifier]; //error
    if(cell == nil){
        cell = [[FavoriteCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    NSString *siteName = [faveKeys objectAtIndex:indexPath.row];

    [cell.lblMainTitle setText:siteName];
    [cell.lblGaugeID setText:[allFavorites objectForKey:siteName]];
    return cell;
}

Here is the full error message:

* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFConstantString instantiateWithOwner:options:]: unrecognized selector sent to instance 0x24bb0'

Can anyone offer some advice on what to check? Thanks! Vivian
Comment: Whats the error message (tell us the instance and the method name).
Comment: Are you using a XIB for your custom cell? If so, it might be that `UITableView` auto-instantiates `UITableViewCell` instead of your custom cell class. (Yay, I <3 Interface Builder!)
Comment: Added the error message to the post
Comment: No, I am not using a xib for the custom cell. I just created a subclass of UITableViewCell
Comment: looks like something is wrong maybe with the "siteName".. can you print that out after you get it out of the array?
Comment: The error occurs before that line (w/ sitename) is reached.
Comment: try putting breakpoints inside your customcell and see which line it fails
Comment: @Vivian: Is `initWithStyle` called at all? Do you use a storyboard file? In that case (I think) `initWithCoder` is called instead. - Did you set the identifier of the prototype cell to the same string "favoriteCell"?
Comment: `instantiateWithOwner:options:` being a method of `UINib`, I don't think the problem comes from your `UICell` subclass. Could you post more of your Controller, the stack trace and the line throwing the exception ? (see [this link on how to break on exception](http://blog.manbolo.com/2012/01/23/xcode-tips-1-break-on-exceptions) if you don't know how to do it)
Comment: It sounds like you've used `registerNib:forCellReuseIdentifier:` somewhere in your controller. Either that or you've put the ReuseIdentifier into InterfaceBuilder. Make sure in InterfaceBuilder it doesn't have a ReuseIdentifier.
Answer: Using - (void)registerNib:(UINib *)nib forCellReuseIdentifier:(NSString *)identifier was a good idea if you had defined your custom cell in a separate NIB file. The problem was that you passed an NSString rather than a UINib object.
Do this instead:
[self.tblFavorites registerNib:[UINib nibWithNibName:@"favoriteCellView" bundle:nil] forCellReuseIdentifier:@"favoriteCell"];
However since you used a prototype cell rather than a separate NIB, there's no need to do this at all. Instead you just need to make sure the prototype cell's reuse identifier is set properly (in this case to "favoriteCell").


Proof of $\sum_{n=1}^{\infty}\frac{1}{n^2}=\frac{\pi^2}{6}$

Question: Prove that $$\sum_{n=1}^{\infty}\frac{1}{n^2}=\frac{\pi^2}{6}$$
I have actually got the HINT for this Proof from a very nice book:
The HINT i started with is:
$$\frac{1}{\sin^2 x}=\frac{1}{4\sin^2\left(\frac{x}{2}\right)\cos^2\left(\frac{x}{2}\right)}=\frac{1}{4}\left(\frac{1}{\sin^2\left(\frac{x}{2}\right)}+\frac{1}{\sin^2\left(\frac{x+\pi}{2}\right)}\right) \tag{1}$$
Now we have:
$$1=\frac{1}{\sin^2\left(\frac{\pi}{2}\right)}=\frac{1}{4}\left(\frac{1}{\sin^2\left(\frac{\pi}{4}\right)}+\frac{1}{\sin^2\left(\frac{3\pi}{4}\right)}\right)$$
Applying $(1)$ Repeatedly we get
$$1=\frac{1}{16}\left (\frac{1}{\sin^2\left(\frac{\pi}{8}\right)}+\frac{1}{\sin^2\left(\frac{3\pi}{8}\right)}+\frac{1}{\sin^2\left(\frac{5\pi}{8}\right)}+\frac{1}{\sin^2\left(\frac{7\pi}{8}\right)}\right)$$
So Generalizing we get:
$$1=\frac{1}{4^n}\sum_{k=0}^{2^n-1} \frac{1}{\sin^2\left(\frac{(2k+1)\pi}{2^{n+1}}\right)}$$
EDIT:
Ok let me explain the next step the author of the book has followed:
$$1=\frac{1}{4^n}\sum_{k=0}^{2^n-1} \frac{1}{\sin^2\left(\frac{(2k+1)\pi}{2^{n+1}}\right)}=\frac{2}{4^n}\sum_{k=0}^{2^{n-1}-1} \frac{1}{\sin^2\left(\frac{(2k+1)\pi}{2^{n+1}}\right)}$$
My doubt is how a factor of $2$ came outside and why the upper limit has changed?
Comment: If you got your method from a book, then it would be useful to provide the reference (author and the title). That said, this series is famous and there is a lot of questions and answers here about it, have you searched them?
Comment: The accepted answer in the linked above question uses the same method as far as I see
Comment: The source is "Problems in Real Analysis" by Teodora Liliana and Titu Andreescu
Answer: This answer is limited to the question asked in the OP's edit. The puzzling step taken there uses the fact that $\sin(\pi-x)=\sin x$ and may best be explained with the example
$$\begin{align}
{1\over16}\left({1\over\sin^2\left(\pi\over8\right)}+{1\over\sin^2\left(3\pi\over8\right)}+{1\over\sin^2\left(5\pi\over8\right)}+{1\over\sin^2\left(7\pi\over8\right)} \right)
&={1\over16}\left({1\over\sin^2\left(\pi\over8\right)}+{1\over\sin^2\left(3\pi\over8\right)}+{1\over\sin^2\left(3\pi\over8\right)}+{1\over\sin^2\left(\pi\over8\right)} \right)\\
&={2\over16}\left({1\over\sin^2\left(\pi\over8\right)}+{1\over\sin^2\left(3\pi\over8\right)} \right)
\end{align}$$
Comment: You made my day, Thank You


Redirect URL to a Tomcat webapp

Question: I have a Tomcat server with two webapps, app1 and app2 (the app part is really the same). Each app has an independent group of users.
I would like the groups to be able to access their respective app using group1.domain.com/app and group2.domain.com/app URLs, meaning that the numbers should be hidden from the URL displayed in browser. I suppose there needs to be a mechanism that would return the correct app based on the group# part of the URL.
I have a vague understanding of URL rewrites. Is there a way to do this with only Tomcat? Or do I need Apache HTTP server? I would rather not use Apache if possible, but have no problem going that way if necessary.
Answer: It is not really about rewriting url but more about virtual hosting.
You can do it in tomcat with the Host element in server.xml. For your case, you will want an Host group1.domain.com where the appbase (read folder where tomcat look for war) will contain app1 and an Host group2.domain.com where the appbase will point to the folder containing app2.
You will maybe need a default Host for those user agent who use the Ip adress.
Thus something like this in server.xml :
 <Host name="group1.domain.com" appBase="/war/group1"/>
 <Host name="group2.domain.com" appBase="/war/group2"/>

And then app.war in /war/group1 (for the first app) and app.war in /war/group2 (for the second)
see Tomcat documentation for details

Redirect URL to a Tomcat webapp


Inequality $(n!)^3<n^n(n+1/2)^{2n}$

Question: $(n!)^3<n^n((n+1)/2)^{2n}$
I've been trying to solve this problem. I've tried using these relations:
$n^2(n+1/2)^2=$Sum of cubes of first n natural numbers
$(n(n+1)/2)=$Sum of first n natural numbers
But still I'm unable to solve this. Can you please help me?
Comment: Your attempts in the post also suggest you meant $(n+1)/2$ instead of $n+1/2$ (the parenthesis are important!) since $n^2((n+1)/2)^2=1^3+2^3+\dots+n^3$ as you mention. Unfortunately you have already got 3 answers for the incorrect version of the statement.
Comment: Your equation is not clearly stated
Comment: Try to prove it using induction
Comment: For what you probably intented to solve, see [Proving $(n!)^3<n^n\times\left(\frac{n+1}{2}\right)^{2n}$ with high school math](https://math.stackexchange.com/questions/3548414)
Answer: We have for positive integer $n$,
$$n!\leq n^n\implies n!^3\leq n^{3n}< (n^3+n^2+n/4)^n=[n (n+1/2)^{2}]^n=n^n(n+1/2)^{2n}$$
Answer: Proof by induction:
For $n=1$ it holds.
Assume that it holds for $n$ we have to prove that it holds for $n+1$, or that:
$$
(n+1)^3\lt \frac{(n+1)^{n+1}}{n^n}\frac{(n+1+\frac12)^{2n+2}}{(n+\frac12)^{2n}}
$$
which is the same as:
$$
(n+1)^2\lt(n+1+\frac12)^2(1+\frac1n)^n(1+\frac1{n+\frac12})^{2n}
$$
or that
$$
(n+1)^2\lt(n+1+\frac12)^2
$$
which is clearly true.
Answer: Proving $$(n!)^3<n^n\left(n+\frac{1}{2}\right)^{2 n}$$ is the same as proving
$$3\log(n!) < n\log(n)+2n \log\left(n+\frac{1}{2}\right)$$ Using Stirling approximation for the lhs and Taylor for the rhs
$$\text{rhs - lhs}=3 n+\left(1-\frac{3}{2} \log (2 \pi  n)\right)-\frac{1}{2 n}+O\left(\frac{1}{n^2}\right)$$ which is true $\forall n \geq 1$.

Inequality $(n!)^3<n^n(n+1/2)^{2n}$


Search template page in Drupal 7

Question: In search results page,
the search form and search results are in the content area.
Can we insert another block between the search form and results list? Or adjust the order for example put "spelling-suggestions" on the top of the form, then add another block between the form and search extra provided by display suite.
If without existing templates, guessing we will have to modify the $node['content'].
Any ideas are welcome, thanks
<form id="search-form" class="search-form" accept-charset="UTF-8" method="post" action="/search/all/test">

One result

Answer: My current method is dirty:
  $build['search_form_resort'] = $build['search_form'];
  unset($build['search_form']);

Then put the $build['search_form_resort'] under the $build['suggestions'].
Read more:
http://api.drupal.org/api/drupal/modules%21search%21search.pages.inc/function/search_view/7

Search template page in Drupal 7


(inverse) Fourier transform of sinc function

Question: $F(k)=\frac{\sin{(k+1)}}{(k+1)}$.
How can I find the inverse Fourier Transform of above function.
I am trying to use the result:
$f(t)\exp(ikt)=F(k-k_0)$.
But I am stuck.
Please help me out. I am new to Fourier transform.
Comment: A part from the shift ($+1$), have you ever encountered the Fourier transform of the box function?
Comment: Yes. But I can't figure out it yet.
Answer: Let me first get rid of the trivial shift, so I will consider what you call
$$ F(k-1) = \frac{\sin(k)}{k} = \mathrm{sinc}(k), $$
which is the sinc function.
The simplest way would be to recognize that the (inverse) Fourier transform of the box function is the sinc. This implies that the Fourier transform of $F(k-1)$ must be the box function. So the easiest thing would be to work backward and see what box exactly you need in order to get this particular expression for the sinc.
Let's instead work forward. We immediately face a problem as $F \notin L^1(\mathbb{R})$. This means that the integral
$$
\int_\mathbb{R} \ dk \ e^{ikx} \frac{\sin(k)}{k} $$
does not exist. What we should do is insert a cutoff $\Lambda$ after which the integral converges, and then evaluate the result as $\Lambda \to \infty$ :
$$
\lim_{\Lambda \to \infty} \int_{-\Lambda}^\Lambda dk \ e^{ikx} \frac{\sin(k)}{k}
$$
However evaluating the integral with the cut-off is cumbersome so I'll use a different approach.
We are after
$$
f(x) = \int_\mathbb{R} \ dk \ e^{ikx} \frac{e^{ik}-e^{-ik}}{2ik} $$
where the integral must actually be intended in a peculiar way. Differentiating with respect to $x$ we obtain, formally,
\begin{align}
f'(x) &= \int_\mathbb{R} \ dk \ e^{ikx} \frac{e^{ik}-e^{-ik}}{2} \\
&= \pi \left ( \delta(x+1)-\delta(x-1) \right )
\end{align}
where $\delta $ is the Dirac delta. Now we know that the primitive of the Dirac delta is the Heaviside function $\theta(x)$ so, integrating with respect to $x$ we get
$$
f(x) = \pi \left ( \theta(x+1)-\theta(x-1) \right ).
$$
This is precisely the box function between -1 and 1 and height $\pi$.
Introducing back the shift we get
$$
\hat{F}(x) = \pi \left ( \theta(x+1)-\theta(x-1) \right ) e^{-ix}
$$
Comment: Thanks for detail explaination.
Comment: @SumitSah I'm happy you appreciate it,
is everything clear? One of the ideas of this site is that if you find the answer useful you should upvote it  and/or accept it.


Describing equivalence classes

Question: The problem is : define relation equivalence on Z by $m=n$ in case $m^2=n^2$.
a)Show that its an equivalence relation on Z.
b)Describe the equivalence classes for = how many are there.
For part a, I proved it to be true by showing that it's reflexive, symmetric and transitive. I have used matrix to do that however I cant figure out part b. Can someone explain part b  to me please.
Comment: Hint: $\;m\sim n\iff m^2=n^2\iff m=\pm n\ldots$
Answer: Hint
$$
m^2 = n^2 \iff m^2 - n^2 = 0 \iff (m - n)(m + n) = 0 \iff m = n \text{ or } m = -n
$$
So $m$ and $n$ are equivalent if and only if either $m = n$ or $m = -n$.
Answer: In general if $f:X\rightarrow Y$ is a function then $\sim$ defined by $x\sim x'\iff f(x)=f(x')$ is always an equivalence relation on $X$ and this is not difficult to prove. Note that:
1) $f(x)=f(x)$ reflexive
2) $f(x)=f(y)\Rightarrow f(y)=f(x)$ symmetric
3) $f(x)=f(y)\wedge f(y)=f(z)\Rightarrow f(x)=f(z)$ transitive
In your case we deal with $f(n)=n^2$ on $\mathbb Z$.
For b) see the answer of Goos.

Describing equivalence classes


Split line into variables

Question: I am trying to split a txt file with multiple lines into separate variables. The text is an output of volume information with names, data sizes, etc. and I wan to split each dataset into a specific variable but can't seem to get it
Example is trying to split this data set into a variable for each item
/vol0                                abcd4     Object RAID6+  228.33 GB         --  400.00 GB  Online
/vole1                               abcd1     Object RAID6+   44.19 TB   45.00 TB   45.00 TB  Online
/vole2                               abcd4     Object RAID6+   11.27 TB   11.00 TB   12.00 TB  Online
/vol3                                abcd4     Object RAID6+    9.50 TB         --   10.00 TB  Online
/vol4                                abcd1     Object RAID6+   18.39 TB         --   19.10 TB  Online

This is the command I've run, but I keep getting an error about "not enough values to unpack".
inputfile = "dataset_input.txt"
with open(inputfile, "r") as input:
    for row in input:
        vol, bs, obj, raid, used, uunit, quota, qunit, q2, q2unit, status = row.split()

I can split the file by space just by doing the below text and it works. Just can't seem to get it into separate variables so I can manipulate the datasets
for row in input: #running through each row in the file
    output_text = row.split() #split the row based on the default white-space delimiter
    print(output_text)

I'm very new to python, so not sure if this is even possible, or how complicated it is
Comment: Every iteration of your loop is going to reset the variables to whatever line you are iterating leaving you with variables set to the last line in your file. The reason your code doesn't work though is that `split()` returns a single list with the strings as elements. [you would need list comprehension or similar](https://stackoverflow.com/a/34654260/2221001) to do what you are trying to do.  Reading this file into a dictionary or pandas dataframe would surely be a better route for whatever you are planning later on in this code.
Comment: So the goal is to loop through the file line by line, separating by variables, and ultimately the piping standard output to a text file once the loop is complete. And then going back to the next line, printing, etc.
At least that's my goal

edit:
Thanks for the link. I'll check it out
Comment: If you will be printing back out to `stdout` inside the loop then your `output_text = row.split()` is a reasonable way to handle this. `output_text` variable will contain a list that you can manipulate however you like. Once done manipulating you can `join()` it back together for printing like `print(' '.join(output_text))` which will stitch the list back into a string separated by spaces.
Comment: At any rate, this sounds like an [XY problem](https://meta.stackexchange.com/a/66378/438222). It would help if you edit your question and explain fully what you are trying to accomplish (writing out to a new file a manipulated version of the file you are reading in). We can likely help get you to that end point.
Comment: When you have empty values in columns - you will not have enough fields to assign values to all your variables. If possible change the format of your file into CSV, or pipe-delimited format (or similar).  Alternatively put `--` into all columns that do not have values.
Comment: Yeah, ultimately my goal is to separate each datafield into a variable and then be able to only keep the 4-5 that I want. So then I can discard the useless information, and only keep vol, uunit, quota, and quota2, printed to my output

I'm trying to convert an old perl script into python. This is a part of the original I'm trying to imitate

# split out the data from the line. Split fields by space
"my ($vol,$bs,$obj,$raid,$used,$uunit,$quota,$qunit,$q2,$q2unit,$status) = split(/\s+/,$_);"

And after some variable manipulation:
print "$vol,$gb_used,$gb_avail,$gb_size\n";
Comment: your rows looks to be fixed length.  Is that correct?
Comment: The simplest approach is to accept the List from `mylist = row.split()` and obtain the elements you want using such as `var1 = mylist[0]` using whatever index value is appropriate 0 being for the first element.
Answer: Firstly what you done is call split method which would split your rows into a list for every single space present in the string.
That would provide you a list with a bigger length than the number of variables you have defined.
This can only be solved by splitting into the correct number of variables you need.
Secondly in every for loop the same variable would be rewritten with new values thus losing the previous iteration value
you can solve this by having the values appended into respective variable arrays
Here is a simple solution in which you first read the entire text file contents , preprocess it and store the processed content into required variable lists
fle=open("dataset_input.txt",'r')
txt=fle.readlines()

#adding another newline for patter homogenity
txt[-1]+='\n'

n=len(txt)

#remove new lines
for i in range(0,n):txt[i]=txt[i][0:-1]

#trim multi spaces to #
import re
for i in range(0,n):
    txt[i]=re.sub('\s{2,}','#',txt[i])
    txt[i]=txt[i].split('#')

#define required variables
x1=[]
x2=[]
x3=[]
x4=[]
x5=[]
x6=[]
x7=[]

#adding the variable values to respective variables
for i in txt:
    x1.append(i[0])
    x2.append(i[1])
    x3.append(i[2])
    x4.append(i[3])
    x5.append(i[4])
    x6.append(i[5])
    x7.append(i[6])

print(x1,x2,x3,x4,x5,x6,x7)

Also note that it is possible to improve the code by combining the list appending in pre process stage itself depending on your life requirement of the main text file contents
Answer: If you wanted to keep your original approach, something like this will cater for the error of sometimes having only 10 'columns' instead of the expected 11:
with open('dataset_input.txt') as f:
    lines = f.readlines()

for line in lines:
    line = line.strip().split()  # Remove white space and split by space, returns a list
    if line[6] == '--':
        # This means there is no quota value present
        # so insert another -- to correct the length ('columns') of the line to 11
        line.insert(6, '--')
    vol, bs, obj, raid, used, uunit, quota, qunit, q2, q2unit, status = tuple(line)
    # Perform any calculations and prints you want here
    # PER LINE (each iteration will overwrite the variables above)
    # Note that all variables will be strings. So convert if required.

You can of course change the "--" to anything you want. e.g:
...
line.insert(6, '0')
...

and also change the "--" in the qunit as well if you wish:
...
line[6] = '0'
line.insert(6, '0')
...

On an unrelated side note, you have input as your file handle in your original code. input is a Python reserved keyword; these should be avoided when you choose any kind of identifier in your code.
Answer: the error not enough values to unpack is produced when executing this line of code : vol, bs, obj, raid, used, uunit, quota, qunit, q2, q2unit, status = row.split().
the reason is that you are reading 11 separate elements from each row, though looking at the example you show, not every row contains 11 words separated by space.
check this out :
with open(inputfile, "r") as input:
    for row in input:
        output = row.split()
        print("this row provides {} arguments".format(len(output)))
        print(output)

the output :
this row provides 10 arguments
['/vol0', 'abcd4', 'Object', 'RAID6+', '228.33', 'GB', '--', '400.00', 'GB', 'Online']
this row provides 11 arguments
['/vole1', 'abcd1', 'Object', 'RAID6+', '44.19', 'TB', '45.00', 'TB', '45.00', 'TB', 'Online']
this row provides 11 arguments
['/vole2', 'abcd4', 'Object', 'RAID6+', '11.27', 'TB', '11.00', 'TB', '12.00', 'TB', 'Online']
this row provides 10 arguments
['/vol3', 'abcd4', 'Object', 'RAID6+', '9.50', 'TB', '--', '10.00', 'TB', 'Online']
this row provides 10 arguments
['/vol4', 'abcd1', 'Object', 'RAID6+', '18.39', 'TB', '--', '19.10', 'TB', 'Online']

you need then to make some cleaning for you data-set, or maybe an if statement on the length would be helpful.
looking at only the small portion of the data you provided i see that the mark "--" means that there is no volume. so you can replace the "--" mark with a couple of meaningful variables (value + unit) for example 0 and any unit. This is how you might do it:
with open(inputfile, "r") as input:
        for row in input:
            output = str(row).replace("--","0 0").split()
            print("this row provides {} arguments".format(len(output)))
            print(output)

and this would be the output
this row provides 11 arguments
['/vol0', 'abcd4', 'Object', 'RAID6+', '228.33', 'GB', '0', '0', '400.00', 'GB', 'Online']
this row provides 11 arguments
['/vole1', 'abcd1', 'Object', 'RAID6+', '44.19', 'TB', '45.00', 'TB', '45.00', 'TB', 'Online']
this row provides 11 arguments
['/vole2', 'abcd4', 'Object', 'RAID6+', '11.27', 'TB', '11.00', 'TB', '12.00', 'TB', 'Online']
this row provides 11 arguments
['/vol3', 'abcd4', 'Object', 'RAID6+', '9.50', 'TB', '0', '0', '10.00', 'TB', 'Online']
this row provides 11 arguments
['/vol4', 'abcd1', 'Object', 'RAID6+', '18.39', 'TB', '0', '0', '19.10', 'TB', 'Online']

Answer: It looks to me like your data is a list of fixed length records and rather than using split() you might take slices based on your fixed length fields. Ultimatley, I would look at implementing using pythons struct but this might get you started processing a fixed length record.
Let's start with some example data you read from your file and let's define a list of fixed length field specifications.
data = [
    "/vol0                                abcd4     Object RAID6+  228.33 GB         --  400.00 GB  Online",
    "/vole1                               abcd1     Object RAID6+   44.19 TB   45.00 TB   45.00 TB  Online",
    "/vole2                               abcd4     Object RAID6+   11.27 TB   11.00 TB   12.00 TB  Online",
    "/vol3                                abcd4     Object RAID6+    9.50 TB         --   10.00 TB  Online",
    "/vol4                                abcd1     Object RAID6+   18.39 TB         --   19.10 TB  Online"
]

##------------------------------
## Only you know for sure what the start and stop is of the fields in this fixed length record.
##------------------------------
fields = [
    {"name": "path", "starts_at": 0, "width": 37},
    {"name": "abc", "starts_at": 37, "width": 5},
    {"name": "type", "starts_at": 47, "width": 13},
    {"name": "size", "starts_at": 60, "width": 11},
    # ....
]
##------------------------------

Now, given your rows of data and the field definitions we can create a list of lists.
##------------------------------
## reshape as a list of lists
##------------------------------
data2 = [
    [
        row[field["starts_at"] : field["starts_at"] + field["width"]].strip()
        for field
        in fields
    ]
    for row
    in data
]
print(json.dumps(data2, indent=2))
##------------------------------

This should give you:
[
    ['/vol0', 'abcd4', 'Object RAID6+', '228.33 GB'],
    ['/vole1', 'abcd1', 'Object RAID6+', '44.19 TB'],
    ['/vole2', 'abcd4', 'Object RAID6+', '11.27 TB'],
    ['/vol3', 'abcd4', 'Object RAID6+', '9.50 TB'],
    ['/vol4', 'abcd1', 'Object RAID6+', '18.39 TB']
]

I myself would rather work with a list of dict if possible, so given the data and field definitions above, I might use them like this...
##------------------------------
## reshape as a list of dict
##------------------------------
data2 = [
    {
        field["name"]: row[field["starts_at"] : field["starts_at"] + field["width"]].strip()
        for field
        in fields
    }
    for row
    in data

]

import json # only for printing a nice output
print(json.dumps(data2, indent=2))
##------------------------------

Giving you:
[
  {
    "path": "/vol0",
    "abc": "abcd4",
    "type": "Object RAID6+",
    "size": "228.33 GB"
  },
  {
    "path": "/vole1",
    "abc": "abcd1",
    "type": "Object RAID6+",
    "size": "44.19 TB"
  },
  {
    "path": "/vole2",
    "abc": "abcd4",
    "type": "Object RAID6+",
    "size": "11.27 TB"
  },
  {
    "path": "/vol3",
    "abc": "abcd4",
    "type": "Object RAID6+",
    "size": "9.50 TB"
  },
  {
    "path": "/vol4",
    "abc": "abcd1",
    "type": "Object RAID6+",
    "size": "18.39 TB"
  }
]

Split line into variables