What makes financial fair play fair?

Question: My understanding of the financial fair play rule from UEFA is that clubs can't spend more money then they take in from ticket sales, sponsorships, media deals, etc. The goal being to prevent a super rich owner from coming in and dumping loads of money into a team to buy all the good players and keep everyone else from getting a chance at them.
As I watch this happen though, I'm wondering how this is actually fair to the smaller clubs. The big clubs will continue to make millions and millions from sponsorship deals that the smaller clubs won't have a chance to get unless they somehow can break into that elite group.
If you use the EPL as an example, the best teams in the league have pretty much always been the same (or at least for the last 25 or so years since the silly amounts of money have been poured into the game). There isn't really a chance for even a medium level team like West Brom or Hull to break into the top 4 long term because they won't be able to keep their best players, even if they have a rich owner swoop in a give them millions.
So what makes this rule fair? Or am I missing the point of the rule?
Answer: The idea behind financial fair play is, as you say, to prevent rich owners dumping in their money into a club, and "purchase" success. Examples of such being Chelsea, Man City and more recently PSG. One could count FC "Red Bull" Salzburg among those, even though that club have not been on the international arena as much as the previous ones.
Now there are two fundamental assumptions here:

More money implies more success: This is actually not quite true, not all teams with rich owners get titles. More money usually means more/better players as the club would be able to attract players beyond their stature, given financial incentives. There are numerous examples of clubs giving astronomical salaries to attract players but fail to capitalise on their squad. AC Monaco is a good example. Similarly there are a series of russian clubs that have had their streak of foreign talent coming in for the $$$ but none of these clubs have made success on the international arena.
Owners injecting money into clubs is the only way to "cheat" financially: This is also not quite true. There is a very thin line between what counts as injecting money, and getting a supreme sponsorship deal though business partners.

The idea behind financial fair play is to prevent teams from spending more money than they earn (via rich owners or otherwise) and have a sustainable future. In theory, bigger clubs get more money and indeed spend more money. However they still have to perform to get the big bucks.
If you exclude the absolute top teams (Man Utd, Real Madrid, Barcelona, FC Bayern etc) the majority of the money they get is through commercial products (i.e. merchandising). However for the overwhelming majority of the teams, the ratio between matchday sales, broadcasting and commercial income are more level, meaning that qualifying to continental cups and going further in these competitions bring in a significant amount of money. (Ref for this paragraph: Deloitte Money League report)
Now while a mid-table team, will not be able to compete with the big dogs in the course of a year or two, by doing better and better, they will increase their budget and possibility to attract players. In other words, success means first of all more money; by finishing the league in a good spot teams get more prize money, possibly get qualified for continental competitions (possibly raking in more $$$) AND who doesn't want to buy the shirt of team that's doing well?
Is it fair to compare Man Utd and Hull financially? No! One of them rake in £75M/year, while I doubt Hull come up to those figures even with all their income. Will/does the financial fair play make it fair? No, not really United still gets more money and buy more players than Hull. What the system is there however is to prevent teams like City, or PSG to buy their way to the top. Whether that will be effective or not is a whole different story however.
All in all, it's a big mess with lots of politics and lawyers involved and very little sportsmanship. I recommend the wikipedia article on the subject for a thorough reading, I am sure there are details in there that I did not catch myself.

What makes financial fair play fair?


How data loss and data sequence is managed in RabbitMQ

Question: As in kafka offset is used to manage the sequence of data that needed to be transfer to consumer, how this type of management is done in RabbitMQ to manage the data sequence to prevent data loss.
Comment: Have you read any rabbitmq docs?
Answer: RabbitMQ consumers do not maintain a client side offset like Kafka consumers must. Kafka stores all messages for a configured time period and clients manage their own offsets meaning that different clients can consume messages from different offsets within the queue. This means that different Kafka consumers are not competing consumers unless they coordinate and share their offset.
RabbitMQ is very different. Messages are stored until they get sent to a consumer and then acknowledged or they expire. If there are multiple consumers for one queue then they are competing consumers and one message can only be consumed by one of the many consumers.
RabbitMQ has the concept of a delivery tag which is a monotonically incrementing number that increments per message delivered over a channel. It has no global meaning, it has the scope of a single channel and so is not shared between consumers on different servers, processes. Consumers only need to track this number for message acknowledgement purposes, it is RabbitMQ that is responsible for choosing which message is delivered to which consumer.


Função não executa sem setTimeout

Question: Estou tendo um problema ao executar uma função ao clicar no icheck. No caso, a função só é chamada caso eu dê um setTimeout de 1 milisegundo, menos do que isso ou sem timeout a função não é executada. Como eu posso fazer para executar essa função sem utilizar timeout?
vm.selecionaFiltros = function(){
    $('.marcas').iCheck({
        checkboxClass: 'icheckbox_minimal',
        radioClass: 'iradio_minimal',
    });

    $timeout(function() {
        $('.marcas').on('ifChanged', function (event) {
            console.log('1');
        });
    }, 100);
}

Comment: você executa todo esse trecho toda vez que o usuário clica no checkbox? .iCheck transforma os elementos em objetos iCheck e normalmente só é usado uma vez, logo após a página carregar. Além disso, se é para detectar o click você deveria usar os eventos ifClicked ou ifToggled.
Comment: Olá @EduardoMoreira, eu testei utilizando o ifClicked e Toggled e removi a inicialização o iCheck de dentro da função, mas o meu problema persiste, já que o problema não é no iCheck, é no tempo de rendenização do site, que não consegue pegar o evento ao clicar.
A função selecionaFiltros é chamada após terminar o ng-repeat da listagem de filtros.
Comment: @BernardoKowacic a função `vm.selecionaFiltros` é chamada automaticamente ou precisa ter alguma interação do usuário? Exemplo, clicar em um `checkbox`?
Comment: Olá @CelsomTrindade, então, a função é chamada quando carrega a página, automáticamente. Atualmente eu tirei a inicialização de dentro da função, deixei apenas a parte que verifica se foi marcado ou não.
Comment: @BernardoKowacic baseado nisso vou tentar uma resposta que eu imagino que seja o problema.. Conversamos mais ao longo dos comentários ali.
Answer: Se essa função vm.selecionaFiltros é chamada de modo automático, o possível problema é que ela esteja acontecendo fora do escopo do AngularJs.
O que isso significa?
Significa que o digest cycle já passou, logo as mudanças não serão aplicadas. digest cycle é um processo do AngularJs (também conhecido como dirty checking) que faz a comparação de todos os bindings através dos watchers ({{meuEscopo}} ou ng-bind="meuEscopo" - cada elemento desse em sua view gera um novo watcher) para verificar se aquele dado sofreu alteração e, se sim, atualizar a view com esse novo valor.
Se a sua função é executada após o digest cycle significa que por mais que as mudanças ocorram o AngularJs ainda não "sabe" disso.
Quando um digest cycle é disparado?
Sempre são disparados quando a aplicação carrega ou através de interações com funções do próprio AngularJS, por exemplo, ngClick, ngChange, ngBlur, etc.. Ou, dentro de um controller ou directive, através do uso de $timeout (que é o que você está fazendo) e $interval e, por fim, através de uma chamada manual, explicado melhor abaixo.
Como resolver?
O modo de resolver isso seria chamando manualmente o digest cycle.
Existem 2 métodos de se obter o mesmo resultado final:

$scope.$digest()
$scope.$apply()

Ambos são semelhantes e irão lhe dar o mesmo resultado final. Porém o $scope.$apply() irá disparar o evento $rootScope.$digest() que afeta todos os escopos e seus elementos child enquanto o $scope.$digest() afeta apenas o escopo local e seus elementos child, lhe dando uma melhor perfomance, já que não irá afetar a aplicação como um todo.
Exemplo simples, supondo que na mesma view que esse ng-repeat você possua um directive que mostre o clima, ele não tem ligação alguma com essa lista e possui seu próprio escopo, uma vez que ele vem de um directive. Se você chamar $scope.$digest(), o digest cycle não irá verificar os watchers que pertencem a ele, logo você tem mais performance. Mas se você chamar o $scope.$apply(), como ele irá disparar o $rootScope.$digest() ao invés do $scope.$digest() - ou seja, o ciclo global, aquele directive de clima e todos os seus watchers e child também serão validados pelo ciclo.
Quando usar um ou outro?
Se você tem certeza que a função chamada só irá afetar valores que estão dentro desse escopo, chame o $scope.$digest(). Mas se você sabe que a interação com essas funções podem interferir em escopos que estão fora do atual, use o $scope.$apply().
Exemplo: Supondo que essa lista de ng-repeat seja para selecionar qual o tipo de temperatura é exibido no directive. Celsius, Kelvin ou Fahrenheit, então se eu clicar em um desses elementos do ng-repeat, eu preciso alterar um elemento fora do meu escopo, logo, chamo o $scope.$apply().
Sendo assim, seu código ficaria assim:
vm.selecionaFiltros = function(){
    $('.marcas').iCheck({
        checkboxClass: 'icheckbox_minimal',
        radioClass: 'iradio_minimal',
    });

    $('.marcas').on('ifChanged', function (event) {
        console.log('1');
        $scope.$digest(); //aqui
    });

    $scope.$digest(); //ou aqui
}

Se quiser, ainda pode remover a declaração da função usando o vm e usar uma função JS simples.
function selecionaFiltros() {
    [...]
}

//chamada da função
selecionaFiltros();

O vm na frente serve para executar uma função que é chamada através da view, com ng-click, ng-blur, etc..

Nota: Apenas para lembrar, como você está usando a syntax de vm, precisa injetar o $scope antes de poder usá-lo.
Comment: Olá @CelsomTrindade, eu coloquei o $scope.$digest(); dentro da função do ifChanged e não aconteceu nada, continuou sem funcionar, tentei colocar em na linha de baixo, mas aí deu erro dizendo que $digest não é uma função. Tentei adicionar o $digest no inject do módulo e na chamada da função e deu erro também. Estou injetando o $scope  para usá-lo. Com o $apply ocorreu a mesma coisa.
Comment: @BernardoKowacic o que você precisa injetar é o $scope, não o $digest ou o $apply. Caso ainda assim não dê certo, monte um fiddle ou plunkr onde o problema possa ser reproduzido para poder analisar melhor.

Função não executa sem setTimeout


Arranging K 545 for a string quartet, how to write the harmony part

Question: So, I am trying a second time to arrange K 545 for a string quartet. I think my second draft is better harmonically speaking than my previous attempt to arrange the same sonata. But there is a whole movement that makes it a tad difficult to arrange for string quartet. That would be the second Andante movement. And here is why the Andante is more difficult to arrange than the Allegro and Allegretto movements.
The Allegro and Allegretto both go into a 4 voice texture sometimes. The Andante however is like exclusively in a 3 voice texture, with those voices being:

Upper voice - Melody
Middle voice - Alberti bass except for the lowest note
Lower voice - Bass line formed from lowest notes of the Alberti bass

And these voices fit conveniently into 3 out of 4 instruments in the quartet. The melody, I would be giving to the first violin. The middle and lower voices fit very well into the cello and viola. That leaves the second violin with basically none of Mozart's original notes except in a few chords. But, I can't just leave it out of the movement entirely, otherwise I will get a lot of feedback along these lines:

