Android 'drawable' folders selection issue

Question: I am currently building an Android application (a game). I have created ldpi, mdpi and hdpi of all of the images (the dimensions of all of these images have been appropriately calculated).
When I test the game on my Samsung S3, the value of the below code is 2.0.
getResources().getDisplayMetrics().density;

This is correct, and all images used in the application are automatically selected from the drawable-hdpi folder.
However, when I test the application on my Google Nexus One, the above code evaluates to 1.5 (correctly), and yet images from the drawable-hdpi folder are still automatically selected.
For reference, I am loading the bitmaps in this manner:
BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inScaled = false;
Bitmap exampleBitmap = BitmapFactory.decodeResource(gamePanel.getResources(), R.drawable.example, bmpFactoryOptions);

EDIT: Removing the second line still does not fix the issue.
Am I doing something wrong? If so, what? Alternatively, is there a workaround?
Many thanks in advance.
Answer: The Samsung Galaxy SIII is an XHDPI device.
The Nexus One is a HDPI device.
Reference:
http://blog.blundellapps.com/list-of-android-devices-with-pixel-density-buckets/
Therefore, because you don't have XHDPI resources, it uses the next closest for the SIII (hdpi).
Comment: Thanks for concisely clearing up the issue. The reference has provided me with a significant amount of extra detail. The image at the bottom of the article was especially useful. I will give you 'Best answer' since the article referenced will probably be the most applicable to general issues relating to pixel densities (for people searching for answers in the future).
Answer: I'm fairly certain that the S3 (2.0 density) is xhdpi, whereas the Nexus One (1.5 density) is hdpi. 1.0 is the reference density (mdpi). What's most likely happening is that the S3 is falling back to the hdpi folder since you've not provided xhdpi resources, and the Nexus One is correctly pulling from the hdpi folder.
Comment: @WillManson 1.0 means a ratio of 1 and MDPI is the 'baseline' resolution. Here's an image to explain: http://developer.android.com/images/screens_support/screens-densities.png
Comment: Aha! I did not realise that 2.0 linked to xhdpi (I foolishly assumed that 1.0 linked to ldpi). Thank you very much for your timely response, you have saved me much frustration.


Angular: $event is not object

Question: I got this error:
TypeError: Cannot read property 'preventDefault' of undefined at Scope.$scope.dispatchAction.
I can't figure out what is the problem, would you please help me? Thanks.
----Template----
$templateCache.put("template/dropdown-user.html",
    '
'+
        '
'+
            " {{item.label}}"+
        '
'+
        "

"+
    '
'
    );

---Directive---
.directive('navbarMenuUserItem',[function(){
    return {
        restrict: 'E',
        templateUrl: 'template/dropdown-user.html',
        replace: true,
        scope:{
            items: '=',
            click: '&itemClick'
        }
    }
}])

---HTML---
<navbar-menu-user-item item-click="dispatchAction(obj,event)" items="usermenu"></navbar-menu-user-item>

Controller*
app.controller('dashboardCtrl',
['$scope','$sanitize','$log','$location','dashboardService','AuthService',
    function($scope, $sanitize, $log, $location, dashboard,AuthService){

        $scope.messages = dashboard.getMessages();
        $scope.usermenu = dashboard.getUserMenu();
        $scope.sidebarmenu = dashboard.getSidebar();

        $scope.logout = function(){
            AuthService.logout();
            $location.path('/');
        };

        $scope.dispatchAction = function(obj,event){
            event.preventDefault();
            console.log(obj);
        };

    }
]);

Comment: You're using wrong syntax to call scope function binding. Try `<a ng-click=\"click({obj:item,event:$event})\"` in your template dropdown-user.html
Comment: @KhanhTO, I just added the $, but still no luck, thanks.
Comment: I think that both obj and event here are undefined, can you just log them without any operations? `item-click="dispatchAction(obj,event)"`
Answer: Khan TOs suggestion is correct. You have to bind your item and your event to the scope in which your expression item-click should be evaluated.
Alternativly you could change your isolated scope definition in the directive to:
scope:{
        items: '=',
        click: '=itemClick'
    }

And your item-click attribute in the HTML to:
item-click="dispatchAction"

In this way you bind your dispatchAction function directly to a variable in your directives scope.

Angular: $event is not object


Supervisord on Fedora configuration error

Question: I am trying to install supervisor on my Fedora 17, using this link as reference:
https://www.digitalocean.com/community/articles/how-to-install-and-manage-supervisor-on-ubuntu-and-debian-vps
It works fine except one trivial problem (I believe).

A simple configuration for our script, saved at /etc/supervisor/conf.d/long_script.conf, would look like so (...)

My problem is, that I have only files/directories:
/etc/supervisord/
/etc/supervisord.conf

I have tried to create conf.d directory under /etc/supervisord/. I have put my config file into /etc/supervisord/conf.d/ and /etc/supervisord/ and also /etc/sueprvisor/.
Despite my effort when issuing command:
supervisortctl reread

I receive:
No config updates to processes

