Vetor de char por referência

Question: Estou tentando passar uma array de char para uma procedure que irá redimensionado (com malloc()), escrever seu conteúdo e voltar ao main().
Sei que todo vetor é um ponteiro e já é passado por referência, mas algo no meu software não esta deixando isso acontecer, quando voltar para a função main() ele esta com os valores iniciais, segue código de exemplo:
#include <stdio.h>
#include <stdlib.h>

void proc(char msg[])
{
    unsigned int i;

    msg = malloc(sizeof(char) * 10);

    msg[0] = 'a';
    msg[1] = 'b';
    msg[2] = 'c';
    msg[3] = 'd';
    msg[4] = 'e';
    msg[5] = 'f';
    msg[6] = 'g';
    msg[7] = 'h';
    msg[8] = 'i';
    msg[9] = 'j';

    for (i = 0; i<10; i++) {
        printf("%c\n", msg[i]);
        msg[i] = 'x';
    }

    printf("\n");
}

int main ()
{
    char msg[] = "12345";
    unsigned int i;

    printf("Before proc\n");

    for (i = 0; i<5; i++) {
        printf("%c\n", msg[i]);
    }

    printf("\nin proc ======\n");

    proc( msg );

    printf("After proc\n");

    for (i = 0; i<10; i++) {
        printf("%c\n", msg[i]);
    }

    printf("FIM");
    return 0;
}

A saída é a seguinte:

bash-4.2$ ./a.out
Before proc
1
2
3
4
5

in proc ======
a
b
c
d
e
f
g
h
i
j

After proc
1
2
3
4
5

FIM

Onde estou errando?
Comment: Qual é o objetivo? A função está bem esquisita, faz coisas meio sem nexo.
Comment: Fiz só um exemplo para tentar isolar o problema que estou tendo ao ler uma porta serial, o que quero é:

1. passar um array de char para uma procedure
2. redimencionar esse array na procedure
3. escrever valores nessa array
4. retornar o main com a array dimencionada e com os novos valores
Comment: Ou seja, qualdo voltar para o main o vetor tem que estar todo preenchido com 'x' e ter tamanho de 10 bytes.
Comment: Você começa trabalhando com uma *string*, depois abando na isto, qual é o correto, é uma *string* ou não?
Comment: O correto é trabalhar o tempo todo com uma string, posso estar errando exatamente nisso, mas tem que ser dinámico.
Comment: A resposta resolveu sua dúvida? Acha que pode aceitá-la? Veja o [tour] se não souber como faz. Isso ajudaria muito indicar que a solução foi útil para você. Também pode votar em qualquer pergunta ou resposta que achar útil no site todo (quando tiver 15 pontos).
Answer: Tem vários erros e complicações. Mantive as escritas para ver funcionando, mas obviamente que isto não deveria existir aí.
Se vai trabalhar com string faça o tempo todo assim. Precisa ter espaço para o terminador.
Se vai alterar o tamanho então precisa alocar o array dinamicamente com malloc().
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void proc(char msg[]) {
    msg = realloc(msg, 11);
    strcpy(msg, "xxxxxxxxxx");
    printf("\nin proc ======\n%s\n", msg);
}

int main() {
    char *msg = malloc(6);
    strcpy(msg, "12345");
    printf("Before proc\n%s", msg);
    proc(msg);
    printf("After proc\n%s\nFIM", msg);
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Não liberei a memória com free() porque em tese iria usar em outro lugar.
Não verifiquei se a alocação funcionou, o que torna o código menos robusto. O normal é fazer isto com malloc() e realloc().
Mas em determinados contextos nada disso é o correto e precisa de uma solução bem diferente desta, especialmente em ambientes embarcados.
Comment: Obrigado, tem algum exemplo ou referência de como fazer isso em sistemas embarcados?
Comment: Depende do que precisa fazer.
Comment: Quero tratar o que vem pela serial mas não sei o tamanho do que vem na serial, por isso estou fazendo array dinamica.
Comment: Precisa criar uma estratégia de *buffer*, mas me parece que é algo avançado para seu conhecimento e depende de várias coisas para decidir como fazer.
Comment: Se fiver um treixo de código vou estudando, mas por hora obrigado.

Vetor de char por referência


How can I list the current user's posts?

Question: How can I list all posts of the current user? I know I should use Views, but how do I do it?
Answer: You can use 'filter by current user' in the Views module.
Answer: The core Tracker module does this per user.


dj-stripe DJSTRIPE_SUBSCRIBER_MODEL_REQUEST_CALLBACK conflict in settings.py

Question: i'am trying to use dj-stripe library, but when i try to override DJSTRIPE_SUBSCRIBER_MODEL, the callback gone wrong.
Here is the model:
class GroupCompany(models.Model):
  owner = models.ForeignKey(Usuario, unique=True, on_delete=models.PROTECT )
  def __unicode__(self):
    return '%s' % self.owner.get_full_name()
  @property
  def email(self):
    return self.owner.email

Here the settings.py
DJSTRIPE_SUBSCRIBER_MODEL = 'base.GroupCompany'

def account_request_callback(request):
    """ Gets an organization instance from the id passed through ``request``"""
    return GroupCompany.objects.get(owner=request.user)

DJSTRIPE_SUBSCRIBER_MODEL_REQUEST_CALLBACK = account_request_callback

The problem is i can't import models in settings, because the aplications isn't loaded yet, but in the docs of dj.stripe, they say this is the way to do!!! im going crazy.
Thanks!
Answer: The way to do this is to import GroupCompany inside of the callback, so that it's loaded when the callback is executed, like so:
def account_request_callback(request):
    from ... import GroupCompany
    return GroupCompany.objects.get(owner=request.user)

-Alex


how change the properties of div on hover

Question: https://razorpay.com/?utm_source=google&utm_medium=cpc&utm_campaign=brand&gclid=CjwKCAjwqarbBRBtEiwArlfEIN_Jl5kiLQRB-zp23dItXm7JMpGNXDK5opevk4W-iEgBRhOjsIZKoBoCSokQAvD_BwE
in this website(under section-do more with razorpay) how they are changing the properties of div on hover and displaying picture
can anyone help me understand by showing sample code.
Comment: Please add meaningful code and a problem description here. Don't just link to the site that needs fixing — otherwise, this question will lose any value to future visitors once the problem is solved or if the site you're linking to is inaccessible. Posting a [Minimal, Complete, and Verifiable example (MCVE)](https://stackoverflow.com/help/mcve) that demonstrates your problem would help you get better answers. For more info, see [Something on my web site doesn't work. Can I just paste a link to it?](https://meta.stackexchange.com/questions/125997/) Thanks!
Answer: You can use CSS
Here's an example:
<code>div {
    display: none;
}

span:hover + div {
    display: block;
}
</code>
https://www.w3schools.com/cssref/sel_hover.asp


Simplifying this hypergeometric function with variable b

Question: The student-t CDf has a hypergeometric function as a component
$$_2F_1\left(\frac{1}{2}, \frac{\nu + 1}{2}; \frac{3}{2}; -\frac{x^2}{\nu}\right)$$
where $\nu$ is the distributions degree of freedom.
Abramowitz and Stegun (10th edition, p.556, 15.1.7) have a simplification that is extremely close to this
$$_2F_1\left(\frac{1}{2}, \frac{1}{2}; \frac{3}{2}; -z^2\right) = z^{-1}\ln[z + (1+z^2)^\frac{1}{2}]$$
The only problem is that the second component of $\frac{1}{2}$ in the Abramowitz simplification is constant, whereas we have $\frac{\nu+1}{2}$.
Is there any way to apply the Abramowitz simplification to our student-t CDF component? How can we simplify our student-t CDF component into some closed form?
Answer: There are closed forms for some values of $\nu$. Here is a partial list (some of them are not found)
$$\left(
\begin{array}{cc}
\color{blue} {\nu} &\color{blue} { \, _2F_1\left(\frac{1}{2},\frac{\nu +1}{2};\frac{3}{2};-\frac{x^2}{\nu }\right)}\\
 1 & \frac{\tan ^{-1}(x)}{x} \\
 2 & \frac{1}{\sqrt{\frac{x^2}{2}+1}} \\
 3 & \frac{1}{2} \left(\frac{\sqrt{3} \tan
   ^{-1}\left(\frac{x}{\sqrt{3}}\right)}{x}+\frac{3}{x^2+3}\right) \\
 4 & \frac{4 \left(x^2+6\right)}{3 \left(x^2+4\right)^{3/2}} \\
 6 & \frac{2 x^4+30 x^2+135}{135 \left(\frac{x^2}{6}+1\right)^{5/2}} \\
 8 & \frac{32 \sqrt{2} \left(x^6+28 x^4+280 x^2+1120\right)}{35
   \left(x^2+8\right)^{7/2}} \\
 10 & \frac{16 \sqrt{\frac{2}{5}} \left(8 x^8+360 x^6+6300 x^4+52500
   x^2+196875\right)}{63 \left(x^2+10\right)^{9/2}} \\
 12 & \frac{x^{10}+66 x^8+1782 x^6+24948 x^4+187110 x^2+673596}{673596
   \left(\frac{x^2}{12}+1\right)^{11/2}}
\end{array}
\right)$$
Comment: Thanks for the list! I suppose my issue which I didn't mention in the question is that $\nu$ can be a real number in the range $0<\nu<30$, so this will pose problems when $\nu$ is not an integer.
Comment: @PyRsquared. What do you want me to cry ? (joke). If $\nu$ is not an integer, just go to the definition of the infinite sum.
Comment: yes I suppose I'll have to do that... the thing is that I am writing a function to compute the CDF of the t-distribution. Introducing for loop sums will slow it down! Oh well. Also, can you tell me where you got this list?
Comment: @PyRsquared. I built it for you (using a CAS, for sure). Do you know this thesis ? http://people.maths.ox.ac.uk/porterm/research/pearson_final.pdf
Comment: no I don't know it. But I'll be sure to check it out for sure! Thanks again


Python FTP socket timeout handling

Question: I'm having a problem handling socket timeouts with python35 ftplib. When a socket timeout error occurs, for some reason I am unable to catch the exception and the script raises the error anyway and exits. Here is the relevant code block:
<code>    try:
        ftp = FTP(self.config.base_url, timeout=400)
        ftp.login()
        ftp.cwd(self.config.root_path)
        ftp.retrbinary("RETR {0}".format(os.path.join(self.root_path, file_path)), fp.write, 1024)
        ftp.quit()
    except socket.timeout:
        self.download_file(file_path)
</code>
For some reason this script will still error out with a socket timeout exception, how is that possible? A general catch-all doesn't work either. Here is the stack trace of the error:
<code>File "ftp.py", line 82, in __init__
  self.ftp = FTP(self.config.base_url, timeout=400)
File "/opt/local/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ftplib.py", line 118, in __init__
  self.connect(host)
File "/opt/local/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ftplib.py", line 156, in connect
  self.welcome = self.getresp()
File "/opt/local/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ftplib.py", line 235, in getresp
  resp = self.getmultiline()
File "/opt/local/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ftplib.py", line 221, in getmultiline
  line = self.getline()
File "/opt/local/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ftplib.py", line 203, in getline
  line = self.file.readline(self.maxline + 1)
File "/opt/local/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/socket.py", line 576, in readinto
  return self._sock.recv_into(b)
socket.timeout: timed out
</code>
As you can see, this is the socket.timeout error being thrown, so how is that not caught? I was unable to find any useful info on how to resolve this issue after many hours of internet research, any insight into this issue would be much appreciated.
For reference, here is the relevant code block of socket.py:
<code> def readinto(self, b):
    """Read up to len(b) bytes into the writable buffer *b* and return
    the number of bytes read.  If the socket is non-blocking and no bytes
    are available, None is returned.

    If *b* is non-empty, a 0 return value indicates that the connection
    was shutdown at the other end.
    """
    self._checkClosed()
    self._checkReadable()
    if self._timeout_occurred:
        raise OSError("cannot read from timed out object")
    while True:
        try:
            return self._sock.recv_into(b)
        except timeout:
            self._timeout_occurred = True
            raise
        except error as e:
            if e.args[0] in _blocking_errnos:
                return None
            raise
</code>
UPDATE:
It seems the issue is that ftplib behaves unexpectedly if the timeout passed to the FTP constructor is greater than the default for a socket timeout. At the time of this edit there is an open python issue to address this behavior: http://bugs.python.org/issue30956
Answer: try to add

ftp.set_pasv(False)

disabling the passive mode it should work

Python FTP socket timeout handling


Why would taxonomy_term_save be slow when called from hook_install_tasks?

Question: As part of making a site more easily deployable from scratch, I have generated two PHP scripts to pre-populate taxonomy vocabularies with a list of terms.  The scripts are straightforward, creating stdClass objects with the appropriate fields and callingtaxonomy_term_save on each one.  Example:
$term = (object) array (
  'name' => 'Art & Architecture',
  'description' => '',
  'format' => 'plain_text',
  'weight' => '0',
  'vocabulary_machine_name' => 'categories',
  'field_cc_numeric_code' =>
  array (
    'und' =>
    array (
      0 =>
      array (
        'value' => '102',
      ),
    ),
  ),
);
$term->vid = $vocabulary->vid;
taxonomy_term_save($term);

The variable $vocabulary already contains the appropriate taxonomy vocabulary structure at the time this is called.  One vocabulary has about 150 terms to create, the other about 2,000.
On a fresh installation of the site made using drush site-install, these scripts run almost instantly when called via drush php-script.  However, if they are incorporated into the installation profile and called by a task in the implementation of hook_install_tasks, they are much slower.  In the latter case, saving each term takes about a second, which is unacceptably slow.
There is discussion of a similar issue at https://www.drupal.org/node/1887924, but no solution offered either there or in the linked bug report.
Why would taxonomy_term_save be so much slower when performed from an installation task?  Is there anything that can be done about it?
Comment: Profiling using XDebug suggests that the problem is a bad interaction with the `pathauto` module.  The bulk of execution time is spent in `pathauto_taxonomy_term_insert`, and omitting Pathauto from the enabled modules in the installation profile returns things to normal speed.  It is still unclear to me why this would be slow in an install hook but not otherwise.  If I can come up with a clean solution I will post it as an answer.
Answer: In this case, the problem resulted from having the Pathauto module enabled during installation.  When a new taxonomy term is saved, Drupal calls pathauto_taxonomy_term_insert(), which calls pathauto_taxonomy_term_update_alias(), which in turn calls pathauto_create_alias().  This last function calls an internal function, _pathauto_path_is_callback(), to determine whether an alias can be created for a given path, and this in turn calls the core function menu_get_item(), which contains the following lines:
if (variable_get('menu_rebuild_needed', FALSE) || !variable_get('menu_masks', array())) {
  menu_rebuild();
}

menu_rebuild contains the following lines:
if (defined('MAINTENANCE_MODE')) {
  variable_set('menu_rebuild_needed', TRUE);
}
else {
  variable_del('menu_rebuild_needed');
}

The cumulative effect seems to be that the menu_rebuild_needed variable is continually reset to TRUE, meaning that a complete menu rebuild is triggered each time a new taxonomy term is saved, slowing things down immensely (from ~100 terms saved per second to ~1 per second).
This seems like a bug, though it's not clear which component, if any, is at fault.  For now, I am working around the problem by disabling pathauto, creating the terms, and then re-enabling pathauto:
module_disable(array('pathauto'));
…
module_enable(array('pathauto'));

Comment: Possibly useful note: I used the [XDebug Profiler](http://www.xdebug.org/docs/profiler) and [qcachegrind](http://kcachegrind.sourceforge.net/html/Home.html), installed through MacPorts, to debug this.


ASP.net MVC3 View inheritance

Question: I've got a list of for example Vehicle's that I want to render in a single page, but have different view characteristics for each vehicle type.
Vehicle
 - VehicleId
 - VehicleTypeId (Car/Boat/Truck/etc...)
 - Description
 - ...
I'd like to on my main AllVehiclesPage
@foreach(var vehicle in Model) //where Model is a List<Vehicle> from AllVehicles
{
    //Render proper View
    //CarView(vehicle)
    //BoatView(vehicle)
    //TruckView(vehicle)
}

In each view it will render differently depending on the vehicle, IE Wheel rim size applies to cars/trucks not to boats etc...
I've read a number of the other questions on Stackoverflow about view inheritance, but they don't seem to apply.
Is this best to do with partial Views? Should I create Usercontrols?
Answer: Use display templates. Replace your entire foreach loop with the following line of code:
@model IEnumerable<Vehicle>
...
@Html.DisplayForModel()

And now comes the interesting part. You define display templates for each type that you want to handle:
~/Views/Shared/DisplayTemplates/Car.cshtml
~/Views/Shared/DisplayTemplates/Boat.cshtml
~/Views/Shared/DisplayTemplates/Truck.cshtml

Each template will be strongly typed to the corresponding concrete type. So here's what will happen on the Html.DisplayForModel() line:

ASP.NET MVC sees that the model is an IEnumerable<Vehicle>
ASP.NET MVC starts enumerating over this collection
For each element of the collection ASP.NET MVC looks at its concrete runtime type.
ASP.NET MVC looks for a corresponding display template for this type defined in the ~/Views/Shared/DisplayTemplates folder and automatically renders it by passing this template the current element as model.

You will notice something interesting in this pattern: I use the word ASP.NET MVC very much instead of the word the .NET developer. That's nifty because all that the developer has to do is follow the standard conventions and then ASP.NET MVC will do the job for him so that this developer doesn't need to write loops, doesn't need to write if conditions and doesn't need to reinvent wheels.
Comment: @DarinDimitrov This would only work if OP was using inheritance between his abstract Vehicle object and his Car/Boat/Truck implementations though wouldn't it ? It seems to me that OP actually has a List but wants to select which template to use based on it's VehicleTypeId property, and not by the Type of object.
Comment: I'm still learning MVC, would this link be a good plact to learn display templates? http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-1-introduction.html
Comment: That is absolutely magnificent place to learn. Brad Wilson is one of the greatest.

ASP.net MVC3 View inheritance


Help with Elementary Vector subspace proof

Question: I am having trouble getting started with a proof of the following statement (I translated it from German, so bear with me):
"$V$ is a vector space and $U$ and $W$ are vector subspaces of $V$. Prove that the following two are equivalent:
a) $U \cap W = \{0\} $
b) Every $v \in U+W$ (with $U+W$ denoting the direct sum) can only be represented in one unique way as $v=u+w$ with $u \in U$ and $w \in W$."
I know that to prove equivalence (i.e. $a \Leftarrow\Rightarrow$ b), I have to show that $a \Rightarrow b$ and $b \Rightarrow a$ but I am having trouble getting anywhere. I attempted to assume $a$ is true and $b$ is false and prove by contradiction, but I couldn't get anywhere. Could you give me one or two hints so I can solve this on my own? Thank you! :)
Comment: Think about the basis for $V$ and $W$ and what it means to be a direct sum in terms of bases.
Answer: Hints:
$$\begin{align*}(1)&\;\;U\cap W=\{0\} : \text{if}\;\;u+w=u'+w'\;,\;\;u,u'\in U\,,\,w,w'\in W\;,\;\\
\text{then}& u-u'=w'-w\in U\cap W\;\ldots\\
(2)&\;\text{ Assume unique representation. If}\;\;x\in U\cap W\;,\;\text {then}\;\;x=x+0=0+x\in U+W\ldots \end{align*}$$
Comment: Very helpful, thank you very much.
Answer: Hint:
Assume $$v=u_1+w_1=u_2+w_2$$ with $u_i\in U$ and $w_i\in W$. Then
$$0=v-v=(u_1-u_2)+(w_1-w_2)$$
Now the first summand is in $U$ the second summand lies in $W$. Can you show that if the $u_i$ and $w_i$ are distinct that the intersection $U\cap W$ can't be trivial?
For the other direction: Assume
$$v=u+w$$
and $x\in U\cap W$. Now consider
$$v=(u+x)+(w-x)$$
Comment: Thank you! :) This helped a lot.