If your arrangement of the Andante is basically a trio, then why did you arrange for a string quartet in the first place?!
Can't you add a harmony part for the second violin to play? This is obviously one of those cases where you have to add notes to the original score.

So, I have to add a harmony part for the second violin. This is where the difficulty lies. I obviously would want to lean towards either parallel thirds and sixths or contrary motion and minimize parallel fourths, parallel fifths, and octave doublings. Quite a few people have told me that I shouldn't have the second violin go over the melody in the first violin. This limits my contrary motion by quite a bit. In my previous draft, I used contrary motion for measures like this one:

The problem I came across there though had to do with voice crossing(I was going in mostly parallel thirds before, so maybe that's why) between the 2 violins. The ideal voicing of the second violin in terms of avoiding voice crossing, if I wanted to use contrary motion and keep it consonant with the harmony would be:

G3 B3 D4

However, that makes the violin go into the very bottom of its range and I have heard that it isn't ideal for that to happen. If I go any higher though, I will either get a unison or voice crossing, neither of which is good. Voice crossing is obviously a bad thing to have happen because it makes the melody sound a bit more static instead of the way it is supposed to sound. Having a unison though is also bad if it is just the 2 violins in unison. I have been told something along these lines when it comes to violins in unison:

If you have 3 or more violins, you can have them in unison with no worries. If you have just 2 violins though, a unison is horrible because of slight tuning differences between the 2 violins. If a situation comes across where you can't avoid a unison between the 2 violins, then have the viola and cello be either in unison with the violins or in octaves so that the tuning differences aren't audible.

So, how can I make it easier for me to write the harmony part for the second violin in the second movement?
Comment: Alberti bass is actually 3 voices, it is an arpeggio figuration of harmonies with 3 voices.
Comment: @LarsPeterSchultz Well, I separate the Alberti bass into 2 voices, a bass line and then a second voice of alternating notes that plays everything except the bass line, And I personally don't relate Alberti bass to arpeggios in all but one situation. That situation being arpeggios going up or down in an arpeggiated fashion. On the one hand, you can break down that figuration into arpeggios as usual. So something like: C E G, E G C, G C E, C E G On the other hand, you can also break it down into overlapping Alberti bass like this: G E G C, C G C E, E C E G
Comment: I just applied the term "arpeggio" in the sense meaning a broken chord, an arpeggiated accompaniment. An Alberti bass simply means that the chords are played as arpeggios, or broken chords. Bur what you call it doesn't really matter. It is very typically for Alberti bass that it is based on 3 voiced chords. You can of course play it on only two string instruments, well even on one.
Comment: When I hear the term "arpeggio", to me, it is much more specific than just a broken chord. A broken chord, obviously is any chord that isn't played as a block chord. This could mean anything from alternating pairs of notes to Alberti bass and everything in between. But when I hear the term "arpeggio", I don't just think of a broken chord but a very specific broken chord, where everything ascends or descends in order. Thus, I don't think of Alberti bass as being an "arpeggio" since it is Low, High, Middle, High, and not ascending or descending in order.
Comment: Well, Alberti bass is a special type of an arpeggiated accompaniment. It is arpeggiated exactly the way you described it: Low, High, Middle, High.
Answer: @Caters Here is an image from Mozart's quartet in D for flute, violin, viola and cello. From the second movement. The strings are playing pizzicato:

You could divide the notes in a similar way with the Alberti bass, the viola and cello on the beat followed by the 2nd violin with 3 sixteenth notes, thus you get all players in the quartet involved.
Comment: So, instead of having the second violin harmonize the melody, which I did in my first draft and found to be tricky to be consonant with both the melody and the harmony, while also sounding like a countermelody, I could simply have the viola harmonize the bass line and have the sixteenths played by the second violin and have the melody played by the first violin? That sounds way easier than the countermelody option I went with in my first draft(where the sixteenths are played by the viola and the second violin tries to stay consonant with both the main melody and the harmony).
Comment: And I already figured I should have the bass line be played pizzicato, except for where there are long notes or dynamics at mezzo-forte or louder, so as to not overwhelm the sixteenth notes.
Comment: I didn't mean the viola to play the bass line. In the Mozart example the bass line is in the cello. The viola plays another note from the chord.
Comment: That's why I said that with your suggestion, the viola would be *harmonizing* the bass line. The original bass line would of course be played by the cello.
Comment: Oh, yes of course.
Answer: Far from an experienced composer/arranger, nor am I a string musician, but based on what I've heard in classical repertoire, having the second violin play as low as G below middle C isn't necessarily a bad thing, although it does add some special flavor to the music, in my opinion more espressivo and passionate, in fact, a lot of composers have used it in their pieces. But that depends on how you want your arrangement to sound, and I'm guessing, like me, you can't tell accurately how their arrangement would sound like without actually hearing it. (Otherwise you won't be asking the question, right?)
About your arrangement, though, I have a coupe little ideas:
1. Bar 9, 2nd Violin: 1 16th rest followed by three 16th notes G and then one 8th note G, similar to the famous motif from the opening of Beethoven's Fifth Symphony. If the second violin part in the previous bars is mostly 3rd or 6th doubling of the first violin, this could give a nice variation.

When the harmony stays the same, the second violin plays the same note instead of moving in parallel or contrary motion with the first. For instance, bar 5 second violin could just play D repeatedly. The following bar is in the chord of G major, which allows further repetition of the same D, though for the last note of the phrase I would have the first violin play octave double stop and the second play the B above the first violin's lower G.
In Camille's answer, he said you could alternate the melody between two violins. Here I would like to give a concrete example based on how I would achieve that. In bar 7, you may have the first violin play quarter notes A F# D and the 2nd play the rest of melody. And then you could have the 2nd violin continue to play the ending of the phrase (B C B A), while the first respond with the eighth notes D C# C. You may also have the first play an extra D which overlaps with the second violin's last A.
Answer: In order of simplicity:
Omit the second violin.  (I can't think offhand of a quartet other than my own that omits particular instruments in a movement, but the symphonic repertoire is full of spectacular examples.  Use those to answer anyone who complains.)
Alternate the melody between the two violins.
Sometimes double the simplified melody an octave higher, holding notes like pianistic "finger pedaling."  Mozart's piano sonatas often have melodic passages in octaves.
Sometimes add finger pedaling to the non-bass notes of the Alberti bass, perhaps an octave higher, pianissimo.


Nestjs server doesn't respond

Question: I am facing an issue where nestjs server after processing data doesn't respond or send response to client. I created an endpoint which takes time to process and insert the data into db. I am aware that this is not a good practice but this is required for few days. Server responds if request completes in 4m 18s but anymore seconds and it doesn't respond. No timeout or any kind of errors are thrown. I tried sending request from postman but neither server nor postman timeout. I also tried try-catch if I was missing anything. I'm deploying  nest server through pm2. So I tried running server without pm2 but same result. However server responds if it is localhost, in my local environment and on the server too.
I am at a loss here about the bug and any issue. Below are the setup I'm running:

Azure VM - B4ms(16GB RAM, 4 vCPU)
Ubuntu 20.04
Nodejs (14.18.2)
Nestjs (7.0)
pm2 (5.1.2)

Below is my main.ts file

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { urlencoded, json } from 'express';

async function bootstrap() {

    const app = await NestFactory.create(AppModule, {
        logger: ['log', 'error', 'verbose']
    });
    //   app.setGlobalPrefix('api');
    app.use(json({ limit: '500mb' }));
    app.use(urlencoded({ extended: true, limit: '500mb' }));

    await app.listen(3000);
}
bootstrap();

Below is my onboarding module to which endpoint controller belongs:
import { Module } from '@nestjs/common';
import { BatchService } from 'src/batch/batch.service';
import { USERS, OFFICES, USER_BATCH, BATCH, SCHEME, USER_OFFICE, DISTRICTS, ONBOARDED_BATCH_DETAILS } from '../core/constants/index';
import { UtilsService } from 'src/core/utils/utils.service';
import scheme from '../models/scheme';
import { SchemesService } from '../schemes/schemes.service';
import batch from '../models/batch';
import offices from '../models/offices';
import users from '../models/user.entity';
import user_batch from '../models/user_batch';
import { OfficeService } from '../office/office.service';
import { UserBatchService } from '../user-batch/user-batch.service';
import { UsersService } from '../users/users.service';
import { OnboardingController } from './onboarding.controller';
import { OnboardingService } from './onboarding.service';
import { UserOfficeService } from '../user-office/user-office.service';
import user_office from '../models/user_office';
import { HttpModule } from '@nestjs/axios';
import { DistrictService } from '../district/district.service';
import district from '../models/district';
import { OnboardedBatchDetailsService } from '../onboarded-batch-details/onboarded-batch-details.service';
import { onboarded_batch_details } from '../models/onboarded_batch_details';

@Module({
    imports: [
        HttpModule
    ],
  controllers: [OnboardingController],
  providers: [
      OnboardingService,
      UsersService,
      { provide: USERS, useValue: users },
      OfficeService,
      { provide: OFFICES, useValue: offices },
      UtilsService,
      UserBatchService,
      { provide: USER_BATCH, useValue: user_batch },
      BatchService,
      { provide: BATCH, useValue: batch },
      SchemesService,
      { provide: SCHEME, useValue: scheme},
      UserOfficeService,
      { provide: USER_OFFICE, useValue: user_office },
      DistrictService,
      { provide: DISTRICTS, useValue: district },
      OnboardedBatchDetailsService,
      { provide: ONBOARDED_BATCH_DETAILS, useValue: onboarded_batch_details }
    ]
})
export class OnboardingModule {}

Below is my endpoint code.
@Post('/test-batch-onboard')
    @HttpCode(200)
    async testBatchOnbard(
        @Headers('apiKey') apiKey,
        @Body() data: Array<BatchData>,
    ){
        return new Promise((resolve, reject) => {
            let t = 259000;  // 4m 19s -- no response

            let d = this.addBatchStudentData(apiKey, data);

            try{
                setTimeout(function () {
                    resolve("I'm done here after \n" + t/60000 + " mins.");
                }, t);
            }
            catch(e){
                console.log(e);
                reject(new InternalServerErrorException());
            }
        })
    }

Here is my app.module.ts

import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config/dist/config.module';
import { ScheduleModule } from '@nestjs/schedule';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { AttendanceController } from './attendance/attendance.controller';
import { DatabaseModule } from './core/database/database.module';
import { AttendanceService } from './attendance/attendance.service';
import { AttendanceModule } from './attendance/attendance.module';
import { UsersModule } from './users/users.module';
import UserAttendance from './models/user_attendance';
import { BATCH, DISTRICTS, OFFICES, ONBOARDED_BATCH_DETAILS, ORGANIZATIONS, USERS, USER_ATTENDANCE, USER_BATCH } from './core/constants';
import { SchedulerModule } from './scheduler/scheduler.module';
import { ReportsModule } from './reports/reports.module';
import { OfficeModule } from './office/office.module';
import { OrganizationModule } from './organization/organization.module';
import { DailyAttendanceTasksService } from './jobs/dailyAttendanceReport.job';
import { UsersService } from './users/users.service';
import { OfficeService } from './office/office.service';
import { OrganizationService } from './organization/organization.service';
import { BatchService } from './batch/batch.service';
import { UtilsService } from './core/utils/utils.service';
import { MailgunService } from './core/utils/mailgun.service';
import { UserBatchModule } from './user-batch/user-batch.module';
import { BatchModule } from './batch/batch.module';
import { OnboardingModule } from './onboarding/onboarding.module';
import { SchemesModule } from './schemes/schemes.module';
import { UserOfficeModule } from './user-office/user-office.module';
import { DistrictService } from './district/district.service';
import { OnboardedBatchDetailsService } from './onboarded-batch-details/onboarded-batch-details.service';
import users from './models/user.entity';
import offices from './models/offices';
import organizations from './models/organizations';
import user_attendance from './models/user_attendance';
import batch from './models/batch';
import district from './models/district';
import { onboarded_batch_details } from './models/onboarded_batch_details';
import { SendBatchDataEmailJobService } from './scheduler/send-batch-data-email-job.service';

@Module({
    imports: [
        ConfigModule.forRoot({ isGlobal: true }),
        ScheduleModule.forRoot(),
        UsersModule,
        AttendanceModule,
        DatabaseModule,
        SchedulerModule,
        ReportsModule,
        OfficeModule,
        OrganizationModule,
        UserBatchModule,
        BatchModule,
        OnboardingModule,
        SchemesModule,
        UserOfficeModule,
    ],
    controllers: [AppController],
    providers: [
        AppService,
        UsersService,
        { provide: USERS, useValue: users},
        OfficeService,
        { provide: OFFICES, useValue: offices },
        OrganizationService,
        { provide: ORGANIZATIONS, useValue: organizations },
        AttendanceService,
        { provide: USER_ATTENDANCE, useValue: user_attendance },
        UsersService,
        { provide: USER_BATCH, useValue: USER_BATCH },
        BatchService,
        { provide: BATCH, useValue: batch },
        DistrictService,
        { provide: DISTRICTS, useValue: district },
        OnboardedBatchDetailsService,
        { provide: ONBOARDED_BATCH_DETAILS, useValue: onboarded_batch_details },
        DailyAttendanceTasksService,
        UtilsService,
        MailgunService,
        DistrictService,
        OnboardedBatchDetailsService
    ],
})
export class AppModule { }

Above code works in localhost in both my local envoronment and server. If you try sending a curl post request locally on server, it returns response but for any other requests, it just doesn't respond at all. I tried to increase nestjs timeout using this but it had no effect. I am searching solution for this issue since 2 days but not able to find. Any help is really appreciated. Thank you.
Edit
Above code runs normally on AWS EC2 instance and returns response.
Comment: Show your AppModule please
Answer: Reading the problem statement it looks like Azure is interrupting the connection for bigger payload and lengthy request.
tuning MTU (maximum transmission unit) and LSO (large send offload) parameters of azure VM can help circumvent this issue temporarily but at the end design needs to be fixed.
Answer: I resolved the issue by increasing the default timeout of the VM. Settings required to change or increase the timeout can be accessed via Azure Powershell. Sadly, this setting is not available in Azure portal. I used Azure powershell version 7.2 and the commands to change timeout is as follows:

$publicIP = Get-AzPublicIpAddress -Name '<name_of_the_ip_address_associated_with_your_VM>'
$publicIP.IdleTimeoutInMinutes = "<your_time_in_mins>"
Set-AzPublicIpAddress -PublicIpAddress $publicIP

** Kindly check for correct syntax of the commands, as different versions of powershell have different syntax.

Nestjs server doesn't respond


Prove that $17$ divides $xy-12x+15y$

Question:

if $x,y$ are integers and $17$ divides both the expression $x^2-2xy+y^2-5x+7y$ and $x^2-3xy+2y^2+x-y$, then prove that $17$ divides $xy-12x+15y$

My attempt:
I tried to factories both expression and the result obtained is as followed
$x^2-2xy+y^2-5x+7y=(x-y)(x-y+5)+2y.....(1)$
$x^2-3xy+2y^2+x-y=(x-y)(x-2y+1) ...... (2)$
From second expression I concluded that $17$ either divides $(x-y)$ or $(x-2y-1)$
Case 1: Let $17$ divides $(x-y)$ then from equation $(1)$ i concluded that $17$ divides $2y$ and hence $17$ divides $x$ so the $17$ divides  $(xy-12x+15y)$
Is my argument correct that $17$ will divide $2y$?
Also what if $17$ does not divides $(x-y)$ instead it divides $(x-2y-1)$?
I want solution without using modulo arithmetic for, what if $17$ does not divides $(x-y)$ instead it divides $(x-2y-1)$.
Any other proof will also help which does not involve modulo arithmetic.
Comment: no , i don't know anything about that
Comment: @IshraaqParvez How will you do induction on integers, as opposed to induction on natural numbers?
Comment: @DonAntonio OK, I'll take back my original comment.
Comment: CRMO 2005, right? There are solutions online, why not just google it?
Answer: Note: I'm going to introduce some integer variables like $k,n ,m $ etc. They are only for the purpose of showing the remainder of a number  when divided by a particular number. For example if I say $x=17k+3 $ then what you need to focus on is the $3$ ( remainder) and not $k$ ( I'm stating this explicitly because at some places I've written $3(17k+3)=17k+9$ , which actually isn't correct but the $k$ is only introduced to show divisibility). Actually this is the idea behind using modular arithmetic as well.

Yes, your argument that $17$ divides $ 2y$ if it divides $x-y$ is correct. From there you deduced that $17$ divides $y $ and hence also $x$ and therefore your case $1$ is correct.

case 2: $17$ divides $x-2y+1$
Write the first equation as
$x^2-2xy+y^2-5x+7y=(x-2y+1)(x-6)+y^2-5y+6$.
Since $17$ divides $x-2y+1$, it divides $y^2-5y+6$.
$y^2-5y+6=(y-2)(y-3) \implies 17$ divides atleast one of $y-2$ and $y-3$. That means $y=17k+2$ or $y= 17k+3$.
Since $17$ divides $ x-2y+1$, it is equal to $17n$.
Sub case 1: $y=17k+2$
$\implies x-17k-4+1=17n \implies x= 17k+3$
Now we can see that $xy-12x+15y= 17k+6-36+30=17k$, therefore $17$ divides it.
Sub case 2: $y=17k+3$
$\implies x-17k-6+1=17n\implies x=17k+5$
And again $xy-12x+15y=17k+15-60+45=17k$, hence $17$ divides it.

Prove that $17$ divides $xy-12x+15y$


String equality using replace and substring methods

Question: I have some questions about string comparison.I couln't find any answers concerning replace and substring methods in particular.So here is the code
public static void main(String args[]) {
    if ("hello".substring(0) == "hello")
        System.out.println("statement 1 is true");
    if ("hello".substring(1) == "ello")
        System.out.println("statement 2 is true");
    if ("hello".replace('l', 'l') == "hello")
        System.out.println("statement 3 is true");
    if ("hello".replace('h', 'H') == "Hello")
        System.out.println("statement 4 is true");
    if ("hello".replace('h', 'H') == "hello".replace('h', 'H'))
        System.out.println("statement 5 is true");
}

The output is:
statement 1 is true
statement 3 is true

Does the substring method create a new String().If so why is statement one true,yet 2 is not?Same question goes about statement 3 and 4.Thank you.
Comment: possible duplicate of [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java)
Comment: Never use `==` when comparing string equality!
Comment: Yes,i am aware i should use equals,but i have to understand it.Also,i did not find my answer on  http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java
Answer: If you compare strings with .equals() (to test value equality) rather than == (which tests referential equality), your program will output different results.
Answer: You should not be comparing strings like that in java. == is comparing the string references instead of the strings itself. Use .equals() method already defined for quality comparison of strings.
str1.equals("Hello");

Comment: In java, String is immutable, so methods like replace, substring always create a new String object
Comment: Why is statement 1 true if so?
Comment: That is probably due to compiler optimizations, the compiler sees that statement 1 and 3 are essentially not doing anything to the string and thus returns the same  string as result.
Answer: I assume you are aware of how string comparison works. So i'll try to explain what is happening.
Strings in java are immutable objects, so once created you can't change them.
To reduce overhead in creating the "same" string object over and over again, there is a pool of already used/created strings.
Now when you now compare if two string objects are the same it compares whether the objects themselves are the same. if you do "hello".substr(0) it will "create" a string object with "hello" in it. Since "hello" was already used, the string object containing "hello" is already in the string object pool. And if you now again "create" the string object "hello" to compare with, it will return the same object from the pool.
The same is happening with the "hello".replace("l","l") it will return the same "hello" string object like above.
But you can not rely on that, because the string-pool can get emptied at any time.
Further reading for "internalling strings" http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#intern()
BUT, if your question is about how to compare string themselves not the objects containing you strings, you should really use "hello".equals("hello") because then it will compare the real content. (As mentioned above)
Answer: The substring() method (which was changed in Java 7), will always return a new object. The only exception to this is if it is to return the whole string (substring(0)). Then, it will return it from the pool and the equality expression (==) will evaluate to true. This is the reason why statement 1 is true, but statement 2 false.
An example.


Servidor de autenticação separado da aplicação

Question: Tenho um cliente que vai desenvolver duas aplicações de sua empresa, ou seja, dois serviços oferecidos por sua empresa, e planos para outros projetos, e versões mobile dos mesmos.
Pois bem, por questões de modularização do projeto e facilidade de desenvolvimento de futuras aplicações, abstraimos todo o processo de autenticação das aplicações para um serviço único de autenticação/login.
Como fazer que toda a interação do usuário com sua conta, login, logout, atualização de dados, se dê em um único local, em um servidor e banco de dados à parte, deixando o servidor de cada aplicação livre e ocupado apenas com o que realmente lhe interessa?
A arquitetura que iremos utilizar é compartilhar um servidor de memcached como session handler das aplicações e do servidor de autenticação, os servidores estarão na mesma VPC na AWS
Comment: Oi, Thiago, bem vindo ao [pt.so]. Editei sua pergunta para tirar coisas não relacionadas com o problema em foco. A pergunta já tem 1 voto para fechamento, vale a pena conferir a [help/on-topic] e o guia [ask] para esclarecer o problema um pouco mais.
Comment: O ambiente é Windows? Se for, utilizem AD e pronto, não precisam mais se preocupar com isso.
Comment: Você pode dar uma olha no [OpenId](http://pt.wikipedia.org/wiki/OpenID). Mas qual tecnologia você vai utilizar? Qual framework? Talvez eu possa ajudar mais.
Comment: Eu acho que, hoje em dia, esse tipo de autenticação nem se faz mais. Todo mundo loga com Google OAuth, Facebutts, OpenID...
Comment: Ambiente Linux, PHP e Zend Framework 2. Mesmo com Login Social você precisa processar em algum momento. O Login social é apenas uma facilidade ao usuário, mas terás de programar igual.
Comment: Mais simples que compartilhar um memcached de sessão?
Answer: Uma das maneiras de simplificar é o seu servidor de aplicação usar algo parecido com o seguinte fluxo:

A aplicação gera um hash e direciona o usuário para o servidor de login com esse parâmetro e mais um token se identificando;
o servidor de login solicita e verifica as credenciais do usuário;
caso o usuário cancele ou as credenciais não se confirmem após N vezes, o servidor de login devolve o usuário para a aplicação, sem confirmar o login, OU
ao confirmar as credenciais, o servidor de login redireciona o usuário de volta para a aplicação, com o ID do usuário e um hash assinado por um valor comum armazenado pelas partes envolvidas.

Dá pra se fazer isto de uma maneira relativamente simples, sem se preocupar com OAuth e outros protocolos mal documentados e complexos demais para a necessidade específica.
Vantagens desta solução:

Portátil - cada parte da aplicação pode ser dividida em diversas máquinas diferentes;
pouco código necessário;
funciona pra uma, duas ou duzentas aplicações, quantas forem necessárias;
escalável, pois não depende de onde cada parte do sistema está rodando;
simples de gerenciar, pois a única informação compartilhada entre as partes é o usuário autenticado, pelo retorno de um ID e assinatura válidos.

Considerações importantes
Este é um esboço geral, que faz sentido num ambiente não sujeito a ataques externos, ou a informações extremamente visadas (não que a solução não seja boa, mas ela só é tão boa quanto o seu cuidado de planejar os detalhes). Você é que tem que avaliar o grau de segurança necessário para a sua aplicação e decidir se vai simplificar ou utilizar alguma solução robusta. O difícil é separar as soluções robustas com motivo das apenas complicadas.
A explicação foi bem simplificada, apenas para dar uma visão geral. Cada etapa tem que ser devidamente cuidada, e você deve usar uma conexão segura e ter um token separado para cada aplicação cliente. Se a conexão não for segura, é necessário um passo a mais para obter um "contra token" do servidor.
Comment: @mgibsonbr boa parte é complexa com motivo, mas outras partes são mal-feitas e mal documentadas. OAuth 2.0 por exemplo é complexo para uso em qq coisa. Inclusive eu uso para fazer Single Sign On com contas do google onde minha aplicação é o controlador das credenciais. Eu que tive que fazer malabarismos, isso sim, para contornar lacunas do protocolo (e não é falta de conhecimento, são problemas conhecidos por "academicismo excessivo", diferente de coisa que tem razão técnica de ser). Para não ficar o chat aqui, depois deleto este comment, e detalho melhor quando surgir ocasião mais oportuna.
Comment: Certo. E sempre que eu precisar confirmar as credenciais, sempre o mesmo processo né? E a sessão fica á cargo de cada aplicação?
Comment: A idéia é essa, isolar completamente os processos. Assim, você tem a vantagem da centralização do login, mas evita efeitos colaterais. Depois é claro que você pode incrementar o sistema, mas a vantagem é que fica tudo isolado. Mais interessante ainda é que se a pessoa salvar as credenciais na aplicação de login, ou se já tiver logado uma vez, quem vai cuidar disso é a a sessão do sistema de login apenas. Na hora que a segunda aplicação chamar, o redirecionamento já vai e volta de maneira transparente para o usuário.
Comment: Certo. E fica mais fácil de escalar, principalmente o memcached.
Comment: Como é feito esse redirecionamento de volta pra aplicação? Em outras palavras, ao fazer o redirect do servidor de login pro servidor da aplicação, onde armazenar o hash? Na própria URL? Minha preocupação é como manter esse hash seguro contra *replay attacks* ou similares (embora pensando aqui, imagino que isso pode ser mitigado usando um hash de curta validade...).
Comment: @mgibsonbr não é curta duração, é uso único. A aplicação cliente redireciona o user para autenticador/?hash=11dj1F31a268, por exemplo. O autenticador ao fazer um login com sucesso redireciona o user para cliente/?hash=hhDabG76GD&outrosparametros=outrosdados (que é o hash "assinado" por um secret que não é transitado pela web). Nesses outros dados, vc poe o que quiser (o user ID ou  outros dados pertinentes, que podem ser "hasheados" com o secret das 2 partes se desejar).
Comment: Eu peguei a ideia geral e achei muito interessante, mas ainda estou quebrando a cabeça pra entender como se implementa isso. Tipo, se é uso único então é preciso um meio de invalidá-lo, não? Da mesma forma, e se por alguma razão o hash assinado não for usado imediatamente? Digamos que o browser travou nesse momento e o usuário desistiu, e outro tomou o lugar dele (meu cenário é o lab. de informática de uma escola). Se o token ainda estiver lá, no histórico do navegador (possível, já que ele consta na URL) o próximo usuário pode abrir o browser e se encontrar autenticado como o primeiro...
Comment: De todo modo, eu não espero que você responda a isso, pois se formos entrar em todos esses detalhes a resposta ficará por demais extensa... O importante é que a ideia geral é boa, e com alguns cuidados pontuais pode ser uma solução excelente. Eu só discordo quando você fala em "protocolos (...) complexos demais para a necessidade específica", pois segurança **é** uma coisa complexa, e se esses protocolos fazem "malabarismos" que pra nós podem parecer estranhos, provavelmente é porque existe uma boa razão pros mesmos existirem! ;)
Answer: Considere utilizar o CAS Central Authentication Service
Basicamente, o CAS é uma aplicação em Java para a qual você delega o serviço de autenticação. Ela se integra, por exemplo, com o Active Directory, permitindo, assim, que o usuário utilize a mesma senha do AD para as aplicações WEB (algo interessante no caso de aplicações corporativas).
Utilizo o CAS com sucesso em uma aplicação desenvolvida em Grails (framework  Java web, baseado em Spring, Hibernate, etc).
O CAS roda em um servidor distinto das aplicações. Assim, qualquer aplicação que necessite de autenticação, nós delegamos a mesma para essa instância do CAS.
Você pode configurar para a autenticação acontecer com um banco de dados, via JDBC.
O CAS é nome do protocolo cujo a aplicação tem o mesmo nome. Ele é single sign-on, o que significa que após ter feito o logon em uma aplicação, as outras que forem abertas dentro da mesma sessão do browser compartilharão suas credenciais, não solicitando novamente usuário e senha.
Veja na página do CAS que existem clientes em Java, PHP, .NET, etc.


How to handle post data of size more than 2 mb

Question: I have json post data with below template
<code> {

    "themeId" : JSONString,
    "themeName" : JSONString,
    "tables" : [{
        "tableName" : JSONString,
        "records" : [{
            "recordVersion" : JSONString,
            "tableItems" : []
        }]
    }]

}
</code>
and on Java side I have REST API like this:
<code>@POST
@Path("/{themeId}")
@Consumes({MediaType.APPLICATION_JSON})
public Response postTheme( @PathParam("themeId") String themeId, ThemeDictionary dictionary) throws InterruptedException {
    //code to handle
}
</code>
It worked fine when post data is less than 2 MB but how to handle data size bigger than 2 MB.
Questions
1) Should I go with pagination.
2) If I split json into half then each half won't be valid json. So, should I accept strings and concatnate on server side?
3) Are there any good examples to handle this scenario
4) Looking for an approach that can handle json data of size less than or greater than 2 MB
Comment: Go for a less monolithic data exchange, post smaller items, every record or so. Even with compression (header `Accept-Encoding: gzip`), that 50 MB (compressed maybe ~1 MB) is too large.
Comment: To be honest it's just a suggestion which might optimize the size a bit. With a 50MB total payload you might still need some form of pagination anyway.
Comment: Need to define some threshold value and after reaching that just post your data to server.With this you can minimize number of server calls in pagination approach.
Comment: Have you tried with [bson](http://bsonspec.org/)?
Comment: I haven't tried but the total post data size will be like 50 MB.. Isn't there a limit to Bson?
Comment: are you trying to upload a file
Comment: No, it is not a file.
Answer: Pagination will not solve you problem since you are sending data to the server, and not receiving.
What servlet container do you use? It looks like default tomcat POST limit size.
If you are using standalone tomcat you need to set parameter
maxPostSize for your Connector: see here or  (here)
Comment: I am using websphere.
Comment: Which version do you use? Can you try to configure it like described here: http://serverfault.com/q/311610 ?
Comment: wlp-javaee7-18.104.22.168
Comment: Pagination not only applied on sending data from server, but also receiving data. Pagination means paging data sending from one side to another.
Comment: javaMan, if there are settings as described here: http://www.ibm.com/support/knowledgecenter/SS7JFU_7.0.0/com.ibm.websphere.express.doc/info/exp/ae/urun_chain_typehttp.html

Original post here: http://stackoverflow.com/a/16593022/2003797
Answer: 2MB is rather small and I think the approach to upload the json file as multipart, then normally process the json file can handle the up to 50MB sized file. An example of handling file uploading can be found here.
For json files that is more than hundred of MBs, we have to find some way to process in streaming, or split the file into smaller files.
Answer: Pagination will be the good option but it will need manual intervention.
Instead of that you can sent multiple Async request to fetch data (ie., fetch 1-200 records in one request and next request will fetch 200-400) like that but it is not recommended way since your server will get more request based on the number of records.
Answer: Json files are great for compression. You should think about it.
Yes you should go with pagination. But there will be some cons of it. Such as consistency.
You should send them by not dividing into strings. I suggest you to send meaningful data. So pagination will be meaningful. If the one of the parts (blocks) of the message is missing, you should only re-send that part. Not the all parts.
"how can you eat a really big fish? - by slicing thin".
Try to post smaller & meaningful parts. Otherwise your servers will need more computing time to process data, your clients need more memory to process.
Answer: Is there any reason why you are not sending the data in one single request? Send the 50MB as one request. There is no limit on the size of data in JSON or HTTP post specification as discussed in the below SO questions
Is there a limit on how much JSON can hold?
Is Http POST limitless?
If you are worried about the performance of your server. One possible option is to split your json logically so that the action can be performed in smaller chunks.
For eg Consider your tables array has 200 items in it you can consider splitting the tables array into smaller chunks maybe say 50 /20 per requests.
<code>{

    "totalPages":2,
    "themeId" : JSONString,
    "themeName" : JSONString,
    "tables" : [{
        //first 50 tables
        "tableName" : JSONString,
        "records" : [{
            "recordVersion" : JSONString,
            "tableItems" : []
        }]
    }]

}
</code>
Next request
<code>{
    "totalPages":2,
    "themeId" : JSONString,
    "themeName" : JSONString,
    "tables" : [{
        //next 50 tables
        "tableName" : JSONString,
        "records" : [{
            "recordVersion" : JSONString,
            "tableItems" : []
        }]
    }]

}
</code>
If you do not need the complete data for the processing the request, you can perform the action on the data as it arrives. If not, add the tables array to some db/file/memory till the last page is received, and for the last request merge the json back together and process the request and send back the proper response. If its the second case there is not much performance improvement.


Restoration of a complex function

Question: I want to find complex function $f(z)$, such that
$$
|f(z)|=e^x(x^2+y^2).
$$
I may guess that $ f(z) = z^2 e^{z+i \alpha}, \text{Im}\, \alpha = 0 $. But how to prove that there is no other functions?
Answer: You have
$$
\lvert f(z) \rvert  = e^x (x^2 + y^2) = \lvert e^z z^2 \rvert
$$
If you are looking for holomorphic solutions (in some domain) then it follows that
$$
 \frac{f(z)}{e^z z^2}
$$
is holomorphic with constant modulus. The maximum modulus principle (or open mapping theorem) implies that the quotient is constant, so that
$$
 f(z) = c e^z z^2
$$
for some complex number $c$ with $\lvert c \rvert = 1$.
Answer: You can consider for instance $f(z) = \vert z \vert^2 e^z$, or even $f(z) = e^{\Re x}(\Re z^2 + \Im z^2)$.
Comment: You mean, that there may be lots of functions?
Comment: Sure. You just require something on the modulus of the function, so if $f$ is such a function, the function $fg$ for any function $g$ such that $\vert g \vert = 1$ will work ! It might be another story if you require more regularity, for instance if $f$ must be an entire function.
Comment: Yes, I see. There I forgot to say that $f$ is analytic function. Does that change anything?
Comment: Yes because you can show that if two functions $f$ and $g$ are entier such that $\vert f \vert = \vert g\vert$ then $f=\alpha g$ for some $\omega  \in \mathbb C$ such that $\vert \omega  \vert = 1$. To see that, one has $\vert f/g\vert =1$ so $f/g$ is bounded thus by Liouville theorem ($f/g$ is holomorphic because the singularities are removable) it is constant: $f/g=\omega $ and the condition $\vert f/g\vert =1$ implies $\vert \omega  \vert = 1$. It is your condition with $\omega = e^{i \alpha}$.

Restoration of a complex function


Windows Server 2016 not Seeing VM on Azure

Question: I have windows Server 2016, and a Windows 10 Workstation on azure, I'm trying to map a drive from the workstation to Windows Server 2016 or vice versus.
Problem:  Windows Server 2016, is not seeing vm1 on Domain Network even though it is on
Domain and is able to ping.
Screenshots of IPCONFIG/all of each computer, Pinging,
network connections
DOMAIN CONTROLER, IPADDRESS 10.0.0.4
VM, IPADDRESS 10.0.0.6
Domain Controller ScreenShot
VM ScreenShot
Pinging DC
Network Connection to Domain
Screenshot Server1/Network Connections
What I've already done
Network Discovery Turned On
DNS client in Services   ON
Function Discovery       ON
I've take down the Firewall on both Server 2016 and the VM.
On the VM side i'm running.
Windows 10
Version 1803 (OS Build 17134.1006)
On the Server Side I'm running
Windows Server 2016
Version 1607
(OS Build 14393.3204)
Answer: You don't need the machines to "see" each other to map a drive. If you have a shared folder on either machine then map it from the other machine with the net use command:
<code>net use X: \\computername\sharename /persistent:yes
</code>
Comment: Okay that makes sense, I'll try that it a minute.  For instance though what would my solution be if I wanted the computers to see each other in the Network drop-down menu in the File Explorer.


Should I practice some J.S. Bach for piano technique and where should I start?

Question: I want to know if playing J.S. Bach would improve my overall piano technique. I look for pieces that help me to become better. I usually play romantic composers. I have played pieces such as

Chopin's "Nocturne op.9 No.2"
Chopin's "Waltz No.14 in E minor posthm."
Schubert's "Moments musicaux nr. 3"
Mendelssohn's "Songs without words op. 30 nr 1".

The most difficult pieces I attempted was "Fantaisie-Impromptu" and "Etude Op. 25. Nr 2." which I can play unfortunately only badly.
So I wonder if playing some "2/3-part Inventions" or the "WTC" would actually also improve my overall playing, or would I just become better at counterpoint music? I played 2 Bach pieces so far, they were the Kempff transcriptions of "BWV 1031 Siciliano" and "BWV 639 Ich ruf zu dir...."
And if I should play some Bach, should I do the "Inventions" or should I jump directly into the" WTC"? I usually play romantic pieces around Henle levels 4-6. But level 6 is still quite difficult for me.
I do enjoy some Bach, but I enjoy Schubert for instance a little bit more. So my main motivation is piano technique.
Answer:
So I wonder if playing some "2/3-part Inventions" or the "WTC" would actually also improve my overall playing

I say YES! I don't know exactly what you call "counterpoint music". Is it "music that has counterpoint" or "music composed entirely based on counterpoint" (like a lot (not all) of Bach's) ?? Because it will indeed improve not only you counterpoint, that is useful to a lot of pieces, but also independence of the hands in general, which piano is all about, right?
Take for example Schumann's Träumerei. It's romantic, but it's an amalgam of voices and phrases and counterpoints. Is it "counterpoint music"? I don't know, but if you are great at WTC fugues it will be so much easier. Of course it's a completely different style, but since you are familiar with Romantic,  it should be easier for you to transpose your skills, the counterpoint (an important matter in this case) would be a technical barrier you won't have anymore.
Talking about "non-counterpoint music", as I said, independence of the hands is always useful for piano. Even melody + accompaniment becomes easier, and also almost every piece has a little counterpoint here and there.

