Azure DevOps - Automatically run rails migrations

Question: I created a Azure devops project that deploys my code from Github. My project is a Rails app that runs on Docker. When I create the Azure DevOps project, it creates the CI/CD pipelines for me. The deployment works, but I can't figure out how to automatically migrate the database when we deploy. I know I can do it manually, but I prefer not to as we might forget when we deploy.
I tried to run the following commands in the "Post Deployment Actions"

rake db:migrate
bundle exec rake db:migrate
rbenv exec bundle exec rake db:migrate
docker-compose run web rake db:migrate

I've also generated my own kuduscript (using kuduscript) to add in the line for migration but it did not work. I don't know if it's because it's not reading my deployment script or if that line doesn't work.
Am I missing something? Should I try to figure out how to migrate through Docker instead? I've looked at all these links but they all run the migration manually.
https://learn.microsoft.com/en-us/azure/app-service/containers/quickstart-ruby
https://medium.com/paris-rb/deploying-your-rails-postgresql-app-on-microsoft-azure-180f8a9fab47
https://learn.microsoft.com/en-us/azure/app-service/containers/tutorial-ruby-postgres-app
Answer: So not sure if you ever figured this out but I just had to do this for a migration I'm working on. The best way to do what you're after from what I've found is to setup a stage in your release pipeline like so:
stage setup
Where basically:

Your service connection logs into the container registry
Pulls the image you just built and pushed to the registry
Use a docker run command to then run your image with all the necessary environment variables and anything else needed to run it properly.
You can then use another task if needed to run a docker exec bundle exec rake db:migrate

If the migrate task runs successfully it should exit 0 allowing you to then run your app service on the latest tagged image with the correct database changes already done.
Comment: Will this work if the database service is configured to be accessed through a Private Endpoint?


Flow Control and Return Values in a BashScript

Question: I'm quite new to bash scripting and i've been working on a small bash file that can do a few things for me. First of all, i'm calling this from a C function using system() and i'd like the script to return a value (1 for error, 0 for OK). Is this possible?
int kinit() {
    int err = system("/home/bluemoon/Desktop/GSSExample/kinitScript.sh");
}

Second, using Zenity, i managed to create a pop up window to insert user/password. Now, according to what the user does, multiple things should happen. If he closes the window or clicks "cancel", nothing should happen. If he clicks "OK", then i should check the input (for empty text boxes or something).
Assuming a correct input, i will use Expect to run a kinit program (it's a promt related with Kerberos) and log in. Now, if the password is correct, the prompt closes and the script should return 0. If it's not, the prompt will show something like "Kinit: user not found". I wanted to, in any case of error (closing window, clicking cancel or wrong credentials) return 1 in my script and return 0 on success.
#!/bin/bash
noText=""
ENTRY=`zenity --password --username`
case $? in
         0)
        USER=`echo $ENTRY | cut -d'|' -f1`
        PW=`echo $ENTRY | cut -d'|' -f2`

        if [ "$USER"!="$noText" -a "$PW"!="$noText" ]
        then
            /usr/bin/expect -c 'spawn kinit '`echo $USER`'; expect "Password for '`echo $USER`':" { send "'`echo $PW`'\r" }; interact'
        fi
        ;;
         1)
                echo "Stop login.";;
        -1)
                echo "An unexpected error has occurred.";;
esac

My if isn't working properly, the expect command is always run. Cancelling or closing the Zenity window also always lead to case "0". I've also tried to return a variable but it says i can only return vars from inside functions?
Well, if anyone could give me some pointers, i'd appreciate it.
Dave
Answer:
i'd like the script to return a value

Sure, just use exit in appropriate places

exit: exit [n]
    Exit the shell.

    Exits the shell with a status of N.  If N is omitted, the exit status
    is that of the last command executed.

My if isn't working properly, the expect command is always run.

if [ "$USER" != "$noText" -a "$PW" != "$noText" ]
#           ^  ^                  ^  ^
#           |  |                  |  |
#           \----- notice spaces ----/

Comment: Took me a while to figure oout the return statuses were multiplied by 256, but i got everything working. If works, Zenity goes for other cases, i can return 0 on success, 1 on error. Only thing missing is being able to return values and such on expect, but I'll still mark your answer as correct =)


