Overlapping sets (3) - significance test

Question: Sorry if this appears to be a naive question!
I have three overlapping sets and I want to find the probability of finding a larger/greater intersection for 'A intersect B intersect C' (in the example below, I want to find the probability of finding more than 135 elements that are common in sets A, B & C). For a two set problem, I guess I would do a Fisher or chi-square test. Here is what I have attempted so far:
<code>### Prepare a 3 way contingency table:
mytable <- array(c(135,116,385,6256,
                   48,97,274,9555),
                 dim = c(2,2,2),
                 dimnames = list(
                    Is_C = c('Yes','No'),
                    Is_B = c('Yes','No'),
                    Is_A = c('Yes','No')))

## test
mantelhaen.test(myrabbit, exact = TRUE, alternative = "greater")
</code>
Is this the right test (alongwith the current parameters) to determine what I want or is there a more appropriate test for this?
Comment: 1) No replacement within a draw. 2) Answer would be a probability of getting more than 135 balls that are common to all three drawings 3) The data is for significance of certain genes, but since that would add another layer of complication, I'd prefer to leave that out for now ;) Thanks for the replies!
Comment: Thank you. (1) Are the sets drawn with or without replacement?  (Obviously replacement occurs in between construction of the individual sets, for otherwise a null intersection would be assured.) (2) Presumably you want an answer in terms of the sizes of the sets or the sizes of the samples, right?  (3) Evidently this is a model for some kind of data collection problem. Could you tell us about the data?
Comment: OK. Just to make sure your question is answerable, then, it is *essential* that you know the total number of balls in the urn and that you know the sizes of the three sets. I am guessing from your `R` example that you know the latter, but can you verify that you also know the former?
Comment: Correct, the sizes of the three sets are known, and the total number of balls in the urn are also known.
Comment: Please tell us how these sets arise: without such information, we cannot determine an appropriate probability model and the question will not have any objective answers.
Comment: As a strawman argument, can we assume that the three sets are drawn from an urn containing numbered balls (numbered from 1 to ~17k). Each set is drawn independently. I guess the number '135' would represent the balls that were common in all the three draws/sets. Does that help? Thanks!
Answer: Let there be $n$ elements total with $a$, $b$, and $c$ in the subsets.  Consider $N$ already partitioned into $A$ and $N-A$.
The number of ways in which a $b$-element set can be drawn which has $l$ elements in common with $A$ is equal to the number of $l$-element subsets of $A$ times the number of $b-l$ element subsets of $N-A$:
$$\binom{a}{l}\binom{n-a}{b-l}.$$
Ensuant to that, the number of ways in which a $c$-element set can be drawn which has $m$ elements in common with $A\cap B$ is the number of $m$-element subsets of $A\cap B$ times the number of $c-m$-element subsets of $N-(A\cap B)$:
$$\binom{l}{m}\binom{n-l}{c-m}.$$
The total number of such choices of $B$ and $C$ is
$$\binom{n}{b}\binom{n}{c}$$
and they are all equally likely.  Summing over the possible values of $l$ gives the probability that the mutual intersection $A\cap B\cap C$ has exactly $m$ elements:
$$\Pr(m) = \frac{1}{\binom{n}{b} \binom{n}{c}}\sum _{l}\binom{a}{l} \binom{n-a}{b-l} \binom{l}{m} \binom{n-l}{c-m}.$$
(The sum extends over all values of $l$ that make sense; by defining $\binom{u}{v}=0$ whenever $v\lt 0$ or $v \gt u$, we do not need to indicate explicit endpoints.)

For instance, here is a plot of the central part of the probability distribution (comprising $99.99$% of the total) for $n=500, a=260, b=320, c=430$:

By summing these values from a particular value $m_0$ on up, we obtain the probability that the cardinality of the triple intersection equals or exceeds $m_0$.
In many practical applications, a Normal approximation to this sum works well.  As a demonstration, here are the log ratios of the true probabilities to those obtained with a Normal approximation.  (The Normal approximation uses the true mean $\mu$ and standard deviation $\sigma$ and estimates the probability of $m$ as $\Phi(\frac{m+1/2-\mu}{\sigma}) - \Phi(\frac{m-1/2-\mu}{\sigma})$ where $\Phi$ is the standard Normal CDF.)

The mean is near $143$ and the SD is near $5.9$.  (As usual, these are computed by summing $m$ and $m^2$, as weighted by the probabilities, to obtain the raw first and second moments, etc. I have not found a way to estimate either value a priori using simple formulas, but they can be estimated by computing probabilities for a small carefully-chosen selection of values of $m$ and fitting a Normal curve to them.)  Evidently, the approximation is excellent (in this case) within one SD of the mean, after which it starts decreasing, but even at three SD from the mean (i.e., around $125$ or $161$) it is still within one or two percent of the correct value.  For instance, the Normal approximation suggests the chance that $m \le 135$ is $0.939$ whereas the correct value is $0.928$.
In cases where there is a narrow range of possibilities of $m$, the distribution is far from Normal--but fortunately then the summations are short.  For instance, here is the distribution for $n=145, a=b=c=140$:

A simulation of $10^5$ independent instances of this situation tallies closely:
Comment: Whoa!! Thanks whuber!! It'll take me a little while to get through this completely, but thanks for taking the time and trouble!!
Comment: Thank you for such a detailed answer. I am wondering if you can elaborate more on how to iterate over l to get the sum ? I saw your another post where you iterate until min(n1,k) for two sets overlap case [https://stats.stackexchange.com/questions/14643/testing-significance-of-overlap-in-r].. I am wondering how to iterate l in this scenario. And also Pr(m) would be be Pr(overlap >=m)?
Comment: Is there a name for this test?


Unpacking and displaying JSON objects returned via jQuery from Django backend

Question: A part of my application takes in some ingredients then spits back relevant recipes. I am trying to convert it to use only AJAX. I'm running into problems parsing the data coming back in JSON and accessing it for use on the front end.
My code in the Django views.py looks like this:
recipes = Recipe.objects.all() #shortened to all objects for example purposes
import simplejson
data = ''
for r in recipes:
        the_date = r.date_created.strftime("%b %d")
        recipe_dict = { 'id' : r.id,
                    'name' : r.name,
                    'user' : r.user.username,
                    'date_created' : the_date,
                    'votes' : r.votes,
                    'slug' : r.slug }
        data += simplejson.dumps(recipe_dict)+'\n'

        return HttpResponse(data)

My javascript looks like this:
//request an updated list of recipes with AJAX
$.get('/recipes/discover', { 'ingredients': ingredients },

    //display these new relevant recipes
    function(recipes){
        $.each(recipes, function() {
                $("#results").append("
"+ this.name +"
");
        })
    })
    .complete(function(){ $('#loading_spinner').fadeOut(1000); })
});

The output I've been getting with this way ends up giving me a new li for what appears to be each character of the JSON response... so .each() is going through each character.
I also tried using jQuery.parseJSON(data); before running each, but this only seems to work when there is only one JSON recipe returned. I am thinking I have something formatted incorrectly in the JSON, or I'm parsing it incorrectly?
Thanks in advance!
Answer: You need to separate objects in JSON with a comma, and enclose arrays within [].
It looks like your returned JSON would look something like:
{'name': ... }{'name':...}

And it should look like:
[{'name': ... },{'name':...}]

That's why a single recipe would parse correctly since it's a valid JSON object, but multiples don't work.
If it is valid JSON, jQuery.parseJSON(...) will work correctly.
Here is a JSON Reference.


Back propagation in seq2seq models

Question: I've implemented a seq2seq model for character-based text mirroring as a part of Udacity's Deep Learning class (here's the code).
My model is very basic because it's a single LSTM as both encoder and decoder. You can see that it performs rather poorly (it only managed to learn how to mirror the first few characters of text).
But I can't extend it to two LSTM's because it's confusing to me how backprop should work with such architecure. We don't have labels to get the errors for encoder states. Is it necessary to somehow compute gradients manually at the encoder's output and back-propagate it further, or Tensorflow's graph will handle it automatically?
Answer: Well here we don't take the errors in encoder time steps. What we do is we transform all the time step information in to a vector representation where it can help to generate correct labels in encoder side.
The gradient method is simple. It's same as how we take gradients in standard RNN. But here we start to propagate gradients from decoder side only.
The method is called the back propagation through time. You can understand that clearly in Chis Olah's amazing blog. Also read about the this amazing article on seq2seq model by google
Comment: Thank you very much. So in LSTM encoder-decoder, only the decoder part got backpropagated! I have always been confused.

Back propagation in seq2seq models


How to create a pop-up when exiting a view?

Question: So I'm making a photo editing app for school from last semesters project. When a user clicks the back button (in editor mode) which in my case is called "Product Selection" I'd like to have a pop-up come up and say "Do you want to delete everything and go back to product selection?" to see if they want to discard their work, and if the user selects yes, the entire project is discarded and they are put back in the lobby.
Where do I put this code to do this? I found the "Product Selection" button in the min story board but not sure what to do from there.
The code for the pop-up I was going to use is:
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Notification"
message:@"Do you want to delete everything and go back to product selection?" delegate:self cancelButtonTitle:@"No" otherButtonTitles:@"Yes"];
    [alert show];
    [alert release]

Any help/wisdom would be extremely appreciated!
Answer: I would create a "Cancel" UIBarButton which executes a custom function:
- (void)cancelTapped {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Notification" message:@"Do you want to delete everything and go back to product selection?" delegate:self cancelButtonTitle:@"No" otherButtonTitles:@"Yes"];
    [alert setTag:1];
    [alert show];
}

And listens for the alert to return on:
- alertView:didDismissWithButtonIndex:
From there, I would write the logic to hide the page and pop the view.
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if (alertView.tag == 1 && buttonIndex == 1) {
        // Delete data and return to lobby
        [self.navigationController popViewControllerAnimated:YES];
    }
}