And if I should play some Bach, should I do the "Inventions" or should I jump directly into the" WTC"?

This one seems easy. Start with the Inventions, when you're doing well, or if you feel like you're not being challenged, jump to WTC. You're not in a hurry, are you? Also, I think it's a good idea to start slow. WTC has 3, 4 and even 5 voice fugues. How can you play that if you didn't even try 2 voice Inventions?
Comment: @Matriz Good point, I could have talked about that! It's indeed a lot harder to remember: there is almost no repetition, lot's of notes and almost no chords. It's like memorizing several complex melodies and playing them all at the same time. But this is another good thing, because you get better at memorizing too! I don't know about predictability, I think it depends on what you are more used to. I just heard this Schubert's you mentioned, and I think it's easier to remember because the left hand is mostly harmony, and there are some repetitions too.
Comment: @Matriz As for learning, I am no expert, but I think it's good to learn them separately. At least for me, in WTC it's impossible to learn all voices together, so one tip that a teacher of my gave me, was to learn each voice separately, then playing 2 at a time, then 3, etc... So in a 3 voice fugue, for example, you would learn: voice 1; voice 2; voice 3; voices 1 + 2; voices 2 + 3; voices 1 + 3; then finally 1 + 2 + 3 (and it will still be hard!)
Comment: Thank you a lot for your comment. The reason why I eventually asked was not only because I am more into Romantic composers but also because I think Bach is sometimes hard to remember and unpredictable. When I listen to the "Inventions", they sound harmonic but still very "random" for me. So I imagine learning the fugues of the WTC would be so hard. I have no problem in remembering for instance Schubert's "Impromptu Op. 90 No. 2" which has a lot of notes, but it seems more predictable. Any tips on that? Should I learn the 2 voices first separately or can I learn them at the same time?
Answer: wtc and inventions are both very useful. it always depends what will be your goal. if you want to profit by studying or if your purpose is to perform this music in front of a public. I always make music for me and my pleasure - this doesn't mean that I don't imagine myself playing for  friends or a big audience.
you have to look at the difficulty:
as I already mentioned  in another post of this SE site the prelude in C of the wtc will be easier to achieve than the inventions. there are also some very easy pieces in the little preludes.
when I started playing piano I was at first confronted with the inventions in C, am, dm, gm, F, Bb. this doesn't say it would be good for all the same (actually I don't believe that it was perfect for me)
If you like to play them slow also the preludes in dm and in D will benefit a lot and spend you great joy.
as the sheet music of Bach is all available for free you should look for it.
Comment: Well I am no beginner and I already played some Bach pieces (as I mentioned the Kempff transcriptions). And of course I already looked into the WTC and Inventions and listened to them. But my point is, would Bach also improve my overall piano playing for non counterpoint pieces? (romantic pieces) Or should I just play Mendelssohn, Schubert and Chopin? I know that Liszt and Chopin were great fans of the WTC, I think Chopin took the book with him when he traveled. For me Bach's music seems very hard to remember. Much more difficult than romantic pieces. "Dankä für dä Bihtrag!"
Comment: I will still carry on to play other preludes of the wtc. "So my main motivation is piano technique."
my aim is not improve my piano technique - da komme ich nie auf einen grünen zweig! I have the pleasure to analyze and enjoy the music just playing in a slow tempo. eventhough I've read today here in somewhere: music has not been written for analyzing but for playing.
Answer: It is good and very valuable to expose yourself to a multitude of styles, composers and eras. However, if it is technique you are after, technique is all in your head.  It is the knowledge of proper movement and what movements not to do.
For instance, if every time you bend over to pick up a piece of paper off the floor you throw your back out, bending over more won't fix your back.  It needs no more strengthening.  The solution is to pick things up by bending from the knees. Ergonomics.
If crossing the thumb under the palm causes ulnar or radial deviation of the wrist and corrupts your speed, then use the arm and elbow to place the thumb instead of flexing it and tying up your extensors.
If trilling causes your fingers to cramp, quit trying to play from the finger muscles (which don't exist) and play from the pronator and supinator.
If your hands feel sore after an hour of playing, go with gravity instead of trying to manhandle it. Gravity just is, you can't strengthen it.  Like petting a cat, pressing harder doesn't increase the enjoyment for the cat.
So if you have technical difficulties or mountains you can't ascent, if you get cramps, fatigue, pain, you don't need more technique or more practice, you need proper movement.  Something is either wrong or getting in the way.
Your teacher should be addressing the laws of physics in your lessons.  If not, they probably don't know and it might be time to graduate to a new teacher.
Comment: So you are essentially saying playing Bach would also improve my playing for romantic composers?


How to find the period of a combined trigonometry function, such as $y=\cos(2x) + \sin(5x)$?

Question: May I know how to find the period of function such as this?
$$y=\cos(2x) + \sin(5x)$$
Is it true that we just need to find the lowest common multiple of both functions' period, so that we could find the period of this function? If it is, why is that so? What's the mechanism behind this?
Thank you so much for you guys' replies.
Comment: You could first notice that if a function has (minimum) period $T_0$, then it also has period $nT_0$, with $n \in Bbb N$...
Answer: We know that if $y(x+T)=y(x)$ for some $T\in R^{+}$ then $y(x)$ is periodic with one of its period as $T$.
$$ $$
Period of $Cos(2x)$ is $T_1=\frac{2π}{2}=π$ and that of $Sin(5x)$ is $T_2=\frac{2π}{5}$
$$. $$
Hence $T=LCM(T_1,T_2)=LCM(π,\frac{2π}{5})$
$$=2π$$
Comment: Thank you very much, sir.
Answer: Suppose that the function $y$ reaches its initial phase at the point $x=x_1$. Now, for the function $y$ to reach the initial phase, both $\cos(2x)$ and $\sin(5x)$ both must be, individually, at their initial phases as well.
Thus, $x_1$ is the smallest number, at which both the functions $\cos(2x)$ and $\sin(5x)$ have completed integer number of periods. Now it's easy to see that $x_1$ must be the $\text{lcm}$ of those individual periods, that is, the point where both $\sin$ and $\cos$ have returned to their initial phases.
For your case, the period of $\cos(2x)$ is $\pi$ and of $\sin(5x)$ is $2\pi /5$. The $\text{lcm}$ is $2\pi$, which is the period of $y$.
Comment: Thank you very much, may I know whether it is true for other functions that have are periodic? such tan(x)
Comment: You're welcome. Yes, you can use the same procedure for them. But keep in mind that the period of $\tan(Ax)=\dfrac{\pi}{A} $ for $A>0$.
Comment: @HenryCai be careful when generalizing. Take e.g. $\sin^2 x$ and $\cos^2 x$ that individually have period $\pi$...
Comment: @dfnu sure, thank you very much, so sir, you indicate that the period might not solely dependent on the coefficient of the x inside the trig function, right?
Comment: @HenryCai not only that. But also that the sum might not have *minimum* period given by the l.c.m. of the original periods. In my example the sum is in fact a constant.
Comment: @dfnu Thank you for your sharing, that really surprises me.


Algebra question, Cardano's method

Question: We have the following information:
$$a^3 + b^3 = -q $$
$$a^3b^3 = -\dfrac{p^3}{27}$$
Apparently this yields the equation $z^2 + qz -\dfrac{p^3}{27}$ of which $a^3$ and $b^3$ are the roots.
Can someone explain this to me? I don't understand why this is the case.
Comment: If two numbers $a$ and $b$ sum to $s$ and their product is $p$, then they are the roots of the quadratic equation $z^2-sz+p=0$, because it factors as $(z-a)(z-b)=0$.
Answer: Suppose that you have the equations $u+v=S$, $uv=P$. First note that the roots of the equation
$(X-u)(X-v)=0$ are $u$ and $v$. But
$$(X-u)(X-v)=X^2-(u+v)X+uv=X^2-SX+P$$
That is, if you know that the sum of a pair of numbers is $S$ and their product is $P$, you can state that the roots of the equation $X^2-SX+P=0$ are precisely these numbers.
Now, let $u=a^3$, $v=b^3$, $S=-q$, $P=-\frac{p^3}{27}$.

Algebra question, Cardano's method


How do I interpret the 'correlations of fixed effects' in my glmer output?

Question: I have the following output:
Generalized linear mixed model fit by the Laplace approximation
Formula: aph.remain ~ sMFS2 +sAG2 +sSHDI2 +sbare +season +crop +(1|landscape)

 AIC   BIC    logLik deviance
 4062  4093  -2022   4044

Random effects:
Groups    Name        Variance Std.Dev.
landscape (Intercept) 0.82453  0.90804
Number of obs: 239, groups: landscape, 45

Fixed effects:
            Estimate Std. Error z value Pr(>|z|)
(Intercept)  2.65120    0.14051  18.868   <2e-16
sMFS2        0.26922    0.17594   1.530   0.1260
sAG2         0.09268    0.14529   0.638   0.5235
sSHDI2       0.28345    0.17177   1.650   0.0989
sbare        0.41388    0.02976  13.907   <2e-16
seasonlate  -0.50165    0.02729 -18.384   <2e-16
cropforage   0.79000    0.06724  11.748   <2e-16
cropsoy      0.76507    0.04920  15.551   <2e-16

Correlation of Fixed Effects:
           (Intr) sMFS2  sAG2   sSHDI2 sbare  sesnlt crpfrg
sMFS2      -0.016
sAG2        0.006 -0.342
sSHDI2     -0.025  0.588 -0.169
sbare      -0.113 -0.002  0.010  0.004
seasonlate -0.034  0.005 -0.004  0.001 -0.283
cropforage -0.161 -0.005  0.012 -0.004  0.791 -0.231
cropsoy    -0.175 -0.022  0.013  0.013  0.404 -0.164  0.557

All of my continuous variables (denoted by a small s before the variable name) are standardized (z-scores). season is a categorical variable with 2 levels (early and late), and crop is a categorical variable with 3 levels (corn, forage, and soy).
This correlation of fixed effects matrix is really confusing me, because all of the correlations have the opposite sign that they do when I look at the simple regressions of pairs of variables. i.e., the correlation of fixed effects matrix suggests a strong positive correlation between cropforage and sbare, when in fact there is a very strong NEGATIVE correlation between these variables - forage crops tended to have much less bare ground compared to corn and soy crops. Pairs of continuous variables have the same issue, the correlation of fixed effects matrix says everything is the opposite of what it should be ... Could this just be due to the complexity of the model (not being a simple regression)? Could it have something to do with the fact that the variables are standardized?
Thanks.
Answer: The "correlation of fixed effects" output doesn't have the intuitive meaning that most would ascribe to it.  Specifically, is not about the correlation of the variables (as OP notes). It is in fact about the expected correlation of the regression coefficients.  Although this may speak to multicollinearity it does not necessarily.  In this case it is telling you that if you did the experiment again and it so happened that the coefficient for cropforage got smaller, it is likely that so too will would the coeffienct of sbare.
In part his book "Analyzing Linguistic Data: A Practical Introduction to Statistics using R " dealing with lme4 Baayen suppresses that part of the output and declares it useful only in special cases.  Here is a listserv message where Bates himself describes how to interpret that part of the output:

It is an approximate correlation of the estimator of the fixed
  effects.  (I include the word "approximate" because I should but in
  this case the approximation is very good.)  I'm not sure how to
  explain it better than that.  Suppose that you took an MCMC sample
  from the parameters in the model, then you would expect the sample of
  the fixed-effects parameters to display a correlation structure like
  this matrix.
Comment: You know, I think you're echoing what I said correctly; but, on reflection I'm not 100pct sure I'm right. You may be best served by opening a new question - that'll get more eyes on your question and increase the likelihood of you receiving a correct answer.
Comment: I'm sorry, this will probably be a silly question, but then why is it important to consider that correlation? I mean, in which situations should that output be considered?
Comment: @Teresa It depends on what you are using it for. If you care about the interpretation, then it is telling you about how confusable two sources of effect are. If you care about prediction, it tells you a bit about what other prediction models might look like and gives you some hint as to how the model might change if you dropped a predictors.
Comment: Continued: if there are relatively high correlations you may fit a GLMM, and the way to check whether it (or, more precisely, its random effects) satisfactorily modelled the dependencies is by computing the correlation matrix of the fixed effect models and comparing it to the one from the GLM. When GLMM addresses the issue of dependencies (e.g., longitudinal data), you will see a dramatic decrease in the correlations.
Comment: So, imagine that I have two variables in that output with a correlation of 0.90, for instance. In terms of interpretation, I assume I should drop one of them, because they are "confusable" and seem to be telling the same information. As for prediction, if I drop one of them, other models shouldn't change that much, as they are correlated, am I right? Or am I interpreting this wrongly?
Comment: @russellpierce, thanks for this answer. One question though, I learned that multicollinearity occurs when _predictors_ correlate with each other. But in your answer you say that it is the correlation of the _regression coefficients_ (not of the predictors) that may speak to multicollinearity. Why not just correlating the predictors themselves instead of the estimated coefficients?
Comment: There seems to be a gap of references (knowledge?) as to why the correlations of fixed effect models appear in the summary and why they are useful: GLMMs arise as a generalisation of GLMs to model heterogeneity/overdispersion as a result of dependencies between predictors (think of, e.g., longitudinal data). In a first analysis of your data you may not spot out the latter and, following Occam's Razor, you may fit a GLM to start with. A way to diagnose whether there are dependencies is to compute the correlation matrix of the resulting coefficient estimates.
Comment: Given the general lack of references on this (worse off, some people in charge of code, see https://github.com/lme4/lme4/issues/300, want to remove the correlation matrix! I would say one should add the one from GLM...) and following @russellpierce's suggestion, it would be a good idea to create an entry for this.
Comment: Like I said above, I'd encourage a new question on these details. My uncertain claim above is that correlation of random effects may be related to multicollinearity, but that they are distinguishable properties. As to why this is the diagnostic info provided by lme4, we'd have to ask the authors
Comment: I suspect it is because these correlations are relevant to model specification. In particular one that comes up in nature a lot is a correlation between the intercept and a slope. Indicating the effect of the slope correlates with the effect of the intercept. There isn't a predictor to stand in for the intercept. So, for this example we can see that this view of the data isn't exactly the same as a question of collinearity of predictors.
Answer: It can be helpful to show that those correlations between fixed effects are obtained by converting the model's "vcov" to a correlation matrix. If fit is your fitted lme4 model, then
vc <- vcov(fit)

# diagonal matrix of standard deviations associated with vcov
S <- sqrt(diag(diag(vc), nrow(vc), nrow(vc)))

# convert vc to a correlation matrix
solve(S) %*% vc %*% solve(S)

and the correlations between fixed effects are the off-diagonal entries.
Answer: If your negative and positive correlations are the same in their value and only their sign differ, you are entering the variable mistakenly. But I don't think this is the case for you as you already seem quite advanced in stats.
The inconsistency you are experiencing can be and is likely caused by multicollinearity. It means when some independent variables share some overlapped effects, or in other words are correlated themselves. for example modeling to variables "growth rate" and "tumor size" can cause multicollinearity, as it is possible and likely that larger tumors have higher growth rates (before they are detected) per se. This can confuse the model. And if your model has few independent variables which are correlated with each other, interpreting the results can sometimes become quite difficult. It sometimes leads to totally strange coefficients, even to such extents that the sign of some of the correlations reverses.
You should first detect the sources of multicollinearity and deal with them and then rerun your analysis.
Comment: -1; misleading.  OP didn't enter his variables incorrectly and multicollinearity may not be an issue.  A correlation between the raw fixed effects might speak to this point, but Simpson's paradox may allow that approach to lead you in the wrong direction.
Comment: Why "misleading"? Which part was misleading? I talked very clearly and avoided inferring clear conclusions. What I said is indeed one of multicollinearity signs and tells us we should check VIFs too. But I don't understand how you know or are sure the "OP didn't enter his variables incorrectly and multicollinearity may not be an issue."?
Comment: Besides you haven't even read my post completely (and downvoted it and call it misleading). If you had, you had seen that I have suggested that the OP should check VIFs (as official indicators for multiC) to make sure whether those high correlations are really pointing to MC or not? but anyways, I am open to learning as long as it is free of arrogance and personal attacks.
Comment: @Vic:  Didn't see your comments until just now.  I didn't mean for you to view my response as a personal attack.  I was of the opinion it was misleading and I provided what I believe to be the correct answer above.  I read your post in its entirety at the time.  I do not know whether I dug into the comments or not. I stand by my downvote.
Comment: ... but I do allow that I may be mistaken in that judgement.  However, it seemed better to explain why I downvoted rather than to just downvote.
Comment: Thanks for responding Vic. When you say 'deal with' the sources of multicollinearity, what do you mean? Just, find out which predictors are highly correlated and choose one of them to keep in the model and toss the other?

Also, detecting the sources of multicollinearity should technically just be a matter of looking at the correlation of fixed effects matrix in the output, right? As far as I've read, that's what that part of the output is for. Though I still don't get why it is systematically telling me that the correlations are the opposite of what they are.
Comment: No you should treat them using some protocols. One is centering your variables which means subtracting them from their means. Another way is to find the sources of multicollinearity and exclude them from your model (and if they are really necessary, assess them in other models from which the paired (correlated) variables are dropped) etc.
Comment: For detecting them, there are some suggested methods. The most acceptable one is to calculate VIF. Variables with VIFs greater than 10 are very likely to be causing multicollinearity. Another way is to check the correlation matrix between your independent variables. Variables with at least 0.4 correlation with any other independent variable are likely sources of multicollinearity.
Comment: There is yet another possibility. Sometimes they might be really what they are showing. Sometimes it is "we" who should change our theory based on our new validated findings. But if the multicollinearity is the culprit, the reason why the variables have been reversed is that it is possible for a variable to obtain any value, which includes positive and negative values from case to case.
Comment: I will look into calculating VIF, thanks for that suggestion. I believe my variables are centered already as they are standardized (x-mean)/stdev. The correlation matrix between my independent variables is (I think) the very thing that my question/confusion was about - the matrix at the bottom of my output, 'Correlation of Fixed Effects'. The fixed effects are all my independent variables. (except the random effect, which is basically just a grouping factor). I don't doubt that multicollinearity may be an issue but I'm not sure I understand how it relates to my initial problem.
Comment: You are very welcome. If some of your correlations are above 0.4 then you are in trouble! No, I was kidding, it is treatable, but really annoys before being totally gotten rid of. I see you have even 0.7 or 0.5 correlations which indicate multicollinearity. Finding why multicollinearity causes a specific artifact effect in each case can be a real pain and its effect differs from case to case, depending the correlated variables, their effects and their correlation direction, etc.... So when I personally see multicollinearity, I never care about "why it caused this or that... I just accepted it!
Comment: Tracing it back is really really difficult or maybe impossible (practically) sometimes, when the model is large and complicated. But one thing is clear: it makes variable coefficients jump! But from what to what? and why? The latter is so impractical to answer.


Problemas na inserção em duas tabelas PHP MySQL

Question: Estou tentando fazer um INSERT em duas tabelas, primeiro preciso inserir as informações do veículo na tablea 'veiculo_cadastrado' e preciso inserir as imagens na tabela 'imagens_veiculo'. Está entrando no ELSE do primeiro INSERT, queria saber o que estou fazendo errado.
<?php
session_start();
require_once('conexao/conexao.php');

if(!empty($_POST['tipo_veiculo'])
    && !empty($_POST['fabricante'])
    && !empty($_POST['modelo'])
    && !empty($_POST['valor_veiculo'])
    && !empty($_POST['placa_veiculo'])
    && !empty($_POST['renavam_veiculo'])
    && !empty($_POST['nome_documento'])){

    $id                      = $_SESSION['id_user'];
    $estado                  = $_POST['estado_veiculo'];
    $tipo                    = $_POST['tipo_veiculo'];
    $fabricante              = $_POST['fabricante'];
    $modelo                  = $_POST['modelo'];
    $ano_fabricacao          = $_POST['ano_fabricacao'];
    $ano_modelo              = $_POST['ano_modelo'];
    $cor                     = $_POST['cor_veiculo'];
    $combustivel             = $_POST['combustivel_veiculo'];
    $portas                  = $_POST['portas_veiculo'];
    $cambio                  = $_POST['cambio_veiculo'];
    $kilometragem            = $_POST['kilometragem_veiculo'];
    $dono                    = $_POST['dono_veiculo'];
    $cidade                  = $_POST['cidade_veiculo'];
    $valor                   = $_POST['valor_veiculo'];
    $descricao               = $_POST['descricao'];
    $placa                   = $_POST['placa_veiculo'];
    $renavam                 = $_POST['renavam_veiculo'];
    $nome_documento          = $_POST['nome_documento'];
    $alienado                = $_POST['alienado_veiculo'];
    $certificado             = $_POST['certificado_veiculo'];
    $garantia                = $_POST['garantia_veiculo'];
    $ipva                    = $_POST['ipva_veiculo'];
    $licenciado              = $_POST['licenciado_veiculo'];
    $revisoes                = $_POST['revisoes_veiculo'];
    $revisoes_concessionaria = $_POST['revisoes_concessionaria'];

    //INFO IMAGEM
    $file       = $_FILES['img'];
    $numFile    = count(array_filter($file['name']));

    //PASTA
    $folder     = '../images/veiculos';

    //REQUISITOS
    $permite    = array('image/jpeg', 'image/png');
    $maxSize    = 1024 * 1024 * 10;

    //MENSAGENS
    $msg        = array();
    $errorMsg   = array(
        1 => 'O arquivo enviado excede o limite definido na diretiva upload_max_filesize do php.ini.',
        2 => 'O arquivo excede o limite definido em MAX_FILE_SIZE no formulário HTML.',
        3 => 'O upload do arquivo foi feito parcialmente.',
        4 => 'Nenhum arquivo foi enviado.',
        6 => 'Pasta temporária ausênte.',
        7 => 'Falha em escrever o arquivo em disco.',
        8 => 'Uma extensão do PHP interrompeu o upload do arquivo.'
    );

    $query = "INSERT INTO veiculo_cadastrado
                (id_user,
                estado_veiculo,
                tipo_cadastro,
                fabricante_veiculo,
                modelo_veiculo,
                ano_fabricacao,
                ano_modelo,
                cor_veiculo,
                combutivel_veiculo,
                portas_veiculo,
                cambio_veiculo,
                kilometragem_veiculo,
                dono_veiculo,
                cidade_veiculo,
                valor_veiculo,
                descricao_veiculo,
                placa_veiculo,
                renavam_veiculo,
                nome_documento,
                alienado_veiculo,
                certificado_veiculo,
                garantia_veiculo,
                ipva_veiculo,
                licenciado_veiculo,
                revisoes_veiculo,
                revisoes_concessionaria)
                VALUES
                ('{$id}',
                '{$estado}',
                '{$tipo}',
                '{$fabricante}',
                '{$modelo}',
                '{$ano_fabricacao}',
                '{$ano_modelo}',
                '{$cor}',
                '{$combustivel}',
                '{$portas}',
                '{$cambio}',
                '{$kilometragem}',
                '{$dono}',
                '{$cidade}',
                '{$valor}',
                '{$descricao}',
                '{$placa}',
                '{$renavam}',
                '{$nome_documento}',
                '{$alienado}',
                '{$certificado}',
                '{$garantia}',
                '{$ipva}',
                '{$licenciado}',
                '{$revisoes}',
                '{$revisoes_concessionaria}')";

    $insereVeiculo  = mysql_query($query, $con);

    if($insereVeiculo){
        $_SESSION['certo'] = "Inserido com sucesso";
        $last = mysql_insert_id();
    } else{
        $msg = "Ocorreu um erro";

    }

    if($numFile <= 0)
        $_SESSION['aviso'] = 'Selecione uma imagem!';
    else{
        for($i = 0; $i < $numFile; $i++){
            $name   = $file['name'][$i];
            $type   = $file['type'][$i];
            $size   = $file['size'][$i];
            $error  = $file['error'][$i];
            $tmp    = $file['tmp_name'][$i];

            $extensao = @end(explode('.', $name));
            $novoNome = rand().".$extensao";

            if($error != 0)
                $msg[] = "$name : ".$errorMsg[$error];
            else if(!in_array($type, $permite))
                $msg[] = "$name :  Erro imagem não suportada!";
            else if($size > $maxSize)
                $msg[] = "$name :  Imagem ultrapassa limite de 10MB";
            else{

                if(move_uploaded_file($tmp, $folder."/".$novoNome))
                    $msg[] = "$name :  Upload realizado com sucesso!";
                else{
                    $msg[] = "$name :  Desculpe ocorreu um erro!";
                }

            }

        $insert = "INSERT INTO imagens_veiculo
                    (id_veiculo,
                    imagem_veiculo)
                    VALUES
                    ('{$last}',
                    '{$novoNome}')";
        $exe_insert = mysql_query($insert, $con);

        }

    }

} else{
    $msg = "Preencha todos os campos";
}

echo $msg;

Formulario

<form method="post" action="php/insereVeiculo.php" enctype="multipart/form-data">

 Veículo

  <input type="radio" name="estado_veiculo" value="Novo">Novo
  <input type="radio" name="estado_veiculo" value="Usado">Usado

  Tipo: *
  <select name="tipo_veiculo" class="form-control option-bold custom-field">
   <option selected>-</option>
   <?php while($row_tipo_veiculo = mysql_fetch_assoc($tipo_veiculo)){ ?>
    <option><?php echo $row_tipo_veiculo['tipo_veiculo']; ?></option>
   <?php } ?>
  </select>

  Fabricante: *
  <select id="fabricante" name="fabricante" class="form-control option-bold custom-field">
   <option selected>-</option>
   <?php while($row_marcas = mysql_fetch_assoc($marcas)){ ?>
    <option value="<?php echo $row_marcas['id'] ?>"><?php echo $row_marcas['nome']; ?></option>
   <?php } ?>
  </select>

  Veículo: *
  <select id="modelo" name="modelo" class="form-control option-bold custom-field">
   <option disabled selected>Selecione o Fabricante</option>
  </select>

  Ano de Fabricação: *
  <select name="ano_fabricacao" class="form-control custom-field option-bold">
   <option selected>-</option>
   <option>2017</option>
   <option>2016</option>
   <option>2015</option>
   <option>2014</option>
   <option>2013</option>
  </select>

  Ano do Modelo: *
  <select name="ano_modelo" class="form-control custom-field option-bold">
   <option selected>-</option>
   <option>2017</option>
   <option>2016</option>
   <option>2015</option>
   <option>2014</option>
   <option>2013</option>
  </select>

         Cor:
         <select name="cor_veiculo" class="form-control custom-field option-bold">
          <option selected>-</option>
          <option>Branco</option>
          <option>Roxo</option>
          <option>Preto</option>
          <option>Cinza</option>
         </select>

         Combustível: *
         <select name="combustivel_veiculo" class="form-control custom-field option-bold">
          <option selected>-</option>
          <option>Gasolina</option>
          <option>Alcool</option>
          <option>Diesel</option>
          <option>Flex</option>
          <option>Gás</option>
         </select>

         Portas:
         <select name="portas_veiculo" class="form-control custom-field option-bold">
          <option selected>-</option>
          <option>1P</option>
          <option>2P</option>
          <option>3P</option>
          <option>4P</option>
         </select>

         Câmbio: *
         <select name="cambio_veiculo" class="form-control custom-field option-bold">
          <option selected>-</option>
          <option>Manual</option>
          <option>Automático</option>
          <option>CVT</option>
         </select>

        kilometragem: *
        <input type="text" name="kilometragem_veiculo" class="form-control custom-field" placeholder="-" >

        Dono:
        <select name="dono_veiculo" class="form-control custom-field option-bold">
         <option selected>-</option>
         <option>Único Dono</option>
         <option>Segundo Dono</option>
         <option>Mais de dois donos</option>
        </select>

        Cidade do Veículo: *
        <input type="text" name="cidade_veiculo" class="form-control custom-field" value="<?php echo $_SESSION['cidade_user']; ?>">

 Valor de Venda

        Valor: *
        <input type="text" name="valor_veiculo" class="form-control custom-field" placeholder="-" >

 Descrição

       <textarea name="descricao" class="custom-field-textarea form-control" style="height: 250px;"></textarea>

 Documentação do Veículo

        Placa:
        <input type="text" name="placa_veiculo" class="form-control custom-field" placeholder="-" >

        Renavam:
        <input type="text" name="renavam_veiculo" class="form-control custom-field" placeholder="-" >

        Nome Documento
        <input type="text" name="nome_documento" class="form-control custom-field" placeholder="-" >

         <input type="radio" name="alienado_veiculo" value="Alienado">

          Alienado

         <input type="radio" name="certificado_veiculo" value="Com Certificado">

          Com Certificado

         <input type="radio" name="garantia_veiculo" value="Garantia de Fabrica">

          Garantia de Fábrica

         <input type="radio" name="ipva_veiculo" value="IPVA Pago">

          IPVA Pago

         <input type="radio" name="licenciado_veiculo" value="Licenciado">

          Licenciado

         <input type="radio" name="revisoes_veiculo" value="Todas revisões feitas pela agenda do carro">

          Todas revisões feitas pela agenda do carro

         <input type="radio" name="revisoes_concessionaria" value="Todas revisões feitas pela concessionária">

          Todas revisões feitas pela concessionária

 Imagens Veículo

                                    ENVIE AS IMAGENS

                                     Selecione as imagens do seu veículo.

      <input class="button-new-anuncio btn-default" type="submit" name="img[]" value="Adicionar Anúncio" />

</form>
Answer: Acredito que o erro esteja aqui :

if($insereVeiculo)

sobre insert mysql_query não retorna true para conseguir isso deve usar o comando

mysql_affected_rows

para analisar quantas linhas foram afetadas.
mysql_query : http://php.net/manual/pt_BR/function.mysql-query.php
Para comandos SELECT, SHOW, DESCRIBE ou EXPLAIN, mysql_query() retorna um resource em caso de sucesso, ou FALSE em caso de falha.
Para outros tipos de consultas SQL, UPDATE, DELETE, DROP, etc, mysql_query() retorna TRUE em caso de sucesso ou FALSE em caso de erro.
O recurso de resultado retornado pode ser passado para mysql_fetch_array(), e outras funções para manipular tabelas de resultados, para acessar os dados retornados.
Use mysql_num_rows() para obter quantas linhas foram retornadas para um comando SELECT ou mysql_affected_rows() para obter quantas linhas foram afetadas por um comando DELETE, INSERT, REPLACE, ou UPDATE.
mysql_query() irá também falhar e retornar FALSE se o usuário não tiver permissões para acessar a tabela(s) referenciadas pela consulta.
mysql_affected_rows  : http://php.net/manual/pt_BR/function.mysql-affected-rows.php
Comment: Fiz essa alteração e percebi que ele apenas executa o primeiro INSERT, mas ele da o retorno de que "Ocorreu um erro" só que faz o INSERT corretamente no banco. No segundo INSERT ele para no "Selecione uma imagem"
Comment: Altera a pergunta e post o código html com o formulário de upload.


Find x that minimises F(x,g(x))

Question: I am trying to formulate an optimisation problem (which I think I have done correctly) but am struggling in solving it when substituting in a sample function, which leads me to think that maybe the formulation is incorrect, so would like to see where my error(s) were made. Assuming the formulation is correct, is there an analytical solution?
Consider some function $$F = f(x,g(x))$$ where we wish to find the minimum.
Taking: $$F'(x) = \frac{\partial{f}}{\partial{x}} + \frac{\partial{f}}{\partial{g}} \frac{\partial{g}}{\partial{x}} = 0$$
We should be able to solve for $x$.
Now consider $$f(x,g(x)) =  x-xg(x) - x g(x)^2$$
$$g(x) = \Phi(x) = {\frac {1}{\sqrt {2\pi }}}\int _{-\infty }^{x}e^{-t^{2}/2}\,dt$$
where $\Phi(x)$ is the cdf of a Normal distribution (although any cdf should work).
Attempting to calculate the partial derivatives and substituting into the above gives:
$$F'(x) = 1-g-g^2 + \left( -x(1+2g)\cdot \frac{1}{\sqrt{2\pi}} e^{-x^2/2} \right) = 0$$
where I've dropped $(x)$ from the notation for simplicity.
Assuming this is correct then I have a formula still in terms of both $x$ and $g(x)$, and no easy substitution given $g(x)$ is an integral. Is my approach totally wrong here, or is this equation more solvable than it looks?
Comment: Your derivative looks good to me. At first glance I don't see much either, but I would note that $0 \le g(x) \le 1$, and $g(x)$ is an increasing function - that might help.
Comment: What are the bounds on $x$? It's clear that if $x \ge 0$, then $f(x, g(x)) \ge 0$ (and this minimum is achieved at $x=0$).
Comment: Thanks, I realised that I wrote the question wrongly thanks to your comment! I want to maximise F, not minimise it! (Or minimise -F, if you will)... I will edit the question. But yes x>0.
Comment: Some more observations: $f \to -\infty$ as $x \to +\infty$, so there will be a maximum between the roots of $f$. Clearly $x=0$ is one root, and the other is when $1-g-g^2 = 0$, i.e. when $g=(\sqrt{5} - 1)/2$. This equation can be solved and will give you a bound on the maximum, but I'm not hopeful for an exact solution.
Comment: Interesting. I agree with your analysis but I have tried to plot the function (see my answer below) but I don't see the root where you suggest... it appears that the roots are (0,0.25) which is surprising.
Answer: $$g(x) = \Phi(x) = {\frac {1}{\sqrt {2\pi }}}\int _{-\infty }^{x}e^{-t^{2}/2}\,dt=\frac{1}{2} \left(\text{erf}\left(\frac{x}{\sqrt{2}}\right)+1\right)$$
$$f(x,g(x)) =  x(1-g(x)-g(x)^2)=-\frac{1}{4} x \left(\text{erf}\left(\frac{x}{\sqrt{2}}\right)
   \left(\text{erf}\left(\frac{x}{\sqrt{2}}\right)+4\right)-1\right)$$
$$f'(x,g(x))= \frac{e^{-\frac{x^2}{2}} x
   \left(\text{erfc}\left(\frac{x}{\sqrt{2}}\right)-3\right)}{\sqrt{2 \pi
   }}+\frac{1}{4} \left(-\left(\text{erfc}\left(\frac{x}{\sqrt{2}}\right)-6\right)
   \text{erfc}\left(\frac{x}{\sqrt{2}}\right)-4\right)$$
$$f''(x,g(x))= \frac{e^{-\frac{x^2}{2}} \left(x^2-2\right)
   \left(\text{erf}\left(\frac{x}{\sqrt{2}}\right)+2\right)}{\sqrt{2 \pi
   }}-\frac{e^{-x^2} x}{\pi }$$
Starting with $x_0$, Newton methods solves pretty fast $f'(x,g(x))=0$ :
$$\left(
\begin{array}{cc}
n & x_n \\
 0 & 0 \\
 1 & 0.15666426716443753140 \\
 2 & 0.15106897311919179609 \\
 3 & 0.15106533761909824900 \\
 4 & 0.15106533761750598442
\end{array}
\right)$$ At this point, $f''(x,g(x))$ is negative $(\approx -1.7003)$; so, this point is a maximum of $f(x,g(x))$.
So, the maximum of $f(x,g(x))$ is $\sim 0.0190825$.
Edit
If we plot $f(x,g(x))$ and notice that the maximum is close to $x=0$, we could avoid all these calculations building its Taylor expansion around $x=0$.
$$f(x,g(x))=\frac{x}{4}-\sqrt{\frac{2}{\pi }} x^2-\frac{x^3}{2 \pi }+O\left(x^4\right)$$ This would give the maximum
$$x_*=\frac{\sqrt{19}-4}{3}  \sqrt{\frac{\pi }{2}}\approx 0.149938 \quad \text{and} \quad f(x_*,g(x_*))=\frac{19 \sqrt{19}-82}{54} \sqrt{\frac{\pi }{2}}\approx 0.0190105 $$ which is quite decent.
Similarly, for more accuracy, we could use one more term for the expansion
$$f(x,g(x))=\frac{x}{4}-\sqrt{\frac{2}{\pi }} x^2-\frac{x^3}{2 \pi }+\frac{x^4}{3 \sqrt{2 \pi}}+O\left(x^5\right)$$ and build the $[1,2]$ Padé approximant of $f'(x,g(x))$. This would give
$$x_*=\frac{201 }{4 (420-\pi)}\sqrt{\frac{\pi }{2}}\approx 0.151080$$
$$ f(x_*,g(x_*))=\frac{201 }{1024 (420-\pi)^4}\sqrt{\frac{\pi }{2}}\left(-2404548720+20194569 \pi -67776 \pi ^2+64 \pi ^3\right)$$ which is $\approx  0.0190786$.
Comment: Sorry to say that I edited the formula, possibly after you started this answer, as the objective function is now $x(1-g-g^2)$.
Comment: @Zac. I rewrote my answer entirely.
Answer: I haven't solved it yet but figured that the function is reasonably inspectable via plotting in this case. Some simple python code allows us to visually identify where the minimum should be, although from the answers so far no analytical solution appears forthcoming:
<code>import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm

g = norm.cdf
x = np.linspace(-1,1)

# Objective func to maximise:
f = x*(1 - g(x) - (g(x))**2)
# Cost func to minimise:
L = -f

plt.plot(x,L)
plt.grid()
</code>
From this, the minimum appears to be around 0.015.

Find x that minimises F(x,g(x))


$T:V \to V$ be a unitary, self conjugated, Prove: exists a subspace $W$: $T(v) = v''-v', v = v'+v'', v' \in W, v'' \in W^{\perp}$

Question: Let $V$ be a unitary inner product space with finite dimension.
Let $T:V \to V$ be a unitary $(T^*T=TT^*=I)$, adjoint $(T^*=T)$ linear transformation.
Prove that exists a subspace for $V$ call it $W$ such that:
$$
T(v) = v''-v'
$$
For all $v \in V$ which satisfies: $v = v'+v''$, $v' \in W, v'' \in W^{\perp}$
I wrote a $2$ pages answer, i think what i wrote is not good and very complicated, can someone direct me to a more simple answer?
Comment: By unitary finite space I assume you mean a finite dimensional inner product space, and by "self conjugated" do you mean self adjoint or just $T=\overline{T}$?
Comment: @Dave I tried to correct
Answer: From unitary and self adjoint we deduce that the eigenvalues of $T$ belong to $\{1,-1\}$. Indeed, one way to see this is that unitary operators have eigenvalues in the unit circle in $\mathbb C$, and self adjoint operators have real eigenvalues. Another way is that unitary implies $TT^*=I$ and self adjoint means $T=T^*$, so $T^2-I=0$ and thus the eigenvalues must satisfy $\lambda^2-1=0$.
Now let $W$ be the $-1$-eigenspace of $T$. Since $T$ is diagonalizable, the eigenspaces are orthogonal and direct sum to all of $V$, so we have that $W^\perp$ is the $1$-eigenspace of $T$.
I'll let you bring it all together.
Comment: Ok so that explain $V = W \oplus W^{\perp}$ but how did they get to this $T(v) = v''-v'$ transformation?
Comment: Use the eigenvalue/eigenvector definition (and linearity)
Comment: $T(v) = T(v'+v'') = T(v') + T(v'') = v'+(-)v'' = v'+v''$ Thank you.


Maximum likelihood estimator in Uniform distribution

Question: For Random sample with uniform distribution in
 Tetha< x< Tetha +1
What's the maximum likelihood function how can we maximize it?
Comment: what have you done to attempt this question?
Comment: Many versions of this question have been answered here: see https://stats.stackexchange.com/search?q=uniform+maximum+likelihood.
Answer: The likelihood function is:
$$p(x|\theta)=\prod_{i=1}^n p(x_i|\theta)= \prod_{i=1}^n I(\theta < x_i<\theta+1)$$
The maximum value of this function is $1$, and the $\theta$ satisfying this maximum value is not unique , i.e. $\theta\in (x_{max}-1,x_{min}+1)$, if the interval is not empty, which can happen when the model is wrong, or there is noise.