How can I list all the IP address and referrers of visitors of a specific node?

Question: The tracker module is active on the website and I want to get all the Track statistics of a node created.
www.example.com/node/3/track lists all the redirection etc. But what I want to do, is to get all IP addresses that visited this node:
In Track Tab I can see the logs but the IP address and the referrer details are not listed here, to see this info I have to visit the link (www.example.com/admin/reports/access/24488 etc.) for per log listed in Track page.
How can I list all the IP address and referrers of visitors of a specific node via Drupal interface, Views or via PHPMyAdmin etc.?
Comment: Hey herci, any feedback about my answer here?
Comment: Actually I did use the Visitors module. Although it has lots of features I can use it doesn't do what I exactly want. So, at that time I wrote a custom code to get this info directly from the DB. Thanks for your message.
Answer: Have a look at the Visitors module. It comes with various reports, such as reports about pages that have recently been visited, or that have been hit frequently, or about pages count per month, day of month, day of week, hour. And it also includes a Referrers report (for referrer type either internal, external, or both).
One of the included reports is the Recent hits report, a table with columns Date of visit, Title, Path and User ID of the visitor. If you follow any of the "details" links in that report, you'll get something that looks as in this example:

The demo site contains some sample reports (charts) available to anonymous users also.
You may also want to look at the visitors_schema to get an idea of the data that actually get logged (recorded) by this module.
In case the delivered reports are not a perfect fit, it's probably a very good starting point for some custom reporting. Either via a custom module that would simply have to query the data maintained by the Visitors module. Or via a straight forward custom report created with the Forena module.
Disclosure: I'm the maintainer of the Visitors module,
and co-maintainer of the Forena module.


JQuery changing th width after multiple plugins

Question: I am trying to make a table with a scrollable tbody within a table using this plugin. There are plenty of other questions about jquery or pure-css scrollable tbody elements, but none as involved as mine.
The issue is that I'm also using a jQuery tablefilter plugin which adds an additional header row for filters. When I load the tablescroll plugin, it overrides the table dimensions and my headers no longer match.
The columns are variable width and the tablescroll plugin assumes they are equal length which causes the improper alignment.
I tried resetting them manually using javascript Here:
var $table = $(".tablescroll"),
$cols = $(".tablescroll tr td").slice(0,5),
$th = $(".fixedHeader tr th");
$table.tableScroll();
$filter = $(".filterRow th");
$.each($th, function(index, value){
      $th[index].style.width = $cols[index]['clientWidth'];
      $filter[index].style.width = $cols[index]['clientWidth'];
});

and it adds the correct style attribute to each th but the headers keep the same incorrect alignment. This is also the VERY LAST javascript loaded on the page.
Here's my HTML:
<form>

                Name
                Description
                Site
                Created Date
                Modified Date

                Test Name
                Test Description
                Test Site
                2013-12-18 15:20:05
                2014-01-29 19:36:09

</form>

I'm curious why my javascript calls add the style but change nothing about the appearance and if I should continue with this plugin or simply work out a pure css solution.
Thanks in advance.
Answer: Did you try setting the inline style for the table instead of using Javascript?

or for the header column directly

Comment: That's what the js accomplishes if you view page source. However, abstracting it through js allows me to use it in multiple places like I want.
Comment: Your headers change depending on the data? What about min-width and max-width to have a range? Your table header's width will be re-sized depending on the content of the row, if you put a max-width and the content of a cell is too long, it will wrap your text in more than 1 row.
Comment: Sorry, I misunderstood your response. The columns each have a defined width, it's just not the same from column to column. I edited my comment to reflect why I used js.
Comment: I see. Do you have a footer (not the table footer, but a footer you load on every page dynamically) that might be loading other scripts?
Comment: Yes but the page was formatted correctly until I added the tablescroll plugin. I know that is causing the problem so I'm trying to run a fix after it is initialized.
Comment: The plugin you're using creates another table just for the headers. Why don't you try to do what that plugin does manually? I mean, create a table at the top for your headers containing only the thead attribute, and add another table below with only the tbody attribute. Put the 2nd table inside a div and add the css 'overflow:auto' to that div. This will work if you're doing it only to a few tables, otherwise, it will be a nightmare.
Answer: Like @jkgm777 said, the plugin removes the headers and creates a new table for them. This threw off all the css and js that was referencing the header class in the specific table which caused the behavior.
My solution will require a pure-css version due to sorting and filtering functionality that will not work across tables.


AWS FIFO SQS queue message is disappearing when I repost the same message even after successfully deleting it

Question: I am facing a strange issue in SQS. Let me simplify my use-case, I have 7 messages in the FIFO queue and my standalone app should keep-on polling the messages in the same sequence for my business case infinitely. For instance, my app read message1 and after some business processing, the app will delete it and repost the same message into the same queue(tail of the queue), and these steps will be continued for the next set of messages endlessly. Here, my expectation is my app will be polling the message continuously and doing the operations based on the messages in the queue in the same sequence, but that's where the problem arises. When the message is read from the queue for the very first time, delete it, and repost the same message into the same queue, even after the successful sendMessageResult, the reposted message is not present in the queue.
I have included the below code to simulate the issue, briefly, Test_Queue.fifo queue with Test_Queue_DLQ.fifo configured as reDrivePolicy is created. At the very first time after creating the queue, the message is posted -> "Test_Message" into Test_Queue.fifo queue(Getting the MessageId in response ) and long-polling the queue to read the message, and after iterating the  ReceiveMessageResult#getMessages, deleting the message(Getting MessageId in response). Again, after the successful deletion of the message, the same message is reposted into the tail of the same queue(Getting the MessageId in response). But, the reposted message is not present in the queue. When, I checked the AWS admin console the message count is 0 in the Messages available and Messages in flight sections and the reposted message is not even present in Test_Queue_DLQ.fifo queue. As per the SQS docs, if we delete the message, even if it is present in flight mode should be removed, so reposting the same message should not be an issue. I suspect on SQS side, where they are performing some equals comparison and skipping the same message during in visibleTimeOut interval to avoid deduplication of the same message in the distributed environment, but couldn't get any clear picture.
Code snippet to simulate the above issue
public class SQSIssue {

    @Test
    void sqsMessageAbsenceIssueTest() {
        AmazonSQS amazonSQS = AmazonSQSClientBuilder.standard().withEndpointConfiguration(new AwsClientBuilder
                .EndpointConfiguration("https://sqs.us-east-2.amazonaws.com", "us-east-2"))
                .withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(
                        "<accessKey>", "<secretKey>"))).build();

        //create queue
        String queueUrl = createQueues(amazonSQS);
        String message = "Test_Message";
        String groupId = "Group1";

        //Sending message -> "Test_Message"
        sendMessage(amazonSQS, queueUrl, message, groupId);
        //Reading the message and deleting using message.getReceiptHandle()
        readAndDeleteMessage(amazonSQS, queueUrl);
        //Reposting the same message into the queue -> "Test_Message"
        sendMessage(amazonSQS, queueUrl, message, groupId);

        ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest()
                .withQueueUrl(queueUrl)
                .withWaitTimeSeconds(5)
                .withMessageAttributeNames("All")
                .withVisibilityTimeout(30)
                .withMaxNumberOfMessages(10);
        ReceiveMessageResult receiveMessageResult = amazonSQS.receiveMessage(receiveMessageRequest);
        //Here I am expecting the message presence in the queue as I recently reposted the same message into the same queue after the message deletion
        Assertions.assertFalse(receiveMessageResult.getMessages().isEmpty());

    }

    private void readAndDeleteMessage(AmazonSQS amazonSQS, String queueUrl) {
        ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest()
                .withQueueUrl(queueUrl)
                .withWaitTimeSeconds(5)
                .withMessageAttributeNames("All")
                .withVisibilityTimeout(30)
                .withMaxNumberOfMessages(10);
        ReceiveMessageResult receiveMessageResult = amazonSQS.receiveMessage(receiveMessageRequest);
        receiveMessageResult.getMessages().forEach(message -> amazonSQS.deleteMessage(queueUrl, message.getReceiptHandle()));

    }

    private String createQueues(AmazonSQS amazonSQS) {

        String queueName = "Test_Queue.fifo";
        String deadLetterQueueName = "Test_Queue_DLQ.fifo";

        //Creating DeadLetterQueue
        CreateQueueRequest createDeadLetterQueueRequest = new CreateQueueRequest()
                .addAttributesEntry("FifoQueue", "true")
                .addAttributesEntry("ContentBasedDeduplication", "true")
                .addAttributesEntry("VisibilityTimeout", "600")
                .addAttributesEntry("MessageRetentionPeriod", "262144");
        createDeadLetterQueueRequest.withQueueName(deadLetterQueueName);
        CreateQueueResult createDeadLetterQueueResult = amazonSQS.createQueue(createDeadLetterQueueRequest);
        GetQueueAttributesResult getQueueAttributesResult = amazonSQS.getQueueAttributes(
                new GetQueueAttributesRequest(createDeadLetterQueueResult.getQueueUrl())
                        .withAttributeNames("QueueArn"));
        String deadLetterQueueArn = getQueueAttributesResult.getAttributes().get("QueueArn");

        //Creating Actual Queue with DeadLetterQueue configured
        CreateQueueRequest createQueueRequest = new CreateQueueRequest()
                .addAttributesEntry("FifoQueue", "true")
                .addAttributesEntry("ContentBasedDeduplication", "true")
                .addAttributesEntry("VisibilityTimeout", "600")
                .addAttributesEntry("MessageRetentionPeriod", "262144");

        createQueueRequest.withQueueName(queueName);
        String reDrivePolicy = "{\"maxReceiveCount\":\"5\", \"deadLetterTargetArn\":\""
                + deadLetterQueueArn + "\"}";
        createQueueRequest.addAttributesEntry("RedrivePolicy", reDrivePolicy);
        CreateQueueResult createQueueResult = amazonSQS.createQueue(createQueueRequest);
        return createQueueResult.getQueueUrl();
    }

    private void sendMessage(AmazonSQS amazonSQS, String queueUrl, String message, String groupId) {
        SendMessageRequest sendMessageRequest = new SendMessageRequest()
                .withQueueUrl(queueUrl)
                .withMessageBody(message)
                .withMessageGroupId(groupId);
        SendMessageResult sendMessageResult = amazonSQS.sendMessage(sendMessageRequest);
        Assertions.assertNotNull(sendMessageResult.getMessageId());
    }
}

Answer: From Using the Amazon SQS message deduplication ID:

The message deduplication ID is the token used for deduplication of sent messages. If a message with a particular message deduplication ID is sent successfully, any messages sent with the same message deduplication ID are accepted successfully but aren't delivered during the 5-minute deduplication interval.

Therefore, you should supply a different Deduplication ID each time the message is placed back onto the queue.
Comment: Added few more points in https://stackoverflow.com/a/65846306/3303074
Answer: https://stackoverflow.com/a/65844632/3303074 is fitting, I should have added the SendMessageRequest#withMessageDeduplicationId, but I would like to add few more points to the answer, The technical reason behind the message disappearance is because I have enabled the ContentBasedDeduplication for the queue. Amazon SQS uses an SHA-256 hash to generate the MessageDeduplicationId using the body of the message (but not the attributes of the message) if the MessageDeduplicationId has not been mentioned explicitly when sending the message. When ContentBasedDeduplication is in effect, messages with identical content sent within the deduplication interval are treated as duplicates and only one copy of the message is delivered. So even we add different attributes for the same message repost into the same queue will not work as expected. Adding MessageDeduplicationId helps to solve the issue because even the queue has ContentBasedDeduplication set, the explicit MessageDeduplicationId overrides the generated one.
Code Snippet
        SendMessageRequest sendMessageRequest = new SendMessageRequest()
                .withQueueUrl(queueUrl)
                .withMessageBody(message)
                .withMessageGroupId(groupId)
                 // Adding explicit MessageDeduplicationId
                .withMessageDeduplicationId(UUID.randomUUID().toString());
        SendMessageResult sendMessageResult = amazonSQS.sendMessage(sendMessageRequest);