record of email notifications sent out (webform / postfix)

Question: I have a webform with example.com/node/123/webform/emails set to send email notification from email@example.com to several email addresses when a submission is received.
Is there a way to see a record of email notifications sent out ie with date and time etc to verify that the notifications have in fact been sent?
Thanks...
Answer: Webform doesn't provide default functionality for it.
you can use either of these modules to log outgoing mail:

Mail Log
Email Log
Comment: @ Pravin thanks  for your reply - I don't like www.drupal.org/project/emaillog because it is only rc-1 and 37 sites using it. I tried https://drupal.org/project/maillog - it works fine for some emails sent out eg new comment but so far does not seem to work for webform new submission (ie no log).
Answer: My favorite and so far most reliable, if not most convenient, way to achieve that is out of Drupal, actually. If you set it up inside Drupal, and you hit some errors, you never are 100% certain if mail wasn't sent, or just wasn't logged. Or, if logging happens first, you can never know for sure if mail was sent, or was only supposed to be.
The way I prefer to do it is to use external SMTP server for outgoing mail. That way I can be sure all mail I have logged actually was sent from Drupal, and chance I logged all mail are bigger, too. After all, SMTP servers have decades of evolution more than Drupal, or even PHP. Added bonuses include:

Less CPU and memory use on webserver, because it does not need code for mail log, and this code would be loaded on each uncached request.
Ability to deliver mail even if recipient's server is temporarily down.

Example
If you have business Gmail, you can use SMTP Authentication Support module to make your site send via Gmail, and you will see mail sent from site in your Sent Mail, just like this:

No special configuration was needed to get this working. You can use full power of Google if you do so: filters, labels, whatever you wish.
If you will use company mail server, just make sure your sysadmin will configure it in similar manner.
Comment: @ Molot thanks I am interested in this - does that mean using https://www.drupal.org/project/smtp and something like mandrill.com ? I am googling but please let me know any helpful links re setup etc
Comment: @Juc1 see my updated answer
Comment: @ Molot wow that is cool - I will try with gmail where I am using business Gmail and also I am looking into https://www.drupal.org/project/mandrill
Comment: @Juc1 glad to help. Happy coincidence you are actually using Gmail, too :D I never used mandrill, but I've heard it is good, but only worth the money if your traffic is significant enough to justify prices.
Comment: @ Molot I have setup Mandrill - I think you get the first 12,000 emails per month for free - if anyone is interested there are some nice set up instructions here http://redcrackle.com/blog/send-drupals-transactional-emails-using-mandrill


Multiple regression p-value differs in summary and in pf() output used for extraction, in R

Question: When fitting multiple variables to one outcome via the lm() function in R, summary(lm) gives me the p-values for individual regressors but not for the full model in an easily extractable (as in, just accessing fields) kind of way.
According to this question, it is possible to extract the p-value via summary(lm)$fstatistic by using the command:
pf(x$fstatistic[1],x$fstatistic[2],x$fstatistic[3],lower.tail=FALSE)

However, while in the example linked this provides the same p-value as is printed, I get a different one:
> summary(model)
# ...
Residual standard error: 1.533 on 371 degrees of freedom
  (555 observations deleted due to missingness)
Multiple R-squared:  0.3364,    Adjusted R-squared:  0.2864
F-statistic: 6.718 on 28 and 371 DF,  p-value: < 2.2e-16

and:
f = summary(model)$fstatistic
> pf(f[1],f[2],f[3],lower.tail=F)
       value
5.948007e-20

