Implement a "Find all" algorithm that displays matched lines in a table, and jumps to line when table cell clicked

Question: I would like to implement functionality for being able to search a QPlainTextEdit for a query string, and display all matched lines in a table. Selecting a row in the table should move the cursor to the correct line in the document.
Below is a working example that finds all matches and displays them in a table. How can I get to the selected line number in the string that the plaintextedit holds? I could instead use the match.capturedEnd() and match.capturedStart() to show the matches, but line numbers are a more intuitive thing to think of, rather than the character index matches.
MWE (rather long sample text for fun)
import PySide6.QtCore as qtc
import PySide6.QtGui as qtg
import PySide6.QtWidgets as qtw

class MainWindow(qtw.QWidget):
    def __init__(self):
        qtw.QWidget.__init__(self)
        self.resize(600, 600)
        self.setWindowTitle('My Application')
        self.fileViewer = qtw.QPlainTextEdit()
        self.lineEditQuery = qtw.QLineEdit()
        self.tableResults = qtw.QTableWidget()
        self.tableResults.setColumnCount(2)
        self.tableResults.setHorizontalHeaderLabels(['Line Number', 'Matched Line'])
        self.buttonFind = qtw.QPushButton('Find All')

        layout = qtw.QVBoxLayout()
        layout.addWidget(self.fileViewer)
        layout.addWidget(self.lineEditQuery)
        layout.addWidget(self.buttonFind)
        layout.addWidget(self.tableResults)
        self.setLayout(layout)

        # Set some properties of QTableWidget
        self.tableResults.setSizeAdjustPolicy(qtw.QAbstractScrollArea.AdjustToContents)
        self.tableResults.setSelectionBehavior(self.tableResults.SelectRows)

        # Insert search query
        self.lineEditQuery.setText('simplicity itself')

        # Connect button click event
        self.buttonFind.clicked.connect(self.findAll)

    def findAll(self):
        """Collect matches in dict and pass on the insert method."""
        query = qtc.QRegularExpression(self.lineEditQuery.text())
        fileContents = self.fileViewer.toPlainText().splitlines()

        result = {}
        for i, line in enumerate(fileContents):
            match = query.match(line)
            if match.hasMatch():
                result[i] = line
                match.capturedEnd()

        self.insertMatches(result)

    def insertMatches(self, matches):
        self.tableResults.setRowCount(len(matches))

        rowCounter = 0
        for i, line in matches.items():
            itemNumber = qtw.QTableWidgetItem(str(i))
            itemLine = qtw.QTableWidgetItem(line)
            self.tableResults.setItem(rowCounter, 0, itemNumber)
            self.tableResults.setItem(rowCounter, 1, itemLine)
            rowCounter += 1
        self.tableResults.resizeColumnsToContents()