the phrase "its derivative" when a function has a derivative only almost everywhere

Question: Theorem: A function $F$ is an indefinite integral if and only if it is absolutely continuous
Corollary: Every absolutely continuous function is the indefinite integral of its derivative.
(thm 5.14,5.15 Royden,Real Analysis)
Since absolute continuity does not imply differentiability everywhere I am assuming that I could replace this with
"Every absolutely continuous function $F$ is the indefinite integral of any function $f$ which is equal to $F'$ almost everywhere",
and it is just assumed in analysis texts that the reader knows this?
Comment: You missed another infelicity: "the indefinite integral". That should be "an indefinite integral", surely? It looks as if this book was written in a hurry.
Answer: If $f=g$ a.e. then $\int f=\int g$.
Comment: I realize that. It just seems odd that the corollary is stated with "its derivative" when it may not even have a derivative. Considering that mathematicians tend to be so particular about phrasing. So is your answer to my question yes?
Comment: I agree with Hagen.  In Royden's book, you have previously seen how to integrate a function defined almost everywhere; and that it doesn't matter how you extend the definition to everywhere.  Since it makes sense to integrate such an "almost everywhere" defined function, and the derivative we are talking about is such an "almost everywhere" defined function, there is no problem with the statement.
Answer: This is of course technically lazy. However, there is a way it makes sense! The issue here is that technically, the function has a derivative - but said derivative is defined in a space where "almost everywhere" is enough. The derivative is not (quite) a function in the traditional sense - its value is undefined on a set of measure 0.
The way to justify this has to do with the theory of distributions and of the integrable function spaces $\mathcal{L}^p$. The derivative of any continuous (in fact, any locally integrable) function exists in a rigorous sense - it just may not be a function. In this case, what's being noted is that absolute continuity guarantees that the derivative of $f$ is "almost" a function, in the sense of being defined almost everywhere. In particular, this means it's well-defined in the space of integrable functions $\mathcal{L}^1$ - where functions are considered equivalent if they are equal almost everywhere.
Yes, this is a bit odd to wrap one's brain around - but it's a classic analyst's trick to "forget" for the moment that we're passing through a space in which functions are only defined up to changes on a set of measure 0.
EDIT: A quick clarification - what you state in the question, that $F$ is the integral of any function $f$ equal to $F'$ almost everywhere, is in fact ill-defined itself! After all, you're presuming that there's a function $F'$ to be equal to... you're passing through more general function spaces also, and just not noticing.
Comment: I don't state that $F^{'}$ is a function. Actually the question is "what if $F^{'}$ isn't a function.
Comment: OK, there is a lot to think about in EPAstor's answer. I'm surprised the texts (Royden's isn't the only one) assume you know this without mentioning these spaces. Maybe a pointless complaint, but I'm wary of assuming  an omission was made when it's in more than one text.                                                   I did find another text which states instead: "If $f$ is integrable on [a,b], then $F(x)=\int_a^xf(t)dt$ is differentiable almost everwhere, and $F^{'}(x)=f(x)$ almost everywhere." This is (to me) much more comprehensible and takes care of TonyK's comment too.


How can i create touchevents in certain areas of the screen in android?

Question: I have a neat background for my app with the "buttons" already included in the background.
I would like to surround these "buttons" with a bounding box or rectangle somehow and then have that area respond to a touch event.
How can i do this in android?
thanks!
Answer: Simply surround it with any layout and setOnClickListener for that layout.
As an example
 <LinearLayout
   android:background="#abc123"
   android:layout_height="wrap_content"
   android:layout_width="wrap_content"
   android:paddingBottom="10dp"
   android:paddingTop="10dp"
   android:id="@+id/lay1">

 <Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button" />
 </LinearLayout>

Now put separate listeners for the button and the linear layout.This will be consistent with all the screens i.e the padding will be fixed everywhere.
Comment: That depends on your way of creating the layouts.Jst stay away from giving fixed dimensions.
Comment: how do i surround the different parts of the background with any layout?
Comment: i try to wrap the layouts around my background elements but they don't resize the way i want them to. Now they do resize the way i want them to, but they are always shifted back up to the top left corner of the screen. I can't get them to surround the elements i need them to.
Comment: I don't want a button, i just need to be able to touch the screen (not a button) and trigger some code. I already have it working with buttons, but now with the new background i need to be able to touch portions of the background and trigger the touchevents
Answer:
Add button in XML
Attach Click Listener
Run Application

For more information and help click here
EDIT: Code for run
public void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()) {
    case R.id.but_1_but:
        // do stuff for 1st button
        break;
    case R.id.but_2_but:
        // do stuff for 2nd button
        break;
    }
}

Comment: I have already done this, but now i need the code that runs when the button is clicked to happen when a certain area of my background is touched
Comment: my dear friend, i do not want to use a button. However i have found a solution and i will be posting it shortly
Answer: Add a View (This will be transparent and will sit on top of all your view components) to your layout. And set a OnTouchListener to your View. Then listen for touch events within the expected X, Y co-ordinates.
Answer: Try and use
Region rgn = new Region();

In this ,set a boundary  which should be with in the button.
And check a condition that if your click is within the x and y  of this region ,do  something...
Refer
http://www.java2s.com/Code/Android/2D-Graphics/Regions.htm


How to load/export grid data into excel?

Question:
Is their any way to create the excel sheet with the data loaded from grid in extjs.
    Going through this link,I have not clearly understood the appraoch and how to achieve my goal.Other related questions were e.g here,but could not get anything out of it.Please help me resolve this.Any help is appreciated.Thanks.
Answer: The general concept is that an Excel file is actually XML, at least in the more recent versions of Excel. You can create plain XML that just contains the data. Or you can add a lot of formatting, use the rich presentation that Excel provides. I would suggest that you start off as simply as possible, with just the data, and then add complexity.
To learn how to do this, you need to understand how to generate any XML, then the particular XML that Excel requires, and then how to return that mime type to the browser.
Here is one place (of many) that you can find the XML for Excel.
Comment: Thank you for your instant reply.Can you please interpret it somemore with some example(snippet).Thanks
Comment: Sorry, Daemon, I don't know anything about extjs. However, if you do a Google search for "extjs grid export to excel" you should be able to find some code to copy and paste.
Answer: The better option is for export to be handled from the server side rather than from the client-side script. A new request for export can be sent to the server with the currently applied filters and get the file in generated in excel using Apache FOP or similar libraries(http://xmlgraphics.apache.org/fop/).
Export from extjs raises some problems like
1) what data would you expect for a paged grid.
2) what about the filters applied on the grid


Installing PIP on Windows 10 python 3.5

Question: I just started learning Python, and successfully downloaded Python 3.5. I attempted to download/upgrade PIP 8.1.2 multiple times using get-pip.py, which I ran (successfully I think) but when I attempted to execute python get-pip.py
I got the error code:
    File "<stdin>", line 1
    python get-pip.py
        ^
    SyntaxError: invalid syntax

I understand that pip is included in python but the pip website requires users to upgrade pip which I don't think I can since any pip commands lead to syntax errors, and do not produce the same output that most tutorial sites show. I have tried to find different ways to fix it, but I can't figure out whats wrong aside from pip not being on the computer in the first place or corrupted. Thank you for your assistance.
Answer: Not sure what you are asking. If you want to run python get-pip.py do it in a windows command prompt, not in the python interpreter. But I do not know why you would want to do that.
Answer: You already have pip; there is no need to run get-pip. Upgrading can be done by pip itself.
But the reason you are getting errors is that all these commands, including pip itself, should be run at the command line, not in the Python interpreter.
Answer: You won't need to upgrade pip if you just downloaded python 3.5, go to where you have your Python3.5 file and open the folder Scripts, you will find pip.exe. Open powershell and use the cd command to move to the folder containing pip.exe. From here you can use pip install to get modules.
Open Windows Powershell
PS C:Users\you> cd C:\path\to\scripts\folder\containing\pip
PS C:\path\to\scripts\folder\containing\pip> pip install module

Installing PIP on Windows 10 python 3.5


Passar dados da controller para o EJS

Question: Preciso passar os dados obtidos, por uma query no banco de dados, para o meu template EJS com o objetivo de manipular esses valores.
Meu código atual está assim
router.get('/devreport', redirectLogin, (req, res) => {
    //todo trocar o valor para o codigo do sg ao invés de 1. mockado para finalizar
    let cod_sg = 1;
    let heuristic_values = [];
    let selectQuery = `SELECT *
                        FROM formulario
                        WHERE cod_sg = ?`

    let queryValues = [cod_sg];

    execSQLQuery(selectQuery, queryValues)
        .then(dbResponse => {
                heuristic_values.push({
                    values: dbResponse[0].heuristic_responses
                });
            console.log(heuristic_values);
            res.render('../views/devreport.ejs', { heuristic_values });
        })
        .catch(error => {
            console.log(error);
            console.log(req.session.userId);
            res.json('fuck');
        });

    /* req.session.cod_sg = null; */

    res.render('../views/devreport.ejs');
});

Resultado do console.log(heuristic_values);
[ { values: '{"likert-one": "strong_agree", "likert-six": "strong_agree", "likert-ten": "strong_disagree", "likert-two": "agree", "likert-five": "agree", "likert-four": "neutral", "likert-nine": "strong_agree", "likert-eight": "neutral", "likert-seven": "neutral", "likert-three": "strong_disagree", "likert-eleven": "agree", "likert-twelve": "strong_disagree", "likert-fifteen": "neutral", "likert-sixteen": "neutral", "likert-fourteen": "neutral", "likert-thirteen": "neutral", "likert-seventeen": "neutral"}' } ]

Entretanto, quando eu chego na página a qual eu renderizei esses valores, tenho o seguinte retorno
ReferenceError: C:\Users\konex\Videos\ExpertSystem\views\devreport.ejs:14
    12|

    13|

 >> 14|             <%  const responses = heuristic_values %>

    15|

    16|

    17|

heuristic_values is not defined
    at eval (eval at compile (C:\Users\konex\Videos\ExpertSystem\node_modules\ejs\lib\ejs.js:618:12), <anonymous>:11:27)
    at returnedFn (C:\Users\konex\Videos\ExpertSystem\node_modules\ejs\lib\ejs.js:653:17)
    at tryHandleCache (C:\Users\konex\Videos\ExpertSystem\node_modules\ejs\lib\ejs.js:251:36)
    at View.exports.renderFile [as engine] (C:\Users\konex\Videos\ExpertSystem\node_modules\ejs\lib\ejs.js:482:10)
    at View.render (C:\Users\konex\Videos\ExpertSystem\node_modules\express\lib\view.js:135:8)
    at tryRender (C:\Users\konex\Videos\ExpertSystem\node_modules\express\lib\application.js:640:10)
    at Function.render (C:\Users\konex\Videos\ExpertSystem\node_modules\express\lib\application.js:592:3)
    at ServerResponse.render (C:\Users\konex\Videos\ExpertSystem\node_modules\express\lib\response.js:1008:7)
    at router.get (C:\Users\konex\Videos\ExpertSystem\controllers\home_controller.js:248:9)
    at Layer.handle [as handle_request] (C:\Users\konex\Videos\ExpertSystem\node_modules\express\lib\router\layer.js:95:5)

