Pra que serve o Event.namespace do jQuery

Question: Na documentação do jQuery, temos lá a explicação do event.namespace.
Isso permite utilizar um evento (ou criar um evento) específico do jQuery,
com um namespace, através de um . ponto e um nome na frente desse evento.
Exemplo:
$(document).on('click.first_event', function (event)
{
     alert(event.namespace);
});

Gostaria de saber qual é a vantagem de utilizar eventos com esses namespaces no jQuery?
Pra que serve esses namespaces?
Comment: Observação: Não é uma duplicata de http://pt.stackoverflow.com/questions/47956/eventos-com-namespace
Comment: Não acho que seja uma duplicata, lá pergunta como replicar em javascript puro.
Comment: Mas o pessoal foi bem rápido pra marcar como duplicado. Eu também não concordo - senão nem teria perguntado.
Comment: Wallace não é bem uma mensagem pra ti, mas pra fila de analise, quando alguem for clicar pra fechar, vai ler o meu comentário junto a pergunta, assim coloco minha opinião de que isto não é uma duplicata, eu comentei pela fila de analise diretamente e marquei pra deixar aberta.
Answer: Um event.namespace pode ser útil para controle de quais eventos específicos quero remover.
Exemplo:
Suponhamos que eu tenha três eventos de scroll vinculados a window.
Quero remover um deles especificamente, porém não todos.
Se eu fizesse assim:
$(window).scroll(function (){
      alert('1');
   }

   $(window).scroll(function (){
      alert('1');
   }

   $(window).off('scroll');

Eu removeria todos os eventos.
Porém se eu fizesse assim, eu conseguiria êxito, graças ao event.namespace.
$(window).bind('scroll.alert_1', function ()
{
     alert('1');
});

$(window).bind('scroll.alert_1', function ()
{
     alert('2');
});

$(window).unbind('scroll.alert_1');

No caso acima, só será exibido o alert('2'), já que consegui remover um evento específico por conta desse namespace.


Feeding categorical data to classifier

Question: Suppose I have the dataset in the following format:
col1    col2     col3      col4         col5 (to be predicted)
12      13       4         primary      label1
1       15       2         secondary    label2
5       7        8         primary      label3
14      12       44        college      label4

col5 needs to be predicted for some test data using col1, col2, col3 and col4
During training, col1, col2, col3 can be feeded as such in an array to the classifier but how to feed col4. I am aware that this is categorical and need to be converted to numeric type, but even after assigning some number, it will still remain as nominal type.
So if primary=1, secondary=2 and college=3, the numbers 1,2 and 3 cant be compared as per their magnitude because they are still like labels, with no numerical significance.
So how should I proceed after this step... should they be normalized ? or any further should be done ?
Comment: Your outcome seems to be continuous. If so, you shouldn't use a classifier.
Comment: @gung, I am sorry , i intended it ti be a categorical feature. I have edited the question. So now how shall I do it ?
Comment: Which kind of model are you planning to use? Regression or tree methods? The solution depends on the kind of model.
Comment: @spdrnl,  I am trying to use Random Forest Classifier
Comment: Do you use python or r?
Comment: Thanks for the answer.. I am using Python and will try both options you suggested
Answer: In R just encode it as 1, 2, 3 and mark it as a factor.
In python you could use one hot encoding. This means creating a new variable for each label, and then setting to one one of these variables. For example primary would become 1 0 0, secondary 0 1 0, college 0 0 1.
Since the labels also represent values on an interval scale, one could try to encode the labels 1, 2, 3 (and in R not mark it as a factor) to see if the model competes accuracy wise. A bit of fiddling with other numbers might also give a good prediction. In this case accuracy is chosen over cleanliness, or a good justification should be given.
Answer: If you are using python, your data should probably be in a pandas.DataFrame object:
import pandas as pd
df = pd.read_cvs(data, sep=' ')  # there are lots of read options, hit tab after pd.read
df = df.drop(['col5'])           # Drop the target column before the next step

From there you can use one-hot style encoding by the get_dummies() function:
df = pd.get_dummies(test_dat)
This splits each categorical column by feature and replaces it one new column for each feature in a given column. If the index (i.e. row) contains the value its column was split from, then you'll see a 1, else you'll see a zero.
This is useful when your classifier needs numerical data, however not all classifiers will need numerical data, so be sure to check that.

Feeding categorical data to classifier


Poisson Process conditional probability

Question: Let $N(t)$ be a Poisson Process with rate $\lambda$
Find $\displaystyle P(N(4) \le 2N(2) \mid N(2) = 1) = \frac{\sum_{i = 0 }^2P(N(4) = i, N(2) = 1)}{P(N(2) = 1)} = ?$
Can I split this up using the independent increments?
Comment: @whuber this leads me to $P(N(0,4) \le 2N(0,2) \mid N(0,2) = 1) = P(N(2,4) = 0 ) + P(N(2,4) = 1) + P(N(2,4) = 2)$ and $N(2,4) \sim$ Poisson$((4-2)\lambda)$. Is this the correct logic?
Comment: Presuming "$N(t)$" means the number of events in the interval $[0,t],$ the assumption of independent increments is essential for making any progress at all.  But why haven't you proceeded to evaluate the answer to see whether it makes sense?  There's less work involved than writing the question!
Comment: As I wasn't entirely sure in which way to split it up: Namely, $P(N(4) - N(2)  = i - N(2), N(2) = 1)$ which seems incorrect but so does $P(N(4) - N(2) = i - 1, N(2) = 1) $.
Comment: You might find it helpful and revealing to adopt a more precise notation: let $N(s,t)$ be the number of events in the interval $(s,t]$ and note that $N(4)=N(0,4)=N(0,2)+N(2,4)=N(2)+N(2,4).$
Comment: Good work: It looks like you're well on your way to a correct solution.
Answer: \begin{align}
\mathbb P(N(4)\leqslant 2N(2)\mid N(2)=1) &= \frac{\mathbb P(N(4)\leqslant 2N(2), N(2)=1)}{\mathbb P(N(2) = 1}\\
&= \frac{\sum_{i=0}^2 \mathbb P(N(4)=i, N(2)=1)}{\mathbb P(N(2)=1)}\\
&= \frac{\sum_{i=0}^2 \mathbb P (N(4) - N(2) = i,N(2)=1)}{\mathbb P(N(2)=1)}\\
&=\frac{\sum_{i=0}^2 \mathbb P (N(4) - N(2) = i)\mathbb P(N(2)=1)}{\mathbb P(N(2)=1)}\\
&= \sum_{i=0}^2 \mathbb P(N(4) - N(2) = i)\\
&= e^{-2\lambda}(1 + 2\lambda +2\lambda^2).
\end{align}

Poisson Process conditional probability


How is $x = -\text{sign}(c_i)e_i$ the solution to minimize $c^T x$ subject to $\|x\|_1 \le 1$?

Question: From Convex Optimization by Boyd & Vandenberghe:

$$\begin{array}{ll} \text{minimize} & c^T x\\ \text{subject to} & \|x\|_1 \le 1\end{array}$$
Let $i$ be the index such that $\|c\|_{\infty} = |c_i|$, then the
solution is given by $$x = -\text{sign}(c_i)e_i$$ where $e_i$ is the $i$-th
standard basis vector.

Can someone explain how this is derived?  I don't see why the unit vector in the maximum direction of $c$ minimizes this.
Answer: Since $\Vert x\Vert_1\leq1$, this means $\sum_j\vert x_j\vert\leq 1$. Now let $x_0=-\mathrm{sign}(c_{i})e_i$ as in your question. For an arbitrary $x$ we then have:
$$
|c^Tx|=\left\vert\sum_{j} c_j x_j\right\vert\leq\sum_j|c_j||x_j|\leq|c_i|\sum_j|x_j|=|c_i|\Vert x\Vert_1\leq|c_i|
$$
Because $c^Tx_0=-|c_i|$, we have that this is indeed the best possible.


Alias path precedence rule?

Question: I just checked that an alias path named, say, any/path can point to N different existing paths. Is there any fixed precedence order as per which one will be processed? Or is it a random order?
Comment: Well, right you are, still - and looks like a specific language has precedence over neutral. I just don't know if this is a random behavior or a rule-of-thumb.
Comment: From the user interface it is not possible to have two records for the same path alias, and the same language, but pointing to different internal paths. Calling `path_save()` it is possible. See my answer to understand which alias would be used.
Answer: Using the user interface, it is not possible to set the same alias pointing to different destinations for the same language.
If a module would execute code similar to the following one, it would be possible to have two records for the same alias.
$path = array(
  'alias' => 'homepage',
  'source' => 'node/1',
);
path_save($path);

$path = array(
  'alias' => 'homepage',
  'source' => 'node/2',
);
path_save($path);

drupal_lookup_path() contains the following code to retrieve the internal path associated with a path alias from the database. $path_language is the last argument passed to the function; when the function doesn't get that argument, it uses the value of $GLOBALS['language_url']->language.
    if ($path_language == LANGUAGE_NONE) {
      unset($args[':language']);
      $alias = db_query("SELECT alias FROM {url_alias} WHERE source = :source AND language = :language_none ORDER BY pid DESC", $args)->fetchField();
    }
    elseif ($path_language > LANGUAGE_NONE) {
      $alias = db_query("SELECT alias FROM {url_alias} WHERE source = :source AND language IN (:language, :language_none) ORDER BY language DESC, pid DESC", $args)->fetchField();
    }
    else {
      $alias = db_query("SELECT alias FROM {url_alias} WHERE source = :source AND language IN (:language, :language_none) ORDER BY language ASC, pid DESC", $args)->fetchField();
    }

If $path_language is equal to LANGUAGE_NONE (i.e. you are looking for the internal path associated with the language-independent alias), drupal_lookup_path('source') returns the internal path which is saved in the path_alias table with the higher pid (which normally is the latest created row).
If $path_language is not equal to LANGUAGE_NONE, the database rows are ordered to get the language-specific alias before the language-neutral, and then by pid. Also in this case, the returned internal path would be the last created one.
Suppose url_alias contains the following values.

pid   | source    | alias      | language
4     | node/1    | homepage   | und
5     | node/2    | homepage   | und
8     | node/21   | homepage   | it
9     | node/22   | homepage   | it
10    | node/31   | homepage   | xx-lolspeak
11    | node/32   | homepage   | xx-lolspeak

What I would get from that table is:

drupal_lookup_path('source', 'homepage'): node/2
It returns the last created alias that is language-independent.
drupal_lookup_path('source', 'homepage', 'es'): node/2
There isn't an alias for Spanish, and the function fallback to the language-independent alias. It gets the last created alias.
drupal_lookup_path('source', 'homepage', 'xx-lolspeak'): node/32
It returns the last created alias for Lol Speak.

Alias path precedence rule?


Replacement Bridge for a Jackson Stealth Ex Guitar (Jackson JT580 Bridge)

Question: I have a Jackson Stealth Ex which I want to get fixed but it's going to need a new bridge.
The bridge it comes with is a Jackson JT580 Bridge but I can't find a left handed version anywhere.
Is there any alternative bridge the will fit in the cavity done for a Jackson JT580 bridge or does anyone know where to get the from?
Comment: Have you contacted the Jackson company's customer service department?
Answer: I could be wrong here -- I'm a hardtail guy and don't know too much about Floyd Rose tremolos -- but it seems that it should be just a licensed Floyd Rose bridge, and another lefty Floyd Rose should be a drop-in replacement.
Answer: The Gotoh Floyd Rose replacement bridge and an Original Floyd Rose bridge (As stated by VarLogRant) should be a drop in replacement in most cases.  I have a few acquaintances that replaced the Jackson bridges because they wouldn't stay in tune...
Check here for exact info, but it has been reported that some of the Gotoh OFR replacements have a trem block that is too long which prevents you from putting the back cover on the guitar.
You could also check out the Ping Floyd Rose replacements.
Answer: The above answer is correct. That is to say, sorry, but he is completely wrong and he doesnt know anything about Floyd Rose trems. (Maybe next time, offer facts and experience and not opinion...)
Regarding the Original Question:
There are many design parameters that have to be considered when making the swap from any Liscenced floyd to an Original or FR 1000. Some of these are the length and type of allen bolts. Saddle material. Size of the back plate. Size of the block. (matertial of block). Alignment of the springs to the trem cavity (backside route width and depth). Fittment of the plate to the studs. Can you replace the studs with similar threaded, etc... All presuming you wish to avoid going at this with a rotary tool in hand and carving out the routs for designed fitment. Floyds are tricky beasts. Installed correctly, theyre amazing. Installed with ignorance, and your results may be much less successful than expected.
Here instead is a site with excellent information based on facts and user experience which should help you out.
http://audiozone.dk/index-filer/TremoloInfoProject.htm#jt580
In particular, the swap you describe (replacing JT580 with OFR) has been done successfully and the pictures are posted here. Keep in mind the caveats I mentioned above. You will need to check the depth and width of the route on your particular guitar. If you have a thin body, the block may not accomodate nicely. One user's success does not mean it will work for you. So check to see how his project compares to your own. But at least its good to know that it has been done successfully! (JT580 to OFR replacement).
cheers


Função Ajax não está funcionando no Wordpress

Question: Estou criando um plugin para o CMS Wordpress, nele tenho um script que roda perfeitamente até a parte de fazer a requisição ajax para gravar alguns dados no banco de dados. O código funciona até a parte de exibir o texto dentro da div passo2form que inicialmente fica vazia e após clicar no botão o texto é inserido dentro dela. Porém os dados não são gravados no banco de dados. Meu código está assim:
Html principal:

        <input type='text' name='nome' id='nome' class='campo-form' placeholder='Nome' maxlength='50'>

        <input type='email' name='email' id='email' class='campo-form' placeholder='Email' maxlength='120'/>
        <button type='submit' id='enviarform' class='botao-enviar'>Efetuar Simulação</button>

Arquivo Javascript que é executado:
jQuery('#enviarform').click(function(){
        var nome = document.getElementById('nome').value;
        var email = document.getElementById('email').value;

        jQuery( "#passo2form" ).html("

Olá " + nome + ",

Estaremos enviando em breve sua cotação para o email " + email + "

");

var formData = {
        'nome'              : jQuery('input[name=nome]').val(),
        'email'             : jQuery('input[name=email]').val()
    };

    // process the form
    jQuery.ajax({
        type        : 'POST',
        url         : 'processa.php',
        data        : formData,
        dataType    : 'json',
        encode      : true
    })
        .done(function(data) {

            console.log(data);

        });

});

Eu testei o arquivo ´processa.php´ e funciona perfeitamente fazendo a inserção dos dados no banco. Mas segue o código:
<?php
include_once($_SERVER['DOCUMENT_ROOT'].'/wordpress/wp-config.php' );

global $wpdb;

$nome = trim($_POST['nome']);
$email = trim($_POST['email']);

$wpdb->insert(
        wp_formclientes,
        array(
            'nome'    => $_POST['nome'],
            'email'   => $_POST['email']
        )
    );

$wpdb->show_errors();

?>

Comment: Dá algum erro no console?
Comment: @SampaioLeal não me retorna nenhum erro
Comment: @Wendell Na aba Network do seu web inspector aparece a requisição para o `processa.php`?
Comment: @PanterA não aparece, somente a requisição do `processa.js` que é o arquivo do script.
Comment: @Wendell com a aba de Networks aberta, e clicando no botão `#enviarform` nada aparece? E o que essa propriedade `encode: true` no objeto enviado para o `jQuery.ajax` faz? Não encontrei ela na documentação oficial.
Answer: Ah, vou fazer uma cópia do seu código usando as funções básicas do JQuery, você poderia testar e ver se faz diferença:

$('#enviarform').click(function(){
        var nome = $('#nome').val();
        var email = $('#email').val();

        $( "#passo2form" ).html("

Olá " + nome + ",

Estaremos enviando em breve sua cotação para o email " + email + "

");

var formData = {
        'nome'              : $(nome).val(),
        'email'             : $(email).val()
    };

    // process the form
    $.ajax({
        type        : 'POST',
        url         : 'processa.php',
        data        : formData,
        dataType    : 'json',
        encode      : true
    })
        .done(function(data) {

            console.log(data);

        });

});

        <input type='text' name='nome' id='nome' class='campo-form' placeholder='Nome' maxlength='50'>

        <input type='email' name='email' id='email' class='campo-form' placeholder='Email' maxlength='120'/>
        <button type='submit' id='enviarform' class='botao-enviar'>Efetuar Simulação</button>

Comment: não funcionou, continua da mesma forma, todas as demais funções funcionam mas não grava nada no banco de dados. Se eu criar um `form action` do tipo `post` e direcionar para o arquivo `processa.php` os dados são gravados no banco de dados. Então acredito que o problema é na função em ajax.
Answer: Eu consegui solucionar. Primeiramente adicionei uma função no arquivo principal do plugin, como esta:
function addCustomer(){

global $wpdb;

$nome = trim($_POST['nome']);
$email = trim($_POST['email']);

if($wpdb->insert('wp_formclientes',array(
'nome'=>$nome,
'email'=>$email
))===FALSE){

echo "Error";
}
else {
    //mensagem de sucesso
}
add_action('wp_ajax_addCustomer', 'addCustomer');
add_action('wp_ajax_nopriv_addCustomer', 'addCustomer');

E isto foi no meu arquivo processa.js:
var urlsite = jQuery('#urlsite').val();
var urlsitenova = urlsite + "/wp-admin/admin-ajax.php";

jQuery('#cadastraForm').submit(ajaxSubmit);

function ajaxSubmit(){

    var newCustomerForm = jQuery(this).serialize();

    jQuery.ajax({
    type:"POST",
    url: urlsitenova,
    data: newCustomerForm,
    success:function(data){
    jQuery("#feedback").html(data);
    }
});

return false;
}


How can I use indexes with sort on a MongoDb $or query?

Question: I've got a collection mailCollection with indexes on the .sender and .recipient values.  When I do an $or query and sort by .timestamp the entire collection is scanned.  How can I index this collection or rewrite the query to grab the documents where .sender or .recipient match a specific value, sorted and limited?
mailCollection indexes:
{recipient: 1}
{sender: 1}

Slow code:
email = <some email address I want to query>;
cursor = mailCollection.find({$or: [{sender: email}, {recipient: email}]});
cursor.sort({timestamp: 1}).limit(100).toArray(function(error, result) {
  //yikes, full collection scan
});

If it makes a difference, I'm using the MongoDb node.js driver.
Comment: Have you tried actually adding `timestamp` as an index? Have you tried adding `timestamp` as a secondary field in a compound index to either of the existing indexes? Perhaps read [Sort and Non-prefix Subset of an Index](https://docs.mongodb.com/manual/tutorial/sort-results-with-indexes/#sort-and-non-prefix-subset-of-an-index) add indexes and run with `explain()`. Use `hint()` if needed and then remove indexes that would not be picked up. No the driver does not make a difference.
Answer: Dodgy. A 3-way index intersection does not work. So you need to intersect with a compound index. However, you need to make sure that you have a proper prefix in your compound index so that you have a proper use for it and make it efficient.
The data
> db.indextest.find()
{ "_id" : ObjectId("59f401893e9fcadcbf2b1694"), "sender" : "email@example.com", "recipient" : "email@example.com", "timestamp" : ISODate("2017-10-28T04:03:21.468Z") }
{ "_id" : ObjectId("59f405d93e9fcadcbf2b1695"), "sender" : "firstname.lastname@example.com", "recipient" : "email@example.com", "timestamp" : ISODate("2017-10-28T04:21:45.573Z") }
{ "_id" : ObjectId("59f408413e9fcadcbf2b1699"), "sender" : "firstname.lastname@example.com", "recipient" : "firstname.lastname@example.com", "timestamp" : ISODate("2017-10-28T04:32:01.651Z") }
{ "_id" : ObjectId("59f408563e9fcadcbf2b169a"), "sender" : "firstname.lastname@example.com", "recipient" : "email@example.com", "timestamp" : ISODate("2017-10-28T04:32:22.376Z") }
{ "_id" : ObjectId("59f408763e9fcadcbf2b169b"), "sender" : "email@example.com", "recipient" : "email@example.com", "timestamp" : ISODate("2017-10-28T04:32:54.268Z") }
{ "_id" : ObjectId("59f4087e3e9fcadcbf2b169c"), "sender" : "firstname.lastname@example.com", "recipient" : "email@example.com", "timestamp" : ISODate("2017-10-28T04:33:02.615Z") }

The indices
I decided to create an index both on sender and recipient with an additional key on timestamp. This should give you efficient queries for the most common use cases:

Which messages did a given user receive, sorted by date?
Which messages did a given user send, sorted by date?
And your query ;)

This gives you the most bang with the least overhead (one field in one index).
Given the indices
> db.indextest.getIndices()
[
  {
        "v" : 1,
        "key" : {
            "_id" : 1
        },
        "name" : "_id_",
        "ns" : "test.indextest"
    },
    {
        "v" : 1,
        "key" : {
            "recipient" : 1,
            "timestamp" : 1
        },
        "name" : "recipient_1_timestamp_1",
        "ns" : "test.indextest"
    },
    {
        "v" : 1,
        "key" : {
            "sender" : 1,
            "timestamp" : 1
        },
        "name" : "sender_1_timestamp_1",
        "ns" : "test.indextest"
    }
]

The result
Running your query:
> db.indextest.find({$or:[{sender:"firstname.lastname@example.com"},{recipient:"email@example.com"}]}).sort({timestamp:1}).explain()

gives the expected result (edited for brevity):
> db.indextest.find({$or:[{sender:"firstname.lastname@example.com"},{recipient:"firstname.lastname@example.com"}]}).sort({timestamp:1}).explain()
{
    "queryPlanner" : {
        "plannerVersion" : 1,
        "namespace" : "test.indextest",
        "indexFilterSet" : false,
...
        "winningPlan" : {
            "stage" : "SUBPLAN",
            "inputStage" : {
                "stage" : "FETCH",
                "inputStage" : {
                    "stage" : "SORT_MERGE",
                    "sortPattern" : {
                        "timestamp" : 1
                    },
                    "inputStages" : [
                        {
                            "stage" : "IXSCAN",
                            "keyPattern" : {
                                "recipient" : 1,
                                "timestamp" : 1
                            },
                            "indexName" : "recipient_1_timestamp_1",
                            "isMultiKey" : false,
...
                            "direction" : "forward",
                            "indexBounds" : {
                                "recipient" : [
                                    "[\"firstname.lastname@example.com\", \"email@example.com\"]"
                                ],
                                "timestamp" : [
                                    "[MinKey, MaxKey]"
                                ]
                            }
                        },
                        {
                            "stage" : "IXSCAN",
                            "keyPattern" : {
                                "sender" : 1,
                                "timestamp" : 1
                            },
                            "indexName" : "sender_1_timestamp_1",
                            "isMultiKey" : false,
...
                            "direction" : "forward",
                            "indexBounds" : {
                                "sender" : [
                                    "[\"firstname.lastname@example.com\", \"email@example.com\"]"
                                ],
                                "timestamp" : [
                                    "[MinKey, MaxKey]"
                                ]
                            }
                        }
                    ]
                }
            }
        },
        "rejectedPlans" : [ ]
    },
...
    "ok" : 1
}

EDIT: Depending on your collection size, a sort merge might not be ideal.
Comment: Seems to have worked!  Thanks!  Just had to upgrade to the latest version of MongoDb to allow index intersection.


How is the gradient of a curve or function its normal

Question: I see in several books that the gradient of a function (curve), f(x,y) is defined as the normal to the curve without the proof. Can someone prove mathematically that this is true?
Comment: You have got something wrong
Comment: Can you please explain where?
Answer: Gradient of a function, i.e., $\vec{\nabla} f(x)$, is not normal to the curve $f(x)$. It is normal to the contour curve, and tangent to the curve $f(x)$.
Consider a function $z=f(x,y)$ then rewrite it as $f(x(t),y(t)) = c$ with some constant scalar $c$ for each level surface (i.e. a surface with constant value of $f(x,y)$). Then let $\vec{r}(t) = \begin{bmatrix}x(t) & y(t)\end{bmatrix}'$ be a parametric curve on the level surface . Also note that $x=x(t), y=y(t)$ for the general case.
Now we take the derivative
$\dfrac{df}{dt} = \dfrac{\partial f}{\partial x}\dfrac{dx}{dt} + \dfrac{\partial f}{\partial y}\dfrac{dy}{dt} = 0$
$\dfrac{df}{dt} = \begin{bmatrix}\dfrac{\partial f}{\partial x} & \dfrac{\partial f}{\partial y}\end{bmatrix} \begin{bmatrix}\dfrac{dx}{dt} & \dfrac{dy}{dt}\end{bmatrix}' =0$
$\vec{\nabla} f(x,y) \cdot \vec{r}(t) = 0$
Because the inner product of the above two vectors is 0, it implies that $\vec{\nabla} f(x,y) \perp \vec{r}(t)$. Hence the gradient of $f(x,y)$ is perpendicular to the level surface (i.e. the contour line) of $f(x,y)$.
The same proof can be used for the function $f$ in higher dimension.
Comment: Can you tell me how it is normal to the contour curve
Comment: A simple proof has been added in the last edit.


Print filename from url

Question: Im using Drupal 6 with Audio.
I have created a view that shows a list of files to download and play. There are two fields which both show the download link. I would like to change the second download link field so that it strips all the info and only prints the filename from the url contained in its content. So instead of
<*a href-"file/path/music20.mp3">Download

I would like to see
music20.mp3

or
music20

Thanks in advance
Comment: Do you mean you want `music20.mp3` ?
Comment: ^? He means he only wants the file name shown. It has been a while since I used D6, But try looking at the options for the field. If it is a file field it may have an option to only show the file name, or you might have  to uncheck a checkbox for link to content.
Comment: Yes I want the filename shown. I am using Views to create that list and there are no options for filename for Audio items.

I was thinking that maybe there is a way of preprocessing via the template file and using php basename to pull the filename. Possible?
Answer: In drupal 7, views 3 if you add a relationship File Usage: File you get some new fields you can add to your view, including the filename. The filename includes the extension (.doc, .pdf etc). But even with that you could theme the specific field with a template where you could easily use php to cut the .mp3 part.

Print filename from url


Gerando PDF com MPDF apartir de BLOB

Question: Bom estou precisando gerar um PDF a partir de um campo BLOB salvo no banco de dados, a minha ideia é da possibilidade de fazer upload de PDF transformando ele em BLOB para não ocupar espaço em disco e facilitar o transporte do mesmo.
Estou fazendo da seguinte forma:
include("../pdf/mpdf60/mpdf.php");

$mpdf=new mPDF();

$mpdf->WriteHTML($registros->BLO_PDFXX_ARQUI);

$mpdf->Output();
exit;

onde o $registros->BLO_PDFXX_ARQUI é o código que estou tentando fazer. Porém ai vem a pergunta, com MPDF tenho condição de fazer isto ?
Minha outra duvida é existe algum gerenciado que me facilitaria neste caso de conteúdo BLOB ?
Answer: Para gerar PDF a partir  de um código HTML eu recomendo o Wkhtmltopdf
http://wkhtmltopdf.org/
ou ainda mais simples HTML2PDF
http://html2pdf.fr/en/default
ambos são práticos de utilizar e já trazem alguns exemplos em seu pacote.
Qualquer duvida me disponho a auxiliar.
Comment: Este gera para mim de BLOB para pdf ?
Comment: Para isso basta usar o php para tratar o BLOB e criar um html com o contéudo e formatação desejada.

http://php.net/manual/pt_BR/function.ibase-blob-echo.php

Caso você não esteja utilizando firebird essa é outra forma bem simples:

http://stackoverflow.com/questions/20556773/php-display-image-blob-from-mysql
Comment: quando estou dando echo esta dando erro interno do servidor
Comment: estou pesquisando desta forma aqui $bloo = ibase_blob_echo($registros->BLO_PDFXX_ARQUI);
echo $bloo;
Comment: no log de erro do php deu este erro PHP Fatal error:  Call to undefined function ibase_blob_echo()
Comment: Dessa forma é mais simples, a função ibase_blob_echo é uma função disponivel pela library do firebird.

echo '';
Comment: Porém não é uma imagem, na verdade o processo é o seguinte, o cara faz upload de um arquivo .pdf transformo ele em blob e salvo no banco, agora quero recuperar este arquivo .pdf. O problema ocorre ao recuperar os dados BLOB
Comment: Você pode usar o mesmo código echo ' Baixar PDF  ' , basta alterar o tipo do arquivo retornado e a tag.

Gerando PDF com MPDF apartir de BLOB


$\int f(x) x^n dx=0$ for all $n\geq 1$.

Question: This problem is similar to Baby Rudin Excercise 20 in chapter 7. The problem states that $g:[0,1]\to \mathbb{R}$ is continuous and that for all natural $n\geq 1$, $\int_0^1 g(x) x^n dx=0$. Prove that $g\equiv 0$. We do NOT know that $\int_0^1 g(x)dx=0$. (The Rudin exercise has the additional assumption that this holds for $n=0$ as well) I know that this implies that $\int_0^1 g(x)dx=\int_0^1 g(x)^2dx$ but am unable to conclude from here.
Comment: Note: $g(x)^2$ is always non-negative. If $g(x) \neq 0$, then $g(x)^2 > 0$! Use this plus continuity to prove that the integral of $g^2$ would then be positive.
Comment: It would be nice when referring to an exercise in a book to state what that exercise says, especially for those who don't have the book.
Comment: I edited that thanks
Answer: Hint. We know that $\int_0^1 (xg(x)) x^n dx=0$ for all $n\geq 0$. Now apply Baby Rudin Exercise to the continuous function $xg(x)$.
Comment: @AdamMartens Yes, you are correct.
Comment: Thank you very much...that makes it much easier. So then you could theoretically replace $n\geq 1$ by $n\geq 42$ (or any other integer?) and make the same conclusion?

$\int f(x) x^n dx=0$ for all $n\geq 1$.


Nao estou a conseguir passar o vetor do subprograma para o programa,remodelado

Question: Faça um subprograma que tenha como parâmetros de entrada e saída: o endereço de um vetor de números inteiros e o número de elementos desse vetor. O subprograma deve eliminar do vetor todos os valores que estejam fora do intervalo entre 10 e 20, recolocando os valores dentro do vetor e ajustando o número de elementos do vetor
<code>#include <stdio.h>
#include <stdlib.h>

    int NrVector(int j);

int main(){
    int j,vector[j],z=0,h;

    printf("Introduza o nr de numeros que pretende introduzir:");
    scanf("%d", &j) ;
     h=j;

    vector[z] = NrVector(j);
    printf("%d", NrVector(j));
            for(z=0;z<j;z++){if(10<=vector[z] && vector[z]<=20){
            printf("{%d}", vector[z]);}
            else{ h-=1;}    }

            printf("o nr de elementos: %d", h);

    printf("\n");
    system("pause");
    exit(1);
}
    int NrVector(int j){
    int vector[j],i=0,z=0,valor;

                for(i=0;i<j;i++){

                printf("Introduza o nr:");
                scanf("%d", &valor);
                vector[i]=valor;}

                }
</code>
Answer: Vários erros. Tente:
<code>#include <stdio.h>

void NrVector(int *, int);

int main() {
    int j, y, z, h;
    printf("Introduza o nr de numeros que pretende introduzir:");
    scanf("%d", &j);
    int vector[j];
    h=j;
    NrVector(vector, j);
    for(z=0; z<h; z++) {
        if(10<=vector[z] && vector[z]<=20) {
            printf("{%d}", vector[z]);
        }
        else {
            for (y=z+1; y<h; y++)
                vector[y-1] = vector[y];
            h-=1;
        }
    }
    printf("o nr de elementos: %d\n\n", h);
    for(z=0; z<h; z++)
        printf("\t[%d]: %d", z, vector[z]);
    printf("\n");
    return 0;
}

void NrVector(int * vet, int j) {
    int i=0, z=0;
    for(i=0; i<j; i++) {
        printf("Introduza o nr:");
        scanf("%d", &vet[i]);
    }
}
</code>


Exception thrown when one parameter of an Oracle stored function is null

Question: I want o call a PL/SQL function using a named query.
One of the parameters causes me problems. In the PL/SQL definition its type is NUMBER.
Here is the Java code where it is set:
q.setParameter (Test.DISTRICT_ID_PARAM,districtId);
and districtId is a Long.
When districtId is not null everything is ok, but when it is null this is the outcome:
org.hibernate.exception.SQLGrammarException: could not execute query
I'm sure there's no problem with the plumbing since the query works well when districtId is not null.
Answer: I'm not familiar with Java or Hibernate specifically, but in Oracle applications I've written I've come across similar behaviour with null parameters (C#) - if Java has the concept, have you tried setting the parameter value to be DB null (in C# DBNull.Value)?
If the value is null I think Oracle interprets it as the parameter not being passed at all.
Comment: The DB function accepts another 3 parameters of type VARCHAR2. I set those the same way I do with the previous one and everything works well, even if they are null. What I am trying to find out is whether there is something different when it comes to NUMBER parameters.
Comment: @RaduStoenescu: From PL/SQL parameter passing point of view there is no difference when passing null parameter to type varchar2 or number.
Comment: @MarkWatts: If you pass a parameter with a null value to PL/SQL function the function sees that parameter and the value of the parameter is null.
Comment: @user272735 That is true when calling PL/SQL directly (e.g. via SQL*Plus or similar) but when making calls to Oracle via code there is, certainly in .Net, a difference between defining a parameter value as null and DBNull.Value. Using null yields the error ORA-01008. However, this seems to be true for both VARCHAR2 and NUMBER types, so it can probably be ruled out as the source of Radu's problem.


CakePHP 2 & Translate Behavior: save multiple translations in a single form

Question: Its possibile save multiple translations of the same field in a single form?
I have a model with Behavior Translate to translate the name field. The three translations (deu, eng, ita) are properly recorded in the i18n table but the field is not properly validated! Any suggestions?
app/Model/Category.php
class Category extends AppModel {
    public $actsAs = array('Translate' => array('name' => 'TranslateName'));
    public $validate = array(
        'name' => array(
            'notempty' => array(
                'rule' => array('notempty'),
                'message' => 'Error notempty',
            ),
        ),
    );
    ...

app/View/Categories/admin_edit.ctp
<?php
echo $this->Form->create('Category');
echo $this->Form->input('Category.id');
echo $this->Form->input('Category.name.deu', array('label' => __d('Category', 'Name Deu')));
echo $this->Form->input('Category.name.eng', array('label' => __d('Category', 'Name Eng')));
echo $this->Form->input('Category.name.ita', array('label' => __d('Category', 'Name Ita')));
echo $this->Form->end(__d('app', 'Submit'));
?>

app/View/Controller/CategoriesController.php
if ($this->Category->save($this->request->data)) {
    $this->Session->setFlash(__d('Category', 'The category has been saved'));
} else {
    $this->Session->setFlash(__d('Category', 'The category could not be saved. Please, try again.'));
}

Answer: I have a similar Problem
But you can try out this - it should solve it for you: https://github.com/zoghal/cakephp-MultiTranslateBehavior


Can not reset User's Password and Cannot create user in Active directory

Question: We have 3 Domain Controllers. DC1( Central DC) , DC2 (ADC) , DC3 (ADC)
FSMO roles are shown below
Schema master -DC1
Domain naming master -DC1
PDC -DC3
RID pool manager -DC3
Infrastructure master -DC2
We can password reset and also can create new user in AD (DC2). DC2 server is working fine.
The OS version of the working server is windows server 2016.
But we cannot do these things with these 2 servers.(DC1, DC3)
When we going to reset user's password , going to create a new user , below error is happening.
Windows cannot complete the password change for __ because: The password does not meet the password policy requirements. Check the minimum password length, password complexity and password history requirements.
The OS version of the working (DC1, DC3) server is Microsoft Hyper V server 2019.
The same password policy is configured for these 3 servers.
Enforce password history 5 passwords remembered
Maximum password age 45 days
Minimum password age 0 Days
Minimum password length 8 characters
Minimum password length audit Not Defined
Password must meet complexity requirements Enabled
Store passwords using reversible encryption Disabled
I want to fix this issue. Could you please help me ?
Thanks
Comment: The first thing to check is replication. Is it working correctly?
Answer: Windows cannot complete the password change for __ because: The password does not meet the password policy requirements. Check the minimum password length, password complexity and password history requirements.

There is probably a group policy in place which enforces a complex password. With gpresult /v and a RSOP query you should see which policy. https://activedirectorypro.com/how-to-configure-a-domain-password-policy/


apache - DirectoryIndex - php page with arguments

Question: I've got a single tikiwiki instance and several domain names. I want domain-1.com to have a homepage at domain-1.com/tiki-index.php?page-1. And then I want domain-2.com to have a homepage at domain-2.com/tiki-index.php?page-2. Both will internally map to the same tikiwiki instance.
I.e. I want several domains to point to the same tikiwiki instance. But coming from different domains should land you at different home pages. And then user could manually navigate from domain-1.com/tiki-index.php?page-1 (hompage) to domain-1.com/tiki-index.php?page-2
I tried to do this by setting DirectoryIndex but looks like it ignores all page arguments, i.e. ?page-1.
Any clues how to make an index page with arguments?
Comment: Apache DirectoryIndex directive https://amitoverflow.com/2021/04/29/how-to-use-directoryindex/
Answer: did it mylsef
RewriteEngine on
RewriteCond %{REQUEST_URI}  "^/$"
RewriteRule ^(.*) "http://domain-1.com/tiki-index.php?page=page-1"

The key here is to set rewrite condition to match empty URI, that is the default address - http://domain-1.com


Local DNS after Office 365 migration

Question: After migrating 50 mailboxes from SBS 2008 / Exchange 2007 to Office 365, we are finding that some Outlook 2013 clients are trying to connect to the old Exchange server.
I think this is related to internal DNS, resolving domain.com to the domain controller instead of externally.
Can someone please suggest a fix for this?
We can't disable the Exchange 2007 server yet as mail is still migrating using MigrationWiz.
Answer: Outlook, uses "Autodiscover" to find out where the user mailbox is, as long as you have Exchange server running in your network, the users will always be pointed to that server before anything.
There are different stages for autodiscover, listed here according to the order Outlook uses them:

SCP lookup: Exchange will save some helpful information for Outlook inside Active Directory, Outlook will query that information to find out where the user mailbox is.
HTTPS root domain query: Outlook will run a query to the domain name the user is using, for exmaple: https://testdomain.com/autodiscover/autodiscover.xml
HTTPS Autodiscover domain query: Outlook will add the domain "autodiscover" to the HTTPS root domain query: https://autodiscover.testdomain.com/autodiscover/autodiscover.xml.
HTTP redirect method for any of the links above.
SRV record query stored in DNS.
Local XML file configured by the admin.
Cached URL in the Outlook profile.

I would start with the SCP lookup method, as usually this is the default method for Outlook to find its mailbox inside a domain, you will need to disable that using the following steps:

Open Exchange Management Shell "EMS"
Run the command "Get-ClientAccessServer": this will list the Client Access Server "CAS" configured in your domain.
Run the command "Set-ClientAccessServer -Identity "CASName" -AutoDiscoverServiceInternalUri $NULL" to clear the SCP lookup information from the domain, where CASName is the result of the Get-ClientAccessServer command.

IMPORTANT NOTE: running this command will disable user access to the internal mailbox, you will need to configure each user who have their mailbox still hosted in the internal Exchange server manually.
Comment: Thanks! Clearing the SCP lookup worked. Outlook immediately connected to Office 365 instead of the local Exchange.

Local DNS after Office 365 migration


Definindo limite para query com UNION no MySQL

Question: Gostaria de saber como eu crio um limite para um query que utiliza UNION no MySQL, no meu caso eu quero definir o LIMIT 5 para a seguinte query:
$friends_a = mysql_query("(SELECT * FROM users WHERE id!='$user_q[id]' AND
id='$friends_1_q[user_one_id]') UNION ALL (SELECT * FROM users WHERE
id!='$user_q[id]' AND id='$friends_1_q[user_two_id]')");

Já tentei com vários códigos que eu encontrei na internet e não consigo, o que eu devo fazer?
Answer: Talvez isso resolva
$friends_a = mysql_query("(SELECT * FROM (SELECT * FROM users WHERE id!='$user_q[id]' AND
id='$friends_1_q[user_one_id]') UNION ALL (SELECT * FROM users WHERE
id!='$user_q[id]' AND id='$friends_1_q[user_two_id]') as tabela limit 5");

Comment: Não, não funcionou, retornou o query em branco.
O que se refere com 'tabela'?
Comment: tabela são os dados resultantes do UNION ALL, ou seja query1 UNION ALL query2 = tabela, então faço um SELECT para retornar todos os dados de tabela colocando o LIMIT 5.


Policy update equation - purpose of summation

Question: On the policy improvement equation, I'm confused about the need for the summation sign.

[Apologies for taking a picture - I didn't know how to type this equation in Latex
In the diagram below, if we wanted to estimate the policy for state s (left),my understanding is that we would compute each of:
pA * (rA + y* vA)
pB * (rB + y* vB)
pC * (rC + y* vC)
and whichever of the three (A,B,C) gives us the highest value will be the action we choose to take.
Why then do we have have a summation sign in the policy update equation? How would summing those three equations help?
Answer: You haven't quite understood how all this works, because (or so it appears to me) your notation mixed up actions and states.
Let us consider the value of being in state $s$ at some arbitrary stage.  If we have actions $a \in \{A,B,C\}$ to choose from at that stage - state combination, we'll choose whichever action gives us the maximum expected reward, hence the term $\arg \max_a$ before the summation term.  Now, the reward of a particular action comes in two parts, the immediate reward $r(s,a)$ and the value of finding ourselves in some state $s'$ at the next stage, $V(s')$.
Let's deal with the second term first.  When we select a particular action, in the general case there's no guarantee that we will end up at a particular state after the transition; it may be that action $A$ gives us probabilities $\{0.5,0.3,0.2\}$ of ending up in states $1,2,3$ respectively, action $B$ gives us probabilities $\{0.2,0.5,0.3\}$ for ending up in the three states respectively, and so forth.  Consequently, we need to calculate the expected reward related to the state transition by summing across all possible $V(s')$ weighted by the probabilities of finding ourselves in the various states $s'$ given the current state - action pair.  Since those values are dependent upon the policy $\Pi$ we're using, they are actually denoted $V_{\Pi}(s')$. The probabilities of the various future states $s'$ given the current state - action pair $(s,a)$ are denoted by $p(s'|s,a)$, so the expected value associated with the state transition can be written as:
$$\sum_{s'}p(s'|s,a)V_{\Pi}(s')$$
which is usually multiplied by a discount factor $\gamma$ to reflect the fact that future rewards are often considered less valuable the farther into the future they are.
Now for the first term.  Just because we've selected a particular action $a$ in state $s$ doesn't mean we have a guaranteed immediate reward $r$; the reward can be random, with a probability distribution depending on $s$ and $a$.  An obvious example is picking heads or tails in a coin flip; I win if I pick correctly, but I'm not guaranteed of winning, the coin flip itself affects the results.  So we can't just use the immediate reward, we have to calculate its expected value:
$$\sum_rp(r|s,a)r$$
Since both probabilities - of $r$ and $s'$ - are conditional upon only $s$ and $a$, we can combine the two expressions as follows:
$$\sum_{r,s'}p(r,s'|s,a)[r + \gamma V_{\Pi}(s')]$$
This gives us the expected value of choosing action $a$ when in  state $s$.  Our optimal policy $\Pi'$ when in state $s$ will choose the action that maximizes this value:
$$\Pi'(s) = \arg \max_a \sum_{r,s'}p(r,s'|s,a)[r + \gamma V_{\Pi}(s')]$$


Finding remainders from an encoding function

Question: Let's consider the encoding function:
$$y=ax \bmod 5$$
where $x$ is the number that corresponds to a certain letter in the alphabet.
I'm trying to understand why for every number $n$, with $n>4$, I can find a number a such as
$ax  \equiv nx \bmod 5$.
First of all, I'm trying to understand why, given a certain $x$, if a ranges between $[0,\ldots,4]$ I cover all possible remainders (that is the remainders from $0$ to $4$).
For example, if I take $x=3$, then:
$0=0*3 \rightarrow$ remainder is $0$
$3=1*3 \rightarrow$ remainder is $3$
$6=2*3 \rightarrow$ remainder is $1$
and so on...
But i don't know how to prove it... Can you help me?
Answer: As stated, your assertion is fals: if $x=5$ (or any multiple of $5$), then $ax\equiv 0\pmod 5$ regardless of what $a$ is.
But given $x$ not a multiple of $5$: if you want $ax\equiv r\pmod 5$ for some particular $r\in\{0,1,2,3,4\}$, then you can do so by choosing $a\equiv rx^{-1}\pmod 5$, where $x^{-1}$ is the modular inverse of $x$.
For a general modulus $q$ in place of $5$, this will be possiblie whenever $\gcd(r,q)=1$.
Comment: Why do we know at prior that, in this case, $x^{-1} \in \left \{ 0,1,2,3,4 \right \}$ ?


How to get defined display names (id) from selected view?

Question: Getting selected view is simple:

views_get_view('name');

I didn't find and have no idea what do next...
I need to get every defined view page path and add menu item to it.
Answer: This will loop through every page display and set a menu item.
<code>  $view = views_get_view('VIEW_NAME');
  foreach ($view->display as &$display) {
    if ($display->display_plugin == 'page') {
      // Add an if or switch statement here to check $display->id
      // so you can set different menu items for each display.
      $display->display_options['menu'] = array(
        'type' => 'normal', // Menu item type.
        'title' => t('Menu item title'), // Menu item title
        'description' => '', // Menu item description
        'name' => 'main-menu', // Menu name
        'weight' => 0, // Menu item weight
        'context' => 0, // Not sure off the top of my head what this is for.
      );
    }
  }
</code>
However this will set the same menu item for each display.
You will need to check the $display->id for each one so that you can set a different menu item for each display.
Also, that example sets a normal menu item.
If you want a local task or default local task it will be slightly different.
...also, why do you need to do this? why not add the menu item via the views UI?
Comment: "...also, why do you need to do this? why not add the menu item via the views UI?" Long story, I am migrating from Joomla. In this menu (besides links from Views) I need to add other links (dynamic - GET params). Migration must be repeatable too. I want to have it all in one place.


MongoDb arbiter can be used with multiple replicaSets?

Question: If I have different webpages for differents countries and each webpage have a mongodb replicaSet of 2-3 nodes, can I use an arbiter with more than one replicaSet so it votes in all?
Or I need to initiate an arbiter per replicaSet?
Comment: so you have more replicaSets and each replicaSet has 2-3 nodes, right? You want one single arbiter to be in multiple replicaSets?
Comment: the problem is that when you start a mongod instance you have to specify the -replSet parameter, thus linking a potential arbiter to that specific replicaSet. So, I don't think you can you a single arbiter on multiple replicaSets. But it wouldn't be much of a deal to start for each replicaSet a new arbiter, since arbiter instances are so lightweight.
Comment: Every solution for running MongoDB across multiple data centers is a tinkered solution..don't trust in everything marketing buzz made 10gen. The replication model of MongoDB is limited and is partly flawed.
Comment: Yeah, that's the question. I will wait some more to see but your answers seems logic.
Comment: As @AndreiSfat suggests .. a replica set member (arbiter or data node) can only belong to a single replica set.  The arbiter process is lightweight as it does not hold any data and only participates in elections.  The main purpose of arbiters is for situations where you have an even number of members in your replica set and need a tie-breaking vote.
Comment: @esaelPsnoroMoN can you argument your comment please? or share a link to any site with more info about that. Thanks.
Comment: I only want to maintain a copy outside my datacenter and switch to it if the datacenter fails. It's no critical if some data is lost in the switch.
Comment: well, first of all, I don't understand why would you want to struggle in having only one arbiter, since we have brought up some good arguments (lightweight) on having separate arbiter. You can have a single arbiter, but you cannot turn it on multiple replicaSets at once.
Comment: @AndreiSfat oh no, that answer is ok, I want arguments for "Every solution for running MongoDB across multiple data centers is a tinkered solution.."
Comment: @Wiliam, I think we don't want to touch that subject and start making a discussion about that, because we would compromise your question and we don't want to close you question. Let's stick with an answer, if not mine, maybe other will bring stronger arguments than me
Answer: You can have multiple arbiter processes running on a single server (different ports).  They are quite lightweight in terms of resources, as all they are doing is voting.  You should look into starting the arbiters with the following arguments to keep them as lightweight as possible (from the Command Line Parameters Page):

--smallfiles - Use a smaller initial file size (16MB) and maximum size (512MB)
--nojournal - Disable journaling. In v2.0+, journaling is on by default for 64-bit

If you do not run with those options, then the arbiter will still work, but will pre-allocate data files before it knows that it is an arbiter.
Update (Jan 2018): Since this answer was written official guidance has been added to the docs for startup options of an arbiter, including options in the new config format. It can be found here.
Comment: Thanks @Adam. This is a very important question&answer for me in order to reduce the amount of server but it's a bit out of date so: is your answer still valid for MongoDB 3.4?
Comment: @Delmo Yes, the way that arbiters work has not changed; they are still lightweight, so you can run multiple arbiters on a single instance. Double-check those parameters though, because the move to WiredTiger means they work a bit differently in recent MongoDB versions.
Comment: Thanks @VinceBowdren Added an update to reflect the current official guidance for more recent versions


Gerar PDF em Golang

Question: A dificuldade se encontra na criação da variável "err" na qual não consigo desenvolver, consegui perceber que o erro se dá pela fonte que o arquivo está tentando usar e minha máquina não possui o arquivo dessa font. Como é um arquivo do GitHub, não fui eu que fiz, peguei ele pronto para analisar a estrutura, vou disponibilizar o link.
https://github.com/signintech/gopdf
package main
import (
    "log"
    "github.com/signintech/gopdf"
)

func main() {
    pdf := gopdf.GoPdf{}
    pdf.Start(gopdf.Config{PageSize: *gopdf.PageSizeA4})
    pdf.AddPage()
    //err := pdf.AddTTFFont("wts11", "../ttf/wts11.ttf")
    err := pdf.
    if err != nil {
        log.Print(err.Error())
        return
    }

    err = pdf.SetFont("wts11", "", 14)
    if err != nil {
        log.Print(err.Error())
        return
    }
    pdf.Cell(nil, "您好")
    pdf.WritePdf("hello.pdf")
}

Answer: É possível compilar este exemplo, segue os passos que eu fiz para executar com sucesso:
Criei um projeto com o comando:
$ go mod init example.com/x

Criar um projeto com a seguinte estrutura de pastas:
.
├── _main.go
├── _ttf
    └── wts11.ttf

O arquivo wts11.ttf pode ser baixado no repositório que contém a lib gopdf. Ref. Abrir em um browser e baixar o arquivo (aprox. 10.1 MB).
Após fazer o download colocar o arquivo baixado na hierarquia de pastas descrita acima.
Agora será possível executar o programa:
main.go
package main

import (
    "log"

    "github.com/signintech/gopdf"
)

func main() {
    pdf := gopdf.GoPdf{}
    pdf.Start(gopdf.Config{PageSize: *gopdf.PageSizeA4})
    pdf.AddPage()
    err := pdf.AddTTFFont("wts11", "ttf/wts11.ttf")
    if err != nil {
        log.Print(err.Error())
        return
    }

    err = pdf.SetFont("wts11", "", 14)
    if err != nil {
        log.Print(err.Error())
        return
    }
    pdf.Cell(nil, "您好")
    pdf.WritePdf("hello.pdf")
}

Supondo que está na raiz do diretório do projeto e seguiu as instruções acima:
$ go run main.go

Após a execução com sucesso deve haver um arquivo hello.pdf na raiz do diretório do projeto.

Gerar PDF em Golang


Field type date bad formatting

Question: i have a strange issue with a field "date".
First i save it programatically this way :
$now = new \DateTime();
$node->set('field_paiement_date' => DrupalDateTime::createFromTimestamp($now->getTimestamp());
$node->save();

Then when i come on the content type in the back office i've got this value :
And finally when i dump the field in question i got this value :
My current timezone is 'Pacific/Noumea', so the correct value i want to show to the users is the one when i dump the field. What is the best way to do that ?
Regards,
Comment: You've stored the time in your local time, but you need to store it in UTC, see https://drupal.stackexchange.com/a/246668
Comment: ... then you print the raw database value. If you output the date field normally, that is by a field formatter configured in the display mode of the content type, then it should print the date in the current time zone. If you need to print the date field directly in twig, then use the `date` property, which is a formattable date object instead of the `value` property which is the raw data.
Comment: Okay now it's works thank you !
I have an other issue, in my twig template when i want to use the date filter, it always print as UTC but not at my current timezone ...
Answer: Datetime values in storage are UTC, if you are storing datetime values by your own, you have to pay attention on this and display datetimes to users considering your timezone ('Pacific/Noumea' probably declared in your php.ini or user's timezone present in user profile).
Storing 2018-05-02T08:23:25 as your current datetime in caledonia in database is a nonsense considering timezone, because the format DateTimeItemInterface::DATETIME_STORAGE_FORMAT do not include timezone.
$date = strtotime($node->field_paiement_date->value);
\Drupal::service('date.formatter')
  ->format($date, 'custom', 'Y-m-d H:i:s', drupal_get_user_timezone());
\Drupal::service('date.formatter')
  ->format($date, 'custom', 'Y-m-d H:i:s', 'Pacific/Noumea');

Field type date bad formatting


Reference request: infinitary Ramsey theory

Question: I was reading about the (various) infinite versions of Ramsey's theorem, and stumbled across a text containing a proof of the Bolzano-Weierstrass Theorem using it:

Unfortunately, I forgot where I found this article. It explained the whole topic very well and stated Ramsey's (infinite) theorem in a very clear way.

Does anyone recognize this text by chance? I searched this for a very long time.
I'd be grateful for similar reading recommendations; that is, "set-theoretic" approach to the infinite Ramsey theorem and infinite graphs in general.
Answer: This is from p. $15$ of the Forcing Summer School Lecture Notes by Spencer Unger, which are available in two slightly different versions here and here. I found them by searching for:

"by ramsey's theorem there is an infinite"  bolzano "whenever we"

I can see why you might not have found them – "whenever we define a coloring we think" seems like the most unique phrase to search for, but if you include "define" in the search it doesn't return any hits; it looks as if the 'fi' ligature messes up the search.
Comment: Nice searching technique! I tried various forms


Summarise survey of proportions

Question: I have asked N individuals for their estimate of the presence and quality of phone numbers in a database, i.e. missing, wrong, correct. I have received triples of percentages, e.g. (20, 30, 50)
How do best summarize the result and provide confidence intervals?
Answer: You can do it 'hierarchically'. First, choose one type of number, say missing, and compute percentages of two other types provided that they're not missing.
So for 20% missing, 30% wrong and 50% correct, you'll have 20% missing and among non-missing ones 5/8= 62.5% are correct, rest is wrong.
Now these two numbers (percent of missing numbers, percent of correct numbers among non-missing) are independent, so you can compute two CI's in usual way. The third one (for wrong, non-missing) will immedietaly follow from second one (
for correct, non-missing).
But note: I don't say that this is the best option. It is the one I find usefull.

Summarise survey of proportions


Is there a possible mathematical solution for this?

Question: I have what might be considered an odd question.  I want to see if I can find a formula/equation to help me with the following.
I'm working in a software package that we are using to calculate fees.  The problem is there are many limitations on what the application can do, such as little to no functions, character limits, etc.
I need to calculate a pro-rated fee based off of square footage and a month.
Examples:
250 sq ft in October is 50
3200 sq ft in April is 62.50
The base values come from a table, like so:
        0-499   500-999 1000-1999  2000-2999 3000-3999
10      50.00   60.00   75.00      100.00    125.00
11      45.83   55.00   68.75      91.67     114.58
12      41.67   50.00   62.50      83.33     104.17
1       37.50   45.00   56.25      75.00     93.75
2       33.33   40.00   50.00      66.67     83.33
3       29.17   35.00   43.75      58.33     72.92
4       25.00   30.00   37.50      50.00     62.50
5       20.83   25.00   31.25      41.67     52.08
6       16.67   20.00   25.00      33.33     41.67
7       12.50   15.00   18.75      25.00     31.25
8       8.33    10.00   12.50      16.67     20.83
9       4.17    5.00    6.25       8.33      10.42

I've got a nice nested If statement that works fine, however to use the full table (values go up to 60,000+ sq ft) goes well over the 3k character limit...
Here is a snip-it of that If statement:
If($[60RETAIL]MONTH$ = 1,
If(AND($[60RETAIL]SQFT$ > 0, $[60RETAIL]SQFT$ <= 499), 41.67 - 50,
(If(AND($[60RETAIL]SQFT$ > 499, $[60RETAIL]SQFT$ <= 999), 50 - 60,
(If(AND($[60RETAIL]SQFT$ > 999, $[60RETAIL]SQFT$ <= 1999), 62.5 - 75,
(If(AND($[60RETAIL]SQFT$ > 1999, $[60RETAIL]SQFT$ <= 2999), 83.33 - 100,
(If(AND($[60RETAIL]SQFT$ > 2999, $[60RETAIL]SQFT$ <= 3999), 104.17 - 125,
(If(AND($[60RETAIL]SQFT$ > 3999, $[60RETAIL]SQFT$ <= 4999), 125 - 150,
(If(AND($[60RETAIL]SQFT$ > 4999, $[60RETAIL]SQFT$ <= 5999), 166.67 - 200,
(If(AND($[60RETAIL]SQFT$ > 5999, $[60RETAIL]SQFT$ <= 6999), 208.33 - 250,
(If(AND($[60RETAIL]SQFT$ > 6999, $[60RETAIL]SQFT$ <= 7999), 250 - 300,
(If(AND($[60RETAIL]SQFT$ > 7999, $[60RETAIL]SQFT$ <= 8999), 291.67 - 350,
(If(AND($[60RETAIL]SQFT$ > 8999, $[60RETAIL]SQFT$ <= 9999), 333.33 - 400,
(If(AND($[60RETAIL]SQFT$ > 9999, $[60RETAIL]SQFT$ <= 10999), 416.67 - 500,
(If(AND($[60RETAIL]SQFT$ > 10999, $[60RETAIL]SQFT$ <= 19999), 500 - 600,
(If(AND($[60RETAIL]SQFT$ > 19999, $[60RETAIL]SQFT$ <= 29999), 583.33 - 700,
(If(AND($[60RETAIL]SQFT$ > 29999, $[60RETAIL]SQFT$ <= 39999), 666.67 - 800,
(If(AND($[60RETAIL]SQFT$ > 39999, $[60RETAIL]SQFT$ <= 49999), 750 - 900,
(If(AND($[60RETAIL]SQFT$ > 49999, $[60RETAIL]SQFT$ <= 59999), 833.33 - 1000,
(If($[60RETAIL]SQFT$ > 59999, 917.67 - 1100,
1))))))))))))))))))))))))))))))))))),

Multiply that by 12 and you can see how large it gets..  I'm hoping for an equation that I can use that will shrink my math down to a smaller solution..
Even possible?
Thanks!
EDIT:
I stuck this in the Mathematics section as I was looking for a math solution as the program I'm using has very little programming ability.  It looks like it is on hold for being in the wrong section?  If someone can think of a better area I'd gladly put it there!  My first post :)
Thanks!!
EDIT2:
I think the limitations of the software win this one.. even after shortening it a little with some of the great suggestions here, it still won't be short enough to fit in the character limitations.
That being said, I have a plan B involving SQL triggers/Stored Procedures that will work, was just trying to avoid using the back end.  However the ideas you've provided will help alot as the formulas will shorten my code on the back end!
Thank you everyone!!
Comment: Your best bet is to find out where the table came from and investigate the source.  It may have been generated by a simple rule.
Comment: Are those....  Nested if statements 0_0 ummm,  ugh,  ummm.... No,  no,  no
Comment: What kind of code is this?
Comment: The program is CityWorks, their fee section allows for some Excel/Vba style functions, but very few, no variables, etc.  It's really almost built for a straight "take the value entered in a box and add this" kind of thing.. makes for a challenge!
Answer: That part of the data seems to be piecewise linear:

The blue line ($f$) und red line ($f_2$) are:
$$
f(x) = 50 + (45.83-50)(x-10) \\
f_2(x) = 8.33 + (4.17-8.33)(x-8)
$$
If your programming language allows to define functions then you
can avoid repetition in your code by moving these statements
If(AND($[60RETAIL]SQFT$ > 499, $[60RETAIL]SQFT$ <= 999), 50 - 60

into a function with the changing data as parameters.
Reading the parameters for the $k$-th statement from same array variables
$p1[k]$, $p2[k]$ etc within a loop will further shrink your code.
If your data itself turns to be out all piecewise linear,
you can replace the data in the array with data generated from
the piecewise linear function called for some index parameters.
Comment: unfortunately you can't define functions or variables, but you've given me some ideas, i'll let you know what I figure out!  Thanks!
Answer: This seems to match
int A[] = {6000,7500,10000,12500};
int tmp = (sqft<500)? 5000 : A[sqft/1000];
int q = month<10? 10-month : 22-month;
return ((tmp * q +11)/22) * 0.01;

Comment: Forgot to mention you can't use variables, although there might be a function for arrays.. I'll have to look at that!
Answer: In each column of your table, the items obey a straight-line relationship with row number: The item in row 2 is $\frac{11}{12}$ of the item in row 1, the item in row 3 is $\frac{10}{12}$ of the item in row 1, and so on. In general the item in row $k$ is $\frac{13-k}{12}$ times the item in row $1$.
You can shorten your code by exploiting this relationship -- in order to reproduce the table you need only know the top row. But you need to be careful to map the month to the appropriate row number. (If the table always starts in October, then you could map October to k=1, November to k=2, December to k=3, etc., and then apply your formula to obtain fee[k].)
Comment: I think you may be on to something, going to try a couple of things and will post back.  Thanks!


What comes first on Exchange Quota or Vacation message?

Question: If I have a vacation message set in Exchange and I am over quota, will people get my vacation message or will they just get the exceeded quota message?
Answer: If the receiving user is over their receive quota, the sending user will receive a bounceback.
If the sender received the auto-reply (out of office message), they would assume that the message was received, which isn't the case, since the recipient was over quota.


If an event $A$ has $P(A)$=$1$, then $A^c$ is empty?

Question: I'm trying to see if the statement "if $P(A)=1, P(B)=P(B \cap A)$" is true.
My thought process was that
$P(B) = P(B \cap A)+P(B \cap A^c)$, and if $P(A)=1$, then $P(B \cap A^c) = 0$ because $A^c$ is empty, but I'm not sure if that is true. Intuitively, I believe the statement above should be true, but I'm not sure if my reasoning is okay.
Any comment or advice is appreciated!
Comment: If $\mathbb{P}(A) = 1$, then $\mathbb{P}(A^c) = 0$, but $A^c$ does not have to be the empty set.
Comment: Since $P$ is a (probability) measure, it is not true that $A = \Omega$ ($\Omega$ : sample space) even if $P(A) = 1$. Your reasoning is right **almost surely**.
Comment: It is false that $P(E)=0\implies P=\varnothing$
Comment: Then how could I argue that $P(B)=P(B \cap A)$ since $P(B \cap A^c)=0$, or is that statement false to begin with?
Answer: You're almost there.
However, as noted in the comments, it's not true that $A^c$is empty. What is true is that because $P(A)=1$, then $P(A^c)=0$.
It follows that $$P(B\cap A^c) \leq P(A^c)=0$$
Which yields the desired result.
Comment: No worries. I've been stuck one million times on simple stuff.
Comment: Ah, by the monotonicity of probability measures, right?
Comment: That's correct.
Comment: It's kind of frustrating to not be able to see something nearly trivial :/ thank you anyways!
Answer: Well you are write because as we know P(B)=P(A intersection B) this implies that B is contained in A or B will only happen if A happen this means that B will not happen if A did not happen so P(B intersection A') is zero but also we know A is sure event this means P(A')=1-P(A)=0 .But this does not means that A is an empty set.


How to make width of dropwdown items Flexible?

Question: http://www.lwis.net/free-css-drop-down-menu/dropdown.simple.horizontal.html
in this sample width of dropdown is fixed
ul.dropdown ul {
margin-top:1px;
width:150px;}

I need width of drop-down dependable of Character inside  without breaking in 2 line
width should depend on text.
Answer: Set a min / max width, or, not set a width at all (and add some padding)?
min-width{10px;}
max-width{15px;}

I know min/max-width will not be supported in IE7 or below
Answer: The following two additional style declarations in Firebug gave me the results you're asking for.
ul.dropdown ul
{ width: auto; }

ul.dropdown ul li
{ white-space: nowrap; }

Answer: Block level elements don't collapse down to the width of the contents. You might be able to get around this with inline-block, but that could get tricky.
Might be best to use javascript to calculate the width based on the widest LI. Let it load sans a specific width, have javascript kick in looping through each  in each
 to find the widest, and then set the UL to that specific width.


how to classify input image using clustering algorithm such as k-mean?

Question: I want to classify cifar10 images using a clustering algorithm (k-mean). Each image in the cifar10 dataset has a label, so, the results must be a set of labels which are corresponding to the test images.
The input of the proposed code (k-mean) is a text file contains a numbers (I do not now what these numbers). The dataset that I used are available here CoverType. The output that I have is like this::

3204.0,184.0,14.0,277.0,41.0,2803.0,223.0,249.0,156.0,966.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,2.0
  2916.0,231.0,9.0,240.0,30.0,1874.0,206.0,249.0,180.0,1729.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,5.0
  2782.0,144.0,16.0,210.0,18.0,953.0,241.0,235.0,119.0,735.0,0.0,0.0,1.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,3.0
  3112.0,17.0,9.0,247.0,33.0,5032.0,213.0,221.0,145.0,1104.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,2.0
  3081.0,86.0,7.0,297.0,44.0,1503.0,230.0,229.0,132.0,2758.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0
  3031.0,44.0,22.0,283.0,19.0,4904.0,219.0,186.0,91.0,3078.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0
  2888.0,150.0,13.0,242.0,56.0,845.0,236.0,239.0,130.0,1611.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,2.0
  2884.0,37.0,12.0,283.0,29.0,3127.0,219.0,212.0,126.0,2336.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,2.0
  3001.0,115.0,9.0,418.0,36.0,5227.0,236.0,232.0,127.0,5615.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,2.0
  3035.0,80.0,5.0,60.0,-4.0,3216.0,227.0,230.0,137.0,5356.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0

I have many questions about this issue::
1- In my case what the inputs should be?
3- I know that the output must be a set of clustering (K) and in this case K=10. The output has 10 lines(statement). Does each line represent a cluster? and what each line mean?
2- How can I use this output of the k-mean to classify an input test image and return its label?
Answer: I quite don't understand what you are trying to do, but K-means is an unsupervised learning method, hence it doesn't need/use labels.
K-means rather calculates the distances based on the pixel values and so groups the images in clusters.
You could take a look at this medium article.
Comment: If you would use k-means without any previous feature extraction such as HOG or similar, your input for the algorithm would be indeed only the 3D array of values from 0 to 255. But k-means can be used with any data consisting of numerical values. Of course, it is not guaranteed to give a good clustering. You wrote that you don't know what the values in your dataset represent. This information should be found on the website you downloaded the data from. You could also just perform k-means without the knowledge of your data, which is highly don't recommend.
Comment: I update my question, I wrote something wrong and I correct it. I know that the k-means are unsupervised learning method. but I want to use it with supervised data.
Comment: Why aren't you just downloading the CIFAR-10 data from here: https://www.cs.toronto.edu/~kriz/cifar.html. Normally, the data should consist of 3D numpy arrays that represent RGB images. So the values should range from 0 to 255. You can than use those values for the K-Means algorithm
Comment: because I write the cifar10 as an example. But actually I would work in my own data-set.
Comment: Did you mean the input into the k-means is the images pixels values without any extract features??
Answer: I doubt that k-means will help you anything:

It is unsupervised. It will not output a label learned from the data.
It probably does not produce satisfactory results on the cigar data set.

Rather I believe you have not understood the problem, and what the k-means algorithm does. Because these two things don't combine.


Systemd, how to mount a device at boot, but disable automount after boot

Question: I do not seem to find a simple solution to the following problem:
I have a device listed in fstab, this should get mounted at boot. But if I manually unmount/remove the device after boot and if I present the device later on, systemd sees the device and automatically mounts it.
So how to prevent the latter (like pre-systemd behaviour). I can not use noauto in /etc/fstab since that will disable mounting at boot, which I still want to have.
There are some ways to workaround systemd for this problem. But I would like to see it fixed with using systemd.
After some digging it seems that the fstab systemd generator is creating device units and mount units. The generator seems to add implicit values to this generated device unit, one of them is a "Wants" to the mount unit. Causing a dependency between the mount and the device. How can I influence or override the systemd generators so that it does not create this "Wants" dependency between the device and the mount?
show dev-mapper-test.device |grep -i wants
Wants=mnt-test.mount
But now the tricky part, even if you could override that "wants" then also starting at boot will be disabled...
Thanks
Comment: Related: [systemd: Cannot disable generated unit file](https://unix.stackexchange.com/q/405566/143394)
Answer: You can write systemd unit with Type=oneshot.
Type=oneshot: this is useful for scripts that do a single job and then exit.
Example:
<code>[Unit]
Description=one_mount
After=network.target

[Service]
Type=oneshot
ExecStart=/usr/bin/mount /dev/partition /path/to/point
ExecStop=/usr/bin/umount /path/to/point

[Install]
WantedBy=multi-user.target
</code>
Comment: Thanks, but how to override the generated unit files out of fstab with this type?


Heptathlon point system calculation

Question: Are there equations that are used to calculate the scores (as in diving and such)?
If so, what are these equations?
And if not, please state how the points are calculated.
Answer:
The scoring system was developed by Dr. Karl Ulbrich. The events are split into three parts, where the scores are counted according to the three formulae:
Running events (200 m, 800 m and 100 m hurdles):

Jumping events (high jump and long jump):

Throwing events (shot put and javelin):

P is for points, T is for time in seconds, M is for height/length in centimeters and D is length in meters. a, b and c have different values for each of the events (see table).

Wikipedia.
The point are given for every event and sum up to the heptathlete score (A competitor in a heptathlon is referred to as a heptathlete).
Comment: Please note that the men's events have different a,b,c values.
Comment: @Ste Mens are competing in Decathlon.
Comment: At the Olympics yes, but not in Indoor Athletics.
Comment: To add to this: in competition, these scores are not calculated, but rather assigned from a table which is calculated from these formulas.

Heptathlon point system calculation


Defining homotopy fiber "naturally"

Question: For a map $f\colon A\to B$, many authors define the mapping fibration $E_f\to B$, where $E_f$ consists of pairs $(a,\gamma)\in A\times B^I$ with $\gamma(0)=f(a)$, and the fibration map is $(a,\gamma)\mapsto \gamma(1)$. The fiber $F_f$ is the homotopy fiber, and consists of pairs $(a,\gamma)$ with $\gamma$ a path from $f(a)$ to a basepoint $b\in B$.
At the same time, there are many god-given fibrations lying around that are confusing similar. For example, we have $B^I\to B$, with $\gamma\mapsto \gamma(0)$. As sets, $E_f$ is just the pullback of $f$ along this fibration. However, this doesn't actually produce the right fibration map $E_f\to B$ is any obvious way.
So my (soft) question is the following:

Is there a way to define the homotopy fiber of a map $f\colon A\to B$ which is "natural" in the colloquial sense?

I should also clarify that I don't know any model theory and am asking this as a newcomer to homotopy theory.

Partial answer:
The most satisfying solution I have found is to start with the path fibration $PB$ consisting of paths starting at a basepoint $b_0$. The map $PB\to B$ with $\gamma\mapsto g(1)$ is a fibration, and $F_f$ is the pullback of $f\colon A\to B$ along this. This is almost satisfying, but still requires picking this evaluation map.
Comment: Would a better word be 'canonical' rather than 'natural'? The path space fibration is perfectly natural.
Answer: Tldr; jump to the $(\ast)$.
The category $Top$ of topological spaces is complete and cocomplete. That is, all limits and colimits exist in the category. On the other hand, the homotopy category $hTop$, formed by quotienting out the (weak) equivalences, is neither complete nor cocomplete. In fact while it has products and coproducts, it has very few other limits or colimits. See here for some examples of pullback/pushout squares which do not exit in $hTop$.
The point is that the strict fibre of an arbitrary map $f:X\rightarrow Y$ over a point $y\in Y$ is the equaliser of the two maps $f,c_y:X\rightrightarrows Y$, where $c_y$ is the constant map at $y$. Now this is not a good homotopical notion, in general, due to the lack of limits in $hTop$. It is a theorem that if a category has equalizers and finite products then it has all finite limits, and we have already noted above that $hTop$ does not even have all pullbacks. Since it has products $hTop$ cannot have all equalisers.
To see exactly what goes wrong consider the fact that the strict fibres of $f:X\rightarrow Y$ over the different points of $Y$ will not in general have the same homotopy type (even keeping within the same path component). For instance consider the map $S^1\rightarrow \mathbb{R}$ induced by projecting onto the first coordinate; the fibres are either empty, have one point, or have two points.
A sufficient condition that all the strict fibres over all points in a given path component have the same homotopy type is that the map $f$ is a fibration. And this is what the homotopy fibre does: it replaces the map $f$ by a fibration $p_f:E(f)\rightarrow Y$ and then takes its strict fibre over a given point. For everything to make sense we require some comparison map $j_f:X\rightarrow E(f)$ which is a homotopy, or at least weak, equivalence, and that everything should be natural - in the mathematical sense - at least up to homotopy.
Note that this 'up-to-homotopy' comparison map $j_f$ is the best we can do, for if $j_f$ were a homeomorphism, then the map $f$ would already be a fibration, and its homotopy fibres would just be its strict fibres. Thus if it were always possible to replace a map by a fibration up to homeomorphism, then there would be no need for homotopy fibres to begin with.
$(\ast)$ Now, the point is that the homotopy fibre of a map $f:X\rightarrow Y$ does not really live in $Top$. Since at best we can ask for the map $j_f$ to be a homotopy equivalence, the homotopy fibre of $f$ really lives in the homotopy category $hTop$ where it makes sense to consider the objects $X$ and $E(f)$ as the same. And now in the homotopy category everything is perfectly canonical, since $X$ and $E(f)$ are the same object as seen through categorical eyes. For example in the path space fibration we no longer have to pick an evaluation, since all these maps are homotopy equivalent, and thus represent the same morphism in $hTop$.
Thus we realise that the object $E(f)$ is nothing but an auxiliary construct. It is a point set lift of the problem in $hTop$ to a problem in $Top$. It allows us to create a more understandable model for the problem by using spaces with points, and maps defined on elements, rather than having everything 'up-to-homotopy'. However there is no canonical way to achieve this. For, just as the strict fibres of an arbitrary map $f:X\rightarrow Y$ may be badly behaved, the fibres of the projection $Top\rightarrow hTop$ are not uniform. Asking for a canonical section of this map is too much.
Thus we content ourselves with mathematically natural (again, up to homotopy) constructions point-set constructions, happy with the knowledge that once we project the problem back to $hTop$ we truly do have something safe and canonical.
Answer: A general philosophy is that you want "equivalent" (in a suitable homotopical sense), not "equal".
The strict notion of the fiber over the basepoint $b$ of a map $f : A \to B$ is that it is a space whose points correspond to having a point $a \in A$ together with an assertion that $f(a) = b$.
In homotopy theory, that auxiliary data should consist of an equivalence $f(a) \simeq b$ rather than asserting an equation, or even merely asserting the proposition that an equivalence exists. So, in a formal sense, the points of the homotopy fiber over $b$ should consist of pairs $(a,p)$ where $a$ is a point of $A$ and $p$ is an equivalence between $f(a) \simeq b$.
The typical way of expressing an equivalence is as a path: given $b, b' \in B$, an equivalence from $b$ to $b'$ is given by a path $p : I \to B$ with $p(0) = b$ and $p(1) = b'$.
This construction topologizes in a natural way; we should get a model for the homotopy fiber over $b$ by taking the subspace of $E_f \subseteq A \times B^I$ comprised of pairs $(a,p)$ such that $f(a) = p(0)$ and $b = p(1)$.
I am, of course, glossing over the work in elaborating if and how this sort of thing works coherently to describe the sorts of things we intend to describe; I hope, however, it's enough to get an idea about the motivation.

As a systematic construction, you should consider the fibration $B^I \to B \times B$  (whose components are the "start point" and "end point" maps) as a topological object representing all the different equivalences possible between two points of $B$.
In particular, given any point $(b, b') \in B \times B$, the (strict) fiber over that point represents the space of all equivalences $b \simeq b'$. Topologically, of course,
this is the space of all paths (with fixed endpoints) from $b$ to $b'$.
So, given variables $a \in A$ and $b \in B$, the way to express $f(a) \simeq b$ is to take the pullback bundle
$$ \require{AMScd} \begin{CD}
M @>>> B^I
\\ @VVV @VVV
\\ A \times B @> f \times 1_B>> B \times B
\end{CD} $$
Then the (strict) fiber of $M \to A \times B$ over any specific point $(a_0,b_0)$ is precisely the space of all equivalences $f(a_0) \simeq b_0$. And if you fix a specific $b$, this construction becomes precisely the one discussed above
$$ \require{AMScd} \begin{CD}
E_f @>>> B^I
\\ @VVV @VVV
\\ A @> f \times \{b\}>> B \times B
\end{CD} $$
Your example comes from fixing one of the endpoints as an intermediate step: we have three pullback squares
$$ \require{AMScd} \begin{CD}
F_f @>>> PB @>>> B^I
\\ @VVV @VVV @VVV
\\ A @>f>> B @> \{ b \} \times 1_B  >> B
\end{CD} $$
The strict fiber of $PB \to B$ over $b' \in B$ is the space of equivalences $b \simeq b'$, and then the strict fiber of $F_f \to A$ over $a \in A$ is the space of equivalences $b \simeq f(a)$.

Defining homotopy fiber "naturally"


Cylindrical hoof lateral surface and volume

Question: I am trying to figure out the proof for lateral surface and volume of a cylindrical hoof (or, more generally, a cylindrical wedge) given by Wolfram MathWorld but I am having some trouble understanding it. I would be grateful if someone could explain it in details. THanks.
Comment: What part of the proof? What do you understand? What do you understand? Is there an unfamiliar concept present? Please be _specific_.
Comment: You are primarily interested in the cylindrical hoof formulas, correct?
Comment: Yes, that is correct.
Answer: For this problem we will use the variables and diagram as shown on Wolfram Math World .
The first thing we need to do is compute the equation of the plane cutting out the hoof. We have four points on the plane: $(0,0,0)$, $(0,R,0)$, $(0,-R,0)$, and $(R,0,h)$.
We can write any plane in the form $Ax+By+Cz+D=0$. Plugging in $(0,0,0)$ we get $D=0$. Now plugging in $(0,R,0)$ we get $BR=0$, so $B=0$. Finally, using $(R,0,h)$, we get $AR+Ch=0$ so $C=-\dfrac{AR}{h}$. Thus, we get the equation of the plane as
$$Ax-\frac{AR}{h}z=0$$
and dividing through by $A$ (possible because $A=0$ gives a degenerate answer) and rewriting gives
$$hx=Rz.$$
Now, in order to proceed, we need to perform some integration. First we shall find the volume $V$. If we imagine vertical slices (more precisely the intersection of planes parallel to the $y$ $z$ plane), we get rectangles of height $z(x)=\dfrac{h}{R}x$ and width $y(x)=2\sqrt{R^2-x^2}$. The height here comes from our plane equation and the width comes from the equation for the base of the cylinder: $x^2+y^2=R^2$. Onto our integration!
$$V=\int\limits_{0}^{R}z(x)y(x)\,dx=\frac{2h}{R}\int\limits_{0}^{R}x\sqrt{R^2-x^2}\,dx$$
Letting $x=R\sin t$ we have
$$
V=\frac{2h}{R}\int\limits_{0}^{\pi/2}R\sin t\sqrt{R^2-(R\sin t)^2}R\cos t\,dt
=2hR^2\int\limits_{0}^{\pi/2}\sin t\cos^2 t\,dt
=\frac{-2hR^2}{3}\cos^3(t)\Biggr|_{0}^{\pi/2}
$$
Hence $V=\dfrac{2}{3}hR^2$ as desired.
To find the lateral surface area $LSA$, we imagine taking flat slices (more precisely the intersection of planes parallel to the $x$ $y$ plane), and we get varying sizes of arcs of a circle of radius $R$. We use the fact that an arc has length $R\theta$ where $\theta$ is the central angle of the arc (for reference you can see this Wolfram Math World article). Since $x=R\cos\frac{\theta}{2}$, we have $z=h\cos\frac{\theta}{2}$, so $\theta=2\cos^{-1}\frac{z}{h}$. Hence
$$LSA=\int\limits_{0}^hR\theta\,dz=2R\int\limits_{0}^h\cos^{-1}\frac{z}{h}\,dz$$
Letting $z=h\cos t$ we get
$$LSA=-2Rh\int\limits_{\pi/2}^0t\sin t\,dt=2Rh\int\limits_0^{\pi/2}t\sin t\,dt=2Rh(-t\cos t+\sin t)\Biggr|_{0}^{\pi/2}$$
Hence $LSA=2Rh$ as desired.
Answer: The problem of the volume of Archimedes hoof has been carefully laid out and solved in the published article The Method of Archimedes: Propositions 13 and 14 and there are some animations and Mathematica$^{\circledR}$ code here: The Method of Archimedes: Propositions 13 and 14.
I have also done work on the surface area, but this has not been published. Basically, what you do is separate the surface into three part: base, slant plane, and cylindrical collar. Here is an interesting result for you to ponder...
$$A_{plane}+A_{base}=2A_{base}\Phi=\pi\Phi$$
Yes, that's $\Phi$, the golden ratio. (This result is for a hoof in a $2\times2\times2$ cube.) I can also tell you that the surface of the cylindrical collar is $2h=4$.
I'm reluctant to go into further detail on a post that is now two years old. Please, someone let me if there is still interest out there!


Exact calculation of $\sum_{n=0}^\infty \cos(36^\circ)^n$

Question: Right now we are covering geometric series.To find $\cos 36^\circ$ I use the sum and difference formula.
Knowing that $\cos36^{\circ} = \frac{1+\sqrt{5}}{4} = \phi/2$ calculate $\sum_{n=0}^{\infty}\cos^n36^{\circ}$ and express it in terms of $\phi$.
Should I just use the common ratio as $\cos 36^\circ$? How can I solve this?
Knowing that $\cos18^{\circ} = \frac{-1+\sqrt{5}}{4} = \psi/2$, calculate $\sum_{n=0}^{\infty}\cos^n18^{\circ}$ and express it in terms of $\psi$.
Comment: Yes, it is a geometric series with common ratio $\phi/2 = \cos 36^\circ$...
Answer: Well $$S=\sum^\infty_{n=0}\cos(36º)^n=\sum^\infty_{n=0}\bigg(\frac{\varphi}2\bigg)^n$$
Now \begin{align*}S&=1+\frac{\varphi}2+\bigg(\frac\varphi2\bigg)^2+\bigg(\frac\varphi2\bigg)^3+\ldots\\\frac\varphi2S&=\;\;\quad\frac\varphi2+\bigg(\frac\varphi2\bigg)^2+\bigg(\frac\varphi2\bigg)^3+\ldots \\\end{align*}
Therefore $$S\cdot\frac{\varphi}{2}=S-1\implies S=\frac{2}{2-\varphi}$$
Use a similar approach for the other sum considering that $\psi=\varphi^{-1}$...
Comment: You've offset the sum by one term.
Comment: Thanks @J.G., I hadn't noticed
Comment: sorry for such a simple question but can you please explain a little more how you got the sum? the last two lines are what im having trouble with
Comment: @user130306 I simply expanded $$\sum_{n=0}^\infty \bigg(\frac{\varphi}2\bigg)^n$$ in the first line. In the second one, I multiplyed $S\cdot\varphi/2$ because it is the common factor. Substracting $S$ from $S\cdot\varphi/2$ yields the third line.
Comment: but why does $s-1$ imply $2/2-\phi$? im just confused what formula you are using and what the common ratio is
Answer: The first sum is a geometric series with ratio $\frac{\phi}{2}$ and so is equal to
$$
\frac{1}{1-\frac{\phi}{2}}
$$
Since $\phi^2=\phi+1$, we get
$$
\frac{1}{1-\frac{\phi}{2}} = \frac{2}{2-\phi} = 2(1+\phi)
$$
The second sum is handled in exactly the same way.
Comment: how do you get $2/(2-\phi)$?
Comment: @user130306, I guessed that it is of the form $a+b \phi$ and found $a=b=2$ using $\phi^2=\phi+1$.
Answer: Both sums are convergent geometric series of the form $\sum_{n\ge 0}r^n=\frac{1}{1-r}$: the first is $\frac{1}{1-\phi/2}$, while the second is $\frac{1}{1-\psi/2}=\frac{1}{1-1/(2\phi)}$.


Accessing Contents of "System.Reflection.Pointer"? (Python 3.10)

Question: I'm calling a set of C# functions from a Python 3.10 script via the clr module from the PythonNet library. One of those functions returns a pointer of type System.Reflection.Pointer, that points to an array of float values.
I'm quite a bit confused as to how I'm exactly supposed to acquire or access the actual float array that the System.Reflection.Pointer variable is supposedly pointing to.
In my Visual Studio 2022 IDE, I can see that the pointer variable has a few class functions, such as ToString() or Unbox(), however none of those give me the desired float array.
What is the proper way of accessing the data pointed to by a System.Reflection.Pointer variable in Python?
Thanks for reading my post, any guidance is appreciated.
Answer: You can't do that with only Python.NET APIs. Create a C# converter(as a class library and call it in Python, like the following example.
In C#, do like this.
using System.Reflection;

namespace Example;
public class Converter
{
    public static unsafe IntPtr PointerToIntPtr(Pointer p)
    {
        return (IntPtr)Pointer.Unbox(p);
    }
}

In Python, do like this.
import clr

clr.AddReference('path to the .NET dll')
import Example
...
# The ptr is assumed to be an instance of System.Reflection.Pointer
addr = Example.Converter.PointerToIntPtr(ptr).ToInt64()
# The addr will be an int.

Comment: Unfortunately, I'm unable to access or edit anything on the C# side here. I'm interfacing with some software, that was pre-packaged. I saw some other users talk about a `Marshal` class in C#, and it's class function `Copy`, however I have no idea how to use it. Would that be closer to what I need?
Comment: You don't need to modify existing C# modules. You need to create a new [class library](https://learn.microsoft.com/en-us/dotnet/standard/class-libraries). It's very easy but you have to learn for a few hours if you don't have experience with C# and .NET.


Vibrate iPhone while Recording

Question: I'm trying to get my iPhone to vibrate while I'm recording.
I've tried this:
UInt32 category = kAudioSessionCategory_PlayAndRecord;
status |= AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(category), &category);
UInt32 allowMixing = true;
status |= AudioSessionSetProperty (
      kAudioSessionProperty_OverrideCategoryMixWithOthers,  // 1
      sizeof (allowMixing),                                 // 2
      &allowMixing                                          // 3
       );
status |= AudioSessionSetProperty(
      kAudioSessionProperty_OtherMixableAudioShouldDuck, // 1
      sizeof (allowMixing),        // 2
      &allowMixing          // 3
       );

As suggested here. Then vibrate the device later on by calling
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);

But it does not work. But it does not vibrate. It records fine, and if I call a vibrate moments before I stop recording it vibrates after stop it.
Apparently it's a bug, does anyone know of a work around?
Comment: Seems like that would be a great way to reduce the quality of the recording...
Comment: Define "it does not work". Does it vibrate but not record? Does it record but not vibrate? Neither?
Comment: Quality is not an issue. I'm just doing some sound basic sound processing and vibrating after certain sounds. The user will never hear the audio thats being processed, it's never saved, etc.
Answer: AT LAST! As of iOS 13, there is a new property on AVAudioSession
        let _ = try? AVAudioSession.sharedInstance().setCategory(.playAndRecord)
        if #available(iOS 13.0, *) {
            let _ = try? AVAudioSession.sharedInstance().setAllowHapticsAndSystemSoundsDuringRecording(true)
        }

Comment: This should be the answer!! Thanks mate
Answer: My guess is that the vibration functions are specifically suppressed during audio recording. You could easily test this by doing something else that would normally make the phone vibrate (e.g. send yourself a text message with the mute switch on) while you are recording your audio—my bet is that it won't vibrate for that, either.
This earlier thread confirms my view.
Comment: Forgot about this question. This answer will do. I actually overcame the problem with a bit of jailbreaking and some other jiggery-pokery.
Comment: can you please guid me... i am using MPMoviePlayerController and if i wan to record video withought any audio then can i vibrate my phone while recording the video???
Comment: here is my question http://stackoverflow.com/questions/21059607/how-to-use-vibration-while-recording-iphone5-ios... can you please see my question related to this

Vibrate iPhone while Recording


Defining prior on variance and not precision

Question: I know that WinBugs uses precision as a parameter in dnorm instead of variance
 model {

    #Likelihood
        for(i in 1:N1){
            y1[i] ~dnorm(mu,tau)
        }

    sigma <- sqrt(1/tau)

    #Priors
    mu ~ dnorm(0,0.000001)
    tau~ dgamma(taumu, taus)
   }

My question is: if instead I want to specify the prior for sigma because I know its mean and variance would it be right to use the following model ?
  model {

    #Likelihood
        for(i in 1:N1){
            y1[i] ~dnorm(mu,tau)
        }

    tau <- sqrt(1/sigma)

    #Priors
    mu ~ dnorm(0,0.000001)
    sigma ~ dnorm(sigmamu, sigmas)
   }

Thanks in advance
Comment: you cannot put a normal prior on a positive quantity.
Comment: If you know or set mean and variance for $\sigma$, then you can pick one and only one inverse gamma distribution with the same mean and variance. Or any other distribution on the positive real line with the same mean and variance. But you cannot "have that the variance is normally distributed" because this is impossible.
Comment: On the [Wikipedia page about the inverse gamma](http://en.wikipedia.org/wiki/Inverse-gamma_distribution), the connection between natural parameters and mean and variance is available.
Comment: @Xi'an thanks. So if I calculate the shape parameters from the known sigmamu and sigmas values these are the parameters of the inverse gamma for the precision and not the variance?
Comment: @Xi'an thanks I understand it but I have that the variance is normally distributed with mean sigmamu and std sigmas so how can I do to convert these information into precision?
Comment: @Xi'an thanks but I think what I am trying to understand is given sigmamu and sigmas how I find the corresponding inverse gamma.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/20233/discussion-between-xian-and-user3706794).
Answer: If "sigma <- sqrt(1/tau)" as indicated in the model on the top, then how is "tau <- sqrt(1/sigma)"?
$\sigma = 1/\sqrt\tau \implies \sigma^2 = 1/\tau \implies \tau = 1/\sigma^2$.
Answer: In the second model, tau <- sqrt(1/sigma) is wrong; it should be tau <- 1/sigma^2.  You also cannot give a normal distribution to a non-negative random variable, so you will need to choose a different distribution for $\sigma$. If you simply want to keep the same form as Model 1 but set your prior mean and variance for $\sigma$ to known values, this can be accomplished by checking the appropriate moments for the gamma prior and using some algebra to get the desired moments.


Arduino ethercard.h get dhcp option

Question: Is there any way to get a specific dhcp option using Arduino and ethernet?
I am trying to spare the pins that would be used as a setup, so i send the configuration to the arduino via lan.
I would like to be able to specify where the arduino will receive the configuration from.
I was thinking of providing it with a configuration server through a dhcp option (option codes 224 through 255 are reserved for private use)
I cannot find any information on how to retrive specific dhcp options using ethercard.h and ENC28J60 board anywhere in the documentation.
Did anyone attempt (and succeed) in doing this?
thanks
Answer: After some extensive reading of the ethercard source, i came up with this:
Add ether.dhcpAddOptionCallback(246,DHCPOption); to void setup, and this void:
<code>void DHCPOption(uint8_t option, const byte* data, uint8_t len) {
    Serial.println(option);
    Serial.println(len);
    for (int i = 0; i < len; i++) {
        Serial.println(data[i]);
    }
}
</code>

Arduino ethercard.h get dhcp option