Comment: Good suggestion @LyndseyScott! I have made the changes accordingly.
Comment: I like your solution (and your edits) @Ramon, but one suggestion for @user3275721… I'd add a tag to the alert so that the didDismissWithButtonIndex action is performed specifically in response to that alert.
Comment: I have a idea as well. What if I hide the "Product Selection" button just on the editor page and show the "Cancel" button as stated above?  But what file/location would I do this?
Comment: Why use tags? Just store the UIAlertView in a property and compare objects. A lot more robust than an arbitrary tag.
Answer: Use this delegate method (don't forget adding UIAlertViewDelegate on your .h):
 UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Notification" message:@"Do you want to delete everything and go back to product selection?" delegate:self cancelButtonTitle:@"No" otherButtonTitles:@"Yes"];
 alert.cancelButtonIndex = 0;

[alert show];

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{

    // If user confirmed:
    if (buttonIndex != 0) {

   // Do what you need.
   }
}


If meta key's value is x then echo

Question: I have 3 pieces of code that essentially should do the same thing, but none of them are working and they are all echoing "Not Working!".
The meta key is wilcity_belongs_to and the value is 2980. These are all based on what plan a listing is on. So if the listing plan is value 2980 then it must echo "Working!".
$meta = get_post_meta( get_the_ID(), 'wilcity_belongs_to',true );
if( $meta == '2980' ) {
    echo "Working!";
} else {
    echo "Not Working!";
};

and
global $wpdb;
$wpdb->get_results( "select * from $wpdb->wpam_postmeta where meta_key = 'wilcity_belongs_to' " );
if ( $wilcity_belongs_to == '2980') {
    echo "Working!";
} else {
    echo "Not Working!";
};

and
if ( get_post_meta( $post->ID, 'wilcity_belongs_to', true ) == '2980' ) {
    echo "Working!";
} else {
    echo "Not Working!";
};

Here is a screenshot of what is in the database: Database
This is in Table: wpam_postmeta
Please could i get help on this, ive been trying everything.
Comment: Did you verify the actual value of `$meta`? `var_dump($meta);`
Comment: Ive never used var_dump before so i added it in both echo's and got a return of Not Working!bool(false) so not sure whats wrong then
Comment: 1 - Enable WordPress Debugging With WP_DEBUG, WP_DEBUG_LOG in the wp-config.php
Comment: @SiavashEbrahimi Thank you, i got this: WordPress database error You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'where meta_key = 'wilcity_belongs_to'' at line 1 for query select * from  where meta_key = 'wilcity_belongs_to'  made by require_once('wp-load.php'), require_once('wp-config.php'), require_once('wp-settings.php'), include('/themes/wilcity-childtheme/functions.php')
Comment: Table $wpdb->wpam_postmeta not exists ! Check the table name
Comment: What does `var_dump( get_the_ID() )` returns? Are you getting meta value within loop? `get_post_meta` will return `false` if id is not correct
Comment: @IharAliakseyenka got a false there too, but dont know why it is so
Comment: @SiavashEbrahimi i checked database and wpam_postmeta is the right table in the database
Comment: My guess you get it out of the loop as `get_the_ID` [returns](https://developer.wordpress.org/reference/functions/get_the_id/) (int|false) The ID of the current item in the WordPress Loop. False if $post is not set. Need information where are calling `get_post_meta` (which template, is it within loop or not). Also you may try to use `get_queried_object_id()` instead
Comment: @Ryan I think $wpdb->wpam_postmeta is not registered. you must write it like this : $wpdb->prefix . 'wpam_postmeta'
Comment: The first example will only work if inside the loop. #2 will only work if you update your code to `$wpdb->postmeta`  or `{$wpdb->prefix}postmeta`, or `wpam_postmeta`.  #3 will only work if `$post` global is defined.  Since you're only including brief snippets of code, it will be difficult for someone to give you a good answer here.
Answer: Did you try this way? get_results() usually returns an array with the result set.
global $wpdb;
$result = $wpdb->get_results( "select * from $wpdb->wpam_postmeta where meta_key = 'wilcity_belongs_to' " );
foreach ($result as $row) {
   if ( $row["wilcity_belongs_to"] == '2980') {
       echo "Working!";
   } else {
       echo "Not Working!";
   };
};

Comment: Still got a Not Working! echo
Comment: @Ryan sry... get_results() returns an array of results. i added a foreach()
Comment: Thank you for the help, but unfortunately now it isnt echoing anything

If meta key's value is x then echo


Hbase ipc.RpcServer responseTooSlow issue and region server goes down

Question: I have configured Hbase 1.2.6 with Hadoop 2.7.4. I have configured Nutch on it.
Following are two Hbase-site properties
<property>
  <name>hbase.rpc.timeout</name>
  <value>1200000</value>
  <description>Changed to 20 minutes</description>
</property>

<property>
  <name>hbase.client.scanner.timeout.period</name>
  <value>1200000</value>
  <description>Changed to 10 minutes</description>
</property>

When I start a job. After some time following warning started and region servers goes down. That's why Job is also failed.
2017-12-22 17:39:25,660 WARN  [B.defaultRpcServer.handler=18,queue=0,port=16020] ipc.RpcServer: (responseTooSlow): {"call":"Scan(org.apache.hadoop.hbase.protobuf.generated.ClientProtos$ScanRequest)","starttimems":1513946351644,"responsesize":8238,"method":"Scan","param":"scanner_id: 65 number_of_rows: 2147483647 close_scanner: false next_call_seq: 5 client_handles_partials: true client_handles_heartbeats: true track_scan_metrics: false renew: false","processingtimems":14015,"client":"10.11.21.42:36388","queuetimems":0,"class":"HRegionServer","scandetails":"table: use_webpage region: use_webpage,com.blogsky.shayan-pix:http/category/cat-2,1513328565609.09e0aff4d1e1d0e5733825c90f289be5."}
2017-12-22 17:39:37,626 WARN  [B.defaultRpcServer.handler=24,queue=0,port=16020] ipc.RpcServer: (responseTooSlow): {"call":"Scan(org.apache.hadoop.hbase.protobuf.generated.ClientProtos$ScanRequest)","starttimems":1513946357681,"responsesize":8654,"method":"Scan","param":"scanner_id: 64 number_of_rows: 2147483647 close_scanner: false next_call_seq: 5 client_handles_partials: true client_handles_heartbeats: true track_scan_metrics: false renew: false","processingtimems":19945,"client":"10.11.21.42:56252","queuetimems":0,"class":"HRegionServer","scandetails":"table: use_webpage region: use_webpage,ir.persianblog.gae6:http/,1509943454203.6992fa37fa94574aa4797b9ae64a296b."}

Answer: Notice the locality for that region. If the locality is low do a region compaction for that particular region. If that doesn't fix this, run Major Compaction for that table. You can see that the locality for almost all regions becoming 1. This worked for me.


Condição de saída no do-while em código C

Question: Preciso que o usuário insira os números 1, 2 ou 3 para escolher as localidades, e se não selecionar uma delas, perguntar de novo.
Porém ao inserir o número 0 ou 4, por exemplo, ele volta na tela inicial (que seria o menu, de destinos, custos e sair).
Preciso que ele diga "Informe um codigo de cidade valido" e questione de novo um dos três números.
O que fiz de errado?
printf("Selecione a opcao desejada:\n 1 - Destinos \n 2 - Custos \n 3 - Sair\n");
    scanf("%d", &op);
    switch(op) {
        case 1 : printf("\n1 - Destinos:\n\n Codigo da cidade      Valor da passagem por pessoa\n\n");
                 printf(" 1 - Nova York    ===>      R$3.231,00\n");
                 printf(" 2 - Londres      ===>      R$3.789,00\n");
                 printf(" 3 - Dubai        ===>      R$4.932,00\n\n");
                 printf("Informe o numero de seu destino\n");
                 scanf("%d", &destino);
                 if (destino <= 0 && destino > 3) {
                 do{
                 printf("Informe um codigo de cidade valido.\n");
                 scanf("%d", &destino);
                 } while (destino <= 0 && destino > 3);
                 }

Comment: É impossível um valor ser <= 0 e simultaneamente > 3. Reveja a definição dos operadores lógicos && e ||.
Comment: A resposta resolveu sua dúvida? Acha que pode aceitá-la? Veja o [tour] se não souber como faz. Isso ajudaria muito indicar que a solução foi útil para você. Também pode votar em qualquer pergunta ou resposta que achar útil no site todo.
Answer: Isso?
printf("Selecione a opcao desejada:\n 1 - Destinos \n 2 - Custos \n 3 - Sair\n");
scanf("%d", &op);
switch(op) {
case 1:
    printf("\n1 - Destinos:\n\n Codigo da cidade      Valor da passagem por pessoa\n\n");
    printf(" 1 - Nova York    ===>      R$3.231,00\n");
    printf(" 2 - Londres      ===>      R$3.789,00\n");
    printf(" 3 - Dubai        ===>      R$4.932,00\n\n");
    printf("Informe o numero de seu destino\n");
    scanf("%d", &destino);
    while (destino < 1 || destino > 3) {
         printf("Informe um codigo de cidade valido.\n");
         scanf("%d", &destino);
    }

Coloquei no GitHub para referência futura.
Comment: Só explicitando, a ideia principal foi a troca do operador lógico `&&` pelo operador `||` (já que o usuário deve entrar com os dados novamente se o `destino` escolhido for menor que 1 **ou** maior que 3).
Comment: Eu não expliquei porque sequer sei se é o que a pergunta pede. Se eu tiver certeza, aí eu posso complementar.


Customizing the Stars Image for Ajaxful_Rating RoR plugin

Question: I'm trying to come up with my own star image that's slightly smaller and different style than the one provided in the gem/plugin, but Ajaxful_rating doesn't have an easy way to do this.  Here's what I've figured out so far:

The stars.png in the public folder is three 25x25 pixel tiles stacked vertically, ordered empty star, normal star, and hover star.
I'm assuming as long as you keep the above constraints, you should be fine without modifying any other files.
But what if you want to change the image size of the stars to larger or smaller?
I've found where you can change the height in the stylesheets/ajaxful_rating.css
.ajaxful-rating{
   position: relative;
   /*width: 125px; this is setted dynamically */
   height: 25px;
   overflow: hidden;
   list-style: none;
   margin: 0;
   padding: 0;
   background-position: left top;
}
.ajaxful-rating li{ display: inline; }
.ajaxful-rating a,
.ajaxful-rating span,
.ajaxful-rating .show-value{
   position: absolute;
   top: 0;
   left: 0;
   text-indent: -1000em;
   height: 25px;
   line-height: 25px;
   outline: none;
   overflow: hidden;
   border: none;
}

You just need to change every place that says "25px" above to whatever height your new star image is.  This works fine but doesn't display the horizontal part correctly.  Anyone know where I would look to set the horizontal part as well? (I'm assuming it's in an .rb file somewhere based upon how many stars you specified in your ajaxful_rating setup)
Answer: Nevermind, I'm stupid.
In the lib/axr/stars_builder.rb, find the following:
<code>def ratings_tag
  ......
  @css_builder.rule('.ajaxful-rating', :width => (rateable.class.max_stars * 25))
  ....
end
</code>
Change the 25 to your new width.


How GCP denies like AWS does at OU level?

Question: I am wondering how one can prevent access in GCP from Folder level. AWS has concept of OU and SCP (policies) to e.g. deny (intersect) permissions at lower level resources. Now, if GCP is allow-only and additive how can I prevent that users do not get access to certain resources within the Projects?
Also refer to this: GCP equivalent of "deny" permissions in aws policy
thanks.
Comment: You can assign rights at the project level or the resource level. Let's assume that you want to allow Bob to only access to Compute Engine VM A. Do not give Bob permissions to GCE at the project, give him access at the resource (VM A). Instead of trying to show "theory", create a real example of what you need to accomplish. GCP and AWS are so different in how IAM is implemented; do not attempt to compare them.
Comment: thanks but your example does not answer the question. You describe basic IAM process in GCP. That was not my point.
Comment: I did not provide an answer; I provided a comment to help you improve your question.
Comment: is this a comment to improve the question: "You can assign rights at the project level or the resource level. Let's assume that you want to allow Bob to only access to Compute Engine VM A. Do not give Bob permissions to GCE at the project, give him access at the resource (VM A)." ??
Answer: In GCP, The effective policy for a resource is the union of the policy set at that resource and the policy inherited from its parent (project, folder or organization).
You can configure restrictions on how your resources can be used with the help of Organization policy Service

The Organization Policy Service gives you centralized and programmatic
  control over your organization's cloud resources. As the organization
  policy administrator, you will be able to configure restrictions
  across your entire resource hierarchy.
Comment: ok thanks. But it looks to me that GCP and AWS behave differently in how they propagate policies down the hierarchy. GCP "allow" type rules apply a merge, AWS applies an intersection. So for the "allow" type rules to me looks that AWS is bit more safe. You can be sure that "allow" rules never grow going down the hierarchy. Even more: in GCP you can disable inheritance "inheritFromParent" to FALSE so that Org Policy will no propagate. I think you cannot force that in AWS..


Python - percorrer uma lista - substituir palavra dentro do word (.docx)

Question: Bom dia!
Preciso de um auxílio...
Tenho um arquivo word, com nome de 'teste.docx'.
Gostaria de substituir cada termo dentro dele por strings que estão numa lista. Veja exemplo.
O problema que está ocorrendo é que a alteração não está entrando em loop.
Podem me ajudar? Obrigado desde já!

----x----
from docx import Document

caminho = 'D:\\Users\\89614879\\Desktop\\Nova pasta\\'
arquivo = 'teste.docx'
docword = caminho + arquivo

doc = Document(docword)

lista = [['111','adm','Pedro Paulo'],['222','cont','Luiz Carlos'],['333','econ','Jorge Fernando'],['444','jorn','Claudia Leite']]
qtd_linhas = len(lista)
qtd_colunas = len(lista[0])

nome_arq = ['Pedro Paulo', 'Luiz Carlos', 'Jorge Fernando','Claudia Leite']

for i, paragrafo in enumerate(doc.paragraphs):
    palavra = '<' + str(i) + '>'
    if palavra in paragrafo.text:
        for x in range(qtd_linhas):
            for y in range(qtd_colunas):
                paragrafo.text = paragrafo.text.replace(palavra, str(lista[x][y]))
                new_docword = caminho + nome_arq[y] + '.docx'
                doc.save(new_docword)

Answer: Seu código está quase bom, só algumas coisas que estão invertidas.
A lógica é a seguinte, primeiro, faça o for na lista, pois cada elemento da lista significa um novo arquivo que você vai gerar. Em cada iteração, aplique as substituições no arquivo inteiro e salve o arquivo, antes de começar novamente com novo arquivo e novas substituições:
import os
from docx import Document

caminho = r'D:\Users\89614879\Desktop\Nova pasta'
arquivo = 'teste.docx'
docword = os.path.join(caminho, arquivo)

lista = [['111','adm','Pedro Paulo'],['222','cont','Luiz Carlos'],['333','econ','Jorge Fernando'],['444','jorn','Claudia Leite']]
nome_arq = ['Pedro Paulo', 'Luiz Carlos', 'Jorge Fernando','Claudia Leite']

for novo_nome, substituicoes in zip(nome_arq, lista):
    doc = Document(docword)
    for paragrafo in doc.paragraphs:
        for i, substituicao in enumerate(substituicoes):
            palavra = '<' + str(i) + '>'
            if palavra in paragrafo.text:
                paragrafo.text = paragrafo.text.replace(palavra, substituicao)
    new_docword = os.path.join(caminho, novo_nome + '.docx')
    doc.save(new_docword)

Comment: nosklo, agradeço sua atenção. Obrigado pela orientação.


Is there a built-in function in SQL, which can tell if an existing row has been modified in the last 24 hours?

Question: In my application (C# application, using Entity-Framework and SQL Database), I am needed to create a daily task to update/insert data from a third-party application (both the applications are using SQL server database). For efficiency sake, I am looking for a way to determine what all records from the previous day have been modified and thus import only those records.
I know I can add a modified_on column to the source table and create a trigger to update that column when something is changed on that record, but that will need me to make changes to the third-party application's database schema which I want to avoid.
Comment: if **you** don't store the date, no one does :)
Comment: @DaleK sure point taken :)
Answer: There's the change tracking feature but it's of limited use to you as you're using EF and that makes the way the data is queried awkward. You may be able to use it somehow, but I doubt it's elegant.
Way easier is to indeed change the schema but add only a single column of type rowversion. That binary datatype (loaded as byte[] in EF) is special and gets larger every time something (such as the third-party application) updates the row. No need for any triggers. You can look what the largest one is you already processed and then query all those that are larger than that.
Comment: Thanks, I will look into the option of a column of type `rowversion`.
Answer: In addition to change tracking suggested by John, in another answer, you can think of setting up Temporal tables.
You can run queries against the temporal tables to identify the changed records and pull them accordingly from main table.


Relative density word problem

Question: So I am having a issue with this problem and cant see a way of solving it.

The world discus champion is temporarily living on a planet which has half the radius of the Earth. He discovers that he can throw the discus 10 times further than he can on Earth. Estimate the relative density of this planet compared to that of Earth. Ignore any effect of air resistance.

My initial assumption is that the discus is thrown in the air vertically and I could calculate the K.E of throwing up in the air.
So kinetic energy from earth
$v^2=u^2-2gy$
$u=\sqrt{2gy}$
$K.E=\frac{1}{2}m_\text{disc}2gy=m_\text{disc}gy$
but here my issue I was thinking of using gravitational potential to setup the following equation.
$gy=\frac{-GM_{p}}{r_{E}+y}$
but that my issue, because of the negative it make no sense to me how you can approach this question another way, to form a numerical solution.
Have I overlooked something?
Answer: They are probably ignoring the fact that the discus gets lift from the air and considering it a projectile.  They then talk about distance thrown, which is maximized when the launch angle is $45^\circ$.  You should determine by what factor the acceleration of gravity has to change to make the distance covered increase by a factor $10$.  Lowering $g$ will let the discus stay in the air longer, so it will cover more ground.
Then note that the surface gravity of a planet scales as the product of the radius and the density.  You are told that the radius is cut in half, so you need to get the rest of the factor out of the density.
Comment: Ah thank you. This question buggin me for the better part of half the day, and I got stuck in mind set.

Relative density word problem


How do I add comments to a YAML webform?

Question: I would like to add comments to the Sourcecode of my webforms in YAML.
# comment (without quotes).
But when I save this, it automatically gets removed.
20_e_mailadres:
  '#type': email
  '#title': E-mailadres
# write a comment here
21_werkmail:
  '#type': email
  '#title': werk E-mailadres

How do I add comments to a YAML webform so they are kept when I save?
Comment: Is this a feature request? Then it should be posted to the mentioned module's issue queue on drupal.org, not here on Drupal Answers.
Comment: You also shouldn't prefix your elements with numbers, always start with letters instead. I'm currently working on a project where this has been done and now I can't access these element's information in Twig because variables must not start with numbers.
Comment: Afaik comments are removed from any config yml on import and export. This is true for any config. I've used a workaround with migrations where I save a copy of the yml with my comments in a separate folder (custom module) so they can be referenced later. The problem is the developer has to make sure to update them whenever they update the yml.
Comment: I believe it's a "how to"? I can't imagine this isn't possible. To make the YAML-code more readable, it should be possible no?
Comment: You tell us what it is, but currently there is no question, just stating facts. Maybe update your question for clarification and also include what you've tried so far. When it's about YAML for reading data I think that would be no problem. But this YAML is also used to store data and then I guess it's a bit difficult to write a submit handler intelligent enough to distinguish between comments belonging to an element that got removed maybe or a new element that's been added maybe. So the program needs to read and handle the data before storing the updates. Difficult.
Answer: Context

Drupal 8.x
Webform module
YAML comments

Use-case

developer KoenC wishes to add comments to a YAML file and have those comments retained upon save

Problem

Per the YAML specification, comments are specified as "throwaway" artifacts.
This means that YAML commments are not required to be preserved by parsers that implement the YAML specification

Workaround

Metadata and comments can be added as separate YAML nodes (see e.g., https://stackoverflow.com/a/8565238/42223)
Answer: Comments are not supported in the YAML source because the YAML is decoded and reencoded every time an element is updated.
On my todo list is to add support for '#admin_notes' to each element which could be used to store 'comments'. For now, you could add a '#comment' property to any element.
@see Issue #3165328: Add support for #admin_notes to webform elements


Learn to sing, how can I improve my singing?

Question: I am looking for constructive opinions about my singing. Is it almost in pitch but transposed? And why does everyone tell me that when I sing it's not beautiful?
Listen
https://voca.ro/lYFphCkKo2T (you can leave you hat on)
https://voca.ro/7ZrxCCGhFMC (fais comme loiseau)
Comment: It sounds like you are holding back, afraid to sing out loud. Never mind what the neighbors say, practice like they are not there ;-) If you sing in a room that has some reverb, it will iron out the minor pitch deviations and give you more confidence. Don't let anyone tell you that you are "tone deaf", after some practice and experimentation with your voice you will pick up the pitch sooner or later. It's more about overcoming fear than being able to hear in most cases.
Answer: Forget about being in tune or not.  Your voice does not sound supported by your diaphragm so the quality of sound is very poor.  It sounds weak and inconsistent.  Some of this could be a bad recording since your voice sounds like it's going in and out.  If you are not currently taking lessons then that is the bast way to improve your singing, take lessons and learn how to use your core to support your voice.  It also sound compressed like you are not resonating in your sinuses.  Again, lessons would help.  People don't know what they are hearing they only know if they like it or if it sounds musical.  Your voice does not sound musical.  It sounds like you are talking in a sing-song like manner and that is not really singing.
Answer: The pitch is very inaccurate here. Even without knowing the song I can tell it's out of tune because the intervals you're singing are all over the place. But I listened to the song to give you precise advice.
Let's take your key. You sang (approximately):
fais -> com -> me-l' -> oiseau
A -> A -> B -> D#
It should be, in your key:
A -> A -> C# -> E (assuming the first and second notes are meant to be the same)
Now, the A you started on wasn't an accurate A; you were about half way between A and A#. But you didn't have an accompaniment so that doesn't matter too much.
From "fais" to "com", you sang A to A. I don't know if that were intentional, but the original song goes up 5 semitones between 'fais' and 'com'. In other words, if I assume your "com" is the right note, A, then the notes are E -> A -> C# -> E. The "fais" is very short, so maybe you did that stylistically, I don't know.
The gap from "com" to "me-l'" you sang an interval less than 2 semitones (sharp A to slightly less sharp B). The original has a 4 semi tone gap.
From "me-l'" to "oiseau" you sang slightly less than 4 semitones (sharp B to D#), but the "oiseau" you sang went higher and higher up another semitone to E. The original has 3 semitones here.
Because of how inaccurate it is, and also how your tone is not great, a teacher is the way to go. Self teaching will be very hard. BUT, I understand not everyone can afford that so if you really want to work at home... learn to sing a major chord. So that's C E G. Or in this key it's A C# E. "fais comme l'oiseau" just opens on a major chord. If you can sing a major chord, you can sing the first words of this song. Download a piano app, play C, E, G and sing the notes, up and down.
Answer:
And why does everyone tell me that when I sing it's not beautiful?

Because it's not in tune. Pure and simple. If the first note is in tune then every other note is out of tune with that first note and with all the other notes.
If you can't hear this yourself then it may be that you are tone deaf. There is an online test for this here. Whether or not it is any good is difficult for me to say. I tried it and scored 100% (i.e. not tone deaf) but it is inconceivable to me that anybody could do the test and not score 100% in the same way that I can't conceive how somebody who is red-green color blind can't tell the difference between red and green, this despite the fact that one of my brothers is red-green color blind.
Comment: But is it just transposed but i sing the good relative pictches ? Or not ?
Comment: Not, I'm afraid. None of the notes are in tune with their neighbors.
Comment: Ok thanks for the response. But does I changed too much or not enough my demitones, in general ? What can I do to improve ?
Comment: And... Are my notes I sing in my records out of tune more than one tone, generally ? How many demitones do I sing out of tune ?
Comment: For information, I got 100 percent to the test. But it does not say me how many demitones i am out of tune in my records... and in sang just higher or lower but maybe not the good intervals between each notes''' ?
Comment: You could use software like melodyne to analyse your recordings. It can tell you how much your intonation is off. But like ggcg already mentioned, there is much more to singing than hitting the right notes.


Rewriting Django template {% for %} into a Model method

Question: I have existing code that works:
{% for author in seminar.authors.all %}
{{ author.first_name}} {{ author.last_name }}
{% if forloop.last %}{% else %}, {% endif %}
{% endfor %}

As you may have guessed, seminar.authors is a m2m field. Generic, nothing special.
I know how to write Model methods, but im not sure how to properly loop through each author item per seminar object and apply a comma if the current iteration is all but last.
Would it be alright to name this Model method get_author_display? Im not sure if this clashes with Django's built-in get_*_display.
furthermore, I'd love to support a few forloop.last conditions:

1 author name = no comma or "and"
2 author names = comma
3 or more author names = commas w/ "and" prepending the last author name.

but in an elegant manner. Ideas?
Answer: Are you sure your second extra requirement is correct? Surely with just two names you want "and" and no comma?
Anyway, there's nothing particularly difficult about this. The trick is to get the queryset's length first - note that it's actually more efficient to use len rather than .count() here, because count() on an unevaluated queryset does a separate call to the database.
def get_author_display(self):
    authors = self.authors.all()
    length = len(authors)
    output = []
    for i, author in enumerate(authors):
        val = "%s %s" % (author.first_name, author.last_name)
        if i == (length-1) and length > 2:
             val = "and " + val
        output.append(val)
    return ', '.join(output)

And no, there's nothing wrong with calling the method that: authors will never have CHOICES set, so won't get an automatic get_foo_display method.
Comment: Wow. That would have taken me a while to find myself. I think an adjustment needs to be made to the last line, as im getting output with ", and" e.g. "Katherine Fulton, Richard Rockefeller, and Larry Brilliant".


How to run the same query on all the databases on an instance?

Question: I have (for testing purposes) many dbs with the same schema (=same tables and columns basically) on a sql server 2008 r2 instance.
i would like a query like
SELECT COUNT(*) FROM CUSTOMERS

on all DBs on the instance. I would like to have as result 2 columns:
1 - the DB Name
2 - the value of COUNT(*)
Example:
DBName  //   COUNT (*)

TestDB1 // 4

MyDB  // 5

etc...

Note: i assume that CUSTOMERS table exists in all dbs (except master).
Comment: Get `sp_ineachdb` (articles on it [here](https://www.mssqltips.com/sqlservertip/5686/execute-a-command-in-the-context-of-each-database-in-sql-server-using-spineachdb/) and [here](https://www.mssqltips.com/sqlservertip/5694/execute-a-command-in-the-context-of-each-database-in-sql-server-part-2/); download [here](https://github.com/BrentOzarULTD/SQL-Server-First-Responder-Kit/blob/dev/sp_ineachdb.sql)).
Answer: Try this one -
    SET NOCOUNT ON;

    IF OBJECT_ID (N'tempdb.dbo.#temp') IS NOT NULL
       DROP TABLE #temp

    CREATE TABLE #temp
    (
          [COUNT] INT
        , DB VARCHAR(50)
    )

    DECLARE @TableName NVARCHAR(50)
    SELECT @TableName = '[dbo].[CUSTOMERS]'

    DECLARE @SQL NVARCHAR(MAX)
    SELECT @SQL = STUFF((
        SELECT CHAR(13) + 'SELECT ' + QUOTENAME(name, '''') + ', COUNT(1) FROM ' + QUOTENAME(name) + '.' + QUOTENAME(@TableName)
        FROM sys.databases
        WHERE OBJECT_ID(QUOTENAME(name) + '.' + QUOTENAME(@TableName)) IS NOT NULL
        FOR XML PATH(''), TYPE).value('text()[1]', 'NVARCHAR(MAX)'), 1, 1, '')

    INSERT INTO #temp (DB, [COUNT])
    EXEC sys.sp_executesql @SQL

    SELECT *
    FROM #temp t

Output (for example, in AdventureWorks) -
COUNT       DB
----------- --------------------------------------------------
19972       AdventureWorks2008R2
19975       AdventureWorks2012
19472       AdventureWorks2008R2_Live

Comment: Hi Devart, i am using this sql and works great. But is it possible to add a check if the user running this query has access to each database or not and if not, the query should still continue to run and return only the databases the user has access to. What I am after is whether the user has DBO role permission on each of the database and if not move onto next one.. please can you advise.
Comment: @Charliface, this has stopped working for me with the latest revision.
Comment: The best method which I've ever seen.
Answer: Straight forward query
EXECUTE sp_MSForEachDB
        'USE ?; SELECT DB_NAME()AS DBName,
        COUNT(1)AS [Count] FROM CUSTOMERS'

This query will show you what you want to see, but will also throw errors for each DB without a table called "CUSTOMERS". You will need to work out a logic to handle that.
Raj
Comment: It probably worth mentioning that the sp_MSForEachDB is undocumented, unsupported, and has some known issues as discussed by Aaron Bertrand here https://sqlblog.org/2020/05/12/bad-habits-to-kick-relying-on-undocumented-behavior
Comment: +1 it is a very compact solution but i choose the other since your solution crates  many result tables, while the other not
Answer: How about something like this:
DECLARE c_db_names CURSOR FOR
SELECT name
FROM sys.databases
WHERE name NOT IN('master', 'tempdb') --might need to exclude more dbs

OPEN c_db_names

FETCH c_db_names INTO @db_name

WHILE @@Fetch_Status = 0
BEGIN
  EXEC('
    INSERT INTO #report
    SELECT
      ''' + @db_name + '''
      ,COUNT(*)
    FROM ' + @db_name + '..linkfile
  ')
  FETCH c_db_names INTO @db_name
END

CLOSE c_db_names
DEALLOCATE c_db_names

SELECT * FROM #report

Comment: You have forgotten in the script to declare [at]db_name, you need to add one line: DECLARE @db_name NVARCHAR (150), otherwise very useful script :-)
Comment: This is a useful general snippet, I just replaced `sys.databases` with `sys.tables` for a very different purpose, using the same boilerplate.
Comment: Where is the temp table delcared?
Comment: @Phil3992 you're right it should be added, but it would just be a two column table with a name as VARCHAR and a count as INT.
Answer: declare @userdb_list table (name varchar(4000) not null);
-- fill the db list with custom subset
insert into @userdb_list
select name from sys.databases --can add where condition to filter db names

declare
@curr_userdb varchar(300),
@db_placeholder varchar(300),
@final_db_exec_query varchar(max),
@query varchar(max);
set @query = '' --  <add ur query here>

set @db_placeholder = 'use {db}';
set @curr_userdb = (select min(name) from @userdb_list);

while @curr_userdb is not null
begin
set @final_db_exec_query = replace(@db_placeholder, '{db}', @curr_userdb +  '  ' + @query);
exec (@final_db_exec_query);
--print @final_db_exec_query
set @curr_userdb = (select min(name) from @userdb_list where name > @curr_userdb);
end
GO

Solution without cursor - clean and simple
Answer: Because I know that a question was just referred to here that asked a slightly different question... if you only want to execute on certain databases, those databases could be stored in some table. Here I stored in a temporary table.
CREATE TABLE #Databases (
DbName varchar(255))

INSERT INTO #Databases (DbName)
Values ('GIS_NewJersey'), ('GIS_Pennsylvania')

DECLARE @command varchar(1000)

SELECT @command = 'Use [' + DbName + '];
Update sde.SAP_Load
    SET FullAddress =  CONCAT_WS('','', HouseNumber, Street, City, Postal, RegionName)
    Update sde.PREMISE
    SET FullAddress =  CONCAT_WS('', '', HouseNumber, Street, City, Postal, RegionName)
    Update sde.PREMISE_GEOCODE
    SET FullAddress =  CONCAT_WS('', '', HouseNumber, Street, City, Postal, RegionName)'
FROM #Databases

EXEC @command


Capturar nome de um Estado (uf) e uma imagem

Question: Boa noite a todos.
Eu tenho uma imagem do Brasil com seus estados:

Como faço, caso eu clique na imagem do estado de São Paulo, preencher este nome em um campo text.
<code><input type="text" name="uf" id="uf"  value="">
</code>
Agradeço desde já ajuda.
Comment: Em que formato está essa imagem? é um SVG?
Answer: Para poderes saber onde clicas o melhor é ter um SVG que tem elementos para cada região e o JavaScript pode saber onde o clique ocorreu.
Para caprat isso podes fazer assim, por exemplo:
A estrutura do SVG (exemplo de SVG copiado daqui):
<code> <g>
    <a xlink:href="#tocantins">
    ... etc
</code>
e o jQuery
<code>$('svg a').on('click', function(e) {
    e.preventDefault();
    var id = this.getAttributeNS('http://www.w3.org/1999/xlink', 'href').slice(1);
    $('input').val(id);
});
</code>
Exemplo online: https://jsfiddle.net/jaxzw33k/1
Comment: funcionou direitinho! Obrigado mesmo, hj durmo tranquila. Grata


Problema de encoding no composer

Question: Atualmente o meu arquivo do composer começou a apresentar alguns erros nas mensagens que parecem erros de encoding, alguém já passou por isso e sabe como resolver? Dei uma pesquisada pra ver se achava algo mas não encontrei nenhuma resposta a respeito disso.
Segue a imagem para mostrar como está vindo o restorno:

Alguém sabe como é possível resolver esse problema?
Comment: Qual seu sistema operacional? Outras ações no prompt não dão erro de encoding? Só acontece com o composer?
Comment: Estou usando windows 10 com o anniversary update, acontece apenas com o composer...
Answer: O problema ocorre devido a última atualização do Windows 10 (Anniversary Update) que causou esse erro de encoding. Se usar o Powershell do cmd ficará tudo certo.
Então a melhor solução é aguardar uma nova atualização que corrija esse problema.

Problema de encoding no composer


Using AVAudioPlayer with Dynamic URL in Swift 3 causing Thread Errors

Question: I am new to Swift and making an audio app using AVAudioPlayer. I am using a remote URL mp3 file for the audio, and this works when it's static.
For my use case, I want to pull a URL for an mp3 file from a JSON array and then pass it into the AVAudioPlayer to run.

If I move the AVAudioPlayer block into the ViewDidLoad and make the mp3 file a static URL, it will run fine.
Then, when I move this code into my block that extracts an mp3 url from JSON, I can print the URL successfully. But when I pass it into my audio player, problems arise. Here's the code.
override func viewDidLoad() {
super.viewDidLoad()

    let url = URL(string: "http://www.example.com/example.json")
        URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in
            guard let data = data, error == nil else { return }

            let json: Any?
            do{
                json = try JSONSerialization.jsonObject(with: data, options: [])
            }
            catch{
                return
            }

            guard let data_list = json as? [[String:Any]] else {
                return
            }
            if let foo = data_list.first(where: {$0["episode"] as? String == "Example Preview"}) {

                self.audiotest = (foo["audio"] as? String)!
                print(self.audiotest) // this prints

                // where i'm passing it into the audio player
                if let audioUrl = URL(string: self.audiotest) {

                    // then lets create your document folder url
                    let documentsDirectoryURL =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

                    // lets create your destination file url
                    let destinationUrl = documentsDirectoryURL.appendingPathComponent(audioUrl.lastPathComponent)

                    //let url = Bundle.main.url(forResource: destinationUrl, withExtension: "mp3")!

                    do {
                        audioPlayer = try AVAudioPlayer(contentsOf: destinationUrl)

                    } catch let error {
                        print(error.localizedDescription)
                    }
                } // end player

// ....

Specifically, I get an error Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value when clicking a play button IBAction that is connected to the audio player. Finally, that action function looks like this:
  @IBAction func playPod(_ sender: Any) {
    audioPlayer.play()
}

Do you know where I'm going wrong? I'm confused as to why I can't print the URL and also get a response that the URL is nil in the same block, but maybe that's an asynchronous thing.
Answer: The problem is that you didn't save the mp3 file to documents and trying to play it
this line
    audioPlayer = try AVAudioPlayer(contentsOf: destinationUrl)

assumes that there is a saved mp3 file in that path , but acutally there is no files you appended the audio extension on the fly
besides for steaming audio from a remote server, use AVPlayer instead of AVAudioPLayer.
AVPlayer Documentation
Also try this with urls parsed from json
  var urlStr = (foo["audio"] as? String)!

  self.audiotest = urlStr.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)

Comment: Hey, I verified your answer. I added a download button in the previous view controller. What's cool is that by targeting that URL in the second VC (as shown above), it now knows to find it in the bundle which I thought was going to be hard. Much appreciated!
Comment: Interesting. I do save it in a previous view but maybe I am having an issue accessing. Do you have a sense of why it would play outside the block (when I make the URL the same but hard code it in as a value rather than responding to the var)? That's what I don't get.
Comment: is there any space in the https path


Desabilitar um botão no asp.net MVC

Question: Estou desenvolvendo uma aplicação que gerencia inscrições em cursos, ainda sou aprendiz no asp.net MVC, e estou com a seguinte dúvida:
Na minha tela de cursos tem um botão de "inscrição" para os cursos listados nessa tela. Gostaria de saber como eu faço para desabilitar o botão quando o usuário se inscrever, ou seja, clicar em "inscrição" e também não permitir a inscrição dele novamente no mesmo curso.

Detalhe: Esse botão também decrementa a quantidade de vagas.
Segue código do decremento.
public ActionResult Confirmacao(int? id)
    {
        using (var scope = new TransactionScope())
        {
            Curso curso = new Curso();

            curso = db.Cursos.Include(x => x.Aluno).AsNoTracking().FirstOrDefault(f => f.Id == id);

            curso.Qtd_Vagas--;
            db.Entry(curso).State = EntityState.Modified;
            db.SaveChanges();

            scope.Complete();
        }

        return View(db.Cursos);
    }

Aqui o Ajax onde chamo a Action

HTML Razor
@model IEnumerable<MeuProjeto.Models.Curso>

Lista de Cursos

            Curso

            Sigla

            Ementa

            Inicio

            Fim

            Turno

            Status

            Quantidade de Vagas

    @foreach (var item in Model)
    {

                @Html.DisplayFor(modelItem => item.Nome_Curso)

                @Html.DisplayFor(modelItem => item.Sigla)

                @Html.DisplayFor(modelItem => item.Ementa)

                @Html.DisplayFor(modelItem => item.Dt_Inicio)

                @Html.DisplayFor(modelItem => item.Dt_Fim)

                @Html.DisplayFor(modelItem => item.Turno)

                <input type="text" name="Status" id="Status" value="@Html.DisplayFor(modelItem => item.Status)" readonly class="Status" />

                @Html.DisplayFor(modelItem => item.Qtd_Vagas)

                        <input type="submit" value="Inscrição" id="inscricao" name="inscricao" class="btn btn-success" data_toggle ="modal", data_target="#modalaviso" />

    }

    <input type="button" value="Voltar" class="btn btn-danger" />

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")

}

Answer: Aqui tem um problema enorme:

                    <input type="submit" value="Inscrição" id="inscricao" name="inscricao" class="btn btn-success" data_toggle ="modal", data_target="#modalaviso" />

Pela definição do HTML, atributos id devem ser únicos. É a maneira que temos para identificar unicamente um componente da sua tela. Portanto, inserir dentro de um foreach vários botões com o mesmo id está errado.
Troque:

    <input type="submit" value="Inscrição" id="inscricao" name="inscricao" class="btn btn-success" data_toggle ="modal", data_target="#modalaviso" />
...

Por:

    <input type="submit" value="Inscrição" class="inscricao btn btn-success" name="inscricao" data_toggle ="modal", data_target="#modalaviso" />
...

class é o atributo HTML usado para identificar componentes da tela com alguma característica em comum, e que pode ser repetido livremente. Um componente pode ter, inclusive, várias classes.
Como você está usando Ajax, basta usar um callback para o evento success, trocando o antigo id por class:

Veja mais sobre o seletor .inscricao aqui.
Comment: Não funcionou @Cigano, é só acrescentar esse trecho de código abaixo?
Comment: Não. Você precisa readequar o código à necessidade da sua tela, testar, verificar se o *callback* é acionado.
Comment: Você tem algum exemplo? Pra eu ter uma noção de como fazer?
Comment: Coloque na sua pergunta o HTML do Razor, por favor. Só assim eu posso ter uma ideia de como ativar o botão corretamente.
Comment: Coloquei o HTML @Cigano.
Comment: @Novato Atualizei a resposta.
Comment: Não funcionou @Cigano. Não sei se é porque tem algo de errado no meu código de decremento, porque para o botão inscrição decrementar eu tô tendo que passar o número do Id na URL. Exemplo: Curso/Inscricao/1  assim ele funciona, caso eu entre na pagina Curso/Inscricao sem passar o Id não funciona.

Desabilitar um botão no asp.net MVC


dropdown (select box) get Name of selection

Question: I have this code on Fiddle Code
I have the picture portion of my code working, where it will change picture every time you select a value.
What I want to display is the actual Name " Image 1 " of the value.. so Image 1 etc.
I went through stackoverflow and found some examples, and I tried to implement them but i can't get it to work.
So in short, when you select an a value... it will show picture and in the empty div it will show the name
$(document).ready(function() {

   $("#image").change(function() {
     $("#imagePreview").empty();
        $("#imagePreview").append("");
   }).change();
 });

$('#image option:selected').text(); {

   $( "div" ).text( str );
}

<select name="image" id="image" class="inputbox" size="1">
   <option value="imageall.jpg" selected> - All - </option>
   <option value="image1.jpg">image1.jpg</option>
   <option value="image2.jpg">image2.jpg</option>
   <option value="image3.jpg">image3.jpg</option>
</select>

   displays image here

EDIT:  Something like this : EXAMPLE
Comment: Really got confused about what you are asking..? can you add some bit more details to it..?
Comment: I want to get the NAME of the selected element to APPEAR beside the picture.

SO when picture show up below it will write Image 1 and the name will change with every change in options

why downgrade something you don't understand?
Answer: Try,
$(document).ready(function () {
    $("#image").change(function () {
        $("#imagePreview").empty();
        $("#imagePreview").append("");
        $("div:last").text($('option:selected', this).text());
    }).change();
});

DEMO
Comment: what does the div:last do?  if you remove last what happens? it seems to duplicate like crazy?
Comment: @op1001 As per the demo you have provided, we have to display the text into the last div right..? that's why I had used the `:last` selector out there.. The better option would be add an id to the displayer div and replace its id with `div:last`..   something like this http://jsfiddle.net/c93MB/6/
Comment: Like this right?  http://jsfiddle.net/c93MB/8/

if you take last out it just repeats and repeats

like this http://jsfiddle.net/c93MB/9/ weird.


Banco de dados não identificado: "No database selected"

Question: Estou fazendo um arquivo de carrinho de compras. O código aparentemente está correto, mas ao incluir o arquivo de conexão com o banco, o navegador exibe a mensagem "No database selected".
Obs: Tanto o arquivo, denominado "Pedido.php", quanto o de conexão com o banco (conexão.php) estão no mesmo diretório.
Aqui está o código:

    <?php
        include 'conexao.php';
        session_start();

        if(!isset($_SESSION['carrinho'])){
            $_SESSION['carrinho'] = array();
        }

        //ADICIONA PRODUTO

        if(isset($_GET['acao'])){

            //ADICIONA CARRINHO

            if($_GET['acao'] == 'add'){

                $id = intval($_GET['id']);
                if(!isset($_SESSION['carrinho'][$id])){
                    $_SESSION['carrinho'][$id] = 1;
                }else{
                    $_SESSION['carrinho'][$id] += 1;
                }
            }

        }

    ?>

Carrinho de compras

                Produto
                Quantidade
                Preço
                Subtotal
                Remover

        <form action="?acao=up" method="POST">

            <input type="submit" value="Atualizar carrinho"/>

            Continuar comprando

            <?php

                if(count($_SESSION['carrinho']) == 0){
                    echo '
Não há produtos no carrinho
';
                }

                else{

                    foreach($_SESSION['carrinho'] as $id => $qtd){

                        $sql     = "SELECT * FROM produto WHERE id= '$id'";
                        $result  = mysql_query($sql) or die (mysql_error());
                        $produto = mysql_fetch_assoc($result);

                        $nome    = $produto['nome'];
                        $preco   = number_format($produto['preco'], 2, ',', '.');
                        $sub     = number_format($produto['preco'] * $qtd, 2, ',', '.');

                        echo '

                                    '.$nome.'
                                    <inpu type="text" size ="3" name="produto['.$id.'] value="'.$qtd.'">
                                    '.$preco.'
                                    '.$sub.'
                                    Remover

';
                    }

                }

            ?>

        </form>

Answer: No seu arquivo de conexão, voce precisa informar o nome do banco de dados. Aqui tem um exemplo:

<?php
$conn = mysql_connect("localhost", "root", "123");
$db = mysql_select_db("dados", $conn);
$query = mysql_query("SELECT * FROM clientes");
?>

Uma dica: Procure atualizar o seu código e utilizar MySQLi ou PDO
http://blog.thiagobelem.net/guia-pratico-de-mysqli-no-php
Answer: Essa parte eu coloquei no próprio arquivo "conexao.php":

exec("set names utf8");
}catch(PDOException $e){
    echo "Erro ao conectar com o MySQL:".$e->getMessage();
}

?>

<?php
$conn = mysql_connect("localhost", "root", "123");
$db = mysql_select_db("dados", $conn);
$query = mysql_query("SELECT * FROM clientes");
?>


modificar chosen e ckeditor

Question: Chosen
Como modificar o valor data-placeholder: através do javascript
ex:
<select data-placeholder="Para:" name="cd_aluno[]"id="cd_aluno"  multiple class="chosen-select">

alterar o data-placeholder com o js
CKEditor
Como desabilitar o textarea do ckeditor (disabled)
Ex:
<textarea id="editor1" class="form-control" name="email" rows="15"style="margin-top: 2px;"></textarea>

document.getElementById("editor1").disabled = true;

Answer: Para alterar o data-placeholder, use o .data() do JQuery:
$('#cd_aluno').data('placeholder', 'novo valor');

Para desabilitar o CKEditor (torná-lo somente leitura), você pode configurá-lo na inicialização, definindo a opção de configuração CKEDITOR.config.readOnly para true. Por exemplo:
config.readOnly = true;

Outra forma é definir o atributo disabled para o elemento <textarea> que o CKEditor substitui. Veja esse exemplo, que permite habilitar e desabilitar o modo somente leitura do CKEditor.

modificar chosen e ckeditor


A `Concatenate` layer requires inputs with matching shapes except for the concat axis Keras

Question: I am new to deep learning and coding.
I am trying to concatenate the categorical embedding layer with numeric features to fit into the model for multi-class classification. However, even I tried to Reshape the input, the layers cannot be concatenated. Any help is high appreciated.
Here is my audio input:
# fill in the 31 features grabbed from the original data set
audio_input = Input(shape=(31,), name='audio_features')
audio_input = Reshape((1,31))(audio_input)

Here is my embedded layer, reference1, reference2:
time_signature_input = Input(shape=(1,), name='time_signature')
time_signature_embedded = Embedding(train.time_signature.max()+1, min(600, round(1.6 * time_signature_size**0.56)), input_length=1, name='time_signature_embedded')(time_signature_input)

When I tried to concatenate:
concatenated = Concatenate()([cats,audio_input])
out = layers.Flatten()(concatenated)

I got the error:
A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got inputs shapes: [((None, 1, 6),(None, 1, 31)]

Answer: Try this,
audio_input = Input(shape=(31,), name='audio_features')
time_signature_input = Input(shape=(1,), name='time_signature')

nb_unique_classes = train.time_signature.max()+1
embedding_size = min(600, round(1.6 * time_signature_size**0.56))

time_signature_embedded = Embedding(nb_unique_classes , embedding_size , input_length=1, name='time_signature_embedded')(time_signature_input)
time_signature_embedded = Reshape(target_shape=(embedding_size,))(time_signature_embedded)

model_layers = concatenate([time_signature_embedded] + [audio_input])


Do I really need twho different Exchange servers 2007|2010?

Question: Given am Exchange Server 2003 running on a dedicated server on a LAN protected by a Linux in DMZ, Microsoft says that if you upgrade, you should install two different servers (meaning two boxes, two licenses of Windows Server and two installations of Exchange) with different Exchange "server role".
Exchange is installed in a safe LAN, there is a Linux relay in DMZ that feeds messages to Exchanges and gets from it the messaged to be delivered on the Net (smart relay).
The mail traffic is about 2000 Internet messages/day and probably another 2000 msg/day sent by local users within the organization. The servers hosts 200 users.
Answer: We just deployed Exchange 2010 with single server & configured the hub role to be Internet facing as per this info: link text
Comment: +1 antispam and other edge-features can be added to the hub transport role in single-server scenarios
Answer: No you don't - your Linux relay is performing the main function of the Exchange Edge server.
Sure an Exchange server would have more functionality (but not necessarily performance), but it is pretty easy to add Spam Assassin/ClamAV... to a Linux server to replicate some of its features.
Comment: Thank you! There already are SA, ClamAv, amavis and some Postfix rules (rbl, helo check, sender domain check) on Linux machine.


How to create Block configuration form

Question: I am new to drupal. I have created a block from module using hook_block_info() and hook_block_view(). This block will be used as front page image slideshow. So I want to provide text fields in the configuration page of that block where user can add Image files for slideshow.
What is the process of creating configuration form for the block. I searched online but couldn't understandable solution. Thanks!
I am using Drupal 7
Answer: You can create block configuration page using hook_block_configure().
where you can create form with your required field like textfield, file etc.
function demo_block_configure($delta = '') {
    $form = array();
    if ($delta == 'demo') {
        $form['demo_number'] = array(
            '#type' => 'textfield',
            '#title' => t('Number of nodes you want the block to show'),
            '#default_value' => variable_get('demo_number', 10),
            '#size' => 60,
        );
    }
    return $form;
}

function demo_block_save($delta = '', $edit = array()) {
    if ($delta == 'demo') {
        variable_set('demo_number', $edit['demo_number']);
    }
}

now you can get this variable using variable_get function
$no_of_block = variable_get('demo_number');

you can see this page in configuration of your block
Answer: You could take a look at the Examples module this provides code examples of various different api implementations, including block forms. The code your looking for is in the block module. All the examples are working so you can play around with them on a test Drupal 7 site if you want.
Answer: You need to create a custom module for this. The module will create a database table that will store the image file path. The module will also provide an admin interface (drupal form) with a file field. When the admin uploads image and submits form, you need to store the file path in the database table you created. Now in hook_block_view() you need to iterate through every file path and render it as slideshow.
There is an alternate solution to your problem which will be more usable.

Create a content type with an image field. Now create nodes of that
  content type and upload images. Use views_slideshow module to
  display the nodes of the content type. Since it is a view, therefore
  you will be able to display it as a block and place it anywhere.

Hope the above solution will be more useful.

How to create Block configuration form


Accessing website from two ports - Apache config

Question: I have a website setup and want to be able to access the same site from two different ports.  Does anybody know how I would do this?
For example, I want to be able to access exactly the same at http://example.com:5678 as I can at http://example.com:80.  I had tried fiddeling with virtualHosts in my httpd.conf from what I read on forums and the docs but couldn't figure it out - any ideas?
Also, how would I be able to make it work for http://domain1.com:80 shows the same as http://domain2.com:5678? (for both where domain1 and domain2 are hosted on same server)
Does WHM/cPanel support this (other than domain parking)?  If not, how would I change my apache to do this?
Thanks
Sam
Updated
I am not sure that you understood.  I have a virtualHost set up and want that to be accessible from two different ports, showing exactly the same.  Here is my virtual host currently.
<VirtualHost 188.8.131.52:80>
    ServerName example.co.uk
    ServerAlias www.example.co.uk
    DocumentRoot /home/example/public_html
    ServerAdmin email@example.com
    UseCanonicalName Off
    CustomLog /usr/local/apache/domlogs/example.co.uk combined
    CustomLog /usr/local/apache/domlogs/example.co.uk-bytes_log "%{%s}t %I .\n%{%s}t %O ."
    ## User example # Needed for Cpanel::ApacheConf
    UserDir enabled example
    <IfModule mod_suphp.c>
        suPHP_UserGroup example example
    </IfModule>
    <IfModule !mod_disable_suexec.c>
        <IfModule !mod_ruid2.c>
            SuexecUserGroup example example
        </IfModule>
    </IfModule>
    <IfModule mod_ruid2.c>
        RUidGid example example
    </IfModule>
    ScriptAlias /cgi-bin/ /home/example/public_html/cgi-bin/

    # To customize this VirtualHost use an include file at the following location
    # Include "/usr/local/apache/conf/userdata/std/2/example/example.co.uk/*.conf"

</VirtualHost>

Answer: You can specify multiple binding addresses and ports in VirtualHost.
Change
<VirtualHost 18.104.22.168:80>

To
<VirtualHost 18.104.22.168:80 18.104.22.168:5678>

You will also need to specify the port outside of the VHost, so your config might look something like this:
Listen 80
NameVirtualHost 22.214.171.124:80

Listen 5678
NameVirtualHost 126.96.36.199:5678

<VirtualHost 184.108.40.206:80 220.127.116.11:5678>
    ServerName example.co.uk
    ServerAlias www.example.co.uk
    DocumentRoot /home/example/public_html
    ServerAdmin firstname.lastname@example.com
    UseCanonicalName Off
    CustomLog /usr/local/apache/domlogs/example.co.uk combined
    CustomLog /usr/local/apache/domlogs/example.co.uk-bytes_log "%{%s}t %I .\n%{%s}t %O ."
    ## User example # Needed for Cpanel::ApacheConf
    UserDir enabled example
    <IfModule mod_suphp.c>
        suPHP_UserGroup example example
    </IfModule>
    <IfModule !mod_disable_suexec.c>
        <IfModule !mod_ruid2.c>
            SuexecUserGroup example example
        </IfModule>
    </IfModule>
    <IfModule mod_ruid2.c>
        RUidGid example example
    </IfModule>
    ScriptAlias /cgi-bin/ /home/example/public_html/cgi-bin/

    # To customize this VirtualHost use an include file at the following location
    # Include "/usr/local/apache/conf/userdata/std/2/example/example.co.uk/*.conf"

</VirtualHost>

Update for your question:
If you want domain1.com:80 and domain2.com:5678 to display the same content, but do not want domain1.com:80 and domain2.com:800 to be the same...then you will need to seperate the vhosts.
<VirtualHost 22.214.171.124:80>
ServerName domain1.com
ServerAlias *.domain1.com
</VirtualHost>

<VirtualHost 22.214.171.124:5678>
ServerName domain2.com
ServerAlias *.domain2.com
</VirtualHost>

Comment: is what you are saying then that I don't need to use:

          `ProxyRequest Off;
          ProxyPass / http://example.co.uk:5678/;
          ProxyPassReverse / http://example.co.uk:5678/;`

?
Comment: No, you don't need them from what I can tell from your question.
Comment: Thanks - that seems to work.  As you can see from the example, it says do not edit because it is automatically generated by WHM/cPanel.  Any idea on how I would add this stuff in more permanently so cPanel doesn't get rid of it?  Thanks.
Comment: I don't have much experience with that, sorry. I don't know that you will get much of a response here either. I would suggest posting a new question now that your config is okay, tailored specifically towards cPanel.
Answer: If it's the same domain name just add:
Listen 5678

In the same location you have
Listen 80

Comment: thanks, but it says I can't put that into my VirtualHost.  See above update to post.


LilyPond: Combine parts when identical, but split into staves when different

Question: I'm arranging the second movement of Ravel's Ma mere l'Oye for recorder ensemble. There are two parts for tenor recorder, and I'd like to combine them into one written part. Sometimes, the two parts are identical, and sometimes, they're different enough that it would be awkward to put them on one staff. However, they won't fit on a single page if I use two staves throughout.
Is there a way to combine the parts so that they will share a single staff when the parts are identical, but use separate staves when the parts differ?
Answer: The LilyPond installation contains a file input/regression/divisi-staves.ly that shows an example of how to achieve Divisi staves that will split more complex music into multiple systems temporarily while extending the split to the line breaks.
Documentation of that feature is unfortunately awfully lacking, so you need to go by example.
\version "2.19.13"

\header {
  texidoc = "The @code{VerticalAxisGroup.remove-layer}
property can be used for typesetting temporary divisi staves where
the switch to split staves is done only at line breaks such that all
complex passages are rendered in separate staves."
}

boring = \set Staff.keepAliveInterfaces = #'()
tricky = \unset Staff.keepAliveInterfaces

violI=\relative d' {
  \boring \repeat unfold 100 d4
  \tricky <d g'>2
  \boring \repeat unfold 98 d4
  \bar "|."
}

violII=\relative g {
  \boring \repeat unfold 100 g4
  \tricky <g d'>2
  \boring \repeat unfold 98 g4
  \bar "|."
}

\score {
  \new StaffGroup \with { \consists "Keep_alive_together_engraver" }
  <<
    \new Staff \with { instrumentName = "Violin I"
               shortInstrumentName = "V I"
               \override VerticalAxisGroup.remove-empty = ##t
               \override VerticalAxisGroup.remove-first = ##t
               \override VerticalAxisGroup.remove-layer = 1
             }
    \violI
    \new Staff \with { instrumentName = "Violin II"
               shortInstrumentName = "V II"
               \override VerticalAxisGroup.remove-empty = ##t
               \override VerticalAxisGroup.remove-first = ##t
               \override VerticalAxisGroup.remove-layer = 1
             }
    \violII
    \new Staff \with { instrumentName = "Violins"
               shortInstrumentName = "V I&II"
               \override VerticalAxisGroup.remove-layer = 2
             }
    <<  \violI \\ \violII  >>
  >>
  \layout {
    short-indent = 2\cm
    indent = 3\cm
  }
}


Random walk on white faces of a soccerball

Question: Suppose you do a random walk on the 20 white (hexagonal) faces of a soccer-ball.
https://commons.wikimedia.org/wiki/File:Soccerball.svg
At each time step you go back to and adjacent white face, selecting the adjacent faces at random with equal probability.
What is the expected number of steps until you return to the original position?
I believe the answer is 20, the same as the number of white faces.
A harmonic function on a finite graph must be constant or have at least two poles, so the only stationary distribution gives all the faces equal probability of 1/20.  The expected return time is thus 1/(1/20).
Comment: Perhaps not everyone knows the tiling associated with soccer balls, might be a good idea to describe it.  Ideally, since you only care about the white hexagons, describe the associated graph.
Comment: Sketch:  draw the graph associated with the hexagons  (it's got $20$ vertices, and an edge between two means that the two hexagons share a border).  Let $E_i$ be the expected number of moves given that you start on $i$.  Then, if hexagon $i$ borders hexagons $j,k,l$ we have $E_i=1+\frac {E_j+E_k+E_l}3$ where, to abuse notation a bit, $E_*$ on the right is now $0$ if $*$ is the special hexagon.  Easy to solve that system (at least with a machine).
Comment: Note:  the symmetries greatly speed the computation.  For instance, the three hexagons bordering $*$ all have the same expectation, so you don't need anything like $20$ separate variables.
Answer: This is a comment (so please don't downvote)... but includes figures.
The soccer ball is a truncated icosahedron:

With this net (without the white/black distinction).

Here is its graph of edges:

In Mathematica:
<code>Graphics3D[PolyhedronData["TruncatedIcosahedron", "Faces", "Polygon"]]

PolyhedronData["TruncatedIcosahedron", "Net"]

GraphData["TruncatedIcosahedralGraph"]
</code>
Comment: The graph associated with the random walk described in the question is actually that of a regular dodecahedron.


User session and https

Question: I've got a few pages on my site that need to be accessed via https.
I need to pull some information about the current logged user on those pages.
The problem is, users log using http mode and the session is not kept when switching from http to https.
I've looked into secure login module but it brings some other issues (with facebook connect...)
Is there any way we can tell the cookie to persist ?
Thanks in advance
Comment: Are you using secure pages or similar module?
Answer: Add $conf['https'] = TRUE; to settings.php.
from here:
http://drupal.org/node/1037542
and
http://drupal.org/https-information
however, why not just run the whole site securely?
Comment: This is a good read: http://drupal.org/node/1131986

you could hack in a function to copy the sessions `sid` value to `ssid`, but I don't think that's a good idea due to security concerns.
Comment: Thanks for your reply, I added $conf['https'] = TRUE; my session is still lost between http and https, it's actuall killing my session. Once I click on a https link and come back to http, my session is lost.

User session and https


Trying to change the scale of a health bar using collider and it does not register

Question: This is the code for the Player game object  i am trying to damage a game object when it collides with another game object and transform the scale of a healthbar, extra text because i am receiving an error saying i am putting too much code and too little writing on my question so here we go i guess.
public class PlayerMovement : MonoBehaviour
{
    public float moveSpeed;
    public Rigidbody2D rb;
    private Vector2 moveDirection;
    bool facingRight = true;
    public static float healthAmount;

    void Start()
    {
        healthAmount = 1f;
        rb = GetComponent<Rigidbody2D>();
    }

    void OnTriggerEnter2d(Collider2D col)
    {

        if (col.gameObject.tag == "Bat")
                   healthAmount = -0.1f;

    }

    void Update()
    {
        ProcessInputs();

        if (healthAmount <= 0)
        {
            Destroy(gameObject);
        }

    }

    // movement math
    void FixedUpdate()
    {
        Move();
    }

    void ProcessInputs()
    {
        float moveX = Input.GetAxisRaw("Horizontal");
        float moveY = Input.GetAxisRaw("Vertical");

        moveDirection = new Vector2(moveX, moveY).normalized;

        if (moveX < 0 && facingRight)
        {

            Flip();

        }
        else if (moveX > 0 && !facingRight)
        {

            Flip();
        }
    }

    void Move()
    {

        rb.velocity = new Vector2(moveDirection.x * moveSpeed, moveDirection.y * moveSpeed);

    }

    void Flip()
    {

        facingRight = !facingRight;
        transform.Rotate(0f, 180f, 0f);

    }

}

and this is the code for the health bar

public class HealthBarS : MonoBehaviour
{

    Vector3 localScale;

    void Start()
    {
        localScale = transform.localScale;
    }

    void Update()
    {
        localScale.x = PlayerMovement.healthAmount;
        transform.localScale = localScale;
    }
}

Comment: Can you specify the wrong behavior? Is is about collision not happening? Or maybe incorrect scaling? Did you try debugging or reading the docs on OnTriggerEnter2d?
Comment: the issue is that when the Bat enemy which has the Bat tag on it collides with the Player character the healthAmount does not get reduced.
Answer: From what I understand you need the PlayerMovement instance, not the class. Also make sure the bat object's collider is marked as trigger. Try this:
public class HealthBarS : MonoBehaviour
{

    Vector3 localScale;
    PlayerMovement playerMovement;

    void Start()
    {
        playerMovement = FindObjectOfType<PlayerMovement>();
        localScale = transform.localScale;
    }

    void Update()
    {
        localScale.x = playerMovement.healthAmount;
        transform.localScale = localScale;
    }
}


Como abrir uma tela com formulário pré preenchido com PHP e HTML?

Question: Boa noite a todos,
eu gostaria de saber como abrir um formulário cujos campos já estejam previamente preenchidos com os dados do usuário(resultantes de uma pesquisa no banco de dados), ficando a cargo dele somente editar as informações. Pesquisei na internet e encontrei uma forma, mas seria gerando o HTML do formulário todo via comando echo do PHP; entretanto li que isso não é uma boa prática de programação... há alguma forma de fazer isso de maneira que respeite as boas práticas?
Comment: Use o atributo `value` para colocar os valores no formulário: `` se for `select` coloque o atributo `selected` no `option` e.g: `Homem`.
Answer: Seria interessante você ter no atributo "value" uma referência para uma variável, então toda vez que você carregasse os dados do banco você atribuiria os valores.
Por exemplo:
Você chamaria a página passando os valores na requisição:
    <?php

    function __autoload($class) {

        if (file_exists("../app.ado/{$class}.class.php")) {
            include_once "../app.ado/{$class}.class.php";
        }
    }

    // Verifica se exitem valores passados na requisição - A mesma página serve para cadastro e edição,
    //  quando é aberta sem nenhum valor passado é para cadastro, caso contrário é edição
    if (empty($_REQUEST)) {
        // Variáveis que estão referenciadas nas textbox
        $id = "";
        $nome = "";
        $emailContato = "";
        $idInstituicaoEnsino = "";
        $tipo = "";
    } else {
        $id = $_REQUEST['id'];
        $nome = $_REQUEST['nome'];
        $emailContato = $_REQUEST['emailContato'];
        $idInstituicaoEnsino = $_REQUEST['idInstituicaoEnsino'];
        $tipo = $_REQUEST['tipo'];
    }

    ?>

E depois temos o html:
    <form method="post" action="controller.php">

                                Identificação

                                <input type="text" name="_id"
                                       value="<?= $id ?>"
                                       placeholder="Id Numérico"
                                       size="10" title="Numero que identifica o curso"/>

                                Nome

                                <input type="text" name="_nome"
                                       value="<?= $nome ?>"
                                       placeholder="Nome do curso"
                                       size="50" title="Nome do curso"/>

 ... E assim por diante

Comment: Se quiser em tenho um exemplo que fiz há um tempo.
Comment: Para atribuir os valores pode ser em um bloco php na sua página, onde você irá declarar essas variáveis e invocar os método para a consulta. Agora a lógica da consulta e tudo mais pode ser em um arquivo separado, como boa prática, para separar html de php.
Comment: curti essa ideia, mas e o código para setar essa variável, ele ficaria no mesmo arquivo juntamente com o html? ou tem como eu fazer separado e somente referenciar?
Comment: se vc puder, eu quero ver sim, mt obrigado
Comment: De nada. Editei a resposta com o exemplo do código.
Answer: A estrtura para pré-preencher informação de um formulário HTML é realmente muito simples, ainda mais usando PHP.
<?php
  $nome_html = htmlspecialchars( $nome );
  $email_html = htmlspecialchars( $email );
?>

<form name="meuForm" method="post" id="formulario">
    Nome
    <input type="text"
           class="input_text"
           name="nome" id="name"
           value="<?= $nome_html ?>" />
    Email
    <input type="text"
           class="input_text"
           name="email" id="email"
           value="<?= $email_html ?>" />
    <input type="button"
           class="button"
           value="Enviar" />
</form>

Algumas dicas:

Faça o quoting htmlspecialchars($variável) das variáveis, para não correr o risco do seu HTML ser pixado pelo conteúdo de sua variável.
Evite usar estrutura de tabelas
 para organizar seu formulário, prefira estrutura tableless, que deixam seu código muito mais organizado, separando o design e organização em um arquivo CSS.


"Running it" multiple times in No-Limit Hold'em poker

Question: Suppose on the flop in no limit hold'em two players go all-in. They both have 2 hole cards and there's 3 community cards on the board at present. There will be 2 more cards drawn and each player will make the best 5 card hand out of the 5 community cards and their own 2 hole cards.
Sometimes people like to "run it out" more than once, and deal the 2 final cards 2 times, and either split the pot, or one person wins twice and wins the whole pot. There's also variations where they'll run it out more than 2 times.
Does this benefit one player more than the other? Figuring out the percentage chance of 1 player winning is no easy feat for running it out once only, and I have no idea how to approach this problem for running it out more than once.
Comment: It is just to reduce variance.  If you are a 3:1 dog and run it 4 times then statistically you would win once.   In a tournament a big stack would typically only run it once as in the payout structure putting the other player out is worth more than the pot.   No tournament I know of lets players run the deck more than once.
Answer: Expected value is linear, even over dependent random variables. The chance to win each run (not conditional on particular outcomes of the previous runs) is the same as the chance to win the original, so there is no advantage in expected winnings to running the hand $n$ times instead of once. Although some people find it counterintuitive, running the hand multiple times doesn't favor either the drawing hand or the hand which is ahead, whether the draw is likely to hit or not.
The variance is reduced significantly when you run the hand several times. It can greatly affect the probability that the player is ahead or behind for the day, or the probability of reaching or keeping other thresholds of psychological importance.
Some people feel that allowing your opponents to run a hand multiple times decreases their risk aversion, and mistakes due to risk aversion, earlier in the hand. This is one reason some players such as Barry Greenstein might have the policy of not letting people run the hand multiple times.
Another effect of running the hand multiple times is to decrease the probability that players bust out, and have to decide whether to rebuy or leave. Leaving may bring in other players you would prefer to play against or may leave the table shorthanded, which may suit you if you are relatively strong at shorthanded play. If a player wins the whole pot, he may also reach an uncomfortable stack depth where he might make more errors. Running the hand multiple times also takes time which could be spent playing poker instead.
On the other hand, if someone asks to run the hand multiple times, and you refuse, this may look unfriendly, and a casual player may decide to spend his money elsewhere.
Comment: From my understanding, the two runs typically occur *without* replacement.  It's true that the EV happens to be the same regardless, but I don't think your first line is likely to be very convincing to a skeptic.  For instance, if a player only has one "out" and hits it the first time, he cannot win the second time.  Your answer is right, but I wonder if maybe you could improve it by more explicitly dealing with cases like this?
Comment: The chance that the first run is favorable exactly balances the chance the that the first run is unfavorable. The chance that you win with cards $3$ and $4$ is the same as the chance that you win with cards $1$ and $2$, by symmetry.
Comment: What if there's 2 outs for the behind player? Doesn't running it twice risk both outs coming on one run and being completely dead on the other run? I did the calculations for 1 out and you're definitely 100% correct.
Comment: (+1) For some reason this (1) is very obvious from linearity and (2) somehow seems miraculous, like there is a conspiracy making things cancel out exactly right.
Answer: "Figuring out the percentage chance of 1 player winning is no easy feat for running it out once only"

On the contrary, approximations are easy on the flop and turn.

From the flop, with 2 cards to come. Percent to win = (# outs) x 4. Example, if you have 9 clean flush outs on the flop, then you are about 36% (actually, slightly less than 36%).
On the turn, with 1 card to come, percent to win = (# outs) x 2 - 1. Example, you missed the the flush on the turn but still have 9 clean outs, then it's (9 x 2) - 1 or about 17%.

Re: running it twice.
E.g., Let's say that I have a flush draw (9 outs and thus, about 36% on the flop to win) against a made hand on the flop. We agree to run it twice.
At this point, I am behind and will lose 36% of the time if we run it once. But if we run it twice, my chances of winning or splitting the pot is greater than 36%. Because at this point, I'd be happy with a split pot and all I'm looking to do is win at least one of the runs.
So run it once, I am 36%.
Run it twice, given that I have some extra chance (an additional) 36% chance, my chance to chop OR win is greater than the 36% to win in a single run. Ergo, there is a benefit to run it twice for the person getting the chips in bad. It doesn't increase the chance of winning the pot but provided there is now a better than 36% chance of winning OR chopping the pot, this is surely a benefit.
Thus, to answer the OP's question. There is a benefit to running it twice for the person getting the chips in bad. It doesn't increase their chances of winning the pot. But there is the added value/possibility of a chopped pot, which should be clearly welcome for anyone getting their chips in bad.


Disable caching of attached css/js libraries for custom module?

Question: I have been trying to disable caching during development so I followed drupals guide step by step: https://www.drupal.org/node/2598914
After doing this I would assume that the caching is completely disabled but when I am loading a js/css file for a specific module in mymodule/mymodule.libraries.yml I still have to clear all caches for me to see any updates.
How do you disable caching for attached libraries in custom modules?
test_module.routing.yml
test_module.test:
  path: '/test-me'
  defaults:
    _title: 'Testing module css cache'
    _controller: 'Drupal\test_module\Controller\TestController::test'
  requirements:
    _permission: 'TRUE'

test_module.libraries.yml
test:
  version: VERSION
  css:
    theme:
      test.css: {}

TestController.php
<?php

namespace Drupal\test_module\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Render\Markup;

class TestController extends ControllerBase
{
    public function test()
    {
        return [
            "#markup" => Markup::create("
Hello World
"),
            '#attached' => [
                'library' => ['test_module/test']
            ]
        ];
    }
}

test.css
.test-class {
    padding: 40px;
    background-color: blue;
}

If I change the background-color to red for example, and refresh the page (F5, Ctrl+F5, Ctrl+Shift+R, Right click refresh -> Clear cache and Hard Rest), it will not change to red until I clear all caches.
What piece am I missing to make this work? Or is it just not possible?
Note: It doesn't matter if I clear my browser cache at all (I currently have it disabled with devtools open)
Answer: You should simply remove the version: VERSION line, because this declares your library to be the same version as your Drupal core version, which does not change as often. By deleting this line, Drupal will add a default query string that changes after every cache rebuild/deployment, so it will naturally cache-bust.
See https://chromatichq.com/insights/drupal-libraries-version/ for more information on the VERSION value in libraries and why it shouldn't be used by anyone outside of core.
Answer: You are on the wrong track. Caching of static assets (and CSS files are static assets when you disable CSS/JS aggregation) has nothing to do with Drupal's cache. Disable the caching of *.js and *.css files on your web server instead (e.g in .htaccess if you are using Apache).
Comment: Yes, although Drupal tries to overcome this restriction by adding a cache buster query string, which is changed on a cache clear, so it appears that Drupal clears CSS, but in reality it doesn't.
Comment: The cache buster string only really works well with aggregation enabled and `drush cr`. With aggregation disabled, the query string for custom libraries is just the version number from the `library.info`, which is not really useful when iterating quickly over CSS on local dev
Comment: Without aggregation this works for CSS as well, only for JS you need to adjust the version number. What I meant, the OP expects that Drupal can clear CSS automatically, because Drupal can do it manually by `drush cr`. But Drupal doesn't have control over static CSS files, as you pointed out in the answer. Drupal simply invalidates the cache-buster each time the cache is cleared, without knowing whether CSS files were modified.
Comment: Thank you, I will look into disabling the caching in nginx and see if that does the trick.
Comment: Man I was so convinced drupal was caching it.  Thank you so much for pointing me in the right direction.  Updating nginx to not cache static files (css/js) saved the day.
Comment: You don't need to disable caching in nginx, you just need to remove the `version: VERSION` line in your libraries.yml file. Then it should just all work.
Answer: You can use the js_cache_buster module and add the enable_buster: true value to the js you want in your library.yml file. This will increment the ?v= value each time the cache is cleared.