How do I show in the home page the facets shown in the product page?

Question: I'm working on the http://drupal.org/project/commerce_kickstart distribution.
You can see that the products pages shows the search facets: http://demo.commerceguys.com/ck/products
How do I do to show these facets in the First Sidebar of the front page?
If this can't be done, then I think theres a main part missing in this distribution.
Imho the facets search in the products page are great but users are very used to see a main navigation in the left side of the home page, like: http://www.amazon.com/ , http://store.apple.com/us
How can I get this feature? Maybe there is module for this?
I've found this one http://drupal.org/project/commerce_catalog but it seems to be the placeholder for a project...
Comment: Did you manage to solve the Facets issue @chefnelone ?
Answer: Facets are built inside blocks. Just go to the admin/structure/block and search for Facet API, click configure on the Facet you would like to display on the front page, scroll to the end of the page and you will see a section Visibility options > Pages and on the right a selection named Show this block under the following pages.
You just have to add the pages where you want the selected Facet API block to appear. For instance if you type collection/*, the Facet will appear under every collection for the user to filter.
Comment: This does not work, I selected my facet api block to show only in the  page and it's not shown


Do musicians share the tabs/chords of their music?

Question: I kinda thought about this question, after watching a guy teaching how to play little Walter's  Juke intro Riff.
He said that scholars have analyzed the lick to death. So do musicians share the tabs/chords of their music?
If Snickers shared the recipe, then everyone could make Snickers chocolate. Same applies here, especially to musicians like Slash, where you have no lyrics, pure music, his chords is all he has.
People might have get their hands on the music of the dead musicians like Mozart, but what about people like Slash, Joe Satriani etc. Do they share the chords?
And if not, how do people play their music? Just by making assumptions and trying to guess the notes? Just like we did with Juke?
I am not talking about solo singers who just sing the song, those people have to share everything so that the bands could play in concert with them, I am talking about individuals/bands who create and play their own music.
Comment: With Classical music or larger bands the music has to be written down to accommodate the players.  All Classical composers have to write their parts out (unless they are the only performer).
Comment: The story, which I've been unable to confirm, is that during Van Halen's early years Eddie solo'ed with his back to the audience to keep people from watching his technique.
Answer: Great question!
The answer is that there are multiple layers to any given musician's music, and while some are easy to duplicate, others are impossible. Also, some layers can be easily duplicated by a listener, and while other layers might not be, it still could be in the artist's interest to provide that information.
As an example, after just a single listen (and another to check), I can come up with this transcription of "le riff":

This is nothing more than the notes and rhythms, which in this case are fairly easy for a trained listener to transcribe. (I don't know harmonica tablature, but it would be isomorphic to this notation).
The notes and rhythms are usually seen as the top level. They can be easily "figured out" and duplicated by others, but this is only one piece of the puzzle. As the instructor mentioned in the video you referenced, there are subtleties in playing the riff that are below the surface: producing the same pitch in a different way for ease of technique, or a different tone, and exact length of bends that aren't as obvious because they go by very fast.
Another level down might get us to the original artist's hardware and microphone/recording setup, i.e. the how of replicating the artist's unique tone. Eventually you get to the artist themselves -- their unique physiology that can never be replicated exactly, but still has an effect on the overall music that they are creating.
Whether an artist decided to share any of this information that is known to them is highly dependent on their personal feelings about copyright law, how they make money to begin with, and art in general:

An artist who owns the copyright on a song might license it to a publisher so they both make a ton of money on royalties for sheet music, karaoke, etc.
A classical composer (dead or living), makes an income off of sales of the sheet music, and royalties from the performance of that music by other people.
A guitarist might reveal some of their individual playing technique and practice tricks to make an instructional video to be sold.
Any instrumentalist might partner with an instrument manufacturer to create a "signature line" of instruments that they use exclusively, in order to benefit both parties.

At the same time:

Early jazz masters (at the dawn of the recording industry) didn't want to be recorded for fear of other musicians learning to play their music and taking away their business (of live concerts). The way you learned to play jazz was by going to live concerts and then trying to imitate the masters in your practice room.

So, to recap and answer your individual questions:

People might have get their hands on the music of the dead musicians like Mozart, but what about people like Slash, Joe Satriani etc. Do they share the chords?

Mozart's not just dead, his music is also in the public domain! He and present-day classical composers depend on their music being played by other musicians, so they copyright a published product containing the notes and chords, and then sell that. Slash and Joe Satriani are recording artists who make the majority of their income from record sales and live concerts. Most of what they play is very easy (relative to all of music, that is) to figure out on the surface levels, but if you got on stage and played all of Slash's notes and rhythms, you wouldn't sound like Slash. Joe Satriani is largely the same way, although I believe a larger percentage of his music is stuff that can't be easily figured out just from the recorded sound alone -- you might need to see him perform live to get a clue!
You'll probably find that people are more likely to publish their notation when the music they are playing is idiomatic to styles that people are already familiar with. When you are composing AND performing new music that sounds like nothing anyone has ever heard before, then understandably you might not want to reveal all of your secrets!
And lastly, I don't think you need to separate out vocalists from the thought process here. The only thing they are really sharing with the band is an arrangement -- something they may or may not have written themselves, or may only be a structure and key. It is impossible for a vocalist to share their actual voice, which is usually what distinguishes them from all of the other singers out there.
Answer: Bunch of questions there! Regarding 'How do people play their music [if they don't share the chords]', usually you can figure out what's going on by listening to the recording. You need to know 2 things:

What note/chord/sound could this be?
How do I play it on my instrument?

If you have a little music theory background, and familiarity with your instrument (which means: know how to play a C chord, G scale, and other things without needing to look it up), then you can learn a lot without needing a recipe.
Sites like http://www.soundslice.com can help you discover tabs and make your own.
Answer: Well, I think it depends on the artist in question.
Certain famous albums you can buy books that have both the score and tabs of the songs. I'm currently working through a bass one of Californication by RHCP. For a famous song everyone wants to play that isn't available like that I think it's just a refinement process. Someone has a listen, makes an educated guess, posts it online, people edit it to fix any errors.
For most, sitting down and working out the exact notes is an exercise in training yourself to translate what you hear onto your instrument.
With classical music obviously the ipod hadn't been invented, so to hear music an orchestra would learn one of Mozart's pieces, and it was in his interest to spread it around so that his music was heard and he could sell more. If you had to find a local rock band to hear Sweet Child Of Mine each time you fancied a listen I assume that the old method of distribution would still be the case. Plagurism definitely occured if that's what you're asking about, but I guess it would be a case of Mozart's word against yours at that point.
On a personal level none of my parts for my band are written down. Mostly because only I play them and it's all stored in my head. If we got to a point where people actually wanted to play my parts (unlikely :P ) I'd probably write them down properly for everyone.
Answer: Mentioning Mozart, there's the story of him listening to monks in a monastery concert,performing music that was not allowed to be seen by anyone except the performers, and going home and transcribing it from memory after one hearing.O.k., he was rather exceptional, but some musicians can do this , maybe after several hearings.When passing the info. on to others, it's very difficult to explain exactly what tone to use, how exactly to play certain phrases,etc.As stated in other answers,sounding just like the artist concerned is virtually impossible.
As far as guitar music is concerned, tab theoretically helps the player. I'm sceptical, though, as unless it's produced by the actual artist who performed the piece, it's just someone's interpretation of the way it's played, and where the notes are pressed down.I think in a lot of cases, tab on the internet is produced by people who find the tune in a particular place on the guitar, and post that as gospel.Often, there's a better way to play it, but if one is totally reliant on tab, one rarely gets to play the piece successfully.Am I being sceptical or realistic?
To me, having the 'bare bones' of a song is good, as I can put my own slant on it, but some players need or want to reproduce all of the nuances. This can come from a long time of playing, or just go and buy the transcription and practise.


Deriving the least squares estimators problem

Question: I'm working through a proof of the least squares estimators, i.e. proving that estimators of the regression coefficients are,
$$\hat{\beta}_0=\bar{y}-\hat{\beta}_1 \bar x$$
and,
$$\hat{\beta}_1=\frac{S_{xy}}{S_x^2}$$
So far in my proof, I've got to this line:
$$\sum_{i=1}^n y_i -n\beta_0 -\beta_1\sum_{i=1}^nx_i = 0$$ (1)
Which I'm told leads to:
$$\hat{\beta_0}=\frac{1}{n}\bigg(\sum_{i=1}^n y_i -{\beta_1}\sum_{i=1}^nx_i\bigg)$$(2)
$$\hat \beta_0 = \bar y - \hat \beta_1 \bar x$$(3)
My problem is that I don't understand why $\beta_0$ became $\hat \beta_0$ on the second line, and why $\beta_1$ became $\hat \beta_1$ on the third line. To me, the first line leads to this:
$${\beta_0}=\frac{1}{n}\bigg(\sum_{i=1}^n y_i -{\beta_1}\sum_{i=1}^nx_i\bigg)$$
$$\beta_0 = \bar y -\beta_1 \bar x$$
But of course, I wouldn't know how this then leads to the desired result. So why do the regression coefficients suddenly become their estimator counterparts in lines 2 and 3?
Comment: Are you trying to prove the linear regression equations?
Comment: @CogitoErgoCogitoSum Trying to prove the results shown at the start of my question
Comment: Your first statement $\hat{\beta}_0=\bar{y}-\hat{\beta}_1$ is not true as you can see at $(2)$. Please post your question more careful.
Answer: Estimators are what parameters would be equal to if they met certain criteria that they probably only approximately do. Eq. (1) is equivalent to $\beta_0$ happening to have a value that minimizes OLS, but in theory it could have any value. The problem with the two hatless equations you propose is that they claim the $\beta_i$ have criterion-meeting values, but we don't actually know that's true. The hat-bearing quantities are estimators, which we define as the values the $\beta_i$ have if they meet the desired criteria.
Of course, (2) doesn't really give us an estimator because it contains $\beta_1$, which has unknown value. But once we similarly settle on the belief $\beta_1=\widehat{\beta}_1$ (make sure before going further that you understand on what criterion we take the value $S_x^{-2}S_{xy}$ seriously), we can turn the not-quite-helpful (2) into the helpful equation (3).


How to reload screenrc without restarting screen?

Question: After modified screenrc, how to see the changes without restarting screen?
Answer: You could try Ctrl-a : source ~/.screenrc.
Comment: @garconcn: If this is something you might do frequently, put that stuff (non-screen-creation instructions) in a second file and `source` it from `.screenrc` (which will contain your screen creation instructions) for regular startup and when you need to `source` it again after `screen` has already started, just do "ctrl-a : source secondary-file" to skip the screen-creation stuff.
Comment: Sourcing the file should work.  Detaching and reattaching will not.
Comment: Using "source" is the correct (and only) way to have screen re-read the .screenrc in a running session. Yes, this means it will re-run any commands you have inside it, including commands that create windows or layouts.

You could edit the file to comment out the commands that create thew new windows/layouts; source the file; and then un-comment those lines. Of course, if it's the window creation you're wanting to test, you don't have much choice here...
Comment: @Zed: But it will re-apply the termcap/terminfo stuff which will not happen when you use `source`.
Comment: @Dennis, I tried detaching and reattaching and it didn't work, hence I came to ask this question. Also, using source can open all windows from .screenrc, however it doesn't refresh the session, but creating duplicate windows in one session. Thanks.
Comment: @James, comment the opened window and source the screenrc file works fine for me. This solved my problem. Thank you.
Comment: @Dennis, yes, I need to refresh the screenrc very frequently, I will consider doing this. thanks for the tips.
Comment: It said `permission denied` to ~/.screenrc when I have `.screenrc` as a symlink. Does any body face it?
Comment: @FelikZ:As a symlink to what? What are the permissions and ownership of that target file?
Comment: @DennisWilliamson this is symlink to a file stored in other mounted volume. Permissions are full, so I think that screen unable to handle symlinks at all.
Comment: @FelikZ: Permissions on symlinks will be 777, what are the permissions and ownership on the target of the symlink?
Answer: I tried the option mentioned here - Ctrl-a : source ~/.screenrc and it didn't work for me.
This is what worked for me - Ctrl-a : source $HOME/.screenrc
Comment: Same issue on my Mac, had to use 'source $HOME/.screenrc'
Comment: It would be normal to expect `~` to expand to your home directory.
Comment: @Iain I know, ideally it should. I guess something was wrong with my ENV then. Nevertheless, it worked.
Comment: I had this exact same issue on CentOS 5.
Comment: Same issue with zsh and oh-my-zsh on archlinux.
Comment: I tried ~/.screenrc on a old gentoo box and it didn't work. I changed directory to my home and used `source .screenrc` and it worked fine. Something about the tilde for home I suppose.
Comment: This fixed my issue on OS X with zsh and oh-my-zsh
Answer: I have this in my .screenrc file:
bind R eval "source $HOME/.screenrc" "echo '.screenrc reloaded!'"

Which causes screen to reload the .screenrc file when Ctrl-AShift-R is pressed.
Of course, this only works if you've already got the line in your .screenrc file! To 'bootstrap' this sortcut on an existing screen session, add the line above line to your .screenrc file and then follow @Dennis Williamson's answer. After that, you'll be able to use the new keyboard shortcut.
Comment: This is brilliant. Is there anything that can be added to the command to stop the reload from opening additional windows? I have .screenrc configured to automatically start two shell windows on startup, so reloading .screenrc continually opens two new windows.
Answer: The Ctrl-a : source ~/.screenrc (or variants) mentioned by others are indeed "the way to go".
But if you are using a frontend for screen (e.g. byobu), a bit of extra work is needed:

Open a new terminal
Attach the screen here too: screen -x
Run Ctrl-a : source ~/.screenrc (like everyone suggested)
Detach the screen: Ctrl-a d
Stop the new terminal: exit

The settings are now applied everywhere this screen is attached, no matter what frontend you are using. (Even when using no frontend at all)


QtQuick TableView not working with C++-QAbstractTableModel

Question: I am trying to get the Qt model/view-architecture working with a QML-View, but for whatever reason it is only partially working.
What works:

rowCount
data
roleNames

Not working:

columnCount (the method is called, but seems to have no effect, as long is it is > 0)
headerData (is this actually supposed to set the column headers? All examples set the headers in QML)
flags
setData

What I am trying to do (for some weeks already), is to create a simple ApplicationView with a TableView and a C++-model, which is editable by the view.
Right now only a whole row is selectable, not a single cell. The table data doesn't seem to be editable at all. Can anyone give me a hint?
main.qml

import QtQuick 2.3
import QtQuick.Controls 1.2

ApplicationWindow {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    TableView {
        model: theModel
        TableViewColumn {
            role: "nameRole"
            width: 75
        }
        TableViewColumn {
            role: "ageRole"
            width: 50
        }
    }
}

ModelItem.hpp

#ifndef MODELITEM
#define MODELITEM

#include <QString>

struct ModelItem {
    ModelItem(QString name_, int age_)
        : name(name_), age(age_) {}
    QString name;
    int age;
};

#endif // MODELITEM

TableModel.hpp

#ifndef TABLEMODEL_HPP
#define TABLEMODEL_HPP

#include <QAbstractTableModel>
#include "ModelItem.hpp"

class TableModel : public QAbstractTableModel
{
    Q_OBJECT
public:
    TableModel(QObject *parent = 0);

    //works
    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
    int rowCount(const QModelIndex &parent) const;
    int columnCount(const QModelIndex &parent) const;

    //does not work
    QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const;

    QHash<int, QByteArray> roleNames() const;
    enum Roles {
        NameRole = Qt::UserRole + 1,
        AgeRole
    };

    Qt::ItemFlags flags(const QModelIndex &index) const;
    bool setData(const QModelIndex &index, const QVariant &value, int role);

private:
    QList<ModelItem*> items;
};

#endif // TABLEMODEL_HPP

TableModel.cpp

#include "TableModel.hpp"

TableModel::TableModel(QObject *parent)
    : QAbstractTableModel(parent) {
    items.append(new ModelItem("Hugo",33));
    items.append(new ModelItem("Egon",34));
    items.append(new ModelItem("Balder",66));
    qDebug("TableModel initialisiert");
}

int TableModel::columnCount(const QModelIndex &parent) const {
    Q_UNUSED(parent);
    qDebug("columnCount");
    return 2;
}

int TableModel::rowCount(const QModelIndex &parent) const {
    Q_UNUSED(parent);
    qDebug("rowCount");
    return items.count();
}

QVariant TableModel::data(const QModelIndex &index, int role) const {
    qDebug("data");
    switch (role) {
        case NameRole: return items[index.row()]->name;
        case AgeRole: return items[index.row()]->age;
    }
}

QVariant TableModel::headerData(int section, Qt::Orientation orientation, int role) const {
    qDebug("headerData");
    switch (role) {
        case NameRole: return "1";
        case AgeRole: return "2";
    };
    return QVariant();
}

QHash<int, QByteArray> TableModel::roleNames() const {
    QHash<int, QByteArray> roles;
    roles[NameRole] = "nameRole";
    roles[AgeRole] = "ageRole";
    qDebug("roleNames initialised");

    return roles;
}

Qt::ItemFlags TableModel::flags(const QModelIndex &index) const {
    qDebug("--flags called--");
    return Qt::ItemIsEditable | QAbstractTableModel::flags(index);
}

bool TableModel::setData(const QModelIndex &index, const QVariant &value, int role) {
    qDebug("setData called");
    switch (role) {
        case NameRole: items[index.row()]->name = value.toString();
        case AgeRole: items[index.row()]->age = value.toInt();
    }
    emit dataChanged(index, index);
    return true;
}

main.cpp

#include <QApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>

#include "TableModel.hpp"

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QQmlApplicationEngine engine;

    TableModel model;
    engine.rootContext()->setContextProperty("theModel", &model);
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    return app.exec();
}
Comment: Thank you Marc for the SSCCE. I am not good at qml, but upvoted.
Answer: columnCount and rowCount called in QAbstractItemModel::index method, which is called by TableView before data method.
QModelIndex QAbstractTableModel::index(int row, int column, const QModelIndex &parent) const
{
    return hasIndex(row, column, parent) ? createIndex(row, column, 0) : QModelIndex();
}

bool QAbstractItemModel::hasIndex(int row, int column, const QModelIndex &parent) const
{
    if (row < 0 || column < 0)
        return false;
    return row < rowCount(parent) && column < columnCount(parent);
}

columnCount has no effect, as long is it is > 0, because TableView called the index method with column always equal to 0.
headerData and flags did not affect the QML TableView. You can only set the headers on the QML side. To create an editable TableView, you should implement your custom itemDelegate
main.qml
ApplicationWindow {
    visible: true
    id: root
    Component {
        id: editableDelegate
        Item {
            Text {
                width: parent.width
                anchors.margins: 4
                anchors.left: parent.left
                anchors.verticalCenter: parent.verticalCenter
                elide: styleData.elideMode
                text: styleData.value !== undefined ? styleData.value : ""
                color: styleData.textColor
                visible: !styleData.selected
            }
            Loader {
                id: loaderEditor
                anchors.fill: parent
                anchors.margins: 4
                Connections {
                    target: loaderEditor.item
                    onEditingFinished: {
                        theModel.setData(styleData.row, styleData.column, loaderEditor.item.text)
                    }
                }
                sourceComponent: styleData.selected ? editor : null
                Component {
                    id: editor
                    TextInput {
                        id: textinput
                        color: styleData.textColor
                        text: styleData.value
                        MouseArea {
                            id: mouseArea
                            anchors.fill: parent
                            hoverEnabled: true
                            onClicked: textinput.forceActiveFocus()
                        }
                    }
                }
            }
        }
    }
    TableView {
        id: table
        anchors.fill: parent
        model: theModel
        itemDelegate: editableDelegate;
        TableViewColumn {
            role: "nameRole"
            width: 75
            title: "name"
        }
        TableViewColumn {
            role: "ageRole"
            width: 50
            title: "age"
        }
    }
}

To apply the changes to your model, you should implement the setData method, like this:
TableModel.h
bool setData(const QModelIndex &index, const QVariant &value, int role) {
    switch (role) {
        case NameRole: items[index.row()]->name = value.toString(); break;
        case AgeRole: items[index.row()]->age = value.toInt(); break;
    }
    emit dataChanged(index, index);
    return true;
}

Q_INVOKABLE bool setData(int row, int column, const QVariant value)
{
    int role = Qt::UserRole + 1 + column;
    return setData(index(row,0), value, role);
}

Comment: Wow, thanks a lot! I would have never found this solution on my own.
Comment: @MarcQ: good questions deserve good answers ;-) Thanks, Meefte (upvoted).
Answer: The above answer covers things nicely. I just want to add a couple of notes:

in QML you can simply do model.role = value within an item delegate instead of having to call setData() by hand
several QAbstractItemModel methods, including setData(), have been made Q_INVOKABLE in Qt 5.5: https://codereview.qt-project.org/#/c/107171/
Comment: can you provide an example for the model.role=value in the above context? do you have to individually set the role value for each item tableview delegate or can this be applied for itemDelegate? Also if setDate is set as Q_INVOKABLE how do you call it from QML?


For a subspace $U$ of $V$, is the annihilator of the annihilator of $U$ equal to the image of $U$ under the canonical isomorphism $V \to V^{**}$?

Question: So, with the annihilator of a set $U$ defined as Anni($U$) = $\{f \in V^* \: | \: \text{for all $u \in U$: }f(u) = 0\}$, and the canonical isomorphism $\varphi: V \to V^{**}$ given by $\varphi(v)(w^*) = w^*(v)$, I want to know if for a subspace $U$ of $V$ we have $\varphi[U] = $ Anni(Anni($U$)).
So far, I have the inclusion $\varphi[U] \subseteq $ Anni(Anni($U$)), and I'll show how. Let $f \in \varphi[U]$, then for some $u \in U$ we have $f(w^*) = w^*(u)$ for all $w^* \in V^*$. Then for all $w^* \in $ Anni($U$) we have $f(w^*) = w^*(u) = 0$, since $u \in U$ and $w^* \in $ Anni($U$). So then we have $f \in $ Anni(Anni($U$)).
However, I'm struggling with proving Anni(Anni($U$)) $\subseteq \varphi[U]$. The problem I'm having is, for any $f \in $ Anni(Anni($U$)), we only know how $f$ acts on the elements of $U$. For any elements in $V \setminus U$ we don't really know where $f$ maps those elements, so I am not sure if $f \in \varphi[U]$, nor do I know how to prove it is or isn't.
Answer: If $V$ is finite dimensional, then we have $\dim(\mathrm{Anni}(U)) = \dim(V) - \dim(U)$.
Thus, we may conclude that $\dim[\mathrm{Anni}(\mathrm{Anni}(U))] = \dim(U)$
From this and your inclusion $\mathrm{Anni}(\mathrm{Anni}(U)) \subseteq \varphi[U]$, it follows that $\mathrm{Anni}(\mathrm{Anni}(U)) = \varphi[U]$.
This statement will generally fail for infinite dimensional spaces, for either generalization of a dual space.
If you take $V^*$ to refer to the algebraic dual of $V$, then $\varphi:V \to V^{**}$ will fail to be an isomorphism whenever $V$ is infinite dimensional.
If you take $V$ to be a topological vector space and take $V^*$ to refer to the continuous dual, then we can construct a counterexample as follows: when $V$ is a Hilbert space, we have $\mathrm{Anni}(\mathrm{Anni}(U)) = \overline{U}$, and we will have $U \subsetneq \overline{U}$ if $U$ is a non-closed subspace of $V$.  Every infinite dimensional normed space has a non-closed subspace.
Comment: I am curious as to whether the statement holds for finite dimensional subspaces $U$ of a reflexive Banach space $V$, if anyone happens to have a quick answer. I suspect that it does.


Zend 1.12 Flash Message always coming up

Question: In my site, I upgraded my PHP version and flash messages got display over the site.
  As I checked in my view.phtml file that if Flash Message contains data it should show. It is showing the Flash messages all the times.Like
Item has been updated successfully.

I looked over internet but couldn't able to find the issue. Did anyone face the same issue?
I am using following things in my class ,
Under init function:
$this->_helper->getHelper('FlashMessenger');
Under my specific action:
$this->_flashMessenger->addMessage(array('message' => 'Item updated successfully.',
                'status' => 'alert-success'));
In my view.phtml file-

<?php echo $this->flashMessages(); ?>

All was working fine from last year, This happened just after upgrade of PHP version.
Thanks.
Comment: David Weinraub I got the issue, It was caching enabled on the updated server. ACL cache which was not clearing the flash messages arrays. Thanks for your comment. Have a great day !!
Comment: Upgrade from/to which PHP version? Assuming that your logic flow is sound (i.e., you are not actually calling `addMessage()` on every page), I would look at the view-helper itself. Since there is no `flashMessages()` view-helper in the standard [ZF 1.12 View component](https://framework.zend.com/manual/1.12/en/zend.view.helpers.html), this must be a custom view-helper in your app. Perhaps something there is detecting messages incorrectly? When you say that "I checked in my view.phtml file that if Flash Message contains data it should show", how are you checking that? Just some ideas...
Comment: glad you solved your problem. As a matter of SO housekeeping, may I suggest that you either add your solution as an Answer (yes, you can answer your own Questions on SO) or delete the original Question? Thanks and cheers!
Answer: I have figure out the issue, This issue was to due to ACL cache enabled on the server. After disabling it, Everything works as expected.
Thanks !!


As a site collection administrator I am not able to access site settings on site collection

Question: As a collection administrator I am not able  to access site settings on SharePoint site collection. if I click on site settings it showing "sorry, this site has doesn't share with you". But I login using site collection administrator account on dev server.
If I create new site collection with same web application I can access everything. one more thing I restored production database on this server and I associated with this web application.
I hope anyone can help to this issue please.
Answer: This might happen as the production environment will have different users and when you restore it to your development environment, your development environment changes were override.
To fix this issue, go to Central Administration -> Application management. Under site collection section, click on "Change site collection administrators".

In this select your site collection. Change site collection administrator and click ok.
Comment: same thing i did but still i am facing same issue
Comment: Please make sure you add your user in primary site collection administrator (not the secondary). Also please check your user have permission in content database.


Arranging letter with restriction

Question: Need to find the the number of ways to arrange letter for below condition.
first letter cannot be placed in first or last position.
repetition is allowed, however letter cannot be repeated in adjacent positions.
I need logic for n letter in n position.
Example:
3 letter  set {a,b,c} in 3 position
"a" cannot be put in  first or last position.
you cannot put two consecutive letter as repetition as ( b b c).
so possible values for 3 letter to be arranged in 3 position.
c a b
c b c
c a c
b a c
b a b
b c b
Answer : No of ways = 6.
Comment: please explicitly state your question
Comment: This might be helpful- http://math.stackexchange.com/questions/1457652/complex-permutation/1457665#1457665
Answer: You have 2 choices for your first letter: $b$ or $c$.
Then you have 2 choices for your next letter: $a$ or [whichever of $b$ or $c$ was not the first letter]. Let's consider these two cases separately.
(1) $a$ was chosen for the middle. Then we have 2 choices for the final letter: $b$ or $c$.
(2) $a$ was not chosen for the middle. Then we are forced to use whichever letter was not used for the middle ($b$ or $c$).
This gives us: $2(1\cdot 2 + 1\cdot 1) = 6$ possible answers.
Notice the multiplication as we stack one choice on top of another and the addition when we must branch out to different possibilities.
Comment: Hmmm, $a$, should be the middle letter as it cannot be first nor last. Furthermore $b$'s and $c$'s may be used more than once.
Comment: Can we come up with generic solution , what will be case for 4 letters 4 position ( =60 ), 4 letter 5 position ? The solution above by Bill Cook is correct. Thanks.

Arranging letter with restriction


Why are NFL hash marks closer than NCAA hash marks?

Question: Typically as you move up to more competitive levels of a sport, elements are adjusted to account for the increase of skill/speed/power of better players.

NBA 3-point line is farther from hoop than NCAA 3-point line
MLB uses wooden bats while NCAA uses metal bats
NFL requires 2 feet for completion, NCAA requires 1 foot for completion

Why are NFL hash marks closer together than NCAA hash marks?

If the difference relates to field goals, I don't understand why the NFL would narrow the marks and make it easier for kickers.
If the difference relates to location of ball spots, is there a reason the NFL chooses to keep lateral ball spots closer to the center of the field?
Comment: I know that it has to do mostly with offense vs defense.  It would be hard to defend almost a whole side of the field if one team was down close to the sideline.  Plus is makes it easier on an offense that they can call a play to one side or the other without caring too much about which hash they are on.  When it comes to kicking, I don't think they want to make it harder.  The NFL, especially today is about scoring.  I couldn't find any good references about why they are closer than the NCAA.  Should be interesting to see if someone can give a complete answer with good references.
Answer: In 1972 the NFL moved the hash marks closer together, "looking for a way to produce more action and more touchdowns, now that defenses have become so effective".
The article goes on to add,

Putting the ball in play farther from each sideline supposedly gives the offense more room to exercise its options. But it also becomes more seductive to try a field goal, since the kicker has less of an angle for his attempt.
Comment: This article cites another SI article from two weeks earlier, but finding and linking specific articles in the SI Vault is colossally difficult and annoying.
Answer: It's less about the kicker, and more about the defense v offense. Having the ball placed closer to the centre of the field means that the field is almost equally wide in both directions, making it more difficult to defend.
Further to this, the NFL moved the hashmarks closer together when they moved the posts to the back of the endzone, to help offset the increase in difficulty (extra 10 yards to every kick).
Answer: The NFL changed the speed of the game by moving hash marks in. It enabled the "sweep" to be run to either side of the field-- BALANCE was now a word used to describe offenses and not just 50/50 run pass-- as evidence was the vast number of 1000+ rushers (It was referred to as "the year of the runner") -- it also enables the crossing route or "east west game" which college does not have-- college is a slow power game that is a North South game, and has no east/west capability. The close hash marks allowed the "Mouse" Davis spread (run and shoot) to be installed-- it allowed Bill Walsh's 1-2-3 offense to be installed. It is the single biggest aspect to the leagues success via rule change, as it was both innovative and impactful.
Answer: A big part of it is what was mentioned before - more touchdowns.  IMHO it is also intended to create a more wide-open kind of play for fan consumption.  To my way of thinking it's like a Butterball turkey.  Most people want breast meat so they breed them to have lots of breast meat with the unintended consequence that the breast meat has hardly any taste.  I don't buy the compensate for moving the goal post argument.  NCAA kickers on average should be less able than NFL kickers but they manage to make field goals with the angle.  It's just an additional way to cause more scoring and thus more excitement.


PHP on Windows - ps_files_cleanup_dir error

Question: I am occasionally getting the following error when loading a PHP page:
PHP Notice:  session_start(): ps_files_cleanup_dir: opendir(C:\Windows\TEMP) failed: No error (0) in C:\server\default.php on line 299

Month-old sess_ files in C:\Windows\TEMP still exist.
I am running PHP 5.6.5 on IIS on Windows 8.1.
Why is PHP unable to perform garbage collection, and how do I fix it?
Comment: @kmindi It's been able to write the `sess_` files.
Answer: Session temporary files are created in this directory as per the 'session.save_path' property in php.ini. Without the permissions to delete files in this directory PHP is unable to remove these files as part of its normal session garbage handling process and so they accumulate when they are no longer needed/you will occasionally see this error whenever garbage collection is performed.
The Application Pool user, which is the one that actually runs the PHP executable, needs at least modify permissions on C:\Windows\TEMP to perform garbage collection (this is not granted by default). If you have not changed this user from the default then it should be 'DefaultAppPool', or you can use the App Pool group, which will be similar to IUSRS.
Best practice is to create a new Application Pool for each site. When you do this IIS will create a Windows user which you can then grant modify permissions to. You can script this or do it from the command line using the following command:
icacls c:\windows\TEMP\ /inheritance:e /grant "IIS APPPOOL\your-user:(OI)(CI)M" /t /c /Q

Update: As Gremio notes, you should move the session files to a specific directory, so that you are not granting write access for this user (that may be exploited) to whatever else Windows stores in the TEMP directory. You can modify the sessions save settings in the php.ini, globally, or specifically for your application at run time (details here).
Comment: I would not grant Modify for C:\Windows\Temp to an account used by a web server (including IIS, phpcgi, Python, Etc.). There's just no telling what could end up there. You could instead change the path for sessions to something else where you can grant the account M. Or you could just give the account 'list folder' as users have everything they need by default (which these accounts are unspoken members of) except list folder. Granted, if a hacker can exploit the code and access that location, they're potentially taking over sessions no matter what you do.
Answer: I found that the easiest way to deal with this problem was to change the path being used to save temporary information to one of my choosing, followed by setting the appropriate security permissions.
To change the path used to store temporary files:

Edit the php.ini for your installation (mine was located in C:\Program Files\PHP\v7.4).
Located the session.save_path setting.
Change the path from C:\Windows\Temp to a folder of your choosing.  I created a folder specifically for this.

To change the permissions on the folder you specified above:

Right-click on the folder in Windows Explorer and choose Properties.
Choose the Security tab.
Click Advanced to open the Advanced Security Settings popup.
Click Change Permissions.
Click Add... to add a new user.
Type in IIS_IUSRS as the object name and click OK.
On the Permissions Entry popup, tick the settings for Full control under the Allow column.
Click OK to return to the main Permissions list.
Make sure to select the checkbox at the bottom of the page that states Replace all child object permissions with inheritable permissions from this object.
Click OK and confirm all the other popups and windows.

PHP should immediately begin to use the new folder location for session and temporary data.
Answer: Just give Full Permissions to the User "IUSR" on the Directory "C:\Windows\Temp". Maybe just Directory Listing and Deleting is enough... but in a non-productive system this shouldn't be a problem.


Is there a way for an internal module in an ambient declaration to use a type from an external module?

Question: In this declaration, I'd like the interface ITest to have a property 'modA' of the type 'ModA' from the external module 'modA':
<code>declare module foo {
    interface ITest {
        str: string;
        modA: ModA;
    }
}

declare module "modA" {
    class ModA {
        num: number;
    }
    export = ModA;
}
</code>
Comment: Starting from TypeScript 0.9, a module is no longer a "type", so what you want to do may not be possible...
Comment: Spent some time on this and concluded moving these into two separate d.ts files is the solution, with "foo" importing "modA".  In my case this approach resulted in writing import statements just to get type information.  Unfortunately these statements also resulted in the mid being added to the define statement!  Submitted an issue: https://typescript.codeplex.com/workitem/2111
Answer: Use external modules everywhere and then optimize it with r.js from RequireJS package.


Add line to the bottom of last cell

Question: I have UiTableView. Cells on it by clicking change itself height. I need to add custom separator lines. I alwaays add to the top of cell. So all work fine, but last cell haven't seporator line on the bottom, and user cann't see the end of tableview. I try to add next code in
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

and then try use it in
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

I create in the begin new UIImageView
@implementation MovieSessionsVC
...
    UIImageView *seporatorView;
}

And this my code:
[seporatorView removeFromSuperview];
if (indexPath.row == self.sessions.count - 1) {
    seporatorView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"seporator.png"]];
    if([self cellIsSelected:indexPath])
        seporatorView.frame = CGRectMake(0, 106, cell.width, 0.5);
    else
        seporatorView.frame = CGRectMake(0, 63, cell.width, 0.5);
    [cell addSubview:seporatorView];
}

I use self.sessions.count for number of rows, and heoght of my cells is 64 and 107 when selected
So line appear and work fine, but when I pick up my tableview on maximum it is disappear
Comment: Are you using your CustomCell, and designing from XIB ?
Comment: Yes, custom cell add in storyboard
Answer: If it isonly the last cell where you want to add something to, a line in your case, then it is probalby the easiest to draw the line on top of the footer view. You can create a UIView and assign that to the tableFooterView property of UITableView. That footer may just have a height of 1.0 and is filled with a colour.
You can of course draw a line in drawInRect of that footerView. For doing so you will need to subclass UIView. But I think that some standard UIView with a background colour and a height of 1.0 would do.
Answer: Just set the resize property of the separator image same as the image below

The separator image to sit to the bottom on any cell resize.. Make sure the cell resize property is all selected..

Add line to the bottom of last cell


Problema com Datatables em Laravel 5.2

Question: Olá, tentei usar o Datatables server-side e não server-side mas ele não exibe o datatables. Faço tudo de acordo com a documetação (https://datatables.net/) e em tutoriais na internet, mas não funciona e também não exibe nenhum erro (as páginas carregam normalmente).
Meu Controlador:
namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;

use App\Http\Requests\ValidarFuncRequest;

use Redirect;
use Datatables;

use App\Funcionario;
use App\Dependente;

class FuncionariosController extends Controller
{
    public function index(){

        $funcionarios = Funcionario::all();
        return view('funcionarios.lista', ['funcionarios' => $funcionarios]);

    }

    public function novoForm(){

        return view('funcionarios.formFuncionario');

    }

    public function salvarFuncionario(ValidarFuncRequest $request){

        $funcionario = new Funcionario();

        $funcionario->create($request->all());

        \Session::flash('msg_sucesso', 'Funcionário cadastrado!');

        return Redirect::to('funcionarios/novoForm');

    }

    public function editar($id){

        $funcionario = Funcionario::findOrFail($id);

        return view('funcionarios.formFuncionario', ['funcionario' => $funcionario]);

    }

    public function atualizar($id, ValidarFuncRequest $request){

        $funcionario = Funcionario::findOrFail($id);
        $funcionario -> update($request->all());

        \Session::flash('msg_sucesso', 'Funcionário atualizado!');

        return Redirect::to('funcionarios/'.$funcionario->id.'/editar');

    }

    public function listarDpt($id){

        $funcionario = Funcionario::find($id);

        return view('funcionarios.listaDpt', ['funcionario' => $funcionario]);

    }

    public function deletar($id){

        try{

            $funcionario = Funcionario::findOrFail($id);

            $funcionario -> delete();

            \Session::flash('msg_sucesso', 'Funcionário deletado com sucesso!');

        } catch(\Illuminate\Database\QueryException $e){

            var_dump($e->errorInfo);

            \Session::flash('msg_erro', 'Funcionários com dependente(s) não podem ser deletado!');

        }

        return Redirect::to('funcionarios');

    }

    public function novoDpt($id){

        $funcionario = Funcionario::findOrFail($id);

        return view('funcionarios.novoDept', ['funcionario'=>$funcionario]);
    }

}

Minha view:
@extends('layouts.app')

@section('content')
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="//cdn.datatables.net/1.10.12/css/jquery.dataTables.css">

                    Funcionários
                    Adicionar Funcionário

                        @if(Session::has("msg_sucesso"))

 {{ Session::get('msg_sucesso')}}

                        @elseif(Session::has('msg_erro'))

 {{Session::get('msg_erro')}}

                        @endif

                                    ID
                                    Nome
                                    Sexo
                                    Ações

                                @foreach($funcionarios as $funcionario)

                                        {{$funcionario -> id}}
                                        {{$funcionario -> nome}}
                                        {{$funcionario -> sexo}}

                                             id}}/editar" class="btn btn-default">Editar

                                            {!! Form::open(['method' => 'DELETE', 'url' => 'funcionarios/'.$funcionario->id, 'style' => 'display: inline;',  'onsubmit' => 'return ConfirmarDelete()']) !!}
                                            <button class="btn btn-default">Excluir</button>
                                            {!! Form::close() !!}

                                            id}}/listarDpt" class="btn btn-default">Dependente(s)

                                @endforeach

@endsection

Minha rout:
<?php

Route::get('/', function () {
    return view('welcome');
});

Route::auth();

Route::get('home', 'HomeController@index');

Route::get('funcionarios', 'FuncionariosController@index');
Route::get('funcionarios/novoForm', 'FuncionariosController@novoForm');
Route::get('funcionarios/{funcionario}/editar', 'FuncionariosController@editar');
Route::post('funcionarios/salvarFuncionario', 'FuncionariosController@salvarFuncionario');
Route::patch('funcionarios/{funcionario}', 'FuncionariosController@atualizar');
Route::delete('funcionarios/{funcionario}', 'FuncionariosController@deletar');

Route::get('dependentes', 'DependentesController@index');
Route::get('dependentes/formDpt', 'DependentesController@novoForm');
Route::post('dependentes/salvarDpt', 'DependentesController@salvar');
Route::delete('dependentes/{dependente}', 'DependentesController@deletar');
Route::get('dependentes/{dependente}/editarDpt', 'DependentesController@editar');
Route::patch('dependentes/{dependente}', 'DependentesController@atualizar');

Route::get('funcionarios/{funcionario}/listarDpt', 'FuncionariosController@listarDpt');
Route::get('funcionarios/{funcionario}/novoDept', 'FuncionariosController@novoDpt');

Route::get('dependentes/{funcionario}/novoForm', 'DependentesController@novoForm');

Route::get('projetos', 'ProjetosController@index');
Route::get('projetos/novoForm', 'ProjetosController@novoForm');
Route::post('projetos/salvarProjeto', 'ProjetosController@salvarProjeto');
Route::get('projetos/{projeto}/editarProjeto', 'ProjetosController@editarProjeto');
Route::patch('projetos/{projeto}', 'ProjetosController@atualizarProjeto');
Route::delete('projetos/{projeto}', 'ProjetosController@deletarProjeto');
Route::get('projetos/{projeto}/listaFunc', 'ProjetosController@listaFunc');

Route::get('projetos/{funcionario}/addFunc', 'ProjetosController@addFunc');
Route::patch('projetos/{projeto}', 'ProjetosController@addBotao');

Comment: analisando assim de longe eu faria um primeiro teste com o debug do proprio navegador pressione F12, guia console e verifique se tem algum problema no javascript geralmente é isso o problema e só você mesmo tem possibilidade de testar. Um outro ponto é que tem chamada de função repetida isso causa erro de javascript e ele não chega a executar o .DataTables(), se faz o seguinte retire aqueles javascript que estão nas `` deixe somente o código PHP e execute pra ver...
Comment: Muito obrigado cara, não resolveu diretamente o problema mas foi uma luz no fim do túnel. Obrigado mesmo! kkkk
Comment: você está usando qual carregamento é o ajax: https://datatables.net/examples/ajax/simple.html desse link ou qual é o tipo: nos diversos exemplos: https://datatables.net/examples/index
Comment: Estou usando o da do inicio do site, que é sem ajax. Queria que ao menos ele funcionasse (em todos os tutors que vi ele funciona normal) sem ajax e depois tentaria usando o server-side, mas nenhum funciona... Penso até que o laravel não esteja carregando os arquivos .js e .css, mas tentei de várias formas e dá na mesmo.
Comment: Consegui resolver o problema então?
Answer: O problema é que tem que ir na pasta app.blade.php (onde fica o head e body para se colocar os links e scripts) e lá colocar os arquivos .js e .css. Tinha feito isso mas o problema é que o javascript tem que ficar acima de qualquer outro script e, no meu caso, estava lá em baixo.
Comment: entendi o problema .... bom ter resolvido.

Problema com Datatables em Laravel 5.2


Can a penalty be declined in the NHL?

Question: The Edmonton Oilers scored 2 short-handed goals on San Jose Sharks during the 2nd game of the first round 16-17 playoffs. Even though a team on a powerplay has one more skater than the other team, if a team is experiencing what the Sharks did, not accepting a penalty wouldn't be crazy idea to consider.
So although there isn't any true upside to rejecting a penalty, is it possible for a team to reject a power play?
Answer: No. Penalties are awarded by the officials. Team preference is not a factor; they do not have any input on the decision.
Rule 15.1, page 25 of the NHL rulebook makes clear that

[if the offender's team has possession] the Referee shall immediately blow his whistle and penalise the offending player.
[after a delayed penalty, and the offender's team gains possession], the Referee will blow his whistle to stop play and impose the penalty on the offending player.

Minor penalties may also be washed put automatically if a delayed penalty leads to a goal by the non-offending team, but this is an artifact of the normal rule applying to delayed penalties.
At no point in any part of the rule is any mention or implication that the offender's opponents may decide the penalty is not served at all.

Can a penalty be declined in the NHL?


How can i add .pdf extention on the default upload files

Question: When i create an article i saw that i'm allowed to upload image files only

Allowed file types: .png .gif .jpg .jpeg

How can i add .pdf file extension and attached with the article?
I'm using zen theme
Comment: Try to create one field type "file"and then search the field "Allowed file extensions" and adding .pdf .
Answer: Go to Structure > Content types, click manage fields for the article content type, then edit on the Image field. There you can edit the allowed file types.
However, note that this is an image field. It does not make sense to upload PDF files to an image type field. Instead, you might want to add a new field with type file and configure that to allow pdf files.
Also note that you can't leave the allowed values empty, that would not allow any file types.
Comment: it has nothing in managed field.Do I have to create new field?
How do I add vtt type in simple file upload ... I am using form to upload it works for txt but not working for vtt and exel
Answer: There is a module for Drupal 6: File attachment utilities; you can get some idea from its code.
Answer: Go to "Administer -> Site Configuration -> File Uploads," add '.pdf' to the "Default permitted file extensions:" section, and click on "Save configuration."
Comment: The queston is tagged [tag:7]. The setting you suggest is used doesn't exist in Drupal 7.
Answer: You can setting by content types -> article -> edit and then you must adding to upload field the extension .pdf
It' s easy!
Answer: Navigate to Administration » Structure » Content types. Click on Manage fields for the "Article" content type.  Note that in Drupal 7, the default "Article" content type already have a field for file attachments (named "Attachment"), so there is no need to create a new field, as suggested in the currently accepted answer.
Press the Edit link on the Attachment field and locate the field Allowed file extensions
The default attachment content type is just txt.  Change this to txt pdf, and press "Save settings".
To add a PDF attachement, make sure you use the Attachment field (not Image field) for the PDF-attachment when creating new Article content.


How to save XML node back into XML file with LINQ-to-XML?

Question: I've got an XML file which I use to create objects, change the objects, then save the objects back into the XML file.
What do I have to change in the following code so that it extracts a node from the XML based on the id, replaces that node with the new one, and saves it back into the XML?
The following gives me 'System.Xml.Linq.XElement' does not contain a constructor that takes '0' arguments':
//GET ALL SMARTFORMS AS XML
XDocument xmlDoc = null;
try
{
    xmlDoc = XDocument.Load(FullXmlDataStorePathAndFileName);
}
catch (Exception ex)
{
    HandleXmlFileNotFound(ex);
}

//EXTRACT THE NODE THAT NEEDS TO BE REPLACED
XElement oldElementToOverwrite = xmlDoc.Descendants("smartForm")
    .Where(sf => (int)sf.Element("id") == 2)
    .Select(sf => new XElement());

//CREATE THE NODE THAT WILL REPLACE IT
XElement newElementToSave = new XElement("smartForm",
                              new XElement("id", this.Id),
                              new XElement("idCode", this.IdCode),
                              new XElement("title", this.Title)
                              );

//OVERWRITE OLD WITH NEW
oldElementToOverwrite.ReplaceWith(newElementToSave);

//SAVE XML BACK TO FILE
xmlDoc.Save(FullXmlDataStorePathAndFileName);

XML file:
<?xml version="1.0" encoding="utf-8" ?>
<root>
  <smartForm>
    <id>1</id>
    <whenCreated>2008-12-31</whenCreated>
    <itemOwner>system</itemOwner>
    <publishStatus>published</publishStatus>
    <correctionOfId>0</correctionOfId>
    <idCode>customerSpecial</idCode>
    <title>Edit Customer Special</title>
    <description>This form has a special setup.</description>
    <labelWidth>200</labelWidth>
  </smartForm>
  <smartForm>
    <id>2</id>
    <whenCreated>2008-12-31</whenCreated>
    <itemOwner>system</itemOwner>
    <publishStatus>published</publishStatus>
    <correctionOfId>0</correctionOfId>
    <idCode>customersMain</idCode>
    <title>Edit Customer</title>
    <description>This form allows you to edit a customer.</description>
    <labelWidth>100</labelWidth>
  </smartForm>
  <smartForm>
    <id>3</id>
    <whenCreated>2008-12-31</whenCreated>
    <itemOwner>system</itemOwner>
    <publishStatus>published</publishStatus>
    <correctionOfId>0</correctionOfId>
    <idCode>customersNameOnly</idCode>
    <title>Edit Customer Name</title>
    <description>This form allows you to edit a customer's name only.</description>
    <labelWidth>100</labelWidth>
  </smartForm>
</root>

Answer: Well, the error has nothing to do with saving, or even with replacement - it has to do with you trying to create an XElement without specifying the name. Why are you trying to use Select at all? My guess is you just want to use Single:
XElement oldElementToOverwrite = xmlDoc.Descendants("smartForm")
    .Where(sf => (int)sf.Element("id") == 2)
    .Single();

(As Noldorin notes, you can give Single a predicate to avoid using Where at all. Personally I quite like to split the two operations up, but they'll be semantically equivalent.)
That will return the single element in the sequence, or throw an exception if there are 0 elements or more than one. Alternatives are to use SingleOrDefault, First, or FirstOrDefault:

SingleOrDefault if it's legal to have 0 or 1
First if it's legal to have 1 or more
FirstOrDefault if it's legal to have 0 or more

If you're using an "OrDefault" one, the result will be null if there are no matches.
Comment: Single has an overload that takes a predicate, so no need to use `Where`.
Comment: Yup - I had forgotten about that, but I actually find it more readable to use the separate operations anyway :)
Answer: I think the problem is simply your use of the Select call in the statement assigning oldElementToOverwrite. You actually seem to want the Single extension method.
XElement oldElementToOverwrite = xmlDoc.Descendants("smartForm")
    .Single(sf => (int)sf.Element("id") == 2)


LINQ - How can I use DataSet.DataRelation to join these tables and sum one field?

Question: My LINQ query is not producing the expected output below. Basically, it's the sum of table3.cost corresponding to table2.code and table2.class categorized by table1.alias and ordered by table1.priority. I added two DataRelation's to the DataSet:
ds.Relations.Add("Table1Table2", ds.Tables[1].Columns("ID"), ds.Tables[2].Columns("ParentID");
ds.Relations.Add("Table2Table3",
    new DataColumn[] { ds.Tables[2].Columns["Code"], ds.Tables[2].Columns["Class"] },
    new DataColumn[] { ds.Tables[3].Columns["Code"], ds.Tables[3].Columns["Class"] });

var query = from aliases in table1.AsEnumerable()
    join children in table2.AsEnumerable() on aliases("ID") equals children("ParentID")
    orderby aliases("priority")
    select new
    {
        Name = aliases("alias"),
        Cost =
            from data in table3.AsEnumerable()
            group data by new { code = data("code"), classcode = data("class") }
            into datatemp
            select new
            {
                cost = datatemp.Sum(x => x("cost"))
            }
    };

Any ideas what I'm doing wrong? Thanks in advance!
table1: list of aliases and priorities
-----------------
alias   priority
alias1  1
alias2  2
alias3  4
alias4  3
table2: children records joined to table1 by ParentID (1-to-many)
-----------------
code  class   ParentID
code1 class1  1
code2 class2  1
code3 class3  2
code4 class4  4
table3: data, joined to table2 by class and code (1-to-many)
-----------------
code  class   cost
code1 class1  1.00
code1 class1  10.00
code1 class1  26.00
code2 class2  5.00
code2 class2  0.00
code3 class3  1000.00
Expected output:
alias1 42.00
alias2 1000.00
alias4 0.00
alias3 0.00
Answer: var query = from x in Table1.AsEnumerable()
orderby x.Field<int>("Priority")
select new {
    Name = x.Field<string>("alias"),
    TotalCost = x.GetChildRows("Table1Table2")
            .Sum(c => c.GetChildRows("Table2Table3")
                    .Sum(tx => tx.Field<decimal>("cost")))
};


Trick with inequalities

Question: I have that $\forall n >n_0$ I have $|a_n-a|<1$. I want to get to the result that says $\forall n>n_0$ we have $|a_n|<|a|+1$.
I am very doubtful about my working out as I don't know if it works, especilly the highlighted part:
Suppose $a_n-a \geq 0$, then $|a_n-a|=a_n-a<1$ hence $a_n<a+1$.
Suppose $a_n-a <0$ then $|a_n-a|=-a_n+a <1$ hence $-a_n <-a +1$.

Hence since $a+1$ or $-a +1$, which is (is it though?) $|a|+1$, this works for $a_n$ and $-a_n$, we have $|a_n|<|a|+1$

Is this even correct? Or how should I prove that?
Answer: Just use the triangle inequality: $\;\lvert a_n \rvert=\lvert (a_n-a) +a\rvert\le \lvert a_n -a\rvert+\lvert a \rvert <1+\lvert a \rvert $.
Answer: $$|a\pm b|\ge |a|-|b|\implies |a_n|-|a|\le|a_n-a|<1\implies |a_n|<|a|+1$$
Comment: Much simpler.  :D
Comment: @SimpleArt this inverted triangle inequality always gets me! Thank you DonAntonio
Comment: @Euler_Salter Exactly so.

Trick with inequalities


Interpretation of proportion coefficient in linear regression

Question: If I have an equation:
income = 22 + 12 * (hrs_prop),
where hrs_prop is the proportion of hours spent assuming between 0 and 0.24 and income is in thousand of dollars.
How can I interpret the slope?
What does one unit change mean here?
Thanks
Answer: Welcome to StackExchange! Hope you learn a lot in this forum.
The generic expression for a linear equation with one independent variable is $y = \alpha + \beta x$.
The slope, $(\beta)$ expresses the rate of change or, in other words, the ratio of the vertical and horizontal changes between two points. That means, if you vary one unit of your independent variable ($x$), your dependent variable ($y$) will vary $\beta$ units. In your example, if you increase one unit of hrs_prop, the income will increase 12 thousand of dollars (although it does not make sense to increase a unit a proportion, serve as an example).
Comment: Thank you David for your reply. But since the independent variable is in proportion. How to interpret the increase of one unit?
Comment: @RogKa Divide by $100$ to get increments of one "proportion point". If you increase the proportion by $0.01$, then $y$ increases by $\hat\beta/100$. // Since it is silly to increase a proportion by $1$, it could be worth mentioning this in the answer. // If you want to talk about percent increases, where increasing from $0.1$ to $0.2$ is a $100\%$ increase instead of a $0.1$ increase, life gets harder. Is this what you want to do?
Comment: I'm not sure if I'm understanding properly your question. Let's suppose the increase of the ```hrs_prop``` is $n, \ \forall \ n \ \in \ [0, 0.24]$. The result of increasing $n$ units ```hrs_prop``` will result in an increase of $\beta \cdot n$ the variable ```income``` . For example, if the proportion increases 0.1 units, the ```income``` will increase $0.1 \cdot 12$ units. In your particular case, that will result in an increase of 1.2 thousand of dollars.
Comment: The example clarifies. thanks a ton


Validações de Strings

Question: Andei pesquisando como validar e-mail, datas, horas etc. E no caso do e-mail, encontrei um código como este: /^.+@.+\..{2,}$/;. Ele está incompleto. Mas queria entender o que são esses símbolos, e o que eles representam para fazer a validação de uma string?
Se alguém puder esclarecer como isso funciona eu agradeço.
Comment: Olá tudo joia? se tratam de expressões regulares e em programação ajudam muito inclusive se tem livros escritos somente para esse tipo de conteúdo, acredito que significa excessão a barra depois pode se colocar qualquer caractere seguido de arroba e logo depois segue de qualquer cacatere e depois se tem uma lista com dois caractere e por fim finaliza, se esqueci ou errei alguma coisa peço desculpas fiz rapidinho de cabeça. segue um link de conceitos básicos de expressões regulares: http://www.devmedia.com.br/conceitos-basicos-sobre-expressoes-regulares-em-java/27539
Answer: A explicação dessa regex é assim:

/^.+@.+\..{2,}$/

/ - simbolo de abertura do objeto regex.
^ - indica inicio da string
.+ - qualquer carater menos mudança de linha, uma ou mais ocorrências
@ - um caracter "arroba"
\. - o caracter ponto, escapado porque em regex o ponto tem uma funcionalidade, assim com \ quer dizer o proprio caracter ponto e não a função que ele costuma ter em regex
.{2,} - qualquer caracter menos mudança de linha, dois seguidos ou mais
$ - final da string
/ - fecho do objeto regex

Há um site muito bom para analizar regex, dá uma olhada aqui: https://regex101.com/r/tP8yC9/1
Comment: E essas expressões regulares é um padrão para todas as linguagens? É a mesma coisa no java e no jquery ou javascript?
Comment: @Vynstus na grande maioria sim. Creio que o teu exemplo funciona bem noutras linguagens. No link que passei na resposta podes mudar linguagem na barra da esquerda. Podes também dar uma olhada aqui: https://en.wikipedia.org/wiki/Comparison_of_regular_expression_engines
Comment: @Vynstus a resposta era o que procuravas?
Comment: Sim, desculpe a demora. Obrigado.

Validações de Strings


How Do you Evaluate $z=(2+2i)^{4i}$

Question: I am trying to evaluate $z=(2+2i)^{4i}$ in the form $u+iv$ but I unsure how to. I am aware of the notion of complex logarithm and I initially thought it to be related to logs in some way but I could not get the correct answer. I would preferably like to just be pointed in the right direction so that I can try to get the correct answer for myself.
Thanks in advance!
Comment: Does this answer your question? [How to calculate $i^i$](https://math.stackexchange.com/questions/1027646/how-to-calculate-ii)
Comment: $(2+2i)^{4i}=e^{4i(\log2+\log(1+i))}$, then use the fact that $1+i=\sqrt{2}e^{i\pi/4}$ to get (using the principal $\log$) that $(2+2i)^{4i}=e^{4i(\log(2)+\frac12 \log(2)+i\pi/4}=e^{6i\log(2)-\pi}=2^{6i}e^{-\pi}$
Answer: You can have a look at my general presentation for $z^u$ when both $z$ and $u$ are complex numbers.
https://math.stackexchange.com/a/3729281/399263
So as I indicated express $z=2i+2$ in polar form and write the periodicity explicitly: $$2+2i=2\sqrt{2}\exp\left(i\frac{\pi}4+2ik\pi\right)\text{ for }k\in\mathbb Z$$
Then multiply the inners of the exponential by $u=4i$ in cartesian form:
$(2+2i)^{4i}=\exp\Big(4i\times\big(\underbrace{\ln(2\sqrt{2})}_{\frac32\ln(2)}+i\frac{\pi}4+2ik\pi\big)\Big)=\exp\Big(6i\ln(2)-\pi-8k\pi\Big)$
To make the principal value appear, separate what's depends on $k$ and what's not:
$$\begin{cases}z_{[0]}=\exp\big(6i\ln(2)-\pi)\big)=e^{-\pi}\Big(\cos(6\ln(2))+i\sin(6\ln(2))\Big)\\\\w^k=\exp\big(-8k\pi\big)=(e^{-8\pi})^k\end{cases}$$
Finally you get the multivalued expression $(2+2i)^{4i}=z_{[0]}\times w^k$
With $ k\in\mathbb Z$, where $z_{[0]}$ is called the principal value, and $w$ the multiplicative factor.
Comment: Better than I wanted to do it.

How Do you Evaluate $z=(2+2i)^{4i}$


Windows "User must change password at next logon" with kiosks?

Question: Is there a way to allow users to change their passwords from a web page in Windows?
We have a client that has hundreds of 'kiosk' workstations because all the users use web services that have their own logins.  All the machines are domain-joined and they sign in to one account automatically.
One of the 'web apps' users sign in to relies on each individual having an account in active directory.  When a user forgets their AD password, we would like to reset it to a default password that everyone in the company knows, and we tell the user to go reset it.
On a 'normal' windows network, they would hit CTRL+ALT+DEL, put in their username and the default password, and then be prompted to change it.
...but on a kiosk network, they are already signed in to the generic account, and the web app has no way of forcing the password change.  So they still can't sign in.  We also can't enforce policies of expiring passwords every $x months.
I know Outlook Web Access has a form built-in for allowing users to change passwords.  Unfortunately, this client doesn't use Outlook Web Access.
Is there a 3rd party utility or a better way of allowing users to change their passwords?  Even a desktop app we can tell them to run to enter a username, default password, new password, and a confirmation would be useful.
Comment: There are plenty of such products.  But product recommendations aren't really allowed here on SF.  Maybe look at Forefront Identity Manager Self Service Password Reset portal.
Comment: Do you have a budget? You can create your own via https://msdn.microsoft.com/en-us/library/ms180915(v=vs.90).aspx
Answer: I finally found a solution.
In Windows Server 2003 and earlier IIS creates an iisadmpwd folder under c:\windows\system32\inetsrv\.  That app can be used to change passwords.
Unfortunately the app is no longer distributed with Windows Server 2008 or later, but you can apparently copy the source over to a Windows Server 2008 or later machine and get it to run.
http://blogs.msdn.com/b/asiatech/archive/2009/03/17/how-to-manage-my-windows-user-password-through-iis-web-portal.aspx
A little Microsoft hate: Be careful if you try to install this on a server with existing websites (especially Outlook Web Access) as something as simple as registering a single DLL will take down IIS and cause all your apps to start throwing errors until your ApplicationHost.config file as documented here:
http://devfarm.it/asp-net-mvc-2/install-website-windows-2008-64-bit-ms-exchange/


preciso passar esse cod para angularjs alguem sabe me ajudar

Question: Alguém sabe passar isso para angular?
$(document).on(
    'keydown',
    function(e) {
        if (e.ctrlKey && e.altKey
            && e.which === 83) {
        $(".btnSalvarRegistro").click();
    }
);

por favor me ajude.
Answer: É recomendado pela documentação do AngularJS fazer o controle de eventos via diretivas, mas postarei dois exemplos para que você veja qual se adequará a seu caso:
Via Diretiva

var app = angular.module('app', []);

app.directive('shortcut', function($document) {
  return {
    restrict: 'E',
    replace: true,
    scope: true,
    link:    function postLink(scope, iElement, iAttrs){
      $document.on('keypress', function(e){
      console.log(e.ctrlKey)
      console.log(e.altKey)
      console.log(e.which)
      console.log("--------")
          if(e.ctrlKey && e.altKey && e.which === 83){
            scope.$apply(scope.changeMessage("letra S +  apertada"));
            e.preventDefault()
          }
      });
    }
  };
});

app.controller('MainCtrl', function($scope) {

$scope.changeMessage = function(m){
  $scope.message = m
}

});

  <shortcut></shortcut>

View keys pressed

  <input type="text">
  {{message}}

Via Controller

var app = angular.module('app', []);

app.controller('KeydownController', function KeydownController($scope, $document) {
  $scope.counter = 0
  $document.on("keypress", function (event) {

      // AO APERTAR ENTER
      if(event.which === 83) {

          $scope.$apply($scope.counter++);
          event.preventDefault();
      }
  });
});

  <input type="text">
  {{counter}}


Creating a View filter for a CCK field

Question: I have created a custom filter which displays some select options to the user in order to filter a view. However, I am uncertain how to add this using the hook_views_data() hook, being that the table which the filter is being applied to is a CCK table called content_type_sm_mention.
Currently I have the following, which I am not sure is right. What is missing?
function smd_views_data()
{
    $data = array();
    $data['content_type_sm_mention']['sentiment'] = array(
      'title' => t('Sentiment'),
      'help' => t('Filter by mention sentiment.'),
      'real field' => 'field_mention_sentiment_value',
      'group' => t('Content'),
      'filter' => array(
        'handler' => 'views_handler_filter_sentiment',
      ),
    );
    return $data;
}
function smd_views_handlers() {
  return array(
    'info' => array(
      'path' => drupal_get_path('module', 'smd') . '/includes/views',
    ),
    'handlers' => array(
      'views_handler_filter_sentiment' => array(
        'parent' => 'views_handler_filter',
      ),
    ),
  );
}

Answer: To find out what is missing, implement hook_views_data_alter() and dsm($data) in the function to find the right path for your field.
Answer: I would look at content_views_data() in the cck module to see if you can figure out what it is returning.
Comment: If he is asking is probably because he did and he could not figure it out. Why don't you explain what he is doing in his example instead?
Comment: @lordg I am in the same position as you...

Creating a View filter for a CCK field


gcp kubernetes autopilot mode, what is the free tier

Question: I'm trying to use the free tier (autopilot mode) to learn k8s on gcp.  However I cam across the following Is it possible to have Google Cloud Kubernetes cluster in the free tier?.  However when I checked the link given in the question I could not find the specified limitation f1-micro machines are not supported due to insufficient memory.  Is this still valid ? can I use k8s on gcp in the free tier without incurring any cost?
Answer: There is no way to get a free GKE cluster on GCP, but you can get a very cheap one by following the instructions at
https://github.com/Neutrollized/free-tier-gke.
Using a combination of GKE's free management tier and a low cost machine type, the cost estimate is less than $5 per month: .
More details on what is available as part of the free tier can be found here: https://cloud.google.com/free.
Also, for your question regarding limitation of f1-micro to be used in GKE,if you follow the documentation limitation
It is written that- Minimum CPU platform cannot be used with shared core machine types. Now since f1-micro machines are shared core machine types. So it is valid and cannot be used.
Answer: As described in the documentation, there is no management cost for 1 Autopilot or 1 GKE standard zonal mode.
You don't pay for the control plane. But then you have to pay for your workload measured in seconds for autopilot (pod level) and seconds for GKE standard (node level (compute engine))
Answer: Hi If you want to learn the K8s on GCP you can try using qwiklabs where you get some initial credits by which you can access some of the labs where you can learn and practice your activities. https://go.qwiklabs.com/qwiklabs-free
Answer: For study purpose, I believe its better to have classic (Standard) GKE cluster rather than autopilot, where you have less managing options.
When its come to pricing, using Preemptible nodes in GKE cluster is a better option where pricing is really low.
you can enable this selecting as below
Preemptible nodes


What is the expectation of the product of two random variables of Dirichlet distribution?

Question: I understand that the expectation of a random variable $X_i$ a Dirichlet distribution is $E[X_i] = \frac{\alpha_i}{\sum_k \alpha_k}$ and $E[\ln(X_i)] = \psi(\alpha_i) - \psi(\sum_k \alpha_k)$
I read a great paper "Distribution of Mutual Information from Complete and Incomplete Data" that states that $E[X_i\ln(X_i)] = \sum_{i} \frac{\alpha_i}{\sum_k \alpha_k} \{\psi(\alpha_i) - \psi(\sum_k \alpha_k)\}$
I was wondering what is $E[X_i X_j]$?
Can I use the property $\operatorname{Cov}(X_i X_j) = E[X_i X_j] - E[X_i] E[X_j]$ to get $E[X_i X_j] = \operatorname{Cov}(X_i X_j) + E[X_i] E[X_j]$?
What about $E[X_i \ln(X_j)]$? Can I also use the $\operatorname{Cov}$ to derive it?
Latest update:
I believe that $E[X_i \ln(X_j)]$ can be derived using $\operatorname{Cov}[X_i, \ln(X_j)]$
I found that
$\mathrm{Cov}[X_i,X_j] = \frac{- \alpha_i \alpha_j}{\alpha^2 (\alpha+1)} \ \ \ $ where    $\alpha = \sum_{i=1}^K\alpha_i$
and
$\operatorname{Cov}[\log(X_i),\log(X_j)] = \psi'(\alpha_i) \delta_{ij} - \psi'(\alpha_0)$ where $\psi$ is the digamma function, $\psi'$ is the trigamma function, and $\delta_{ij}$ is the Kronecker delta
Is there a form for $\operatorname{Cov}[X_i,\log(X_j)]$? If so, we can use it to derive $E[X_i \ln(X_j)]$.
Comment: I am confused. What are you asking?
Comment: @Lost1 I apologise for the poor English, I have amended the question. My main question is how to derive $E[X_i \ln(X_j)]$
Answer: $$E(X_i)=\frac{\alpha_i}{\alpha}\qquad E(X_iX_j)=\frac{\alpha_i\alpha_j}{\alpha(\alpha+1)}\qquad\alpha=\sum_k\alpha_k$$
Edit: Recall that for every $i\ne j$ the density $f$ of the distribution $f$ of $(X_i,X_j)$ is such that
$$
f(x,y)=\frac{\Gamma(\alpha)}{\Gamma(\alpha_i)\Gamma(\alpha_j)\Gamma(\alpha-\alpha_i-\alpha_j)}x^{\alpha_i-1}y^{\alpha_j-1}(1-x-y)^{\alpha-\alpha_i-\alpha_j-1}\mathbf 1_D(x,y),
$$
where
$$D=\{(x,y)\mid x\gt0,y\gt0,x+y\lt1\}.$$
Hence,
$$
E(X_i\log X_j)=\iint_Dx\log y\,f(x,y)\,\mathrm dx\mathrm dy,
$$
that is,
$$
E(X_i\log X_j)=\frac{\Gamma(\alpha)}{\Gamma(\alpha_i)\Gamma(\alpha_j)\Gamma(\alpha-\alpha_i-\alpha_j)}\iint_Dx^{\alpha_i}y^{\alpha_j-1}(1-x-y)^{\alpha-\alpha_i-\alpha_j-1}\log y\,\mathrm dx\mathrm dy.
$$
The change of variable $x=(1-y)z$ yields
$$
E(X_i\log X_j)=\frac{\alpha_i}\alpha\frac{\Gamma(\alpha+1)}{\Gamma(\alpha_j)\Gamma(\alpha-\alpha_j+1)}\int_0^1y^{\alpha_j-1}(1-y)^{\alpha-\alpha_j}\log y\,\mathrm dx\mathrm dy=\frac{\alpha_i}\alpha E(\ln Y),
$$
where $Y$ is beta $(\alpha_j,\alpha-\alpha_j+1)$. According to the WP page on the beta distribution,
$$
E(\ln Y)=\psi(\alpha_j)-\psi(\alpha+1),
$$
hence
$$
E(X_i\log X_j)=\frac{\alpha_i}\alpha(\psi(\alpha_j)-\psi(\alpha+1)).
$$
Comment: Thank you very much for your answer. Do you have the form for $E[X_i \ln(X_j)]$?
Comment: As an integral on $[0,1]\times[0,1]$, sure.
Comment: can you show me how? Thanks!
Comment: Whoa! Thank you so much! You are a genius. Do you have any recommendations for a good book on Dirichlet distribution? I could not find any references that talk about joint Dirichlet distribution.
Comment: @Michael Your edit is incorrect. Users Dan and Eupraxis1981: Before "Approving" an Edit, please make sure it is not absurd. To believe that $α_i=α−α_j$ and/or $αΓ(α)=Γ(α+1)$ could be "change of variables" is a sure sign one does not know what is going on.
Comment: @Michael No reference, really? http://en.wikipedia.org/wiki/Dirichlet_distribution
Comment: I apologise for my incorrect edit. I thought you use $\alpha_i = \alpha - \alpha_j$ and $\alpha \Gamma(\alpha) = \Gamma(\alpha+1)$ to get the second step of $E(X_i \log X_i)$


Lebesgue measure of a subset of the unit circle

Question: I'm having trouble getting started on this question:
Let $S^1$ be the unit circle. Let $m = d \theta$ be the Lebesgue measure on $S^1$. Let $M \subset S^1$ be a measurable set such that $m(M) \geq 3 \pi / 2.$ Let
$$ X = \{ \theta \in S^1: m(M \cap (\theta - 0.1, \theta + 0.1)) \leq 0.1\}. $$
Prove that $m(X) \leq \pi.$
Any suggestions?
Comment: What's the Lebesgue measure on $S^1$ - arc lenght?
Comment: Pretty much. But you formally define it as a push forward of the Lebesgue measure on $\mathbb{R}$ under the function $e^{i\theta}.$ This will agree with arclength for any arc on the circle.
Answer: Convolution is a powerful tool. Let $A = \{ e^{i\theta} : \lvert \theta\rvert < 0.1\}$, and $f = \chi_A \ast \chi_M$. Then you have $X = f^{-1}([0,0.1])$, and
\begin{align}
\int_{S^1} f(\theta)\,d\theta &= \int_{S^1} \int_{S^1}\chi_A(\theta-\varphi)\chi_M(\varphi)\,d\varphi\,d\theta\\
&= \int_{S^1}\int_{S^1} \chi_A(\theta-\varphi)\chi_M(\varphi)\,d\theta\,d\varphi\\
&= \int_{S^1} m(A)\chi_M(\varphi)\,d\varphi\\
&= m(A)\cdot m(M)\\
&= 0.2 m(M)\\
&\geqslant 0.2\cdot\frac{3\pi}{2}.
\end{align}
On the other hand,
\begin{align}
\int_{S^1} f(\theta)\,d\theta &= \int_X f(\theta)\,d\theta + \int_{S^1\setminus X} f(\theta)\,d\theta\\
&\leqslant 0.1\cdot m(X) + 0.2\cdot m(S^1\setminus X)\\
&= 0.2\cdot 2\pi - 0.1\cdot m(X),
\end{align}
so, combining with the above
$$0.2\cdot\frac{3\pi}{2} \leqslant 0.2\cdot 2\pi - 0.1\cdot m(X) \iff m(X) \leqslant 2\bigl(2\pi - \tfrac{3\pi}{2}\bigr) = \pi.$$


How do I find the records with the maximum value for a particular field in a group

Question: I have a graphs table which has fields name and version.  Each time a record is inserted the version is 0 if name does not exist in the database and max(version) + 1 otherwise. I'd like to get list of records with the highest version for each unique name.  The following code does this:
def self.latest_versions
   Graph.group(:name).maximum(:version).map{ |k,v|  find_by name: k, version: v}
end

but I wonder if there is a much faster way to do this using a scope that just chains active record relations?
Answer: How about this
def self.latest_versions
  name_versions = Graph.group(:name).maximum(:version).map {|k,v| [k,v].join(';')}
  Graph.where("concat(name, ';', version) IN (?)", name_versions)
end

after get the name, version groups, convert it into an array, which concat the 2 column into 1, by query through the composed column, we only need another sql query, totally 2, much better than the existed one.
Comment: I do not think this will work, it just returns the record with the maximum version number over all graphs.  There are different types of graphs, distinguished by the :name field. Each type of graph has its own versioning, so the most recent graph with name 'line_plot', might have version 5, and the most recent graph with name 'bar_plot', might have version 7. Your code will only return version 7 of the 'bar_plot', but I need to return both version 7 or 'bar_plot' and version 5 of 'line_plot'
Comment: yep, understand now, sorry for the misunderstand.
Comment: @Obromios i have update the `answer`, you can check it.
Comment: This does look better, except for a typo, you just need to close with a right parenthesis at the end of the third line. I have accepted and upvoted it.  If you think the question and your answer could be useful to others please upvote the question.
Comment: Thanks, i have fix the typo broblem.


Infinite product representation of a function in terms of its non-trivial zeroes?

Question: From Wikipedia's Weierstrass Factorization Theorem, I learned that every entire function can be represented as a product involving its zeroes. Examples are the sine and cosine function. The Riemann zeta function, however, is not entire.
Let us assume the Riemann Hypothesis. Can $\zeta(s)$ be represented by an infinite product involving both its trivial zeroes at $\zeta(s)=-2n$ (for $n \in \mathbb{N}$) and its non-trivial zeroes at $\zeta(s)=\frac{1}{2} + i t$?
Thanks, Max
Comment: To give a bit of historical context, the Weierstrass factorization is not enough to pin down the factors involved; one has to use Hadamard's factorization instead which relies on information about the growth rate of the function. Actually it is said that Hadamard developed his theory in order to get at the prime number theorem. First, the Riemann xi function was factorized by von Mangoldt by using Hadamard's theory. A few years later Hadamard and de la Vallee-Pousin proved the prime number theorem continuing the same line of development.
Comment: @timur: thank you for the historical background. I like it when mathematics is put into (historical) perspective.
Comment: I have to say that the factorization formula was already stated by Riemann in his famous paper, without rigorous proof. He gave some reasons as to why the formula is valid, and this reasoning was shown to be valid provided that Hadamard's theory is known. The point I wanted to make in my earlier comment but forgot was that the factorization formulas have been from the beginning, and still are one of the most powerful tools to study Riemann's zeta function.
Answer: The standard approach to this problem is to write
$\xi(s) = \dfrac{s(s-1)}{2}\pi^{-s/2}\Gamma(s/2)\zeta(s).$  This function is entire, and has zeroes precisely at the non-trivial zeroes of $\zeta(s)$.  It also has a slow enough rate of growth that it can be written as a product over its zeroes:
$$\xi(s) = \xi(0) \prod_{\rho}(1-\dfrac{s}{\rho}),$$
where the product is over zeroes of $\xi(s)$, i.e. over non-trivial zeroes of $\zeta(s)$.  (Here I am following more-or-less the notation in Edward's book Riemann's zeta function, which is a good reference for these sort of things.)
[Edit: Also, to ensure convergence, the product should be taken over "matching pairs" of zeroes, i.e. the factors for a pair of zeroes of the form $\rho$ and $1-\rho$ should be combined.]
We can then write
$$\zeta(s) = \dfrac{2\xi(0)}{s(s-1)}\pi^{s/2}\dfrac{1}{\Gamma(s/2)}\prod_{\rho}(1-\dfrac{s}{\rho}).$$
If we now replace $\dfrac{1}{\Gamma(s/2)}$ by its Weierstrass product, we get
a product formula for $\zeta(s)$, namely
$$\zeta(s) = \dfrac{\xi(0)}{s-1} (\pi e^{\gamma})^{s/2}\prod_{n=1}^{\infty}(1 +\dfrac{s}{2n})e^{-s/2n}
\prod_{\rho}(1-\dfrac{s}{\rho}).$$
(Here $\gamma$ is Euler's constant.)
Note that we can now compute $\xi(0)$, because we know that the value of $\zeta(s)$ at $s = 0$ is equal to $-1/2$.  We find that $\xi(0) = 1/2$,
and so
$$\zeta(s) = \dfrac{1}{2(s-1)}(\pi e^{\gamma})^{s/2}\prod_{n=1}^{\infty}(1+\dfrac{s}{2n})e^{-s/2n}\prod_{\rho}(1-\dfrac{s}{\rho}).$$
An added cultural remark: Riemann's explicit formula for the prime counting function is obtained by taking a Fourier transform of the logarithm of this formula.  Combined with the fact that all the non-trivial zeroes $\rho$ have real part $< 1$ (proved by Hadamard and de la Vallee Poussin), this gives the prime number theorem.
Comment: [Here's the MathWorld entry for $\xi(s)$](http://mathworld.wolfram.com/Xi-Function.html).
Comment: @ J.M. and especially Matt: thanks a lot! Is p for prime here or does it stand for the non-trivial zeroes of $\zeta(s)$?
Comment: Never mind I see it's the zeroes. Can we also do something about the $e^{-s/2n}$ part, as in incorporating it somehow in the part between the brackets (of the infinite product of (1+s/2n))? Something similar was done with the sine function (see the link I mentioned, you'll see it at the bottom).
Comment: To nitpick, the factors in the factorization of xi must be paired, as in $\xi(s)=\prod_{\Im\rho>0}(1-\frac{s}{\rho})(1-\frac{s}{1-\rho})$.
Comment: @timur: Dear Timur, Thanks for pointing this out.  I'll add this as a remark into the answer.  Regards,
Comment: @Max: Dear Max, These exponential factors are needed to ensure convergence of the product.  In the case of $\sin(x)$, we can pair the factors corresponding to matching positive and negative zeroes so as to cancel out the exponential factors, but that trick isn't available here, and so I don't think they can be removed.  Regards,
Comment: @Max: They come from the Gamma function so they are harmless and I think no reason to try to remove them. The reason you cannot treat them as in sine is that $1/\Gamma$ is an entire function having essentially (negative) half of the zeroes of sine, and the other (positive) half is needed to pair them up and cancel the exponential factor. This is also the reason why you get $\sin(z)$ when you multiply $1/\Gamma(z)$ with something like $1/\Gamma(-z)$.
Answer: (Would be a comment, but I don't have the reputation.)
The Riemann zeta function is certainly not entire: it has a simple pole at s = 1. It is, however, meromorphic.
Comment: Ok so when a function has a point at which the value of the function is 'infinity' the function is not entire, no? Thanks, Zhen.
Comment: Not entire, but such singularity (called poles) is better than the other case which is called essential singularity.


DisplayForModel() not displaying complex objects + MVC4

Question: I have the below model:
public class Car
{
    public int Id { get; set; }
    public string Colour { get; set; }
    public Category Category { get; set; }
}
public class Category
{
    public int CatId { get; set; }
    public string Name { get; set; }
}

I am returning the model to view as below:
 public ActionResult Index()
    {
        var car = new Car { Id = 1, Colour = "Black", Category = new Category { CatId = 2, Name = "Audi" } };

        return View(car);
    }

My view is :
@model MvcApplication6.Models.Car

@{
ViewBag.Title = "Car";
 }

@Html.DisplayForModel()

This is not displaying the Category.
I have and found this is a bug in MVC, and as a workaround I need to override Object.ascx displaytemplate.
So I have added, object.cshtml in Views/Shared/DisplayTemplates/ folder, the code is below.
@functions{
public bool ShouldShow(ModelMetadata metadata)
{
    //return number % 2 == 0 ? true : false;

    return metadata.ShowForDisplay
       && metadata.ModelType != typeof(System.Data.EntityState)
       && !metadata.IsComplexType
       && !ViewData.TemplateInfo.Visited(metadata);
}
}

@if (Model == null) {
@(ViewData.ModelMetadata.NullDisplayText)
} else if (ViewData.TemplateInfo.TemplateDepth > 1) {
@(ViewData.ModelMetadata.SimpleDisplayText)
} else {
foreach (var prop in ViewData.ModelMetadata.Properties.Where(pm => ShouldShow(pm))) {
    if (prop.HideSurroundingHtml) {
        @(Html.Display(prop.PropertyName))
    } else {
        if (!String.IsNullOrEmpty(prop.GetDisplayName())) {

@(prop.GetDisplayName())

        }

@(Html.Display(prop.PropertyName))

        }
    }
}

however still the catogery is not getting displayed, can somebody advsie?
Answer: Hm, i made everything like you and got code for template from here: http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-3-default-templates.html
HomeController.cs
public class HomeController : Controller
    {
        //
        // GET: /Home/
        public class Car
        {
            public int Id { get; set; }
            public string Colour { get; set; }
            public Category Category { get; set; }
        }

        public class Category
        {
            public int CatId { get; set; }
            public string Name { get; set; }
        }

        public ActionResult Index()
        {
            var car = new Car { Id = 1, Colour = "Black", Category = new Category { CatId = 2, Name = "Audi" } };

            return View(car);
        }
    }

Index.cshtml
@model MvcApplication1.Controllers.HomeController.Car

@{
    ViewBag.Title = "Car";
}

@Html.DisplayForModel()

Views/Shared/DisplayTemplates/Object.ascx
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<% if (Model == null) { %>
    <%= ViewData.ModelMetadata.NullDisplayText %>
<% }
   else if (ViewData.TemplateInfo.TemplateDepth > 1) { %>
    <%= ViewData.ModelMetadata.SimpleDisplayText %>
<% }
   else { %>
    <% foreach (var prop in ViewData.ModelMetadata.Properties.Where(pm => pm.ShowForDisplay
                         && !ViewData.TemplateInfo.Visited(pm))) { %>
        <% if (prop.HideSurroundingHtml) { %>
            <%= Html.Display(prop.PropertyName) %>
        <% }
           else { %>
            <% if (!String.IsNullOrEmpty(prop.GetDisplayName())) { %>

<%= prop.GetDisplayName() %>

            <% } %>

<%= Html.Display(prop.PropertyName) %>

        <% } %>
    <% } %>
<% } %>

And i have this result:

Edit:
By the way, if you remove this code from DisplayTemplate:
if (ViewData.TemplateInfo.TemplateDepth > 1) { %>
    <%= ViewData.ModelMetadata.SimpleDisplayText %>
<% }

You could see next result:

That's happen, because when display template started to display Category Category property, TemplateDepth gone to be 2 and you just see identity property, not full object.