Anyone has a clue what I might be doing wrong? Thanks in advance.
Answer: (I'm on Fedora 20) If you look at /etc/supervisord.conf at the bottom you see
[include]
files = supervisord.d/*.ini

So on Fedora your configuration files should end in .ini instead of .conf. I had this same problem and running supervisorctl reread after this detects stuff
Comment: I installed supervidord in centOS and it has `.ini` instead of `.conf` file
Answer: There is no need to create a folder specifically for your configuration file, you can specify its path with the -c /path/to/your/file or --configuration=/path/to/your/file option.
Source: http://supervisord.org/running.html


How do I know which version of MPICH I am having on my windows machine

Question: I just wanted to check what is the version of the library I am having on my windows 7 machine.
How do I do?
I have successfully run some some simple examples such as calculation of PI etc.
This I did by typing commands on CMD prompt.  I guess some command must exist for finding version.
Also the following does not work on my windows machine

mpiexec --version

C:\Users\acme>mpiexec --version
Unknown option: -version Error: no executable specified Unable to parse the mpiexec command arguments.

Comment: treid all possible combinations, but did not work:
Comment: have you tried `-version` or `/v`? Or just `mpiexec` and see what it says? Windows sometimes uses a slightly different syntax for arguments than the Unix world.
Answer: MPICH is is distributed with another binary in the bin/ directory called mpichversion. I'm assuming this is true in the old Windows distributions as well. (Windows hasn't been supported since 1.4.1p) If that's in there, you can just run that.


New mean calculation in multivariate gaussian

Question: Given a Gaussian distribution $N(\mu_1,\sigma_1^2)$, i would like to choose another mean $\mu_2$ which is $2\sigma_1$ away from $\mu_1$.
In this case our new mean $\mu_2=\mu_1\pm 2\sigma_1$.
How do we calculate the new mean($\mu_2$) in multivariate case?
I mean to say, when your multivariate Gaussian distribution is $N(\mu_1,\Sigma_1)$ and my $\Sigma_1$ is symmetric positive definite matrix. i.e
$\left[ \begin{array}{cc} \sigma_x^2 & \sigma_{xy} \\ \sigma_{yx} & \sigma_y^2 \end{array} \right]$.
Comment: what is the context of this problem? As it stands now, it is impossible to answer, since in multivariate case the means are vectors and the distance between them is a number, but the covariance matrix is not.
Comment: I am not sure that I understand even the univariate case. By $\mu_2=\mu_1\pm 2\sigma_1$ you mean that both answers are ok?
Answer: In the bivariate case you can substitute the two points ($\mu_2=\mu_1\pm 2\sigma_1$) with an isodensity ellipse: http://www.stat.psu.edu/online/courses/stat505/05_multnorm/06_multnorm_revist.html .
Your $2\sigma_1$ criterion seems a bit arbitrary, but it includes 95.44997% of the random variable. So you may want to use the 95.44997% isodensity ellipse in the bivariate case, too. The principle axes of this rotated ellipse are the eigenvectors of the covariance matrix, see http://web.as.uky.edu/statistics/users/viele/sta601s08/multinorm.pdf . You can generalise this to more than 2 dimensions.


Two fields values bind to one xrlabel at runtime

Question: My report is bind with DataTable. I want to show two field values in my label.
private void Form1_Load(object sender, EventArgs e)
{
    using (rptCustomer rpt = new rptCustomer())
    {
        rpt.DataSource = CreateTestData();
        rpt.DataMember = CreateTestData().TableName;

        rpt.xrLabel.Text = "[CustomerID] - [CustomerName]"; // it's doesn't work

        //rpt.xrLabel.DataBindings.Add("Text", null, "Customer.CustomerID"); -- it's work

        rpt.xrCustomerID.DataBindings.Add("Text", null, "Customer.CustomerID");
        rpt.xrCustomerName.DataBindings.Add("Text", null, "Customer.CustomerName");
        rpt.xrCustomerAddress.DataBindings.Add("Text", null, "Customer.Address");
        rpt.ShowPreviewDialog();
    }
}

public DataTable CreateTestData()
{
    DataTable dt = new DataTable("Customer");
    dt.Columns.Add("CustomerID");
    dt.Columns.Add("CustomerName");
    dt.Columns.Add("Address");

    for (int i = 1; i <= 10; i++)
    {
        DataRow row = dt.NewRow();
        row[0] = i;
        row[1] = "Customer " + i;
        row[2] = "Address " + i;
        dt.Rows.Add(row);
    }

    return dt;
}

This is my result report.
[CustomerID] - [CustomerName] must be 1 - Customer 1.
Answer: You need to use DataSet object as data source of your report.
Here is example:
using (rptCustomer rpt = new rptCustomer())
{
    var dataSet = new DataSet("TestDataSet");
    var table = CreateTestData();

    dataSet.Tables.Add(table);

    rpt.DataSource = dataSet;
    rpt.DataMember = table.TableName;

    rpt.xrLabel.Text = "[CustomerID] - [CustomerName]"; // Suddenly, it's work.

    //rpt.xrLabel.DataBindings.Add("Text", null, "Customer.CustomerID"); -- It's work too.

    rpt.xrCustomerID.DataBindings.Add("Text", null, "Customer.CustomerID");
    rpt.xrCustomerName.DataBindings.Add("Text", null, "Customer.CustomerName");
    rpt.xrCustomerAddress.DataBindings.Add("Text", null, "Customer.Address");
    rpt.ShowPreviewDialog();
}


How can I add accumulative Margin on button click?

Question: I am trying to add a text slider, where basically a very long text box extends out of the view, and when a button is pressed margin is added so more text can be read. I do not know how to make a button that adds margin without exponentially increasing it each time.

          <button type="button" onclick="display()">Add left margin</button>

This is demo text.

After a few clicks, this starts to increase the margin insane amounts. I believe it is because the 1 is not 1px, but some other unit which makes it add up insanely quick. SO I want to have a button that adds 1px of margin per click, so it smoothly adds margin instead of a big unuseable jump.
My hypothesis is that you need to get the margin value, store it, then add it to a string that has 'px' at the end then update the margin with it?
Answer: You are correct with your thoughts. Store the margin value in a variable outside the function, and increase it by one each time.
The style.marginLeft returns 1px and not 1 which means you cannot increment to it.

var margin = 1;
function display() {
    document.getElementById("myID").style.marginLeft = ++margin + "px";
}

          <button type="button" onclick="display()">Add left margin</button>

This is demo text.

Answer: The parseInt and parseFloat functions will return numeric value for marginLeft (i.e. without the trailing 'px' that is causing your issue).
function display() {
    let el = document.getElementById("myID");
    el.style.marginLeft = `${parseInt(el.style.marginLeft)+1}px`;
 }

Answer: The problem is that happen string concatenation when you use the + operator
You have to convert the value returned from element.style.marginLeft to a number. You can call the Number() function or use the + operator immediately attached how in my solution. Another problem could be that the value returned is like that 1px for example and to increment it you have to parse it, I used split function
function display() {
           let currentMarginValue = +document.getElementById("myID").style.marginLeft.split('px')[0];
           console.log(currentMarginValue)
          var e = document.getElementById("myID").style.marginLeft = currentMarginValue + 1 + "px" ;
       }

Answer: you may need one counter that will increase in every click. please refer below code


Switch to data selection meaning?

Question: I'm setting up rules, trying to setup HTML emailing. I've it setup but not sure how to configure it. What does Switch to data selection mean?'
Comment: Please ask one thing at a time. And whole manual for configuration of SMTP is simply too broad for Q&A format.
Comment: Help with either would be helpful :) I'm hoping that an answer to my first question will help me understand the second. It's already configured, I just don't see where the option is to send html emails is
Answer: For an email action, there are 2 different input modes for the fields in Send HTML email action.

Direct input mode: You're supplying most of the data (e.g. the HTML body) with different token (e.g. <code>[site:slogan]</code>) inserted in it.
Data selector mode: You're using a widget (see image) that lets you drill into data that the Rules action has available. This is useful for finding contextual data (e.g. retrieving the current user's email when a node is updated).

Switch to data selection meaning?


Print view in twig template

Question: My page--front.html.twig is working ok. I want to print the block_1 display of the recent_comments view. I tried this but it does not seem to work.
{{ view.comments_recent(block_1) }}

Answer: You can preprocess a new variable and use views_embed_view like:
$variables['my_view'] = views_embed_view('view_id', 'display_id');

So in your case:
$variables['my_view'] = views_embed_view('comments_recent', 'block_1');

And then in the twig file:
{{ my_view }}

See views_embed_view. It can also take arguments.
Answer: You want the Twig Tweak module. It provides a function to render a view directly in a twig template without the need for preprocessing.
https://www.drupal.org/project/twig_tweak
It also provides a few other functions which might come in handy.

Print view in twig template


Angular Material Datepicker: How to filter so that only dates in an array are allowed?

Question: I have an array of dates returned from an API. For example, I might have an array entitled validDates that has all of the Mondays in September as their values. I would like to use the Material Datepicker filter to only allow date values in the array to be selected.
Example Date Array
validDates = [
    Mon Sep 02 2019 00:00:00 GMT-0500 (Central Daylight Time),
    Mon Sep 09 2019 00:00:00 GMT-0500 (Central Daylight Time),
    Mon Sep 16 2019 00:00:00 GMT-0500 (Central Daylight Time),
    Mon Sep 23 2019 00:00:00 GMT-0500 (Central Daylight Time),
    Mon Sep 30 2019 00:00:00 GMT-0500 (Central Daylight Time)
]

Datepicker Filter (not working)
myFilter = ( d: Date ): boolean => {
    let dateOpen: boolean;
    for ( let x = 0; x < this.validDates.length; x++ ) {
      dateOpen = d.toString() === this.validDates[ x ].toString();
    }
    return dateOpen;
  }

The issue is it only returns the last date (Mon Sep 30 2019 00:00:00 GMT-0500 (Central Daylight Time)) as true so that only the 30th becomes selectable. I want each of the dates in the array to be selectable.
How can I return true for each value in the array?
Comment: where is myFilter used?
Comment: myFilter is used in the component html view
Answer: To only allow dates within an array, the myFilter method may be defined as follows.
myFilter = (d: Date): boolean => {
  // Only allow dates in `validDates`.
  return this.validDates.findIndex( (valid_date) => d.getTime() === valid_date.getTime()) > -1
}

See Stackblitz Demo
To ignore the time component of the Date, see:
Comparing date part only without comparing time in JavaScript
Comment: Worked perfectly and an elegant response. Thanks!
Answer: Finally I found correct solution:
// The array of days of week to be available
const arr = [0, 3, 6];
this.expressSenderDate = (d: Date): boolean => {
    const day = d.getDay();
    // tslint:disable-next-line:align
    return arr.indexOf(day) !== -1;
};


How can I set coordinates to display a specific part of my screen as the center - pygame

Question: I am making a game it is a 2d tile map with scrolling and four direction movements.
I want to set the center a specific part of the map that does not display as center I would have to move to that part of the map for it to center I want to start off at that point as the center.
Comment: move player coordinates to that point? what? can You explain a bit better what You want to achieve, maybe provide a [mre]?
Answer: Suppose you have NxM square tiles with size tile_size and the pygame.Surface object associated with the window (screen).
Set up a rectangle (pygame.Rect) size of the map and align the center of this rectangle with the center of the screen:
map_rect = pygame.Rect(0, 0, N * tile_size, M * tile_size)
map_rect.center = screen.get_rect().center

At the top left of the map_rect rectangle is the offset with which you can place the tiles:
for i in range(N):
    for j in range(M)
        x = i * tile_size
        y = j * tile_size

        # place tile at (x, y)
        # [...]

The same using range(start, stop, step):
for x in range(map_rect.left, map_rect.right, tile_size):
    for y in range(map_rect.top, map_rect.bottom, tile_size):

        # place tile at (x, y)
        # [...]


Why aren't the stems on these 2 notes connected?

Question: Why aren't the stems on these 2 notes connected (one stem pointing upward, and the other one pointing downward)?
Both of them are 1/4 notes though.
Comment: Please post a picture that shows more of the surrounding context. The answer is most likely that the notes are in different "voices" (this can be literally different parts, or imaginary "parts" even in music for one instrument, as a way of thinking of and organizing the music). But this can be confirmed with context. Please also tell what piece this is and the composer.
Comment: Ah, there we go! Yes, you can see how every chord has four notes in it. Even though this is a keyboard arrangement (of an orchestra piece), it preserves the idea of "voices." If it were really fully preserving it, the tenor (second-to-lowest) voice would always be written on the bass clef with its stems pointing up, so that each clef had two voices with the stems telling you which is which.
Comment: Alright, thanks! It's Bach - air on g string
Comment: Okay, Thank you for helping me!!
Answer: It's just a style of notation that emphasizes the separate identity of the two voices.  This is common in multiple-part vocal music, for example, when two parts are written on one staff.
It's not clear what's happening before, but it is apparent that the top voice has a different rhythm from the lower voices, and the mental switch between having separately stemmed voices and then suddenly having them stemmed together might be seen as too jarring.
Comment: Also we often want to avoid changing between separate voices and chords too often, as this looks a bit weird.
Comment: @Lazy I don't understand this comment.  Can you elaborate?  Thanks.


Como customizar "Notification Web API" no Qt?

Question: Estou criando um navegador simples usando QtWebkit e adicionei nele o "suporte" para Notification Web API usando o QWebPage::setFeaturePermission.
Um exemplo:
function notifyMe() {
    if (Notification.permission === "granted") {
        var notification = new Notification("Hi there!");
    } else if (Notification.permission !== "denied") {
        Notification.requestPermission(function(permission) {
            if (permission === "granted") {
                var notification = new Notification("Hi there!");
            }
        });
    }
}

<button onclick="notifyMe();">Notify me</button>

Código:
QObject::connect(page,
    SIGNAL(featurePermissionRequested(QWebFrame*, QWebPage::Feature)), this,
    SLOT(featurePermissionRequested(QWebFrame*,QWebPage::Feature))
);

...

void Form::featurePermissionRequested(QWebFrame* frame, QWebPage::Feature feature) {
    switch (feature) {
        case QWebPage::Notifications:
            qDebug() << "Notification";
            page->setFeaturePermission(frame, feature, QWebPage::PermissionGrantedByUser);
        break;
        case QWebPage::Geolocation:
            qDebug() << "GEO";
        break;
        default:
            qDebug() << "Unknown feature";
    }
}

Sempre que eu clico no botão "Notify me" aparece a seguinte mensagem no Desktop:

Ou seja funciona perfeitamente, porém gostaria de saber se é possível "customizar" as "notifications" no Qt?
Em outras palavras, gostaria que elas fossem similares ao do GoogleChrome ou Firefox, algo como isto:
Comment: mas você não pode customizar usando o JS mesmo? Vê lá na própria página da mozilla tem como customizar, icones, corpo, etc
Comment: @AdirKuhn Acho que você não entendeu o "customizar". O QWebPage usa o `QSystemTrayIcon` para gerar as notificações, o que eu quero é substituir o `QSystemTrayIcon` por um QWidget customizado. Pois mesmo que eu altere o icone no `Notification` ainda sim o QT usa o `QSystemTrayIcon` como na imagem: http://i.stack.imgur.com/oxiZT.png Eu **não** quero usar `QSystemTrayIcon`, quero que seja uma janela *bonitinha*, parecida com está: http://i.stack.imgur.com/S62wY.png
Comment: Conseguiu? Fiquei curioso, kkkkkk
Answer: Para customizar o Notifications Web API no QtWebkit será necessário usar o "Webkit plugins", ou seja, criar um plugin e colocar no diretório qtdir/plugins/webkit.

Nota: Para criar os plugins será necessário usar o "header" <QtWebKit/QWebKitPlatformPlugin>

Criando um plugin Webkit:

Crie um projeto no QtCreator
No arquivo .pro (exemplo src.pro) adicione isto:
TARGET = $$qtLibraryTarget(meupluginwebkit)
TEMPLATE = lib
CONFIG += plugin

HEADERS += $$[QT_INSTALL_HEADERS]/QtWebKit/qwebkitplatformplugin.h \
    meupluginwebkit.h

SOURCES += \
    meupluginwebkit.cpp

DESTDIR = $$PWD/bin-plugin
OBJECTS_DIR = $$PWD/build-plugin
MOC_DIR = $$PWD/build-plugin
RCC_DIR = $$PWD/build-plugin
UI_DIR = $$PWD/build-plugin

Crie o arquivo meupluginwebkit.h na pasta do projeto
#ifndef MEUPLUGINWEBKIT_H
#define MEUPLUGINWEBKIT_H

#include <QtWebKit/QWebKitPlatformPlugin>

class meupluginwebkit : public QObject, public QWebKitPlatformPlugin
{
    Q_OBJECT
    Q_INTERFACES(QWebKitPlatformPlugin)

#if QT_VERSION >= 0x050000
    Q_PLUGIN_METADATA(IID "org.qtwebkit.QtWebKit.QtWebPlugin")
#endif

public:
    explicit meupluginwebkit();
    ~meupluginwebkit();

    bool supportsExtension(Extension ext) const;
    QObject* createExtension(Extension ext) const;
};

#endif // MEUPLUGINWEBKIT_H

Crie o arquivo meupluginwebkit.cpp na pasta do projeto
#include "meupluginwebkit.h"
#include "notification/notification.h"

meupluginwebkit::meupluginwebkit()
{
}

meupluginwebkit::~meupluginwebkit()
{
}

bool meupluginwebkit::supportsExtension(Extension ext) const
{
    return ext == Notifications;
}

QObject* meupluginwebkit::createExtension(Extension ext) const
{
    switch (ext) {
        case Notifications:
            return new Notification();

        default:
            return 0;
    }
}

//Para QT-4.8
#if QT_VERSION < 0x050000
Q_EXPORT_PLUGIN2(webkitplugin, meupluginwebkit);
#endif

Crie dentro da pasta do projeto uma pasta chamada notification
Na pasta notification adicion adicione os arquivos:
notification.h
#ifndef NOTIFICATION_H
#define NOTIFICATION_H

#include <QtWebKit/QWebKitPlatformPlugin>

class Notification : public QWebNotificationPresenter
{
    Q_OBJECT

public:
    explicit Notification();
    ~Notification();

    void showNotification(const QWebNotificationData* data);

signals:
    void notificationClosed();
    void notificationClicked();
};

#endif // NOTIFICATION_H

notification.cpp
#include "notification.h"
#include <QDebug>

Notification::Notification() : QWebNotificationPresenter()
{
    qDebug() << "Create: Notification";
}

Notification::~Notification()
{
    qDebug() << "Delete: this (Notification)";
}

void Notification::showNotification(const QWebNotificationData* data)
{
    qDebug() << "titulo:" << data->title();
    qDebug() << "icone:" << data->iconUrl();
    qDebug() << "mensagem:" << data->message();
    qDebug() << "pagina que chamou a notificação:" << data->openerPageUrl();
}

No exemplo eu usei qDebug apenas para entendimento de como capturar os dados, para criar a sua notificação customizada, provavelmente você terá que usar QWidget

Crie na pasta notification o arquivo notification.pri:
QT += network

HEADERS += \
    $$PWD/notification.h

SOURCES += \
    $$PWD/notification.cpp

Inclua o notification.pri no src.pro:
include($$PWD/notification/notification.pri)

Compilando o src.pro:

Abra o projeto src.pro no QtCreator (se não estiver aberto)
Clique no botão Build (o desenho do martelo, ou use Ctrl+B) - Nota: Não clique no botão "Run" (o desenho do botão "play" verde), não use Ctrl+R)
Feche o projeto src.pro
Abra a pasta aonde se encontra o arquivo src.pro
Abra a pasta bin-plugin
Copie o arquivo meupluginwebkit.dll para QtDir/plugins/webkit/meupluginwebkit.dll (exexemplo com mingw: C:/qt/qt5.4/mingw/plugin/webkit/meupluginwebkit.dll)
Se a pasta webkit não existir, então crie ela.
Abra o seu projeto que está usando QWebView e teste o JavaScript que usa Notification Web API.

Quando você rodar o projeto que usa o QWebView, ele automaticamente irá carregar a dll da pasta webkit, portanto não será necessário nenhum outro tipo de configuração e isto irá subistituir o sistema de notificação padrão do QtWebkit (que no caso no Windows usa o SystemTrayIcon) pelo seu widget customizado.


Conditional distribution of $\exp(-|x|-|y|-a \cdot |x-y|)$

Question: I am trying to use Gibbs sampling or Metropolis-Hastings to draw samples from the joint distribution$$f(x,y)\propto\exp(-|x|-|y|-a \cdot |x-y|)$$ For this I need the conditional distributions of $x$ and $y$ ($a$ is known and constant). How do I obtain these? Is there a trick / shortcut?
Comment: @Xi'an The full conditionals don't seem to be from an obvious density though or am I missing something?
Comment: No trick involved, just apply standard probability: find $f(x|y)$ and $f(y|x)$ from the joint and then simulate from these densities.
Comment: @Xi'an By rejection sampling I presume?
Comment: @Xi'an Could you write down these inverse CDF?
Answer: The conditional density kernels are:
$$\begin{equation} \begin{aligned}
f(x|y) &\propto \exp(-|x|-a \cdot |x-y|), \\[6pt]
f(y|x) &\propto \exp(-|y|-a \cdot |x-y|). \\[6pt]
\end{aligned} \end{equation}$$
The difficulty here is to derive the actual densities that go with these kernels, which takes a bit of algebra.  Integration over the full range of values gives the appropriate constant-of-integration:
$$C(a,y) \equiv \int \limits_\mathbb{R} \exp(-|x|-a \cdot |x-y|) \ dx.$$
To evaluate this constant you need to break your integral up into pieces so that you can remove the absolute value signs.  I will not do all of this, but I will show you part of it, which will show how it can be done.  (For simplicity I am going to assume that $0<a<1$.)  In the case where $y>0$ we have:
$$\begin{equation} \begin{aligned}
C(a,y)
&= \int \limits_{-\infty}^{0} \exp(x-a (y-x)) \ dx \\
&\quad + \int \limits_{0}^{y} \exp(-x-a (y-x)) \ dx \\
&\quad + \int \limits_{y}^{\infty} \exp(-x-a (x-y)) \ dx \\[6pt]
&= \frac{1}{1+a} \Bigg[ \exp((1+a)x-ay)) \Bigg]_{x \rightarrow -\infty}^{x=0} \\
&\quad - \frac{1}{1-a} \Bigg[ \exp((a-1)x-ay)) \Bigg]_{x=0}^{x=y}  \\
&\quad - \frac{1}{1+a} \Bigg[ \exp(-(1+a)x + ay)) \Bigg]_{x=y}^{x \rightarrow \infty} \\[6pt]
&= \frac{1}{1+a} \cdot \exp(-ay) \\
&\quad - \frac{1}{1-a} \cdot \exp(-y) + \frac{1}{1-a} \cdot \exp(-ay) \\
&\quad + \frac{1}{1+a} \cdot \exp(-y) \\[6pt]
&= \Big( \frac{1}{1+a} + \frac{1}{1-a} \Big) \exp(-ay)
 + \Big( \frac{1}{1+a} - \frac{1}{1-a} \Big) \exp(-y) \\[6pt]
&= \frac{2}{1-a^2} \cdot \exp(-ay) - \frac{2a}{1-a^2} \cdot \exp(-y). \\[6pt]
\end{aligned} \end{equation}$$
So for $y>0$ you have:
$$f(x|y) = \frac{(1-a^2) \exp(-|x|-a \cdot |x-y|)}{2 \exp(-ay) - 2a \exp(-y)}.$$
You will need to derive the corresponding case where $y \leqslant 0$ and then you will have the full density.  Both the conditional densities in this problem are the same, so you will then be able to implement the Gibbs sampler by generating from this density.
Answer:
Disclaimer: although there is nothing to complain about Ben's answer (!), except maybe that the normalising constant of the conditional is not of direct use, here is what I
  wrote while being off-line, so I may as well post it!

The full conditional of $X$ given $Y$ has a density that is proportional to
\begin{align}
f(x|y) &\propto \exp\{ -|x|-a|y-x|\}\\
&=\begin{cases}
\exp\{ -x-a(y-x)\} &\text{ if } 0\le x\le y\\
\exp\{ x-a(y-x)\} &\text{ if } x\le \min(y,0)\\
\exp\{ -x+a(y-x)\} &\text{ if } x\ge \max(0,y)\\
\exp\{ x+a(y-x)\} &\text{ if } y\le x\le 0\\
\end{cases} \\
&=\begin{cases}
\exp\{ -(1-a)x-ay\} &\text{ if } 0\le x\le y\\
\exp\{ (1-a)x-ay\} &\text{ if } x\le \min(y,0)\\
\exp\{ -(a+1)x+ay\} &\text{ if } x\ge \max(0,y)\\
\exp\{ (1-a)x+ay\} &\text{ if } y\le x\le 0\\
\end{cases} \\
\end{align}
with one of the two conditions $0\le x\le y$ or $y\le x\le 0$ being obviously empty. Each of the (lhs) terms can be normalised into a (rhs) density:
\begin{align}\exp\{ -(1-a)x\} \mathbb{I}_{0\le x\le y} &\propto \dfrac{(a-1)\exp\{ -(1-a)x\}}{\exp\{ (a-1)y\}-1}\mathbb{I}_{0\le x\le y}\\
\exp\{ (1+a)x\} \mathbb{I}_{x\le \min(y,0)} &\propto \dfrac{(1+a)\exp\{ (1+a)x\}}{\exp\{ (1+a)\min(y,0)\}} \mathbb{I}_{x\le \min(y,0)}\\
\exp\{ -(1+a)x\} \mathbb{I}_{x\ge \max(0,y)}&\propto \dfrac{(1+a)\exp\{ (1+a)x\}}{\exp\{ (1+a)\max(0,y)\}}\mathbb{I}_{x\ge \max(0,y)}\\
\exp\{ (1-a)x\} \mathbb{I}_{y\le x\le 0} &\propto \dfrac{(1-a)\exp\{ (1-a)x\}}{1-\exp\{ (1-a)y\}}\mathbb{I}_{y\le x\le 0}\\
\end{align}
which means that it is directly possible to simulate from each of these densities, by inverse cdf, picking one of the four (three if accounting fo) with probabilities
$$\dfrac{\exp\{-ay\}[\exp\{ -(1-a)y\}-1]}{a-1}\mathbb{I}_{y\ge 0}, \dfrac{\exp\{-ay\}\exp\{ (1+a)\min(y,0)\}}{1+a}, \dfrac{\exp\{ay\}\exp\{ (1+a)\max(0,y)\}}{1+a}, \dfrac{\exp\{ay\}[1-\exp\{ (1-a)y\}]}{1-a}\mathbb{I}_{y\le 0}$$
(Obviously, a basic accept-reject algorithm based on a double exponential $\pm\mathcal{E}(1)$ proposal avoids this painful derivation since, when simulating $X\sim\pm\mathcal{E}(1)$ the accept-reject ratio
$$\dfrac{\exp\{ -|x|-a|y-x|\}}{\exp\{-|x|\}}$$ is $\exp\{-a|y-x|\}\le 1$ and hence can be compared with a Uniformn draw.) Here is a Gibbs outcome for $a=10$ and $10^3$ Gibbs steps (using accept-reject sampling):
Comment: +1. After your comment, I realized the integrals were available in closed form, but lost my patience somewhere in the second step. Good on you for sticking with it. Also, I suppose a Laplace proposal centered at x(or y) may be more efficient.
Comment: Hmm, but the support of Exp(1) is a subset of the support of this distribution. So That *shouldn't* work, right? In other words, you won't ever be able to propose/accept negative values. Am I missing something here?
Comment: My bad: a double Exp(1)... aka Laplace distribution.
Answer: An alternative to the painful simulation from the exact full conditional distributions is to ressort to slice sampling, that is, to express the density in $(x,y)$ as the marginal of a density in $(x,y,u_1,u_2,u_3)$ as follows:
\begin{align*}f(x,y)&\propto\exp(-|x|-|y|-a \cdot |x-y|)\\&=\int_0^\infty\mathbb{I}_{u_1\le\exp\{-|x|\}}\text{d}u_1\int_0^\infty\mathbb{I}_{u_2\le\exp\{-|y|\}}\text{d}u_2\int_0^\infty\mathbb{I}_{u_3\le\exp\{-a|x-y|\}}\text{d}u_3\end{align*}
The full conditionals are then all uniforms
\begin{align*}
x|y,u_1,u_2,u_3&\sim f(x|y,u_1,u_2,u_3)\propto\mathbb{I}_{u_1\le\exp\{-|x|\}}\mathbb{I}_{u_3\le\exp\{-a|x-y|\}}\\
y|x,u_1,u_2,u_3&\sim f(y|x,u_1,u_2,u_3)\propto\mathbb{I}_{u_2\le\exp\{-|y|\}}\mathbb{I}_{u_3\le\exp\{-a|x-y|\}}\\
u_1|x&\sim\mathcal U(0,\exp\{-|x|\})\\
u_3|x,y&\sim\mathcal U(0,\exp\{-a|x-y|\})\\
u_2|y&\sim\mathcal U(0,\exp\{-|x|\})\\
\end{align*}
hence straightforward to simulate:
<code>xz=yz=rep(pi,1e3)
a=10
for (t in 2:1e3){
 u1=runif(1)*exp(-abs(xz[t-1]))
 u2=runif(1)*exp(-abs(yz[t-1]))
 u3=runif(1)*exp(-a*abs(xz[t-1]-yz[t-1]))
 xz[t]=runif(1,log(u1),-log(u1))
 while (a*abs(xz[t]-yz[t-1])>-log(u3)) xz[t]=runif(1,log(u1),-log(u1))
 yz[t]=runif(1,log(u2),-log(u2))
 while (a*abs(xz[t]-yz[t])>-log(u3)) yz[t]=runif(1,log(u2),-log(u2))
}
</code>
$\qquad\qquad$


How to output custom field of Content type in page.tpl.php?

Question: I want to display a custom field which I created in my custom Drupal theme.
The field I created called "Startnummer" so the machine name of the field (I didn't change it) was created as "field_startnummer".
Furthermore, I found an article of that topic an the answer is to put the following line into my page.tpl.php:
<?php print render($content['field_startnummer']); ?>

Unfortunately, that doesn't work!
The next problem is, I do not know how other people would call that problem, so I can't find any solutions.
Any help?
Comment: Controlling the display for a custom field can be done via the core node view modes interface. Do you have a specific reason not to use that? [link](https://www.drupal.org/node/1577752) Other than that the code should work.
Comment: The problem seems to be that in page.tpl.php you shouldn't have content type templating. It is supposed to be done in node--contenttype.tpl.php and required variables are avaliable there, not in page template. If you have any specific reason to break this separation, tell us. It seems it might be XY problem - you have problem X, you think it should be solved doing Y, so you ask us how to do Y, risking you will miss more direct solutions to X.
Comment: If you want to print that field on a specific page, use "node--nodeid.tpl.php" or "node--contenttype.tpl.php" as Mołot mentioned.
Comment: Here is the Theme Hook suggestion documentation https://www.drupal.org/node/1089656
Answer: To output content types fields within a template you'll need to create a specific node.tpl.php for that content type for example node--article.tpl.php and then using the code you already have above should work.
Answer: To print your field in page.tpl.php do this:
Add this to your template.php file
function YOURTHEMENAME_preprocess_html(&$vars) {
  $node = menu_get_object();
  if ($node && isset($node->nid)) {
    $node = node_load($node->nid);
    node_build_content($node);
    $vars['field_YOURFIELD'] = render($node->content['field_YOURFIELD']);
  }
}

Then add this to your page.tpl.php file (or page--customname.tpl.php whatever file you are using to render page). We are using if statement here to avoid errors when/if field is empty.
<?php
if (isset($field_YOURFIELD)){
   print $field_YOURFIELD;
}
?>

After this you might notice that you are getting field output as double. That is because you have field active in Manage display of your content type (admin/structure/types/manage/YOURCONTENTTYPE/display).
So you need to add one more function to template.php.
function YOURTHEMENAME_preprocess_node( &$variables, $hook )
{
    if( $variables['page'] )
    {
      hide($variables['content']['field_YOURFIELD']);
    }
}

This one hides field from node content array. So your field is only printed when you are calling it on page.tpl.php file.


Rails: Reset a model attribute at specific time each day

Question: I have a rails app with a Location model, which has a rating, and a rating_count field. Now, I need to reset every Location's rating and rating_countattributes to 0 at a specific time everyday, lets say 12:00:00 UTC.
How would I accomplish this? I'm using the default sqlite3 databases.
Answer: The best option is to use cron. You can find tons of documentation out there!Although if you are running a Rails app you should check out whenever a pretty neat gem for managing cron jobs for your app!
Answer: The easiest thing is to write a rake task that does that job, and then use whatever scheduling system your host uses (cron).
An alternative is to use delayed_job which allows to push work to a background process. While delayed-job is not exactly suited for something like this, it is perfectably capable of doing this. If your rails process starts, you add a new job, to run at 12:00. And the running of the job reschedules the job.
The nice thing of delayed-job is that your code runs in the context of a rails-process, so you can use methods you already have. Also nice: jobs are stored in the database, so you can have an overview.
Comment: Alright, I'll go with a rake task and cron I guess. So the 'rake task' is simply a migration that uses `remove_column` on `rating` and `rating_count`, and then `add_column` `rating` and `rating_count` correct?
Comment: Just set the values to zero. The easiest way to do this is use `Location.update_all("rating = 0, rating_count =0")`. Documentation for `update_all` is http://apidock.com/rails/ActiveRecord/Base/update_all/class
Answer: If you're on a *nix box, write a script to do the updates (eg. in PHP, or Perl) and simply add it to crontab. Check out cron.


Visual Studio Code custom color gets overwritten?

Question: These are my custom color settings in settings.json:
<code>"editor.tokenColorCustomizations": {
   "textMateRules": [{
      "name": "Object keys, TS grammar specific",
      "scope": [
         "meta.object-literal.key",
         "support.object.key",
         "support.type",
         "support.type.property-name.json",
         "entity.name.type",
         "entity.other.attribute",
         "entity.name.namespace",
         "entity.name.scope-resolution",
         "entity.name.class",
         "storage.type.object.array.java",
         "storage.type.primitive.array.java",
         "storage.type.parameters.groovy",
         "storage.type.object.array.groovy",
      ],
      "settings": {
         "foreground": "#ff3300"
      }
   }]
}
</code>
As I only code in Javascript, there is some apparently useless stuff in the scope, but I was trying to bash any possible parameter, desperately trying to override the theme behaviour responsible for the overwriting. Of course, not knowing what I'm doing, I failed.
I thought I had made some sort of mistake, but if I restart VSC it DOES work, just for 1 or 2 seconds, then it automatically resets to the theme standard (the base team is VSC Dark standard).
:
On start:
After a couple seconds:
I have no "beautifying" or graphical extensions.
VSC is updated to last version.
What causes the overwrite, and how can I avoid it?
Comment: I just noticed something: in the settings.json the effects are applied and not overwritten by the misterious culprit, so my custom settings do work there. Not only that, I noticed the blue object-keys shouldn't be the standard behaviour since, as you can see here (https://i.imgur.com/oXzG8ze.png) there's another expected color for object keys, different from my custom (another red shade).
Answer:
Go to settings.
Turn off semantic highlighting


Programa de comparação entre vetores C++

Question: Fala galera tudo bem? Eu sou iniciante e to tentando construir um programa que compare dois vetores e caso todos os elementos dos dois vetores sejam. vou exemplificar pra ficar melhor...
vetor1 = 10, 20 , 30 e vetor2 = 10 20 30; então a saida vai ser: números iguais.
vetor1 = 10, 20, 20 e vetor2 = 10, 20, 15; então a saida seria: 10 20 e tbm dizendo esses foram os numeros iguais.
vetor = 10, 20, 30 e vetor2 = 15, 19, 4; então a saida seria: nenhum número igual.
o problema é que quando todos os numeros são iguais, alem dele dar a sair falando que todos são iguais ele tbm ta mostrando os numeros e não é para isso acontecer.
<code> #include <iostream>
using namespace std;

int main() {

  int n;
  cin >> n;

  int vetorX[n], i, a,c[n];

  for(a=0; a<n; a++){
  cin >> vetorX[a];
  }

  int vetorC[10] = {19, 7, 14, 0, 11, 17};
  int cont =0, cont1 = 0, cont2 =0;

  for(i=0; i<n; i++){
      for(a=0; a<n; a++){
        //conta a quantidade de numeros iguais
          if(vetorX[a] == vetorC[i]){
            cont ++;
            c[n] = vetorX[a];
            cout << c[n];
          }
      }
  }

  if(cont >= 7){
    cout << "todos iguais";
  }

  if(cont > 1 && cont < n){
    cout << "numeros iguais:";
  }

  if(cont == 0){
    cout << "nenhum igual";
  }

}
</code>
Comment: Me parece que se cont == 0 então não tem nenhum igual e se cont < 7 então existem alguns iguais mas não todos. Uma situação que deve analisar é qual o resultado será obtido caso exista repetição de algum elemento no(s) vetor(es) e o que fazer neste caso.
Comment: peguei sua dica do zero e deu certo e o resto tbm, mas se todos os elementos são iguais ele retorna que são iguais e exibe os números tbm e não quero que isso aconteça, quero que se todos os numeros forem iguais ele retorne que, todos são iguais, sem mostrar os números.
Comment: Não vejo o menor sentido em utilizar 3 comandos `if` com exatamente a mesma condição.
Comment: sim, nem me dei conta disso e tirei. O problema é que continua exibindo os números mesmo se todos os números forem iguais e não é pra rolar isso, seria o caso de botar uma condição pra ele só exibir os numeros se tiver alguma diferença?
Answer: Olá, você pode postar o seu código no compiler explorer que fica mais fácil.
C++ tem uma série de técnicas pra facilitar sua vida
1 - No lugar de usar vetores "[]" use o vetor "std::vector" em C++
2 - Ele tem um monte de operadores sobrecarregados (==, !=, <, >, <=, >=) logo vc pode perguntar diretamente v1 == v2 ou v1 != v2.
3 - Ele tem inicialização por {} do mesmo jeito que os vetores []
<code>    vector a = { 10, 20, 30, 40 };
    vector b = { 10, 20, 30, 40 };

    if ( a == b ) {  // pergunte diretamente se os vetores são iguais
       std::cout << "iguais";
    } else {
       std::cout << "diferentes";
    }
</code>
4 - Aprenda a usar os algoritmos e containers da stl, já tem um algoritmo pronto std::mismatch pra fazer o que você quer, e além disso, vc pode facilmente escrever códigos sem loops "for" ( mais legíveis )
O que você quer fazer é um pouco incomum: gerar uma saída com os valores iguais apenas se o vetor tiver algum número diferente ? Nesse caso você vai ter que passar 2 vezes nos vetores, uma pra ver se eles são diferentes e outra para gerar a saída caso sejam. Mesmo assim :
Exemplo completo https://godbolt.org/z/4j35nx
Lá no código vc vai ver "mismatch()" que deixa claro sua intenção de procurar o primeiro elemento diferente em 2 containers e também vai ver "copy" com ultimo operador cout, ou seja copia para a saída.
Fora isso tem o caso de um vetor ser um sub-conjunto do outro, a = { 10, 20 } e b = {10, 20,30} vc quer qual saída nesse caso ?
Abraços


Problema ao usar Tabs Bootstrap

Question: Estou tentando utilizar o componente tabs do bootstrap, porém não estou conseguindo fazer funcionar, já peguei diversos exemplos, mas não consegui fazer funcionar.

Totais por Filiais

Informações sobre pagamento

Observações

                            Tab 1

                            Tab 2

                           Tab 3

Quando clico, permanece sempre na primeira aba, não troca para as outras. alguém sabe onde está o erro, ou se falta algum código?
Comment: A princípio seu código parece estar certo amigo, segue o link do bootply com seu código: http://www.bootply.com/1XZyeROFwe
Comment: O erro não me parece estar no front-end. Mas verifique o caminho do seu script e css pra ver se está tudo nos conformes...
Comment: Já verifiquei o caminho dos scripts, mas ainda tá na mesma, não tenho mais ideia porque não está funcionando :/
Comment: Os div estão certinhos @Geferson? que pelo que contei aqui, falta o div do row...Tá batendo certo ai?
Comment: Ta sim @Daniel, Achei o problema. não tinha me tocado, mas coloquei a lib do bootstrap antes do Jquery, e o bootstrap usa o Jquery, agora coloquei o Jquery antes e está funcionando. desatenção minha, muito obrigado pela ajuda.
Comment: JQuery sempre tem que vir antes do Bootstrap, se não ele não funciona direito, buga tudo inclusive o carousel.
Answer: As libs estavam invertidas, como o bootstrap depende do Jquery, coloquei a do jQuery antes e tudo passou a funcionar.

Problema ao usar Tabs Bootstrap


Undefined symbols for architecture x86_64&&symbol(s) not found for architecture x86_64

Question: I really don't know what happened to my program.
I used to run it successfully in 2017.
Today it goes wrong.
I try to change the build setting, build phases.They all not work.

Help me PLEASE!
Comment: Try to run in device framework doesn't support simulator
Comment: @shuo-zhao : Though am not familiar with this framework, general solution for this problem is to make sure that the framework is added in Linked framework and libraries of your target. Select your target, click general tab scroll down to see Linked framework and libraries section click + and select your framework clean and rebuild
Comment: Thank you so much for your answers!
Answer: You just need to add <code>-lstdc++</code> to the linker flags for your target. This is a new requirement since AudioKit became a static framework.
Comment: big problems always have short, but not simple solutions!!! You saved my day!! Thank you very much! it works


How can I read this xml?

Question: could you help me?
I need to read this file:
I Tried this way:
$xml = simplexml_load_file('http://api.crossref.org/works/10.18468/pracs.2016v9n3.p99-119/transform/application/vnd.crossref.unixsd+xml');
echo $xml->journal_metadata->full_title;
I don´t know how to get the value of a specific tag.
I need read this:Click to see
Comment: Welcome to Stack Overflow. We do not go to another site to see what you're asking, and we cannot help you with why code we cannot see is not working for you. See [ask] and [mcve] (and while you're at it [Why is "Can someone help me?" not an actual question?](http://meta.stackoverflow.com/q/284236)), and then come back and [edit] your post to include the relevant details **here**, in your question itself.
Comment: _"but it doesn´t work"_ is quite a short description of the specific problem you have....
Comment: and no, this way nobody can help you (exept for doing your work..). Do you have any code you have problems with? What have you tried?
Comment: have you at least googled "xml parser php"?
Answer: First you load the file from the distant server :
$file = @file_get_contents('http://api.crossref.org/works/10.18468/pracs.2016v9n3.p99-119/transform/application/vnd.crossref.unixsd+xml');
if ($file===FALSE)
{
    die ("error getting the content of the file");
}

Then, you parse the xml and extract it into an object using  simplexml :
$o= simplexml_load_string ($file);

Finally, you move through your object tree until you reach the intended destination
echo "
";
$intended_obj = $o->query_result->body->query->doi_record->crossref->journal->journal_article->doi_data;
print_r($intended_obj->resource);
print_r($intended_obj->collection);
echo "
";

That should output :
   SimpleXMLElement Object
(
    [0] => https://periodicos.unifap.br/index.php/pracs/article/view/2791
)
SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [property] => crawler-based
        )
    [item] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [crawler] => iParadigms
                )
            [resource] => https://periodicos.unifap.br/index.php/pracs/article/viewFile/2791/haliadorav9n3.pdf
        )
)

Good luck,

How can I read this xml?


How to solve the anti derivative of $\int \frac{1}{x^{2}-3x} dx$

Question: $\int \frac{1}{x^{2}-3x} dx$
I'm having trouble with understanding how to solve this, is there a reason why it's not the natural log of the denominator?
Comment: Differentiate the log of the denominator. Do you get the original integrand?
Comment: Hmm i suppose not, so then how should i go about solving this?
Comment: Complete the square, then partial fractions?
Comment: @kcris, partial fractions, sure, but no need to complete any squares, just factor the denominator.
Comment: Yeah, I saw that in the answer - that was just my first gut response :)
Answer: $$\frac{1}{x(x-3)}=\frac{1}{3}\frac{x-(x-3)}{x(x-3)}=\frac{1}{3}\left[\frac{1}{x-3}-\frac{1}{x}\right]$$


Why does a button event function run during a page reload in ASP.NET?

Question: public partial class Stats : System.Web.UI.Page
{
    public SqlDataReader DataReader;
    public SqlCommand Command;
    string queryString = ("INSERT INTO UserData (UserProfileID, ConfidenceLevel, LoveLevel, HappinessLevel) VALUES ('a051fc1b-4f51-485b-a07d-0f378528974e', 1, 1, 1);");

    protected void Page_Load(object sender, EventArgs e)
    {
       LabelUserID.Text = Membership.GetUser().ProviderUserKey.ToString();
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        MySqlConnection database = new MySqlConnection();
        database.CreateConn();

        Command = new SqlCommand(queryString, database.Connection);
        Command.ExecuteNonQuery();
    }
}

Not sure I understand why Button1_Click() is executing on a page reload.
I put in a break point in the function and it does hit it as well as update the DataBase.
Answer: If you click the button to post back, then reload after the postback, you're essentially repeating the postback, which will cause the button event to execute again. This will not happen if you simply reload the page after a GET request.
Comment: Is there an option to not have it post back on a page refresh and just refresh the content that is there?
Answer: What do you mean a page reload? If you clicked the button, then hit refresh on the browser, that will cause the browser to re-issue the last post, which means as far as the server is concerned, the button is being clicked again. (The browser should warn you about re-posting though.)
If it's occurring the first time you request the page then perhaps you accidentally wired up the wrong event handler in the ASPX file?
When in doubt, fire up Fiddler to see what's being transmitted to the server.


Ionic5: Disabling ion-checkbox resulted in disabling ion-label when placed in same ion-item

Question: I'm trying to only disable ion-checkbox but this resulted in disabling the ion-label placed in the same ion-item.
<ion-item>
   <ion-label>Using GPS</ion-label>
   <ion-checkbox slot="start" [(ngModel)]='reachedUsingBeacon' disabled="true"></ion-checkbox>
</ion-item>

I tried to solve it by adding pointer-events: auto; but it didn't work.
ion-item {
    pointer-events: auto;
}

Any help will be appreciated. Thanks!
Answer: I was able to solve this issue by removing the disabled property and use css to style it accordingly:
.disabled {
  pointer-events: none;
  opacity: 0.6;
}


Getting batches in tensorflow

Question: This question may have been asked but I failed to find it.
What is the simplest way to constantly get batches of data from a dataset? Is there a built-in tensorflow function to do so?
for instance:
for i in num_trains:
    x_batch, y_batch = get_batch(x_train, y_train, batch_size)
    sess.run(train_step, feed_dict={x:x_batch,y:y_batch})
If there is not such a built in function, how would you implement it? I tried myself but I could not figure out how I can get a new batch different from the previous ones each time I call the function.
Thanks!
Comment: You have to prepare the dataset yourself (i.e., `x_batch`, `y_batch`) to feed into the model. So you can define a function which read from disk some data and return `x_batch` and `y_batch`.
Comment: @walkerlala I could not understand. Can you elaborate further?
Answer: You can try:
# Feed batch data
def get_batch(inputX, inputY, batch_size):
   duration = len(inputX)
   for i in range(0,duration//batch_size):
     idx = i*batch_size
     yield inputX[idx:idx+batch_size], inputY[idx:idx+batch_size]

You can also use tensorflow's dataset API as well:
dataset = tf.data.Dataset.from_tensor_slices((train_x, train_y))
dataset = dataset.batch(batch_size)

Getting the batch:
  X = np.arange(100)
  Y = X
 batch = get_batch(X, Y, 5)
 batch_x, batch_y = next(batch)
 print(batch_x, batch_y)
 #[0 1 2 3 4] [0 1 2 3 4]

 batch_x, batch_y = next(batch)
 print(batch_x, batch_y)
 #[5 6 7 8 9] [5 6 7 8 9]

Typically for running over the dataset for multiple epochs, you would do:
 for epoch in range(number of epoch):
    for step in range(size_of_dataset//batch_size):
        for x_batch, y_batch in get_batch(x_train, y_train, batch_size):
           sess.run(train_step, feed_dict={x:x_batch,y:y_batch})

Using the dataset API:
  dataset = tf.data.Dataset.from_tensor_slices((X, Y))
  dataset = dataset.batch(5)
  iterator = dataset.make_initializable_iterator()
  train_x, train_y = iterator.get_next()
  with tf.Session() as sess:
    sess.run(iterator.initializer)
   for i in range(2):
       print(sess.run([train_x, train_y]))
   #[array([0, 1, 2, 3, 4]), array([0, 1, 2, 3, 4])]
   #[array([5, 6, 7, 8, 9]), array([5, 6, 7, 8, 9])]

Comment: In your dataset API example, if you would want to run the `train_step` you would have to convert `train_x` and `train_y` into tensors. Would this be a right way to do it: `train_x = tf.Variable(dtype=tf.float32,initial_value=sess.run(train_x))`? Would there be any problems when I feed this `train_x` into `feed_dict` later on? Thanks
Comment: Hmm, I am having a hard time trying to understand it. Would this function give you a different batch everytime you call it ?
Comment: added details on how to use it.
Comment: Check: https://www.tensorflow.org/programmers_guide/datasets#consuming_numpy_arrays

Getting batches in tensorflow


Exact `svn export` equivalent command for git?

Question: There is no exact svn export equivalent command for git? Really?
Beware: this is not a duplicate question. That is, I already know and have tested these commands:

git clone --depth 1 <- Still downloads the .git folder.
git checkout-init <- Doesn't work for a remote repo, it works with a working copy (so you need to clone first).
git archive <- This would be the perfect solution, because it has a --remote argument, but it only has 2 possible formats: tar or zip, so I would need to untar/unzip after downloading, and for that I need a pipe (|), but I'm on windows!! (not *n?x)
git clone --bare <- I still don't know what the heck this is, but it's not what I need.

Please enlighten me is there a real svn export replacement in git?
Comment: `git clone --depth 1` is what you need, read the documentation that Bruno is linking to and his comment.
Comment: You will not get around "getting a .git folder", but you will get around downloading the entire changeset history with `--depth 1`. You still have to delete the `.git` folder afterwards. There is no getting around that.
Comment: This is not a duplicate of the proposed question. Basically the OP is asking how to download only the latest manifest of files from a remote repository. `git archive` works from a local clone so that is back to square 1: how to download only the latest manifest.
Comment: If you've installed git on windows then presumably you have git bash and the associate tools that it installs such as tar. If this is the case you can use git archive and a pipe to tar.
Answer: From How do I do a quick clone without history revisions?:
git clone --depth 1 your_repo_url

Then, from the rmdir documentation:
rd /s /q .git

Comment: Not sure you understand what `--depth` does: it does not download all the revisions: it rebuilds a "fake" history only pretending to add the new files each time. You're not downloading any more than you would with the archive.
Comment: Stop proposing --depth, it's already mentioned in the question!
Comment: stackoverflow is not about politeness, it's about correctness
Comment: Its not polite to downvote answers to your own question, imo.
Comment: @knocte, quite surprised to see you're still active on this question. Nevertheless my answer was correct.
Comment: @knocte: did you just downvote this answer after editing the question from "straight-forward" to "exact"?
Comment: @knocte you have marked the wrong answer correct; or you should change your question to be specific to github only
Comment: what happens is that there's no correct answer because there's no exact equivalent to `svn export`, but at least github provides a workaround
Answer: The question "how can I do a svn-style 'export' with git?" is like asking "How can I change the tires on my basketball?". You can't, but that's not the basketball's fault. Yes it is rubber and full of air, but the similarity ends there.
You only need "export" with svn because it pollutes every single subdirectory with a .svn directory. Git doesn't do that, so you really don't need it. A clone IS an export, just with one directory at the root dir that all the repository business lives in.
The easiest thing is to clone the repo and then just delete the .git directory from the top level of the repo. Do that, and it's not a repo anymore, it's just a stand-alone directory of files.
Or, you know, ignore git all together and just use the files you cloned down. That works too.
Comment: That's one of the *stupidest* analogies I've read. For this specific task (downloading just files, not the history, for a specific revision) it makes all kinds of intuitive sense to expect a revision control system with atomic commits to have a command to accomplish it. The reason to use `svn export` is specifically to get a copy of a revision *without* history. So telling someone to clone, getting a copy *with* history, and then just ignore that history, is condescending at best. Also, SVN no longer pollutes every single directory with a .svn folder, as of version 1.7 released back in 2011.
Comment: Irrelevant: removing the .git folder doesn't save the precious time and bandwidth that I could save by not downloading it in the first place.
Comment: Unless your repo contains a LOT of binaries in its history, the repo itself is only fractionally bigger than the checked out working directory will be. Also I can pretty much guarantee you've used up more time and bandwidth complaining about this than you would just using the tool the way it's built.
Comment: DanRay stop assuming the purpose of the tool. If I'm going to use it to download thousands of git repositories, the bandwidth savings would make sense, right?
Comment: I get the feeling that no answer other than "here is how you can make git perform just like your preferred tool" is going to satisfy... git and svn are VERY DIFFERENT from design to implementation.
Comment: DanRay: because I want to retrieve their content.
Comment: @knocte - Okay. Well, do it the way the tool they're in does it, or don't. I'm done with this conversation.
Comment: The analogy is not helpful to me.  both svn and git store files with revision history.  Both svn checkout and git clone create directory structures that contain information about that history.  svn export is a way to ask for only the content of a specific revision without any metadata.  If the point is that git does not, then it is horribly broken.  If the answer is do "git clone" and "rm -rf .git" then just say that -- don't argue that git is so different that the equivalent of "svn export" is not a meaningful action.
Comment: @knocte - Are you really downloading thousands of git repositories? Why?
Comment: This analogy made me laugh :)
Answer: Just get rid of the repository within the working copy.
git clone remote
rm -Rf .git

(On Windows, it's rd /s /q. Thanks for the hint by @Bruno.)
Comment: @knocte, of course, that could be added directly, not necessarily a bad idea. However, `git` fundamentally follows the unix approach of having a small command for each little things you need to do, which you can then combine. Some like this approach, some don't. I don't think `git clone --depth` followed by an `rmdir` is the hardest combination of commands you can get. Even with a potentially limited command line environment (e.g. Windows's `cmd`), it's not that hard. Doing it in one command might be better, but I'm not sure it's worth arguing like this...
Comment: Perhaps `rd /s /q` instead of `rm -Rf` on Windows.
Comment: This has nothing to do with "fanboys". You want `svn export`? Than must use `svn`, because DVCS works very different to centralized VCS. You cannot switch from SVN to git and work with it like it were SVN. Understand git and you will understand what happens here. Or leave it, but don't blame the messenger ;)
Comment: I had to look very closely at the question to find the "I'm on windows!!" ;) I don't know windows' commandline. I'll assume `/s` is he `-Rf` equivalent.
Comment: KingCrunch: irrelevant.

The purpose of this is precisely to avoid deleting the ".git" folder later, and to save bandwidth and time by not downloading it.
Comment: Not sure either, but it looks like `-R` is `/s` and `-f` is `/q`: http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/rmdir.mspx?mfr=true
Comment: `git` _always_ interacts with the local repository. Even `push`, or `pull` goes right into the local one. This means, there is no way to save anything until you have a local copy, and then it's to late ;) I don't know, what you are going to achieve at the end, but as long as the maintainer don't provide a downloadable package (e.g. created via `git archive`) you need the repository anyway. Some web interfaces (github and such) provides the ability to download packaged branches. Usually as long as you don't clone the linux kernel the bandwith and time is negligible.
Comment: @knocte, try using the `--depth` parameter with `git clone`.
Comment: KingCrunch, your efforts to explain me the philosophy of git still don't answer why the hell there is no "svn export" equivalent. Kthxbye
Comment: @knocte, with `--depth=1`, the .git folder is just a few files of config and the patches required for the latest revision, it doesn't download all the revisions.
Comment: Bruno, I know that. But it's still metadata I don't want and it causes me the need to post-process.
Comment: @knocte: Because nobody needs it. I explained the technical part in the comment, @DanRay explainedthe idea behind that in his answer and the consequence in his comment. Git repositories uses deltas and is itself compressed. In many cases you _will_ download more, if you just receive the uncompressed content, instead of the packed repository. Believe me, sometimes I clone repositories via GPRS ;)
Comment: @knocte: what do you mean by post-process? Do you really get a massive overhead? It wouldn't be much worse than uncompressing an archive. Most of the data will be compressed during the transfer anyway.
Comment: @Bruno: Most of the stuff within an git repository is already compressed ;) With `--depth 1` is like downloading the compressed archive and get it unpacked by git. Seriously, I don't understand whats the big deal here...
Comment: @KingCrunch, of course, I think that's quite sensible, but the OP doesn't seem to agree.
Comment: KingCrunch, there is no DVCS conceptual reason for git not to provide this feature, I could create a patch and they would add, so stop spreading wrong conclusions.
Answer: For your I still don't know what the heck this is: git clone --bare will clone the repository without a working copy.  This is usually done on a central repository so as to minimise disk space usage.
Bruno / King Crunch have the best answer.  Although you could use git bash / cygwin to allow you to pipe if you need a one-liner.
Comment: This is about the opposite of `--depth 1`, though.
Comment: Yes I realise that, but Andres mentioned that he did not know what git clone --bare did.
Comment: I edited the answer so this will be more obvious. (And in this form I can even vote it up.)
Answer: At some hostings like GitHub you can make exact svn export.
Example:
svn export https://github.com/GNOME/banshee/branches/master

Even partial! (some subpart of the repository)
Example:
svn export https://github.com/liferay/liferay-portal/branches/6.1.x/tools

For your own repository you should create some GitHub repository and add it as a remote:
git remote add github https://github.com/<user>/<repo>.git

then
git push github <branch>

Now you able to do a partial checkout as above.
UPDATE: Looks like this feature is getting discontinued.
Comment: @knocte, the problem is that this answer doesn't answer the question. The fact that `svn export` works on GitHub has nothing to do with doing what you want with Git, it has to do with the fact the GitHub also offers a Subversion service that is a [bridge to its Git repositories](https://github.com/blog/626-announcing-svn-support). It's still a Subversion server, though, not a Git one.
Comment: that command would not be an **exact** equivalent to `svn export` simply because it requires a post-cleanup step (deleting the .git folder) and the original Subversion command doesn't
Comment: I know, but it's the least worse answer at the moment; I'm planning to contribute an option for this anyway, in git upstream, after 2.0 gets released (already contributed my first patch, I'm making progress)
Comment: The fact remains that `git clone --depth 1 your_repo_url` followed by the deletion of the `.git` repository still does exactly what you want, using **Git** repositories. How would this answer be the "least worse" when it doesn't even use Git repositories? I'm not going to downvote this answer because the answerer is visibly trying to help and this is a reasonable workaround for GitHub, but this doesn't actually answer the question.
Answer: This is a rather old questions, nevertheless I didn't find an "obvious solution" in my opinion. After some research of the git documentation I found:
git archive --format=tar --remote ... | tar xf -

This will receive the contents even from a remote repository and write a tar archive to stdout. The tar command then will extract the contents and create it in your current directory.
If you like to do that from a local repository (which was explicitly not the desired request in the question), then
git archive --format=tar ... | ( cd /your/path && tar xf - )

will do the trick for you. The first approach works on Windows command prompt as well, if you have tar installed. The latter most probably does not and may overwrite your directory.
Answer: Re your point, git archive <- This would be the perfect solution ...but it only has 2 possible formats: tar or zip, you can add new formats using documentation from the EXAMPLES section of the git-archive(1) man page:
   git config tar.tar.xz.command "xz -c"
       Configure a "tar.xz" format for making LZMA-compressed tarfiles.
       You can use it specifying --format=tar.xz, or by creating an output
       file like -o foo.tar.xz.

While being "on Windows" is generally considered an impediment to many tasks, with a little extra work, you can almost catch up to the folks running other operating systems by using software like Cygwin or MKS Toolkit.
If after confirming that whatever command you need is available from within your shell, this sort of git config … command still doesn't work for you, then you should perhaps post additional details about your configuration in a question on SuperUser.com.

As noted by jbruni in the comments, you can list the available formats for your installation using git archive --list.
Note that "git archive --list extra garbage"(man) silently ignored excess command line parameters, which has been corrected with Git 2.44 (Q1 2024).
See commit d6b6cd1 (21 Dec 2023) by Junio C Hamano (gitster).
(Merged by Junio C Hamano -- gitster -- in commit 6bf317d, 08 Jan 2024)

archive: "--list" does not take further options

"git archive --list blah"(man) should notice an extra command line parameter that goes unused.
Make it so.

The error message would now be:
extra command line parameter 'blah'

Comment: What would the output of "no format at all" look like?  The purpose of "git archive" is to create an *archive*.  That implicitly requires some kind of format.  Add a freely available [`tar.exe`](http://gnuwin32.sourceforge.net/packages/gtar.htm) to your build server, then try setting `git config tar.deploy.command "tar -x -C /path/to/target -f -"` and extract on the fly.  NONE of your tools are perfect.  Sure, git's architecture fails to compensate for other failures in your build environment, but that's what you've got.  Just do what you can with the tools available.
Comment: wow, I can't believe git-archive can be configured with custom formats, but cannot be tweaked to have no format at all!!! seriously, it's not that I don't know or don't want to install cygwin or other shell, it's that I'm running this operation in a buildagent in which I don't want to install anything (because I actually don't have control over it)
Comment: Woot, an anonymous downvote.  Care to mention how this answer is inaccurate or misleading?
Comment: You can list the available formats for your installation using `git archive --list`. For my installation, I'm seeing tar, tez, tar.gz, and .zip.
Comment: @jbruni .. Yes -- on my system, I see `.tgz` as well. It might not have been clear from the formatting I used back in 2012, but the bold bit in the first paragraph was actually quoting the question. Since the OP was clear that he had only 2 formats available, I was trying to provide a way to add more.
Comment: Very good addition to [Vladimir Sosnin](https://stackoverflow.com/users/2342590/vladimir-sosnin)'s [answer](https://stackoverflow.com/a/19725565/6309). I took the liberty to include `git archive --list` in your answer. Feel free to revert the edit if needed.
Answer: From https://stackoverflow.com/a/160719/43597
git checkout-index -a -f --prefix=/destination/path/

Comment: Useless answer, as this needs to be done from a repository that has already been cloned. What we want to avoid is to do two steps instead of one (svn export is one step, git clone + git checkout-index is two steps).


How can I get the mappings from feeds

Question: I want to get programmatically the mapping which was set by the user on the feeds config page (<code>/admin/structure/feeds/<name>/mapping_en</code>). But how can I do it?
Answer: I've fount a working solution:
<code>$f = feeds_importer('your-importer-machine-name');
$m = $f->processor->getMappings(); // This returns the mapping.
</code>
It's just needed one day to find it...

How can I get the mappings from feeds


Angular: I can get the object from Service, but it seems I did not assign an object properly

Question: Component:
import { Component, OnInit } from '@angular/core';
import { ItemsService } from '../items.service';
import { Observable } from 'rxjs';
import { Item } from '../item.model';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-customer',
  templateUrl: './customer-detail.component.html',
  // styleUrls: ['./customers-table.component.css'],
  providers: [ItemsService],
})
export class CustomerDetailComponent implements OnInit {
  customer: Item;
  constructor(private _itemsService: ItemsService, private route:
ActivatedRoute) {
  }

ngOnInit() {
    console.log(this.getDataFromService().subscribe(data =>
console.log(data)));
    this.getDataFromService().subscribe(data => this.customer = data);
    console.log(this.customer);
  }

  public getDataFromService() {
    const id = +this.route.snapshot.paramMap.get('id');
    const paraid: string = String(id);
    return this._itemsService.getItem(paraid);
  }

}

Service:
@Injectable()
export class ItemsService {

  private BASE_URL = 'http://localhost:3000/api/';

  constructor(private http: HttpClient) { }

  // Uses http.get() to load data from a single API endpoint
  getItem(id: String): Observable<Item> {
    console.log('getItem: ' + id);
    return this.http.get<Item>(`${this.BASE_URL + id}`);
  }

From the console log I've got this:
Subscriber {closed: false, _parent: null, _parents: null,
_subscriptions: Array(1), syncErrorValue: null, …}

[{…}]
0
:
{CustomerID: 1000, FirstName: "Suzanne", LastName: "Jones", BirthDate:
"1999-01-01"}
length
:
1
__proto__
:
Array(0)

I have an item to fetched from API endpoint, which will get the item by SQL query from the database, I have succeeded to get the data as I can console.log(data).
but I can't console.log(this.customer), did I do something wrong in data => this.customer = data?
Answer: First of all you are not calling the method from the service, you need to use
this._itemsService.getDataFromService()

and You are getting data from an API asynchronously and trying to access it before the response, place the console.log inside the subscribe,
this._itemsService.getDataFromService().subscribe((data) =>  {
   console.log(data)
   this.customer = data;
   console.log(this.customer);
});

Comment: thank you, I can console.log(this.customer) now. I have one more
I tried to do the 2-way binding, and assign name = this.customer.firstName; and in the html file, I put {{name}}. However, I have got the error (core.js:1673 ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'firstName' of undefined
TypeError: Cannot read property 'firstName' of undefined), do you know why it happened in my case?
Comment: you can just do {{customer?.firstName}}
Comment: could it because in the database, the column name is FirstName, and in Angular, I set the interface firstName?
Comment: cannot be, can you post what you get when you do console.log(JSON.stringify(this.customer));
Comment: did it fix your issue /
Comment: [{"customerID":1000,"firstName":"Suzanne","lastName":"Jones","dateOfBirth":"1999-01-01"}] it is what I have got
Comment: dude its an array. so you need {{customer[0]?.firstName}
Comment: thanks, it works. Can I ask why the function will return to the array?
Answer: OffCourse you will not get data in to your console.
because it will take time to fetch data and when you subscribe your function, it will go to fetch data, your outside console will be called.
Use settimeout(()=> {}, 1000) like this:
ngOnInit() {
    console.log(this.getDataFromService().subscribe(data =>
console.log(data)));
    this.getDataFromService().subscribe(data => this.customer = data);
settimeout(()=> {  console.log(this.customer); }, 1000);
  }


Confidence intervals for regression parameters: Bayesian vs. classical

Question: Given two arrays x and y, both of length n, I fit a model y = a + b*x and want to calculate a 95% confidence interval for the slope. This is (b - delta, b + delta) where b is found in the usual way and
delta = qt(0.975,df=n-2)*se.slope

and se.slope is the standard error in the slope. One way to get the standard error of the slope from R is summary(lm(y~x))$coef[2,2].
Now suppose I write the likelihood of the slope given x and y, multiply this by a "flat" prior and use a MCMC technique to draw a sample m from the posterior distribution. Define
lims = quantile(m,c(0.025,0.975))

My question: is (lims[[2]]-lims[[1]])/2 approximately equal to delta as defined above?
Addendum Below is a simple JAGS model where these two seem to be different.
model {
 for (i in 1:N) {
  y[i] ~ dnorm(mu[i], tau)
  mu[i] <- a + b * x[i]
 }
 a ~ dnorm(0, .00001)
 b ~ dnorm(0, .00001)
 tau <- pow(sigma, -2)
 sigma ~ dunif(0, 100)
}

I run the following in R:
N <- 10
x <- 1:10
y <- c(30.5,40.6,20.5,59.1,52.5,
       96.0,121.4,78.9,112.1,128.4)
lin <- lm(y~x)

#Calculate delta for a 95% confidence interval on the slope
delta.lm <- qt(0.975,df=N-2)*summary(lin)$coef[2,2]

library('rjags')
jags <- jags.model('example.bug', data = list('x' = x,'y' = y,'N' = N),
                   n.chains = 4,n.adapt = 100)
update(jags, 1000)
params <- jags.samples(jags,c('a', 'b', 'sigma'),7500)
lims <- quantile(params$b,c(0.025,0.975))
delta.bayes <- (lims[[2]]-lims[[1]])/2

cat("Classical confidence region: +/-",round(delta.lm, digits=4),"\n")
cat("Bayesian confidence region:  +/-",round(delta.bayes,digits=4),"\n")

And get:
Classical confidence region: +/- 4.6939
Bayesian confidence region:  +/- 5.1605
Rerunning this multiple times, the Bayesian confidence region is consistently wider than the classical one. So is this due to the priors I've chosen?
Answer: The 'problem' is in the prior on sigma.  Try a less informative setting
tau ~ dgamma(1.0E-3,1.0E-3)
sigma <- pow(tau, -1/2)

in your jags file.  Then update a bunch
update(10000)

grab the parameters, and summarise your quantity of interest.  It should line up reasonably well with the classic version.
Clarification: The updating is just to make sure you get where you're going whatever choice of prior you decide on, although chains for models like this one with diffuse priors and random starting values do take longer to converge.  In real problems you'd check convergence before summarising anything, but convergence is not the main issue in your example I don't think.
Comment: Although frankly that might be the source of the difference since it's in the original code...
Comment: @Ringold, what worked? The prior on sigma or the update? Or both? Have you tested them separately?
Answer: If you sample from the posterior of b | y and calculate lims (as you define) it should be same as (b - delta, b + delta). Specifically, if you calculate the posterior distribution of b | y under a flat prior, it is same as the classical sampling distribution of b.
For more details refer to: Gelman et al. (2003). Bayesian Data Analysis. CRC Press. Section 3.6
Edit:
Ringold, the behavior observed by you is consistent with the Bayesian idea. The Bayesian Credible Interval (CI) is generally wider than the classical ones. And the reason is, as you correctly guessed, the hyperpriors taken into account the variability because of the unknown parameters.
For simple scenarios like these (NOT IN GENERAL):
Baysian CI > Empirical Bayesian CI > Classical CI ; > == wider
Comment: I added some code using JAGS where I seem to be getting a different answer. Where is my mistake? Is this happening because of the priors?
Comment: Now I'm confused. First you said that the posterior distribution of b|y under a flat prior is the same as the classical sampling distribution of b. Then you said the Bayesian CI is wider than the classical one. How could it be wider if the distributions are the same?
Comment: Sorry - I should have told what @CP suggested in his comments. Theoretically, b|y under a flat prior and classical CI are the same, but you can't do that practically in JAGS unless you use a very very diffuse prior like CP suggested and use a lot of MCMC iterations.
Comment: I have merged your accounts so you can edit your questions and add comments. Yet, please register your account by clicking here: http://stats.stackexchange.com/users/login ; you can use your Gmail OpenID to do it in a few seconds and you'd not loose your account here any more.
Comment: Thanks, I have registered. And many thanks to those who answered this question. I will try the gamma prior.
Answer: For linear Gaussian models it is better to use the bayesm package. It implements the semi-conjugate family of priors, and the Jeffreys prior is a limit case of this family. See my example below. These are classical simulations, there's no need to use MCMC.
I do not remember whether the credibility intervals about the regression parameters are exactly the same as the usual least squares confidence intervals, but in any case they are very close.
> # required package
> library(bayesm)
> # data
> age <- c(35,45,55,65,75)
> tension <- c(114,124,143,158,166)
> y <- tension
> # model matrix
> X <- model.matrix(tension~age)
> # prior parameters
> Theta0 <- c(0,0)
> A0 <- 0.0001*diag(2)
> nu0 <- 0
> sigam0sq <- 0
> # number of simulations
> n.sims <- 5000
> # run posterior simulations
> Data <- list(y=y,X=X)
> Prior <- list(betabar=Theta0, A=A0, nu=nu0, ssq=sigam0sq)
> Mcmc <- list(R=n.sims)
> bayesian.reg <- runireg(Data, Prior, Mcmc)
> beta.sims <- t(bayesian.reg$betadraw) # transpose of bayesian.reg$betadraw
> sigmasq.sims <- bayesian.reg$sigmasqdraw
> apply(beta.sims, 1, quantile, probs = c(0.025, 0.975))
[,1] [,2]
2.5% 53.33948 1.170794
97.5% 77.23371 1.585798
> # to be compared with:
> frequentist.reg <- lm(tension~age)

Answer: Given that simple linear regression is analytically identical between classical and Bayesian analysis with Jeffrey's prior, both of which are analytic, it seems a bit odd to resort to a numerical method such as MCMC to do the Bayesian analysis.  MCMC is just a numerical integration tool, which allows Bayesian methods to be used in more complicated problems which are analytically intractable, just the same as Newton-Rhapson or Fisher Scoring are numerical methods for solving classical problems which are intractable.
The posterior distribution p(b|y) using the Jeffrey's prior p(a,b,s) proportional to 1/s (where s is the standard deviation of the error) is a student t distribution with location b_ols, scale se_b_ols ("ols" for "ordinary least squares" estimate), and n-2 degrees of freedom.  But the sampling distribution of b_ols is also a student t with location b, scale se_b_ols, and n-2 degrees of freedom.  Thus they are identical except that b and b_ols have been swapped, so when it comes to creating the interval, the "est +- bound" of the confidence interval gets reversed to a "est -+ bound" in the credible interval.
So the confidence interval and credible interval are analytically identical, and it matters not which method is used (provided there is no additional prior information) - so take the method which is computationally cheaper (e.g. the one with fewer matrix inversions).  What your result with MCMC shows is that the particular approximation used with MCMC gives a credible interval which is too wide compared to the exact analytic credible interval.  This is probably a good thing (although we would want the approximation to be better) that the approximate Bayesian solution appears more conservative than the exact Bayesian solution.
Comment: Another reason for using simulations: you also get posterior simulations for any function $f(\beta_0, \beta_1, \ldots, \beta_p, \sigma)$ of the parameters. For instance I use this possibility to get a credibility interval about the probability $\Pr(Y > 10 \mid x)$ for some value $x$ of the covariate. I don't know how to get a frequentist confidence interval about this probability.
Comment: Not so odd really. One reason for using a numerical method to find an answer to a problem that can be solved analytically is to ensure that one is using the software correctly.


Rotation/Translation beween 2 Maps?

Question: I have 2 maps, a location value is represented $(x,y)$ on Map1 and $(X,Y)$ on Map2.
I want to know how much rotation and translation is needed to match Map1 and Map2.
i.e.
I need to calculate $\theta, a,b$ in the following equation.
$$
\begin{bmatrix} X \\ Y \\ 1\end{bmatrix} =
\begin{bmatrix}
\cos\theta & -\sin\theta & a \\
\sin\theta &\cos\theta & b \\
0 & 0 & 1
\end{bmatrix}
\begin{bmatrix}
x \\ y \\ 1
\end{bmatrix}
$$
I have 3 pairs of $(x,y)$ and $(X,Y)$.
But they are experimental observed values, thus containing some errors.
How can I specify above $\theta, a,b$ ?
Sincerely,
thank you for your time.
Comment: You might get more response on a mathematics site.
Comment: Thank you for your comment. Could you tell me somewhere if you have any suggested site ?
Comment: Many, many versions of this question have been asked and answered on [GIS](https://gis.stackexchange.com/).  With only three pairs, statistics can't help you much, because you haven't any information to estimate the errors.
Answer: There is a rather simple technique, Procrustes analysis, which does just that. You may use the link provided or you will find a description in some Multivariate Analysis books (e.g., Krzanowski, W.J. Principles of Multivariate Analysis, Oxford Scientific Press).
Comment: Could you explain how this would apply when there are just three pairs of (x,y) data?
Comment: @whuber, checking the formulae involved I see no problems (no inverses of rank defficient matrices, or such). I agree that I would  not place great confidence in any results from such a small body of information, if that is your point: but perhaps the person asking may gather some more data.
Comment: That's correct.  But as far as I am aware, Procrustes analysis takes no heed of the nature of errors in either set of coordinates.  I see this as being analogous to the difference between ordinary regression and errors-in-variables regression.
Comment: Yes, that is true; but the person asking did not mention that this could be a problem. On the other hand, while Procrustes analysis makes no allowance for e.g. different variances of the errors in either map, it does account for changes in scale, as long as the space is isotropic. One matches one map to the other by means of a shift plus a rotation plus (optionally) an expansion (or stretching) of the scale (by means of a "dilation coefficient").

Rotation/Translation beween 2 Maps?


Compound Interest Formula

Question: I was trying to explain $e$ to someone and I ran across this idea. So, $e$ is typically defined as $$e =\lim_{n\to \infty} (1+1/n)^n $$
Which comes from the formula for compound interest
$$P(t) = P_0\left(1+\frac{r}{n}\right)^{nt}.$$
I could not explain why it is that we divide by $n$. The typical answer is that you simply "divide" the interest rate across each compounding period, but of course means that the borrower will end up paying more. This just seems like trickery on the part of the lender. Does anybody have any idea why this formula in particular? Was it simply to trick lenders?
$e$ also then becomes kinda flukey. How would you justify that
$$ \lim_{n\to \infty} \left( 1+\frac{x}{n}\right)^n$$
is an exponential function to some base let alone to the base $e$?
Answer: As
$$
e = \lim_{n \to \infty} \left( 1 + \frac1n \right)^n,
$$
and as for any real number $r > 0$, we have
$$
\lim_{n \to \infty} \frac{n}{r} = \infty = \lim_{n \to \infty} n \  \mbox{ and } \ \lim_{n \to \infty} \frac{r}{n} = 0 = \lim_{n \to \infty} \frac1n,
$$
so we obtain
$$
\lim_{n \to \infty} \left( 1 + \frac{r}{n} \right)^n = \lim_{n \to \infty} \left( \left( 1 + \frac{r}{n} \right)^{\frac{n}{r}}  \right)^r = e^r.
$$
Hence we also conclude that for any real numbers $r > 0$ and $t > 0$, we have
$$
\lim_{n \to \infty} \left( 1 + \frac{r}{n} \right)^{nt} = \lim_{n \to \infty} \left( \left( 1 + \frac{r}{n} \right)^{\frac{n}{r}}  \right)^{rt} = e^{rt}.
$$
Thus if $P_0$ is the initial amount, $r > 0$ is the interest rate compounded $n$ times a given period of time, then after $t$ such periods of $t$, our amount will be
$$
P_0 \times \left( 1 + \frac{r}{n} \right)^{nt},
$$
and so if our interest at rate $r$ is compounded continuously, then our amount after $t$ number of periods will be
$$
P_0 e^{rt}.
$$
Hope this helps.
Answer: I think you mean "trick borrowers", but it doesn't trick anybody.  This is simply how compound interest is normally computed, when the compounding period is shorter than one year.  Does the bank "trick lenders" when it compounds interest on savings deposits this way?  Imagine if your savings account paid $4\%$ compounded quarterly (back in the good old days), and at the end of $3$ months you were paid less than $1\%$ interest.
Comment: I still don't get why we say 4% annual interest, when if we are compounding quaterly we end up with a 4.64% total interest at the end of the year. "Dividing the 4%" among the quarters seems very suspect, which is the usual justification for the formula $(1+\frac{0.4}{4})^4$.
Comment: You mean $4.06\%$ There really isn't much difference.  Actually, I think what happened is that banks started compounding more frequently to attract depositors.  I can even remember cases where borrowers were compounding continuously.  That's a come-on if you like, because the difference is very small, but it's still real.
Comment: but $(1+\frac{0.4}{4})^4 = 1.464$. Hence you have paid 4.64% on top of the principal at the end of the year. Right?
Comment: $4\%=.04$ not $.4$  You're using $40\%$ interest and finding that compounding it quarterly gives somewhat more that $46\%$.
Comment: For small interest rates, indeed we have that (1+r/n)^n is pretty close to 1+r. Is that the only reason we use that formula. I don't know why we don't just give the actual rate per period.
Comment: This custom goes back many years.  We didn't always have computers and calculators that make these calculations simple.  Also, as you say, when rates were small, it didn't really matter.  The Truth in Lending law, which mandated a uniform way of stating interest rates in the United States, didn't come in until interest rates had gotten high enough that customary ways of stating them, particularly on auto loans, became misleading.  But car loans used to be computed in some really weird way that I can remember.  The Truth in Lending law  requires disclosing the effective annual rate.
Answer: There is a formula for case of f(x)^g(x)
When f(x) tends to 1 then
We can write e^((f(x)-1)*g(x))
It is applicable everywhere ..
It is a odd formula but very helpful
Comment: If anyone has any doubt then ask

Compound Interest Formula


Dashboard like module that works with Panels

Question: Dashboard module lets users change the dashboard according to their preferences. IS there a similar module which does the same for panels.
For example.

An admin user decides which blocks should be available on a particular page.
Each user can decide the order in which these blocks should be shown for him and whether they should be shown at all.
Answer: Dashboardify

Dashboardify is a module for creating complex dashboards.
Each user with proper permissions can add any block to dashboard and
  rearrange blocks order on his or her dashboard page. There is one
  dashboard with predefined regions available for each user. User can
  add unlimited instances of the same block which can be useful for
  views blocks with different contextual filters applied. Along with
  block information module stores data what contextual filters were used
  while adding block to dashboard. Block order is autosave via AJAX.

Panel Dashboard

Allows users to locally rearrange and roll up panes on the panel and
  save the state per account. Global state of the panel is not modified
  in the process.

Total Control Admin Dashboard

The Total Control Admin Dashboard creates a default panel page with
  useful administration tools. Its purpose is to create a central
  location from which a Drupal site can be properly cared for. Several
  overview panes are included for site stats and quick reference.
  Several administration panes are provided with quick links to content
  types, menus, taxonomy, and other scattered locations of important
  Drupal site administration. Several views panes are also provided as
  well as full-page comprehensive versions of the views with bulk
  operations. Each views panel pane is customizable via it's pane
  settings, or override the default views provided to suit your own
  needs.


Pegando um único valor parse PHP

Question: $ch = curl_init('site');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/6.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.7) Gecko/20050414 Firefox/1.0.3");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'x.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, 'x.txt');
$html = curl_exec($ch);
$dom = new DOMDocument();

@$dom->loadHTML($html);

$link = array();
foreach($dom->getElementsByTagName('a') as $link) {
  # Mostrar todos os elemento que estiver dentro da tag href

$x = $link->getAttribute('href'); // exibi todos os conteudo dentro do href !
// pegar apenas o link completo
#https://www.site.com/checkout.asp?ref=fvFDGND2MYQ

///
echo $x;

poem dessa forma eu consigo pegar todos os links do html recebido do cURL
http://prntscr.com/5icnbf
e para mim pegar apenas o https://www.site.com/checkout.asp?ref=fvFDGND2MYQ ? apenas esse link ?
Answer: Se queres um link em particular, podes verificar o conteúdo do mesmo para saberes se é de facto o que pretendes:
// ...
foreach ($dom->getElementsByTagName('a') as $link) {

  /* Verifica se é o link que eu quero
   */
  $href = $link->getAttribute('href');
  if (strpos($href, "checkout.asp?ref=") !== FALSE) {
    $x = $href;  // guarda o link
    break;       // sair do ciclo
  }
}