if __name__ == '__main__':
    SAMPLE = """

                            THE ADVENTURES OF SHERLOCK HOLMES

                                   Arthur Conan Doyle

                                    Table of contents

                   A Scandal in Bohemia

                                  A SCANDAL IN BOHEMIA

                                    Table of contents
                                         Chapter 1

              CHAPTER I

         To Sherlock Holmes she is always the woman. I have seldom heard him
         mention her under any other name. In his eyes she eclipses and
         predominates the whole of her sex. It was not that he felt any
         emotion akin to love for Irene Adler. All emotions, and that one
         particularly, were abhorrent to his cold, precise but admirably
         balanced mind. He was, I take it, the most perfect reasoning and
         observing machine that the world has seen, but as a lover he would
         have placed himself in a false position. He never spoke of the softer
         passions, save with a gibe and a sneer. They were admirable things
         for the observer--excellent for drawing the veil from men's motives
         and actions. But for the trained reasoner to admit such intrusions
         into his own delicate and finely adjusted temperament was to
         introduce a distracting factor which might throw a doubt upon all his
         mental results. Grit in a sensitive instrument, or a crack in one of
         his own high-power lenses, would not be more disturbing than a strong
         emotion in a nature such as his. And yet there was but one woman to
         him, and that woman was the late Irene Adler, of dubious and
         questionable memory.

         I had seen little of Holmes lately. My marriage had drifted us away
         from each other. My own complete happiness, and the home-centred
         interests which rise up around the man who first finds himself master
         of his own establishment, were sufficient to absorb all my attention,
         while Holmes, who loathed every form of society with his whole
         Bohemian soul, remained in our lodgings in Baker Street, buried among
         his old books, and alternating from week to week between cocaine and
         ambition, the drowsiness of the drug, and the fierce energy of his
         own keen nature. He was still, as ever, deeply attracted by the study
         of crime, and occupied his immense faculties and extraordinary powers
         of observation in following out those clues, and clearing up those
         mysteries which had been abandoned as hopeless by the official
         police. From time to time I heard some vague account of his doings:
         of his summons to Odessa in the case of the Trepoff murder, of his
         clearing up of the singular tragedy of the Atkinson brothers at
         Trincomalee, and finally of the mission which he had accomplished so
         delicately and successfully for the reigning family of Holland.
         Beyond these signs of his activity, however, which I merely shared
         with all the readers of the daily press, I knew little of my former
         friend and companion.

         One night--it was on the twentieth of March, 1888--I was returning
         from a journey to a patient (for I had now returned to civil
         practice), when my way led me through Baker Street. As I passed the
         well-remembered door, which must always be associated in my mind with
         my wooing, and with the dark incidents of the Study in Scarlet, I was
         seized with a keen desire to see Holmes again, and to know how he was
         employing his extraordinary powers. His rooms were brilliantly lit,
         and, even as I looked up, I saw his tall, spare figure pass twice in
         a dark silhouette against the blind. He was pacing the room swiftly,
         eagerly, with his head sunk upon his chest and his hands clasped
         behind him. To me, who knew his every mood and habit, his attitude
         and manner told their own story. He was at work again. He had risen
         out of his drug-created dreams and was hot upon the scent of some new
         problem. I rang the bell and was shown up to the chamber which had
         formerly been in part my own.

         His manner was not effusive. It seldom was; but he was glad, I think,
         to see me. With hardly a word spoken, but with a kindly eye, he waved
         me to an armchair, threw across his case of cigars, and indicated a
         spirit case and a gasogene in the corner. Then he stood before the
         fire and looked me over in his singular introspective fashion.

         "Wedlock suits you," he remarked. "I think, Watson, that you have put
         on seven and a half pounds since I saw you."

         "Seven!" I answered.

         "Indeed, I should have thought a little more. Just a trifle more, I
         fancy, Watson. And in practice again, I observe. You did not tell me
         that you intended to go into harness."

         "Then, how do you know?"

         "I see it, I deduce it. How do I know that you have been getting
         yourself very wet lately, and that you have a most clumsy and
         careless servant girl?"

         "My dear Holmes," said I, "this is too much. You would certainly have
         been burned, had you lived a few centuries ago. It is true that I had
         a country walk on Thursday and came home in a dreadful mess, but as I
         have changed my clothes I can't imagine how you deduce it. As to Mary
         Jane, she is incorrigible, and my wife has given her notice, but
         there, again, I fail to see how you work it out."

         He chuckled to himself and rubbed his long, nervous hands together.

         "It is simplicity itself," said he; "my eyes tell me that on the
         inside of your left shoe, just where the firelight strikes it, the
         leather is scored by six almost parallel cuts. Obviously they have
         been caused by someone who has very carelessly scraped round the
         edges of the sole in order to remove crusted mud from it. Hence, you
         see, my double deduction that you had been out in vile weather, and
         that you had a particularly malignant boot-slitting specimen of the
         London slavey. As to your practice, if a gentleman walks into my
         rooms smelling of iodoform, with a black mark of nitrate of silver
         upon his right forefinger, and a bulge on the right side of his
         top-hat to show where he has secreted his stethoscope, I must be
         dull, indeed, if I do not pronounce him to be an active member of the
         medical profession."

         I could not help laughing at the ease with which he explained his
         process of deduction. "When I hear you give your reasons," I
         remarked, "the thing always appears to me to be so ridiculously
         simple that I could easily do it myself, though at each successive
         instance of your reasoning I am baffled until you explain your
         process. And yet I believe that my eyes are as good as yours."

         "Quite so," he answered, lighting a cigarette, and throwing himself
         down into an armchair. "You see, but you do not observe. The
         distinction is clear. For example, you have frequently seen the steps
         which lead up from the hall to this room."

         "Frequently."

         "How often?"

         "Well, some hundreds of times."

         "Then how many are there?"

         "How many? I don't know."

         "Quite so! You have not observed. And yet you have seen. That is just
         my point. Now, I know that there are seventeen steps, because I have
         both seen and observed. By-the-way, since you are interested in these
         little problems, and since you are good enough to chronicle one or
         two of my trifling experiences, you may be interested in this." He
         threw over a sheet of thick, pink-tinted note-paper which had been
         lying open upon the table. "It came by the last post," said he. "Read
         it aloud."

         The note was undated, and without either signature or address.

         "There will call upon you to-night, at a quarter to eight o'clock,"
         it said, "a gentleman who desires to consult you upon a matter of the
         very deepest moment. Your recent services to one of the royal houses
         of Europe have shown that you are one who may safely be trusted with
         matters which are of an importance which can hardly be exaggerated.
         This account of you we have from all quarters received. Be in your
         chamber then at that hour, and do not take it amiss if your visitor
         wear a mask."

         "This is indeed a mystery," I remarked. "What do you imagine that it
         means?"

         "I have no data yet. It is a capital mistake to theorize before one
         has data. Insensibly one begins to twist facts to suit theories,
         instead of theories to suit facts. But the note itself. What do you
         deduce from it?"

         I carefully examined the writing, and the paper upon which it was
         written.

         "The man who wrote it was presumably well to do," I remarked,
         endeavouring to imitate my companion's processes. "Such paper could
         not be bought under half a crown a packet. It is peculiarly strong
         and stiff."

         "Peculiar--that is the very word," said Holmes. "It is not an English
         paper at all. Hold it up to the light."

         I did so, and saw a large "E" with a small "g," a "P," and a large
         "G" with a small "t" woven into the texture of the paper.

         "What do you make of that?" asked Holmes.

         "The name of the maker, no doubt; or his monogram, rather."

         "Not at all. The 'G' with the small 't' stands for 'Gesellschaft,'
         which is the German for 'Company.' It is a customary contraction like
         our 'Co.' 'P,' of course, stands for 'Papier.' Now for the 'Eg.' Let
         us glance at our Continental Gazetteer." He took down a heavy brown
         volume from his shelves. "Eglow, Eglonitz--here we are, Egria. It is
         in a German-speaking country--in Bohemia, not far from Carlsbad.
         'Remarkable as being the scene of the death of Wallenstein, and for
         its numerous glass-factories and paper-mills.' Ha, ha, my boy, what
         do you make of that?" His eyes sparkled, and he sent up a great blue
         triumphant cloud from his cigarette.

         "The paper was made in Bohemia," I said.

         "Precisely. And the man who wrote the note is a German. Do you note
         the peculiar construction of the sentence--'This account of you we
         have from all quarters received.' A Frenchman or Russian could not
         have written that. It is the German who is so uncourteous to his
         verbs. It only remains, therefore, to discover what is wanted by this
         German who writes upon Bohemian paper and prefers wearing a mask to
         showing his face. And here he comes, if I am not mistaken, to resolve
         all our doubts."

         As he spoke there was the sharp sound of horses' hoofs and grating
         wheels against the curb, followed by a sharp pull at the bell. Holmes
         whistled.

         "A pair, by the sound," said he. "Yes," he continued, glancing out of
         the window. "A nice little brougham and a pair of beauties. A hundred
         and fifty guineas apiece. There's money in this case, Watson, if
         there is nothing else."

         "I think that I had better go, Holmes."

         "Not a bit, Doctor. Stay where you are. I am lost without my Boswell.
         And this promises to be interesting. It would be a pity to miss it."

         "But your client--"

         "Never mind him. I may want your help, and so may he. Here he comes.
         Sit down in that armchair, Doctor, and give us your best attention."

         A slow and heavy step, which had been heard upon the stairs and in
         the passage, paused immediately outside the door. Then there was a
         loud and authoritative tap.

         "Come in!" said Holmes.

         A man entered who could hardly have been less than six feet six
         inches in height, with the chest and limbs of a Hercules. His dress
         was rich with a richness which would, in England, be looked upon as
         akin to bad taste. Heavy bands of astrakhan were slashed across the
         sleeves and fronts of his double-breasted coat, while the deep blue
         cloak which was thrown over his shoulders was lined with
         flame-coloured silk and secured at the neck with a brooch which
         consisted of a single flaming beryl. Boots which extended halfway up
         his calves, and which were trimmed at the tops with rich brown fur,
         completed the impression of barbaric opulence which was suggested by
         his whole appearance. He carried a broad-brimmed hat in his hand,
         while he wore across the upper part of his face, extending down past
         the cheekbones, a black vizard mask, which he had apparently adjusted
         that very moment, for his hand was still raised to it as he entered.
         From the lower part of the face he appeared to be a man of strong
         character, with a thick, hanging lip, and a long, straight chin
         suggestive of resolution pushed to the length of obstinacy.

         "You had my note?" he asked with a deep harsh voice and a strongly
         marked German accent. "I told you that I would call." He looked from
         one to the other of us, as if uncertain which to address.

         "Pray take a seat," said Holmes. "This is my friend and colleague,
         Dr. Watson, who is occasionally good enough to help me in my cases.
         Whom have I the honour to address?"

         "You may address me as the Count Von Kramm, a Bohemian nobleman. I
         understand that this gentleman, your friend, is a man of honour and
         discretion, whom I may trust with a matter of the most extreme
         importance. If not, I should much prefer to communicate with you
         alone."

         I rose to go, but Holmes caught me by the wrist and pushed me back
         into my chair. "It is both, or none," said he. "You may say before
         this gentleman anything which you may say to me."

         The Count shrugged his broad shoulders. "Then I must begin," said he,
         "by binding you both to absolute secrecy for two years; at the end of
         that time the matter will be of no importance. At present it is not
         too much to say that it is of such weight it may have an influence
         upon European history."

         "I promise," said Holmes.

         "And I."

         "You will excuse this mask," continued our strange visitor. "The
         august person who employs me wishes his agent to be unknown to you,
         and I may confess at once that the title by which I have just called
         myself is not exactly my own."

         "I was aware of it," said Holmes dryly.

         "The circumstances are of great delicacy, and every precaution has to
         be taken to quench what might grow to be an immense scandal and
         seriously compromise one of the reigning families of Europe. To speak
         plainly, the matter implicates the great House of Ormstein,
         hereditary kings of Bohemia."

         "I was also aware of that," murmured Holmes, settling himself down in
         his armchair and closing his eyes.

         Our visitor glanced with some apparent surprise at the languid,
         lounging figure of the man who had been no doubt depicted to him as
         the most incisive reasoner and most energetic agent in Europe. Holmes
         slowly reopened his eyes and looked impatiently at his gigantic
         client.

         "If your Majesty would condescend to state your case," he remarked,
         "I should be better able to advise you."

         The man sprang from his chair and paced up and down the room in
         uncontrollable agitation. Then, with a gesture of desperation, he
         tore the mask from his face and hurled it upon the ground. "You are
         right," he cried; "I am the King. Why should I attempt to conceal
         it?"

         "Why, indeed?" murmured Holmes. "Your Majesty had not spoken before I
         was aware that I was addressing Wilhelm Gottsreich Sigismond von
         Ormstein, Grand Duke of Cassel-Felstein, and hereditary King of
         Bohemia."

         "But you can understand," said our strange visitor, sitting down once
         more and passing his hand over his high white forehead, "you can
         understand that I am not accustomed to doing such business in my own
         person. Yet the matter was so delicate that I could not confide it to
         an agent without putting myself in his power. I have come incognito
         from Prague for the purpose of consulting you."

         "Then, pray consult," said Holmes, shutting his eyes once more.

         "The facts are briefly these: Some five years ago, during a lengthy
         visit to Warsaw, I made the acquaintance of the well-known
         adventuress, Irene Adler. The name is no doubt familiar to you."

         "Kindly look her up in my index, Doctor," murmured Holmes without
         opening his eyes. For many years he had adopted a system of docketing
         all paragraphs concerning men and things, so that it was difficult to
         name a subject or a person on which he could not at once furnish
         information. In this case I found her biography sandwiched in between
         that of a Hebrew rabbi and that of a staff-commander who had written
         a monograph upon the deep-sea fishes.

         "Let me see!" said Holmes. "Hum! Born in New Jersey in the year 1858.
         Contralto--hum! La Scala, hum! Prima donna Imperial Opera of
         Warsaw--yes! Retired from operatic stage--ha! Living in London--quite
         so! Your Majesty, as I understand, became entangled with this young
         person, wrote her some compromising letters, and is now desirous of
         getting those letters back."

         "Precisely so. But how--"

         "Was there a secret marriage?"

         "None."

         "No legal papers or certificates?"

         "None."

         "Then I fail to follow your Majesty. If this young person should
         produce her letters for blackmailing or other purposes, how is she to
         prove their authenticity?"

         "There is the writing."

         "Pooh, pooh! Forgery."

         "My private note-paper."

         "Stolen."

         "My own seal."

         "Imitated."

         "My photograph."

         "Bought."

         "We were both in the photograph."

         "Oh, dear! That is very bad! Your Majesty has indeed committed an
         indiscretion."

         "I was mad--insane."

         "You have compromised yourself seriously."

         "I was only Crown Prince then. I was young. I am but thirty now."

         "It must be recovered."

         "We have tried and failed."

         "Your Majesty must pay. It must be bought."

         "She will not sell."

         "Stolen, then."

         "Five attempts have been made. Twice burglars in my pay ransacked her
         house. Once we diverted her luggage when she travelled. Twice she has
         been waylaid. There has been no result."

         "No sign of it?"

         "Absolutely none."

         Holmes laughed. "It is quite a pretty little problem," said he.

         "But a very serious one to me," returned the King reproachfully.

         "Very, indeed. And what does she propose to do with the photograph?"

         "To ruin me."

         "But how?"

         "I am about to be married."

         "So I have heard."

         "To Clotilde Lothman von Saxe-Meningen, second daughter of the King
         of Scandinavia. You may know the strict principles of her family. She
         is herself the very soul of delicacy. A shadow of a doubt as to my
         conduct would bring the matter to an end."

         "And Irene Adler?"

         "Threatens to send them the photograph. And she will do it. I know
         that she will do it. You do not know her, but she has a soul of
         steel. She has the face of the most beautiful of women, and the mind
         of the most resolute of men. Rather than I should marry another
         woman, there are no lengths to which she would not go--none."

         "You are sure that she has not sent it yet?"

         "I am sure."

         "And why?"

         "Because she has said that she would send it on the day when the
         betrothal was publicly proclaimed. That will be next Monday."

         "Oh, then we have three days yet," said Holmes with a yawn. "That is
         very fortunate, as I have one or two matters of importance to look
         into just at present. Your Majesty will, of course, stay in London
         for the present?"

         "Certainly. You will find me at the Langham under the name of the
         Count Von Kramm."

         "Then I shall drop you a line to let you know how we progress."

         "Pray do so. I shall be all anxiety."

         "Then, as to money?"

         "You have carte blanche."

         "Absolutely?"

         "I tell you that I would give one of the provinces of my kingdom to
         have that photograph."

         "And for present expenses?"

         The King took a heavy chamois leather bag from under his cloak and
         laid it on the table.

         "There are three hundred pounds in gold and seven hundred in notes,"
         he said.

         Holmes scribbled a receipt upon a sheet of his note-book and handed
         it to him.

         "And Mademoiselle's address?" he asked.

         "Is Briony Lodge, Serpentine Avenue, St. John's Wood."

         Holmes took a note of it. "One other question," said he. "Was the
         photograph a cabinet?"

         "It was."

         "Then, good-night, your Majesty, and I trust that we shall soon have
         some good news for you. And good-night, Watson," he added, as the
         wheels of the royal brougham rolled down the street. "If you will be
         good enough to call to-morrow afternoon at three o'clock I should
         like to chat this little matter over with you."

         ----------
         This text is provided to you "as-is" without any warranty. No
         warranties of any kind, expressed or implied, are made to you as to
         the text or any medium it may be on, including but not limited to
         warranties of merchantablity or fitness for a particular purpose.

         This text was formatted from various free ASCII and HTML variants.
         See http://sherlock-holm.es for an electronic form of this text and
         additional information about it.

         This text comes from the collection's version 3.1.
    """

    app = qtw.QApplication([])
    mw = MainWindow()
    mw.fileViewer.insertPlainText(SAMPLE)
    mw.buttonFind.clicked.emit()
    mw.show()
    app.exec_()

Comment: What do you mean by "get to the selected line"?
Comment: I mean move the cursor in fileViewer to the line number where a match was found.
Answer: In order to move the cursor to a specified position, it's necessary to use the underlying QTextDocument using document().
Through findBlockByLineNumber you can construct a QTextCursor and use setTextCursor() to "apply" that cursor (including the actual caret position) to the plain text.
    def goToLine(self, line):
        block = self.fileViewer.document().findBlockByLineNumber(line)
        self.fileViewer.setTextCursor(qtg.QTextCursor(block))
        self.fileViewer.setFocus()

Since you will be working with QTextDocument and QTextCursor anyway, I suggest you to avoid searching line by line, since QTextDocument already provides a more compliant and extensible interface through find():
class MainWindow(qtw.QWidget):
    def __init__(self):
        # ...
        self.tableResults.itemClicked.connect(self.goToLine)

    def findAll(self):
        self.tableResults.setRowCount(0)
        query = qtc.QRegularExpression(self.lineEditQuery.text())
        doc = self.fileViewer.document()
        cursor = qtg.QTextCursor(doc)
        rowCounter = 0
        while True:
            cursor = doc.find(query, cursor)
            if cursor.isNull():
                break
            self.tableResults.insertRow(rowCounter)
            block = cursor.block()
            itemNumber = qtw.QTableWidgetItem()
            # set the data as integer, not as string; you cannot do that using
            # QTableWidgetItem constructor
            itemNumber.setData(qtc.Qt.DisplayRole, block.firstLineNumber())
            itemLine = qtw.QTableWidgetItem(block.text())
            self.tableResults.setItem(rowCounter, 0, itemNumber)
            self.tableResults.setItem(rowCounter, 1, itemLine)
            rowCounter += 1
        self.tableResults.resizeColumnsToContents()

    def goToLine(self, item):
        line = self.tableResults.model().index(item.row(), 0).data()
        block = self.fileViewer.document().findBlockByLineNumber(line)
        self.fileViewer.setTextCursor(qtg.QTextCursor(block))
        self.fileViewer.setFocus()