Answer: Você está apenas passando o conteúdo heuristic_values na renderização do ejs e não a variável em si, se você quer acessar uma variável na sua view você deve especificar o seu nome da seguinte maneira:
res.render('../views/devreport.ejs', { 'heuristic_values' : heuristic_values });

Aqui é passado uma variável 'heuristic_values' nomeada.
Quando você passou apenas os o heuristic_values você passou apenas o conteúdo dele, para tirar a prova e entender a forma de passagem de dados na sua view(devreports.ejs) no seu código como está em vez de colocar sua variável coloque um dos valores contidos, como likert-one, você verá o conteúdo ser impresso na tela.
Comment: Cara foi só um exemplo, mas faça o seguinte na linha que você renderiza o ejs,`res.render('../views/devreport.ejs', { heuristic_values });` você altera para  `
res.render('../views/devreport.ejs', { 'heuristic_values' : heuristic_values });`, na sua view você coloca `<%  const responses = heuristic_values %>` agora deve funcionar
Comment: cara, fiz as alterações que você solicitou e continuo com o mesmo problema. Ao colocar <%  const responses = likert-one %>, o erro atualiza para likert is not defined
Comment: pô, men, eu tinha feito exatamente isso ai :(
muito obrigado por tentar me ajudar
Answer: identifiquei o problema. Testei e está OK!
O motivo era: eu estava usando o res.render duas vezes.
Na primeira vez, eu renderizava com a variável heuristic_values.
Na segunda vez, eu renderizava sem. Por conta disso, perdia-se a referência.
res.render('../views/devreport.ejs', { heuristic_values });

res.render('../views/devreport.ejs');

Passar dados da controller para o EJS


innerHTML VS innerTEXT

Question: Qual a diferença entre usar o innerHTML e o innerText em Javascript? Se eu quero mudar o conteúdo do TEXT_NODE, qual devo usar?
Por exemplo:

I also wrote a book! Read it
    here.

Se eu quero mudar o texto do parágrafo acima, eu usaria desta forma:
var p = document.getElementById("p1");
p.innerHTML="Texto Qualquer";

ou desta? :
var p = document.getElementById("p1");
p.innerText="Texto Qualquer";

Tem alguma diferença? Visualmente eu vi que os dois fazem a mesma coisa.
Comment: O problema é que usando um ou outro o link `` vai embora.
Answer: O innerText altera o conteúdo de um elemento de sua página (DOM) com o conteúdo tratado apenas como texto. Por exemplo:
document.getElementById('Teste').innerText = 'teste'

Irá exibir:

Já o innerHTML altera o conteúdo de um elemento com o conteúdo tratado como HTML.
Por exemplo, este código:
document.getElementById('Teste').innerHTML = 'teste'

Será exibido dessa maneira:

Criei um código no jsFiddle para você poder perceber melhor a diferença entre ambos.
https://jsfiddle.net/brunossn/xpvt214o/803018/
Answer: O innerText pode ser entendindo como:

uma propriedade que representa o conteúdo textual "renderizado" de
  um nó e seus descendentes. Usada como getter, retorna de maneira
  aproximada o texto que o usuário obteria caso tivesse selecionado o
  conteúdo e copiado para a área de transferência

Já o innerHTML:

define ou obtém a sintaxe HTML descrevendo os elementos descendentes.

Logo, em palavras simples, o innerText recupera e define o conteúdo da tag como texto simples, enquanto innerHTML recupera e define o conteúdo em formato HTML.
Veja um exemplo onde pegamos o conteúdo HTML da
:

let innerHTML = document.getElementById('innerHTML').innerHTML;
console.log(innerHTML);

Texto Mais texto

Agora veja esse outro exemplo com innerText, onde só pegamos o texto, sem a tag span, diferentemente do primeiro exemplo:

let innerText = document.getElementById('innerText').innerText;
console.log(innerText);

Texto Mais texto

Pegando um gancho no seu exemplo da pergunta, caso queira trocar, por um exemplo, o texto de um link poderia usar o innerText. Veja:

var p = document.getElementById("link");
p.innerText="Texto Qualquer";

I also wrote a book! Read it
    here.

Caso você quisesse trocar o conteúdo HTML de uma div, ou até mesmo trocar o link de um certo elemento o poderia fazer com o innerHTML.

var p = document.getElementById("p1");
p.innerHTML='Trocamos o link';

I also wrote a book! Read it
    .

Referências:

MDN innerText
MDN innerHTML
Answer: O innerText funciona de forma semelhante ao textContent. O innerHTML pode adicionar ou pegar elementos HTML, já com o innerText isso não é possivel, ele pode apenas atribuir um texto ou pegar o texto de determinado elemento.
Answer: Neste caso é possível fazer a junção de dois parágrafos, usando o innertext ou o iner HTML? Eu estou tentanto fazer isso e não  estou conseguindo.
function juntarMostrar() {
    let texto = document.getElementById("paragrafo1").innerHTML;

    let texto2 = document.getElementsByClassName("area1")[0].innerHTML;

    let juntar = document.querySelectorAll('section'). innerHTML;

    juntar.innerHTML = `${('paragrafo1')} + ${("area1")[0]}`;

    }

Comment: Isto não responde realmente à pergunta. Se você tiver uma pergunta diferente, pode fazê-la clicando em [Fazer pergunta](https://pt.stackoverflow.com/questions/ask). Você também pode [adicionar uma gratificação](https://pt.stackoverflow.com/help/privileges/set-bounties) para chamar mais atenção a esta pergunta quando tiver [pontos de reputação](https://pt.stackoverflow.com/help/whats-reputation) suficientes. - [Da Revisão](/review/late-answers/380249)

innerHTML VS innerTEXT


How can I learn timing from a guitar tab?

Question: When playing guitar/bass from tabs, I find that I can learn the fingering easily, but the timing is often wrong when I play with a backing track. I'm fairly noobish to music notation/tablature, but I have been playing for a long time. Simple rhythm suffices for a chord chart, but not so much when it comes to a tab. The problem is even worse with bass tabs, since it can be challenging to even hear the bass part on most tracks without an equalizer and subwoofer, which I don't have easy access to.
Is there any way besides playing with a track to determine timing from a guitar/bass tab?
Answer: Tab notation does not include any timing information -- the closest you get is bar lines, which at least helps you orientate yourself.
Some books present tab alongside a traditional musical score, so you can get pitch, timing and phrasing from the stave, and choice of string/fret from the tab. The notes on the tabs are lined up with the notes on the stave.
Don't think of a tab as a full specification of what to play -- because it isn't. Think "I know how this is meant to sound; the tab tells me where to put my fingers to get each note".
Comment: I'd say that `tab notation does not include any timing information` is false unless we're talking about *bad* tab notation written by people who don't know what they're doing.  Admittedly there's a lot of tablature like that out there, but ideally each column of a tab should represent a specific subset of the beat.  It's certainly not as expressive as a traditional score though.
Comment: @MatthewRead: but it's true in the sense that there's no information about how *long* to play each note for.
Comment: @naught101 Again, only in bad tabs ;)
Comment: @MatthewRead: ok, I've obviously never seen any good tabs. Are there any examples on the 'web?
Comment: @naught101 I don't know of an example offhand, but I've seen tabs that used `----1~~~` (or similar) to indicate holding a note.
Comment: @naught101  Troy Stetina's tabs are always good tabs that almost perfectly equate to traditional sheet music: https://ec-assets.sheetmusicplus.com/product/Look-Inside/large/2970340_04.jpg
Comment: @MatthewRead same comment ^.
Answer: Tab, in my opinion, is great for getting the general pattern or notes of a song, but pretty poor at conveying real musical information. It would be pretty difficult to sight read a song notated in tab that you had never heard before, as tab does not provide note lengths and expression symbols in the same way that notation does. I have always used tab to learn the progression of notes, and then set them in place by ear.
That being said, tab can provide some timing aid. Usually, the dashes that make up the stave can help you to identify what beats, semi beats, or even quarter beats look like in the context of the bar.
Using a very simple example to illustrate, in 4/4 time,
|0-0-0-0-|
Indicates crotchets, while
|0-0-0-0-0-0-0-0-|

Indicates quavers. So  for a bar with 16 dashes, a note with 2 dashes is a quaver, and 4 dashes is a crotchet.
This is not very easy and quick to work out when sight reading, hence why tab is better for reference. It can provide a basic idea however.
Also, as slim said, many music books provide tab beneath the score, so you can see the nature of the note directly above the tab note in order to get the timing.
I've probably explained this in the longest and most complicated way possible, sorry about that. Hope its given some help though.
Comment: Tabs _can_ show the exact timing but in my experience rarely do... on the most common websites I find that even when I think I know a song well, the tab doesn't make sense to begin with until I figure out which notes match each phrase in the song.
Answer: Tabs are usually done in parallel with "real" scores containing the detailed timing information.
Where a tab is supposed to be self-sufficient, it has to contain quite more information than a "standard" tab.
Take a look at the LilyPond documentation for \tabFullNotation: the text a bit above shows how things look with a standard score/tab combination instead.
Answer: Where they provide timing information it is usually limited to a bpm number and sometimes an indication as to whether it is 4/4 3/4 etc so an option if you don't have the track to listen to is to use a metronome.
It will at least give you consistent bar and beat lengths, so you can practice effectively.
Answer: You might wanna check out you-tab.com, they have tabs that are synced to the original music, so you can learn the timing as you play along.
They just went up so they aren't many songs on it yet. But you can see how it works here.
Answer: There is no rhythm/timing information in the vast majority of tab.  Some try to give clues with the spacing between "notes" but it doesn't really work that well.
When you're working with tab, it's expected that you will play along with a recording of some sort to get the timing right.
Answer: While tab is a good way to convey the specific notes played in a passage it is not great at getting timing across and as such should be taken with a large grain of salt. Some tab conventions are better than others but if you are trying to learn a specif passage you still need to listen to  the original and get to know it to work out which notes are crucial and which are just accents.


Key based access control for private files

Question: I'm building a site that provides paid video content, for embedding in customer's own sites. I'm successfully controlling access to the nodes that contain the video content based on purchasable user roles.
Now I need to provide users with an embed code which ideally would only work from their domain. For now I'd be happy just to be able to limit it to specific users.
I have installed the key_auth and restui modules, and I have enabled the 'file' REST resource. I can now access information *about* the file as an anonymous user with the paying subscriber's api key in the query. However I can't access the actual file.
The info I get back is below.
<code>{"fid":[{"value":3}],"uuid":[{"value":"5655ecda-b421-4ab8-aa92-d43c6c0fbfdf"}],"langcode":[{"value":"en"}],"uid":[{"target_id":1,"target_type":"user","target_uuid":"58d862eb-86e9-4ec6-bb33-89bda5c1767a","url":"\/user\/1"}],"filename":[{"value":"file_example_MP4_480_1_5MG.mp4"}],"uri":[{"value":"private:\/\/2022-04\/file_example_MP4_480_1_5MG.mp4","url":"\/system\/files\/2022-04\/file_example_MP4_480_1_5MG.mp4"}],"filemime":[{"value":"video\/mp4"}],"filesize":[{"value":1570024}],"status":[{"value":true}],"created":[{"value":"2022-04-16T15:52:39+00:00","format":"Y-m-d\\TH:i:sP"}],"changed":[{"value":"2022-04-16T15:52:43+00:00","format":"Y-m-d\\TH:i:sP"}]}
</code>

How can I get access to the actual video in this way?
Comment: If the video is going to be embedded on the client site, anyone viewing the video must necessarily have access. You can probably prevent it from being embedded on unauthorised sites, since most browsers will respect content security policy headers, but if the video is being served as a file you can't prevent it being copied and then served on other platforms.
Comment: @AlfredArmstrong Yes, having gone to the lengths described in my answer this became apparent. For this reason I'm now looking at using a video hosting platform that provides protection against this, but its been an interesting journey.
Comment: I take that by *get access to the actual video* you mean getting the video URL. Since you are using a REST API, I also take the request doesn't come from the Drupal site. The video relative path is given in `uri.url`. To that, you need to add the site URL. For example, if that is `http://example.com/drupal`, that video URL would be `http://example.com/drupal/system/files/2022-04/file_example_MP4_480_1_5MG.mp4`. Since the code is making a REST request, it knows the URL to which the request is sent, which also means it can get the missing part in the video path to make it a complete URL.
Comment: Or are you asking *On the Drupal side, how do I alter the values returned from the REST API to include the absolute video URL?*
Comment: Alternatively, *get access to the actual video* just means that accessing the video using its URL from outside Drupal returns a 403 error and you want to know how to avoid that. Since the video is saved as private file, on Drupal side the access to those files is controlled by [`hook_file_download()`](https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21File%21file.api.php/function/hook_file_download/9.3.x). How an implementation of that hook would understand the file is requested by a *client* that uses REST API to access the information is the "real" question, in this case.
Comment: @apaderno Thanks for your efforts. What I was trying to do is create a rest endpoint that simply returns the file. That would either result in a download if the GET request is made through a browser, or in the file being displayed in a page if used in a src attribute.
Answer: I had to write a custom module with the following structure:
<code>
video_resource.info.yml
src/Plugin/Deriver/VideoDeriver.php
src/Plugin/rest/resource/VideoResource.php
</code>

The rest resource and entity deriver are cut-down copies of the EntityResource and EntityDeriver:

<code>\Drupal\rest\Plugin\rest\resource\EntityResource
\Drupal\rest\Plugin\Deriver\EntityDeriver
</code>

These classes together create a rest resource for every entity type. I set mine to only create a rest resource for the 'File' entity type, with the following code in its get() function:

<code>$filepath = $entity->getFileUri();
$response = new BinaryFileResponse($filepath);
return $response;
</code>


The change of variable.

Question: I have a quetion to ask and i wish to find her an answer for it, so i would like to know if the change of variables must to be a one to one transformation, if that the case i would like to know why. Thank you.
Answer: I am not sure if this is what you are interested in, but if you want to know whether the equality$$\int_{g(a)}^{g(b)}f(x)\,\mathrm dx=\int_a^bf\bigl(g(x)\bigr)g'(x)\,\mathrm dx\tag1$$depends upon $g$ being injective, then answer is negative. The equality $(1)$ holds as long as:

$f$ is continuous;
$g$ is differentiable;
$g'$ is continuous;
$g\bigl([a,b]\bigr)\subset D_f$.

Actually, $(1)$ follows from the chain rule and the fundamental theorem of Calculus.
Comment: so in general the transformation g mustn't be bijective?
Comment: @AmineElBouzidi I would rather say that it doesn't have to be injective.
Comment: ok thank you sir for your answer.

The change of variable.


User Login Block does nothing

Question: The core user login block does not appear to work.
I have it placed in the Header region (Omega theme if that helps), with the following overrides:
function mytheme_theme(&$existing, $type, $theme, $path) {
   $hooks['user_login_block'] = array(
     'template' => 'templates/user-login-block',
     'render element' => 'form',
   );
   return $hooks;
 }

This lets me use my own tpl file for the login block.
function mytheme_preprocess_user_login_block(&$vars) {
  $vars['name'] = render($vars['form']['name']);
  $vars['pass'] = render($vars['form']['pass']);
  $vars['submit'] = render($vars['form']['actions']['submit']);
  $vars['rendered'] = drupal_render_children($vars['form']);
}

This lets me pass new variables..
Then in the tpl file:

    <?php print $name; ?>
    <?php print $pass; ?>
    <?php print $submit; ?>

    Create an Account | Forgot Password

Except when I login, the page refreshes, and nothing happens. User is not logged in, no error. When I use correct or incorrect credentials, nothing happens.
I used this same approach on a Drupal 6 site and it worked fine. Where am I going wrong?
I disabled Login Destination and Login Toboggan while debugging, no change.
Answer: You should print hidden elements:

    <?php print $name; ?>
    <?php print $pass; ?>
    <?php print $submit; ?>
    <?php print $rendered; // HERE HIDDEN ELEMENTS ?>

    Create an Account | Forgot Password

User Login Block does nothing


What can we say about $\sum x_n$ if $\lim n x_n =0$?

Question: I proved that if $(x_n)$ is a decreasing sequence of non-negative real numbers such that $\sum x_n$ converges, then $\lim nx_n=0$.
I ask about the other direction. If $(x_n)$ is any sequence of real numbers such that $\lim nx_n=0$ it is true that $\sum x_n$ converges?
What if $(x_n)$ is also a decreasing sequence of non-negative real numbers?
It seems to me that the answer to both of these questions is no! So I searched counter-examples. Unfortunatelly I couldn't find any. Neither could I prove these statements. Can someone help me? Thanks!
Comment: $x_n = \frac{1}{n \log n}$ (or shift it left if you insist on the sequence starting at $n=0$ or at $n=1$).
Comment: Wow! That just solved it! Don't you want to post this as an answer so I can accept it?
Answer: No to both: $x_n = \frac{1}{n \log n}$ is a counterexample to both.  (To get around the fact $x_1$ is not defined, you can make a definition by cases to set e.g. $x_1 = 10$ and $x_n = \frac{1}{n \log n}$ otherwise.)


$ker(T)^{\bot} = \overline{im(T^*)}$ if $T$ is a linear operator between Hilbert spaces

Question: Let $T$ be a linear operator.
For any underlying normed spaces it holds that
$$ker(T)^{\bot} \subset \overline{im(T^*)},$$
but if they are both Hilbert spaces we get
$$ker(T)^{\bot} = \overline{im(T^*)}.$$
Now my question is:
How to prove the inclusion from right to left?
Comment: You need inner product on the space for orthogonality and adjoint.
Comment: @Berci The adjoint operator on a normed space is defined with the help of the duality pairing, so no inner product needed. This coincides with the inner product when Hilbert spaces are considered.
Comment: Well, yes, but then both sides live in the dual space.
Answer: For a Hilbert space, and any vectors $x,y$, $$\langle T^*x,y\rangle = \langle x,Ty\rangle$$ Hence $x\in(im T)^\perp\iff x\in\ker T^*$, i.e., $(im T)^\perp=\ker T^*$. Taking a second perp gives $$(\ker T^*)^\perp=(im T)^{\perp\perp}=\overline{im T}$$  Apply this identity with $T^*$ instead of $T$ to get $$(\ker T)^\perp=\overline{im T^*}$$
Edit: This works in Hilbert spaces but not Banach spaces because $T^{**}=T$ is valid in the former but not the latter in general.
Edit 2: Direct proof. Let $x\in\overline{im(T^*)}$ and $y\in\ker T$, then there are vectors $z_n$ such that $T^*z_n\to x$, and $Ty=0$. So $$\langle y,x\rangle=\lim_{n\to\infty}\langle y,T^*z_n\rangle=\lim_{n\to\infty}\langle Ty,z_n\rangle=0$$


How to create an html table to display an array of objects with not the same fields?

Question: I have an array of objects in which the fields may differ slightly.
when I build a table due to the fact that I do not have the same fields in objects, my table shrinks
how can I make a table so that I have an empty line where there are no fields.
Dear colleagues, please tell me how to correctly complete this task.
you can use only pure javascript
const data = [
      {
      "#": 1,
    "First Name": "Wilhelm Conrad",
    "Last Name": "Röntgen",
    "Born Location": "Lennep",
    "Died Location": "Munich, Germany",
    "Gender": "male",
    "Prizes": "yes"
    },
      {
        "#": 1,
    "First Name": "Wilhelm Conrad",
    "Last Name": "Röntgen",
    "Born Location": "Lennep",
    "Gender": "male",
    "Prizes": "yes"
    },
      {
        "#": 1,
    "First Name": "Wilhelm Conrad",
    "Last Name": "Röntgen",
    "Born Location": "Lennep",
    "Died Location": "Munich, Germany",
    "Gender": "male",
    "Prizes": "yes"
    },
      {
        "#": 1,
    "First Name": "Wilhelm Conrad",
    "Last Name": "Röntgen",
    "Born Location": "Lennep",
    "Gender": "male",
    "Prizes": "yes"
    },
      {
        "#": 1,
    "First Name": "Wilhelm Conrad",
    "Last Name": "Röntgen",
    "Born Location": "Lennep",
    "Gender": "male",
    "Prizes": "yes"
    }
]

const keys = Object.keys(data[0])

let tab = document.createElement('table');

const buildTableHeader = () => {
    let thead = document.createElement('thead');
    let tr = document.createElement('tr');

    for (const key of keys) {
        const th = document.createElement("th");
        th.appendChild(document.createTextNode(key));
        tr.appendChild(th);
    }
    thead.appendChild(tr)
    tab.appendChild(thead);

    document.body.appendChild(tab)
}

let tb = document.createElement('tbody');

const buildTableBody = () => {
    for (let a of data) {
        let tr = document.createElement('tr');
        for (let key in a) {
            let td = document.createElement('td');
            let tn = document.createTextNode(a[key]);
            td.appendChild(tn);
            tr.appendChild(td);
        }
        tb.appendChild(tr);
    }
    tab.appendChild(tb);
    document.body.appendChild(tab);
}

buildTableHeader()
buildTableBody()

Answer: const buildTableBody = () => {
    for (let a of data) {
        let tr = document.createElement('tr');
        for(let key of keys) {
            let td = document.createElement('td');
            let tn = document.createTextNode(a[key]);
            td.appendChild(tn);
            tr.appendChild(td);
        }
        tb.appendChild(tr);
    }
    tab.appendChild(tb);
    document.body.appendChild(tab);
}

Change for (let key in a) to for(let key of keys)
Answer: You're trying to iterate data when some properties don't exist. If you iterate your keys instead you can check if whatever key you have is in your data object.
If they don't just create an empty tn.
const buildTableBody = () => {
    for (let a of data) {
        let tr = document.createElement('tr');
        keys.forEach((key) => {
            let td = document.createElement('td');
            let tn = key in a ? document.createTextNode(a[key]) : document.createTextNode('');
            td.appendChild(tn);
            tr.appendChild(td);
        });
        tb.appendChild(tr);
    }
    tab.appendChild(tb);
    document.body.appendChild(tab);
}


I can't access a provided variable in rule action

Question: In a rule I have 2 actions, the first one provides a variable (my_var_name). But in the second action this var is not shown as available.

I can't figure out what the problem is.
Answer: I was having this problem with a different module with Rules.  I believe the data types are conflicting.  node:author:name is a string, while the value have calculated is an integer, a decimal or a float.
My Problem:
User Field - Voting Currency (set as integer)
Event:

Vote was cast on entity

Action:

Query database for the value of the vote cast
Calculate the value to add/subtract from the Voting Currency field
Set the new value of Voting Currency field.

I discovered the vote was a decimal data type.
I removed the Voting Currency integer field with a Voting Currency decimal field and everything worked!
Comment: It was the same problem in my case. It was a conflict between an integer and a decimal number
Comment: Actually I attached an image to a Drupal issue queue of this http://drupal.org/node/1882086#comment-6911124


How to override correctly OnFormClosing() method in C#

Question: I have a form which has a button called "Search". When I click it, another form is opened to search an item. When the user clicks on the X in this second form to close it, I don't really want it closed, I just want to make it no visible (by secondForm.visible = false).
I've found that  what I need is just to override the OnFormClosing() method and I've done in the form class but it isn't executed at all. I know that it isn't executed because when the next time that "Search" button is clicked (instead of do new SecondForm() it tries just to do secondForm.visible = true) I get an exception which says that I can't work on an deleted object (secondForm) or something like that. So the second form has just been closed instead of no visible.
At this point I'm starting to think that which I need is to assign, by some way (which I obviusly don't know), this new override method to the button X.
EDIT:
This is my overrided method in the second from class:
protected override void OnFormClosing(FormClosingEventArgs e)
    {
        base.OnFormClosing(e);

        if (e.CloseReason == CloseReason.WindowsShutDown) return;

        this.Visible = false;
    }