Para verificar, o que foi feito foi verificar se existe a expressão checkout.asp?ref= no link a ser processado, recorrendo à função strpos(). Deverás alterar a expressão caso procures outro link que não o que tens na pergunta.
Podes ver um exemplo a funcionar no Ideone combinado com o teu problema anterior.
Comment: :)) Agora sim peguei só o link que preciso muito obrigado ...

Pegando um único valor parse PHP


JQuery via the .info file isn't working

Question: I'm using/experimenting with Zen on my drupal site, and have just inserted a js file named alert.js into my theme's js folder.
The file has the following code:
<code>  (function ($){
Drupal.behaviors.kiwiAlert = {
  attach: function(){
    alert('Hello World');
   }
 };
})(jQuery);
</code>
I followed up by making the necessary changes in my .info file, by inserting the following snippet:
<code> scripts[] = js/alert.js
</code>
Since my site is in development mode I've set the cache to be cleared/theme registry to be rebuilt upon each page load, but just in case I cleared my cache again.
And nothing, the alert message doesn't show, why is this not working??
PS: I also tried the following code in the js file, in the same context, but to no avail :C
<code> alert("Hello World!!");
</code>
Any and all answers will be much appreciated :)
Comment: Strange, I added exactly what you have to a test site, and it worked for me. Are you adding this to a sub theme that isn't enabled?
Comment: nope, it's enabled and is implemented as the default theme, I wonder what's causing this not to work.
Comment: If you open your page in chrome, use the inspector (right click, inspect element) and head over to the console, and you type Drupal.behaviors, is kiwiAlert in the list of behaviors loaded?
Comment: theres actually an error in the console window the following: Failed to load resource: the server responded with a status of 403 (Forbidden)
Comment: well thats the problem but I have no idea as to why or how to fix it
Comment: Sounds like a permissions issue. Do you know what the permissions on your JS file is set to?
Comment: you're phenomenal, I uploaded the file with restrictions, just fixed it, and the alert shows up, thank you! XD you should paste the comment as the answer so I can upvote you :)
Answer: Answered in comments, but just moving the answer here for posterity's sake.
The theme was loading the .js file, but the permissions were restricted, so the server was returning a 403 error. Changing the permissions fixed the issue.
Comment: well, don't I feel like the worst person ever, just made this account on drupal SE, the other account on stackoverflow has enough rep to upvote, this one doesn't. :( thanks for the help and hopefully my gratitude and a bit of my stupidity will serve as a metaphoric upvote, sorry :{
Comment: No worries, glad I could help!

JQuery via the .info file isn't working


what is the easiest way to pass a list of integers from java to a frege function?

Question: Assume I have a Frege module
module Util where

total :: [Int] -> Int
total xs = fold (+) 0 xs

If "total" was written in Java, I could call it via
Util.total(Arrays.asList(1,2,3));

What is the best way to call the Frege implementation from Java?
Answer: You could use a good old int [] array, the corresponding frege type would be JArray Int. Because arrays can be made from and into lists in both Java and frege, they are good for such tasks.
Please use the repl to get an idea how to convert the array into a list so that you can pass it to your function.
If there are concerns rgd. heap space, there is also a so called ArrayIterator in Data.Iterators, that is an instance of the ListView type class. So another option would be to write your frege so as to take a ListView
total xs = fold (+) 0 xs.toList

and in java call the equivalent of
ArrayIterator.from (... code to create array here ...)

And if you can't change the frege code, or don't want to, you can make a lazy list with
(ArrayIterator.from (... code to create array here ...)).toList

Last but not least, you can fold over the array without converting it before with foldArray.
Comment: I'm using Sean Corfield's Leiningen plug-in to compile Frege code and to be able to call Frege code from Clojure. But when I try to call a Frege function that expects a list of integers (say with `(X/foo [1,2,3])`) I get the error `ClassCastException clojure.lang.PersistentVector cannot be cast to frege.runtime.Lazy`. @Ingo, can the answer above somehow be put to use here as well?
Comment: @0dB well, the message is quite clear. I'd put it this way: A clojure list is not a frege list. The answer above is a bit outdated, though. If you can manage to produce a java.util.List, we'll probably find a way to get that data into Frege. It would be good to open up a new question, though.


Convert Sql query to Linq

Question: Select Top(8) * from products order by CreatedOn desc can u convert this query to Linq List
where product is a table in sql Created on is a dateTime comumn..
Answer: var result = (from p in products
             orderby p.CreatedOn descending
             select p).Take(8);

OR
var result = products.OrderByDescending(p=>p.CreatedOn).Take(8);

Comment: @Marko Ivanovski @Timwi - sorry a typo, thanks for your help.
Answer: Have a look at the Linq to Sql Cheat Sheet. It contains a lot of useful, easy to follow LinqToSql information and is available for C# and VB.NET.
Relating to your query, look at the Paging and Order section, taking out the Skip(x) part of the query, and and replace the .Take(5) with your .Take(8) for your Top(8) value.
Answer: Check this StackOverflow question which talks about converting similar kind of query:
Converting SQL containing top, count, group and order to LINQ (2 Entities)
Comment: @Timwi - Thanks. Did not realize it was a duplicate from stack overflow itself.

Convert Sql query to Linq