While a bit difficult to get used with, using the QTextCursor interface has a lot of benefits. For instance, you could set the matched cursor (which includes the selection of the found text) as item data, and set that cursor for the plain text; the result is that not only you'll get the correct position, but you'll also have the matched text automatically selected:
    def findAll(self):
            # ...
            itemNumber = qtw.QTableWidgetItem()
            itemNumber.setData(qtc.Qt.DisplayRole, block.firstLineNumber())
            # since the cursor is being reused for the search, you must
            # construct a *new* instance based on it
            itemNumber.setData(qtc.Qt.UserRole, qtg.QTextCursor(cursor))
            # ...

    def goToLine(self, item):
        index = self.tableResults.model().index(item.row(), 0)
        cursor = index.data(qtc.Qt.UserRole)
        self.fileViewer.setTextCursor(cursor)
        self.fileViewer.setFocus()

Note: you should use self.tableResults.setEditTriggers(self.tableResults.NoEditTriggers) to avoid item editing in the table
Comment: Great, thanks! I will go for the quicker solution for now, but will eventually try to make use of the cursor interface as advised!


How to delete from an object FileList

Question: The function of this code, the preview image is displayed after selecting the file. Also internally, each key and value is inserted into the FileList object.
Each image displayed as a preview has a delete button. So, when you press it, the image disappears from the screen, and internally, I want to delete the corresponding key and value from the FileList object. I knew that I could delete from Object, like a " delete Object.key ; "  However, in this case, this does not work effectively. Perhaps there are other different solutions to it. Please let me know if you know if

<!DOCTYPE html>

    <meta charset="utf-8">
    <title></title>

<form id='form' action="data.php" method="post" enctype="multipart/form-data">
<input type="file" id="files" name="files[]" multiple />
<button class="show">Butoon</button>
</form>

<output id="list"></output>

Comment: Just think you may find this answer helpful. https://stackoverflow.com/questions/16943605/remove-a-filelist-item-from-a-multiple-inputfile/47642446#47642446
Answer: Replace delete x[' + id + ']; with:
x.splice(id,1);
Comment: Thank you for your reply. I tried it, but I couldn't.

How to delete from an object FileList


How to add filter parameters to controllers in Laravel?

Question:
I want to add some parameters to a filter in Laravel framework.
The catch is, that i am calling my filters from controller's constructor and not route.
My code look like this:
Controller
public function __construct()
{
    $this->filter('before','test');
}

Filter
Route::filter('test',function(){
    // echo parameters passed to filter in controller.
});

Thanks for your help!
Answer: For anyone else, it's quite simple..
Controller
$this->filter('before','test',array('value'));

Filter
Route::filter('test',function($label){
    echo $label; // Outputs the 'value'
});

Comment: As a shortcut, you can also write `$this->beforeFilter('test', array('value'))`.


Where are hooks stored/cached?

Question: I have a hook_form_alter in a module, and it should be firing, but it appears it's not. I've cleared caches and rebuilt the registry. Is there someplace in the database or somewhere else where I can see if my hook is registed? FWIW here is my hook:
/**
 * Implements hook_form_alter
 */
function my_module_form_alter(&$form, &$form_state, $form_id) {
  drupal_set_message($form_id);
}