What are possible reasons for these values to be different, and which one is the "right" one for the significance of the whole model?
Comment: First you say `R` does not give the p value for the full model from `summary(lm)` then you show an example where it does. Perhaps the issue is only *extracting* the p value.  Also, as @Roland implied, comparing p values with 16 or 20 initial 0's is fraught; but it is hard to conceive of a case where it matters whether the p value is one in a quadrillion or one in 10 quintillion (using American definitions of those terms).
Comment: I don't understand your problem: `5.948007e-20 < 2.2e-16`. `summary.lm` limits the precision of the printed p-value (which is appropriate).
Comment: Precision limiting for printing is fine, but even in that case `< 6e-20` would make more sense than `< 2.2e-16`. There is no reason to say "smaller than an arbitrary value", even if it is true. And yes, I meant extracting as you pointed out.
Answer: The p-value calculated by print.summary.lm (use getAnywhere(print.summary.lm) to study the code)  is rounded for floating point precision using format.pval.
2.2e-16 is the value of .Machine$double.eps, which is

the smallest positive floating-point number x such that 1 + x != 1

So, the rounding is not arbitrary, but for numerical reasons.


Criar Nova Coluna em DataFrame com base em coluna com função def_Pandas

Question: Gostaria de adicionar em um DataFrame os resultados que obtive depois de aplicar a seguinte função em duas colunas desse DataFrame:

Colunas do DataFrame: "DATA", "VEÍCULO" e "Análise qualitativa das matérias"

Desejo saber a quantidade de Análise qualitativa NEGATIVA, Análise POSITIVA e NEUTRA por VEÍCULO

Colunas e Dados do Dataframe:

<code>#Colunas e Dados do DataFrame:

DATA                               VEÍCULOS Análise qualitativa das matérias
0     01/01/2023                 RD NEWS - CUIABÁ - MT                          POSITIVA
1     01/01/2023                 RD NEWS - CUIABÁ - MT                            NEUTRA
2     01/01/2023     ESPORTES E NOTÍCIAS - CUIABÁ - MT                          POSITIVA
3     01/01/2023                 RD NEWS - CUIABÁ - MT                          POSITIVA
4     01/01/2023                BLOG DO PEDRO LUIS [MT]                         POSITIVA
...          ...                                    ...                              ...
1639  31/01/2023       TBO/TV BRASIL OESTE - CUIABÁ MT                            NEUTRA
1640  31/01/2023  BARRA EM FOCO - BARRA DO BUGRES - MT                            NEUTRA
1641  31/01/2023             DIÁRIO DIGITAL MT - CUIABÁ                           NEUTRA
1642  31/01/2023                     A FOLHA NEWS - MT                            NEUTRA
1643  31/01/2023                  J1 AGORA - MT ONLINE                            NEUTRA
</code>

Eu quis agrupar a quantidade de dados da coluna 'VEÍCULOS' que na coluna 'Análise qualitativa de matérias' estavam como 'NEGATIVAS'. Mas,depois, precisava contá-las e atribuir o número de vezes em que cada VEÍCULO apareceu como NEGATIVO.Então, usei o bloco de função abaixo:

<code>#Entrada:
def counter_(g, threshold=['NEGATIVA']):
    num= len(g[g == 'NEGATIVA'])
    return num
secom_df = (secom_df.groupby('VEÍCULOS')['Análise qualitativa das matérias'].apply(counter_))

#Saída:
    VEÍCULOS
360 FATOS - CUIABÁ - MT                                       2
360 NEWS - CUIABÁ - MT                                        0
A BRONCA POPULAR [MT]                                         2
A FOLHA DO MÉDIO NORTE ONLINE - BARRA DO BUGRES - MT [MT]     0
A FOLHA MT - CUIABÁ MT                                        2
                                                             ..
ZAKI NEWS - CÁCERES - MT                                      0
ÁGUA BOA NEWS - MT                                            0
ÂNCORA NOTÍCIAS - MT                                          0
ÚLTIMA HORA MT - CUIABÁ - MT                                  9
ÚNICA NEWS - MT                                              89
</code>

Por exemplo, após aplicar a função def acima, o VEÍCULO "ÚNICA NEWS-MT" teve 89 aparições como'NEGATIVAS'

DESEJO adicionar essa coluna com função 'def', como uma NOVA COLUNA no DataFrame "secom_df" já existente. Já tentei transformar esse bloco 'def' em uma Nova Coluna denominada 'secom_df['ANÁLISE NEGATIVA']' a partir da atribuição dos resultados desse bloco a uma variável 'secom_df_jan', mas a Saída vem com valores 'NaN', como fazer?

<code>#Entrada:
secom_df_jan = (secom_df.groupby('VEÍCULOS')['Análise qualitativa das matérias'].apply(counter_))
</code>
secom_df['ANÁLISE NEGATIVA'] = secom_df_jan
<code>#Saída
    DATA                            VEÍCULOS Análise qualitativa das matérias  ANÁLISE NEGATIVA
0      01/01/2023              RD NEWS - CUIABÁ - MT                          POSITIVA               NaN
1      01/01/2023              RD NEWS - CUIABÁ - MT                            NEUTRA               NaN
2      01/01/2023  ESPORTES E NOTÍCIAS - CUIABÁ - MT                          POSITIVA               NaN
3      01/01/2023              RD NEWS - CUIABÁ - MT                          POSITIVA               NaN
4      01/01/2023             BLOG DO PEDRO LUIS [MT]                         POSITIVA               NaN
...           ...                                 ...                              ...               ...
42992  31/12/2023             FOLHAMAX - CUIABÁ - MT                          POSITIVA               NaN
42993  31/12/2023             LEIAGORA - CUIABÁ - MT                            NEUTRA               NaN
42994  31/12/2023          O DOCUMENTO - CUIABÁ - MT                          POSITIVA               NaN
42995  31/12/2023             FOLHAMAX - CUIABÁ - MT                            NEUTRA               NaN
42996  31/12/2023               RDM ON-LINE - MT [MT]                           NEUTRA               NaN
</code>
(Estou usando Windows 10, Visual StudioCode, Python 3.11.8 e Pandas)

Se não fui clara, favor me informar, pois o Fórum ainda não me permite anexar a imagem.
Answer: O problema é aqui
<code>    secom_df['ANÁLISE NEGATIVA'] = secom_df_jan
</code>
Você está apenas inserindo a coluna, mas sem associar os valores de cada elemento da série secom_df_jan aos veículos do df secom_df. Como não há valores associados, ele imprimirá NaN, que é como o pandas representa valores numéricos ausentes
Use um map para preencher cada linha de ANÁLISE NEGATIVA com os valores da série secom_df_jan para cada veículo:
<code>    secom_df['ANÁLISE NEGATIVA'] = secom_df['VEÍCULOS'].map(secom_df_jan)
</code>
Teste baseado no df que forneceu (substitui algumas análises por Negativa para conter todos os valores possíveis na entrada)
<code>import pandas as pd

data = {
    'DATA': ['01/01/2023', '01/01/2023', '01/01/2023', '01/01/2023', '01/01/2023',
             '31/01/2023', '31/01/2023', '31/01/2023', '31/01/2023', '31/01/2023'],
    'VEÍCULOS': ['RD NEWS - CUIABÁ - MT', 'RD NEWS - CUIABÁ - MT', 'ESPORTES E NOTÍCIAS - CUIABÁ - MT',
                 'RD NEWS - CUIABÁ - MT', 'BLOG DO PEDRO LUIS [MT]', 'TBO/TV BRASIL OESTE - CUIABÁ MT',
                 'BARRA EM FOCO - BARRA DO BUGRES - MT', 'DIÁRIO DIGITAL MT - CUIABÁ',
                 'A FOLHA NEWS - MT', 'J1 AGORA - MT ONLINE'],
    'Análise qualitativa das matérias': ['POSITIVA', 'NEUTRA', 'POSITIVA', 'NEGATIVA', 'POSITIVA',
                                          'NEUTRA', 'NEUTRA', 'NEGATIVA', 'NEUTRA', 'NEUTRA']
}

def counter_(g, threshold=['NEGATIVA']):
    num = len(g[g.isin(threshold)])
    return num

secom_df = pd.DataFrame(data)
secom_df_jan = secom_df.groupby('VEÍCULOS')['Análise qualitativa das matérias'].apply(counter_)
secom_df['ANÁLISE NEGATIVA'] = secom_df['VEÍCULOS'].map(secom_df_jan)
print(secom_df)

</code>
<code>#Output:
         DATA                              VEÍCULOS Análise qualitativa das matérias  ANÁLISE NEGATIVA
0  01/01/2023                 RD NEWS - CUIABÁ - MT                         POSITIVA                 1
1  01/01/2023                 RD NEWS - CUIABÁ - MT                           NEUTRA                 1
2  01/01/2023     ESPORTES E NOTÍCIAS - CUIABÁ - MT                         POSITIVA                 0
3  01/01/2023                 RD NEWS - CUIABÁ - MT                         NEGATIVA                 1
4  01/01/2023               BLOG DO PEDRO LUIS [MT]                         POSITIVA                 0
5  31/01/2023       TBO/TV BRASIL OESTE - CUIABÁ MT                           NEUTRA                 0
6  31/01/2023  BARRA EM FOCO - BARRA DO BUGRES - MT                           NEUTRA                 0
7  31/01/2023            DIÁRIO DIGITAL MT - CUIABÁ                         NEGATIVA                 1
8  31/01/2023                     A FOLHA NEWS - MT                           NEUTRA                 0
9  31/01/2023                  J1 AGORA - MT ONLINE                           NEUTRA                 0
</code>
Veja mais sobre o uso de map aqui:
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.map.html
Aqui a documentação sobre dados ausentes (e são vários, o "N" depois de Na representa o tipo de dados que ele esperava, neste caso numérico ):
https://pandas.pydata.org/pandas-docs/stable/user_guide/missing_data.html#working-with-missing-data
Outra alternativa é você usa métodos de junção e mesclagem de dfs e séries do pandas:
https://pandas.pydata.org/docs/user_guide/merging.html
Eles podem lidar com isso, mas retornam um novo df e , pelo que solicitou, você deseja adicionar a coluna ao existente, o mantendo.
Comment: Olá Luigi, obrigada por responder...vou tentar essa função "map". Ressalto desde já que eu queria um Resultado diferente, eu queria era que cada "VEÍCULO" saísse  única vez e com a quantidade de vezes que eles tiveram as avaliações NEGATIVAS, não queria que os "VEÍCULOS"  se repetissem. Será que é possível fazer isso e ainda associar os valores da forma como mencionei, isto é, associar com as demais colunas de"Análise qualitativa das matérias" e a nova coluna "ANÁLISE NEGATIVA"? Acredito que se for acrescentar esse associação com a Coluna "Datas" não daria, certo?
Comment: O que dá pra fazer é criar um df de dados para cada veículo à secom_df_jan

`
def get_data(g, df):
    return df.loc[df['VEÍCULOS'] == g].reset_index(drop=True).drop(columns=['VEÍCULOS'])

secom_df = pd.DataFrame(data)
secom_df_jan = secom_df.groupby('VEÍCULOS')['Análise qualitativa das matérias'].apply(counter_).reset_index(name='ANÁLISE NEGATIVA')
secom_df_jan['Análise qualitativa das matérias'] = secom_df_jan.apply(lambda row: get_data(row['VEÍCULOS'], secom_df ), axis=1)

`
secom_df_jan terá linhas únicas de cada veículo, com os dados dele em Análise qualitativa das matérias


HTML5 AUDIO Tag Support for Icecast?

Question: Is it possible to play an Icecast stream using HTML5's AUDIO tag? The syntax I'm using seems happy enough with ShoutCast but not Icecast which I'm confused by. Also if I browse to a certain URL of an Icecast stream a browser window automatically displays the player (see last example).
Working ShoutCast example.
<audio src="http://18.104.22.168:8000/;listen.pls?sid=1" autoplay="true" muted="false" controls="true" volume="1.0"></audio>

Non working Icecast examples.
<audio src="http://220.127.116.11:8016/;stream" autoplay="false" muted="false" controls="true" volume="1.0"></audio>