This is what I do when button "Search" is clicked:
private void btnSearch_Click(object sender, EventArgs e)
    {
        if (subFormCreated)
            subFormSearch.Visible = true;
        else
            initializeSubFormSearch();
    }

    private void initializeSubFormSearch()
    {
        subFormSearch = new SubForm(listaPersonas, actualMostrado);
        subFormSearch.Show();
        subFormCreated = true;
    }

Finally, the exception what I get is ObjectDisposedException. The exact message is something like (I don't know if I'm traslating it correctly) ObjectDisposedException was unhandled. Cannot get access to the  deleted object. Name of the object: SubForm.
Comment: Please show the exact code and the exact exception message.
Answer: You didn't stop it from closing, you forgot to set the e.Cancel property to true.  Correct code is:
protected override void OnFormClosing(FormClosingEventArgs e) {
    if (e.CloseReason != CloseReason.WindowsShutDown) {
        this.Visible = false;
        e.Cancel = true;
    }
    base.OnFormClosing(e);
}

With the additional details that you never want to avoid calling base.OnFormClosing() when the operating system is shutting down and you call it after your customization so that the client program can overrule your decision if needed.
Make it even more resilient by subscribing the FormClosed event in your main class so you know that the subFormCreated variable needs to be set to false.  Note that you don't need that variable, you could just set the subFormSearch variable back to null.  So, roughly:
private void displaySubFormSearch() {
    if (subFormSearch != null) {
        subFormSearch.WindowState = WindowState.Normal;
    }
    else {
        subFormSearch = new SubForm(listaPersonas, actualMostrado);
        subFormSearch.FormClosed += delegate { subFormSearch = null; };
    }
    subFormSearch.Show();
}