Comment: is your hook in your my_module.module file ? is your my_module module enabled ? are you actually displaying a form (in other words is there a form to alter) ?
Comment: Yes, yes, and yes.
Comment: You can use [module_implements](https://api.drupal.org/api/drupal/includes%21module.inc/function/module_implements/7) to see if the hook is being implemented by your module.
Comment: How drupal hooks work is a taugh question but there's plenty resources out there that have a go at explaining it. See https://www.drupal.org/node/292 , http://stackoverflow.com/questions/4994512/can-you-create-your-own-hook-in-drupal and search up for tutorials on hooks like : https://www.youtube.com/watch?v=5UdFxcAHm0Y Good luck.
Comment: Modules that are enabled are listed in the 'system' table. Hooks themselves aren't stored anywhere just called. In the case of hook_form_alter, it is called when a form is initiated. When a form is initiated it'll call ALL/ANY hook_form_alter. The system will go through enabled modules and call upon all hook_form_alters(). I'm guessing your module is called 'my_module'. If it is then the other question is, are you trying this hook on a page that has a form? If no forms are initiated this hook does not execute.
Answer: The hook implementations ARE cached inside the database.. this is why it's necessary to clear cache in order for a newly implemented hook to fire.
Taking a look, inside the cache_bootstrap table, there is a row with cid value of module_implements, and it's data value is a very large serialized string.  When unserialized, it is an array of the form

'hook_name' => array('module1', 'module2', 'module3', ...)

The hook names have the hook_ beginning lopped off, so hook_block_info() will appear as block_info. I believe the value is the list of modules which implement that hook, so...

'block_info' => array('views', 'webform', 'my_module')

Means that the following hooks are registered and should be fired:
views_block_info()
webform_block_info()
my_module_block_info()

Comment: I'm not quite sure offhand what would be the _best_ way to accomplish what you're trying to do--I'm not sure if there's a way to force hooks to always run (let alone only on admin pages) which only run during cache rebuild by design.

I suspect you need to implement a different hook, and figure out how to get the link definitions which are passed into the hook you're currently using. `hook_init()` runs on every non-cached page load and would accomplish that part. Bear in mind that implementing hook_init is discouraged for performance reasons.
Comment: I think this could be validated as The One True Hook Cache to Rule Them All by finding a hook you _know_ is firing, using php code to select the serialized strong from the db, unserialize, unset the necessary value for that hook, reserialize it and update the `cache_bootstrap` table with the new serialized value, then confirm the hook is no longer firing.
Comment: How do we bust the hook cache from within the function? I have `hook_menu_links_discovered_alter()` in a custom module that's trying to add a link to the admin toolbar. And when I put a `kint()` statement in the hook, it only fires when I clear the cache, and I need it to fire every (administrator) page load.
Answer: If you're running drush, you could try fn-hook. That will print out a list of all the modules that are using a given hook. At the very least this will tell you if the Drupal thinks the module is using the hook
Comment: The question is "Is there someplace in the database or somewhere else where I can see if my hook is registered?"
Comment: Is drush actually storing them, or just looking them up from the modules (or 'somewhere else') when this command is run? I am looking for authoritative places where hooks are stored.
Comment: It uses module_implements to get a listing of the hooks, which intern is checking the cache tables. So as you were looking to avoid using that function, my answer is no longer valid for you. Though it might be useful for someone in the future.

Where are hooks stored/cached?


How to pass information between beans in JSF 2?

Question: I have a scenario and dont have a clear idea for this to work yet.
Here's the example scenario :

I have a myView.xhtml file that can be displayed as a window popup or a primefaces dialog popup from 2 other container xhtml, let's say container1.xhtml and container2.xhtml (the myView.xhtml is included with something like this ? <ui:include src="myView.xhtml" />)
And, we also have the view-scoped beans, let's call them myViewBean, container1Bean and container2Bean
container1Bean has the property of transactionDate, and container2Bean has a property of transDate
myViewBean's @PostConstruct method will query the database based on a parameter of type date.
On container1.xhtml, if a user clicks on a button that will popup the myView.xhtml, container1Bean should be able to provide it's transactionDate to the myViewBean, and myViewBean will be able to query based on it in the @PostConstruct method.
On container2.xhtml, if a user clicks on a button that will popup the myView.xhtml, container2Bean should be able to provide it's transDate to the myViewBean, and myViewBean will be able to query based on it in the @PostConstruct method.

I was thinking about using @Inject Container1Bean and @Inject Container2Bean in the MyViewBean, so that inside MyViewBean, i can get the transactionDate of container1Bean or transDate of container2Bean. To decide which container bean is active is to check which one is not null.
But what if the container beans grows, there could be other container beans that make use of the MyViewBean, and the @Inject ContainerXXBean will grow in numbers inside the MyViewBean. There must be other solutions for this.
Please share ideas on how to accomplish this .. Thank you ! :-)
Thank you !
Answer: If you want to access only the contents of the other beans you can do that programmatic.
Get the current instance of the FacesContext inside from one bean. And using that context you can grab the instance of other beans.
See this illustration. As per the title of your question, you want to some information between beans. You can accomplish this by calling the other bean's public methods, which may be specifically created for this purpose. (setters-getters).
Comment: Thanks, that's quite a list of ways to get a bean form the FacesContext. But i think my situation here is not about the fetching the bean by name, since i could do with the @Inject. It's more to the how can i make a reusable view/bean that can somehow be parameterized from  another containing view. Im begininning to think about using a JSF 2 composite component for this. hehe ..
Answer: If container1Bean, myViewBean and container2Bean share some properties, why not putting them in a new bean ? (let's call it sharedBean, but I'm sure you'll find a better name adapted to your case). You could then inject sharedBean using @ManagedProperty in every dependent bean. Let's just try not to have circular references.
I'll also suggest to review your architecture. Are you sure you need all thoses beans, partitionned exactly like this? This sounds like something which will be difficult to maintain.
Comment: Thank you for your suggestion. And im very very interested in your suggestion on reviewing the architecture. I have a basic thinking that every page will have it's own view-scoped-bean to handle each page's action. And also, some pages are reusable and can be viewed from other pages, and can be parameterized (just like the example, that viewBean can have different query results based on the params). Do you have any suggestions on how to partition the jsf beans ? I've been wondering also about the best practice for this. Thanks !
Comment: I'd just say, make a small diagram on paper. You could share a bean for multiple views, it helps sometimes. Also, if multiple views on your diagram share too much info, just make them share the bean. For the rest, just ask yourself whether you should have views with parameters (should it be possible to have an influence on the view by changing the url?) or if you should just call methods (with parameters, which could be objects) to navigate.


Date range display in views using PHP

Question: How do I display date ranges for Value1 and Value2 in the following format where value2 is display as the difference between Value1 and Value2 expressed in days. I'd like to rewrite the results of a view field using PHP code.
Value1=1-Jan-2013
Value2=6-Jan-2013
i.e. result expected:
1-Jan-2013 +5d

Answer: <?php
$datetime1 = date('d-M-Y', strtotime(value1));
$datetime2 = date('d-M-Y', strtotime(Value2));
$interval = date_diff($datetime1, $datetime2);
$result = $datetime1 . ' ' . $interval;

result will be
1-Jan-2013 +5d

Date range display in views using PHP


What is the copy function in web console in Firefox 60.5.1?

Question: Seem the copy function in global scope but it is not in the window scope.
I run on Firefox 60.5.1 Debian Stretch.
Is any documentation for the global copy function?
>> copy
function ()
>> window.copy
undefined

Answer: This is part of the console utilities API* and can only be called from the console, therefore it is not part of the window scope, copy is defined as:

copy(object) copies a string representation of the specified object to the clipboard.

*Yes, that is from the Chrome docs, I could not find docs for Firefox, however they usually behave the same.


Passenger Enterprise edition - "Mass Deployment" clarification

Question: We're thinking about purchasing a license for Passenger Enterprise, and I'm looking for a better explanation about the "Mass Deployment" feature in Passenger Enterprise Edition.
Say you have Rails 3 applications -

my_blog
news_site
online_resume

These all get dropped into a directory on the server, and we can point Passenger to look at that directory and serve up those applications.
So my question is: How does nginx come in to play here? Is the nginx configuration for that virtual server completely ignored? We often need to upgrade nginx config for things like rewrites, as well as some passenger configuration (min_instances, for example).
Answer: Mass Deployment is a feature inside Phusion Passenger Standalone (in Enterprise). Standalone creates Nginx virtual hosts for all those apps. You can specify options through the command line, see --help.


to loop two arrays in the ng-repeat

Question: I have two arrays one in recommendation Name which I like to show as a hyperlink and second is recommendation ID which I want to pass in the URL, but in Html, if I am using ng-repeat on the recommendation Name then I cannot see the value of recommendation Id and vice -versa.
My codes are:
Controller.js:
    function viewRecommendationCtrl($scope,$http,$state)
    {
        $http.get('/viewRecommendations')
        .success(function(data){
            $scope.recoName = data.recoName;
            $scope.recoId = data.recoId;
            console.log($scope.recoName);
            console.log($scope.recoId);
    })
}

HTML code is:

{{reco}}

The data format is: for recoName
0: "Great"
1: "UTKARSH"
2: "Physical working place for R&D and manufacturting team"
3: "Define a standard operating process (SOP) for R&D team"
4: "Legal Compliance as per the Government of India (GOI) rules"

for recoId:
0: {low: 4, high: 0}
1: {low: 5, high: 0}
2: {low: 1, high: 0}
3: {low: 2, high: 0}
4: {low: 3, high: 0}

So what should be the code?
Thanks
Comment: Can't you incorporate your recoId in your recoName like [{recoName: "Great", recoId:[{low:4,high:0}]}].... like this?
Comment: @iswar it can be in one array which defines the both recoName and recoId
Comment: is not the best practice but, if you recoName is same index as recoId, you can use the property `$index` of ng-repeat to get the recoId. If you can make in a single array like Iswar suggested it would be way easier
Answer: You get the index of the array $index.

{{recoId[$index].low}}

Comment: This is working, but I have to show the value in the low field of the recoId, so if I am using the recoId.low[$index] is not working.
Comment: Bind the value as `recoId[$index].low`. I have edited the answer

to loop two arrays in the ng-repeat


Probability of at least one unique outcome

Question: We have n actors. Each actor chooses from n*2 actions. How can I calculate the probability that at least one actor will choose a unique outcome?
For example, say we have 5 pickup artists in a town with 10 bars. Each PUA chooses a bar at random. What are the odds that at least one PUA will have a bar to himself/herself?
This is relevant to some work I'm doing on scheduling in a distributed system. I know that the relevant equation should probably start with $\binom{n + 2n -1}{n}$, but then what?
Answer: This is not a simple calculation in general, though the probability will be almost 1 if $n$ is any substantial size.
To take your example of five people and 10 bars, there are $10^5$, i.e 100,000 possible equally-likely distributions.  All of these will have at least one person alone, except the 10 cases where all five are in a single bar or the 900 cases where three are in a particular bar and two in another.  That leaves 99090 distributions which satisfy your condition, more than 99%.
Note that 99090 is not divisible by $\binom{5 + 10 - 1}{5} = 2002$.
For $n=1$ to $6$, the fractions seem to be $\frac{2}{2},$ $\frac{12}{16},$ $\frac{210}{216},$ $\frac{3920}{4096},$ $\frac{99090}{100000}$ and $\frac{2962872}{2985984}$, where the denominator in each case is $(2n)^n$. I would expect the probabilities then to keep rising as $n$ increases beyond 6.
Comment: +1 You can obtain the distribution with an (efficient) dynamic program.  Let $p(n,j,k,m)$ be the probability of $j$ isolated actors and $k$ non-isolated actors choosing from $m$ actions.  Adding one more actor gives the recursion $p(n+1,j,k,m)$ = $p(n,j,k,m)(k/m)$ + $p(n,j+1,k-1)((j+1)/m)$ + $p(n,j-1,k)(m-j-k+1)/m$.  Of course $p(n,1,0,m) = 1$, letting us start the recursion.  Computations simplify when you base them on $m^{n-1}/(m-1)^{[j+k-1]}p(n,j,k,m)$: the values are integers independent of $m$.  ($x^{[j]}$ is the factorial power $x(x-1)\cdots(x-j+1)$.)
Answer: Below, I briefly sketch out one "back of the envelope" calculation, which is in no way optimal, but does at least show that the probability converges to one exponentially fast. Before getting into the (gory) details, we give the answer.
$$
\Pr(\text{at least one actor chooses a unique outcome}) \geq 1 - (e/4)^{n/2} .
$$
As mentioned before, comparing this result to the above for small $n$ shows that the result is not super sharp. But, it does provide a guarantee for all $n$ and shows that as $n$ grows, the probability goes to 1 at least exponentially fast. (The actual rate is probability more like $e^{b n \log n + o(n)}$).

The idea is to turn the problem into an occupancy or coupon-collecting problem. If you want a more precise answer, you can refer to the (extensive) literature on these subjects, but to prove a faster rate takes messier analysis.
Let $U_n$ be the proportion of actors that choose a unique outcome (when we have $n$ total actors), which we use below. (Technically, the analysis below is for even $n$, but that's a minor point. The same result holds for odd $n$; just replace $n/2$ by $(n-1)/2$ and $3n/2$ by $(3n+1)/2$ in the relevant places.)
Restating the problem in terms of balls and bins. We have $n$ balls and $2n$ bins. The "balls" are the "actors" and the "bins" are the possible outcomes. We want to know the probability that at least one bin has only a single ball in it. The probability that any particular bin has only one ball is $\left(1 - \frac{1}{2n}\right)^n$. So, the expected proportion of balls in a bin by themselves (i.e., actors that choose a unique outcome) is
$$
\mathbb{E}(U_n) = \left(1 - \frac{1}{2n}\right)^n \to e^{-1/2} \approx 60.65\%
$$
This gives us pretty good hope that the probability of at least one ball being in a bin by itself is (very) high.
To get a bound on this probability, note that if each of the occupied bins has at least two balls in it, then at most $n/2$ bins can be occupied. So
$$
\Pr(\text{no bin has exactly 1 ball}) \leq \Pr(\text{no more than n/2 bins are occupied})
$$
Now, if no more than $n/2$ bins are occupied, then there must be some subset of $3n/2$ bins that are all empty. There are ${2n \choose 3n/2} = {2n \choose n/2}$ such subsets, and so by the union bound, we get
$$
\Pr(\text{some subset of 3n/2 bins is empty}) \leq {2n \choose n/2} \left(1 - \frac{3n/2}{2n}\right)^{n} = {2n \choose n/2} 4^{-n}
$$
To finish up, we use the elementary inequality
$$
{2n \choose n/2} \leq \left(\frac{2n e}{n/2}\right)^{n/2} = (4e)^{n/2} .
$$
Putting it all together, we get
$$
\Pr(\text{no bin has exactly 1 ball}) \leq (4 e)^{n/2} 4^{-n} = (e/4)^{n/2} .
$$
Hence,
$$
\Pr(\text{at least one actor chooses a unique outcome}) \geq 1 - (e/4)^{n/2} .
$$


Are mappings $f: \mathbb{R} \to \mathbb{R}$ with $|f'(x)| < 1$ contractions?

Question: This is an extension of this question found here. Can we safely assume that all differentiable maps $f:\mathbb{R} \to \mathbb{R}$ with $|f'(x)| < 1$ are contraction mappings?
For clarity, given a metric space $M$, a contraction mapping is defined as a continuous map $f: M \to M$ such that for some constant $k < 1$ and all $x, y \in M$, $$d(fx, fy) \leq kd(x,y)$$
Also, contraction mappings are contrasted with weak contractions, which are functions similarly defined, but only with the requirement that $$d(fx, fy) < d(x,y)$$
Progress so far: I've tried constructing counterexamples that have derivatives that approach 1 asymptotically but to no avail. Most of the counterexamples require that the function $f$ contain $log$ or $\frac{1}{x^n}$ terms, which are not defined on all of $\mathbb{R}$, and so contradict the requirement that $f:\mathbb{R} \to \mathbb{R}$.
Comment: Good question. $\;\!$
Answer: By the mean value theorem, any such function is a weak contraction.
To find an example which is not a (strong) contraction, just pick any continuous function $g : \Bbb{R} \to (-1, 1)$ which satisfies $\lim_{x\to\infty} g(x) = 1$. Then
$$f(x) = \int_{0}^{x} g(t) \, dt $$
will serve as a counter-example. For example, if we choose $g(x) = x^2/(1+x^2)$ then
$$f(x) = x - \arctan x $$
is a counter-example by the mean value theorem.
Comment: @AnanthRaviKumar, That is exactly what I am claiming: there exists a differentiable function $f : \Bbb{R} \to \Bbb{R}$ with $|f'| < 1$ which is *not* a contraction.
Comment: Wait. In this case, wouldn't the Lipschitz constant be 1, since the limit of the $\frac{x^2}{1+ x^2}$ is 1? Wouldn't that in turn imply that this is NOT a contraction map?


Moderated regression: Why do we calculate a *product* term between the predictors?

Question: Moderated regression analyses are often used in social sciences to assess the interaction between two or more predictors/covariates.
Typically, with two predictor variables, the following model is applied:
$Y = β_0 + β_1*X + β_2*M + β_3*XM + e$
Notice that the test of moderation is operationalized by the product term $XM$ (the multiplication between independent variable $X$ and moderator variable $M$). My very fundamental question is: why do we actually calculate a product term between $X$ and $M$? Why not, for instance, the absolute difference $|M-X|$ or just the sum $X + M$?
Interestingly, Kenny alludes to this issue here http://davidakenny.net/cm/moderation.htm by saying: "As will be seen, the test of moderation is not always operationalized by the product term XM" but no further explanation is given. A formal illustration or proof would be enlightening, I guess/hope.
Answer: A "moderator" affects the regression coefficients of $Y$ against $X$: they might change as values of the moderator change.  Thus, in full generality, the simple regression model of moderation is
$$\mathbb{E}(Y) = \alpha(M) + \beta(M)X$$
where $\alpha$ and $\beta$ are functions of the moderator $M$ rather than constants unaffected by values of $M$.
In the same spirit in which regression is founded on a linear approximation of the relationship between $X$ and $Y$, we may hope that both $\alpha$ and $\beta$ are--at least approximately--linear functions of $M$ throughout the range of values of $M$ in the data:
$$\eqalign{
\mathbb{E}(Y) &= \alpha_0 + \alpha_1 M + O(M^2) + (\beta_0 + \beta_1 M + O(M^2))X \\
&= \alpha_0 + \beta_0 X + \alpha_1 M + \beta_1 MX + O(M^2) + O(M^2)X.
}$$
Dropping the nonlinear ("big-O") terms, in the hope they are too small to matter, gives the multiplicative (bilinear) interaction model
$$\mathbb{E}(Y) = \alpha_0 + \beta_0 X + \alpha_1 M + \beta_1 MX.\tag{1}$$
This derivation suggests an interesting interpretation of the coefficients:  $\alpha_1$ is the rate at which $M$ changes the intercept while $\beta_1$ is the rate at which $M$ changes the slope.  ($\alpha_0$ and $\beta_0$ are the slope and intercept when $M$ is (formally) set to zero.)  $\beta_1$ is the coefficient of the "product term" $MX$.  It answers the question in this way:

We model the moderation with a product term $MX$ when we expect the moderator $M$ will (approximately, on average) have a linear relationship with the slope of $Y$ vs $X$.

Of interest is that this derivation points the way towards a natural extension of the model, which might suggest ways to check goodness of fit.  If you are not concerned with nonlinearity in $X$--you either know or assume that model $(1)$ is accurate--then you would want to extend the model to accommodate the terms that were dropped:
$$
\mathbb{E}(Y) = \alpha_0 + \beta_0 X + \alpha_1 M + \beta_1 MX + \alpha_2M^2 + \beta_2 M^2X.
$$
Testing the hypothesis $\alpha_2=\beta_2=0$ evaluates the goodness of fit.  Estimating $\alpha_2$ and $\beta_2$ could indicate in what way model $(1)$ might need to be extended: to incorporate nonlinearity in $M$ (when $\alpha_2 \ne 0$) or a more complicated moderating relationship (when $\beta_2 \ne 0$) or possibly both.  (Note that this test would not be suggested by a power series expansion of a generic function $f(X,M)$.)

Finally, if you were to discover that the interaction coefficient $\beta_1$ were not significantly different from zero, but that the fit is nonlinear (as evidenced by a significant value of $\beta_2$), then you would conclude (a) there is moderation but (b) it is not modeled by an $MX$ term, but instead by some higher-order terms beginning with $M^2X$.  This might be the kind of phenomenon to which Kenny was referring.
Answer: If you use the sum of predictors to model their interaction, your equation would be:
$$
\begin{eqnarray}
Y &=& \beta_0 + \beta_1X + \beta_2M + \beta_3(X + M) + e\\
  &=& \beta_0 + \beta_1X + \beta_2M + \beta_3X + \beta_3M + e\\
  &=& \beta_0 + (\beta_1 + \beta_3)X + (\beta_2 + \beta_3)M + e \\
  &=& \beta_0 + \beta_1'X + \beta_2'M + e
\end{eqnarray}
$$
where $\beta_1'=\beta_1+\beta_3$ and $\beta_2'=\beta_2+\beta_3$. Therefore, your model would have no interaction at all. Clearly, this is not the case with product.
Recall the definition of the absolute value:
$$
|X-M| = \begin{cases}
          X-M, & X \geq M\\
          M-X, & X < M
        \end{cases}
$$
Although you can reduce the model $\beta_0 + \beta_1X + \beta_2M + \beta_3|X-M| + e$ to the one with only $X$ and $M$ terms, using the def. of $|X-M|$, the absolute value is a "specialized form of moderation that is unlikely to be realistic in many situations", as pointed out in the comment below.
Comment: Actually, including an $|X-M|$ term is demonstrably a form of moderation: the value of $M$ changes $\beta_2$.  It is, however, a limited, specialized form of moderation that is unlikely to be realistic in many situations.  It is not correct to say that such a model has "only main effects."
Comment: Yes, you are right, $|X-M|$ is a form of moderation, I got carried away by transformation and will edit the answer accordingly. Thanks for pointing this out.
Comment: @Milos: Your example about the sum of predictors was an eye-opener, a somewhat embarrassing one, I must say because I should have already realized the mathematical implications ;) whuber: As far as I understand it, the absolute value is only useful when both predictor variables are measured in same units (e.g. two psychometric tests, using the same metric, such as z-scores or T-scores). The absolute difference between X and M is a *useful* metric, although not the only possible one (i.e. the prodcut term could also be used).
Answer: You won't find a formal proof for using multiplicative moderator. You can support this approach by other means. For instance, look at the Taylor-MacLaurin expansion of a function $f(X,M)$:
$$f(X,M)=f(0,0)+\frac{\partial f(0,0)}{\partial T} T+\frac{\partial f(0,0)}{\partial M} M+\frac{\partial^2 f(0,0)}{\partial T\partial M} TM
+\frac{\partial^2 f(0,0)}{2\partial T^2} T^2
+\frac{\partial^2 f(0,0)}{2\partial M^2} M^2\dots$$
If you plug a function of this form $f(X,M)=\beta_0+\beta_XX+\beta_MM+\beta_{XM}XM$ into the Taylor equation, you get this:
$$f(X,M)=\beta_0+\beta_XX +\beta_MM +\beta_{XM}XM$$
So, the rationale here is that this particular multiplicative form of the moderation is basically a second order Taylor approximation of a generic moderation relationship $f(X,M)$
UPDATE:
if you include quadratic terms, as @whuber suggested then this will happen:
$$g(X,M)=b_0+b_XX +b_MM +b_{XM}XM+b_{X2}X^2 +b_{M2}M^2$$
plug this into Taylor:
$$g(X,M)=b_0+b_XX +b_MM +b_{XM}XM  +b_{X2}X^2 +b_{M2}M^2$$
This shows that our new model $g(X,M)$ with quadratic terms corresponds to a full second order Taylor approximation, unlike the original moderation model $f(X,M)$.
Comment: Since the basis of your argument is the Taylor expansion, why did you not also include the other two quadratic terms $X^2$ and $M^2$?  True, they are not forms of moderation, *but their inclusion in the model usually will affect $\beta_{XM}$*.
Comment: @whuber, I decided to keep the post short - that's the main reason. Otherwise, I started writing about my preference to include second order terms whenever you have a cross term, then cut it out.


Problemas ao exportar do PHP para CSV

Question: Estou com problema na hora de visualizar um arquivo csv. A minha intenção é que possa usar o comando do Excel "dados para coluna" e fique linha a linha, mas o arquivo tem pulado linha impossibilitando. O código foi feito baseado em um outro exemplo aqui mesmo postado por um adm.
<code>     date_default_timezone_set('America/Sao_Paulo');

ini_set('memory_limit', '12000M');
 require_once($_SERVER['DOCUMENT_ROOT']."/administrator/lib/connection.php");

//echo "<script type=\"text/javascript\"> window.open(\"http://www.tometoo.com.br/generateCSV2.php\", \"_blank\")</script>";

        $PDO = Database::Connect();

        $SQL = "SELECT idpost, idcomment, cm_id_author, pg_name, ps_date, cm_date, ps_message, cm_name_author, cm_message, pss_likes, pss_shares, pss_comments, cms_like, cms_reply
        from fb_post
        INNER JOIN fb_pssummary ON pss_idpost = idpost
        INNER JOIN fb_page ON ps_idpage = idpage
        INNER JOIN fb_comment ON cm_idpost = idpost
        INNER JOIN fb_cmsummary ON cms_idcomment = idcomment
        where ps_date between '2016-09-01 00:00' and '2016-09-01 23:59:59'
        ORDER BY ps_date ASC";

        $SQL = $PDO->prepare($SQL);

        $SQL->execute();

        $result = $SQL->fetchAll(PDO::FETCH_ASSOC);

        function array_para_csv(array &$array)
        {
           if (count($array) == 0) {
             return null;
           }
           ob_start();
           $df = fopen("php://output", 'w');
           fputcsv($df, array_keys(reset($array)));
           foreach ($array as $row) {
              fputcsv($df, $row);
           }
           fclose($df);
           return ob_get_clean();
        }

        function cabecalho_download_csv($filename) {
    // desabilitar cache
    $now = gmdate("D, d M Y H:i:s");
    header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
    header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
    header("Last-Modified: {$now} GMT");

    // forçar download
    header("Content-Type: application/force-download");
    header("Content-Type: application/octet-stream");
    header("Content-Type: application/download");

    // disposição do texto / codificação
    header("Content-Disposition: attachment;filename={$filename}");
    header("Content-Transfer-Encoding: binary");
}

cabecalho_download_csv("setembro_1_1M_1_parte" . date("Y-m-d") . ".csv");
echo array_para_csv($result);
</code>
a saída tem ficado assim no excel
229151370439618_1206843959337016,1206843959337016_1206850609336351,1063115217101837,CartaCapital,"2016-09-01 00:15:31","2016-09-01 00:27:42","VIOLÊNCIA POLICIAL
O centro de São Paulo se tornou uma verdadeira praça de guerra hoje a noite, a partir do momento que Polícia Militar, resolveu dispersar a manifestação contra o golpe a partir do meio dela. O efeito, foi a dispersão de manifestantes para diversos cantos e uma verdadeira caça  promovida pelos policiais a base de bombas e balas de borracha.
Segundo informações, uma jovem está neste momento no Hospital da Clínicas com a forte possibilidade de ter perdido a visão de um olho e um fotógrafo teve seu equipamento de trabalho quebrado e foi detido.
Até o momento, nem mesmos os advogados do fotógrafo foram informados sobre o motivo da detenção
Imagens por Tadeu Amaral
Golpe #Impeachment","Marco Antonio Camelo","Carta capital defende bandidos.",418,76,263,4,0
favor ignorar o conteúdo do facebook que não tem nada a ver com minha opinião. Como podem observar além da acentuação tem o problema das linhas.
Comment: Da uma olhada nesse post, eu respondo como ler/gravar  e visualizar o csv http://pt.stackoverflow.com/questions/118619/importar-analisar-e-extrair-dados-de-um-csv-com-php/118629#118629
Comment: Qual o fator de separação usado no arquivo `.csv`? Eu uso o ponto-e-vúrgula.
Comment: Essa é uma das partes da minha dúvida, como poderia colocar o delimitador , mas o estranho é ele pular linha, não criar uma única linha por retorno do while.
Comment: foi colocado um `\r\n` no fim de cada linha, mas, se não souber o fator de separação, não saberá como dividir corretamente o texto.
Comment: não coloquei o \r\n nem PHP_EOL pois essa função do PHP parece fazer isso, o delimitador que ta usando é a vírgula
Comment: Os separadores, quando tem texto, mais recomendados são ponto-e-vírgula e pipe. Sem contar que se está escolhendo a forma certa de abertura na própria planilha.
Comment: Olha, eu usei essa classe uma vez para criar um arquivo em excel https://github.com/PHPOffice/PHPExcel com base nesse exemplo : http://www.voltsdigital.com.br/labs/gerando-planilhas-excel-com-php/
Comment: Use a [biblioteca PHPExcel](https://phpexcel.codeplex.com/).  E pare de sofrer.
Comment: Obrigado a todos, e vou parar de sofrer! hahaha Aplicando a biblioteca aqui no projeto.
Answer: Uma solução para evitar este tipo de problema é através de uma biblioteca muito bem desenvolvida PHP Excel:
1) Após baixar a biblioteca PHP Excel
2) Basta utilizá-la da seguinte maneira a partir do seu código:
<code>date_default_timezone_set('America/Sao_Paulo');
ini_set('display_errors', 1);
error_reporting(-1); //mostra todos os erros (-1 ou E_ALL)
ini_set('memory_limit', '12000M');
require_once($_SERVER['DOCUMENT_ROOT']."/administrator/lib/connection.php");
require_once($_SERVER['DOCUMENT_ROOT']."/administrator/lib/PHPEXcel/Writer/PHPExcel.php");
require_once($_SERVER['DOCUMENT_ROOT']."/administrator/lib/PHPEXcel/Writer/Excel2007.php");