Does $\int{f(x)\cdot f'(x)}dx=\frac{f^2(x)}{2}+c$ work?

Question: $$\int{f(x) \cdot f'(x)dx}=\frac{f^2(x)}{2}+c$$
Does this rule always work, as it appears this way to me.
$$\int{y\frac{dy}{dx}dx}=\int{ydy}=\frac{y^2}{2}+c$$
This is my working so far but I was wondering if this works for all functions or are there some limitations?
Comment: (1)  It is just a $u$-substitution and (2) you could check the answer by differentiation and notice that it is correct.
Comment: No, it does not always work.  There are functions $f(x)$, with  derivatives $f'(x)$, that exist and are bounded everywhere, but are not Riemann integrable.  See [Volterra's Function](https://en.wikipedia.org/wiki/Volterra%27s_function).
Comment: @UmbertoP. I interpret the symbol $\int$ as an integral, and prefer to write $\int_a^x f(t)f'(t)\,dt$.  If it merely means here a function that has as its derivative $f(x)f'(x)$, then yes, $\frac12 f^2(x)$+C $ is it.
Comment: your second line is essentially a proof that it works.
Comment: certainly for the functions I have tried it is true and I cannot see why it would not be true for all functions $f(x)$ but not sure if anyone else knew better?
Comment: @Randall This is not generally true   See [Volterra's Function](https://en.wikipedia.org/wiki/Volterra%27s_function).  One needs to ensure that $f'(x)$ is continuous almost everywhere.
Comment: OK, fine.  Assuming the integral exists, yes.
Comment: @MarkViola You bring up an interesting subtlety. Does an *indefinite* integral involve any concept of integrability, or is it just another way of stating that one function is the derivative of another?
Comment: ah I see now, this was what I meant for if it always works or not. If this was to be used how would you know whether or not it works?
Comment: @MarkViola That is interesting. I happen to take the other point of view.
Comment: @UmbertoP. In taking that "other point of view," the symbol $\int$ can no longer be interpreted as an integral.  It becomes merely a pure symbol.
Comment: Yeah, I know. It is a convenient abuse of notation.
Answer: Let $u=f(x)$, then $du= f'(x)dx.$
Thus  $$\int{f(x) \cdot f'(x)dx}=  \int{udu} = \frac {u^2}{2}+c  =     \frac{f^2(x)}{2}+c $$
Comment: How does one know that $f'$ is integrable?  Volterra's Function is an example of a function that is differentiable everywhere, has a bounded derivative everywhere, but is not Riemann integrable.
Comment: This is an indefinite  integral which is simply  an antiderivative.
Comment: It's an integral.  So, we'll agree to disagree


How can I change the project I upload to in GAE using maven?

Question: A while back, I created a GAE project using maven locally. First I created a remote project, and used the projectID while creating the local project to relate the local project with the remote one. I then used the mvn appengine:update command to upload the project, and opened the projectID.appspot.com to check, and everything worked correctly.
After some recent changes though, I wanted to change the target remote project, so I created a new project in Google Cloud Platform and in my local appengine-web.xml file, I changed the old projectID with the new one. I then tried mvn appengine:update again, to re-upload the project to the new location, and although it finished without promting any errors, it didn't work properly. When I tried to open the newProjectId.appspot.com page, the app didn't appear. Instead it only showed a page titled "App Engine Demo", with a "Hello, world" message. I checked the Activity tab of my new project in Google Cloud Platform and it shows the deployments, and also the cron jobs I created are running (100% errors though), but nothing seems to have been uploaded. What have I missed? Do I need to change anything else besides appengine-web.xml in order for the project to be correctly uploaded to the new location?
Comment: This should result in the outcome you're looking for. Double check the ids, make sure you have access, do a mvn clean appengine:update and see if it works. Then I would check the default version to ensure it matches what you just uploaded.
Comment: There are many possible variables. Did you run `mvn clean`? Did you deploy to the project you think you did (check pom.xml / appengine-web.xml)? Did you deploy to the current defeault service and version?
Answer: If you created the new project using a different Google account, you need to delete .appcfg_oauth2_tokens_java file so that it asks you for authorization again.
Comment: Hey, thanks for the advice, unfortunately the new project was created using the same account.


Vue Reactivity, How to Improve nested component dependency structure

Question: I have a parent search component that loads data based on search param changes, and it has a child component basically created to separate complicated logic e.g , which fires events and passes data to parent based on changes to state e.g (could be a selector, input change, etc...). what I want is to wait for both the child component to fire its initial events and the parent component as well and then call the function in watch for search params.
currently this code is making two request I want to wait for the child event to be fired to make it a single call, or if there is an alternative solution to this kind of architecture I would appreciate it.

<template>
  <HelloWorld @id-change="(e) => (searchParams.userIds = e)" />
</template>

This the child component that loads the Ids and the passes it to parrent.
<template>

</template>

I want a way to bring this to a single call but at the moment its call the loadFromBackendFunction twice, yeah I the state is change twice so therefore two calls but I want an alternative solution.
Comment: In the handler check that all the required parts are present in `newVal` and only call backend when they're there.
Comment: It's not really clear what you're asking for. Is it [debounce](https://css-tricks.com/debouncing-throttling-explained-examples/)? Note asking for recommendations is *off-topic* on [SO]. Please read [ask].
Answer: I guess the first call comes from this part
  created() {
    this.searchParams.sortType = "ASEC";
  },

It triggers the watcher and causes the first call to loadDataFromBackend
But why do you set sortType to DESC in data() and change it right after creating to ASEC?
This does not make any sense to me. I would just put ASEC as default value.
Comment: thats just an example, I keep some of these search params in router on reload on I want to assign them


Angular 7, p-table PrimeNG: Error: InvalidPipeArgument: '[object Object]' for pipe 'SlicePipe'

Question: Estou tentando fazer uma listagem em uma "p-table" do primeng, até ontem estava listando tudo perfeitamente, mas hoje ao rodar o projeto angular notei que estava ocorrendo este erro. Não faço a menor idéia do que significa e muito menos o motivo, pois tudo estava funcionando normalmente.
Erro:
TableBody.html:8 ERROR Error: InvalidPipeArgument: '[object Object]' for pipe 'SlicePipe'
at invalidPipeArgumentError (common.js:4323)
at SlicePipe.push../node_modules/@angular/common/fesm5/common.js.SlicePipe.transform (common.js:5812)
at Object.eval [as updateDirectives] (TableBody.html:8)
at Object.debugUpdateDirectives [as updateDirectives] (core.js:23911)
at checkAndUpdateView (core.js:23307)
at callViewAction (core.js:23548)
at execEmbeddedViewsAction (core.js:23511)
at checkAndUpdateView (core.js:23308)
at callViewAction (core.js:23548)
at execComponentViewsAction (core.js:23490)

Linha 8 do TableBody.html: (onde ocorre o erro. obs: nunca entrei nesse arquivo)
<ng-template ngFor let-rowData let-rowIndex="index" [ngForOf]="(dt.paginator && !dt.lazy) ? ((dt.filteredValue||dt.value) | slice:dt.first:(dt.first + dt.rows)) : (dt.filteredValue||dt.value)" [ngForTrackBy]="dt.rowTrackBy">

O codigo da minha tabela.html e do componente.ts: (obs: o método GET está funcionando normalmente retornando todos os dados, já testei separadamente e o problema ocorre quando cai os dados na tabela.)
Código disponível no codeshare
Answer: Passei pelo mesmo problema com Angular 7 e PrimeNG.
No meu caso, estava recebendo um objeto Observable contendo dentro dele um array com os dados da requisição GET no back-end.
Para iterar na tabela do PrimeNG você precisa de um Array.
Dessa forma, foi preciso buscar dentro do objeto o array com os dados e armazenar na variável dentro do componente.
//função get dentro do service.ts
return this.http
           .get<any[]>(`${this.url}`)
           .pipe(
                 map(res => res['content']) //pegando o array no HttpResponse
           );

Depois, no componente, armazena o array na variável e itera sobre ela para exibir.


Problemas com url amigavel no codeigniter

Question: Estou com o seguinte problema.
Estou trabalhando com um sistema em CodeIgniter e preciso remover o index.php da url.
Meu .htaccess esta como abaixo:
RewriteEngine on
RewriteCond $1 !^(index\.php|resources|assets|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]

O index.php em si já consegui resolver. O problema eh que o sistema tem um plugin de linguagens e a configuração do link é como abaixo:
www.site.com.br/pt/controller

A questão é que esse htacces esta sobrescrevendo o pt e eu não posso remover esse pt. E no caso, vão ter outras linguagens como en, es e etc.
Como resolve isso?
Answer: Altere a linha
RewriteRule ^(.*)$ index.php/$1 [L,QSA]

para
RewriteRule ^([a-zA-Z0-9\-\_]+)/([a-zA-Z0-9\-\_\s]+)[\/]?(.+)?$ index.php?1=$1&2=$2&3=$3 [NC,L]
RewriteRule ^([a-zA-Z0-9\-\_]+)/([a-zA-Z0-9\-\_]+)?$ index.php?1=$1&2=$2 [NC,L]
RewriteRule ^([a-zA-Z0-9\-\_]{1,})?$ index.php?1=$1 [NC,L]

depois para acessar o pt da URL você pode usar:
$_GET['1']

e assim por diante.
Comment: vlw cara.... funcionou aqui... brigadão


Youtube download link from http://www.youtube-mp3.org/

Question: I've been using the http://www.youtube-mp3.org/ to obtain download links for mp3 songs for a "internet radio" project (download file stream and output it). Lately the http://www.youtube-mp3.org/ seemed to changed it's workflow. Till now I was able to obtain the proper format of the url:
http://www.youtube-mp3.org/get?ab=128&video_id=KMU0tzLwhbE&h=5671e7d33d4eccb5b89ea8f54d9911d4&r=1387110278658.1527580295
Whereas r=timestamp
I did the timestamp myself as epoch. This worked well without the .1527580295 suffix.
Unfortunetly this seems to be needed as the link without the suffix redirects back to the conversion site.
Up till now the algorithim was as mentioned:
Youtube mp3 org linq acquiring explained
http://www.youtube-mp3.org/api/itemInfo/?video_id=#{video_id}&ac=www&r=#{Time.now.to_i}
Does any one know how to obtain the suffix part?
//Hey,
I'm not much of an web programming guy ... but this is something I have surely overlooked. Thanks!
Added this to my small C# API.

    const int AM = 65521;
    int GetCCSufix(string a)
    {
        int c = 1, b = 0, d, e;
        var chars = a.ToCharArray();
        for(e =0; e< chars.Length; e ++)
        {
            d = chars[e];
            c = (c + d) % AM;
            b = (b + c) % AM;
        }
        return b << 16 | c;
    }

Works great ;)
Comment: Hi. I could not get it work. Can you share where you got the documentation of new API call? What do you send to the GetCCSufix as parameter? My result is; `r=1388806010725.1561527943?` which is the VideoID & The Unix Time as parameter to the GetCCSufix method. But does only work *some* times on service. Most I will receive blank page.
Comment: I mean, I use Java time, not Unix time. I think there is another issue on this service. Blank page error occurs on less watched videos only. But on website directly, it works always.
Comment: Hey,
Sorry for the great delay in anwsering -> New year leisure I guess. I'll answer it when I'll be back home.
Comment: Can you give an example link to verify that the blank page occurs? They have to convert it first and probably then it's cached. But if it happens after that then it is odd.
Comment: I think's its not allowed here. can you catch my by email to info on my goldengel.ch website?
Comment: Any idea on how to deal with the new version of the API? @Nasenbaer
Comment: No. It simple does not work at all. I created own service.
Answer: I don't know what this suffix means but reading the client javascript file from youtube-mp3.org you can learn how to generate it.

var __AM=65521; // the largest prime less than 2^16...
function cc(a){
    var c = 1, b = 0, d, e;
    for(e = 0; e < a.length; e++){
        d = a.charCodeAt(e);
        c = (c+d)%__AM;
        b = (b+c)%__AM;
    }
    return b<<16|c;
}

The generated media URL is :
"http://www.youtube-mp3.org/get?ab=128&video_id="+video_id+"&h="+info.h+"&r="+timeNow+"."+cc(video_id+timeNow)

with

var timeNow = Date.now().toString();

Comment: My friend this url is deprecated. A new argument added at the end of the url. Please update your answer.
Comment: This is awesome! I spent weeks on this! Thank you so much!
Comment: @Raphaël Could you update your answer for the new version of the API?
Comment: Why not use youtubeinmp3.com/api - it has an official API. The only downside is that every few downloads they will redirect you to their website before starting the download... (but it's not the case if you do your homework good... ;)).
Comment: I just found youtubeinmp3.com has a daily download limit... :\


org.eclipse.swt.SWTException: Invalid thread access

Question: I am Opening outlook and attaching a file using My Java Web Application (JSF). The Methd is working Only once and when I attempt to call the Method again I get:
org.eclipse.swt.SWTException: Invalid thread access

Here is My method:
public void sendemails() {
        Display display = Display.getCurrent();
        Shell shell = new Shell(display);//Error is Happening on this Line.
        OleFrame frame = new OleFrame(shell, SWT.NONE);
        // This should start outlook if it is not running yet
        OleClientSite site = new OleClientSite(frame, SWT.NONE, "OVCtl.OVCtl");
        site.doVerb(OLE.OLEIVERB_INPLACEACTIVATE);
        // Now get the outlook application
        OleClientSite site2 = new OleClientSite(frame, SWT.NONE, "Outlook.Application");
        OleAutomation outlook = new OleAutomation(site2);
        OleAutomation mail = invoke(outlook, "CreateItem", 0 /* Mail item */).getAutomation();
        setProperty(mail, "BodyFormat", 2 /* HTML */);
        setProperty(mail, "Subject", "Testing");
        setProperty(mail, "HtmlBody", "I am Sending to you");
        ServletContext ctx = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
        String path = (String) ctx.getAttribute("capturepath");
        File file = new File(path);

        if (file.exists()) {
            OleAutomation attachments = getProperty(mail, "Attachments");
            invoke(attachments, "Add", path);
        } else {
            FacesContext.getCurrentInstance().addMessage(
                    null,
                    new FacesMessage(FacesMessage.SEVERITY_INFO,
                            "Failed!",
                            "File " + path + " Does Not exists"));
        }
        invoke(mail, "Display" /* or "Send" */);
    }

After Looking around I found out that I should create a method like this:
public void exec() {
        Display.getDefault().asyncExec(new Runnable() {
            @Override
            public void run() {
                sendemails();
                System.out.println("Outlook called");
            }
        });
    }

Which I have but when I call the exec Method Nothing Happens. can I sort this Invalid thread access without Neccesarily having to create another Method??
Answer:
can I sort this Invalid thread access without Neccesarily having to
  create another Method?

In short, no.
In long:
Anything that changes or adds something to the GUI in SWT needs to be called on the Display Thread, otherwise an Invalid thread access Exception will be thrown. You can either call asyncExec(Runnable) or syncExec(Runnable r)
Now, by looking at this question, I think that syncExec might be a better option for you.
Comment: Thanks for this Suggestion but This Only calls Outlook Once also, Later Nothing Happens no erros .. noting :(
Comment: Nope just Not responding.
Comment: So, does the error stop showing at the marked line in the code? Could you edit the question, please, and I'll have another look.
Answer: There is a solution for this :
Display.getDefault().syncExec(new Runnable(){
public void run() {
    // Your code to run Synchronously
}
});

Display.getDefault().asyncExec(new Runnable(){
public void run() {
    // // Your code to run Asynchronously
}
});


Very Simple matrix calculation

Question: I need to prove that, given $f$ a vector valued function from $B_1(0) \subset \mathbb{R}^m$ to $\mathbb{R}^m$, we have that (knowing that $\partial_{\nu}f = Df \cdot \frac{x}{|x|}$)
$$\langle Df , Df \cdot x \otimes \frac{x}{|x|}\rangle = |\partial_{\nu}f|^2 |x|.$$
I understand that $x \otimes \frac{x}{|x|}$ is a rank one $m \times m$ matrix, hence I get just by dividing and subtracting
$$\langle Df , Df \cdot \frac{x}{|x|} \otimes \frac{x}{|x|}\rangle \, |x|,$$ hence
$$\langle Df , \partial_{\nu}f \cdot \frac{x^T}{|x|}\rangle \, |x|.$$
From here I cannot understand how to justify that I can put on the left the $\frac{x^T}{|x|}$ term. Thanks!
Answer: Do not get confused between the matrix-vector product and the Hilbert-Schmidt product, which for vectors coincide. Kevin's computations are fair if we consider scalar-valued functions only. In the vectorial case we have the following:
$$ \langle Df,  Df\cdot x\otimes\frac{x}{|x|}\rangle=\langle Df,  \partial_{\nu}f \cdot \frac{x^T}{|x|}\rangle$$
$$=\sum_{k=1}^m \nabla f_k \cdot \partial_{\nu}f_k \cdot \frac{x^T}{|x|}$$
$$=\sum_{k=1}^m \nabla f_k \cdot \frac{x}{|x|} \cdot (\partial_{\nu}f_k)^{T}$$
$$ \langle Df \cdot \frac{x}{|x|},  \partial_{\nu}f\rangle= |\partial_{\nu}f|^2.$$

Or simply, by definition of Hilbert-Schmidt norm:
$$ \langle Df,  Df\cdot x\otimes\frac{x}{|x|}\rangle=\langle Df,  \partial_{\nu}f \cdot \frac{x^T}{|x|}\rangle$$
$$= \text{Tr}\left(Df\cdot (\partial_{\nu}f \cdot \frac{x^T}{|x|})^T\right)$$ $$ = \text{Tr}\left(Df\cdot  \frac{x}{|x|} \cdot(\partial_{\nu}f)^T \right)$$
$$= \text{Tr}\left(\partial_{\nu}f \cdot(\partial_{\nu}f)^T \right)$$ $$=\langle\partial_{\nu}f,\partial_{\nu}f \rangle =|\partial_{\nu}f|^2.  $$
Comment: Now it's clearer! Thank you very much to both of you!
Answer: Let $f:B_1(0)\subseteq \mathbb{R}^m\to\mathbb{R}^m$ be given and define the upgraded directional derivative:
$$\partial_{\nu}f:= Df\cdot \frac{x}{|x|} = Df\bigg(\frac{x}{|x|}\bigg),$$
where $Df := \big[\partial_jf_i(x)\big]_{ij}$ is the Jacobian matrix, each row being the gradient of $f_i$.
And define the Hilbert-Schmidt inner-product of matrices as:
$$\langle A,B\rangle = Tr(A^*B) = \sum\limits_{j=1}^m\langle Ae_j,Be_j\rangle,$$
for the usual orthonormal basis, $\{e_i\}$, on $\mathbb{R}^m$ ($A^* = A^t$ here). Then we want to show:
$$\color{darkblue}{\langle Df,Df\cdot x\otimes \frac{x}{|x|}\rangle = |\partial_{\nu}f|^2|x|},$$
where lastly $a\otimes b := a\cdot b^t\in \mathbb{R}^{m\times m}$.

Accordingly, using the definitions and multi-linearity of tensor products, matrices, and our particular inner product:
$$\big\langle Df,Df\cdot x\otimes \frac{x}{|x|}\big\rangle = \sum\limits_{j=1}^m\big\langle Df\cdot e_j,\big(Df\cdot x\otimes \frac{x}{|x|}\big)\cdot e_j\big\rangle$$
$$= \sum\limits_{j=1}^m\big\langle Df\cdot e_j, (Df\cdot x)\frac{x^t}{|x|}\cdot e_j\big\rangle$$
$$= \sum\limits_{j=1}^m\big\langle Df\cdot e_j, (Df\cdot x)\frac{x^j}{|x|}\big\rangle$$
$$= \sum\limits_{j=1}^m\big\langle Df\cdot (e_j\cdot \frac{x^j}{|x|}), Df\cdot x\big\rangle$$
$$= \big\langle Df\cdot \frac{x}{|x|}, Df\cdot x\big\rangle$$
$$= \big\langle Df\cdot \frac{x}{|x|}, Df\cdot \frac{x}{|x|}\big\rangle|x|$$
$$= |\partial_{\nu}f|^2|x|.$$

Thanks to @Son Gohan and @Crash Bandicoot (4!) for the suggestions/clarification of the HS inner product and notations.
Comment: Let me accept your answer, as a reward for the time spent. I'd accept Son Gohan's answer as well if I could.

Very Simple matrix calculation


Load a block contents dynamically / via AJAX?

Question: I need to have a custom block on the page (will be sitewide) that has two states - one for when a cookie is present and has a certain value, and the other for when that cookie is not there or the value is outdated. Think of it like login states, but no authentication through Drupal.
What is the proper way to go about this with the block build() method? Do I implement a lazy loader that has the logic in it that builds the render array? Do I also add a cache context based on this cookie and its value so it is unique to those users?
Comment: Drupal 8 lazy-builds blocks which are cacheable by user and delivers them via AJAX (BigPipe) out of the box. Why not implement an alternative authentication provider and use it as it is? Or use at least a session cookie which Drupal can handle much better than a standard cookie. For the latter it is probably a better idea to initiate lazy-loading via AJAX in client-side js code.
Comment: Well it's not really auth, that was just an example of a block state (Login / Logout). I'm reading an externally set cookie and rendering state based on that.
Comment: Drupal is not very good at handling cookies other than session cookies. Did you consider a client-side js solution?
Comment: I'll have to check with some front end folks on pure JS solution.
Comment: So even if we use the setCookie/getCookie method from Symfony, it will be problematic? I don't see many references to cookies in Drupal, and user_save_cookie/user_delete_cookie looks deprecated and unused. I don't need to really set or save one, just read one.
Comment: I have a simple functional test at the moment with `$this->getSession()->setCookie('foo', 'bar');` and reading that seems to work, but thats just in the test. I have not implemented anything yet.
Comment: You can get the cookie from the request, see https://drupal.stackexchange.com/questions/274485/cant-find-cookie-for-validation-in-eventsubscriber. Set the context and trigger the kill switch like in the code example and it should work. But this is not good for performance. So I would deliver an empty block container, attach a js library to the block, get the cookie value client-side and then initiate an ajax request to get the block content.
Comment: I see what you mean now. Checking this example, this seems more optimal (your latter suggestion): https://git.drupalcode.org/project/block_ajax
Comment: Great example, I post this as an answer then.
Answer: You can get the cookie from the request, see Can't find cookie for validation in EventSubscriber. Set the context and trigger the kill switch like in the code example and it should work. But this is not good for performance. So I would deliver an empty block container, attach a js library to the block, get the cookie value client side and then initiate an ajax request to get the block content.
See the code of the module Ajax Block as example how to lazy load a block client side: https://git.drupalcode.org/project/block_ajax
Comment: Unfortunately that module does not seem to work for anonymous users, and fails under functional tests (ajaxId is undefined). I also cannot seem to return a render array, I am limited to #markup in my block only. Do you have a possible simpler example on hand that does not need that module?
Comment: Scratch that - my block is working and rendering, and seemingly loading with the Block Ajax module. But something about that module is preventing me from effectively writing a test and checking 1 of 3 possible responses based on the cookie value. I can use different browsers and see it manually, but would like to provide a test.
Comment: By example I didn't meant the module itself, only the scaffolding consisting of a block plugin, empty or containing static default content like "Logged out", a js library containing the logic to check for the cookie and an ajax controller returning the dynamic block content.


Python function class, and __init__

Question: I currently have this code
class Vehicle:
    def __init__(self, make, model, yearOfManufacture, mileage):
        self.make = make
        self.model = model
        self.yearOfManufacture = yearOfManufacture
        self.mileage = mileage

    def get_make(self):
        return self.make

    def get_model(self):
        return self.model

    def get_year(self):
        return self.yearOfManufacture

    def get_mileage(self):
        return self.mileage

    def set_make(self, make):
        self.make = make

    def set_model(self, model):
        self.model = model

    def set_year(self, yearManufacure):
        self.yearOfManufacture = yearManufacure

    def setmileage(self, mileage):
        self.mileage = mileage

    def __str__(self):
        return append.(self.__dict__)

vehicle1 = Vehicle("Honda", "Civic", 2014, 50000);
print(vehicle1)
print("The mileage of this vehicle is:", vehicle1.get_mileage())
vehicle1.set_year(2012)
print("The year of manufacture of this vehicle is:", vehicle1.get_year())

which gives the output as
{'make': 'Honda', 'model': 'Civic', 'yearOfManufacture': 2014, 'mileage': 50000}
The mileage of this vehicle is: 50000
The year of manufacture of this vehicle is: 2012

How can I make it show as
Make: Honda; Model: Civic; Year of Manufacture: 2014; Mileage: 50000
The mileage of this vehicle is: 50000
The year of manufacture of this vehicle is: 2012

Comment: The code you've posted doesn't work, but did you try writing a `__str__` method to do what you describe?
Comment: @Kafia Kindly check my answer
Answer: Change the __str__ magic method to as follows:
def __str__(self):
    return f"Make: {self.make}; Model: {self.model}; Year of manufacture: {self.yearOfManufacture}; Mileage: {self.mileage}"

Output:
Make: Honda; Model: Civic; Year of manufacture: 2014; Mileage: 50000
The mileage of this vehicle is: 50000
The year of manufacture of this vehicle is: 2012

Python function class, and __init__


Shift target values by a big value to improve the Mean Absolute Percentage error (MAPE)

Question: I'm working on a Machine Learning regression task, where I have to predict a continuous value, and I have to minimize the Mean Absolute Percentage error, the problem that the target values ranges from zero to a bigger values, but most of the values are closer to zero, and when calculating the MAPE, it explodes due to small numbers in the denominator, so I came up with idea of shifting the values by some big amount, like adding the value 100 to each of the target values, and after training I can subtract 100 from the predictions to get the real value, I tried it and it works well, but is that right?
$$
MAPE = \frac{1}{N}\sum_{t=1}^{n}\left| \frac{At - Ft}{At} \right|
$$
Comment: Welcome to Cross Validated! $//$ $1)$ [Note the issues with MAPE.](https://stats.stackexchange.com/q/299712/247274) $//$ $2)$ If you are able to achieve (reliable) strong predictive performance, quantified by your measure of performance of interest, what else is there? $//$ $3)$ I wonder if it would be possible to treat that $100$ as a hyperparameter to tune. Sure, you get good performance by adding/subtracting $100$, but what about if you use $10$ or $10000?$ (Perhaps you have already tried various values.)
Comment: hi @Dave , thanks for the response, I didn't try other values than 100, but I thing if add more bigger values like 10000, the mape will decrease, the thing is, is adding or shifting the target values for training, and then subtracting the shifting value from the predictions, is this statistically or mathematically right to do, even if it's improve the model performance ?
Comment: Do you have any values of zero in the original data?
Answer: There are reasons not to use MAPE. However, if that is what you have to optimize (for whatever reason), then your goal is to do as well as possible in terms of MAPE.
The statistical/mathematical problem can be thought of as some kind of minimization of MAPE over many possible ways of making predictions. You've found a way to make predictions that gives a good MAPE score. While this might not be the optimal way to make predictions, you seem to have an effective model.
It might be that $100$ is fairly specific to your particular data, so standard validation procedures would be warranted. For instance, if you bootstrap your data and find the optimal value to be $100$ sometimes but that, other times, $100$ is a terrible value and the good values to pick are in the thousands, then you might not believe this modeling approach to be reliable.
A drawback to kind of "hacking" around like this is that it is not driven by a classical theory, so standard theorems do not apply. However, computational methods (like the bootstrap mentioned above) can lead to convincing evidence.
Basically anything can be an estimator, and while there are estimation techniques that have desirable properties under particular assumptions (e.g., maximum likelihood) that might be our go-to methods because they tend to work well, we don't shy away from effective alternatives (if we put together evidence that they are, indeed, effective).
Comment: thanks for you answer, I tried other values than 100, when I tried bigger values like 1000 and 10000, the model was worsening, and I tried smaller values like 10 and 1, and it was better in terms of speed of convergence and better predictions, so I don't know what can I conclude from these results, but I think that shifting the target values by any value greater than zero, but not a very big value, led to better results.
So what are your thoughts regarding these results ?
Comment: @MohamedEssam This sounds like a hyperparameter to tune, not really different from tuning a regularization hyperparameter to get the best out-of-sample performance. // I don't know the circumstances that would lead to this, but I could imagine that you will keep getting better performance as you keep decreasing the value toward zero, only for the performance to drop off at exactly zero.
Comment: I very much second Dave's recommendation to read [this thread](https://stats.stackexchange.com/q/299712/1352), as well as his answer to basically treat this as a ML task with the MAPE as the loss function. Much better to use the loss function you actually want to optimize (the MAPE), rather than to tweak the data and use a different loss function (presumably something like the square loss that is usually built in). I also recommend [Kolassa (2020)](https://doi.org/10.1016/j.ijforecast.2019.02.017), because I do believe it directly addresses your issues.


Is applying KL divergence to two fuzzy cluster membership assignments appropriate?

Question: Deep Embedded Clustering, originally by Xie et al. and in a question on CV as well, assigns cluster memberships with a $t$-distribution, hardens them with a second power, and computes the KL divergence to optimise centroids and data representation in the latent layer of an autoencoder. My question is simply this: is it appropriate to use KL divergence in this situation, given that the variables are dependent and sum to any positive integer, not just one? Let me expand a bit more.
KL divergence can be interpreted as the dissimilarity of two distributions, $Q$ and $P$, where the entropy of their probability density function is compared:
$$\text{KL}(P||Q) = \sum_{x\in X} P(x)\log\frac{P(x)}{Q(x)}$$
However, in the article Xie et al. use it with fuzzy cluster assignments. For example with two data points and two centroids, a matrix of cluster assignments $Q$ and the hardened assignments $P$ could look like this:
$$Q=\begin{bmatrix}0.8&0.3\\0.2&0.7\end{bmatrix}\quad P=\begin{bmatrix}0.9&0.2\\0.1&0.8\end{bmatrix}$$
where the columns of the matrices represent data points belonging to clusters as rows. The columns are normalised to sum to 1. The hardening relates to the optimisation task, but it's not important here. What's important is that we have two different assignments for the same data.
Xie et al. proceed to calculate the KL divergence from $Q$ and $P$. The output is certainly valid, reflecting the dissimilarity of the assignments. However, as I stated above, I'm suspicious. Two things concern me:

Dependent variables: as the assignments of each data point are normalised, the variables are dependent. Does this affect the calculation?
Not a proper probability density function: the values sum to the number of data points instead of 1. Does the distribution need to be always normalised to 1?
Answer: When researching this question, I think I've found some answers. I'm by no means an expert, so feel free to post other answers.

I think using $\text{KL}$ is appropriate here.
Dependent variables
As the distribution has a constant sum, all the variables are dependent to a certain degree. I doubt that the fact that subsets of the variables are further dependent affect the calculation.
Not a proper PDF
Normalising the distributions again would amount to multiplying them both with some value. Let's see it through in the $\text{KL}$ formula.
$$\text{KL}(cP||cQ) = \sum_{x\in X} cP(x)\log\frac{cP(x)}{cQ(x)} = c\sum_{x\in X} P(x)\log\frac{P(x)}{Q(x)}$$
So turns out that the factor just scales the overall value of $\text{KL}$, having no practical effect in the optimisation process. Though scaling could be done just to be pedantic.


Repetir laço enquanto o usuário escolher a opção de continuar

Question: Estou desenvolvendo uma aplicação em Java e após calcular tudo que o usuário pediu, eu preciso que ele informe a seguinte mensagem: "Deseja calcular novamente? S/N".
Estou usando o do/while mas não estou conseguindo fazer funcionar. Segue abaixo o código:
package beta;

import java.util.Scanner;

/**
 *
 * @author lab
 */
public class Beta {

    public static void main(String[] args) {

        Scanner obj = new Scanner(System.in);
        String escolha ;
        double raio , area , base , altura , raioM , diagonalm , diagonalM ;
        String volta;
        Scanner scanner = new Scanner(System.in);

        do{

            System.out.println("O que deseja Calcular? ");
                    System.out.println("1. Circulo");
                    System.out.println("2. Triângulo");
                    System.out.println("3. Trapézio");
                    System.out.println("4. Retângulo");
                    System.out.println("5. Corda Circular");
                    System.out.println("6. Diagonal do Losango");
                    System.out.println("7. Sair");
            escolha = obj.nextLine();

switch(escolha){

             case "1":
                System.out.println("Qual o raio do Círculo? ");
                raio = obj.nextDouble();
                area = 3.14 * (raio*raio);
                System.out.println("A área do Círculo é " + area);
             break;

             case "2":
                System.out.println("Qual a base do Triângulo: ");
                base = obj.nextDouble();
                System.out.println("Qual a Altura do Triângulo: ");
                altura = obj.nextDouble();
                area = (base*altura)/2;
                System.out.println("A área do Triângulo é " + area);
             break;

             case "3":
                System.out.println("Qual a base do Trapézio: ");
                base = obj.nextDouble();
                System.out.println("Qual a Altura do Trapézio: ");
                altura = obj.nextDouble();
                area = (base+base)*altura/2;
                System.out.println("A área do Trapézio é " + area);
             break;
             case "4":
                System.out.println("Qual a base do Retângulo: ");
                base = obj.nextDouble();
                System.out.println("Qual a Altura do Retângulo: ");
                altura = obj.nextDouble();
                area = base*altura;
                System.out.println("A área do Retângulo é " + area);
             break;
             case "5":
                System.out.println("Qual o maior raio da Corda Circular: ");
                raio = obj.nextDouble();
                System.out.println("Qual o menor raio da Corda Circular: ");
                raioM = obj.nextDouble();
                area = raio*raio - raioM*raioM;
                System.out.println("A área da corda circular é Pi " + area);
             break;
             case "6":
                System.out.println("Qual a maior Diagonal do Losango: ");
                diagonalM = obj.nextDouble();
                System.out.println("Qual a menor Diagonal do Losango: ");
                diagonalm = obj.nextDouble();
                area = (diagonalM*diagonalm)/2;
                System.out.println("A área do Losango é " + area);
             break;

           }
      escolha = scanner.next();
    } while(escolha.equalsIgnoreCase("Deseja calcular novamente? S/N"));

    } // fim main

} // fim classe

Comment: Você está perguntando se o que foi lido é idêntico à `"Deseja calcular novamente? S/N"` (ignorando diferença de caixa alta/baixa), o que não faz sentido
Answer: Primeiro, não tem porque criar dois Scanner's, já que ambos estão lendo do System.in. Usar apenas um é o suficiente (e chamar um deles de obj não ajuda muito, dê nomes melhores para as variáveis).
Outro ponto é que a escolha deve ser comparada com "s", e não com o texto "Deseja calcular novamente? S/N".
Outro detalhe é que métodos como nextDouble() não consomem a quebra de linha (no caso, o ENTER), então você deve chamar nextLine() logo depois, caso contrário a próxima chamada de nextLine() consumirá apenas a quebra de linha, deixando a escolha vazia.
Faltou também verificar se a opção é "7", e sair do while neste caso. E também removi a variável volta, pois ela não é usada no código.
Enfim, o código ficaria assim:
Scanner scanner = new Scanner(System.in);
String escolha;
double raio, area, base, altura, raioM, diagonalm, diagonalM;

do {
    System.out.println("O que deseja Calcular? ");
    System.out.println("1. Circulo");
    System.out.println("2. Triângulo");
    System.out.println("3. Trapézio");
    System.out.println("4. Retângulo");
    System.out.println("5. Corda Circular");
    System.out.println("6. Diagonal do Losango");
    System.out.println("7. Sair");
    escolha = scanner.nextLine();
    // se for 7, sai do while
    if ("7".equals(escolha))
        break;

    switch (escolha) {
        case "1":
            System.out.println("Qual o raio do Círculo? ");
            raio = scanner.nextDouble(); // use o "scanner", não mais o "obj"
         .... dentro do switch é igual
    }

    scanner.nextLine(); // consumir a quebra de linha, pois nextDouble() não a consome
    System.out.println("Deseja calcular novamente? S/N");
} while (scanner.nextLine().equalsIgnoreCase("s")); // nem precisa guardar o resultado de nextLine() em uma variável, pode comparar direto

Mas se as opções só podem ser números, então por que não usar nextInt() para lê-las?
Scanner scanner = new Scanner(System.in);
int escolha;
double raio, area, base, altura, raioM, diagonalm, diagonalM;

do {
    System.out.println("O que deseja Calcular? ");
    System.out.println("1. Circulo");
    System.out.println("2. Triângulo");
    System.out.println("3. Trapézio");
    System.out.println("4. Retângulo");
    System.out.println("5. Corda Circular");
    System.out.println("6. Diagonal do Losango");
    System.out.println("7. Sair");
    escolha = scanner.nextInt();
    if (escolha == 7)
        break;

    switch (escolha) {
        case 1:
           ....

        case 2:
           ....

           ....etc

        default: // pequena "firula"
            System.out.printf("Opçao inválida: %d\n", escolha);
    }

    scanner.nextLine();
    System.out.println("Deseja calcular novamente? S/N");
} while (scanner.nextLine().equalsIgnoreCase("s"));

Comment: Estava comentando no momento que você publicou a resposta ;-)
Comment: @JeffersonQuesado E eu ia comentar que estava respondendo no momento em que vc comentou :-)
Comment: E eu estava respondendo, saí pra jantar, voltei, respondi e vi que vocês já estavam comentando esta resposta =(
Comment: Realizei todas as alterações que indicou amigo e ficou exatamente como eu queria, muito obrigado, de coração mesmo, já não aguentava quebrar a cabeça com esse código mais, sou iniciante em Java ainda! kkk Obrigado!
Comment: @LuísFillipeMagalhães Se uma das respostas resolveu o seu problema, vc pode escolher a que melhor resolveu e aceitá-la, [**veja aqui**](https://pt.meta.stackoverflow.com/q/1078/112052) como e porque fazê-lo. Não é obrigatório, mas é uma boa prática do site, para indicar a futuros visitantes que aquilo resolveu o problema. E quando tiver 15 pontos, [**vc também poderá votar**](https://pt.stackoverflow.com/help/privileges/vote-up) em todas as respostas que achou úteis.
Answer: Você pode matar essa charada olhando a condição do while, na sua condição "(escolha.equalsIgnoreCase("Deseja calcular novamente? S/N"));" você está comparando se o usuário escreveu "Deseja calcular novamente? S/N" ignorando o tamanho das letras, ou seja, para apresentar novamente o menu no fim de uma de suas opções(considerando que o usuário tenha digitado um número no intervalo [1,7]) o usuário teria que escrever "Deseja calcular novamente? S/N".
Provavelmente o que você quer pode ser feito trocando
escolha = scanner.next();
} while(escolha.equalsIgnoreCase("Deseja calcular novamente? S/N"));

por
System.out.println("Deseja calcular novamente? S/N");
escolha = scanner.next();

} while(escolha.equalsIgnoreCase("s"));

Obs: Há trechos no seu código que podem ser melhorados, tentei focar apenas no cerne da pergunta.
Comment: Vou testar agora o programa com as modificações, sobre as melhoras em outros trechos, estou iniciante em java ainda kkkk menos de 2 semanas aprendendo, mas já gostei bastante da linguagem!
Comment: Sua dica foi bem útil amigo, mas ainda estou com um problema, apos realizar os cálculos, o progama sugere a pergunta "Deseja calcular novamente? S/N" conforme o previsto, mas quando seleciono o "S" ele me apresenta as opções novamente mas antes que eu responda o que desejo calcular ele já me faz a pergunta "Deseja calcular novamente? S/N" novamente.. Alguma ideia de como poso solucionar isso? Mas muito obrigado já por estar me ajudando!
Comment: Para resolver este problema você deve trocar **escolha = obj.nextLine();** por **escolha = obj.next();**, todavia seria melhor se você já utiliza-se o nextInt() e trocasse os cases do switch para inteiro assim como o  @hkotsubo exemplificou. Fico agradecido por ter sido útil =)


Como aplicar decorators que sejam classes em métodos de instância de outras classes?

Question: Estou tentando implementar uma classe que seja um method decorator em python. A ideia é aplicá-la à métodos de outras classes. No entanto, ela está se perdendo quanto a referência self do método da classe anotada.
Fiz o seguinte MCVE para demonstrar o problema:
import traceback

class Decorator:
    def __init__(self, wrapped):
        self.__wrapped = wrapped

    def __call__(self, *args, **kwargs):
        print(f"PARÂMETROS: args = {args}, kwargs = {kwargs}")
        return self.__wrapped(*args, **kwargs)

class Teste:
    def __init__(self):
        self.__x = 123

    @Decorator
    def foo(self):
        return self.__x

x = Teste()

print("\nInvocando método de instância como se fosse estático.")
try:
    print(Teste.foo(x))
    print("Funcionou!")
except:
    traceback.print_exc()

print("\nInvocando método de instância diretamente.")
try:
    print(x.foo())
    print("Funcionou!")
except:
    traceback.print_exc()

No código acima, eu criei a classe Decorator cujas instâncias devem ser aplicadas à métodos de outras classes como method decorators. A classe Teste é a que contém o método foo decorado. O código subsequente tenta invocar o método foo de Teste de duas formas diferentes (como se fosse um método estático e da forma usual como um método de instância).
Eis o resultado:
Invocando método de instância como se fosse estático.
PARÂMETROS: args = (<__main__.Teste object at 0x02BE0E90>,), kwargs = {}
123
Funcionou!

Invocando método de instância diretamente.
PARÂMETROS: args = (), kwargs = {}
Traceback (most recent call last):
  File "mcve.py", line 30, in <module>
    print(x.foo())
  File "mcve.py", line 9, in __call__
    return self.__wrapped(*args, **kwargs)
TypeError: foo() missing 1 required positional argument: 'self'

O resultado demonstra que invocar Teste.foo(x) funciona, mas invocar x.foo() não funciona. Eu gostaria que métodos de instância fossem chamados como tal, independente do fato de eu ter aplicado um method decorator arbitrário nele. Nota-se que quando o método é chamado tal como um método de instância, a instância de Teste não está nem no args e nem no kwargs.
Também tentei isso daqui, mas novamente não funcionou:
class Decorator:
    def __init__(self, wrapped):
        self.__wrapped = wrapped

    def __call__(*args, **kwargs):
        print(f"PARÂMETROS: args = {args}, kwargs = {kwargs}")
        return args[0].__wrapped(*args, **kwargs)

Assim, pergunto:

Como posso fazer um method decorator que seja uma classe de forma que uma chamada x.foo() funcione?
Ou de outra forma, como posso "pescar" a referência a instância do método decorado (o self do foo) ao invés de pegar o self do próprio decorator?

Adendo
Imaginando que a classe Decorator seja assim:
class Decorator:
    def __init__(self, wrapped):
        self.__wrapped = wrapped

    def __call__(self, *args, **kwargs):
        print(f"PARÂMETROS: args = {args}, kwargs = {kwargs}")
        return self.__wrapped(*args, **kwargs)

    def bar(self):
        return 456

A ideia é que print(x.foo.bar) também imprima 456.
Answer: Contextualização do erro
O problema é que ao fazer o método decorado, o atributo Teste.foo passa a ser uma instância de Decorator, pois decorá-lo assim é equivalente ao fazer:
class Teste:
    def __init__(self):
        self.__x = 123

    def _foo(self):
        return self.__x

    foo = Decorator(_foo)

E, portanto, quando você faz Teste.foo(x), sendo x a sua instância, você na verdade estará fazendo o equivalente à:
Decorator.__call__(Teste.foo, x)

Sendo executado, assim, self.__wrapped(*args, **kwargs), em que self será Teste.foo, __wrapped será o método Teste._foo e o valor de x passado entrará em *args. Desta forma, o resultado produzido será o equivalente a chamar Teste._foo(x), que seria o mesmo que x._foo(), produzindo, assim, a saída esperada.
Enquanto, quando você faz x.foo(), os parâmetros mudam, pois será o mesmo que fazer Decorator.__call__(x.foo). Como pode ver na implementação, o método __call__ chamará o método decorado passando apenas *args e **kwargs e, como na chamada não é passado nada além da instância do decorador, esses valores serão uma lista vazia e um dicionário vazio respectivamente. Como consequência disso, ao invocar o método decorado em self.__wrapped(*args, **kwargs), nenhum parâmetro será passado, o que gera o erro citado na pergunta, pois o parâmetro self é obrigatório visto que é um método de instância.
Possível solução
O que você pode fazer é utilizar uma closure no seu decorador de forma que, ao invés de fazer o atributo Teste.foo ser uma instância de Decorator você faz ele ser um closure definido por esta classe. Isso implica que quando você fizer a chamada do método decorado, ao invés de estar invocando o método __call__ do decorador, você estará invocando uma função. Sendo uma função, ela não espera a instância como primeiro parâmetro, contornando o problema apresentado, isso sem perder a referência a instância do decorador pois, como é uma closure, ela manterá referências do escopo em que foi definida, incluindo o self do seu decorador.
Para isso, você faz com que o próprio método __call__ seja o decorador dos seus métodos:
class Decorator:
    def __call__(self, method):
        def wrapper(obj, *args, **kwargs):
            # Aqui você ainda pode utilizar self para acessar a instância do decorador
            return method(obj, *args, **kwargs)
        return wrapper

Desta forma, quando você fizer x.foo() você estará invocando a closure wrapper definida pela classe Decorator, passando como primeiro parâmetro, obj, uma referência à própria instância x, gerando o resultado esperado.
class Teste:
    def __init__(self):
        self.__x = 123

    @Decorator()
    def foo(self):
        return self.__x

x = Teste()

print(Teste.foo(x))  # 123
print(x.foo())  # 123

Comment: Talvez consiga implementar soluções distintas utilizando o método `__new__` ou descritores, mas preciso analisar com mais calma em um momento de menor cansaço.
Comment: Vou testar isso amanhã com calma. De qualquer forma, sua resposta me parece muito boa, já tem o meu +1.
Comment: Bem, fiz uns testes e a sua solução resolve o que coloquei na perrgunta. No entanto, quando eu estava reduzindo o meu problema original para um MCVE, eu cortei os demais métodos do Decorator e com a solução proposta, eles tornam-se inacessíveis. A razão pela qual o Decorator era retornado ao invés de uma closure era para que tais métodos estivessem disponíveis. Conhece alguma solução para esse caso?
Comment: @VictorStafusa acessíveis de onde? Se for de dentro do decorador, mesmo dentro da closure voce consegue acessa-los. Até coloquei como comentário no código isso. Deu algum erro ao tentar reproduzir?
Comment: Acessíveis externamente como `x.foo.bar`. Editei a pergunta.
Comment: Sua resposta me ajudou a resolver o problema, mas não o solucionou completamente. Depois de quebrar a cabeça por uns dias, cheguei na solução da resposta que postei aqui. Agradeço muito pela ajuda.
Answer: Agradeço muito ao Anderson Carlos Woss. Apesar da resposta dele ter me indicado alguns caminhos, não permitia que eu acessasse coisas como x.foo.bar, e portanto ainda não era tudo o que eu precisava.
Pesquisando mais sobre o assunto, também considerei essa resposta do Martijn Pieters no SO.en, que apesar de ser para uma pergunta bem diferente, há vários fatores similares a esta daqui.
Depois de quebrar bastante a cabeça por uns dias, cheguei a isso:
import traceback
from functools import wraps

class InnerDecorator:
    def __init__(self, real_self, wrapped, other):
        self.__real_self = real_self
        self.__wrapped = wrapped
        self.__other = other

    def __call__(self, *args, **kwargs):
        if self.__real_self is None:
            print(f"PARÂMETROS (ESTÁTICO): args = {args}, kwargs = {kwargs}")
            return self.__wrapped(*args, **kwargs)
        else:
            print(f"PARÂMETROS (INSTÂNCIA): self = {self.__real_self} args = {args}, kwargs = {kwargs}")
            return self.__wrapped(self.__real_self, *args, **kwargs)

    def other(self):
        return self.__other

class Decorator:
    def __init__(self, wrapped):
        self.__wrapped = wrapped

    def __get__(self, obj, objtype = None):
        if self.__wrapped is None:
            raise AttributeError("unreadable attribute")

        @wraps(self.__wrapped)
        def interno():
            return InnerDecorator(obj, self.__wrapped, 77)
        return interno()

    def other(self):
        return self.__get__(None, None).other()

    def __call__(self, *args, **kwargs):
        return self.__get__(None, None)(*args, **kwargs)

@Decorator
def xoom(bar):
    return 500 + bar

class Teste:
    def __init__(self, x):
        self.__x = x

    @Decorator
    def foo(self, bar):
        return self.__x + bar

print("\nInvocando método de instância como se fosse estático.")
try:
    x = Teste(3)
    print(Teste.foo(x, 30))
    print(Teste.foo.other())
    print("Funcionou!")
except:
    traceback.print_exc()

print("\nInvocando método de instância diretamente.")
try:
    x = Teste(5)
    print(x.foo(10))
    print(x.foo.other())
    print("Funcionou!")
except:
    traceback.print_exc()

print("\nInvocando funções.")
try:
    print(xoom(55))
    print(xoom.other())
    print("Funcionou!")
except:
    traceback.print_exc()

Eis a saída:
Invocando método de instância como se fosse estático.
PARÂMETROS (ESTÁTICO): args = (<__main__.Teste object at 0x02FD5990>, 30), kwargs = {}
33
77
Funcionou!

Invocando método de instância diretamente.
PARÂMETROS (INSTÂNCIA): self = <__main__.Teste object at 0x02FC0F90> args = (10,), kwargs = {}
15
77
Funcionou!

Invocando funções.
PARÂMETROS (ESTÁTICO): args = (55,), kwargs = {}
555
77
Funcionou!

Enfim, isso demonstra que o @Decorator pode ser aplicado em um método como se ele fosse estático, pode ser aplicado em um método de instância normal e também pode ser aplicado em uma função qualquer que não seja método de qualquer classe. Além disso, ele acrescenta uma propriedade other ao método decorado.
O principal ponto de melhoria é que foram necessárias duas classes para fazer isso, o Decorator e o InnerDecorator e há alguma duplicação de código entre elas. Mas já me dou por satisfeito e atingi o objetivo que buscava atingir.


ubuntu 10.04; kvm bridged networking not working with public ip addresses

Question: I have a dedicated hosted server box with ubuntu 10.04 64 bit installed.  I would like to run kvm with ubuntu 8.04 installed for some php 5.2 compatible apps(they don't work right with php 5.3, the default in ubuntu 10.04).
I installed KVM as instructed at https://help.ubuntu.com/community/KVM/Installation .  I installed the vm using virt-manager.  I never could figure out how use virt-install or any of those automated installers.  I just installed it using the disc.  I set up bridged networking as per https://help.ubuntu.com/community/KVM/Networking . However, the bridged connection doesn't work.
Here's my /etc/network/interfaces on the host, running ubuntu 10.04.    (with specific public ip blanked)
auto lo
iface lo inet loopback

auto eth0
iface eth0 inet manual

auto br0
iface br0 inet static
        address xx.xx.xx.xx
        netmask 255.255.255.248
        gateway xx.xx.xx.xa
        bridge_ports eth0
        bridge_stp on
        bridge_fd 0
        bridge_maxwait 10
`

Here's my /etc/network/interfaces on the guest, running ubuntu 8.04.
auto lo
iface lo inet loopback

auto eth0
iface eth0 inet static
address xx.xx.xx.xy
netmask 255.255.255.248
gateway xx.xx.xx.xa

The two vm's can communicate to each other.  But, the guest vm can't access anyone in the real world.
Here's my /etc/libvirt/qemu/store_804.xml
<domain type='kvm'>
  <name>store_804</name>
  <uuid>27acfb75-4f90-a34c-9a0b-70a6927ae84c</uuid>
  <memory>2097152</memory>
  <currentMemory>2097152</currentMemory>
  <vcpu>2</vcpu>
  <os>
            <type arch='x86_64' machine='pc-0.12'>hvm</type>
            <boot dev='hd'/>
              </os>
  <features>
    <acpi/>
    <apic/>
    <pae/>
  </features>
  <clock offset='utc'/>
  <on_poweroff>destroy</on_poweroff>
  <on_reboot>restart</on_reboot>
      <on_crash>restart</on_crash>
      <devices>
            <emulator>/usr/bin/kvm</emulator>
    <disk type='file' device='disk'>
      <driver name='qemu' type='raw'/>
      <source file='/var/lib/libvirt/images/store_804.img'/>
      <target dev='hda' bus='ide'/>
    </disk>
    <disk type='block' device='cdrom'>
      <driver name='qemu' type='raw'/>
      <target dev='hdc' bus='ide'/>
      <readonly/>
            </disk>
                    <interface type='bridge'>
      <mac address='52:54:00:26:0b:c6'/>
      <source bridge='br0'/>
      <model type='virtio'/>
        </interface>
    <console type='pty'>
      <target port='0'/>
    </console>
    <console type='pty'>
      <target port='0'/>
    </console>
    <input type='mouse' bus='ps2'/>
    <graphics type='vnc' port='-1' autoport='yes'/>
            <sound model='es1370'/>
    <video>
      <model type='cirrus' vram='9216' heads='1'/>
    </video>
  </devices>
</domain>

Any idea where I've gone wrong?
Answer: You can't use bridge mode in such environment, you can almost be certain that the hosting partner will block all traffic not originating from the MAC-address of the real NIC in your server. You'll need to setup a routed setup, in which all traffic to/from VM guests are send through your host. One way of doing this is using the native Libvirt support of routed networking ("forward mode="route" in the XML-configuration of the network).
There's a German server hosting company who has written a couple of guides on the subject, you can use Google translate to translate it into English, in case you don't understand German :)
http://wiki.hetzner.de/index.php/Kategorie:KVM
Comment: Thanks.  That makes perfect sense.  I shall try it and report back if all works well.
Comment: Thats odd Kenni, I'm doing exactly this in my data center at the moment. Works fine.
Comment: Depends on the data center; mine don't allow it either.  It's a reasonable decision for them to take and they do provide instructions to work around it, but can't get the damn thing to work anyway... http://wiki.hetzner.de/index.php/KVM_mit_Nutzung_aller_IPs_-_the_easy_way
Answer: The guest also needs a default route. Do you have that?
So, you're doing all this just to get a new (downgraded) version of an app? Why not just build (or find, or install from source) a PHP 6.2 package in the host?
Comment: I had already checked that.

    Kernel IP routing table
    Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
    xx.xx.xx.8     *               255.255.255.248 U     0      0        0 eth0
    default         xx.xx.xx.9     0.0.0.0         UG    100    0        0 eth0

That is the automatically generated routes table, which looks good to me.
Comment: As far as building PHP 5.2 from source, or downgrading manually;  I have followed some procedures install PHP 5.2 manually.  However, there are many more things needed like mysqli and phpmyadmin, all of which I couldn't easily figure out how to downgrade.  Instead of chasing a bunch of dependencies, I would rather just install the store software on a supported platform.
Comment: Ah well, just switch to Gentoo. ;-)


Assign two domain names to a single EC2 instance

Question: I am running an AWS EC2 Linux instance with Elastic IP a.b.c.d. and I am hosting two different websites on it:

ServiceA: http://a.b.c.d/serviceA
ServiceB: http://a.b.c.d/serviceB

I have purchased the following domains: serviceA.com and serviceB.com and I would like to assign them to the proper hosting path. I found how to do it with URL redirect. Is there a way to do it through DNS configuration?
Answer: Yes.
Make both domains point to your IP (A records).
On the AWS EC2 Linux web server configuration, set serviceA.com and serviceB.com as Virtual Hosts for serviceA and serviceB folders respectively. The server will show one website or the other based on which Host: header it receives.


$scope Is not accessable inside PageMethods.GetEmployeeDetails

Question: $scope is not being accessed inside PageMethods.GetEmployeeDetails Can any one guide me thanks.
function FirstController($scope, $http) {
    $scope.source = 10;

    PageMethods.GetEmployeeDetails(function Success(data) {
        $scope.source = 11;
        $scope.MyData = data;

    });
}

Comment: I want to get "data" and use it in UI, so i need to assign it to $scope veriable??
Comment: I think your controller defination is wrong. Is this the full controller? if not, please add the full controller defination.
Answer: I believe based upon the question that you want to be able to call GetEmployeeDetails from your UI/DOM
In order to do that you will need to define that question on your $scope:
$scope.GetEmployeeDetails(function Success(data) {...

then in your markup (which will need to be within the scope of your controller:

    <button type="button" ng-click="GetEmployeeDetails(data)">Click Me</button>

Edit based upon OP's comments below
The issue the above fixes is to allow a method to be accessible via scope and therefore DOM
This is how to allow a call outside of "angular-land" (aka not in an angular module) to recognize changes to scope
Since the method PageMethods.GetEmployeeDetails is not recognized/managed by angular it has no idea the $scope may have changed upon callback. So in order to handle that scenario you must tell angular to reevaluate the $scope to allow angular to refresh the DOM as shown here:
PageMethods.GetEmployeeDetails(function Success(data) {
    $scope.$apply(function(){
        $scope.source = 11;
        $scope.MyData = data;
    });
});

Comment: I'm Getting json data from PageMethods, how can i replace it with $scope
Comment: @AmaanKhan I've updated my answer based upon your clarification, but left the original in case you or others find that useful.


Ring Isomorphism of Subfield to Matrix Space

Question: Let K be a subfield of a field L, which can be treated as an n-dimensional K-vector space (n < $\infty$). Show that L is isomorphic as a ring to a subring of $M_n(K)$.
I can't figure out what isomorphism makes sense.
Comment: Hint: For each $\alpha\in L$, the map $L\to L$ defined by $x\mapsto \alpha\cdot x$ is a $K$-linear map.
Answer: $L$ is a $K$-vector space of dimension $n$. For each $l\in L$, there is a $K$-linear map $m_l:x\in L\mapsto lx\in L$. This gives us a function $\phi:l\in L\mapsto m_l\in\operatorname{End}_K(L)$.
Show this $\phi$ is an injective morphism of rings.
Finally —and only if you insist in matrices— pick a basis of $L$ as a $K$-vector space, and use it to define a ring isomorphism $\operatorname{End}_K(L)\to M_n(K)$, and consider the composition off $\phi$ with this.


how to search record with multiple input

Question: I want to search record with multiple input.If i enter keyword like delhi,mumbai in text field
record should be display
<code>my code is
<input type="search" name="search[]">
$location=$_POST['search'];
mysql_query("select * from record where location like '%$location%'")
</code>
please help me i am not able to search record with multiple location
Answer:
Use mysqli or PDO instead.
I assume you have multiple input fields named "search[]".

What you should do is something like this:
<code>$locations=$_POST['search'];
$likeSqlStr = '';
foreach ($locations as $loc) {
   if (!empty($loc)) {
      $likeSqlStr .= " OR location LIKE '%" . $loc . "%'";
   }
}
$query = "select * from record where (" . (!empty($likeSqlStr) ? '0' . $likeSqlStr : '1') . ")";
$results = mysqli_query($query);
</code>


Translating multiple universal quantifiers in predicate logic

Question: I'm very confused as to how to interpret predicate logic statements with multiple universal quantifiers sharing the same domain. For example, I'm trying to make sense of the following statement:
CM is the domain of all Cabinet Ministers
MS is the domain of all movie stars
L(x,y): person x likes person y
∀c1 ∈ CM, ∀c2 ∈ CM,c1≠c2 -> ∃s ∈ MS,  L(s,c1) ^ L(s, c2) ^ (∀c3∈CM, c1≠c3^c2≠c3 -> ~L(s,c3))
I have no idea what this could mean. It seems to me that it's saying all cabinet ministers are either liked or disliked by a movies star. I interpret ∀c1 ∈ CM to be all cabinet ministers but how can there be ∀c1 ∈ CM and ∀c2 ∈ CM? Are all cabinet ministers split in two groups?
Comment: There's a free variable $x$ that doesn't make much sense.  Perhaps the last predicate should be $\neg L(s,c_3)?$
Comment: yes, that's what I meant, my bad for the typo
Answer: Let's read it from left to right.

$\forall c_1 \in CM,\ \forall c_2 \in CM, \dots$

For any two cabinet ministers $c_1,c_2$ ...

$\dots c_1 \ne c_2 \Rightarrow \dots$

... if $c_1 \ne c_2$, then ...

$\dots \exists s \in MS, \dots$

... there is a movie star $s$, such that ...

$\dots L(s,c_1) \wedge L(s,c_2) \wedge \dots$

... $s$ likes $c_1$ and $s$ likes $c_2$, and ...

$\dots \forall c_3 \in CM \dots$

... for all cabinet ministers $c_3$ ...

$\dots c_1 \ne c_3 \wedge c_2 \ne c_3 \Rightarrow \dots$

... if $c_3$ is neither $c_1$ nor $c_2$, then ...

$\dots \neg L(s, c_3)$

... $s$ does not like $c_3$.

Now if you were to read the 'English' version of these things, it doesn't make much sense. But putting it together further, we can now say something like this:

For any two cabinet ministers $c_1$ and $c_2$, who are not the same minister, there is a movie star $s$ who likes both $c_1$ and $c_2$ and such that, for any minister $c_3$ other than $c_1$ or $c_2$, the movie star $s$ does not like $c_3$.

Even more concisely:

For any two distinct cabinet ministers, there is a movie star who likes both ministers but does not like any other ministers.

The word 'distinct' is packed up in $c_1 \ne c_2$, and the words 'any other' are packed up in $\forall c_3 \in CM,\ c_1 \ne c_3 \wedge c_2 \ne c_3 \Rightarrow \cdots$.
Comment: That makes a lot of sense. I'm just wondering what the difference would be then if we were to say ∃c1 ∈ CM, ∃c2 ∈ CM, c1≠c2? What really is the difference between "There exist two distinct cabinet ministers" and "For any two distinct cabinet ministers"?
Comment: Suppose there are 100 ministers. If you use $\forall$, then it says that no matter which two you pick, there is some movie star who likes them (and only them). On the other hand, if you use $\exists$, then it says that there are two ministers who have a movie star who like them (and only them) but there could very well be 98 ministers who are hated by all movie stars.
Comment: In translating "∀c1 ∈ CM, ∀s ∈ MS, ~(∃c2 ∈ CM,c1≠c2 ^ L(c2,s)) -> ~ L(c1,s)" would I be right in saying "for any cabinet minister c1, if there does not exist a distinct cabinet minister that likes all movie stars then no cabinet minister likes any cabinet ministers." So could the interpretation be that "all cabinet ministers dislike all movie stars if there isn't' another cabinet minister that likes all movie stars?"
Comment: @simba: No. When you say "[if] there does not exist a [disctinct] cabinet minister that likes all movie stars", you're saying $\neg \exists c_2 \in CM,\ \forall s \in S, L(c_1,s)$, which is not what you have. Note that the implication part of that statement is of the form $\neg P \Rightarrow \neg Q$, which is the contrapositive of $Q \Rightarrow P$. As such, it is equivalent to saying: "If any minister likes a movie star, then there is another minister that likes the same movie star."
Comment: my mistake, I should've noticed right away the position of the negation. Thank you so much for your explanation!


Stream getUserMedia to an Icecast server?

Question: Is there a way to stream the local blob created by webrtc's getUserMedia (vidio and audio) to an Icecast server, making it possible to live broadcast using HTML5?
Specifically in the following example (from Justin Uberti's 2012 Google I/O video) I can  capture audio/video and play it locally in a video element:
<code><script type="text/javascript">
var onGotStream = function(stream) {
  var url = webkitURL.createObjectURL(stream);
  video.src = url; //
}
navigator.webkitGetUserMedia({video: true, audio: true}, onGotStream, null);
<script>

<video = id='video' autoplay='autoplay'/>
</code>
But instead of setting the video src to the local blob I'd like to send the stream to an Icecast server and then play that live stream using video elements pointing to the Icecast server.
Is this possible? How would I go about it?
Thanks!!
Comment: Did u find out anything?
Comment: @BobSmith http://stackoverflow.com/questions/20850396/stream-recorded-audio-from-browser-to-server/20850467#20850467  http://stackoverflow.com/questions/20850396/stream-recorded-audio-from-browser-to-server/20850467#20850467
Answer: Take a look at this
https://github.com/webcast/webcaster
it captures getUserMedia PCM, encodes it to MP3 format using JavaScript right in your browser, sends encoded MP3 data to Liquidsoap http://liquidsoap.fm/ via Websockets and then Liquidsoap can broadcast that stream to Icecast server.


For which odd number $k$ does $\ \varphi(n) \mid n-k \ $ has infinitely many solutions?

Question: The Lehmer-totient problem: For a prime number $\ n\ $ we have $\ \varphi(n)=n-1\ $. In particular, we have $\ \varphi(n) \mid n-1\ $. Is there a composite number $\ n\ $  with $\ \varphi(n)\mid n-1\ $ ?
It is not known if there is any such composite $n$ but may be Lehmer-totient problem is the tip of the iceberg. I was running computations on variation of this problem and I observed that for every small odd $k$ such as $k = 3,5,7,\ldots 25$ there were only a couple of solutions of $\ \varphi(n) \mid n-k\ $ for $n < 10^{10}$. E.g. for $k = 3$, the only solutions so far are $n = 9, 195$ and $5187$. The data suggests that at most there are finitely many solutions for a given odd $k$.
Question: Is there any fixed odd $k > 1$ such that $\ \varphi(n) \mid n-k\ $ has infinitely many solutions?
Answer: This is an open conjecture by R. L. Graham (see R. K. Guy, Unsolved problems in Number theory, Second ed., Springer-Verlag, p. 93):
Conjecture: For all positive integers $k$ there are infinitely many $n$ such that
$$
ϕ(n)|(n − k)
$$
The conjecture has been proved for $k = 0$, $k = 2^a$ for $a> 0$ and for $k = 2^a\cdot 3^b$ with $a,b>0$.
For odd $k\ge 3$ the conjecture is still open.
Comment: I don't think it's open for $k = 1$, unless the existence of infinitely many primes has come into doubt ;-)
Comment: @NickMatteo Edited.


Question from Gelman Regression & Other Stories

Question: Comparison of proportions: You want to gather data to determine which of two students is a better basketball shooter. One of them shoots with 30% accuracy and the other is a 40% shooter. Each student takes 20 shots and you then compare their shooting percentages. What is the probability that the better shooter makes more shots in this small experiment?
I'm struggling with the above question. I think the solution requires computing a z score and looking at the probability of getting a value below. I.e., my logic so far is
$$p_1 - p_2 = -.1$$
$$se(p_1-p_2) = .15$$
$$z = -.66$$
Want to know $Prob(p_1-p_2 <0)$
implies; $Prob(Z > z) \to Prob(Z > -.66) \to 1-Prob(Z < -.66) = 1 - .2454 = .7546$
My reasoning isn't totally clear to me. Specifically, I'm not sure why $Prob(p_1-p_2 <0)$ implies $Prob(Z > z)$ makes sense.
Comment: You are using a Normal approximation for a discrete problem.  The issue is that the chance the two shooters tie is approximately $0.1055941$ and you have to account for that.  If you split the difference--subtract half this chance from your current estimate--you will get close to the correct value of $0.6925396.$ A better way to use a Normal approximation is to reframe the question in terms of the *difference* in total baskets made.
Comment: @Aaron Note that the phrasing of the question suggests what to do with ties
Answer: Let's actually start with a simulation to see where we should be heading, and then do the math.  Using R...
<code>nsim = 1e5
set.seed(0)
a = rbinom(nsim, 20, 0.3)
b = rbinom(nsim, 20, 0.4)
mean(b>a)
[1] 0.69248
</code>
So whatever the answer is mathematically, it should be around 0.69.
Let $A$ and $B$ be independent random variables for the number of shots made by both players respectively.  Note because we have a success/failure outcome, and we make a sequence of them, then $A$ and $B$ are binomial random variables with mean $np$ and variance $np(1-p)$.  Here, $p$ is the probability of success for an individual trial. The normal approximation to the binomial is then
$$ A \sim \mathcal{N}(6, 4.2) $$
$$ B \sim \mathcal{N}(8, 4.8) $$
Here, I have just used the mean and variance of the binomials.  The question asks about the better player making more shots, which is equivalent to asking $P(B-A>0)$.  Because we are using a normal approximation, $B-A$ is also a normal random variable.
$$ B-A \sim \mathcal{N}(2, 9)$$
With the normal approximation to the difference in hand, we can apply standard techniques to estimate the probability.  One of these techniques is a continuity correction.  When we apply the continuity correction, we get an answer very similar to our simulation result.
$$ z = \dfrac{(0+0.5) - 2}{\sqrt{9}} = \dfrac{-1.5}{3}$$
$$ 1- \mathbf{\Phi}(z) \approx 0.6914$$
Where $\mathbf{\Phi}$ is the cumulative distribution function for the standard normal.
Comment: @whuber Yes, simulation is overkill in this scenario, however it instills a good habit in students and so that is why I include it.
Comment: +1.  Very clear.  BTW, a simulation is overkill here where the exact answer can more easily be found with brute force, as in `(function(n=20, p1=0.4, p2=0.3) sum((outer(dbinom(0:n, n, p1), dbinom(0:n, n, p2)))[outer(0:n, 0:n, \`-\`) > 0]))()`
Comment: Thanks for the answer. Where does (0+0.5) come from?
Comment: @AaronGibney  We are standardizing $B-A=0$.  The 0.5 comes from the continuity correction.
Comment: Thank you for the help, I understand now.


Can all or most combinatoric optimization problems in Machine Learning be solved using Viterbi algorithm?

Question: I am just scratching the surface of the topic but are there practical limitations even for Viterbi Algorithm? Also, are Viterbi Algorithm and dynamic programming equivalent?
Answer: The Viterbi algorithm solves the problem of finding the most likely latent states for given a hidden Markov model with known transition probabilities. This is a very specific problem, whereas dynamic programming is a very general methodology for solving combinatorial optimisation problems. For example, Dijkstra's algorithm for finding the shortest path in a graph uses a dynamic programming approach but it doesn't involve probabilities at all so it's not really equivalent to the Viterbi algorithm.
Combinatorial optimisation arises in many other areas, for instance Mixed-Integer linear programming problems can arise when you want to do variable selection in SVMs and linear models. These can be solved with branch-and-bound type algorithms.  Another example is that maximum a posteriori inference in Markov random fields can be formulated as a max-cut problem which is often solved with the Edmonds–Karp algorithm. The Edmonds-Karp algorithm is a greedy type algorithm.
You can probably reduce a given combinatorial optimisation problem to a problem with a standard dynamic programming solution but in general it won't always be the best approach. It may be instructive to look at the "no free lunch" type theorems.


Spring boot Data-JPA e JSF Java Config

Question: estou configurando um projeto usando o Spring boot para ioc e Data-Jpa junto com JSF contudo estou com um probleminha no @Autowired meu DAO não esta carregando.
Alguém sabe fazer essa configuração e onde posso estar errando?
Segue minha configuração:

Classe ApplicationConfig
@SpringBootApplication
@ComponentScan
public class ApplicationConfig extends SpringBootServletInitializer {

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
    return application.sources(ApplicationConfig.class);
}

@Bean
public ServletRegistrationBean servletRegistrationBean() {
    FacesServlet servlet = new FacesServlet();
    ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(servlet, "*.xhtml");
    return servletRegistrationBean;
}
}

Classe loginMbController
@ManagedBean(name = "login")
@Component
public class LoginMBController {

@Autowired
private CustomerDao customerDao;

public void test() {
    System.out.println("Hello");
    System.out.println(customerDao);
}
}

O customerDao
public interface CustomerDao extends JpaRepository<Customer, Long>{

}

O application.properties
# Show or not log for each sql query
spring.jpa.show-sql = true

# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto = update

# Datasource
spring.datasource.jndi-name=java:jboss/datasources/mysqlDS

Login.xhtml

<h:head></h:head>
<h:body>

    <h:outputText value="Login Page" />

<h:form>

</h:form>
</h:body>

e meu web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>CarlosSnackBar</display-name>
<welcome-file-list>
    <welcome-file>login.xhtml</welcome-file>
</welcome-file-list>
</web-app>

quando eu clico no botão "ok" no console aparece "hello null"
Comment: A injeção funciona em algum outro componente? Já tentou incluir *base package* ou *base package class* no *component scan* para certificar que o DAO esteja no contexto? Outro possível motivo é o MB estar apenas no contexto JSF, e não no Spring
Comment: Opa vlw Bruno, sim eu vou precisar injetar outros componentes e eu tentei colocar explicito no @componentScan o base package mas deu o mesmo problema. e como assim o MB não esta no contexto Spring?
Answer: Você tem que anotar seu DAO como um Repositorio do Spring Data.
@Repository
public interface CustomerDao extends JpaRepository<Customer, Long>{

}

Spring boot Data-JPA e JSF Java Config


If theory (in some logic) has 2 different models, are these models related in some other way?

Question: Let us assume, that we work in sound and complete logic. Let us assume that we have theory Th and 2 different models Mod1 and Mod2 that are interpretations of this theory Th. My question is - what we can say about how Mod1 is related to Mod2? E.g. one can imagine the interpretation of Th into topological spaces (it is possible for some logics), what can we say about the relation betwen the algebraic-topology invariants of those 2 models? Or is there any other, more modest results about relation between the models who are interpretations of the same theory?
Comment: See e.g. Kees Doets, [Basic model theory (CSLI, 1996)](https://books.google.com/books?id=qBjmwAEACAAJ&dq=Kees+Doets+Basic+model+theory&hl=it&newbks=1&newbks_redir=1&sa=X&ved=2ahUKEwih9s7Fqof4AhUvQ_EDHVj2BmUQ6AF6BAgIEAI), **Ch.2 Relations Between Models**
Comment: Does my answer address your question?
Comment: Thx, the answer gives the right path into the core of the problem, so, yes, it address my question directly. But I am still seeking (not quite actively though) the more specific answer with the following application in the mind: the collective of neurons of single layer of ("canonicalized") neural network can form the neural manifold and the set-subset structure in this manifold can be the (crisp of fuzzy) model of some (crisp or fuzzy theory) theory. Of course, there can be many such models for one theory and I thought that maybe they are related somehow. I will get back to your answer and...
Comment: ... and try to apply in my situation. Also - such neural manifold can not the exact model but the neural encoding of some exact model. Even more confusing.
Answer: I suspect you're thinking of complete theories; or, to put it another way, you're looking for a structural characterization of the relation of (first-order) elementary equivalence. Incomplete theories don't generally say much. For example, any two structures trivially satisfy the empty theory, and any two groups - however different - are models of the theory of groups.

Main answer
For simplicity let's restrict attention to structures in relational languages. In this case, there is in fact a good structural relation we can conclude, namely the existence of an appropriate "back-and-forth family."
We start with the notion of a partial isomorphism:

If $\mathfrak{A},\mathfrak{B}$ are structures in the same language, a partial isomorphism from $\mathfrak{A}$ to $\mathfrak{B}$ is an isomorphism $p:\mathfrak{A}'\cong\mathfrak{B}'$ with $\mathfrak{A}'\subseteq\mathfrak{A}$ and $\mathfrak{B}'\subseteq\mathfrak{B}$. We allow structures to be empty here, so that the empty map is always a partial isomorphism between any two structures.

An individual partial isomorphism is basically useless. What we care about are sets of partial isomorphisms with intereting "gluing" properties:

Given structures $\mathfrak{A},\mathfrak{B}$ in the same language and a linear order $L$, an $L$-back-and-forth-system for $\mathfrak{A}$ and $\mathfrak{B}$ is an indexed family $(P_l)_{l\in L}$ such that:

each $P_l$ is a nonempty set of partial isomorphisms from $\mathfrak{A}$ to $\mathfrak{B}$;

whenever $l<_Lm$, $p\in P_m$, and $a\in \mathfrak{A}$, there is a $q\in P_l$ with $q\supseteq p$ and $a\in dom(q)$; and

whenever $l<_Lm$, $p\in P_m$, and $b\in \mathfrak{B}$, there is a $q\in P_l$ with $q\supseteq p$ and $b\in ran(q)$.

(We can actually generalize this a fair bit, e.g. allow $L$ to be a partial order, but that's not super important right now.) Note that $L$-back-and-forth-systems, while not genuine functions, are still "function-like" in many ways; in particular, they can be composed in an appropriate way, and the relation "there is an $L$-back-and-forth system between" is an equivalence relation.
The two most important choices of $L$ here are $\mathbb{N}$ and $\mathbb{N}^*$ (= $\mathbb{N}$ with the opposite ordering). If there is an $\mathbb{N}^*$-back-and-forth system between $\mathfrak{A}$ and $\mathfrak{B}$, we say $\mathfrak{A}$ and $\mathfrak{B}$ are potentially isomorphic (and write "$\mathfrak{A}\cong_p\mathfrak{B}$"). It turns out that this is a very useful notion:

(Karp/Barwise) The following are equivalent for structures $\mathfrak{A},\mathfrak{B}$ in the same language:

$\mathfrak{A}\cong_p\mathfrak{B}$.

$\mathfrak{A}$ and $\mathfrak{B}$ satisfy the same sentences in the infinitary logic $\mathcal{L}_{\infty,\omega}$.

There is a forcing extension of the set-theoretic universe in which $\mathfrak{A}\cong\mathfrak{B}$.

Unfortunately, this overshoots our goal. First-order elementary equivalence corresponds to the usual ordering on $\mathbb{N}$:

(Fraisse) The following are equivalent for structures $\mathfrak{A},\mathfrak{B}$ in the same language:

$\mathfrak{A}\equiv\mathfrak{B}$ (= $\mathfrak{A}$ and $\mathfrak{B}$ satisfy the same first-order sentences).

There is an $\mathbb{N}$-back-and-forth system between $\mathfrak{A}$ and $\mathfrak{B}$.

(We can also talk - more intuitively, but less efficiently - in terms of games and strategies, the relevant term here being Ehrenfeucht-Fraisse games.) Besides being useful for analyzing specific structures and theories, Fraisse's theorem also is a key part of characterizing first-order logic as a whole system - see Lindstrom's theorem.
EF-games, and variations on the same (such as pebble games), are important in finite model theory; see Libkin, Elements of finite model theory.

Coda
Resisting the temptation to leave well enough alone, let me belatedly take this opportunity to say a bit about other logics' elementary equivalence analogue characterizations as well.
Let's start with second-order logic. In a sense, $\equiv_{\mathsf{SOL}}$ is reducible to $\equiv$ + powerset: every structure $\mathcal{M}$ has an associated "power structure" $\mathcal{M}^+$ with underlying set $\mathcal{M}\sqcup\mathcal{P}(\mathcal{M})$, such that $$\mathcal{M}\equiv_\mathsf{SOL}\mathcal{N}\quad\iff\mathcal{M}^+\equiv\mathcal{N}^+.$$ This can be used to tweak the back-and-forth characterization of first-order elementary equivalence to work for second-order logic: basically, we want to look at maps between sets of elements of the structures involved.
On the other hand, the infinitary logic $\mathcal{L}_{\omega_1,\omega}$ - just like $\mathsf{FOL}$ but with countable conjunctions and disjunctions allowed - has a more complicated elementary equivalence relation. The relation $\equiv_{\omega_1,\omega}$ does not correspond to the existence of an $\omega_1$-back-and-forth system; a game-style characterization of $\equiv_{\omega_1,\omega}$ was introduced by Vaanaanen and Wang, but it is more complicated - and in fact it turns out that in a precise sense it is harder for $\mathcal{L}_{\omega_1,\omega}$ to describe its own equivalence relation than it is for $\mathsf{FOL}$ or $\mathsf{SOL}$ (as far as I know this is due to Farmer Schlutzenberg, and extends to other infinitary logics as well).
There is also an important example of a class of logics defined via back-and-forth considerations: Shelah's recently-introduced $\mathbb{L}_\kappa^1$s, for $\kappa$ an appropriate uncountable cardinal. I don't know much about this, but it seems interesting and reinforces the importance of back-and-forth systems; see these slides of Villaveces.
Finally, note that the above are all examples of logics that are substantially stronger than $\mathsf{FOL}$; what about weaker logics? An interesting example is provided by equational logic (see these notes of McNulty). Birkhoff's HSP theorem gives a characterization of equational equivalence: we have $Th_\mathsf{EqL}(\mathcal{A})\subseteq Th_\mathsf{EqL}(\mathcal{B})$ (= every equation true in $\mathcal{A}$ is also true in $\mathcal{B}$) iff $\mathcal{B}$ is a quotient of a subalgebra of a power of $\mathcal{A}$. Put another way, a class of algberas is equationally axiomatizable iff it is closed under quotients, subalgebras, and products. Interestingly, an analogous result also exists for $\mathsf{FOL}$: the Keisler-Shelah theorem states that a class of structures is first-order axiomatizable iff it is closed under ultraproducts and ultralimits. However, while the original HSP theorem is easy to prove, Keisler-Shelah is quite difficult. One natural question here is whether analogous theorems exist for infinitary or higher-order logics. However, it's unclear what "analogous theorem" means exactly in this context.


showing fifth post in wordpress

Question: in my wordpress website how can start showing posts from fifth post?
Because in top of my website there is a slide show that shows title of first five posts
and again under slide show shows first five posts and it is not beautiful.
Answer: You can use either get_posts or query_posts as a means to show the most recent posts excluding the first five. Please keep in mind query_posts directly alters the main loop by changing the variables of the global variable $wp_query.
This kind of seems like what you want though so an example would be to modify the index file of your theme to include:
query_posts('posts_per_page=5&offset=5');

Note: You can change the posts_per_page to what ever you desire. You also have many more options available to you.
For more detailed information please see the following documentation :

http://codex.wordpress.org/Template_Tags/get_posts
http://codex.wordpress.org/Function_Reference/query_posts

TLDR: Use the offset parameter in WP_Query.
Answer: If you are familiar with PHP this code will solve your problem.
Setup a logic to not show data for first 5 post as follows:
$i = 0;
while (have_posts()) {
     ++$i;
     if ($i > 5) {
         the_title();
         // and more content
     }
}

This will show data inside loop only if $i > 5.

showing fifth post in wordpress


Harmonic or fundamental?

Question: I've always called the overtones one can play on, say, guitar, harmonics, but some say the fundamental is also a harmonic. Which means my 1st harmonic is their 2nd harmonic. Confusing - to both of us, at least.
Why would the fundamental (usually an open string, but could be anywhere) ever be termed the 1st harmonic, since in my mind a harmonic is a note produced by splitting the fundamental into integral parts?
Partials is another term that is heard - but all harmonics are partials, and not all partials are harmonics...the plot thickens.
Comment: …or does it just depend on whether you're using a zero- or one-based counting system? eg, in the UK if you go in the front door & up one flight of stairs you're on the first floor. In the US, you're on the second.
Comment: @Tetsujin Using your building and stairs analogy from what I've learned the UK is overtones and the US is harmonics. The first floor UK (overtone) is the second floor US (harmonic).
Comment: and what about instruments that produce inharmonic partials (timpani, gongs, marimbas, vibraphones, etc) or aperiodic sounds (cymbals, snakes, etc)?
Comment: @thrig Lot of these can actually be described by the sum of two harmonics series which can be written for instance (2,3) : second harmonic of the first fundamental mode and third of the second. Similarly the naming problem arises also. For completely inharmonic light white noise, the notion of overtones is irrelevant
Comment: "Carilloneurs have long observed that carillons are not well suited to contrapuntal writing" (David Huron, Voice Leading) so wedging not-harmonics into some harmonic system might be of dubious merit. Maybe doable if the partials are not too terrible, but then "nope" as things become more snake-like. Where the "nope" happens could depend on the culture or individual composer...
Comment: @Tetsujin - so, it's location dependent, bit like cadence naming?
Comment: I honestly have no idea - I was just being my usual flippant self ;))
Comment: @Tetsujin - but you may well be right - and flippancy is tolerated only in a modicum...
Comment: @Tetsujin Normally I'm all in favor of zero-based counting but in this case for a fundamental of `N` Hz, it would be kinda nice if the `n`th harmonic was `nN`.
Comment: Frequencies that you get by moving octave up and down are both harmonics. It's quite hard to count them with natural numbers, because those really need some kind of numbers with a sign (like, integers?) I never heard people using terms such as "minus first harmonic" though. As usual, better choose terminology you're comfortable with, and don't be shy to explain it to the person you use it with.
Answer: The standard terminology that I learned in school was that the octave is the first overtone, the second harmonic.  The numbering for harmonics is standard in physics, perhaps because it yields the convenient property that the frequency of the Nth harmonic is N multiplied by the fundamental frequency.  The numbering for overtones follows from the fact that the fundamental isn't higher than itself, so the second harmonic is the first one that can be described as an overtone.
The Wikipedia article is unfortunately light on source citations, but a web search such as harmonic vs overtone site:.edu turns up some relatively authoritative university physics materials.  I hesitate to link to any of these because of the possibility of link rot.
Another difference is that overtones may be non-harmonic (or "inharmonic"), as in a bell.
Answer: Yes, there are two systems of counting.   You'll see the  fundamental described as the first harmonic, you'll also see that label used for the first overtone, an octave above.  (Well, not necessarily an octave above, but that's a whole other topic.)
Both systems are currently used.  Same way that 'Middle C', MIDI note 60, 256Hz, is labelled 'C4' - unless you're Yamaha when it's 'C3'.
And here's a 'medical' tuning fork that thinks 512hz is 'C2'.
It's a jungle out there.
Comment: I learned something today: apparently a tuning fork can help diagnose broken bones (maybe a quick triage in lieu of an x-ray), by putting the fork and one end and a stethoscope at the other and seeing whether the bone transmits the pitch.
Comment: So much for a scientific approach. For C2, it should be at least a foot long.
Comment: That C2 was probably meant to be c'', using Helmholtz notation. Name C2 comes from scientific notation, and that's 3 octaves lower
Answer: A physicist might say:
If you try to excite for example a string under tension, at an arbitrary frequency – it probably won't generate a stable waveform.  However there are certain frequencies that will be stable.
The lowest frequency that will produce a standing wave on the string is called the 1st harmonic or fundamental frequency.
This is because this frequency will resonate "in harmony" with the system.
The next highest frequency that produces a standing wave is called the 2nd harmonic or 1st overtone.  Other energy levels that will generate a stable waveform are found with the harmonic series.
Superposition blah blah blah...

Harmonic or fundamental?