With the additional detail that you ensure that you restore the window in case the user minimized it previously.  Now it is solid.  You may need properties to pass updated listaPersonas and actualMostrado, it isn't clear.
Answer: You really don't need to override anything here. Just handle the FormClosing event and set e.Cancel = True. Plus make your form invisible in the same handler. In the first form, make a class level object of your second form and call its ShowDialog() upon Search button's Click. Lastly make sure your OK and Cancel buttons have their DailogResult property set appropriately. Roughly it would look like this:
class Form1
{
     private Form2 dlg;

    private void btnSearch_Click(object sender, EventArgs e)
    {
        if(dlg==null) dlg = new Form2();
        dlg.ShowDialog(this);
    }
}

class Form2
{
    private void Form2_FormClosing(object sender, FormClosingEventArgs e)
    {
        e.Cancel = true;
        this.Hide();
    }
}

Comment: I understood it :D but anyway, this solution means that always I run the main form, I will be creating the second form even if I don't need it, right? So I think that I will be assuming a consumption of unnecessary resources. What about that? Does it worth it?
Comment: @Drumnbass: I really won't bother about saving those few KBs of memory given the excessive amount of RAM we have in today's machines. However, I'm making changes to the above code to address this.
Comment: Sure, I supposed that just were a few KBs of memory but notice that I'm still a newbie programming (just a student) and I would start to get good practices since now ;)


Loading all env variables with processbuilder

Question: I want to load the variables I have defined in the .bashrc file prior to the execution of a script from a java code. The script is executed via the ProcessBuilder. On the web, I see that the command array should be started with bash -c as below:
String[] cmdline = {"/bin/bash", "-c", "python", "/home/mahmood/temp.py"};
final ProcessBuilder pb = new ProcessBuilder(cmdline);
pb.command(cmdline);
pb.redirectOutput(Redirect.INHERIT);
final Process p = pb.start();
int exitCode = p.waitFor();
if (exitCode != 0) {
   throw new IOException("... python failed :( \n");
}

Indeed the waitFor never returns! If I drop the bash -c, then the exitCode will be non-zero since the variables have not been loaded.
Please note that there is not a single variable in the .bashrc. Can I fix the problem with ProcessBuilder or there is a better option for that?
Answer: Bash has to be invoked as an interactive shell to read and execute commands from ~/.bashrc. When running bash -c command you're executing command in a non-interactive shell. To run interactively (and read .bashrc), just add -i:
String[] cmdline = {"/bin/bash", "-ic", "python /home/mahmood/temp.py"};

Also, note that the command string (python /path/to/file) has to be specified as a single word (notice single quotes when invoked from shell):
bash -ic 'python /home/mahmood/temp.py'

or otherwise, bash will execute python (the first word) interactively (not running the script) -- and that's the reason your waitFor never returns.

Since running an interactive shell just to load some environment variables from .bashrc might be an overkill, you could extract the variables of interest in a separate file, for example:
export var1=val1
export var2='val 2'
...

and then source that file just before running your python script:
String[] cmdline = {"/bin/bash", "-c", ". /path/to/envfile; python /home/mahmood/temp.py"};