$PDO = Database::Connect();

$SQL = "SELECT idpost, idcomment, cm_id_author, pg_name, ps_date, cm_date, ps_message, cm_name_author, cm_message, pss_likes, pss_shares, pss_comments, cms_like, cms_reply
        from fb_post
        INNER JOIN fb_pssummary ON pss_idpost = idpost
        INNER JOIN fb_page ON ps_idpage = idpage
        INNER JOIN fb_comment ON cm_idpost = idpost
        INNER JOIN fb_cmsummary ON cms_idcomment = idcomment
        where ps_date between :initial and :final
        ORDER BY ps_date ASC";

$SQL = $PDO->prepare($SQL);
$SQL->execute([':initial'=>'2016-09-01 00:00', ':final'=>'2016-09-01 23:59:59']);

$result = $SQL->fetchAll(PDO::FETCH_ASSOC);

exportExcel("nome_do_arquivo", $result);

function exportExcel($filename, $result)
{
    $result = addHeader($result);
    $export = new PHPExcel();
    $cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_to_phpTemp;
    $cacheSettings = array(' memoryCacheSize ' => '8MB');
    PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);

    $export->setActiveSheetIndex(0)
            ->fromArray($result, null, 'A1');

    $xmlWriter = new PHPExcel_Writer_Excel2007($export);

    header("Pragma: protected"); // required
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: public", false); // required for certain browsers
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8');
    header("Content-Disposition: attachment;filename='{$filename}.xlsx'");
    header("Content-Transfer-Encoding: binary");
    $xmlWriter->save("php://output");
    exit();
}