<audio src="http://18.104.22.168:8016/stream" autoplay="false" muted="false" controls="true" volume="1.0"></audio>

<audio src="http://220.127.116.11:8016" autoplay="false" muted="false" controls="true" volume="1.0"></audio>

Icecast stream URL which opens the player automatically in a browser.
http://18.104.22.168:8016/stream

Comment: This `` seems to be working [JSFiddle](https://jsfiddle.net/9wmvmvx8/1/).
Comment: I'm not sure what happened here because I was sure I tried that syntax and it didn't work but I've just tested it now and clearly it does. Thank you!
Answer:
Is it possible to play an Icecast stream using HTML5's AUDIO tag?

Yes, absolutely.
The only requirement is that the browser supports the codec that you're streaming in.

The syntax I'm using seems happy enough with ShoutCast but not Icecast which I'm confused by.

All these stream URLs with semicolons ; are for SHOUTcast only.  SHOUTcast servers run their admin interface on the same URL as streams.  They do user agent sniffing to determine whether the client is a web browser or an audio player.  When web pages started playing audio many years ago, they needed a way to work around this problem so that browsers could get the audio stream.  A stream URL with a semicolon in it forces SHOUTcast to ignore the browser's user agent and replace it with "MPEG OVERRIDE", which causes the rest of the server to return the stream.
Only ; is needed.  The whole ;stream thing is just unnecessary stuff that was copied and pasted.
You can read more here:  https://stackoverflow.com/a/38217135/362536
As for Icecast streams, all you need is this:
<audio src="http://126.96.36.199:8016/stream" />

(Unless of course you support multiple codecs, in which case you would use multiple sources.)
Comment: Make sure you use `src="http://188.8.131.52:8016/stream"` (Brad made a mistake it seems and my edit isn't visible, yet).
Comment: Thanks @TBR!  The edit still wasn't showing up so I just made the correction.
Comment: I tried this previously and it doesn't seem to work.

HTML5 AUDIO Tag Support for Icecast?


Express baseUrl param not available

Question: Let's say I have the following routes:
// routes.js
import PhotoRoutes from './photoRoutes';

const UserBaseRoute = Router();
UserBaseRoute.use('/api/:userId', PhotoRoutes);

// photoRoutes.js
const PhotoRoute = Router();
PhotoRoute.get('/', (req, res) => {
    console.log(req.params);
    res.end();
});

export default PhotoRoute;

When I hit /api/123/ I expect to use {"userId: 123}' But I don't. Why is the :userId defined in the baseRoute not passed up?
Answer: This is a issue related to nested router.
You need to set the mergeParams of child router as true to access params from parent router.
So try following code:
const PhotoRoute = Router({mergeParams: true});

BTW, this option came with Express version 4.5. For more details, refer to the API document

Express baseUrl param not available


ubuntu forward port to another machine

Question: I'm migrating servers, and I'd like to forward port 80 on my existing machine to port 80 on the new machine while DNS switches over.
I'm running Ubuntu 10.04 server and trying to follow the guide at http://www.simplehelp.net/2009/04/15/how-to-redirect-traffic-to-another-machine-in-linux/
I've run
# echo 1 >/proc/sys/net/ipv4/ip_forward

But when I run the next command I get an error:
#iptables -t nat -D PREROUTING -p tcp --dport 80 -j DNAT --to-destination 188.8.131.52
iptables: No chain/target/match by that name.

It seems I don't have the nat table there. Here's the output of iptables -L:
iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

There's no nat table.
What do I need to do to forward it to the other machine?
Note: I know about rinetd, and I can even have the webserver proxy requests to the new server. I'm trying to do this so that the logs will still make sense (rather than having a ton of logs that say the source IP was the old server)
Edit: Thanks to Eduardo, the problem was that the tutorial mistakenly says "-D PREROUTING" which is the command to delete the rule, it should read "-A PREROUTING".
However it still doesn't work. Here's what I'm doing:
machine-1: 192.168.56.150
machine-2: 192.168.56.151
I want to redirect machine-1 to machine-2.
On machine-1 I've run:
echo 1 > /proc/sys/net/ipv4/ip_forward
iptables -t nat -A PREROUTING -p tcp --dport 80 -j DNAT --to-destination 192.168.56.151

On machine-2 I've run:
echo 1 > /proc/sys/net/ipv4/ip_forward #not sure if this is necessary, it didn't work at first so I ran this here too
iptables -t nat -A POSTROUTING -p tcp -d 192.168.56.151 --dport 80 -j MASQUERADE

On my workstation, I try to wget http://192.168.56.150 expecting it to give the response from machine-2 (and that machine-2 will have my workstation's IP in its logs) - however I just get connection timed out. I've checked machine-2 and it responds correctly.
Answer: Try replacing -D PREROUTING with -A PREROUTING. You're trying to delete a rule that doesn't exist. The tutorial has this same error repeated several times, I see - just use -A everywhere.
Also, you can use iptables -nvL -t nat to see the NAT tables.
Comment: Thanks, I can add the rules now. Unfortunately it still doesn't work. Details in an edit to the question.
Comment: @John, you should run the second rule (the MASQUERADE one) in the same machine that's doing the redirect. No rules are necessary in the destination one.
Comment: Thanks, that works. The logs show the request in server-2 as coming from server-1, I was hoping they would show it as coming from the client. Is that possible to do?
Comment: Only if server-1 is the default route for server-2 - which I guess it isn't, or this setup would have worked without the MASQUERADE rule. Consider the alternative: installing a reverse proxy (apache, lighttpd, nginx will all do) on server-1. That way you can pass the requests to server-2 AND keep the original source information. Search "reverse proxy" +  and you'll get lots of information on how to do this.
Answer: Both of the iptables rules need to run on the old machine-1. No special rules should be required on the new machine-2.
To troubleshoot, look at the counters in the iptables -t nat -L -n -v output and use tcpdump as well to verify that the addresses are being translated correctly.
Using MASQUERADE can cause unexpected issues. It's not supposed to, but by experience I've found that using SNAT is much more reliable.
I would normally implement this using a little bash script like this:
#!/bin/bash

OLDIP=192.168.5.5
NEWIP=192.168.56.151
PORT=80

echo 1 > /proc/sys/net/ipv4/ip_forward

# flush old nat rules
iptables -F -t nat

# destination is redirected to new server
iptables -t nat -A PREROUTING -p tcp --dport 80 -d $OLDIP -j DNAT --to $NEWIP

# source on the redirected packets should be us (the old server), and not original client
iptables -t nat -A POSTROUTING -p tcp --sport 80 -d $NEWIP -j SNAT --to $OLDIP

These rules could be a bit greedy though; it would be better to specify the interfaces using -i and -o if possible.

ubuntu forward port to another machine


Determine if high dimensional data is multimodal

Question: I have p-dimensional data and I need to determine if that data has significant modes or if it's clustered in any way. Here p=50, (dense embedding), we have n samples and p <<< n.
What are some ways to do that? I can think of creating sample covarince matrix of 50*50. Not sure how to analyze that full matrix (eigenvalues, etc) for conclusions.
I can also try to do kmeans and see if it converges or do GMM but I needs to try on many number of clusters. The data could have many clusters in theory, possibly residing on lower dim manifolds.
Any thoughts?
Thanks.
Answer: Multimodal is with regard to models, not data. If I understand correctly, you are trying to find the optimal number of clusters given a specific model structure. Typically in this set up selecting "number of clusters" is part of a standard model selection process.
Take GMM for example,

If you use Bayesian GMM, you can try a set of possible "number of clusters", and select the one that minimize BIC on your complete data set;
If you use GMM (without Bayesian), you need to split the data set into training and validation, train each variation on the training set and select the one that maximize the likelihood on validation set.


openssh, permitting some users to use sftp with passwords and limited privileges

Question: I have a linux host with openssh that permits users to login with public key.
AuthenticationMethods publickey

But now I have some users who will need to access the host as a file drop using sftp.  In addition, these users will user passwords rather than key pairs.
I make all of these users belong to the group sftp_users.
firstname.lastname@example.com:~$ id
uid=1005(an_sftp_user) gid=1007(an_sftp_user) groups=1007(an_sftp_user),1006(sftp_users)
firstname.lastname@example.com:~$ groups
an_sftp_user sftp_users
email@example.com:~$

Now I create the file /etc/ssh/sshd_config.d/sftp_users.conf owned by root, 0644:
Match Group sftp_users
  X11Forwarding no
  AllowTcpForwarding no
  AuthorizedKeysCommand /bin/true
  AuthenticationMethods keyboard-interactive
  PasswordAuthentication yes
  ChrootDirectory /sftp-incoming

What I want this to do is to permit users in the group sftp_users to be able to connect with password and access /sftp-incoming.
What actually happens is that I see a message server side in auth.log that says merely that the connection was closed and, client side, I see (using sftp -v) that it tries the certificates it finds in $HOME/.ssh (I've disabled my ssh-agent for these tests) but never tries password login.
Indeed, one line is this:
debug1: Authentications that can continue: publickey

So somehow my Match is not being satisfied or not being seen.  But I'm unclear why.
Any suggestions where I've gone wrong?
Update
The solution from @Gogowitsch largely answers this, especially the note that sftp-internal is, well, internal to openssh and so doesn't need a binary to be available in my chroot jail.  Also important was to discover that chroot requires that the chain of directories be 0755 root all the way down, so I had to sort some permissions.
His suggestion to put the config all in the one sshd_config file was also helpful.  Indeed, once it was working, moving that block back to a config file and using Include to include it fails without error.  The block simply isn't used.  I'm using 8.2:
OpenSSH_8.2p1 Ubuntu-4ubuntu0.1, OpenSSL 1.1.1f  31 Mar 2020

which claims to support Include (present since 7.3p1 and apparently committed on 1 Feb 2020 (prior to 31 Mar 2020).
Comment: Idea: You could use a second SSH daemon running on the same host, but with a different port. One allows password-based login, the other doesn't. Then tell each user which port they should used based on their preferred authentication method.
Answer: I see these immediate issues:

The order of directives. Try putting the Match Group sftp_users at the very end of the file /etc/ssh/sshd_server instead of a file in the sshd_server.d. This is because the last AuthenticationMethods seems to win.
The AuthenticationMethods should contain password. This is apparently what allows the password login.
When using the ChrootDirectory directive, you also have to use the following line within your Match Group sftp_users block:
ForceCommand internal-sftp

This is because the /sftp-incoming becomes the actual root of the file system to all commands. By default, the SSH server attempts to run a binary such as /usr/lib/openssh/sftp-server. From the perspective of the chroot'ed filesystem, there probably isn't any such file.

Potentially, you'll also have to run the following command to make sure that the /sftp-incoming directory cannot be accessed by 'other' (the last digit in the octal 0750):
chmod 0750 /sftp-incoming

As an experimental setup, I used the following Dockerfile:
FROM ubuntu

RUN apt-get update && \
    apt-get install -yq openssh-sftp-server openssh-server

# Create two users, first has no password, second has the password "1".
# This will also create the home directory for the sftp user.
RUN echo | adduser only-passwordless-user && \
    echo | adduser only-with-password-user --home /sftp-incoming/only-with-password-user && \
    echo only-with-password-user:1 | chpasswd && \
    addgroup sftp_users && \
    adduser only-with-password-user sftp_users

# These are needed so that sshd is happy. Otherwise,
# it likes to say "bad ownership or modes for chroot directory"
RUN mkdir -p -m0755 /var/run/sshd && \
    chown root:root /sftp-incoming && \
    chmod 0750 /sftp-incoming

RUN echo AuthenticationMethods publickey >> /etc/ssh/sshd_config && \
    printf "Match Group sftp_users                                \n\
            ForceCommand internal-sftp                            \n\
            X11Forwarding no                                      \n\
            AllowTcpForwarding no                                 \n\
            AuthorizedKeysCommand /bin/true                       \n\
            AuthenticationMethods keyboard-interactive password   \n\
            PasswordAuthentication yes                            \n\
            ChrootDirectory /sftp-incoming                        \n\
           " >> /etc/ssh/sshd_config  # cannot be ".d/sftp_users.conf"

# Start a single-connection debug server.
# Remove the -d parameter to make it long-lived but quiet.
ENTRYPOINT /usr/sbin/sshd -d

You can start a sshd running on port 2200 using this command:
docker build . -t ssh-test && docker run -it --name ssh-test -p2200:22 --rm ssh-test bash

To connect to it using sftp, run this:
sshpass -p1 sftp -P 2200 email@example.com

Comment: Thanks, that largely got me out of this.  The odd thing is that putting the (revised) block in `sshd_config` works, but using `Include` does not.


C++ - What does the 'dot' operator means when used in std::cin.getline()?

Question: I'm used to program in Python, and since in Python, all are objects, it is totally acceptable when at the end of a variable, a . operator is used to access the method of a class. But in C++, let say for something like std::cin.getline(), is this some kind of accessing the member function of cin?
Is cin some kind of a class or a struct?
Comment: Did you try reading some documentation of `std::cin` to find out what it is?
Comment: I am also still kind of confuse with all of the syntax of C++ and how it actually works, so, I just think that by asking here, it would be better and more time saving.
Answer: Once you type:
#include <iostream>

the corresponding headerfile is inserted there. One line of this file reads
extern istream cin;

So as you see you have an object of type istream accessable from anywhere in the file with the include statement.
So your guess that cin is an instance of a class was right and the dot operator calls the getline method of that object/class.
Source: http://www.cplusplus.com/reference/iostream/cin/
Answer: cin is indeed an instance of the class std::istream.
Answer: std

Is the namespace
cin

Is an object from the istream class
getline

Is a method from the cin class.
Comment: `cin` is not a class, it's a (global) variable. It is an instance of a class, though.
Comment: Oops, my bad. Thanks


Certificate error when using IP address after upgrade from WS 2003 to 2008

Question: When I access my site using the IP address (the domain name still works fine) I get a certificate error.  This is after upgrading from Windows Server 2003 to 2008.
Answer: The certificates are associated to a specific hostname. So if you try and access your site with just it's IP address the certificate won't match.
You can use a service such as SSL Shopper's SSL Checker to see what hostname is associated with a given certificate.
example


Error while installing Python TA-lib package on Linux system with no sudo privileges

Question: I'm having trouble installing the python talib package on a linux system (Linux 2.6.32-431.17.1.el6.x86_64). See https://github.com/mrjbq7/ta-lib
.
What I did so far:

brew install ta-lib (Dependency)

This worked fine. If I rerun this command I see Warning: ta-lib-0.4.0 already installed

pip install ta-lib

when running this, I get the following error: error: command /home/username/.linuxbrew/bin/gcc' failed with exit status 1

I don't have sudo privileges on this machine, so I suspect this might be a problem. I also tried
pip install --user ta-lib

and
wget https://github.com/mrjbq7/ta-lib/archive/master.zip && unzip master.zip && cd ta-lib-master && python setup.py install.

Same error as above.
Any ideas as to what I'm doing wrong?
Answer: I also get stuck at this problem. Then I found two ways to solve this. This problem is because ta-lib installation only check several dirs, which not include linuxbrew path. You have two ways to solve this problem.

Follow the instructions on https://github.com/mrjbq7/ta-lib, download "ta-lib-0.4.0-src.tar.gz", and manually install ta-lib
run the following code in shell, (you may need to change the path to ta-lib or ta-lib version)
export TA_INCLUDE_PATH='/home/username/.linuxbrew/Cellar/ta-lib/0.4.0/include'
export TA_LIBRARY_PATH='/home/username/.linuxbrew/Cellar/ta-lib/0.4.0/lib'

then run "pip install ta-lib"


Are there any differences between the sample covariance matrix and the population covariance matrix?

Question: Are there any differences between them (w.r.t) the calculation. I know the sample covariance matrix uses the sample data and the population covariance matrix uses the random varibles.
Answer: Sample covariance matrix is an estimation for the population covariance matrix. As all estimators, it uses sample data and is experimental. On the other hand, the population statistics is theoretical and can be calculated when you know the joint distribution.


ListView with checkboxes or multiple listeners for list item

Question: I realise that this question has been asked a lot and i've read the first 2 pages of google about it but i couldn't find an answer that worked.
Basically i want a ListView with custom items, each one should have a checkbox. How can i make it so that when i click a checkbox the equivalent of listView.setItemChecked(int, boolean)... would happen?
Some of the answers i've found required having another boolean in the list objects, or some would reuse the checkboxes so they reappear checked further down the list. Is there a way to have a checkbox modify something in the listView or how could i add multiple listeners to a list item? For example when i clicked the text something would happen but clicking the image would trigger something else?
Thanks.
Answer: You can listen for multiple items at a list row easily. just listen for them inside your list adapter getView method after finding them.
hope it helps


Evaluate $\sum_{n\geq1} \frac{(-1)^{n+1}H_n^2}{(n+1)^2}$.

Question: I am looking for a closed for $$\sum_{n\geq1} \frac{(-1)^{n+1}H_n^2}{(n+1)^2}.$$ I believe there is a closed form for the sum as we have seen in [1] which poses as, presumably, a more difficult sum of higher order.  Any hint would be much obliged; thank you!
[1]: How to find ${\large\int}_0^1\frac{\ln^3(1+x)\ln x}x\mathrm dx$
Comment: Reindex then use the sum in here https://math.stackexchange.com/questions/3251069/nice-two-related-sums-sum-n-1-infty-frac-1nh-n2n2-and-sum
Comment: $$S=-\frac1{12}\ln^42+\frac{1}{2}\ln^22\zeta(2)-\frac{7}{4}\ln2\zeta(3)+\frac{33}{16}\zeta(4)-2\operatorname{Li}_4\left(\frac12\right)$$
Comment: @zalm Welcome here. Please tell us what you did so far with the problem.
Answer: Besides the solution suggested in the comment, here is another idea:
Recall the generating function (see relation 10)
$$\small{\sum_{n=1}^\infty\frac{ H_n^{2}}{n+1}x^{n}=\frac{6\operatorname{Li}_3(1-x)-3\operatorname{Li}_2(1-x)\ln(1-x)-\ln^3(1-x)-3\zeta(2)\ln(1-x)-6\zeta(3)}{3x}}$$
where if we replace $x$ by $-x$ then $\int_0^1$ we have
$$\small{\sum_{n=1}^\infty\frac{ (-1)^nH_n^{2}}{(n+1)^2}=-\int_0^1\frac{6\operatorname{Li}_3(1+x)-3\operatorname{Li}_2(1+x)\ln(1+x)-\ln^3(1+x)-3\zeta(2)\ln(1+x)-6\zeta(3)}{3x}}dx$$
$$=2\int_0^1 \frac{\zeta(3)-\text{Li}_3(1+x)}{x}dx+\int_0^1\frac{\text{Li}_2(1+x)\ln(1+x)}{x}dx$$
$$+\frac13\int_0^1\frac{\ln^3(1+x)}{x}dx+\zeta(2)\int_0^1\frac{\ln(1+x)}{x}dx$$
$$=2I_1+I_2+\frac13I_3+\zeta(2)I_4$$
Starting with the simplest integral
$$I_4=-\text{Li}_2(-x)|_0^1=\frac12\zeta(2)$$
By integration by parts we have
$$I_1=\int_0^1\frac{\ln x\text{Li}_2(1+x)}{1+x}dx$$
write $\ln x=\ln x+i \pi-i \pi=\ln(-x)-i \pi$
$$\Longrightarrow I_1=\int_0^1\frac{\ln(-x)\text{Li}_2(1+x)}{1+x}dx-i\pi\int_0^1\frac{\text{Li}_2(1+x)}{1+x}dx$$
$$=-\frac12\text{Li}_2^2(1+x)|_0^1-i\pi\text{Li}_3(1+x)|_0^1$$
$$=-\frac12(\text{Li}_2^2(2)-\zeta^2(2))-i\pi(\text{Li}_3(2)-\zeta(3))$$
$$=\frac{i\pi}{8}\zeta(3)-\frac{25}{16}\zeta(4)$$
By Landen's identity $\text{Li}_2(1-x)=\zeta(2)-\ln x\ln(1-x)-\text{Li}_2(x)$ with replacing $x$ by $-x$ we have
$$I_2=\zeta(2)\int_0^1\frac{\ln(1+x)}{x}dx-\int_0^1\frac{\ln(-x)\ln^2(1+x)}{x}dx-\int_0^1\frac{\text{Li}_2(-x)\ln(1+x)}{x}dx$$
$$=\zeta(2)I_4-\int_0^1\frac{\ln x\ln^2(1+x)}{x}dx-i\pi \int_0^1\frac{\ln^2(1+x)}{x}dx+\frac12\text{Li}_2^2(-x)|_0^1$$
where
$$\int_0^1\frac{\ln x\ln^2(1+x)}{x}dx=-\int_0^1\frac{\ln^2x\ln(1+x)}{1+x}dx$$
$$=-4\operatorname{Li_4}\left(\frac12\right)+\frac{15}4\zeta(4)-\frac72\ln2\zeta(3)+\ln^22\zeta(2)-\frac{1}{6}\ln^42$$
the last integral is already calculated in this solution ( see the integral $I$).
and
$$\int_0^1\frac{\ln^2(1+x)}{x}dx=\frac14\zeta(3)$$
follows from this generalization which also gives
$$I_3=\int_0^1\frac{\ln^3(1+x)}{x}dx=6\zeta(4)-\frac{21}{4}\ln2\zeta(3)+\frac32\ln^22\zeta(2)-\frac14\ln^42-6\text{Li}_4\left(\frac12\right)$$
Collecting all the pieces we have
$$\sum_{n=1}^\infty\frac{ (-1)^nH_n^{2}}{(n+1)^2}=2\operatorname{Li}_4\left(\frac12\right)-\frac{33}{16}\zeta(4)+\frac{7}{4}\ln2\zeta(3)-\frac{1}{2}\ln^22\zeta(2)+\frac1{12}\ln^42$$


Change the Created and Last Modified dates in SharePoint/MOSS 2007

Question: We are migrating a large directory structure of documentation into SharePoint 2007.  In our tests, SharePoint obviously sets the created and modified date to the upload time.  Is there anyway to change that to the information from the file?
We are already setting various other metadata in our upload script, but it appears that we can't modify those values.
Answer: Here are some more details on using the API to update the created and modified dates on items in SharePoint:
<code>SPSite site = new SPSite("http://sharepointsite/subsite");
SPWeb web = site.OpenWeb();
SPList list = web.Lists["My List"];
web.AllowUnsafeUpdates = true;
foreach (SPListItem item in list.Items)
{
   item["Modified"] = "Set the date";
   item["Created"] = "Set the date";
   item.UpdateOverwriteVersion();
}
</code>
Comment: Unfortunately this will only modify the dates of the SPListItem, but the containing thread will still have today's date/time.
Answer: You can do it through the API, the Created property on SPListItem is writable.


Automatically switch back to NerdTree after pressing "o" on file

Question: When I press "o" on any file in NerdTree list, it opens this file in one of currently opened tabs. Sometimes, when I'm not 100% sure what file to open, I have to do this:
1) o (open file)
2) ctrl-ww (switch back to nerdtree)
3) j or k (go to next file)
repeat 1-3 many times
I want to be able to press Alt-o to open file and switch back to NerdTree.
I tried this:
map <M-o> o<C-w>w

map <M-o> oC-ww

and both didn't work. What is wrong and how can I fix my mapping?
Comment: You didn't [RTFM](https://github.com/scrooloose/nerdtree/blob/master/doc/NERD_tree.txt#L223), did you?
Comment: @romainl, Thank you for pointing at this; unfortunately I missed this command when I took a look at the manual.
Answer: This is built into the plugin; the go command does this:

go    Open selected file, but leave cursor in the NERDTree


Segmentation fault, initializing recursive struct in C

Question: Okay, I put together a simplified example of the problem code:
#include "stdio.h"
#include "string.h"

struct Trie{
    //Holds sub-tries for letters a-z
    struct Trie *sub[26];
    //Is this a substring, or a complete word?
    int is_word;
};
typedef struct Trie Trie;

Trie dictionary;

int main(int argc, char *argv[]){
    //A list of words
    char *words[7] = {"the","of","and","to","a","in","that"};

    //Add the words to the Trie structure
    int i=0, wordlen;
    Trie *sub_dict;
    for (;i<7; i++){
        //Reset
        printf("NEW WORD\n");
        sub_dict = &dictionary;
        //Add a word to the dictionary
        int j=0, c;
        while (c = words[i][j], c != '\0'){
            printf("char = %c\n",c);
            //Initialize the sub-Trie
            if (sub_dict->sub[c-97] == NULL)
                sub_dict->sub[c-97] = (Trie*) malloc(sizeof(Trie*));
            //Set as new sub-trie
            sub_dict = sub_dict->sub[c-97];
            j++;
        }
        sub_dict->is_word = 1;
    }
}

Basically, I have a Trie data structure that holds the letters "a" through "z". I have a list of words that should get added inside the while loop. Unfortunately, I get a segmentation fault at different points in the loop (depending on when I run it).
I'm guessing the problem has something to do with the line
sub_dict->sub[c-97] = (Trie*) malloc(sizeof(Trie*));
but I'm new to C, so I have absolutely no clue what's going on.
Answer: sub_dict->sub[c-97] = (Trie*) malloc(sizeof(Trie*));
there is an error.
sizeof(Trie*) will be 4 in 32bit os, because Trie* is a pointer, and the size of a pointer in 32bit os is 4.
you can do like this: sub_dict->sub[c-97] = (Trie*) malloc(sizeof(Trie));
Comment: Because you go writing beyond the end of the memory that was allocated, so you trampled over `malloc()`'s control information, so it got confused about which memory it should give you next.
Comment: Why does it segfault if I do `Trie temp; sub_dict->sub[c-97] = &temp` instead? Shouldn't that do the same thing as using `malloc`?
Answer: You seem to presume that when you do
something = (Trie*) malloc(sizeof(Trie*));

then the contents of that structure is initialized to zeroes (e.g. every member will start as NULL). This is not the case with malloc(). You have to either use calloc, or use memset() to reset it after allocation.
In fact, I'd call memset even on your starting dictionary to be on the safe side. (Even though global and static variables are apparently initialized to zero, so this might not be necessary for your case.)
Comment: Yes; use `calloc()` to get zeroed memory.  The data returned by `malloc()` may contain any sort of garbage; it is at most accidentally zeroed.
Comment: So, will the structure just be filled with a bunch of garbage then? Is it only by luck that `sub_dict->sub[c-97] == NULL` gives the intended result?


Como fazer quebra de linha automática em uma textarea com JavaScript ou jQuery

Question: Estou fazendo um envio de mensagem e quero colocar o botão como se fosse dentro do textarea, mas o problema é que a escrita passa por debaixo do botão, existe alguma maneira com CSS, javascript ou jQuery de evitar isso?
Segue o código:

$(document).ready(function(){

        $("#mostrarMsg").hide();

        $('#mensagem').keyup(function(e){
            if (e.keyCode == 13){
                enviarMensagem();
            }
        });
});

function enviarMensagem(){
  var mensagem = $("#mensagem").val();
  if(mensagem == "" || mensagem == " " || mensagem == null){
    return;
  }else{
    $("#mostrarMsg").html(mensagem).show();
    $("#mensagem").val('');
  }
}

#btnEnviarChat{
    position: inherit;
    float:right;
    margin-top:-50px;
    margin-right:10px;
    opacity: 0.5;
    transition-duration: 1s;
}

#btnEnviarChat:hover{

    transition-duration: 1s;
    opacity: 0.9;

}