Comment: The difference between `-ic` and `-c 'source ~/.bashrc; python ...'` (besides the fact you're not running interactive shell with second expression) is that your `.bashrc` will probably prematurely exit *if not* run in an interactive shell -- check the beginning of your `.bashrc` and look for something like: `[ -z "$PS1" ] && return`. If you modify your `.bashrc` not to exit when sourced in non-interactive shell, for example just to hold env vars, then you're approaching the second method from the answer.
Comment: Thanks for that. Actually I learned many things about shell from this Q&A which I have't noticed til now!
Comment: Although the first method ran the script, I see that after the execution of `pb.start()` these lines are printed on the output window `bash: cannot set terminal process group (1615): Inappropriate ioctl for device` and `bash: no job control in this shell`
Comment: Also, what is the difference between using `-ic` and `"-c". "source ~/.bashrc; python..."`?
Comment: You're seeing that message because you're running Bash as [interactive shell](https://www.gnu.org/software/bash/manual/bash.html#Interactive-Shells), but with no terminal attached (because you run it from Java). Interactive shell is a little bit "heavier" to run (see [here](https://www.gnu.org/software/bash/manual/bash.html#Interactive-Shell-Behavior)), that's why the second method might be preferred. In the second method, Bash is run in non-interactive mode, but before executing Python script, we first source our environment variables (`-ic` is just as short way of writing `-i -c`).
Answer: One another approach is to add the environment variables manually as part of ProcessBuilder environment.
For example, assuming we have stored the required environment variables inside a string array envVars, following snippet will add the environment variables as part of ProcessBuilder's environment:
ProcessBuilder pb = new ProcessBuilder(Arrays.asList("python", "temp.py"));
pb.directory(new File("/home/mahmood/"));
Map<String, String> env = pb.environment();
Map<String, String> envToReproduce = new HashMap<String, String>();
for(int x=0;x<envVars.length;x++){
    System.out.println(envVars[x]);
    String[] tempEnv = envVars[x].split("=");
    if(tempEnv.length>1){
        String envVal = tempEnv[1].replaceAll("'","");
        envToReproduce.put(tempEnv[0], envVal);
        env.put(tempEnv[0], envVal);
    }
}

Comment: I see that the `pb.environment()` returns something different than my bashrc. I am debugging with Netbeans, so I think when Netbeans executes, it doesn't read the bashrc and therefore user defined variables are ignored. That means, with Netbeans it is much harder than what I thought! To test the proposed idea, I have to run and debug from the terminal. Thanks.


hook_menu not working with alias

Question: I have a hook_menu:
$items['node/%/tokens/%api_token'] = array(
    'title' => 'View an API Call',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('api_token_edit', 1, 3),
    'access arguments' => array('edit own profile'),
    'type' => MENU_LOCAL_TASK,
);

When visiting url: node/1229/tokens/1, it works as expected.
When visiting the friendly alias: mypage/tokens/1, it gives me a 404.
Why is this? I thought hook_menu used the internal arguments?
Answer: That behavior is not inclued in core. You can try this two modules:

Sub-pathauto (Sub-path URL Aliases): The Drupal Path module matches only full URLs when creating SEO-friendly aliases. This module extends that behavior by also matching known sub-paths and replacing them with their respective alias.
Extended Path Aliases: SImilar to previous module, but includes more functionlaity. The drawback is that it needs core patching (adding a line to nclude/path.inc) or installing PECL runkit library.
Comment: Awesome! I actually have Sub-pathauto enabled already (but only 1 deep). It didn't occur to me that could be an issue. I made it 2 deep and eureka! :) Thank you for this, it's been bugging me for hours.

hook_menu not working with alias


Java modulo operator and GCD

Question: Why does this code give me an answer of 25?
public int findGcd() {
    int num = this.num;
    int den = this.den;

    while (den != 0) {
        int t = den;
        den = num % den;
        num = t;
    }

    return num;
}

This is the main method:
public class FractionTest {
    public static void main(String args[]) {
        Fraction f = new Fraction();
        f.num = 25;
        f.den = 100;
        f.findGcd();
    }
}

Can anyone provide me a complete process of how all the program goes or run?
Comment: Well, what answer were you expecting?
Comment: I was expecting a 4 or 0 since 25/100 is 4 while 25%100 = 4 , sorry I am just really confused can anyone clear things up
Comment: 25/100 is 0, 25%100 is 25, 100/25 is 4 and 100%25 is 0.
Answer: Because gcd(25, 100) = 25 probably
Comment: As this is probably a follow up to this [question](http://stackoverflow.com/questions/6882618/simplifying-fractions-with-java): Indeed 25 is the GCD. Now to simplify the fraction divide both the numerator and denominator by 25 and you get 1/4 instead of 25/100. Which is correct.
Answer: It is called the Euclidean Algorithm.
Comment: I know it's the Euclidean algorithm , I used the pseudocde there for my code, all I want is to have a complete explanation of how the program goes since I've been having a hard time with the modulo operator
Answer: Here's a quick calculation you can also do by debugging your program to see how it works...
http://gcd.awardspace.com/?num1=25&num2=100&OG=on&SC=on&RF=on&RC=on
The link shows you how the calculation is done, if you can't see it yet. Hope this helps.
Answer: The while loop work like this
den!=0 100 != 0
inside loop
t = 25 (den)
0 = 25 % 100
num = 25 (t)
return 25 (num)
So the result is 25

Java modulo operator and GCD


Segmentation fault em C: Estrutura de Adjacência representando grafo

Question: Preciso criar um programa para ler um grafo e representar em uma estrutura de adjacência, entretanto, meu compilador está acusando segmentation fault e não consigo descobrir o que pode estar causando isso. Pode me ajudar?
#include <stdio.h>
#include <stdlib.h>

FILE *ent;
FILE *saida;
int V, E;
int **matriz;
struct adj{
    int w, v;
    struct adj *prox;
};
typedef
struct adj grafo;
grafo **G;

void Estrutura (int V);
void M_Adj (int **matriz, int V);
void ZerarMatriz (int **matriz);
void printMatriz (int **matriz, int V);
void printEstrutura (grafo **G, int V);

int main()//(int argc, char *argv[])
    {
    //declarações e abertura de arquivos
    ent = fopen("ent.txt", "r");
    saida = fopen("sai.txt", "w");

    //ler arquivo de entrada e declarações
    int i,v, w, Vi;
    fscanf(ent, "%d %d", &V, &E);

    //alocar matriz
    matriz = malloc(V * sizeof(int*));
    for (i = 0; i < V; i++)
        matriz[i] = (int*)malloc(V * sizeof(int));

    //alocar vetor cabeça do grafo
    G = (grafo **) malloc(sizeof(V*sizeof(grafo)));

    //int matriz[V][V];
    fprintf (saida, "Arquivo de entrada \n \n");
    fprintf(saida, "%d %d \n", V, E);
    for(i = 0; i < V; i++){
        fscanf(ent, "%d", &v);
        fprintf(saida, "%d ", v);
        fscanf(ent, "%d", &w);
        if (w != 0) fscanf(ent, "%d", &Vi);
        while (w != 0){
        fprintf(saida,"%d %d ", w, Vi);
        fscanf(ent, "%d", &w);
        if (w != 0) fscanf(ent, "%d", &Vi);
    }
    fprintf(saida, "\n");
    }
    ZerarMatriz(matriz);
    M_Adj(matriz, V);
    Estrutura(V);
    fclose(ent);
    fclose(saida);
    free(matriz);
    return 0;
}

void Estrutura (int V){
    ent = fopen("ent.txt", "r");
    int i, Vi, w, v, VV, EE;
    fscanf(ent, "%d", &VV);
    fscanf(ent, "%d", &EE);
    printf("Tam: %d %d \n", VV, EE);
    for (i = 0; i < V; i++)
        (G[i]->prox) = NULL; -- O ERRO É ACUSADO AQUI
    struct adj *aux = malloc(sizeof(struct adj));
    for(i = 0; i < V; i++){
        fscanf(ent, "%d %d", &Vi, &w);
        printf("\n %d %d \n", Vi,w);
        while (w != 0){
            fscanf(ent, "%d", &v);
            aux->prox = NULL;
            aux->v = v;
            aux->w = w;
            if (&(G[i]->prox) == NULL){  -- SE EU NÃO COLOCAR O & COMERCIAL TAMBÉM É ACUSADO AQUI
                G[i]->prox = aux;}
            else
            {
                grafo *aux2 = G[i];
                while(&(aux2->prox) != NULL) -- SE EU NÃO COLOCAR O & COMERCIAL TAMBÉM É ACUSADO AQUI
                    aux2 = (grafo *) (aux2->prox); -- ISSO TAMBÉM NÃO PARECE FUNCIONAR
                (aux2->prox) = aux;
                aux2 = NULL;
            }
            fscanf(ent, "%d", &w);
        }
    }
    aux = NULL;
    fprintf(saida," \n Estrutura de Adjacência: \n");
    printEstrutura(G, V);
}

Eu sei que está um pouco redundante, mas é para fins didáticos. Obrigado.
------------------------------------ Atualização ----------------------------
Victor, muito obrigado pela resposta mas mesmo com essas alterações ainda restaram alguns problemas, por isso, resolvi adicionar os novos vértices no inicio da lista, com as alterações o código ficou assim:
void Estrutura (int V){
    ent = fopen("ent.txt", "r");
    int i, Vi, w, v, VV, EE;
    fscanf(ent, "%d", &VV);
    fscanf(ent, "%d", &EE);
    printf("Tam: %d %d \n", VV, EE);
    struct adj *aux = malloc(sizeof(struct adj));
    for(i = 0; i < V; i++){
        fscanf(ent, "%d %d", &Vi, &w);
        printf("\n %d %d ", Vi,w);
        while (w != 0){
            fscanf(ent, "%d", &v);
            printf(" %d %d ", w, v);
            aux->prox = NULL;
            aux->v = v;
            aux->w = w;
            if (G[i] == NULL){
                G[i] = aux;
            }
            else{
                aux->prox = G[i];
                G[i] = aux;
            }
            fscanf(ent, "%d", &w);
        }
    }
    aux = NULL;
    printEstrutura(G, V);
}

void printEstrutura (grafo **G, int V){
    int i;
    struct adj *aux;
    fprintf(saida, "/n PRINTANDO ESTRUTURA :DDDDD");
    for(i = 0; i < V; i++){
        aux = G[i];
        while (aux != NULL){
             fprintf(saida, "%d %d", aux->w, aux->v);
             aux = aux->prox;
        }
    }
}

Mas com as alterações, meu código fica em loop na função print. Estou há tempos trabalhando direito e isso está atrapalhando bastante meu rendimento, vou dormir um pouco pra evitar deslizes como o últimos. Obrigado.
Comment: Atualizei a minha resposta.
Answer: Acho que o seu principal problema está aqui:
G = (grafo **) malloc(sizeof(V*sizeof(grafo)));

Você errou os parênteses! E como resultado vai alocar uma quantidade de memória bem menor que a que deveria, o que vai causar falha de segmentação quando você acessar o ponteiro alguma posição além da que foi alocada.
O que você queria é isso daqui:
G = (grafo **) malloc(V * sizeof(grafo*));

No entanto, você deve ter sempre em mente que isso vai criar um array de ponteiros para adjacências e não um array de adjacências.
Atenção, neste momento esta região da memória conterá lixo, o que significa que você terá um array de ponteiros inválidos. Então, é uma boa ideia inicializar o array:
G = (grafo **) malloc(V * sizeof(grafo*));
for (i = 0; i < V; i++) {
    G[i] = NULL;
}

Mais para frente, isso vai dar errado:
for (i = 0; i < V; i++)
    (G[i]->prox) = NULL; // O ERRO É ACUSADO AQUI

Pois G[i] é nulo! E se você não tiver colocado aquele laço for que eu sugeri antes, então será ainda pior, pois G[i] será um ponteiro preenchido com lixo. A solução é simplesmente retirar este laço do programa, você não precisa dele.
No laço for grande da função Estrutura, você não define nada em nenhuma das posições do array G. Portanto sempre que você tentar acessar G[i], alguma coisa ruim vai acontecer. Em algum lugar você deveria fazer isso:
G[i] = alguma_coisa;

Por fim, isso não é o que você quer:
if (&(G[i]->prox) == NULL)
...
while(&(aux2->prox) != NULL)

Pois, se G[i] for um ponteiro válido, então &(G[i]->prox) nunca vai ser nulo, pois o ponteiro sempre terá um endereço neste caso. E se G[i] for um ponteiro inválido, isso vai dar falha de segmentação. O mesmo se aplica para aux2. Portanto, com o &, ou ocorre uma falha de segmentação, ou então o if nunca vai entrar e o while nunca vai sair.
O que você quer não é saber se o endereço do ponteiro é nulo e sim se o próprio ponteiro é nulo. Então, retire o &.
Aliás, o endereço de qualquer variável no programa nunca vai ser nulo, uma vez que qualquer variável em que você pode usar o operador de endereço existe, e se ela existe, então ela está em algum endereço em algum lugar de memória. Se não existir, você vai ter uma falha de segmentação ao tentar acessar uma variável que não existe. Por isso, o operador & nunca vai te dar nulo como resposta*.
*: Exceto se você estiver programando alguma parte crítica do kernel do sistema operacional ou da BIOS que precise manipular algum valor na posição zero da memória, o que provavelmente você nunca vai fazer.

ATUALIZAÇÃO:
Não vejo nada de errado no código da sua atualização. Certifique-se que o array G foi devidamente inicializado com NULL em todas as posições. Se não for isso, sugiro colocar alguns printf sempre que adicionar alguma adjacência ao grafo e então tentar encontrar aonde e como ele pode gerar alguma coisa incorreta no grafo que faça o printEstrutura entrar em loop infinito.
Além disso, no seu novo código dá para simplificar isso:
        aux->prox = NULL;
        aux->v = v;
        aux->w = w;
        if (G[i] == NULL){
            G[i] = aux;
        }
        else{
            aux->prox = G[i];
            G[i] = aux;
        }

E transformar nisso:
        aux->prox = G[i];
        aux->v = v;
        aux->w = w;
        G[i] = aux;

Answer: Victor, eu fui meio bobo ao desenvolver o código, sempre que alterava o aux ele ainda estava apontando para mesma posição, logo gerava o loop infinito no print. Muito obrigado pela ajuda.
A versão corrigida ficou assim:
for(i = 0; i < V; i++){
    fscanf(ent, "%d %d", &Vi, &w);
    printf("\n %d ", Vi,w);
    while (w != 0){
        aux = malloc(sizeof(struct adj));
        fscanf(ent, "%d ", &v);
        aux->v = v;
        aux->w = w;
        printf("%d %d ", aux->w, aux->v);
        aux->prox = G[Vi];
        G[Vi] = aux;
        fscanf(ent, "%d", &w);
        aux = NULL;
    }
}


if isset($_POST issue

Question: I have one instance of where a user on my PHP site can login, and I'm trying to make a second where administrators can post announcements.
My login works beautifully, but for some reason I can't get my announcement submission to work. Despite my input fields being named appropriately, the field is being seen as "not set" when I type in a title and announcement on my form. Here is my code:
FORM:
        <form action="announce.php">
    <input  type="text" name="title" />
    <textarea  name="announce" cols="20" rows="2" ></textarea>
    <input type="submit" name="submit" value="Announce" />
    </form>

Here is my PHP:
include_once 'creds.php';
$con=mysqli_connect("$db_hostname","$db_username","$db_password","$db_database");

if (isset($_POST['title']))
{
    $title = $_POST['title'];
    $announce = $_POST['announce'];

$query = "INSERT INTO announcements (labname, name, author, announce)
        VALUES ($lab, $title, $username, $announce)";

$insert = mysqli_query($con, $query);

mysqli_close($con);

echo "added successfully";}
else
{
echo "something went wrong";
}

My other form seems to work but this one doesn't... is my syntax wrong somewhere?
Comment: `` try this
Comment: You are vulnerable to [SQL injection attacks](http://bobby-tables.com), and have multiple SQL syntax errors. You will NEVER get anything into your database until you fix the injection problems and learn basic SQL syntax requirements for strings.
Comment: Forms default to GET methods if not defined.
Comment: Wow, yes, that did the trick. Thank you, I was unaware I had to include that.
Comment: jerdiggity, I was getting the error "something went wrong". Once I fixed the method="post" thing, I got undefined variable errors. You fixed my problem before the parser even knew to! Thanks :)
Comment: Quotes => `($lab, $title, $username, $announce)`
Answer: Your form is submitting as a GET request, not POST.
Change this line:
<form action="announce.php">

to this:
<form action="announce.php" method="post">

Edit: I should really refresh the page before posting.  All credit to noobie-php for getting this right in their comment 30 mins before I posted this!
Answer: Php :
include_once 'creds.php';
$con=mysqli_connect("$db_hostname","$db_username","$db_password","$db_database");

if (isset($_POST['submit']))
{
    $title = $_POST['title'];
    $announce = $_POST['announce'];

$query = "INSERT INTO announcements (labname, name, author, announce)
        VALUES ($lab, $title, $username, $announce)";

$insert = mysqli_query($con, $query);

mysqli_close($con);

echo "added successfully";}
else
{
echo "something went wrong";
}

i think if (isset($_POST['submit'])) this is the problem.

if isset($_POST issue


Tool to draw normal QQ-plot with 45 degree reference line

Question: I have some data (a set of numbers) and I want to compare them with the normal distribution using QQ-plot. The only statistical tool that I am aware of is Octave but Octave doesn't draw the reference line.

As can be seen in the above picture the x-axis has a range from - 3 to 3 but the y-axis has a range from 20 to 140. I think drawing a 45 degree slope line would be wrong.
How can I draw such a reference line in Octave? Or does there exist any easy tool that would draw a QQ-plot with that reference line?
Answer: Here is one possible Octave solution to your question: (largely inspired from the corresponding Matlab function)
randn("state",255)
x = normrnd(10, 2, 200, 1);
[q, s] = qqplot(x);

% compute the y=x line
dx = prctile(q, 75) - prctile(q, 25);
dy = prctile(s, 75) - prctile(s, 25);
b = dy./dx;                                % slope
xc = (prctile(q, 25) + prctile(q, 75))/2;  % center points
yc = (prctile(s, 25) + prctile(s, 75))/2;  % ...
ymax = yc + b.*(max(q)-xc);
ymin = yc - b.*(xc-min(q));

plot(q, s, "Linestyle", "none", "Marker", "+")
line([min(q); max(q)], [ymin; ymax])

Answer: This is easy in R:
x <- rnorm(1000, 100, 10)  #Creates some data; this has is normal with mean 100 sd 10
qqnorm(x)         #qq
qqline(x)         #adds line

Comment: Thanks alot :) , .. in one of my number sets the reference line was horizontal is that ok ?
Comment: I think that's a problem
Comment: a problem in the integers (that they don't follow the normal dist) OR a problem in drawing them ?
Comment: It's OK that they aren't normal (that's part of the reason to use a qq plot). A horizontal line though.... what are your data?
Comment: just a bunch of numbers that are very close to each other   http://dl.dropbox.com/u/8045913/faculty_stuff/tcp_wired_lan_client.txt
Comment: That's why the line is almost horizontal. Most of those numbers are very close, but there are a couple extreme outliers. So, the axis has to accommodate the outliers, but the line is then close to horizontal because it's based on quantiles, not mean/sd


Quais os prós e contras de indexar vetores por zero ou por um?

Question: A maioria das linguagens de programação que conheço tem zero como o primeiro índice de um vetor.
Eu sei que várias linguagens de programação têm o índice um como o primeiro índice de vetor. Até pouco tempo eu achava que isso se limitava a linguagens mais antigas (como COBOL, Fortran, Algol e Smalltalk), mas recentemente descobri que Lua e Matlab também começam seus arrays por 1.
Eu acho que a decisão de índice inicial deve ser algo bastante sério. Que fatores os designers de linguagens consideram para determinar indexação base? Quais os prós e contras de cada forma?
Comment: @BillWoodger não se preocupe, tem horas que seu texto fica muito mais fácil de entender do que os de alguns dos nossos "nativos". _don't worry, sometimes your text is easier to understand than some of our "native"'s_
Comment: @bigown Para os mais rapidos, eu uso Ingles. Com menos importancia de tempo, o meu proprio Portuguese fraco. Para respostas, uma mixtura de tempo, Google Translate, e ajuda de meu filho. Isto, so metodo fraco :-)
Comment: Talvez, e esta é a minha opinião ( questão sinalizado ) , que foi originalmente pensado mais importante que um subscrito significou algo análogo ao leitor humano. Colocar algo no slot zero quando explicando é menos fácil de entender do que colocar algo em um slot . Compilador / interpretador faz algum trabalho de "traduzir" mas não é grande problema.
Comment: Eu quase consegui entender :D
Answer: É possível enumerar vantagens e desvantagens de cada estilo de indexação. Mas sinceramente, se alguém disser que uma maneira é muito melhor e a outra é um lixo, essa pessoa é meio fanática... Afinal, até mesmo programadores C contam as linhas no seu editor de texto começando em 1 ;-)
Vamos aos exemplos:
Vetor de 100 elementos, começando em 0 como em C, C++, Java ou Python e usando intervalos abertos no final como em Python (isto é, o último índice fica de fora):

A declaração em C, C++, Java, etc. é lista[100] (indicando a quantidade de elementos), mas só dá para indexar até lista[99] (usar lista[100] igual ao que foi declarado seria um erro).
Portanto será necessário usar size()-1 para acessar o último elemento.
O acesso a subfaixas do vetor é fácil. Se eu quisesse andar no vetor de 10 em 10 elementos, é só fazer 0*10, 1*10, 2*10, 3*10. Em Python fica assim: lista[0:10] inclui os primeiros 10 elementos, de 0 a 9; lista[10:20] inclui os elementos de 10 a 19; e lista[20:30] representa os elementos de 20 a 29. Repare que não foi necessário fazer nenhum "+1" nem "-1" e para obter o número de itens basta calcular fim - início.
O segundo elemento se chamará [1], o que é meio estranho. A melhor maneira de interpretar é pensar nos índices como deslocamento: lista[0] é o item do começo da lista, lista[1] é partir do começo e pular 1 (portanto o segundo elemento), lista[2] conta do começo e pula 2 (portanto chegando no terceiro elemento). Se a implementação de baixo nível fizer bom uso desse detalhe na implementação (como a dualidade de ponteiros e arrays em C), pode-se economizar uma instrução de máquina, deixando o código mais eficiente.
Se quiser andar em círculos nos primeiros 5 elementos, é possível incrementar o contador assim: i = (i + 1) % 5
Uma faixa vazia pode ser escrita como lista[10:10].
Uma faixa de um elemento fica lista[10:11] (contém apenas o elemento lista[10])
Você precisará somar 1 para exibir os índices de uma lista ao usuário, pois é meio estranho começar uma lista com 0, a menos que seja um log para debugging. Também é estranho apresentar uma lista que termina em 9 mas não tem 9 elementos.
Um índice inválido pode ser representado com -1 (mas não com 0). Por exemplo, se uma busca não encontrar nenhum elemento, muitas funções em linguagens populares retornam -1 ou outro valor negativo. Python usa -1 para representar o último elemento, então o mais comum é jogar uma exceção quando uma busca não encontra nada.

Vetor de 100 elementos, começando em 1, usando intervalos fechados (isto é, o último índice é incluído) como em Matlab:

O primeiro elemento é 1 e intuitivamente os índices são como números ordinais: primeiro, segundo, terceiro...
O último elemento é 100 e a quantidade de elementos é igual ao último índice. Bem mais intuitivo e evita erros.
O acesso a subfaixas é um pouco mais complicado: lista(1:10), lista(11:20), lista(21:30). Repare que é necessário usar 10 e 11, 20 e 21, 30 e 31, etc. Como esses valores provavelmente estarão em variáveis, o código fica com vários "+1" e/ou "-1".
A quantidade de elementos de uma subfaixa é fim - início + 1. Por exemplo, de 11 a 20 existem 10 elementos, porque inclui as duas pontas, tanto o 11 quanto o 20.
Se quiser andar em círculos nos primeiros 5 elementos, a fórmula fica: i = mod(i, 5) + 1 (agora, em vez do %, usei mod, já que estou usando Matlab como exemplo). Perceba que o "+1", neste caso, fica fora do da operação mod, mas não é nem mais fácil nem mais difícil que indexando a partir de 0.
Uma faixa vazia (se suportada) poderia ser descrita como lista(10:9).
Uma faixa de um elemento fica lista(10:10).
Você pode exibir os índices diretamente ao usuário, pois a maioria das pessoas espera que uma lista seja numerada a partir de 1 (esta lista é assim).
Um índice inválido pode ser representado com 0. Por exemplo, se uma busca não encontrar nenhum elemento, retornar 0 para representar sua ausência pode ser bem intuitivo.

Note ainda que essas não são as únicas possibilidades. Eu combinei a indexação começando com 0 e as subfaixas com final aberto como em Python, mas em VimScript os índices começam em 0 e as subfaixas são lista[0:9], lista[10:19], lista[20:29]. Muita gente justifica o início de arrays com 0 baseado em subfaixas, mas isso mistura dois conceitos separados.
Ou então uma linguagem pode ter pouco ou nenhum suporte a subfaixas, o que diminui a importância algumas das características que eu listei acima. As vantagens das subfaixas são bem visíveis em Python, enquanto que a linguagem C, que não tem subfaixas, provavelmente foi criada indexando a partir de 0 por causa da aritmética de ponteiros. Afinal, se temos um ponteiro para o começo de um vetor, não precisamos fazer mais nada para acessar o primeiro item (já estamos nele, portanto o deslocamento é 0).
Outra curiosidade é o Visual Basic, em que uma declaração lista(10) é um vetor de 11 elementos, numerados de 0 a 10. Vantagem: a declaração contém um índice válido. Desvantagem: você precisa somar 1 mentalmente para saber o número de itens da lista.
Algumas linguagens permitem escolher qualquer faixa, como em Fortran ou Pascal. Por exemplo, em Pascal (ou Delphi) ficaria assim: array[-10 .. 10] of integer, o que permite usar arrays de um jeito bem criativo e bem adaptado ao problema a ser resolvido, pelo menos para arrays de tamanho fixo. Arrays dinâmicos são outra história e dependem do dialeto do Pascal — muitas vezes imitam a linguagem C e indexam a partir de 0 mesmo. Uma alternativa seria prover funções que retornem os limites do array.
Comment: Lembrei de mais uma situação interessante: funções de busca. Uma função de busca que não encontre um elemento pode retornar 0 se os índices começarem com 1, o que é interessante porque 0 pode ser associado à ausência do elemento. Caso 0 seja o índice do primeiro elemento, a função precisará retornar -1 ou indicar de outra maneira a falha na busca (exceção, retorno null, retorno None, etc.). Usar -1 pode ser inconveniente por não ser um valor associado com ausência nem com "false", impedindo de usar a forma if (! find(...)).
Comment: Um artigo com um ponto de vista interessante, mostrando como a história da indexação por 0 pode ser facilmente esquecida e substituída por explicações "após o fato": http://exple.tive.org/blarg/2013/10/22/citation-needed/
Answer: Veja essas notas do Dijkstra que eu descaradamente copiei do SOEn.
Basicamente a convenção ajuda a representar sequências sem ter que lidar com corner cases. Sabe aqueles códigos horríveis que possuem ifs para lidar com os limites inferiores e superiores? De quebra essa nota explica o motivo de existência de outra convenção: O porquê de incluirmos o limite inferior mas não o superior no intervalo de funções que lidam com índices (vide funções como substring; para obtermos os primeiros n caracteres de uma string geralmente fazemos algo como string.substring(0,n)).

Veja também esse artigo na Wikipedia que enumera as seguintes vantagens:

Redução de erros por um elemento
Aritmética de ponteiros. O primeiro elemento de um array está na posição 0 - ou seja, em ponteiro, qualquer outro elemento está na posição ponteiro + tamanho do elemento * índice.
A questão de um sequência ser mais convenientemente representada por um intervalo aberto [0, n) do que por um intervalo fechado [1, n] conforme o artigo do Dijkstra.
Comment: Dado que numa lista de 100 elementos o último tem o índice 99 (e não 100), a redução de erros por um elemento é algo meio duvidoso; eles podem aumentar. A redução de erros só ocorre depois de pegar a prática, mas isso vale também para a indexação por 1 (e nela já temos prática desde a infância nas primeiras aulas de matemática ou até antes).
Comment: Oi @marcus, eu acho que o ponto do Dijkstra, bem como dos autores do artigo linkado é que indexação por 0 combinada com intervalo aberto costuma, em média, evitar erros por um, principalmente em lógicas de *slicing*. Pensando no seu exemplo, usar `0..100` com um intervalo aberto (`n < 100`) no término não resulta em nenhum problema. É possível, é claro, argumentar que `1..100` com intervalo fechado (`n <= 100`) seria similar. Dito isso, eu concordo com o seu ponto, usar `size - 1` para obter o último elemento pode ser bastante contraintuitivo. No fundo é questão de convenção / preferência.
Answer: Bom, minha segunda sinalização rejeitada (de duas) :-)
Eu entendo que esse site possui regras diferentes do SO - e eu gostaria de aproveitar para dizer que esse site é meu favorito, por uma longa margem, dentre os sites da SE que eu visitei (que são mais do que podem ser vistos no meu perfil) - e talvez não seja tão bom comentar duma posição periférica. Essa é uma questão de opinião também :-)
OK, como resolver essa questão? Primeiro, pegar as quatro linguagens de idade que foram mencionadas, e identificar por que elas usaram "1" como ponto de partida (ao mesmo tempo, estabelecer qual, se alguma, possui "arrays" no sentido que eles são entendidos por muitos).
Então, pegar um punhado de linguagens, de preferência populares, e descobrir por que elas usam zero. Achar a linguagem mãe, onde deve haver uma relação óbvia.
Descobrir se algum dos dois conjuntos de respostas indicam um "agrupamento" de razão que por sua vez dê suporte à ideia de uma razão específica para esse traço.
Também descobrir para Lua e Mathematica (essa pode ser a parte mais fácil) por que eles usam um.
Juntar todos os resultados. Cogitar. Especular. Teorizar. Publicar.
Trabalho para um Historiador da Computação que especialize em Desenvolvimento de Linguagens.

Dijkstra
Um homem de opiniões, todas corretas de seu próprio ponto de vista. Porque para ele seu conhecimento é absoluto, e suas opiniões são fatos.
A man of opinions, every one of them correct to his own absolute certain knowledge.
Algumas citações das notas citadas nessa resposta.

I mention this experimental evidence - for what it is worth - because
some people feel uncomfortable with conclusions that have not been
confirmed in practice.

Many programming languages have been designed without due attention to
this detail [that we had better regard zero as a most natural number].

[a mathematical colleague of mine] accused a number of younger
computing scientists of "pedantry" because - as they do by habit -
they started numbering at zero. He took consciously adopting the most
sensible convention as a provocation.

Dijkstra escreve muito bem. É um prazer ler seus textos, não só pelo conteúdo mas também pelas pitadas de bom-humor.
Porém, afirmar que começar em zero é a única maneira de se fazer as coisas, e que qualquer outra opção não seria nem natural nem rigorosa é... uma afirmação, e parte do princípio de que tudo na sociedade (ou no trabalho), principalmente computação, deve ocorrer por meio do rigor, e levar a alguma conclusão natural que não possa ser contestada.
As coisas não funcionam assim.
Acho que Dijkstra adoraria entrar num elevador e ver um botão Piso 0. Ele talvez se recusasse a entrar num elevador que usasse T para o térreo ou 1 como o último andar antes da garagem.
Na verdade, eu gosto dessa ideia. Imagine o Dijkstra apertando zero e indo para na garagem. Ele volta para o elevador e aperta o zero de novo. Garagem outra vez. Ele iria escrever bem sobre isso, dizendo que o problema é do projeto do prédio. OK. Isso é só a minha opinião e a minha imaginação.
Abra uma gaveta de arquivos. Veja as pastas lá dentro. Se alguém diz "primeira", "última", "terceira a partir do fundo", "aquela ao lado da vermelha" ou algo assim, conseguimos encontrar o que procuramos, independentemente de contarmos do zero ou do um. Pode até ser que precisemos olhar o conteúdo de duas pastas para encontrar, mas vai dar certo se a informação que nos deram estiver correta.
Isso importa?
O processador da linguagem lida com tudo de qualquer forma. Não importa o que nós escrevemos (desde que apropriado para aquela linguagem), o processador da linguagem vai fazer o que ele tem de fazer. Em muitos exemplos não há mais um significado nem mesmo em si própria. Um array associativo não começa com zero, ou um. Hoje há muitas "construções de loop" que não têm de especificar um valor inicial, porque quando você pensa sobre isso, é razoável esperar de uma linguagem de nível mais alto que "eu gostaria de consultar todos os valores dessa coisa, compilador favor começar no lugar certo" funcione como esperado.

Não, eu não vou gastar mais esforço nessa pergunta do que ela vale, sinto muito. Eu a marquei como CW, já que essas são algumas reações a opiniões, em uma pergunta opinativa, que não pode ser respondida de outra forma senão com incertezas, eu certamente não quero nenhuma reputação por isso, ainda que alguém a julgue merecedora.
É uma pergunta para um bar na praia, pra quando você está preso num elevador com alguns programadores, ou para seus sonhos, quando você vence o debate e todo o mundo (da programação) concorda com você.

Posição Inicial 1 = Deslocamento 0
COBOL, aquela linguagem que está aí há um tempo e que talvez poucos entendam, não possui "arrays", mas ela tem "tabelas" com OCCURS.
01  A-TABLE.
    05  FILLER OCCURS 100 TIMES
        INDEXED BY AN-INDEX-NAME.
        10  SOME-DATA             PIC XX.

Para referenciar uma entrada na tabela, subscrevendo, você pode usar o índice data-item AN-INDEX-NAME ou usar um literal ou usar um data-name (somente inteiros, mas nós não temos "ints" dessa forma).
A maneira mais rápida de acessar um elemento é com um literal, porque o compilador calcula o deslocamento. O literal 1 ganha o deslocamento 0. O literal 2 ganha ((2-1) * tamanho do elemento) etc.
O índice data-item você atribui (SET) a um valor. Você faz SET ... TO 1 e o compilador usa um valor zero. Você usa SET ... TO 2 e o compilador usa ((2-1) * tamanho do elemento) etc. Você pode fazer SET ... UP ou SET ... DOWN e o compilador adiciona ou subtrai o tamanho do elemento de forma apropriada.
Usando um índice data-item é a segunda maneira mais rápida. Na maior parte do tempo.
Usando um data-item como subscrito, o compilador precisa gerar código para "converter" o valor para um deslocamento. Um pouco mais de trabalho. Sempre um data-name para subscrever com um valor de 1 será calculado para um deslocamento de 0.
Exceto. Para o caso especial, onde o tamanho do elemento é um.
Nesse caso, o compilador irá usar o valor de data-name diretamente, ele vai apenas "fingir" que a tabela começa um byte antes. Nesse caso especial, o data-name-for-a-subscript é mais rápido que usando o índice data-item.
Nós humanos sempre usamos 1 para a primeira entrada de uma tabela. O compilador usa 0, ou modifica sua implementação de 0 no caso especial de uma tabela com entradas de um único byte e usa 1 para a primeira entrada.
Agora, a situação é, com COBOL, nossas tabelas têm tamanho fixo. Nós precisamos saber quantas entradas existem na tabela, quais são de fato usadas. O compilador não pode nos dizer. Se nós temos que saber quantas são, nós temos que saber que é 0 quando não há nenhuma entrada. Se nós tivéssemos que subscrever de zero, nós teríamos um teste interessante para ver se nós excedemos o número de entradas em uma tabela.
Meu palpite seria que o exposto acima não é a razão pela qual a subscrição "começa" de um no design, mas que o design decidiu, porque o objetivo da linguagem era tornar mais fácil para humanos programarem, que começar por um era um conceito mais fácil de pegar o jeito (naquele estágio da história da computação).
Para conseguir uma base para um ou outro ponto, você provavelmente teria que dar uma olhada na linguagem FLOWMATIC, em que muito do design da mesma foi usada para COBOL.
Possíveltalvezquemsabe não foi nem uma decisão consciente mas algo tão "óbvio" que nem foi muito discutido.
Entretanto, é improvável que qualquer um vivo saiba a resposta para COBOL. Ou FORTRAN. Ou ALGOL. SMALLTALK é um pouco mais novo. Talvez uma resposta possa ser encontrada observando todas as notas de design de COBOL. Talvez não.
É uma pergunta apenas de especulação e opinião, e do modo que eu vejo não há uma resposta "certa" ou "errada" a por que essas linguagens dessa época fizeram assim.
Dijkstra, que parece achar que todos

 deveriam começar em 0, certamente não sabia.

Resposta traduzida livremente do original em inglês, no histórico de revisões.
Comment: Most people don't ever intend to design new programming languages. But some of us do, myself included. For us, this is a very relevant question, even if the answer turns out to be "a matter of preference" (it's not: computers are as happy consuming binary code, but programs are written by humans). I wouldn't ask every question about language design here at StackOverflow (most would be more appropriate in a platform like Discourse), but a selected few are sure answerable objectively (I have strong subjective reasons to shun 1-based indices, but they don't fit this site so I'm keeping to myself)
Comment: So... who's going to translate this to Portuguese? :)
Comment: @bfavaretto "So... who's going to translate this to Portuguese?" There is goes... Hopefully I didn't mess up the COBOL part. Only left the Dijkstra quote as it is, since I couldn't figure out its exact meaning ("correto com certeza absoluta, pelo menos até onde vai seu conhecimento"? "correto de acordo com seu conhecimento, que é certo e absoluto"? etc)
Comment: Agreed. In fact, one very good reason to choose between one or another is how well it integrates with other programs - potentially written in different languagues (most of them contemporary). BTW: IMHO the answer got a lot better after the edit (those facts about the reasoning behind COBOL implementations are very insightful), so I retracted my downvote.
Comment: @mgibsonbr Eu também não sei traduzir a citação, tive a mesma dúvida. Bill, você pode explicar o significado pra gente?
Comment: @mgibsonbr fair enough, but I don't see something like this as a good starting-point for even approaching the question over 1/0, let alone answering it. I think a language could be designed without the programmer having to *know*, and that would deal with a lot of "off by one" problems. To design a new language for todays' new programmers, I think you have to research pretty-much in modern times. I don't think the past will tell you whether 0 or 1 is "right" or "wrong", just how they were used in a given particular language. Implementation detail.
Comment: @mgibsonbr no problem, although I was thinking of avoiding benefits if anyone wanted to upvote, I also get protected from the downvotes (didn't think of that). Inter-language communication? Very interesting. Can't discuss it here though :-)
Comment: @mgibsonbr and just a point, those are facts about how COBOL (on IBM Mainframes) is *implemented* (for the one-byte table especially, the rest is fairly general). I deliberately avoided rationalising, reading history backwards, to say why COBOL had 1 when it came into being.
Comment: @bfavaretto, I think quoting Dijkstra just got me going (coming as it did after the allusion that COBOL is a pre-Christian-era language). A bit of a non-answer, I have to admit. If there is interest I can do a little work on it, but I'm not sure how helpful it is to the discussion (which shouldn't be happening in this format....).
Comment: Regarding the question, this is answerable: *Que fatores os designers de linguagens consideram para determinar indexação base? Quais os prós e contras de cada forma?* Of course there is no right answer to "which is better", but that's not what's being asked. Note: your flag was rejected from the review queue (3 "leave open" votes). Had a mod handled it, it would probably be marked *helpful*.
Comment: @mgibsonbr Muito obrigado. Sorry about the continuation...
Comment: @bfavaretto more difficult than I thought.