function addHeader($value)
{
    $return = null;
    if (is_array($value)) {
        $header = array_keys($value[0]);
        $return[0] = $header;
        foreach ($value as $key => $row) {
            foreach ($row as $columnKey => $column) {
                $currentfindedKey = array_search($columnKey, $header);
                $return[$key][$currentfindedKey] = $column;
            }
        }
        array_unshift($return, $header);
    }
   return $return;
}
</code>
Comment: @IvanFerrer seu link foi trocado do Codeplex pro GitHub pois o primeiro está sendo desativado. Está sendo feito um esforço conjunto pela mudança: https://pt.meta.stackoverflow.com/questions/6317/codeplex-ser%C3%A1-desativado-no-dia-25-12-2017-que-tal-atualizarmos-os-links?cb=1. Caso o link que usei foi inapropriado, favor escolher um que o seja mas que não venha do Codeplex. Grata.
Comment: Valeu mesmo!!!! Vou fazer o teste aqui agora.
Comment: Olá Ivan, fiz os testes aqui e constatei que uso essa lib em meu template. O problema que encontro nela é em gerar um quantidade grande de linhas. No meu caso, como atuo com big data, preciso gerar alguns CSV`s que chegam a 20gb, algo perto de 8M de linhas. Com essa lib eu gero até umas 20 mil linhas sem problemas, após isso, fica muito tempo de processamento, mesmo em segundo plano leva em torno de 2 horas pra começar o download, o que inviabiliza o relatório, no CSV ao menos o download é imediato. Se lembrar de algo que possa compartilhar, fico grato!!! Abs
Comment: Mas conseguiu o que desejava?
Comment: @IvanFerrer reverti para a edição da Carla, o Codeplex, como explicado no link citado, esta sendo descontinuado.

Problemas ao exportar do PHP para CSV


Uninstalling Exchange Server 2013 after installer crash

Question: I installed Microsoft Exchange server on a blank 2008r2 server a few days ago. After installing Exchange I had to remove and re-enable the Active Directory Domain Services role to fix another issue. When uninstalling Exchange earlier today the uninstaller crashed and I had to restart it. After starting the uninstaller I now get the error message:
Error:

The following error was generated when "$error.Clear();

Set-MailboxServer -Identity $RoleFqdnOrName -CalendarRepairWorkCycle $null -CalendarRepairWorkCycleCheckpoint $null

" was run: "The operation couldn't be performed because object 'PLSERVER.mydomain.co.uk' couldn't be found on 'PLSERVER.mydomain.co.uk'.".

I really just want to uninstall Exchange server in any way possible. I am not quite sure how to tackle this error message though, especially since I am very new to Windows server (I come from a *nix background).
Comment: You should never run *anything* on a DC that isn't Directory Services or DNS. In very small environments, sometimes it's unavoidable, but large packages like Exchange/MSSQL/SharePoint/etc should never be on a DC.
Comment: You're running Exchange and AD on the same server?
Comment: Yes, I was just trying to determine whether Exchange suited my clients needs. In production would they always be on separate machines?
Comment: Yes. Exchange is a complex beast suited for its own server entirely.
Comment: Thanks that useful to know. At least if something like this happens you can then nuke it and start again.
Answer: I've been through a manual uninstall of Exchange. It sucked. It required a call to Microsoft Support and many hours on the phone with them.
The gist of it was that you get the install media and find all of the MSIs, right click on each and select uninstall, lather rinse repeat. Then, manually delete all Exchange references from the registry.
That said, this is entirely unsupported outside of the direction of Microsoft. I really recommend opening a ticket with them.
Comment: At that point it may be faster to just wipe the machine and start over again if it's not a production server.
Answer: There's no need to uninstall if you don't want to.
All you should do is to run repair.
Given the Exchange configuration intact in the AD, the installer will repair the "damaged" installation.
If you really need, run uninstaller after it, it should complete successfully.


Compare which of two groups is MORE similar to a third group?

Question: I know I can use an ANOVA (+ post-hoc tests) to determine the equality (or inequality) of three groups:

(i.e., H0: each of 3 means are equal; H
A: at least 1 of 3 means is not equal).

However, how do I determine which of 2 group means is more similar to a third group's mean?
Obviously I could do this using arithmetic by comparing the means of each group

i.e., something like: [(meanA - meanC)]  <  [(meanB - meanC)],

but I'm looking for a formal statistical test to answer this question.
Update:
A formal hypothesis might look something like:

H0: [meanA - meanC] = [meanB - meanC]
HA: [meanA - meanC] > [meanB - meanC]

(However, he hypothesis doesn't necessarily need to take that mathematical form.)
EXAMPLE:
Are the average heights of cherry trees or maple trees closer to the average height of apple trees?
Comment: @Dave I have a hard time with KL divergences because--unless I haven't correctly apprehended your proposal--first you need to perform some kind of continuous density estimation based on the data and, without huge amounts of data, I believe the resulting estimates of KL divergences to be unstable and sensitive to the choice of density estimator.  I am more inclined to explore with a client *which aspect(s) of the distributions are important for their study* so we can choose (or develop) procedures suitable for comparing (and discriminating) those particular features.
Comment: ANOVA is not used to show *equality* but rather *inequality* of group means. As such, the question is not easy to follow.
Comment: @Dave the implicit sense of "similar" in an ANOVA context *must* be in terms of differences of means.  Like Michael M, though, I find it hard to follow this question because it is predicated on a misinterpretation of ANOVA and also because "which of two groups is similar to a third" is ambiguous: exactly what hypothesis is being proposed here?
Comment: @whuber I took the ANOVA comment as an analogy, not that means are the only way that groups 1 and 2 could differ from group 3. Anyway, yes, we definitely need additional clarification about what comparison is interesting. However, what would you think about comparing KL divergences if the question isn't just about similarity of means but of the distributions overall?
Comment: One suggestion I have is the Kullback–Leibler divergence, but it will depend immensely on what you consider similarity to mean. Please elaborate on what you want to be similar. Means? Means and variances? Medians and skewness? Entire distributions?
Comment: If you find a scale on which variability is about equal, your question may well answer itself if you look at the distributions (meaning, above else plot the data). I don't know how serious cherry, apple and maple tree heights are as an example, but it's the only one in sight. I would expect mild skewness at least of each distribution. and heteroscedasticity collectively, but would also expect some transformation between square root and logarithm to work quite well in making broad contrasts between distributions as clear as possible.
Answer: If you randomly draw one individual from each group, you can calculate the value [A - C] - [B - C]. If you repeat this a number of times (with replacement), you will generate a distribution of [A - C] - [B - C].
This distribution captures the information you are interested in. If its mean value is >0, A is closer on average to C. If its mean value is <0, B is closer on average to C. You can also calculate confidence intervals and p-values. The p-values correspond to the % of the distribution values that are below or above zero (depending on whether the mean is positive or negative).
Answer: Some ideas:  I will write a formal model in ANOVA style using normal assumptions, but that part can surely be relaxed. So let $Y_{ij}$ be independent observations, $Y_{ij} \sim \mathcal{N}(\mu_i, \sigma^2)$ for $j=A,B,C$, $i=1, \dotsc, n_j$. I will measure "similarity" of the distributions by the absolute value of the difference of means, so define
$$
   \delta_A=\mu_A-\mu_C, \delta_B=\mu_B-\mu_C
$$ and then our interest or focal parameter as
$$ \Delta=\delta_A-\delta_B.  $$
For a fast solution (which also avoids the normality assumption) I would use bootstrapping to construct a confidence interval for $\Delta$. But that assumes a reasonably large sample size.  A more principled (and maybe better) solution would be to construct the profile likelihood function for $\Delta$, and get a confidence interval from that. See for instance Constructing confidence intervals based on profile likelihood.
Answer: This is a nice question. If you are using STATA, things are simple.
You first run your AN(C)OVA including your factor variable (of 3 groups, say A, B, C) and any covariates. Then, you calculate contrasts of margins (with say C as the reference group), i.e. A-C and B-C with respective p-values (unadjusted or adjusted for multiple testing). This is implemented with various commands: contrast; margins (factor v.), contrast; margins r.(factor v).
Finally, there is the user-defined command 'mlincom' which allows for comparisons (i.e. contrasts) of previously calculated marginal contrasts, e.g. mlincom 2-1.
As simple as that. Look up all commands in STATA help files. Also have a look at https://xiangao.netlify.app/2019/04/22/marginal-effects-in-margins/.
I hope this was helpful.


Responsive grid for Onsen UI

Question: Unfortunately Onsen UI does not have a responsive grid for placing blocks on screens of various sizes. What grids can you recommend for use with Onsen UI? I have experience with Bootstrap but this library is too big to use it in a project for a responsive grid only. I've explored some other grids, but unlike Bootstrap, they can not hide some blocks on small screens or change their order (just make a stack instead of a line). Does anyone have a positive experience with a responsive grid for Onsen UI?
Answer: Skeleton is a well established very lightweight grid which might fit your needs.
Out of the box their grid system collapses to a single column on mobile, it has a limited number of helper classes and I found this source which lists plenty of push and pull mixins if you need more control over ordering of your columns. You could probably pick and choose just the one's you need. eg
/* Push & Pull */
    .container .push-by-one                   { left: 60px;  }

I started a codepen based on some code from the Skeleton site which you can play with: https://codepen.io/panchroma/pen/JNXoVP
Update

if I have 3 colums I can't create this screen layout: large screen:
  column1 5/12, column2 5/12, column3 2/12; medium screen: column1 7/12,
  column2 5/12, column3 hidden; small screen: column1 100%, column2 100%
  on the next line, column3 hidden. I'm right?

This is no problem with some media queries and a little custom CSS. If you check out my updated codepen you'll see that I'm hidding col 3 with display:none; and display:block; at different viewports.
To change the width of column 1 I inpspected the Skeleton CSS and have used its rule for 7/12 grid to overide the width for the 5/12 grid
HTML

  Skeleton: Responsive CSS Boilerplate

Column 1
5/12 large screen, 7/12 med screen, 100% small

Column 2
5/12 large & medium screens, 100% small

Column 3
2/12 large screen, hidden medium and small screens

CSS
/* Mobile first queries */
 .hidden-md{
   display:none;
 }

/* Larger than mobile */
@media (min-width: 400px) {}

/* Larger than phablet */
@media (min-width: 550px) {}

/* Larger than tablet */
@media (min-width: 750px) {}

/* Larger than desktop */
@media (min-width: 1000px) {}

/* Larger than Desktop HD */
@media (min-width: 1200px) {}

/* Custom helper class */

@media (min-width: 750px) {
  .hidden-md{
      display:block;
    }
}

/* Custom Grid Width */
@media (min-width: 550px) and (max-width: 749px) {
  .five.columns.overide{
     width: 56.6666666667%;
  }

}

Another Update

My dream - to find lightweight CSS grid with Bootstrap functionality
  :)

For min file size it might be hard to match Skeleton + some hand-rolled CSS.
One other option I can think of though is create a regular Bootstrap site then run it through UnCSS.
I've done this a handful of times with Bootstrap based sites. I had mixed success on dynamic CMS sites, really good results on less complex static sites and got an 80-90% reduction in the CSS file size.
There are a number of ways to use UnCSS. I used this Github code with Grunt and Node. I see there's also an online resource.
Good luck in your hunt!
Comment: Thanks for answer! But as I see - it is impossible with Skeleton to change width or hide some columns for small screens?
I.e. if I have 3 colums I can't create this screen layout:
large screen: column1 5/12, column2 5/12, column3 2/12;
medium screen: column1 7/12, column2 5/12, column3 hidden;
small screen: column1 100%, column2 100% on the next line, column3 hidden.

I'm right?
Comment: Hi @David , thanks for update! Yes I know that we can use CSS for these tricks. But Bootstrap grid have predefined classes for these cases (for example: `hidden-xs` for hide column on extrasmall screens, `col-lg-5` and `col-md-7` for define different width on the large and medium screens  etc.). My dream - to find lightweight CSS grid with Bootstrap functionality :)

Responsive grid for Onsen UI


how do I access raw URL from a File Field to render it in twig inside href?

Question: I have a "Our Staff" Content Type, that includes a field for uploading an individual's CV as a PDF:
field_cv_file

I have created a View for this Content Type, then added it to page via Blocks
The twig file I'm using to render/style this area is:
views-view-fields--our-staff-view--block-1.html

I'm having trouble with the URL for the File Field
I can render it as a PDF icon link like this:
{{ fields.field_cv_file.content }}

But I want to obtain the 'raw' URL to apply inside a href, something like this:
Download CV

This however is not working.
I've tried a few different ways of rewriting the code in href, but none are working.
how would I do this?
Comment: Ah, missed that part with views. For views fields take a look at https://drupal.stackexchange.com/questions/223731/how-can-i-access-raw-field-values-in-a-view-template
Comment: @AuxiliaryJoel Change the display type option for CV file field to display as 'URL to file'. I think right now you are displaying this as a generic file that is why it appears on front as a file. I assume you are using 'file' field type for 'CV file' field. I hope my comment helps you out.
Comment: Does this answer your question? [How do I get the raw field value in a twig template?](https://drupal.stackexchange.com/questions/228388/how-do-i-get-the-raw-field-value-in-a-twig-template)
Comment: @Hudri Unfortunately no. I don't get any results when I use any {{ content.... }} code as my twig is a fields twig. Example - this shows PDF icon /link: {{ fields.field_cv_file.content }}  but changing that code to be consistent with the accepted answer that you linked to does not produce anything. I'd like to grab the 'raw' url path in order to apply it as href.
Comment: @Hudri sorry they didn't work either. the accepted answer just threw a target id error on my site, and the other less popular asnwer ( 'strip tags'...) listed the PDF file name as a title like this "Name of PDF.pdf" but no actual path,
Comment: @ManishJain OK thanks Manish, and once I do that,  which if the methods mentioned throughout comments should I be using?
Comment: @AuxiliaryJoel didn't understand your last comment
Comment: @ManishJain what I mean is, I can render the field already, but I want to render it as a full path that I can apply as a href. I changed the file display from Generic File to File to URL to File as you suggested. I then placed it in a href like this: LINK TEXT. Unfortunately that does not work, the path is not correct and just links to a missing page
Comment: @AuxiliaryJoel Yes i understand. You just need to change the display type of field in view. It will automatically render pdf path in href.
Comment: ah thank you! I thought that changing it's display within the content type would reflect in the view as well. I've now changed it in view and it's working with the 'striptags' code. I'll edit my question now to describe what the solution was. Thank you.
Comment: @AuxiliaryJoel Its better if you change it's display from view only. As changing from content type would also impact on field node view.
Comment: @ManishJain Ok no problems Manish I've corrected that now.
Answer: In my case as I was using a views twig, and required the field's file path to be usable inside a href, I had to write it like this:
Download CV


Handling many outgoing TCP connections

Question: I was testing a server on EC2 with "High" network performance to check the maximum outgoing connections I could use on it. Without changing any settings, by opening around ~1000 threads which each sends a TCP request, after 10 minutes or so, I get 'connection refused' error which I am sure its the problem with my side as I know the target server doesn't see any errors.
I followed the instructions on this article which talks about TIME_WAIT and Ephemeral ports so I did these:

Increasing the number of ephemeral ports
Enabling tcp_tw_recycle and tcp_tw_reuse

By doing these two, I still get the errors but after a longer period like hours. In general, I wanna know how much an Ubuntu server with a specific hardware configuration can handle network traffic. How can I monitor the outgoing traffic so I can figure out what exactly went wrong?
Comment: Did u manage? I suck with same issue. Maximum 1000 outgoing connection from 1 host.
Answer: To monitor outgoing traffic look at the following tools: tshark, tcpdump, ettercap.
Also look at these settings:
root@server ~ # sysctl -A | grep -i wait
net.netfilter.nf_conntrack_tcp_timeout_fin_wait = 120
net.netfilter.nf_conntrack_tcp_timeout_close_wait = 60
net.netfilter.nf_conntrack_tcp_timeout_time_wait = 120
net.ipv4.netfilter.ip_conntrack_tcp_timeout_fin_wait = 120
net.ipv4.netfilter.ip_conntrack_tcp_timeout_close_wait = 60
net.ipv4.netfilter.ip_conntrack_tcp_timeout_time_wait = 120

Handling many outgoing TCP connections


Dúvida cast com ponteiro

Question:  while( ++idx <= fp_size)
 {
     byte current = buff[idx];
     int integer = 0 ;
     short shortint = 0 ;

     if(idx < fp_size - 3)
         integer = *((int *))&buff[idx];
 }

Que tipo de cast é este *((int *))?   variável integer é  do tipo int é buff unsigned char.
Answer: O cast é apenas o (int *). O resto é referência e dereferência.
O que acontece nessa linha é o seguinte:
Primeiro, é pego o endereço de um elemento do vetor buff: &buff[idx]. Se buff é do tipo unsigned char, será retornado um unsigned char *.
Feito isso, é realizado um cast de unsigned char* para int*: (int *).
Finalmente, é feita uma derreferência em *, retornando um int.
A variável int irá conter os seguintes valores em seus bytes:
buff[idx]
buff[idx + 1]
buff[idx + 2]
buff[idx + 3]

Isso se a endianness da sua máquina for little endiann. Se for big endiann, será a ordem inversa.

Dúvida cast com ponteiro


Is this inequality provable? $e^{\left(\pi^{e^{\pi^{.^{.^{.^{e^\pi}}}}}}\right)}\ge \pi^{\left(e^{\pi^{e^{.^{.^{.^{\pi^e}}}}}}\right)}$

Question: I am interested in proving the following inequalities:
$e^\pi\ge\pi^e$, $\quad \pi^{(e^\pi)}\ge e^{(\pi^e)}$,  and $\quad e^{(\pi^{(e^\pi)})}\ge \pi^{(e^{(\pi^e)})}.$
How we can prove these inequalities? (The dots may denote an infinite power tower. I think this does not matter.)
$\boxed{e^{\left(\pi^{\left(e^{\left(\pi^{\left(.^{\left(.^{e^\pi}\right)}\right)}\right)}\right)}\right)}\ge\pi^{\left(e^{\left(\pi^{\left(e^{\left(.^{\left(.^{\pi^e}\right)}\right)}\right)}\right)}\right)}}$
or
$\boxed{e^{\left(\pi^{\left(e^{\left(\pi^{\left(.^{\left(.^{e^\pi}\right)}\right)}\right)}\right)}\right)}\le\pi^{\left(e^{\left(\pi^{\left(e^{\left(.^{\left(.^{\pi^e}\right)}\right)}\right)}\right)}\right)}}$
A related question: $e^{\left(\pi^{(e^\pi)}\right)}\;$ or $\;\pi^{\left(e^{(\pi^e)}\right)}$. Which one is greater than the other?
Comment: Well, it doesn't work if you take it in the limit to infinity, because you'd wind up with infinite quantities on both sides. However, it might be possible to prove that for any finite number of repetitions that it's true by taking the proofs in your previous question and applying induction.
Comment: In the infinite (dots) case, it looks like you have $\infty\geq \infty$
Comment: İf in base have e, always bigger?
Answer: Define the sequences $E_n$ and $P_n$ by
$$E_{n+1}=e^{\pi^{E_n}}\qquad\text{and}\qquad P_{n+1}=\pi^{e{^{P_n}}}$$
with $E_1=e^{\pi}$ and $P_1=\pi^e$.  We know that $E_1\gt P_1$ from elementary calculus considerations (or simply by direct numerical calculations).  We wish to show that $E_n\gt P_n$ for all $n$.  Doing so takes care of towers of even length.  But it also takes care of odd-length towers as well, since $E_n\gt P_n$ and $\pi\gt e$ together imply $\pi^{E_n}\gt e^{P_n}$.
Note that
$$E_{n+1}\gt P_{n+1}\iff\ln\ln E_{n+1}\gt\ln\ln P_{n+1}\iff E_n\ln\pi\gt P_n+\ln\ln\pi$$
Thus to finish off a proof by induction, it suffices to show that
$$E_n(\ln\pi-1)\gt\ln\ln\pi$$
for all $n$.  But $E_1\gt1$ kicks off a mini-induction $E_{n+1}=e^{\pi^{E_n}}\ge e^{\pi^{E_1}}\gt e^{\pi^1}= E_1$ for all $n$, so it's enough to show
$$e^{\pi}(\ln\pi-1)\gt\ln\ln\pi$$
There might be some slick analytic way to establish this inequality without any messy calculation, but for the moment at least, let's just note that the two sides aren't even close:  $e^\pi(\ln\pi-1)\approx3.3491498$, while $\ln\ln\pi\approx0.1351687$.
Remark:  I skipped over the proof that $E_1\gt P_1$ in part because the OP, in the linked-to related question, accepts it as known, so the primary interest here seems to be the higher tetrations.  I and others gave purely analytic (non-computational) answers there to the inequality I'm expressing here as $E_2\gt P_2$.  Those answers' approaches might might generalize to all subscripts $n$, but offhand I don't see how.  That's why I took a partly computational approach here.
Answer: We can use the function  $y = x^{{1\over x}}$ to prove $e^{\pi} \gt \pi ^e$
$$y = x^{{1\over x}}$$
Taking logarithm of both sides:
$$\ln y = \frac{\ln x}{x}$$
Differentiating with respect to $x$:
$$\frac{1}{y}\frac{dy}{dx}=\frac{1- \ln x}{x^2}$$
$$\frac{dy}{dx}=\frac{x^{{1\over x}}}{x^2}{(1-\ln x)}$$
$$\frac{dy}{dx}=0$$
$\implies $ $\ln x = 1 $ $ \implies x=e$
At $e$:
$$\frac{d^2y}{dx^2} = \frac{e^{{1\over e}}}{e^2}\left(\frac{-1}{e}\right) \lt 0 $$
$y$ is maximum at $x=e$
But $x=e$ is the only extreme value , hence $y$ is greatest at $ x=e$
$$e^{{1\over e}} \ge x^{{1\over x}} \ , \forall x \gt 0 $$
$$e^{{1\over e}} \gt \pi^{{1\over \pi}}$$
Raising both side to power $e\pi$ we have
$$\implies e^\pi \gt \pi^e$$


How to do a PCA when two subject groups may have different solutions?

Question: I have two subject groups--one received a drug treatment and the other didn't. We collected a lot of behavioral observations on all the subjects. For the purposes of running stats, I want to reduce the number of behaviors using PCA.
Preliminary analysis reveals some of the behaviors are affected by the drug treatment so the drug treatment subjects behave differently than the controls for some behaviors..so how do I run a PCA accounting for the fact that the principal components/loadings might be different for the treated subjects and un-treated subjects?
Comment: Your question is potentially good (and not new here) but is too reticent to be answered. _What do you want_ your PCs to reflect? Plese think in terms of various group heterogeneities (such as Simpson's paradox etc). Imagine you have just 2 features and want to reduce them to one PC. But you have 2 or more different groups, ellipses, clouds of data points. Draw different possible juxtapositions/superpositions and different orientations of the ellipses. What would be your yearnings from the resultant PC as you contemplate such pics?
Answer: You would not want to run PCA separately on both datasets, since the resulting PCA dimensions would not be comparable.
Since actually you want to know how to describe both datasets with least possible dimensions, you will combine both datasets  and perform a single PCA on the combined dataset.
Yet a single PCA dimension will be a linear combination of all input dimensions therefore you can not effectively exclude dimensions, but rather "summarize" your data.
Comment: This answer is a bit short to be good. `you will combine both datasets` The main issue is how to combine, what possible transforms could be helpful at that. You haven't discussed any variants.
Comment: You are right, the answer is rather short and possibly not sufficient. Feel free to add a comprehensive answer and I will upvote it directly.


How can I bind data from nested List<> objects to nested ListView controls?

Question: So I have an asp.net web page where I display some results from an image recognition service. The results are in the form of an object of class OrpObject (the name is irrelevant), which contains a List<> of type Labels_texture. Each of these Labels_texture objects contains their own List<> of type Labels_color.
What I want to do is use a ListView to display each of the results from the Labels_texture list; and then inside each of those individual elements of the ListView, display another (nested) ListView corresponding to the elements in the nested Labels_color List<> in my OrpObject.
The main catch is that there could be a variable number of elements (or none at all) in any of these lists at any time, since they are results from an image recognition service. My main question is: how can I bind the data from the inner List<> in my OrpObject called Labels_color to the corresponding inner ListViews in my webpage, without specifying array indexes when setting the DataSource and doing the DataBind() for those inner ListViews?
Hopefully I was able to make some sense out of all that. Here are the relevant code snippets:
The OrpObject:
public class OrpObject
{
    public List<texture> Labels_texture { get; set; }

}

public class texture
{
    public string detector { get; set; }
    public string category { get; set; }
    public string matched_url { get; set; }
    public List<color> Labels_color { get; set; }
}

public class color
{
    public string category { get; set; }
    public string categoryID { get; set; }
    public string confidence { get; set; }
    public string matched_url { get; set; }
}

And here is the ListView Code from my .aspx file (trimmed down for brevity) (NOTE: I'm new to ASP.NET and I have been blindly attaching runat="server" to everything in my LayoutTemplate just in case it needs to be there. If I don't need all that, could you let me know?)
<asp:ListView ID="ListView_Orp_Results" runat="server">
     <LayoutTemplate>

            <asp:ListView ID="ListView_inner_results" runat="server">
                <LayoutTemplate>

                </LayoutTemplate>
                <ItemTemplate>
                    ...
                </ItemTemplate>
                <EmptyDataTemplate>
                    ...
                </EmptyDataTemplate>
                <EmptyItemTemplate>
                    ...
                </EmptyItemTemplate>
            </asp:ListView>

     </LayoutTemplate>
     <ItemTemplate>
        ...
     </ItemTemplate>
     <EmptyDataTemplate>
        ...
    </EmptyDataTemplate>
    <EmptyItemTemplate>
        ...
    </EmptyItemTemplate>
</asp:ListView>

Finally, here is the snippet from my code-behind file where I try to set my OrpObject and the corresponding Lists to the ListViews' DataSources:
ListView_Orp_Results.DataSource = myOrp.Labels_texture;
ListView_Orp_Results.DataBind();

foreach (texture myTexture in myOrp.Labels_texture)
{
    ListView_inner_results.DataSource = myTexture.Labels_color;
    ListView_inner_results.DataBind();
}

I know a foreach loop here probably won't work... But it's the only thing I could think of to make sure I generate a nested ListView for every texture object contained in the Labels_texture list...
Sorry for the novel, and thanks in advance for any input you might be able to offer!
Answer: You can bind the datasource of your inner list view to a property of the items bound to your outer listview. However, to do that the inner listview as to be in the itemtemplate of the outer listview.
See the code below and note the DataSource='<%# Eval("Labels_color") %>' attribute for the inner list view.
<asp:ListView ID="ListView_Orp_Results" runat="server" ItemPlaceholderID="itemPlaceholder">
 <LayoutTemplate>

 </LayoutTemplate>
 <ItemTemplate>

...

...

...

         <asp:ListView ID="ListView_inner_results" runat="server" ItemPlaceholderID="itemPlaceholder" DataSource='<%# Eval("Labels_color") %>'>
            <LayoutTemplate>

            </LayoutTemplate>
            <ItemTemplate>

...

...

...

            </ItemTemplate>
        </asp:ListView>

 </ItemTemplate>
</asp:ListView>

This way you don't need to bond the nested listview from the code behind.
Just bind the main listview, and all inner listview will be automatically bound to the Labels_texture property of the bound objects
About the runat="server" it is a required attribute for asp.net controls. Basically, this attribute means that asp.net will parse the tag and create a corresponding object.
Most of the time you don't need it on html elements (div, p, ...) but under some circumstance you might want it to manipulate the corresponding object in your code behind.
Comment: Wow, it would have taken me forever to think of that. Thank you so much, that worked! And thanks for the advice on    runat="server"!


View of users with the same 'entity reference' field vale

Question: I'm running a D7 site where every user profile has a 'entity reference' field referencing to their manager.
All I want to do is to create a list of the users sharing the same manager in context to logged-in user.
Can anyone please help
Answer: You need two entity references and a contextual filter to accomplish this.
The contextual filter does not use either of the relationships. Just select provide default value, User ID from logged in user.
The first relationship will get you the manager of the currently logged in user: User entity referenced from field_manager
The second relationship will get you the users that have that manager reference: User referencing User from field_manager. Set this relationship to use the other relationship. That's the first dropdown after you create the relationship.
Then you can simply add the User name field to your view and set it to use the second relationship (User referencing User from field_manager).
Any questions let me know. I have this running on a stripped down local install of Drupal 7.
Comment: Thanks @Jon Reid, you are a life saver. It all works but the only problem I'm having now is  also renders the logged in user as well which is in this case is 'me'. How do I only get the users who shares the same manager as me but not 'me'


Topology-book for self study about physical meaning

Question: I self study physics, and I have come across some mathematics that are unknown to me. It has to do with helicity, linking numbers and other topological factors.
A friend of mine told me that this is called topology. I want to delve into this subject on a mathematics basis but with some physical meaning in it. So I wanted to know if there are any books that are easy to delve into and can teach me these topological factors (especially stuff that have to do with linking numbers) but also give some intuition and maybe some physics exercises (or more generally have some exercises that are not purely mathematical).
Also, except from books,do you know any other means to learn these topological factors (like web sites)?
Thank you
Comment: Possible duplicate of [Best book for topology?](http://math.stackexchange.com/q/7520)
Comment: no,i am asking something much more specific
Comment: this seems to be the book for you: http://www.amazon.com/Geometry-Topology-Physics-Edition-Graduate/dp/0750306068
Comment: is there something for undergraduates?Because i am really interested in physics on undergraduate level(that has to do with undergraduate level mathematics)
Answer: I think Gauge Fields, Knots, and Gravity by Baez and Munian might be exactly what you're looking for. It is a very good text with plenty of illustrations that conveys good intuition about the mathematical and physical content. As per the title, the book discusses physical applications of knot theory, and the section starting on page 310 discusses linking numbers.
Comment: just downloaded it,its great!thanx a lot!
Comment: is it a graduate studies book or undergraduate?  It has some great reviews by the way
Comment: I think it is accessible to both undergrads and grad students. It's definitely not a terse book.
Answer: Metric spaces are basic to topological spaces.  There is a book of only 71 pages where one can learn what is a ''distance'' with a high degree of intuition.
Yu. A. Shreider, WHAT IS DISTANCE, The Chicago university press, 1974. ISBN 0-226-75498-7.
Comment: so,it has to do with linking numbers and helicity?
Comment: If you want to learn any matter which belongs to ''Topology'' you should at least learn what is a ''topology on a given set''. The resulting set is named ''topological space''. Among topological spaces there are some basic ones, they are too close to our intuition, they are ''metric spaces''. A metric space is a set endowed with what is called a metric. This book deals with this.
Comment: In this book you do not find ''linking numbers'' nor ''helicity''
Comment: Yeah but this is a long road..I just want to learn the basucs really quickly so as I can move on to linking numbers