.caixaMensagem{
    resize:none;
    width:100%;
    height:50px;
    border:1px solid black;
}
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">

Aperte Enter para enviar

    <textarea cols="10" id="mensagem" placeholder="Digite sua mensagem..." class="caixaMensagem"></textarea>
    <button id="btnEnviarChat" onclick="enviarMensagem()" class="btn btn-success"></button>

Answer: Coloque um padding-right: 60px; no textarea que o texto não vai chegar no botão:

$(document).ready(function(){

        $("#mostrarMsg").hide();

        $('#mensagem').keyup(function(e){
            if (e.keyCode == 13){
                enviarMensagem();
            }
        });
});

function enviarMensagem(){
  var mensagem = $("#mensagem").val();
  if(mensagem == "" || mensagem == " " || mensagem == null){
    return;
  }else{
    $("#mostrarMsg").html(mensagem).show();
    $("#mensagem").val('');
  }
}
#btnEnviarChat{
    position: inherit;
    float:right;
    margin-top:-50px;
    margin-right:10px;
    opacity: 0.5;
    transition-duration: 1s;
}

#btnEnviarChat:hover{

    transition-duration: 1s;
    opacity: 0.9;

}

.caixaMensagem{
    resize:none;
    width: 100%;
    height:50px;
    border:1px solid black;
    padding-right: 60px;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">

Aperte Enter para enviar

    <textarea cols="10" id="mensagem" placeholder="Digite sua mensagem..." class="caixaMensagem"></textarea>
    <button id="btnEnviarChat" onclick="enviarMensagem()" class="btn btn-success"></button>


Override objects return value

Question: I'm trying to compare an object with an int value such as
if (myObject - 5 == 0)
    doSomething();

my class could look something like this: (most setters/getters removed, so don't mind that all variables are private)
public class SomeClass
{
    public string name;
    private int minValue;
    private int maxValue;
    private int currValue;

    public int getCurrentValue()
    {
        return currValue;
    }
}

What I'm trying to achieve is something like this:
someClassInstance - 5;

to be equal
someClassInstance.getCurrentValue() - 5;

Can I make an override for the object to act as an int (it's own variable) opposed to just being an object?
Comment: possible duplicate of [How to add or subtract two instances of the same class/type](http://stackoverflow.com/questions/10390995/how-to-add-or-subtract-two-instances-of-the-same-class-type)
Comment: Dmitry's answer below is excellent, but just ask yourself if it makes sense to use an unary operator like that. For example: "myCar + hisCar" would make it difficult to understand what operation is being done.
Comment: I am blown away by how cool Dmitry Bychenko answer is, but I somewhat prefer Matthew Watson since it seems more efficient performance wise.
Comment: I don't thing this question should be closed because of @Matthew Watson answer that is not available on the other answer.
Comment: @CreativeMagic: a duplicate can contain better answers as the original, actually this is often the case. It should be closed as duplicate anyway. Note that closing does not mean that it gets deleted, both questions will be linked together.
Answer: May be operator is the case?
public class SomeClass {
  ...

  public static int operator -(SomeClass left, int right) {
    if (Object.ReferenceEquals(null, left))
      throw new ArgumentNullException("left");

    return left.getCurrentValue() - right;
  }
}

...

SomeClass someClassInstance = new SomeClass(...);

int result = someClassInstance - 5;

Another possibility (based on implicit operator) is to convert SomeClass implicitly to int whenever required:
public class SomeClass {
  ...

  // Whenever int is requiered, but SomeClass exists make a conversion
  public static implicit operator int(SomeClass value) {
    if (Object.ReferenceEquals(null, value))
      throw new ArgumentNullException("value");

    return value.getCurrentValue();
  }
}

...

SomeClass someClassInstance = new SomeClass(...);

int result = someClassInstance - 5;

Comment: @besworland: "int result = 5 - classInstance" will not work with "-" operator (you should implement "int operator -(int left, SomeClass right)" in addition to existing one - arguments order matters); but it will work with implicit operator
Comment: +1 worth noting that he should better use a immutable value type, so a `struct` instead of class. To quote E.Lipper: _"this is precisely the sort of job that immutable value types were designed for"_
Comment: Just as a question, will this work with int conversion operator overloaded: int result = 5 - classInstance; ?
Answer: Actually you would be much better off overriding operator int, that way you can do far more calculations with less overloads:
using System;

namespace Demo
{
    public class SomeClass
    {
        public string name;
        private int minValue;
        private int maxValue;
        public int currValue;

        public int getCurrentValue()
        {
            return currValue;
        }

        public static implicit operator int(SomeClass value)
        {
            if (value == null)
                throw new ArgumentNullException("value");

            return value.currValue;
        }
    }

    internal class Program
    {
        private void run()
        {
            var test = new SomeClass {currValue = 5};

            if (test - 5 == 0)
                Console.WriteLine("It worked");

            if (test + 5 == 10)
                Console.WriteLine("This also worked");
        }

        private static void Main()
        {
            new Program().run();
        }
    }
}

Comment: You do have to be careful with implicit conversions though - you can accidentally pass something to a method that expects an `int` and it will silently convert it for you. If you don't want that kind of behaviour, you can change `implicit` to `explicit` and then you have to add an explicit cast to `int`.
Comment: This one seems even better, then operator - overloading! Cool, always good to learn something new! :)
Answer: You could experiment with a mixture of implicit conversions and operator overloading, but from my experience you will never make it work as seamlessly as you wish (and as you could get it to work in C++).
If I were you, I would change the getCurrentValue to a property:
public int CurrentValue
{
    get {return currValue};
}

and just use someClassInstance.CurrentValue -5

Override objects return value


Find the volume bound by the curve $\gamma(t) = (e^{\sin(t)}\cos(t),e^{\cos(t)}\sin(t))$

Question: Find the volume bound by the curve $\gamma(t) = (e^{\sin(t)}\cos(t),e^{\cos(t)}\sin(t))$
I've tried computing directly with $\int_0^{2\pi} \int_0^R r \, dr \, d\theta$ where $R = \sqrt{(e^{\sin(t)}\cos(t))^2+(e^{\cos(t)}\sin(t))^2}$ but this seems unfruitful.
I've also tried considering the path as a line integral over the vector field $F=(-y,x)$, which gives us the area by Green's theorem. Here's why...
\begin{equation}
\int_\gamma F \cdot dr = \int_\gamma -y\,dx+x\,dy = \iint\limits_\Omega dA = \mathrm{Area}(\Omega)
\end{equation}
Where $\Omega$ is the region bound by the curve. But this attempt also seems unfruitful. To be honest I'm not sure if this is even possible without numerical methods. Thanks for the help in advance.
Comment: Just a comment that your first approach can't work, because the parametric form is not of the form $(x,y)=R(\theta)(\cos\theta,\sin\theta)$.
Comment: Among other things, I changed \underset{\Omega}{\int \int} to \iint\limits_\Omega (with two consecutive "i"s).  Thus instead of $\displaystyle\underset{\Omega}{\int \int}$ we see $\displaystyle\iint\limits_\Omega$. ${}\qquad{}$
Comment: By computing $\gamma\wedge\gamma'$ I got $$\pi  \left(2 \text{Hypergeometric0F1Regularized}\left[1,\frac{1}{2}\right]-\frac{3}{2} \text{Hypergeometric0F1Regularized}\left[2,\frac{1}{2}\right]\right).$$
Comment: I am completely unfamiliar with what you just wrote. Hypergeometric 0F1 Regularized !?!
Comment: @user152558: as shown below, the area depends on certain values of Bessel functions, hence it does not have a nice closed expression, but can be computed through a really fast converging series.
Answer: $$\gamma(t)=(x(t),y(t))=\left(e^{\sin t}\cos t,\,e^{\cos t}\sin t\right)$$
is a closed simple curve around the origin, counter-clockwise oriented. The enclosed area is given by:
$$ A = \frac{1}{2}\int_{0}^{2\pi}\left(xy'-yx'\right)\,dt = \frac{1}{8}\int_{0}^{2\pi}e^{\cos t+\sin t}\left(4-\cos t-\sin t+\cos(3t)-\sin(3t)\right)\,dt $$
or, by setting $t=x+\frac{\pi}{4}$,
$$ A = \frac{1}{8}\int_{0}^{2\pi}e^{\sqrt{2}\cos x}\left(4-\sqrt{2}\cos x-\sqrt{2}\cos(3x)\right)\,dx.\tag{1} $$
Since for any $\alpha\in\mathbb{R}$ and $n\in\mathbb{N}$ we have:
$$ \int_{0}^{2\pi} e^{\alpha\cos x}\cos(nx)\,dx = 2\pi\cdot I_{n}(\alpha)\tag{2}$$
by the integral definition of the modified Bessel functions of the first kind, it follows that:
$$ A = \color{red}{\frac{\pi}{4}\left(4\, I_0(\sqrt{2})-\sqrt{2}\, I_1(\sqrt{2})-\sqrt{2}\, I_3(\sqrt{2})\right)}=\color{blue}{3.84713365\ldots}.\tag{3} $$
The area has so a fast-converging series representation given by:
$$ A = \color{purple}{\frac{\pi}{4}\sum_{m=0}^{+\infty}\frac{1}{2^m\,m!^2}\left(4-\frac{1}{m+1}-\frac{1}{2(m+1)(m+2)(m+3)}\right)}.\tag{4}$$


Removing "Member for"

Question: How can I remove the Member for information from appearing on accounts?
I know I can hide the field, but the problem is that Ubercart order link appears in the history field, so I can't hide the field. I have tried using CSS to hide the details, but failed as hiding the dl tag hides the whole field.
Answer: From this comment:

in D7 history is a field on the user entity
goto admin/config/people/accounts/display set the format of the
  history field to 'hidden'
Comment: I have tried hidding the field but the problem is this also hides the ubercart 'view your order history' link, which i want to show on the account page.
Comment: What is the URL for the Ubercart account page ?
Comment: @JasmineAhmed if Ubercart conflicts with core in your use case, either ask how to deal with Ubercart or how to deal with conflict. This answer is a good answer for what you actually asked. Feel free to ask next question, about this conflict this time. by the way, you are 12 versions behind, consider upgrade.
Answer: you remove it in this hook hook_user_view
or you can  add your one .tpl. file,
and just hide it there user-profile-category.tpl.php
 $profile_items

here you'll mess with a html_string - see also https://stackoverflow.com/questions/13620249/how-to-hide-history-section-in-drupal-user-profile-page

Removing "Member for"


Como ocultar todos os botões com foreach?

Question: Segue código:
FindViewById<Button>(Resource.Id.Button_1).Visibility = ViewStates.Gone;

O código acima é para ocultar um "botão 1" e tenho mais de 50 botões. Não quero copiar toda essa linha e fazer até 50 vezes, é muito cansativo. Existe uma forma de fazer um loop usando foreach ou for para ocultar todos esses botões  ?
Answer: Em um pergunta com uma dúvida semelhante, surgiu a seguinte solução:
ViewGroup group = findViewById(R.id.root); // The name of your layout
int children = group.getChildCount();
for (int i = 0; i < children; i++) {

    View child = group.getChildAt(i);
    if (child instanceof ViewOne) {
       ...
    } else if (child instanceof ViewTwo) {
       ...
    }
}

No qual você pega um layout raiz (que contém os seus botões) e consegue iterar sobre eles.
No seu caso ficaria algo como:
ViewGroup viewGroup = FindViewById<ViewGroup>(Resource.Id.root);
int children = viewGroup.ChildCount;
for (int i = 0; i < children; i++)
{
    string buttonID = "btn" + i;
    int resID = Resources.GetIdentifier(buttonID, "id", PackageName);
    FindViewById<Button>(resID).Visibility = ViewStates.Gone;

}

Fonte: https://stackoverflow.com/questions/4184889/android-refer-to-custom-views-in-a-loop/4185818#4185818


Does using Redis for task queuing in NAutobot guarantee transaction safety?

Question: We want to use NAutobot to store a machine state in a custom field.
To prevent 2 services updating this custom field at the same time, it needs proper transaction safety. If I understand the NAutobot documentation right, using Redis ensures this.
Can someone with actual hands on experience confirm this?
Comment: couldn't add a new tag "NAutobot" because I lack the required reputation
Comment: Actually it's a bit ambiguous - at least for me as a non-native speaker. The docs say: "This is used to provide a concurrent write lock for preventing race conditions when allocating IP address objects" So does it work for custom fields as well?
Answer: Answering my own question here since I got an answer from one of the maintainers on Github.

Redis itself does not guarantee this, but the library we are currently using (RQ) for tasks does guarantee order of operations to some degree since each worker can only process a single job at a time.

For the majority of cases, including custom fields, this is not a concern because all database writes happen within transactions, making race conditions for updating the same object at the same time practically impossible.

The concurrent write lock for IP address objects is different. This is because of the feature within Nautobot to allow for a simultaneous request for free address space from a network prefix (e.g. "give me the next 10 available IPs in 192.168.0.0/24..."), and immediate allocation of any number of those free addresses returned by the request (e.g. "... and allocate them"). To do this, the list of IPs returned by the query are immediately written back to the database, creating new IPAddress objects, and therefore removing them from the free pool.

IPAddress objects do not have a uniqueness constraint, so without this explicit write lock, it would be possible for two callers to request IPs from the same block, receive the same free addresses, and attempt to allocate duplicates. This violates the principle of least astonishment, but not the data model, so the Redis write lock here is the key to preserving reasonable expectations of the first caller to receive the lock being the one to allocate the IPs, while the following caller either receiving a correct list, or being unable to allocate the addresses because they are no longer free.

I hope this answers your question!


NoMethodError in Shippers#create after render controller_new_path

Question: My issue is I am checking the validation of a form_for with a nested fields_for inside of it to access the Address table where the user enters in basic information. If any information is incorrect rendering back to the page does not load. The error I am receiving is...
NoMethodError in Shippers#create
undefined method 'addcheck' for #<Address:0x9fb9664>
I feel this is because the checkbox is not a variable in the address table like the rest of the a.variables in the fields_for are. It is used to simply add the address to a Contacts table if it is checked.
I will add - - - to indicate where the errors were
The view for Shippers.new.html where the error occurred is
<%= fields_for :address do |a| %>

    Street Address
  You can drag the marker to property position

    <%=  a.text_field :street_address, :class=> "form-control", :id=> "address", :placeholder=> "Enter Starting Location", :autocomplete=> "on" %>

        Add Contact?
-----------------------------------------------------

            <%= a.check_box :addcheck %>

------------------------------------------------------

I am validating all information in the model by...
class CurrentPackage < ActiveRecord::Base

self.primary_key = :shipment_id
belongs_to      :address, foreign_key: "address_start"

validates :title, :presence => true
validates :total_cost, :presence => true
validates :weight, :presence => true
validates :dimensions, :presence => true
validates :user_id, :presence => true

The create action in my Shippers controller is...
def create

    @address = Address.where({street_address: params[:address][:street_address], city: params[:address][:city], state: params[:address][:state], zip_code: params[:address][:zip_code]}).first
    @shippers = CurrentPackage.new( user_params )
    @shippers.user_id = current_user
    @shippers.time_created = Time.now

    @address2 = Address.where({street_address: params[:address][:street_address2], city: params[:address][:city2], state: params[:address][:state2], zip_code: params[:address][:zip_code2]}).first

    if (!!@address) == false
        @address = Address.new(street_address: params[:address][:street_address], city: params[:address][:city], state: params[:address][:state], zip_code: params[:address][:zip_code])
        @address.save!
    end

    if (!!@address2) == false
        @address2 = Address.new(street_address: params[:address][:street_address2], city: params[:address][:city2], state: params[:address][:state2], zip_code: params[:address][:zip_code2])
        @address2.save!
    end

    @temp = @address.address_id
    @shippers.address_start = @temp

    @temp2 = @address2.address_id
    @shippers.address_end = @temp2

    #@shippers.save!      #replacing
    ------------------------------------------------------
    if @shippers.save
        #redirect_to @shippers
        redirect_to shippers_index_path

    else
        render shippers_new_path         #addcheck fails
        #render @shippers
        #redirect_to shippers_new_path   #works but loses data
        #render 'new'                    #addcheck fails

    end
    --------------------------------------------------
    if (params[:address][:addcheck] == "1")

        if (!!Contact.where({user_id: current_user, contact: @temp}).first) == false
            hmm = Contact.new(user_id: current_user,contact: @temp)
            hmm.save!
        end
    end
    if (params[:address][:addcheck2] == "1")
        if (!!Contact.where({user_id: current_user, contact: @temp2}).first) == false
            hmm2 = Contact.new(user_id: current_user, contact: @temp2)
            hmm2.save!
        end
    end

end

My routes.rb files looks like
get "shippers/isdriver"
get "shippers/index"
get "shippers/show"
get "shippers/update"
post "shippers/create"
get "shippers/new"
get "shippers/destroy"

devise_for :users
get "home/index"

resources :addcheck

I added the resources :addcheck because I saw another stackoverflow post said it worked for them, but not for me.
Just to reiterate, this only happens if the form is incorrect, goes into the else condition for the if @shippers.save, then it tries to load the new page again and breaks.
Any help would be INCREDIBLY appreciated :D
***** Additional Information *******
I took out the addcheck rails line, and ran again, but broke on the next field of :street_address2  for the same reason, because it is not actually a variable in any model, just a place holder.
Comment: This is one of the scenarios for which `strong parameters` have been introduced to ActionController. You should consider checking them out and maybe also using them.
Comment: Thank you for the reply, do you think this could explain though why it loads from a link, but upon rerendering from invalid data it crashes? I do have strong params for the "CurrentPackage.new( user_params )" but I can do the same for Address. If you think this explains its odd behavior, I can give it a shot.
Comment: It fails because `adcheck` is still associated to address. If you want to permanently solve this, maybe you should  make `adcheck` fall out of the `address` hash. Hence, in your view, instead of `<%= a.check_box`, probably better to use `<%= check_box_tag`, (see reply by @clark)
Answer: Rather than associating the check with the address model <%= a.check_box :addcheck %> I think you should make them independent <%= check_box_tag(:addcheck) %>
Comment: Yes! This was the correct approach! Thank you clark and Ruby Racer, you two are awesome!
Answer: Remove the attribute before passing it to the model
if(params[:address].delete(:addcheck) == "1")
....
end

Comment: Thank you for replying so quickly!
I added the line "if (params[:address].delete(:addcheck) == "1")" to see if this would address the issue, but it did not seem to change anything. I am never passing addcheck to the model, since its not part of the address table or any table, it is just part of a check if the user wants to add someone as a contact.
Comment: You must remove the attribute prior to doing the save
Comment: Im not entirely sure still howto correct this.
Could you possibly explain any reason why it works the first time, but only crashes after rerendering?
Comment: Robert, the attribute addcheck is not a real attribute but you are passing it in the model's create method when you call @shippers.save.  ActiveRecord is raising an error as it doesn't understand this attribute that you passed in so you must take measures to remove it from the params hash


Secure Database

Question: We are an Oracle database shop.  I have an application for which I think Oracle likely isn't the best answer.  I am looking for a lightweight, good performing and very secure database.  The database itself will have probably a dozen tables and maybe millions of records.  I don't need stored procedures, clustering or any of the high-end features.
My ultimate goal is security.  I'm looking for built-in encryption, an overall secure design and low-profile to minimize potential security holes.
I'll want to run it on *nix, since they are much easier to make low-profile than Windows.
For example, in the BSD world there are several variants.  FreeBSD is the most portable and OpenBSD is the most secure.  I'm looking for the OpenBSD of the database world.
Comment: This is a very odd question. I don't think I've ever heard of a database that touts security over services. Looking forward to the answer ...
Answer: I'm not aware of any existing item with this particular design goal.  The best you will get is a DBMS with reasonably good built-in security.  Most of the 'NoSQL' DBMS applications don't offer anything particularly special in security.  Traditional database management systems often have quite rich security models and security on this type of system is a mature and well understood discipline.
If you want something to put behind a secure web application, you really have no choice but to design the application with security in mind - traditional database security (e.g. mediate all write access through sprocs with no direct write access to tables) is the best you are likely to get.  Don't forget to have a separate DBMS server and firewall access to the machine appropriately.
If you are worried about physical security of the server, many DBMS platforms have options for physically encrypted data (e.g. PostgreSQL).  Some operating systems will also support encrypted file systems and certain disks also support physical encryption.  Note that key recovery will still negate the encryption - if the key is physically present on the DBMS server a technically savvy hacker may well be able to recover it.
In order to design the security and evaluate what architecture is appropriate you will really have to come up with a threat evalutaion to get some idea of what you are securing against.  Some scenarios might be:

If you want to secure an internal system from prying eyes then appropriate user/role security on a DBMS platform is probably adequate.
If you want to secure a web application then you can get some incremental security by adding a secured transaction layer through sprocs.  This restricts database writes to explictly supported transactions - for example, if an intruder wanted to erase an audit trail they would have to compromise both application and database security to erase entries from the audit tables.  However, the intruder can still execute any valid transaction.
If you have issues with physical security you could possibly try encryption at the disk level.  An entry level SAN might also help with this as the disks can only be accessed through the SAN controller.  This requres that the thief compromise the SAN controller's security or reverse engineer its internal partition format.  Some SANs also offer physical disk encryption.

Bear in mind that most DBMS platforms in widespread use have been used for web applications and have a degree of maturity in this space.  None were designed specifically to be hardened, but most (open-source ones in particular) have been used in web applications for the better part of 15 years.  In this space, application security is really the weak link.
Answer: Full disclosure: I work on the Sybase SQL Anywhere engineering team. I'm actually responsible for many of the security features. I'm trying to answer the question without making the answer sound like an advertisement.
Sybase SQL Anywhere is a lightweight RDBMS which includes all your standard RDBMS features like stored procedures, triggers, row-level locking, etc. as well as your standard security features like users, groups, and object (table, procedure, etc.) permissions. It also contains many advanced security features including strong (AES) database encryption and SSL/HTTPS communications encryption. There is a FIPS-approved encryption component available, and it has achieved Common Criteria certification (look for Adaptive Server Anywhere) at the EAL3+ level.
I do have to say that SQL Anywhere was not designed with security as its primary focus; I'm not aware of any database product that was.

Secure Database


Simulating beta distribution for 6 traits

Question: How can I generate a matrix of 1 and 0 in R, for 1000 items (rows), where each item can only be 1 for a single trait out of 6 possibilities (columns) traits A, B, C, D, E and F e.g.
item A  B   C   D   E   F
1    1  0   0   0   0   0
2    0  1   0   0   0   0
3    1  0   0   0   0   0
4    0  0   0   0   1   0
5    0  0   0   0   1   0
6    0  0   1   0   0   0
7    0  0   0   1   0   0
8    0  1   0   0   0   0
9    1  0   0   0   0   0
10   0  0   0   0   1   0

So that when plotting these 6 traits (on the x axis A=0, B=0.2, C=0.4, D=0.6, E=0.8, F=1), their density probability follows a beta (3,7) distribution?
My objective is to generate a set of similar matrices, each representing different beta distributions e.g.(7,3),(2,8),(8,2), (3,3), so that they may jointly cover a wide range of them, including if possible a bimodal distribution other than (0.5, 0.5).
Comment: The beta is a continuous distribution but you seem to be generating a discrete distribution. How exactly are you translating between the two? What value exactly should follow a beta distribution?
Comment: `sample(c(rep(0, 5), 1), 6)`
Comment: How can I edit this to insure that when generating 1000 items, the traits follow a beta (8,2) distribution?
Comment: I should have said broadly beta distributed.
Following this online calculator:
https://keisan.casio.com/exec/system/1180573226
for Beta (7, 3): A is (0,0), B (0.2,0.01032192), C (0.4, 0.37158912), D (0.6, 1.88116992), E(0.8,2.64241152), F(0,0);
for Beta (1,1): A is (0,1), B (0.2,1), C (0.4, 1), D (0.6, 1), E(0.8,1), F(0,1);
for Beta (0.5,0.5):  A is (0,100), B (0.2,0.795774716), C (0.4, 0.649747334), D (0.6, 0.649747334), E(0.8,0.7957747155), F(0,100);
for Beta (3, 3): A is (0,0), B (0.2,0.768), C (0.4, 1.728), D (0.6, 1.728), E(0.8,0.768), F(0,1);
Answer: Please see the results of simulation. I used sample function with probability distribution set through prob argument. As for B(0.5, 0.5) you could tweak x vector at 0 and 1 neighborhoods to exclude infinities:
set.seed(123)

x <- c(0.0, 0.2, 0.4, 0.6, 0.8, 1)
# for beta w/7 & 3 shapes
y <- dbeta(x, 7, 3)

# sample with probabilities y
samp <- data.frame(id = sample(1:6, 1000, y, replace = TRUE))

# prepare a diagonal matrix
m <- data.frame(diag(6), id = 1:6)

# merge to meet the condition only one '1' in each row
u <- merge(samp, m)

# remove id and adding letter names
u <- u[, -1]
names(u) <- LETTERS[1:6]

# validation
# the result by simulation
colSums(u) / 1000
# A     B     C     D     E     F
# 0.000 0.001 0.070 0.385 0.544 0.000

# normalized beta distribution by built-in function
print(setNames(dbeta(x, 7, 3) / sum(dbeta(x, 7, 3)), LETTERS[1:6]), digits = 1)
# A     B     C     D     E     F
# 0.000 0.002 0.076 0.383 0.539 0.000


The content access permissions need to be rebuilt. Rebuild permissions?

Question: My Drpal website asks
"The content access permissions need to be rebuilt. Rebuild permissions"
what is this means?
Can I go for Reubuild Permission?
Will it cause any problem for current modules?
Answer: I cannot give you a full answer. Your answer is specific to your website.

"The content access permissions need to be rebuilt. Rebuild permissions"
  what is this means?

From some Drupal 6 documentation:

Rebuild Permissions If the site is experiencing problems with permissions to content, you may have to rebuild the permissions cache.
  Possible causes for permission problems are disabling modules or
  configuration changes to permissions. Rebuilding will remove all
  privileges to posts, and replace them with permissions based on the
  current modules and settings.
Rebuilding may take some time if there is a lot of content or complex
  permission settings. After rebuilding has completed, posts will
  automatically use the new permissions.

You then asked:

Can I go for Reubuild Permission?

Sure. This process can take a long time though for a site with many nodes and content.

Will it cause any problem for current modules?

Depending on your situation and the new modules you've installed that are changing how content permission is being assigned rebuilding permissions may or not affect your users. You must first verify what modules are affecting the content permissions and be sure you've assigned appropriate permissions to specific roles that may be using them. It is your responsibility as site owner to be aware of module dependencies.
Comment: Congratulations, you just became 10k user :D Enjoy.


why can't I have awk group statements in the if clause only if else clause is present

Question: If this is good awk syntax
awk '{if (0) {print""}}'

and so is this
awk '{if (0) print""; else print ""}'

, then why is this bad syntax??
awk '{if (0) {print""}; else print ""}'

Comment: Just remove the semicolon after `{print ""}`
Answer: Because the awk conditional syntax is (among others)
if condition compound-statement else compound-statement

Just as in C, by the way. This makes
if condition compound-statement ';' else compound-statement

an error.


How can I combine the scores of a multilabel classifier?

Question: I have a keras neural network with 8 outputs and it is a multilabel problem, which means that an observation can be classified into more than one target class.
Let's suppose I have the following vector of 8 probabilities (events A, B, C, D, E, F, G, H) calculated by the model to a given observation:
[0.31, 0.45, 0.89, 0.02, 0.43, 0.21, 0.96, 0.32]
So, we can interpret that:
P(A) = 0.31, P(B) = 0.45 and so on...
But what if I want the probability of an observation belong to classes A or B, for example (P(A or B) = ?). Or the probability P(A and B) = ?
I imagine there are some things to take in consideration, like:
Are the events independent?

How can I check the intersection of the events?
I would appreciate references of how can I approach this problem.
Answer: With Normalization
If we start with the assumption that an object can belong to exactly one class, I think we still can compute the OR probability. Let's normalize the probabilities first, to have their sum as $1$.
probs = np.array([0.31, 0.45, 0.89, 0.02, 0.43, 0.21, 0.96, 0.32])
probs = probs / probs.sum()
probs
# array([0.08635097, 0.12534819, 0.24791086, 0.00557103, 0.11977716,
#        0.05849582, 0.26740947, 0.08913649])

s.t., $P(C_0 \cup C_1) = P(C_0) + P(C_1)$, and the events that an observation belongs to the output classes are mutually exclusive (so that an observation can belong to exactly one class) and $P(C_0 \; \text{OR} \; C_1)$ can be found with
probs[0] + probs[1]
# 0.2116991643454039

and $P(C_i \; \text{AND} \; C_j) = P(C_i \cap C_j) = 0, \quad i \neq j$
Multilabel Classification With Label Powerset

This is a classic approach to deal with multi-label classification, which is used to transform a multi-label problem to multi-class problem.

In this approach, each possible combinations of outputs is treated as a single unique label, i.e., using a mapping from the power set of $C$ to the indices, $2^C \to \{1,2,\ldots,2^{|C|}\}$, where $C=\{C_1,C_2,\ldots,C_k\}$ is set of all possible class labels.

This method allows to compute $P(C_i \cap C_j)$ directly.

The following example demonstrates the idea, using skmultilearn's implementation of LabelPowerset.
# generate a sample multilabel dataset
from sklearn.datasets import make_multilabel_classification
from skmultilearn.problem_transform import LabelPowerset
from sklearn.ensemble import RandomForestClassifier
import numpy.random as random
from scipy import sparse

random.seed(123)
X, y = make_multilabel_classification(n_classes=8,
                      n_labels=2, # average no. of labels per instance
                      allow_unlabeled=False,
                      random_state=1)
y[0:2]
# array([[0, 0, 0, 1, 0, 0, 0, 1],
#        [0, 1, 0, 1, 0, 0, 1, 1]])

classifier = LabelPowerset(
                  classifier = RandomForestClassifier(),
                  require_dense = [False, True]
             )
classifier.fit(X, y)

classifier.unique_combinations_
# {'1': 0,
#  '7': 1,
#  '1,3,7': 2,
#  '0,6': 3,
#  '3': 4,
#  '0': 5,
#  '6': 6,
# '0,1,7': 7,
# '1,4,7': 8,
# '0,4': 9,
# '4': 10,
# '1,3,4,7': 11,
# '1,6': 12,
# '0,5': 13,
# '1,3': 14,
# '3,4': 15,
# '1,4': 16,
# '1,7': 17,
# '0,1': 18,
# '0,1,3': 19,
# '1,3,5': 20,
# '3,6,7': 21,
# '5,7': 22,
# '0,3': 23,
# '1,6,7': 24,
# '0,6,7': 25,
# '3,5': 26,
# '3,7': 27}

def get_OR_prob(X, classes=None):
   pred = classifier.classifier.predict_proba(X.reshape(1,-1))[0]
   for combination_id in range(len(pred)):
      if sorted(classes) ==
          sorted(classifier.reverse_combinations_[combination_id]):
      return pred[combination_id]
   return 0

Compute $P(C_0 \cap C_6)$ and $P(C_0 \cap C_1 \cap C_6)$:
get_OR_prob(X[2], [0,6])
# 0.19
get_OR_prob(X[2], [0,1,6])
# 0