问:
TYPO3 RealURL Language Domain Configuration
We have following sceneario:

The website has 3 Domains.

domain.de

domain.eu

domain.com.tr

TYPO3 is already setup for multilanguage and the IDs for the languages are:

default (de) = 0

en = 1

tr = 2

Could somebody give us the proper RealURL configuration for this?

答:
Try this, you just need to override default configuration for your other sub-domain.

```<code>$GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['realurl'] = array (
    'encodeSpURL_postProc' => array('user_encodeSpURL_postProc'),
    'decodeSpURL_preProc' => array('user_decodeSpURL_preProc'),
    '_DEFAULT' => array (
        'init' => array (
            'enableCHashCache' => '1',
            'appendMissingSlash' => 'ifNotFile',
            'enableUrlDecodeCache' => '1',
            'enableUrlEncodeCache' => '1'
        ),
        'redirects' => array (
        ),
        'preVars' => array (
            '0' => array (
                'GETvar' => 'no_cache',
                'valueMap' => array (
                    'nc' => '0'
                ),
                'noMatch' => 'bypass',
            ),
            '1' => array (
                'GETvar' => 'L',
                'valueMap' => array (
                    'de' => '0',
                    'en' => '1',
                    'tr' => '2'
                ),
                'noMatch' => 'bypass'
            ),
        ),
        'pagePath' => array (
            'type' => 'user',
            'userFunc' => 'EXT:realurl/class.tx_realurl_advanced.php:&tx_realurl_advanced->main',
            'spaceCharacter' => '-',
            'languageGetVar' => 'L',
            'rootpage_id' => '1'
        ),
        'fixedPostVars' => array (
        ),
        'postVarSets' => array (
            '_DEFAULT' => array (
                'archive' => array (
                    '0' => array (
                        'GETvar' => 'tx_ttnews[year]'
                    ),
                    '1' => array (
                        'GETvar' => 'tx_ttnews[month]',
                        'valueMap' => array (
                            'january' => '01',
                            'february' => '02',
                            'march' => '03',
                            'april' => '04',
                            'may' => '05',
                            'june' => '06',
                            'july' => '07',
                            'august' => '08',
                            'september' => '09',
                            'october' => '10',
                            'november' => '11',
                            'december' => '12'
                        ),
                    ),
                ),
                'page' => array (
                    '0' => array (
                        'GETvar' => 'tx_ttnews[pointer]'
                    ),
                ),
                'category' => array (
                    '0' => array (
                        'GETvar' => 'tx_ttnews[cat]',
                        'lookUpTable' => array (
                            'table' => 'tt_news_cat',
                            'id_field' => 'uid',
                            'alias_field' => 'title',
                            'addWhereClause' => ' AND NOT deleted',
                            'useUniqueCache' => '1',
                            'useUniqueCache_conf' => array (
                                'strtolower' => '1',
                                'spaceCharacter' => '-'
                            ),
                        ),
                    ),
                ),
                'article' => array (
                    '0' => array (
                        'GETvar' => 'tx_ttnews[tt_news]',
                        'lookUpTable' => array (
                            'table' => 'tt_news',
                            'id_field' => 'uid',
                            'alias_field' => 'title',
                            'addWhereClause' => ' AND NOT deleted',
                            'useUniqueCache' => '1',
                            'useUniqueCache_conf' => array (
                                'strtolower' => '1',
                                'spaceCharacter' => '-'
                            ),
                        ),
                    ),
                    '1' => array (
                        'GETvar' => 'tx_ttnews[swords]'
                    ),
                ),
            ),
        ),
        'fileName' => array (
            #'defaultToHTMLsuffixOnPrev' => '.html',
            #'acceptHTMLsuffix' => 1,
            'index' => array (
                'rss.xml' => array (
                    'keyValues' => array (
                        'type' => '100'
                    ),
                ),
                'rss091.xml' => array (
                    'keyValues' => array (
                        'type' => '101'
                    ),
                ),
                'rdf.xml' => array (
                    'keyValues' => array (
                        'type' => '102'
                    ),
                ),
                'atom.xml' => array (
                    'keyValues' => array (
                        'type' => '103'
                    ),
                ),
                'sitemap.xml' => array (
                    'keyValues' => array (
                        'type' => '776'
                    ),
                ),
            ),
        ),
    )
);
/*
 * All your other domain configuration goes here. Change your domain name
 * and domain root page id as per your need.
 *
 */
$GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['realurl']['domain.de'] = $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['realurl']['_DEFAULT'];
$GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['realurl']['domain.de']['pagePath']['rootpage_id'] = '41'; // Change your sub-domain root page id

$GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['realurl']['domain.eu'] = $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['realurl']['_DEFAULT'];
$GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['realurl']['domain.eu']['pagePath']['rootpage_id'] = '51'; // Change your sub-domain root page id

$GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['realurl']['domain.com.tr'] = $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['realurl']['_DEFAULT'];
$GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['realurl']['domain.com.tr']['pagePath']['rootpage_id'] = '61'; // Change your sub-domain root page id
</code>```

Please change codes as per your need. Hope this will help you.

Greetings!

Body:
Try this, you just need to override default configuration for your other sub-domain.

$GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['realurl'] = array (
    'encodeSpURL_postProc' => array('user_encodeSpURL_postProc'),
    'decodeSpURL_preProc' => array('user_decodeSpURL_preProc'),
    '_DEFAULT' => array (
        'init' => array (
            'enableCHashCache' => '1',
            'appendMissingSlash' => 'ifNotFile',
            'enableUrlDecodeCache' => '1',
            'enableUrlEncodeCache' => '1'
        ),
        'redirects' => array (
        ),
        'preVars' => array (
            '0' => array (
                'GETvar' => 'no_cache',
                'valueMap' => array (
                    'nc' => '0'
                ),
                'noMatch' => 'bypass',
            ),
            '1' => array (
                'GETvar' => 'L',
                'valueMap' => array (
                    'de' => '0',
                    'en' => '1',
                    'tr' => '2'
                ),
                'noMatch' => 'bypass'
            ),
        ),
        'pagePath' => array (
            'type' => 'user',
            'userFunc' => 'EXT:realurl/class.tx_realurl_advanced.php:&tx_realurl_advanced->main',
            'spaceCharacter' => '-',
            'languageGetVar' => 'L',
            'rootpage_id' => '1'
        ),
        'fixedPostVars' => array (
        ),
        'postVarSets' => array (
            '_DEFAULT' => array (
                'archive' => array (
                    '0' => array (
                        'GETvar' => 'tx_ttnews[year]'
                    ),
                    '1' => array (
                        'GETvar' => 'tx_ttnews[month]',
                        'valueMap' => array (
                            'january' => '01',
                            'february' => '02',
                            'march' => '03',
                            'april' => '04',
                            'may' => '05',
                            'june' => '06',
                            'july' => '07',
                            'august' => '08',
                            'september' => '09',
                            'october' => '10',
                            'november' => '11',
                            'december' => '12'
                        ),
                    ),
                ),
                'page' => array (
                    '0' => array (
                        'GETvar' => 'tx_ttnews[pointer]'
                    ),
                ),
                'category' => array (
                    '0' => array (
                        'GETvar' => 'tx_ttnews[cat]',
                        'lookUpTable' => array (
                            'table' => 'tt_news_cat',
                            'id_field' => 'uid',
                            'alias_field' => 'title',
                            'addWhereClause' => ' AND NOT deleted',
                            'useUniqueCache' => '1',
                            'useUniqueCache_conf' => array (
                                'strtolower' => '1',
                                'spaceCharacter' => '-'
                            ),
                        ),
                    ),
                ),
                'article' => array (
                    '0' => array (
                        'GETvar' => 'tx_ttnews[tt_news]',
                        'lookUpTable' => array (
                            'table' => 'tt_news',
                            'id_field' => 'uid',
                            'alias_field' => 'title',
                            'addWhereClause' => ' AND NOT deleted',
                            'useUniqueCache' => '1',
                            'useUniqueCache_conf' => array (
                                'strtolower' => '1',
                                'spaceCharacter' => '-'
                            ),
                        ),
                    ),
                    '1' => array (
                        'GETvar' => 'tx_ttnews[swords]'
                    ),
                ),
            ),
        ),
        'fileName' => array (
            #'defaultToHTMLsuffixOnPrev' => '.html',
            #'acceptHTMLsuffix' => 1,
            'index' => array (
                'rss.xml' => array (
                    'keyValues' => array (
                        'type' => '100'
                    ),
                ),
                'rss091.xml' => array (
                    'keyValues' => array (
                        'type' => '101'
                    ),
                ),
                'rdf.xml' => array (
                    'keyValues' => array (
                        'type' => '102'
                    ),
                ),
                'atom.xml' => array (
                    'keyValues' => array (
                        'type' => '103'
                    ),
                ),
                'sitemap.xml' => array (
                    'keyValues' => array (
                        'type' => '776'
                    ),
                ),
            ),
        ),
    )
);
/*
 * All your other domain configuration goes here. Change your domain name
 * and domain root page id as per your need.
 *
 */
$GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['realurl']['domain.de'] = $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['realurl']['_DEFAULT'];
$GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['realurl']['domain.de']['pagePath']['rootpage_id'] = '41'; // Change your sub-domain root page id

$GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['realurl']['domain.eu'] = $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['realurl']['_DEFAULT'];
$GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['realurl']['domain.eu']['pagePath']['rootpage_id'] = '51'; // Change your sub-domain root page id

$GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['realurl']['domain.com.tr'] = $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['realurl']['_DEFAULT'];
$GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['realurl']['domain.com.tr']['pagePath']['rootpage_id'] = '61'; // Change your sub-domain root page id

Please change codes as per your need. Hope this will help you.

Greetings!


来源: stackexchange

问:
Ionic 2 Promise - Finishing the first process before executing the second process
For my Ionic 2 project, I have two functions executing one after another. Each function consists of an API call. I want to wait until the first function finishes executing everything before going to the second function.

The issue I'm having is that since the first function takes some time to finish, the second function executes before the first function finishes executing.

I'm learning how to use Promise as I was told it can solve this issue.
I've simplified the code so it's easier to follow:

```<code>const first = () => {
  self.pspService.post('/api/Conversation/GetPersonalCalendarData',
    {
    }, result => {
      result.Data.forEach(lAppointment => {
      });
    });

  return new Promise((resolve, reject) => {
    resolve();
  });

};

const second = () => {
  self.pspService.post('/api/Conversation/AddPersonalAppointment', {
  }, result => {

  });

  return new Promise((resolve, reject) => {
    resolve();
  });
};

first().then(() => {
  return second();
});
</code>```

答:
You could wrap your post inside the new Promise:

```<code>const first = () => {
    return new Promise((resolve, reject) => {
        self.pspService.post('/api/Conversation/GetPersonalCalendarData', {
            }, result => {
                result.Data.forEach(lAppointment => {});
                resolve();
            });
    });

};

const second = () => {
return new Promise((resolve, reject) => {
    self.pspService.post('/api/Conversation/AddPersonalAppointment', {
        }, result => {
            resolve();
        });
});
};

first().then(() => {
     return second();
});
</code>```

Or return directly the promise generated by the POST

```<code>const first = () => {
    return self.pspService.post('url, {}, result => {
            result.Data.forEach(lAppointment => {});
            return Promise.resolve(result);
        })
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
For my Ionic 2 project, I have two functions executing one after another. Each function consists of an API call. I want to wait until the first function finishes executing everything before going to the second function.

The issue I'm having is that since the first function takes some time to finish, the second function executes before the first function finishes executing.

I'm learning how to use Promise as I was told it can solve this issue.
I've simplified the code so it's easier to follow:

const first = () => {
  self.pspService.post('/api/Conversation/GetPersonalCalendarData',
    {
    }, result => {
      result.Data.forEach(lAppointment => {
      });
    });

  return new Promise((resolve, reject) => {
    resolve();
  });

};

const second = () => {
  self.pspService.post('/api/Conversation/AddPersonalAppointment', {
  }, result => {

  });

  return new Promise((resolve, reject) => {
    resolve();
  });
};

first().then(() => {
  return second();
});

Body:
You could wrap your post inside the new Promise:

const first = () => {
    return new Promise((resolve, reject) => {
        self.pspService.post('/api/Conversation/GetPersonalCalendarData', {
            }, result => {
                result.Data.forEach(lAppointment => {});
                resolve();
            });
    });

};

const second = () => {
return new Promise((resolve, reject) => {
    self.pspService.post('/api/Conversation/AddPersonalAppointment', {
        }, result => {
            resolve();
        });
});
};

first().then(() => {
     return second();
});

Or return directly the promise generated by the POST

const first = () => {
    return self.pspService.post('url, {}, result => {
            result.Data.forEach(lAppointment => {});
            return Promise.resolve(result);
        })
}


问:
Expose QList<QObject *> hierarchy to QML
I'm currently in the situation, that I have a QList with MyClass also including a list QList.

To display this list-hierarchy I want to provide a Repeater within a ListView.

I tried this with a QStringList and it works fine (see uncommented lines below). When I try to do this with my QList I cannot access the name-property of MySubClass. Instead the name-property of MyClass is shown.

WRONG output:

```<code>Object 1
Object 1
Object 1
Object 2
</code>```

Correct output should be:

```<code>Object 1
SubObject 1
SubObject 2
Object 2
</code>```

EDIT: 08.12.2014
I found out, why the sublist did not work. I just had to replace one line in the delegate of the sub-ListView (name -> modelData.name).

Here's my code:

main.cpp

```<code>#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QList>
#include <QDebug>

#include "myclass.h"

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    /* create simple stringlist */
    QStringList dataList;
    dataList << "Data 1"
         << "Data 2"
         << "Data 3";

    /* create more complex QObject List */
    MySubClass *mySubObject = NULL;
    QList<QObject *> mySubList;

    mySubObject = new MySubClass;
    mySubObject->setName("SubObject 1");
    mySubList.append(mySubObject);

    mySubObject = new MySubClass;
    mySubObject->setName("SubObject 2");
    mySubList.append(mySubObject);

    /* create object list */
    MyClass *myObject = NULL;
    QList<QObject *> myList;

    myObject = new MyClass;
    myObject->setName("Object 1");
    myObject->setDataList(dataList);
    myObject->setObjectList(mySubList);
    myList.append(myObject);

    myObject = new MyClass;
    myObject->setName("Object 2");
    myObject->setDataList(dataList);
    myList.append(myObject);

    qDebug () << myList.size();

    myObject = NULL;

    /* start engine and expose object list */
    QQmlApplicationEngine engine;

    QQmlContext *myContext = engine.rootContext();
    myContext->setContextProperty("myObjectList", QVariant::fromValue(myList));

    engine.load(QUrl(QStringLiteral("qrc:///main.qml")));

    return app.exec();
}
</code>```

MyClass.h

```<code>#ifndef MYCLASS_H
#define MYCLASS_H

#include <QObject>
#include <QStringList>

#include "mysubclass.h"

class MyClass : public QObject
{
    Q_OBJECT
    Q_PROPERTY (QString name READ name WRITE setName NOTIFY nameChanged)
    Q_PROPERTY (QStringList dataList READ dataList WRITE setDataList NOTIFY dataListChanged)
    Q_PROPERTY (QList<QObject *> objectList READ objectList WRITE setObjectList NOTIFY objectListChanged)
public:
    inline MyClass(QObject *parent = 0) : QObject(parent) {}
    inline ~MyClass() {}

    QString name() const
    {
        return m_name;
    }

    QStringList dataList() const
    {
        return m_dataList;
    }

    QList<QObject *> objectList() const
    {
        return m_objectList;
    }

public slots:
    void setName(QString arg)
    {
        if (m_name != arg) {
            m_name = arg;
            emit nameChanged(arg);
        }
    }

    void setDataList(QStringList arg)
    {
        if (m_dataList != arg) {
            m_dataList = arg;
            emit dataListChanged(arg);
        }
    }

    void setObjectList(QList<QObject *> arg)
    {
        if (m_objectList != arg) {
            m_objectList = arg;
            emit objectListChanged(arg);
        }
    }

signals:
    void nameChanged(QString arg);
    void dataListChanged(QStringList arg);

    void objectListChanged(QList<QObject *> arg);

private:
    QString m_name;
    QStringList m_dataList;

    QList<QObject *> m_objectList;
};

#endif // MYCLASS_H
</code>```

MySubClass.h

```<code>#ifndef MYSUBCLASS_H
#define MYSUBCLASS_H

#include <QObject>
#include <QString>

class MySubClass : public QObject
{
    Q_OBJECT
    Q_PROPERTY (QString name READ name WRITE setName NOTIFY nameChanged)

public:
    inline MySubClass(QObject *parent = 0) : QObject(parent) {}
    inline ~MySubClass() {}

    QString name() const
    {
        return m_name;
    }
public slots:
    void setName(QString arg)
    {
        if (m_name != arg) {
            m_name = arg;
            emit nameChanged(arg);
        }
    }
signals:
    void nameChanged(QString arg);

private:
    QString m_name;
};

#endif // MYSUBCLASS_H
</code>```

main.qml

```<code>import QtQuick 2.2
import QtQuick.Window 2.1

Window {
    visible: true
    width: 360
    height: 360

    ListView  {
        id: view
        anchors.fill: parent

        model: myObjectList

        delegate: Item {
            width: parent.width
            height: col.height
            Column {
                id: col
                Text {
                    id: nameLabel
                    text: name
                }

                Repeater {
                    id: dataView
//                    model: dataList
                    model: objectList
                    delegate: Text {
                        id: dataLabel
//                        text: modelData
                        // text: name
                          /* Here's the fix!!! (dunno why, but it works) */
                          text: modelData.name
                    }
                }
            }
        }
    }
}
</code>```

答: Try to add Q_DECLARE_METATYPE(MySubClass*) after class definition, in my case QList worked properly, ah, and I passed QObjectList as property

Body:
I'm currently in the situation, that I have a QList with MyClass also including a list QList.

To display this list-hierarchy I want to provide a Repeater within a ListView.

I tried this with a QStringList and it works fine (see uncommented lines below). When I try to do this with my QList I cannot access the name-property of MySubClass. Instead the name-property of MyClass is shown.

WRONG output:

Object 1
Object 1
Object 1
Object 2

Correct output should be:

Object 1
SubObject 1
SubObject 2
Object 2

EDIT: 08.12.2014
I found out, why the sublist did not work. I just had to replace one line in the delegate of the sub-ListView (name -> modelData.name).

Here's my code:

main.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QList>
#include <QDebug>

#include "myclass.h"

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    /* create simple stringlist */
    QStringList dataList;
    dataList << "Data 1"
         << "Data 2"
         << "Data 3";

    /* create more complex QObject List */
    MySubClass *mySubObject = NULL;
    QList<QObject *> mySubList;

    mySubObject = new MySubClass;
    mySubObject->setName("SubObject 1");
    mySubList.append(mySubObject);

    mySubObject = new MySubClass;
    mySubObject->setName("SubObject 2");
    mySubList.append(mySubObject);

    /* create object list */
    MyClass *myObject = NULL;
    QList<QObject *> myList;

    myObject = new MyClass;
    myObject->setName("Object 1");
    myObject->setDataList(dataList);
    myObject->setObjectList(mySubList);
    myList.append(myObject);

    myObject = new MyClass;
    myObject->setName("Object 2");
    myObject->setDataList(dataList);
    myList.append(myObject);

    qDebug () << myList.size();

    myObject = NULL;

    /* start engine and expose object list */
    QQmlApplicationEngine engine;

    QQmlContext *myContext = engine.rootContext();
    myContext->setContextProperty("myObjectList", QVariant::fromValue(myList));

    engine.load(QUrl(QStringLiteral("qrc:///main.qml")));

    return app.exec();
}

MyClass.h

#ifndef MYCLASS_H
#define MYCLASS_H

#include <QObject>
#include <QStringList>

#include "mysubclass.h"

class MyClass : public QObject
{
    Q_OBJECT
    Q_PROPERTY (QString name READ name WRITE setName NOTIFY nameChanged)
    Q_PROPERTY (QStringList dataList READ dataList WRITE setDataList NOTIFY dataListChanged)
    Q_PROPERTY (QList<QObject *> objectList READ objectList WRITE setObjectList NOTIFY objectListChanged)
public:
    inline MyClass(QObject *parent = 0) : QObject(parent) {}
    inline ~MyClass() {}

    QString name() const
    {
        return m_name;
    }

    QStringList dataList() const
    {
        return m_dataList;
    }

    QList<QObject *> objectList() const
    {
        return m_objectList;
    }

public slots:
    void setName(QString arg)
    {
        if (m_name != arg) {
            m_name = arg;
            emit nameChanged(arg);
        }
    }

    void setDataList(QStringList arg)
    {
        if (m_dataList != arg) {
            m_dataList = arg;
            emit dataListChanged(arg);
        }
    }

    void setObjectList(QList<QObject *> arg)
    {
        if (m_objectList != arg) {
            m_objectList = arg;
            emit objectListChanged(arg);
        }
    }

signals:
    void nameChanged(QString arg);
    void dataListChanged(QStringList arg);

    void objectListChanged(QList<QObject *> arg);

private:
    QString m_name;
    QStringList m_dataList;

    QList<QObject *> m_objectList;
};

#endif // MYCLASS_H

MySubClass.h

#ifndef MYSUBCLASS_H
#define MYSUBCLASS_H

#include <QObject>
#include <QString>

class MySubClass : public QObject
{
    Q_OBJECT
    Q_PROPERTY (QString name READ name WRITE setName NOTIFY nameChanged)

public:
    inline MySubClass(QObject *parent = 0) : QObject(parent) {}
    inline ~MySubClass() {}

    QString name() const
    {
        return m_name;
    }
public slots:
    void setName(QString arg)
    {
        if (m_name != arg) {
            m_name = arg;
            emit nameChanged(arg);
        }
    }
signals:
    void nameChanged(QString arg);

private:
    QString m_name;
};

#endif // MYSUBCLASS_H

main.qml

import QtQuick 2.2
import QtQuick.Window 2.1

Window {
    visible: true
    width: 360
    height: 360

    ListView  {
        id: view
        anchors.fill: parent

        model: myObjectList

        delegate: Item {
            width: parent.width
            height: col.height
            Column {
                id: col
                Text {
                    id: nameLabel
                    text: name
                }

                Repeater {
                    id: dataView
//                    model: dataList
                    model: objectList
                    delegate: Text {
                        id: dataLabel
//                        text: modelData
                        // text: name
                          /* Here's the fix!!! (dunno why, but it works) */
                          text: modelData.name
                    }
                }
            }
        }
    }
}


问:
Angular: ngOnChanges not updating value
I am new to ngOnchanges and facing below issue.

my parent component is setting recom value on ngOnChanges and sends the same value to child component. child receives the same as input in ngOnChanges. depending on some condition like totalVal>0 i set inputField  to true which is initially set to false. if inputField is true i show some component in reactive forms. but when my below structure execute model2Form() it still gets inputField as false. I cant post actual code so just created a structure as per my project as shown below.

Please suggest how do i solve this issue.

```<code>// parent component

ngOnchanges(){
  this.recom = [{
    totalVal: 5000,
    monthlydata: true
  }]
}

//child component

@Input()
private recom: any;

inputField: boolean = false;

ngOnChanges(){
  this.setValue();
  this.loadFuture();
}

setValue(){
  if(this.recom.totalVal > 0){
    this.inputField = true;
  }
}

loadFuture(){

}

model2Form(){

//getting input field as false even if i set it as true in setValue()

  if(inputField){
    this.heroForm.setControl('secretLairs', addressFormArray);
  }

}

<!-- parent component>

<parent-comp [recom]="recom"></parent-comp>

<!-- child component -->

<div [FormControlName]="secretLairs"> </div>
</code>```

答:
The problem is that you are trying to monitor changes on an Array. Arrays and Objects don't work so well with ngOnChanges because they are passed by reference, not value. Strings and Integers work well here because its easy for Angular to tell when the value has been changed. Since Javascript passes Objects and Arrays by reference, Angular will only trigger change detection when the reference changes.

Three ways to solve this really:

Store your complex value in a service as either a subject or BehaviorSubject if you have access to your values right away. Then subscribe to it throughout your application where needed. Every time a new value is pushed to the Observable, your components will run their logic on it.

Separate the properties you need to monitor into separate @Inputs() that are monitoring the value of something like a string or number.

The third way to solve this is to assign the Object/Array to an entirely new entity using Object.assign() function and replacing the value of your property outright with the new entity thus creating a new reference.

Title: Angular: ngOnChanges not updating value

Body:
I am new to ngOnchanges and facing below issue.

my parent component is setting recom value on ngOnChanges and sends the same value to child component. child receives the same as input in ngOnChanges. depending on some condition like totalVal>0 i set inputField  to true which is initially set to false. if inputField is true i show some component in reactive forms. but when my below structure execute model2Form() it still gets inputField as false. I cant post actual code so just created a structure as per my project as shown below.

Please suggest how do i solve this issue.

// parent component

ngOnchanges(){
  this.recom = [{
    totalVal: 5000,
    monthlydata: true
  }]
}

//child component

@Input()
private recom: any;

inputField: boolean = false;

ngOnChanges(){
  this.setValue();
  this.loadFuture();
}

setValue(){
  if(this.recom.totalVal > 0){
    this.inputField = true;
  }
}

loadFuture(){

}

model2Form(){

//getting input field as false even if i set it as true in setValue()

  if(inputField){
    this.heroForm.setControl('secretLairs', addressFormArray);
  }

}


问:
Weka not display Correctly classified instances as output
I am new on weka. I have a dataset in csv with 5000 samples. here 20 samples of it; when I upload this dataset into weka, it looks ok, but when I run knn algorithm it gives a result that is not supposed to give. here is the sample data.

a,b,c,d

74,85,123,1

73,84,122,1

72,83,121,1

70,81,119,1

70,81,119,1

69,80,118,1

70,81,119,1

70,81,119,1

76,87,125,1

76,87,125,1

82,92,146,2

74,86,140,2

68,80,134,2

64,76,130,2

64,75,132,2

83,96,152,2

72,85,141,2

71,83,141,2

69,81,139,2

65,79,137,2

here is the result :

=== Cross-validation ===
=== Summary ===

Correlation coefficient                  0.6148
Mean absolute error                      0.2442
Root mean squared error                  0.4004
Relative absolute error                 50.2313 %
Root relative squared error             81.2078 %
Total Number of Instances             5000

it is supposed to give this kind of result like:
Correctly classified instances: 69 92%
Incorrectly classified instances: 6 8%

What should be the problem? What am I missing? I did this in all other algorithms but they all give the same output. I have used sample weka datasets, they all work as expected.

答:
The IBk algorithm can be used for regression (predicting the value of a numeric response for each instance) as well as for classification (predicting which class each instance belongs to).

It looks like all the values of the class attribute in your dataset (column d in your CSV) are numbers. When you load this data into Weka, Weka therefore guesses that this attribute should be treated as a numeric one, not a nominal one. You can tell this has happened because the histogram in the Preprocess tab looks something like this:

instead of like this (coloured by class):

The result you're seeing when you run IBk is the result of a regression fit (predicting a numeric value of column d for each instance) instead of a classification (selecting the most likely nominal value of column d for each instance).

To get the result you want, you need to tell Weka to treat this attribute as nominal. When you load the csv file in the Preprocess tab, check Invoke options dialog in the file dialog window. Then when you click Open, you'll get this window:

The field nominalAttributes is where you can give Weka a list of which attributes are nominal ones even if they look numeric. Entering 4 here will specify that the fourth attribute (column) in the input is a nominal attribute. Now IBk should behave as you expect.

You could also do this by applying the NumericToNominal unsupervised attribute filter to the already loaded data, again specifying attribute 4 otherwise the filter will apply to all the attributes.

The ARFF format used for the Weka sample datasets includes a specification of which attributes are which type. After you've imported (or filtered) your dataset as above, you can save it as ARFF and you'll then be able to reload it without having to go through the same process.


问:
How to use string as a delimiter in getline() function in c++
I have structure member which takes the value of delimiter from XML.And I want use that structure member as delimiter . But as getline() function take delimiter as char only so my I'm stuck over there.

istream& getline (istream& is, string& str, char delim)

I have done following thing in my code:-

```<code>string ABC = struct.delimiter;    // Here struct.delimiter is takes value of
                                     d delimiter from XML delimiter = '='
</code>```

and I want use as

```<code>getline(string1,string2, ABC);
</code>```

Is it possible?
or
Is there another way to do it?

答:
If ABC is guaranteed to be a single character in length you can use ABC[0] to get the first character out of the string:

```<code>getline(string1, string2, ABC[0]);
</code>```

Or just make ABC a char to make that guarantee even more apparent.

```<code>char ABC = struct.delimiter; // (assuming struct.delimiter is also a char,
                             //  if not use srtuct.delimiter[0])
getline(string1, string2, ABC);
</code>```

Body:
I have structure member which takes the value of delimiter from XML.And I want use that structure member as delimiter . But as getline() function take delimiter as char only so my I'm stuck over there.

istream& getline (istream& is, string& str, char delim)

I have done following thing in my code:-

string ABC = struct.delimiter;    // Here struct.delimiter is takes value of
                                     d delimiter from XML delimiter = '='

and I want use as

getline(string1,string2, ABC);

Is it possible?
or
Is there another way to do it?

Body:
If ABC is guaranteed to be a single character in length you can use ABC[0] to get the first character out of the string:

getline(string1, string2, ABC[0]);

Or just make ABC a char to make that guarantee even more apparent.

char ABC = struct.delimiter; // (assuming struct.delimiter is also a char,
                             //  if not use srtuct.delimiter[0])
getline(string1, string2, ABC);


问:
Generate ID's for text and calendar control in Jquery
I want to generate Id's for input type text  whenever I click on .add class. Currently Whenever I click on .add class it generates the id's with same name for each input control. So while adding data it does not work properly.

So how should I generate ID's for each text whenever I click on .add class. Please suggest.

Here is what is generates.

Generated HTML

$('.add').on('click', function() {
  var $tr = $(this).closest('tr');
  var $tr2 = $tr.clone(true, true);
  $tr2.find(".vendorName").children('label').remove();
  $tr2.find(".vendorFromDate").children('label').remove();
  $tr2.find(".vendorToDate").children('label').remove();
  $tr2.find(".vendorName").children().unwrap();
  $tr2.find(".vendorFromDate").children().unwrap();
  $tr2.find(".vendorToDate").children().unwrap();
  $tr2.insertAfter($tr);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr>
  <td>
    <div class="row noPadding vendorForm">
      <div class="vendorDaterow">
        <div class="vendorName" id="dvVendorNameData">
          <label>SP Vender Name</label><span><input type="text" name="nmVendorData" id="txtVendorName1" /></span>
        </div>
        <div class="vendorFromDate">
          <label>From Date</label><span class="datepicker"><input type="text" name="nmVendorData" id="spFromDate1" /><i class="fa fa-calendar" aria-hidden="true"></i></span>
        </div>
        <div class="vendorToDate">
          <label>To Date</label><span class="datepicker"><input type="text" name="nmVendorData" id="spToDate1" /><i class="fa fa-calendar" aria-hidden="true"></i></span>
        </div>
      </div>
      <div class="add">
        <i class="fa fa-plus" aria-hidden="true"></i>
      </div>
      <i class="max">(Maximum 5 Vendors)</i>

    </div>
  </td>
</tr></code>```

Please suggest how should I generate the dynamic ID.

答:
Well, you can always generate IDs based on how many items you have.

you will have something like

```<code>            $(".add").on("click", function(){
            var numBlocks = $('.vendorDaterow').length;
/*gets number of elements with this class in DOM*/

            var formStructure = "";
            formStructure = "<div id='formRow"+numBlocks+"' class='vendorDaterow'>";
            formStructure = "<div class='vendorName' id='dvVendorNameData"+numBlocks+"'>";
            formStructure = "<label>SP Vender Name</label><span><input type='text' name='nmVendorData' id='txtVendorName"+numBlocks+"' />";
            /*continue for whole structure*/

            $("#formRow"+(numBlocks-1)).parent().append(formStructure);
     /*finds last existing #formRow, gets his parent node and append your new node into it. Also you can do your other logic based on id, like hiding the add button or something.*/

        });
</code>```

note that counting IDs starts at 0 (you have nothing, lenght is 0. so the first added node will will be #formRow0.

Body:
I want to generate Id's for input type text  whenever I click on .add class. Currently Whenever I click on .add class it generates the id's with same name for each input control. So while adding data it does not work properly.

So how should I generate ID's for each text whenever I click on .add class. Please suggest.

Here is what is generates.

Generated HTML

$('.add').on('click', function() {
  var $tr = $(this).closest('tr');
  var $tr2 = $tr.clone(true, true);
  $tr2.find(".vendorName").children('label').remove();
  $tr2.find(".vendorFromDate").children('label').remove();
  $tr2.find(".vendorToDate").children('label').remove();
  $tr2.find(".vendorName").children().unwrap();
  $tr2.find(".vendorFromDate").children().unwrap();
  $tr2.find(".vendorToDate").children().unwrap();
  $tr2.insertAfter($tr);
});

          SP Vender Name<input type="text" name="nmVendorData" id="txtVendorName1" />

          From Date<input type="text" name="nmVendorData" id="spFromDate1" />

          To Date<input type="text" name="nmVendorData" id="spToDate1" />

      (Maximum 5 Vendors)

Please suggest how should I generate the dynamic ID.

Body:
Well, you can always generate IDs based on how many items you have.

you will have something like

            $(".add").on("click", function(){
            var numBlocks = $('.vendorDaterow').length;
/*gets number of elements with this class in DOM*/

            var formStructure = "";
            formStructure = "<div id='formRow"+numBlocks+"' class='vendorDaterow'>";
            formStructure = "<div class='vendorName' id='dvVendorNameData"+numBlocks+"'>";
            formStructure = "<label>SP Vender Name</label><span><input type='text' name='nmVendorData' id='txtVendorName"+numBlocks+"' />";
            /*continue for whole structure*/

            $("#formRow"+(numBlocks-1)).parent().append(formStructure);
     /*finds last existing #formRow, gets his parent node and append your new node into it. Also you can do your other logic based on id, like hiding the add button or something.*/

        });

note that counting IDs starts at 0 (you have nothing, lenght is 0. so the first added node will will be #formRow0.


问:
How will _Exit behave in a C++ program?
C99 offers the _Exit function, which exits "immediately", although it does may close file descriptors. Unix/POSIX extends this behavior by mandating the closing of all fd's without flushing (and offers the synonym _exit).

Will these functions call destructors for static objects when called from a C++ program? Does the C++ standard make any guarantees about _Exit?

(Inspired by this question; I suddenly wondered what happens in the typical fork-exec-_exit idiom in C++.)

答: C++0x defines a new function called std::quick_exit that terminates a process without calling any destructors. Just checked, g++-4.4.5 already provides it.</p>

Title: How will _Exit behave in a C++ program?

ContentLicense: CC BY-SA 2.5


问:
maven does not print name of tested class; replaces class name with TestSuite
I'm running this project with testNG, i get the test result(successful one) as

```<code>[RemoteTestNG] detected TestNG version 6.13.1
Success!!
Dec 07, 2017 4:44:06 PM org.openqa.selenium.remote.ProtocolHandshake
createSession
INFO: Detected dialect: OSS
PASSED: begin
PASSED: google

===============================================
    Default test
    Tests run: 2, Failures: 0, Skips: 0
===============================================

===============================================
Default suite
Total tests run: 2, Failures: 0, Skips: 0
===============================================
</code>```

But when running as Maven test, it doesn't print the name of passed test cases(or any test). It just gives number of tests run. I want the passed cases to be printed here as well.

P.S. - Class is in src/test/java. Tried changing it to  src/main/java as suggested in one of issue. but maven skipped the tests altogether in that way as Surefire-plugin runs all tests that are in test source directory src/test/java.

```<code>[INFO] Scanning for projects...
[INFO]

[INFO] ------------------------------------------------------------------------
[INFO] Building MavenFrstProj 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ MavenFrstProj ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory
C:\Users\Shrikanth\workspace\MavenFrstProj\src\main\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.7.0:compile (default-compile) @
MavenFrstProj ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources)
@ MavenFrstProj ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory
C:\Users\Shrikanth\workspace\MavenFrstProj\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.7.0:testCompile (default-testCompile) @
MavenFrstProj ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-surefire-plugin:2.20:test (default-test) @ MavenFrstProj --
-
[INFO]
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running TestSuite
Success!!
Dec 07, 2017 4:45:58 PM org.openqa.selenium.remote.ProtocolHandshake
createSession
INFO: Detected dialect: OSS
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 8.017
s - in TestSuite
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] ---------------------------------------------------------------------
---
[INFO] BUILD SUCCESS
[INFO] ---------------------------------------------------------------------
---
[INFO] Total time: 11.972 s
[INFO] Finished at: 2017-12-07T16:46:02+05:30
[INFO] Final Memory: 12M/178M
[INFO] ------------------------------------------------------------------------
</code>```

Note : Also checking the xml report(TestSuite) generated in target/surefire-reports, it replaces class name as TestSuite and in console output it prints Running TestSuite instead of Running <classname>. May be thats the root, but not sure. How do I fix it. Please help!

答:
By default, the Surefire Plugin will automatically include all test classes with the following wildcard patterns:

```<code>"**/Test*.java" - includes all of its subdirectories and all Java filenames that start with "Test".
"**/*Test.java" - includes all of its subdirectories and all Java filenames that end with "Test".
"**/*Tests.java" - includes all of its subdirectories and all Java filenames that end with "Tests".
"**/*TestCase.java" - includes all of its subdirectories and all Java filenames that end with "TestCase".
</code>```

Make sure your test class names follow this pattern otherwise , add each class inclusively in pom.xml

Body:
I'm running this project with testNG, i get the test result(successful one) as

[RemoteTestNG] detected TestNG version 6.13.1
Success!!
Dec 07, 2017 4:44:06 PM org.openqa.selenium.remote.ProtocolHandshake
createSession
INFO: Detected dialect: OSS
PASSED: begin
PASSED: google

===============================================
    Default test
    Tests run: 2, Failures: 0, Skips: 0
===============================================

===============================================
Default suite
Total tests run: 2, Failures: 0, Skips: 0
===============================================

But when running as Maven test, it doesn't print the name of passed test cases(or any test). It just gives number of tests run. I want the passed cases to be printed here as well.

P.S. - Class is in src/test/java. Tried changing it to  src/main/java as suggested in one of issue. but maven skipped the tests altogether in that way as Surefire-plugin runs all tests that are in test source directory src/test/java.

[INFO] Scanning for projects...
[INFO]

[INFO] ------------------------------------------------------------------------
[INFO] Building MavenFrstProj 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ MavenFrstProj ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory
C:\Users\Shrikanth\workspace\MavenFrstProj\src\main\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.7.0:compile (default-compile) @
MavenFrstProj ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources)
@ MavenFrstProj ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory
C:\Users\Shrikanth\workspace\MavenFrstProj\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.7.0:testCompile (default-testCompile) @
MavenFrstProj ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-surefire-plugin:2.20:test (default-test) @ MavenFrstProj --
-
[INFO]
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running TestSuite
Success!!
Dec 07, 2017 4:45:58 PM org.openqa.selenium.remote.ProtocolHandshake
createSession
INFO: Detected dialect: OSS
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 8.017
s - in TestSuite
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] ---------------------------------------------------------------------
---
[INFO] BUILD SUCCESS
[INFO] ---------------------------------------------------------------------
---
[INFO] Total time: 11.972 s
[INFO] Finished at: 2017-12-07T16:46:02+05:30
[INFO] Final Memory: 12M/178M
[INFO] ------------------------------------------------------------------------

Note : Also checking the xml report(TestSuite) generated in target/surefire-reports, it replaces class name as TestSuite and in console output it prints Running TestSuite instead of Running <classname>. May be thats the root, but not sure. How do I fix it. Please help!

Body:
By default, the Surefire Plugin will automatically include all test classes with the following wildcard patterns:

"**/Test*.java" - includes all of its subdirectories and all Java filenames that start with "Test".
"**/*Test.java" - includes all of its subdirectories and all Java filenames that end with "Test".
"**/*Tests.java" - includes all of its subdirectories and all Java filenames that end with "Tests".
"**/*TestCase.java" - includes all of its subdirectories and all Java filenames that end with "TestCase".

Make sure your test class names follow this pattern otherwise , add each class inclusively in pom.xml


问:
Dataframe for textfile Spark
I'm trying to create a data frame on a text file. For a sample input (Input1)
 below Code is working fine

Input1

```<code>1,5

2,6

3,7

4,8
</code>```

Output1

```<code>+---+----+
| id|name|
+---+----+
|  1|   5|
|  2|   6|
|  3|   7|
|  4|   8|
+---+----+
</code>```

However when I changed the input(Input2), I'm not getting any output.

Input2

```<code>1,"a,b,c"

2,"d,e,f"

3,"a,b,c"

4,"a,d,f"
</code>```

Output2

```<code>+---+----+
| id|name|
+---+----+
+---+----+
</code>```

Code

```<code>    {
        val input = sc.textFile(inputFile).map(x=>x.split(",")).collect {
                            case Array(id,name) => Record(id.toInt, name)
                    }
                    input.toDF().show()
    }
case class Record(id: Int, name: String)
</code>```

Expected output format for Input2

```<code>+---+-----+------+-----+
| id|name1| name2|name3|
+---+-----+------+-----+
|  1|    a|     b|    c|
|  2|    d|     e|    d|
|  3|    a|     b|    c|
|  4|    a|     d|    f|
+---+-----+------+-----+
</code>```

I should make changes to the code and case class as well so that compiler understands the data format for Input2, but I'm not getting what changes I need to do.  Please advice.

答:
Assuming you are using Spark2, you can simply do

```<code>val df = spark.read.csv(inputFile)
</code>```

And you can split apart the second column in following steps.

At the moment, you're trying to read an entire line containing more than one comma, and only matching on an Array of two elements

Title: Dataframe for textfile Spark

Body:
I'm trying to create a data frame on a text file. For a sample input (Input1)
 below Code is working fine

Input1

1,5

2,6

3,7

4,8

Output1

+---+----+
| id|name|
+---+----+
|  1|   5|
|  2|   6|
|  3|   7|
|  4|   8|
+---+----+

However when I changed the input(Input2), I'm not getting any output.

Input2

1,"a,b,c"

2,"d,e,f"

3,"a,b,c"

4,"a,d,f"

Output2

+---+----+
| id|name|
+---+----+
+---+----+

Code

    {
        val input = sc.textFile(inputFile).map(x=>x.split(",")).collect {
                            case Array(id,name) => Record(id.toInt, name)
                    }
                    input.toDF().show()
    }
case class Record(id: Int, name: String)

Expected output format for Input2

+---+-----+------+-----+
| id|name1| name2|name3|
+---+-----+------+-----+
|  1|    a|     b|    c|
|  2|    d|     e|    d|
|  3|    a|     b|    c|
|  4|    a|     d|    f|
+---+-----+------+-----+

I should make changes to the code and case class as well so that compiler understands the data format for Input2, but I'm not getting what changes I need to do.  Please advice.

Body:
Assuming you are using Spark2, you can simply do

val df = spark.read.csv(inputFile)

And you can split apart the second column in following steps.

At the moment, you're trying to read an entire line containing more than one comma, and only matching on an Array of two elements


问:
How to get final verdict out of all returns in Python in a loop?
Sorry, for a stupid question.
Let's say I want to compare elements of two lists using for loop. Now I wrote:-

```<code>for i in range(10):
     if a[i] == b[i]:
         print('True')
     else:
         print('False')
</code>```

where a and b are two list.

Now I will get 10 outputs which will be either true or false. What I want is, if all of them are true then only True is printed and if any of them is false then false is printed (True or False printed only once).

This is just an example, I want to use this method for some other question and that too using for loop.

Please help.

答:
If a and b contain "primitive" (strings, floats, integers, etc) you don't even need to have an element-wise comparison. a == b will do.

This will also work if a and b contain instances of an arbitrary class that implements __eq__.

Otherwise, this can be achieved by combining all, zip and a generator expression in a fairly readable single line:

```<code>print(all(a_elem == b_elem for a_elem, b_elem in zip(a, b)))
</code>```

Note that if the lists contain instances of an arbitrary class, that class should still implement __eq__.

all is short-circuited. It will stop as soon as it finds a pair a_elem, b_elem

where a_elem != b_elem and returns the boolean False.

If for some odd reason you would like the get the strings 'True' or 'False' you can convert the return value of all to a string:

```<code>print(str(all(a_elem == b_elem for a_elem, b_elem in zip(a, b))))
</code>```

Body:
Sorry, for a stupid question.
Let's say I want to compare elements of two lists using for loop. Now I wrote:-

for i in range(10):
     if a[i] == b[i]:
         print('True')
     else:
         print('False')

where a and b are two list.

Now I will get 10 outputs which will be either true or false. What I want is, if all of them are true then only True is printed and if any of them is false then false is printed (True or False printed only once).

This is just an example, I want to use this method for some other question and that too using for loop.

Please help.

Body:
If a and b contain "primitive" (strings, floats, integers, etc) you don't even need to have an element-wise comparison. a == b will do.

This will also work if a and b contain instances of an arbitrary class that implements __eq__.

Otherwise, this can be achieved by combining all, zip and a generator expression in a fairly readable single line:

print(all(a_elem == b_elem for a_elem, b_elem in zip(a, b)))

Note that if the lists contain instances of an arbitrary class, that class should still implement __eq__.

all is short-circuited. It will stop as soon as it finds a pair a_elem, b_elem

where a_elem != b_elem and returns the boolean False.

If for some odd reason you would like the get the strings 'True' or 'False' you can convert the return value of all to a string:

print(str(all(a_elem == b_elem for a_elem, b_elem in zip(a, b))))


问:
Convert Array of Dictionary to custom object swift
I have:

```<code>    let countries : [[String : Any]] = [
            [
                "name" : "Afghanistan",
                "dial_code": "+93",
                "code": "AF"
            ],
            [
                "name": "Aland Islands",
                "dial_code": "+358",
                "code": "AX"
            ],
            [
                "name": "Albania",
                "dial_code": "+355",
                "code": "AL"
            ],
            [
                "name": "Algeria",
                "dial_code": "+213",
                "code": "DZ"
            ]
]
</code>```

I want to add all this array of dictionary to my custom object like

```<code>let country:[Country] = countries
</code>```

My custom object looks like this:

```<code>class Country: NSObject {
        let name: String
        let dial_code : String
        let code: String

        init(name: String, dial_code: String, code: String) {
            self.name = name
            self.dial_code = dial_code
            self.code = code
        }
    }
</code>```

I understand that I need a loop thru the array but idk what is the next step. Would be great to have an example.

答:
you can use Array.foreach like this

```<code>countries.forEach{country.append(Country($0))}
</code>```

and u may change init parameters of Country to [String: Any],
or cast $0 to [String: Any] and read ur values from it and send them to init

Body:
I have:

    let countries : [[String : Any]] = [
            [
                "name" : "Afghanistan",
                "dial_code": "+93",
                "code": "AF"
            ],
            [
                "name": "Aland Islands",
                "dial_code": "+358",
                "code": "AX"
            ],
            [
                "name": "Albania",
                "dial_code": "+355",
                "code": "AL"
            ],
            [
                "name": "Algeria",
                "dial_code": "+213",
                "code": "DZ"
            ]
]

I want to add all this array of dictionary to my custom object like

let country:[Country] = countries

My custom object looks like this:

class Country: NSObject {
        let name: String
        let dial_code : String
        let code: String

        init(name: String, dial_code: String, code: String) {
            self.name = name
            self.dial_code = dial_code
            self.code = code
        }
    }

I understand that I need a loop thru the array but idk what is the next step. Would be great to have an example.

Body:
you can use Array.foreach like this

countries.forEach{country.append(Country($0))}

and u may change init parameters of Country to [String: Any],
or cast $0 to [String: Any] and read ur values from it and send them to init


问:
Which one to go first, Grails or Groovy?
I wanted to create a web application. I thought of selecting Groovy or Grails. But I don't know from where to start! To start with Groovy or Grails?</p>

答:
It may be that you're misunderstanding what exactly Groovy and Grails are.

Groovy is a dynamic language that uses Java's JVM (virtual machine). It can compile to Java bytecode and run anywhere that a typical Java program can run. It's only a language, not a framework for developing web applications. You could use Groovy by itself to build a web application, leveraging Servlets, JSPs, and other libraries to help you. However...

Grails is a framework that uses the Groovy language to help you build web applications. Grails gives you easy ways to create all of the web application components that you'd normally have to build yourself (using Servlets, JSPs, etc.).

This may help explain to you why Bozho suggested to go straight to Grails (and why I agree with him).


问:
What is the correct way to provide an API Key to a Google Cloud Endpoints 2 API for an app?
I have an API in Google Endpoints, and I've generated the API key needed by the Android App I'm working on to access the API. However I have no idea where to supply the API Key when using generated clients library. Every request made from the app returns a 403, Android app  is forbidden. I've read also in SO that it should be given in the header, but the closest that the Google Endpoints API docs mentioned is that an API key should be part of the URL, which however doesn't seem to be case if the request is from an Android client.

When the API key is removed from the API, any query, even curl, is able to retrieve the expected result. Any documentation on how this should be done with code examples will also be very much appreciated.

Edit: I am also wondering if Google itself has placed restrictions on using the android debug.keystore's SHA-1 in Endpoints.

Ps: my earlier question regarding this was unfairly down voted and the only answer received was about country restrictions, which I am sure has nothing to do with this. So maybe this time I'll rephrase my question in another way.

答:
I've managed to get at least one type of API key to work with a Google Cloud Endpoints API. Here's how:

1) The 'usable' API key was generated by not having any restrictions to it (ie: not Android App, Web, etc). You can select restrictions for a key when creating it in the API credentials page.

2) The 'usable' key was passed to the generated clients library through the service..setKey(...) method.

This somewhat produced what I was going for; allowing calls to the API only by callers that can identify themselves. The reason why it works (complete assumptions and guess work from this point onward) is that the generated client library makes a HTTPS request to the API, and therefore, the authorization checks should then be done by the API (Endpoints framework) in the context of a HTTPS request, rather than in the context of an Android App.

If this is true, than I am very much interested in finding out how does an Android App make a 'correct' call to an API with the generated client library.

Update: Screenshot and code of current setup

In Google Cloud Console -> API & Services -> Credentials

Usage of API Key in Java code:

```<code>// Call to the generated client library for the API
DataCollection dataCollection =  service.getDataAPIMethod()
                .setX(...)
                .setY(...)
                .setZ(...)
                .setKey("***")
                .execute();
</code>```

Body:
I've managed to get at least one type of API key to work with a Google Cloud Endpoints API. Here's how:

1) The 'usable' API key was generated by not having any restrictions to it (ie: not Android App, Web, etc). You can select restrictions for a key when creating it in the API credentials page.

2) The 'usable' key was passed to the generated clients library through the service..setKey(...) method.

This somewhat produced what I was going for; allowing calls to the API only by callers that can identify themselves. The reason why it works (complete assumptions and guess work from this point onward) is that the generated client library makes a HTTPS request to the API, and therefore, the authorization checks should then be done by the API (Endpoints framework) in the context of a HTTPS request, rather than in the context of an Android App.

If this is true, than I am very much interested in finding out how does an Android App make a 'correct' call to an API with the generated client library.

Update: Screenshot and code of current setup

In Google Cloud Console -> API & Services -> Credentials

Usage of API Key in Java code:

// Call to the generated client library for the API
DataCollection dataCollection =  service.getDataAPIMethod()
                .setX(...)
                .setY(...)
                .setZ(...)
                .setKey("***")
                .execute();


问:
Test whether audio tag has actually loaded an mp3
EDIT:  This has been flagged as a duplicate of How do you check if a HTML5 audio element is loaded?.

I don't think that this is a duplicate, of the above at least, because the above question regards the situation where you only want to do something after it's finished loading, and so you wait for the finished loading event. I'm talking about distinguishing between a thing that has finished loading valid data and another thing that has finished loading something invalid.

I'm simulating the blocking of mp3s on my local network, via a Squid proxy server, so that we can test for this automatically on behalf of our users, who often work in schools that have mp3-blocking firewalls (which disrupts our website).

To test whether mp3s are being blocked I have a bunch of audio tags which have a source pointing at the different domains I want to simulate being blocked, like so:

```<code>      <audio class="domain-test" controls>
        <source src="<%= url %>">
        Your browser does not support the audio element.
      </audio>
</code>```

The advantage of using an audio tag is that the src (like an img src) isn't subject to CORS restrictions, so I can try loading an mp3 from all the different domains that we use.

In the network inspector, I can see it trying to get the different urls (which are all mp3s), and I can see the response with a 403:Forbidden status, so I can see that my firewall is blocking them.  If I click on the play button on the audio tag, nothing happens.  So far so good: they're blocked.

But, how can I tell, in my javascript, whether it's failed?  I thought that I'd be able to test the readyState of the audio tag, like so (this is in javascript with jQuery):

```<code>audioTag = $("audio.domain-test");
if(audioTag[0].readyState == 0){
  blocked = true;
}
</code>```

But, the readyState is returning 4, which means "Enough data is available—and the download rate is high enough—that the media can be played through to the end without interruption." (see https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/readyState)

I think that it might be because when you try to load an mp3, the firewall shows you an html page saying "Sorry, this is blocked", and this html page is being loaded into the audio tag as its actual data, so it thinks that it's actually loaded ok.  But, the data isn't actually mpeg data, so nothing happens when you press play.

What's a better way, in jQuery or native JS, to test whether the audio tag source has actually loaded properly?

At the moment I'm rendering the audio tags out onto my page, and then running my js tests on pageload, but I could generate the audio tags within my javascript, if that makes things easier.

答:
HTMLMediaElements have an error property that should reflect the failure to parse the content:

The HTMLMediaElement.error is the MediaError object for the most recent error, or null if there has not been an error. When an error event is received by the element, you can determine details about what happened by examining this object.

If something has been loaded (determined by an event or the readyState property) and the error property is null, the content should therefore be valid.

Body:
EDIT:  This has been flagged as a duplicate of How do you check if a HTML5 audio element is loaded?.

I don't think that this is a duplicate, of the above at least, because the above question regards the situation where you only want to do something after it's finished loading, and so you wait for the finished loading event. I'm talking about distinguishing between a thing that has finished loading valid data and another thing that has finished loading something invalid.

I'm simulating the blocking of mp3s on my local network, via a Squid proxy server, so that we can test for this automatically on behalf of our users, who often work in schools that have mp3-blocking firewalls (which disrupts our website).

To test whether mp3s are being blocked I have a bunch of audio tags which have a source pointing at the different domains I want to simulate being blocked, like so:

      <audio class="domain-test" controls>
        <source src="<%= url %>">
        Your browser does not support the audio element.
      </audio>

The advantage of using an audio tag is that the src (like an img src) isn't subject to CORS restrictions, so I can try loading an mp3 from all the different domains that we use.

In the network inspector, I can see it trying to get the different urls (which are all mp3s), and I can see the response with a 403:Forbidden status, so I can see that my firewall is blocking them.  If I click on the play button on the audio tag, nothing happens.  So far so good: they're blocked.

But, how can I tell, in my javascript, whether it's failed?  I thought that I'd be able to test the readyState of the audio tag, like so (this is in javascript with jQuery):

audioTag = $("audio.domain-test");
if(audioTag[0].readyState == 0){
  blocked = true;
}

But, the readyState is returning 4, which means "Enough data is available—and the download rate is high enough—that the media can be played through to the end without interruption." (see https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/readyState)

I think that it might be because when you try to load an mp3, the firewall shows you an html page saying "Sorry, this is blocked", and this html page is being loaded into the audio tag as its actual data, so it thinks that it's actually loaded ok.  But, the data isn't actually mpeg data, so nothing happens when you press play.

What's a better way, in jQuery or native JS, to test whether the audio tag source has actually loaded properly?

At the moment I'm rendering the audio tags out onto my page, and then running my js tests on pageload, but I could generate the audio tags within my javascript, if that makes things easier.


问:
How to filter by year and week in MongoDB
I need to calculate a sum of some fields grouped by Week and year , for exemple
when dt_extract is : 02-01-2017 : so the number of the week is 1 and Year 2017 but the problem with my query i don't know exactly is 2017 or 2016  i juste control the week but i need to get the number of the week and also the year to calculate my Sum .

```<code>var group1 = {

$group :{

        _id:{
                "$isoWeek": "$dt_extract"},

        "Sum_Reliability_Rate_Numerator":{
        "$sum":"$mlf16_txfiabnum"
        }

}
}

var sort ={

$sort : { _id : -1 }

}
}

 db.mplf_tmp_v3.aggregate([group1,sort])
</code>```

This query it's work but i can't find for which year (in my collection i have 2016, 2017 and soon i will get 2018)

I did this request but i got no result

```<code>var match = {

$match : {

         "dt_extract": {"$in":
     [
         "2017-01-02",
         "2017-12-04"
         ]
     }

}

}

var group = {

$group :{
            "_id":{
                "$isoweek" :"$dt_extract" ,

        },

        "Sum_Reliability_Rate_Numerator":{
        "$sum":"$mlf16_txfiabnum"
        }
}
}

 db.supplierswarnings.aggregate([match,group])
</code>```

Here an exemple of the Document for this collection

```<code>{
    "_id" : ObjectId("5a2813a32539c8990f725a8f"),
    "dt_extract" : ISODate("2017-05-14T00:00:00.000+02:00"),
    "mlf16_annee" : "2017",
    "mlf16_semind" : "19",
    "mlf16_semcal" : "19",
    "mlf16_cptmag" : "0000900156",
    "mlf16_codraft" : "02",
    "mlf16_cptfou" : "0000115768",
    "mlf16_codadrdl" : "01",
    "mlf16_codadres" : "01",
    "mlf16_grpges" : "4P",
    "mlf16_clasges" : "2",
    "mlf16_txservnum" : 1,
    "mlf16_txservden" : 13,
    "mlf16_txdocnum" : 0,
    "mlf16_txdocden" : 1,
    "mlf16_txfiabnum" : 0,
    "mlf16_txfiabden" : 0,
    "mlf16_refret2j" : 1,
    "mlf16_refret7j" : 1,
    "mlf16_refret21j" : 0,
    "mlf16_natcouv" : "0",
    "mlf16_nbligndiff" : 0,
    "mlf16_nbrefdiff" : 0,
    "mlf16_cptfou_six" : "115768",
    "dt_year" : 2017
}
</code>```

答:
```<code> var match = {

    $match : {

    "dt_extract": {
    "$gte": new Date("2017-01-02"),
    "$lte": new Date("2017-12-04")
  }

}

}

var group = {

$group :{
        "_id":{
                weekNum : {"$isoWeek" :"$dt_extract"} ,
                year :{"$isoWeekYear": "$dt_extract"},
                dt_extract_date: "$dt_extract"
        },

        "Sum_Reliability_Rate_Numerator":{
        "$sum":"$mlf16_txfiabnum"
        }

}
}

var project = {

$project: {

    "Sum_Reliability_Rate_Numerator":1
}

}

var sort = {
    $sort :{_id : -1}
}

 db.mplf_tmp_v3.aggregate([match,group,project,sort])
</code>```

Body:
I need to calculate a sum of some fields grouped by Week and year , for exemple
when dt_extract is : 02-01-2017 : so the number of the week is 1 and Year 2017 but the problem with my query i don't know exactly is 2017 or 2016  i juste control the week but i need to get the number of the week and also the year to calculate my Sum .

var group1 = {

$group :{

        _id:{
                "$isoWeek": "$dt_extract"},

        "Sum_Reliability_Rate_Numerator":{
        "$sum":"$mlf16_txfiabnum"
        }

}
}

var sort ={

$sort : { _id : -1 }

}
}

 db.mplf_tmp_v3.aggregate([group1,sort])

This query it's work but i can't find for which year (in my collection i have 2016, 2017 and soon i will get 2018)

I did this request but i got no result

var match = {

$match : {

         "dt_extract": {"$in":
     [
         "2017-01-02",
         "2017-12-04"
         ]
     }

}

}

var group = {

$group :{
            "_id":{
                "$isoweek" :"$dt_extract" ,

        },

        "Sum_Reliability_Rate_Numerator":{
        "$sum":"$mlf16_txfiabnum"
        }
}
}

 db.supplierswarnings.aggregate([match,group])

Here an exemple of the Document for this collection

{
    "_id" : ObjectId("5a2813a32539c8990f725a8f"),
    "dt_extract" : ISODate("2017-05-14T00:00:00.000+02:00"),
    "mlf16_annee" : "2017",
    "mlf16_semind" : "19",
    "mlf16_semcal" : "19",
    "mlf16_cptmag" : "0000900156",
    "mlf16_codraft" : "02",
    "mlf16_cptfou" : "0000115768",
    "mlf16_codadrdl" : "01",
    "mlf16_codadres" : "01",
    "mlf16_grpges" : "4P",
    "mlf16_clasges" : "2",
    "mlf16_txservnum" : 1,
    "mlf16_txservden" : 13,
    "mlf16_txdocnum" : 0,
    "mlf16_txdocden" : 1,
    "mlf16_txfiabnum" : 0,
    "mlf16_txfiabden" : 0,
    "mlf16_refret2j" : 1,
    "mlf16_refret7j" : 1,
    "mlf16_refret21j" : 0,
    "mlf16_natcouv" : "0",
    "mlf16_nbligndiff" : 0,
    "mlf16_nbrefdiff" : 0,
    "mlf16_cptfou_six" : "115768",
    "dt_year" : 2017
}


问:
JAVA - Comparing a Double value with Float.MIN_VALUE or Integer.MIN_VALUE
I have the following issue.

I have some data stored in memory (coming from a database query) by using a hash table:

```<code>Map<String,MyObject>
</code>```

where MyObject consists of 3 arrays: float[], int[] and double[].
I use Float.MIN_VALUE, Integer.MIN_VALUE and Double.MIN_VALUE to store values having a NULL value in the database.

I need to process the input hash table and store the output in a hash table

```<code>Map<String, Double> output
</code>```

which must contain only NON NULL values.

So, I perform a comparison like this:

```<code>Double value = ... (get a value from MyObject)
if(value != Float.MIN_VALUE && value != Double.MIN_VALUE && value != Integer.MIN_VALUE){
    // add to OUTPUT hash table
</code>```

but the if statement doesn't work properly when value equals to Float.MIN_VALUE: the first component always returns TRUE (meaning the two values are different).

I also tried something like that

```<code>if(value != new Double(Float.MIN_VALUE))
</code>```

but the problem is still there.

Anyone could suggest me a solution to properly compare the values?

EDIT: Is it safe to use something like that:

```<code>String.valueOf(value).equals(String.valueOf(Float.MIN_VALUE))) ?
</code>```

It seems to work.

答:
This post ist 9 months old, but my response may help other users having to do with doubles and floats.
Fab I don't know how you get a float/double/int value from your Object, but as you kann check it here: If an Object gets the Float.MIN_VALUE assigned,  its value gotten again as float or as double will surely match Float.MIN_VALUE:

```<code>Object obj =  Float.MIN_VALUE; //1.40129846432481707E-45;
float floatVal = ((Number) obj).floatValue();

System.out.println("obj is a " + obj.getClass().getSimpleName()); // obj is a Float
boolean result  = floatVal == Float.MIN_VALUE;
System.out.printf("%.60f == %.60f: %s.\n" , floatVal, Float.MIN_VALUE, result ); // true
</code>```

Even if we assign the value gotten from the object to a variable declared as double, the match still holds true:

```<code>    double doubleVal = ((Number) obj).doubleValue();
    result  = doubleVal == Float.MIN_VALUE;
    System.out.printf("%.60f == %.60f: %s.\n" , doubleVal, Float.MIN_VALUE, result ); //true
</code>```

If we assign the value of Float.MIN_VALUE not explicitly as a Float:

```<code>obj =  Float.MIN_VALUE; //1.40129846432481707E-45;
</code>```

The macths till holds, even though the value of obj is interpreted as a Double:

```<code>floatVal = ((Number) obj).floatValue();
doubleVal = ((Number) obj).doubleValue();
Formatter fmt = new Formatter();

System.out.println("obj is a " + obj.getClass().getSimpleName()); // obj is a Double
result  = floatVal == Float.MIN_VALUE;
System.out.println(fmt.format("%18.17e", floatVal) + " == " + fmt.format("%18.17e", Float.MIN_VALUE) + "? " + result ); // true
result  = doubleVal == Float.MIN_VALUE;
System.out.println(fmt.format("%18.17e", doubleVal) + "= = " + fmt.format("%18.17e",Float.MIN_VALUE) + "? " + result ); // true
</code>```

I hope this will help someone!

Body:
I have the following issue.

I have some data stored in memory (coming from a database query) by using a hash table:

Map<String,MyObject>

where MyObject consists of 3 arrays: float[], int[] and double[].
I use Float.MIN_VALUE, Integer.MIN_VALUE and Double.MIN_VALUE to store values having a NULL value in the database.

I need to process the input hash table and store the output in a hash table

Map<String, Double> output

which must contain only NON NULL values.

So, I perform a comparison like this:

Double value = ... (get a value from MyObject)
if(value != Float.MIN_VALUE && value != Double.MIN_VALUE && value != Integer.MIN_VALUE){
    // add to OUTPUT hash table

but the if statement doesn't work properly when value equals to Float.MIN_VALUE: the first component always returns TRUE (meaning the two values are different).

I also tried something like that

if(value != new Double(Float.MIN_VALUE))

but the problem is still there.

Anyone could suggest me a solution to properly compare the values?

EDIT: Is it safe to use something like that:

String.valueOf(value).equals(String.valueOf(Float.MIN_VALUE))) ?

It seems to work.

Body:
This post ist 9 months old, but my response may help other users having to do with doubles and floats.
Fab I don't know how you get a float/double/int value from your Object, but as you kann check it here: If an Object gets the Float.MIN_VALUE assigned,  its value gotten again as float or as double will surely match Float.MIN_VALUE:

Object obj =  Float.MIN_VALUE; //1.40129846432481707E-45;
float floatVal = ((Number) obj).floatValue();

System.out.println("obj is a " + obj.getClass().getSimpleName()); // obj is a Float
boolean result  = floatVal == Float.MIN_VALUE;
System.out.printf("%.60f == %.60f: %s.\n" , floatVal, Float.MIN_VALUE, result ); // true

Even if we assign the value gotten from the object to a variable declared as double, the match still holds true:

    double doubleVal = ((Number) obj).doubleValue();
    result  = doubleVal == Float.MIN_VALUE;
    System.out.printf("%.60f == %.60f: %s.\n" , doubleVal, Float.MIN_VALUE, result ); //true

If we assign the value of Float.MIN_VALUE not explicitly as a Float:

obj =  Float.MIN_VALUE; //1.40129846432481707E-45;

The macths till holds, even though the value of obj is interpreted as a Double:

floatVal = ((Number) obj).floatValue();
doubleVal = ((Number) obj).doubleValue();
Formatter fmt = new Formatter();

System.out.println("obj is a " + obj.getClass().getSimpleName()); // obj is a Double
result  = floatVal == Float.MIN_VALUE;
System.out.println(fmt.format("%18.17e", floatVal) + " == " + fmt.format("%18.17e", Float.MIN_VALUE) + "? " + result ); // true
result  = doubleVal == Float.MIN_VALUE;
System.out.println(fmt.format("%18.17e", doubleVal) + "= = " + fmt.format("%18.17e",Float.MIN_VALUE) + "? " + result ); // true

I hope this will help someone!


问:
Spark: Issue while using event-time sliding window in streaming query
I am doing the real-time data streaming in Spark 2.2. As per my problem statement, I want to query the data within sliding window of 120 sec. duration. I am triggering the streamingquery after every 1 sec. Hence ideally, the query should run only one previous 120 sec. data(updated/fresh data).

But when I am running the query, it is running on entire data which has come before 120 sec. (old) data. This means that the window is sliding over the data which is already processed.

What may be the reason behind this? and how can I apply the window only on fresh data(unprocessed)?

答:
With spark 2.2 and structured streaming you can specify a watermark on the event-time column you're performing your aggregations, the Scala code should look something like this, for a 120-second sliding-window that slides every second:

```<code>query
 .withWatermark("event-time-column", "120 second")
 .groupBy("event-time-column", "120 second", "1 second")
</code>```

Thus, all the data and aggregation state from data older than 120 seconds is going to be dropped and only fresh data is processed

Full documentation here:
https://spark.apache.org/docs/latest/structured-streaming-programming-guide.html

ContentLicense: CC BY-SA 4.0

Body:
With spark 2.2 and structured streaming you can specify a watermark on the event-time column you're performing your aggregations, the Scala code should look something like this, for a 120-second sliding-window that slides every second:

query
 .withWatermark("event-time-column", "120 second")
 .groupBy("event-time-column", "120 second", "1 second")

Thus, all the data and aggregation state from data older than 120 seconds is going to be dropped and only fresh data is processed

Full documentation here:
https://spark.apache.org/docs/latest/structured-streaming-programming-guide.html


问:
How To Open Chrome Browser window with a specific URL with JavaScript?
How To Open Chrome Browser window with a specific URL with JavaScript in Internet Explorer 8?

Any Suggestions or Ideas?

答:
Try this:

```<code>var openUrl = window.open('url');
</code>```

It will use the default browser to open the specified url.

Body:
Try this:

var openUrl = window.open('url');

It will use the default browser to open the specified url.


问:
Return the Worksheet that an Excel Chart is referencing using VBA
I need to be able to identify the worksheet that an excel chart (on a worksheet) is getting it's data from. I only need the data sheet which series 1 is referencing. I've started trying to extract the sheet name from .SeriesCollection(1).Formula but it gets realy complex. here's what I've got so far:

```<code>Sub GetChartDataSheet()

Dim DataSheetName As String
Dim DataSheet As Worksheet

DataSheetName = ActiveChart.SeriesCollection(1).Formula

DataSheetName = Left(DataSheetName, InStr(1, DataSheetName, "!$") - 1)
DataSheetName = WorksheetFunction.Replace(DataSheetName, 1, Len("=series("), "")
If Left(DataSheetName, 1) = "'" And Right(DataSheetName, 1) = "'" Then DataSheetName = Mid(DataSheetName, 2, Len(DataSheetName) - 2)
DataSheetName = Replace(DataSheetName, "''", "'")

Set DataSheet = Sheets(DataSheetName)

End Sub
</code>```

this works in a lot of cases, but if my users have a strange worksheet name (eg Sh'e e$,,t!3!$) it fails. the same goes if series 1 has been named (eg .SeriesCollection(1).Formula = "=SERIES(**"Hell,o !"**,'Sh''e e$,,t!3!$'!$B$2:$B$18,'Sh''e e$,,t!3!$'!$C$2:$C$18,1)".

Is there a simple way to solve this?

答:
You can use the Find function to look for the values of SeriesCollection(1).

In the worksheet that hold the data of SeriesCollection(1), you will be able to find all the values in that array.

More explanations inside the code below.

Code

```<code>Option Explicit

Sub GetChartDataSheet()

Dim DataSheetName As String
Dim DataSheet As Worksheet
Dim ws As Worksheet
Dim ValuesArr As Variant, Val As Variant
Dim FindRng As Range
Dim ShtMatch As Boolean

Dim ChtObj As ChartObject
Dim Ser As Series

' if you want to use ActiveChart
Set ChtObj = ActiveChart.Parent

Set Ser = ChtObj.Chart.SeriesCollection(1)
ValuesArr = Ser.Values ' get the values of the Series Collection inside an array

' use Find to get the Sheet's origin
For Each ws In ThisWorkbook.Sheets
    With ws
        ShtMatch = True
        For Each Val In ValuesArr ' loop through all values in array
            Set FindRng = .Cells.Find(what:=Val) ' you need to find each value in the worksheet that SeriesCollection data is tied to
            If FindRng Is Nothing Then
                ShtMatch = False
                Exit For
            End If
            Set FindRng = Nothing ' reset
        Next Val

        If ShtMatch = True Then
            Set DataSheet = ws
            Exit For
        End If
    End With
Next ws
DataSheetName = DataSheet.Name

End Sub
</code>```

Body:
I need to be able to identify the worksheet that an excel chart (on a worksheet) is getting it's data from. I only need the data sheet which series 1 is referencing. I've started trying to extract the sheet name from .SeriesCollection(1).Formula but it gets realy complex. here's what I've got so far:

Sub GetChartDataSheet()

Dim DataSheetName As String
Dim DataSheet As Worksheet

DataSheetName = ActiveChart.SeriesCollection(1).Formula

DataSheetName = Left(DataSheetName, InStr(1, DataSheetName, "!$") - 1)
DataSheetName = WorksheetFunction.Replace(DataSheetName, 1, Len("=series("), "")
If Left(DataSheetName, 1) = "'" And Right(DataSheetName, 1) = "'" Then DataSheetName = Mid(DataSheetName, 2, Len(DataSheetName) - 2)
DataSheetName = Replace(DataSheetName, "''", "'")

Set DataSheet = Sheets(DataSheetName)

End Sub

this works in a lot of cases, but if my users have a strange worksheet name (eg Sh'e e$,,t!3!$) it fails. the same goes if series 1 has been named (eg .SeriesCollection(1).Formula = "=SERIES(**"Hell,o !"**,'Sh''e e$,,t!3!$'!$B$2:$B$18,'Sh''e e$,,t!3!$'!$C$2:$C$18,1)".

Is there a simple way to solve this?

Body:
You can use the Find function to look for the values of SeriesCollection(1).

In the worksheet that hold the data of SeriesCollection(1), you will be able to find all the values in that array.

More explanations inside the code below.

Code

Option Explicit

Sub GetChartDataSheet()

Dim DataSheetName As String
Dim DataSheet As Worksheet
Dim ws As Worksheet
Dim ValuesArr As Variant, Val As Variant
Dim FindRng As Range
Dim ShtMatch As Boolean

Dim ChtObj As ChartObject
Dim Ser As Series

' if you want to use ActiveChart
Set ChtObj = ActiveChart.Parent

Set Ser = ChtObj.Chart.SeriesCollection(1)
ValuesArr = Ser.Values ' get the values of the Series Collection inside an array

' use Find to get the Sheet's origin
For Each ws In ThisWorkbook.Sheets
    With ws
        ShtMatch = True
        For Each Val In ValuesArr ' loop through all values in array
            Set FindRng = .Cells.Find(what:=Val) ' you need to find each value in the worksheet that SeriesCollection data is tied to
            If FindRng Is Nothing Then
                ShtMatch = False
                Exit For
            End If
            Set FindRng = Nothing ' reset
        Next Val

        If ShtMatch = True Then
            Set DataSheet = ws
            Exit For
        End If
    End With
Next ws
DataSheetName = DataSheet.Name

End Sub


问:
Defining controller in namespace still Class App\Http\Controllers error taking place in laravel 5.5
I am working in laravel 5.5. I have created a controller folder with name Abc and inside it created a controller file with name abc.php, inside this file I have written code:

```<code>namespace App\Http\Controllers\Abc;

use App\Http\Controllers\Controller;

//use Illuminate\Support\Facades\DB;

class abcController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function NewPromotion()
    {
        return view('new-promotion');
    }
}
</code>```

And in Route folder under web.php file I am calling its view file, like:-
Route::get('/new-promotion','Abc\abcController@NewPromotion');

In spite of defining in namespace I am still getting error i.e.

"ReflectionException (-1)
  Class App\Http\Controllers\Abc\abcController does not exist".

What could be the possible issue?

答:
Good way to create controller is use cmd (you have to be in project directory)</p>

```<code>php artisan make:controller "Abc\abcController"
</code>```

Body:
I am working in laravel 5.5. I have created a controller folder with name Abc and inside it created a controller file with name abc.php, inside this file I have written code:

namespace App\Http\Controllers\Abc;

use App\Http\Controllers\Controller;

//use Illuminate\Support\Facades\DB;

class abcController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function NewPromotion()
    {
        return view('new-promotion');
    }
}

And in Route folder under web.php file I am calling its view file, like:-
Route::get('/new-promotion','Abc\abcController@NewPromotion');

In spite of defining in namespace I am still getting error i.e.

"ReflectionException (-1)
  Class App\Http\Controllers\Abc\abcController does not exist".

What could be the possible issue?

Body:
Good way to create controller is use cmd (you have to be in project directory)

php artisan make:controller "Abc\abcController"


问:
It sould be so obvious, but why does this fail?
Been coding .net for years now yet I feel like a n00b. Why is the following code failing?

```<code>byte[] a = Guid.NewGuid().ToByteArray(); // 16 bytes in array
string b = new UTF8Encoding().GetString(a);
byte[] c = new UTF8Encoding().GetBytes(b);
Guid d = new Guid(c);    // Throws exception (32 bytes recived from c)
</code>```

Update

Approved the answer from CodeInChaos. Reason for the 16 bytes becomming 32 bytes can be read in his answer. Also stated in the answer:

the default constructor of
  UTF8Encoding has error checking
  disabled

IMHO the UTF8 encoder should throw exception when trying to encode a byte array to string that contains invalid bytes. To make the .net framework behave properly the code should have been written as follows

```<code> byte[] a = Guid.NewGuid().ToByteArray();
 string b = new UTF8Encoding(false, true).GetString(a);  // Throws exception as expected
 byte[] c = new UTF8Encoding(false, true).GetBytes(b);
 Guid d = new Guid(c);
</code>```

答:
To encode arbitrary byte data as a string you should use base-64, hex, etc. You cannot assume that random set of bytes makes a valid UTF* (or other encoding) string.

http://marcgravell.blogspot.com/2010/03/binary-data-and-strings.html

Body:
Been coding .net for years now yet I feel like a n00b. Why is the following code failing?

byte[] a = Guid.NewGuid().ToByteArray(); // 16 bytes in array
string b = new UTF8Encoding().GetString(a);
byte[] c = new UTF8Encoding().GetBytes(b);
Guid d = new Guid(c);    // Throws exception (32 bytes recived from c)

Update

Approved the answer from CodeInChaos. Reason for the 16 bytes becomming 32 bytes can be read in his answer. Also stated in the answer:

the default constructor of
  UTF8Encoding has error checking
  disabled

IMHO the UTF8 encoder should throw exception when trying to encode a byte array to string that contains invalid bytes. To make the .net framework behave properly the code should have been written as follows

 byte[] a = Guid.NewGuid().ToByteArray();
 string b = new UTF8Encoding(false, true).GetString(a);  // Throws exception as expected
 byte[] c = new UTF8Encoding(false, true).GetBytes(b);
 Guid d = new Guid(c);


问:
Resource not found error in MVC when posting using beginform
The below code is not working properly as expected.

The controller have an action method

```<code>[HttpPost]
        public ActionResult LoginResult()
        {
            string name = Request.Form["name"];
            return View("Dashboard");
        }
     public ActionResult Dashboard()
    {
        string strName = Request["username"].ToString();
        return View();
    }
</code>```

and in view i have a form

```<code> @using (Html.BeginForm("LoginResult", "Dashboard", FormMethod.Post))
    {
     @Html.EditorFor(model =>model.username)
    <button type="button" id="ajax_method">submit Via AJAX</button>

    }
</code>```

and im submitting this using a function

```<code><script>
    $(function () {
        $('#ajax_method').click(function (e) {
            e.preventDefault();
            $.ajax({
                type: "POST",
                url: "Dashboard/LoginResult",                             //Your Action name in the DropDownListConstroller.cs
                data: "{'AJAXParameter1':'" + $('#username').val() + "'}",  //Parameter in this function, Is case sensitive and also type must be string
                contentType: "application/json; charset=utf-8",
                dataType: "json"

            }).done(function (data) {
                //Successfully pass to server and get response
                if (data.result = "OK") {
                    alert("submit successfully.");
                }
            }).fail(function (response) {
                if (response.status != 0) {
                    alert(response.status + " " + response.statusText);
                }
            });
        });

    });
</script>
</code>```

but im getting 404 error  while clicking the button.

Even I tried adding that routerspecifications in route config.

```<code>   routes.MapRoute(
            name: "login",
           url: "{controller}/{action}/{id}",
           defaults: new { controller = "Dashboard", action = "LoginResult", id = UrlParameter.Optional }
        );
</code>```

and modified the cshtml again. But this is also not working.

```<code> @using (Html.BeginForm("login", "Dashboard", FormMethod.Post))
    {
     @Html.EditorFor(model =>model.username)
    <button type="button" id="ajax_method">submit Via AJAX</button>

    }
</code>```

It may be a silly error but it spoil my day. Can anyone extend a hand to solve this issue.

答:
In my case, deleting default routing caused me issue.

```<code> routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { action = "Index", id = UrlParameter.Optional }
            );
</code>```

adding this resolved the issue for me. as mine is hybrid project of webforms and mvc. i didn't notice it.

Body:
The below code is not working properly as expected.

The controller have an action method

[HttpPost]
        public ActionResult LoginResult()
        {
            string name = Request.Form["name"];
            return View("Dashboard");
        }
     public ActionResult Dashboard()
    {
        string strName = Request["username"].ToString();
        return View();
    }

and in view i have a form

 @using (Html.BeginForm("LoginResult", "Dashboard", FormMethod.Post))
    {
     @Html.EditorFor(model =>model.username)
    <button type="button" id="ajax_method">submit Via AJAX</button>

    }

and im submitting this using a function

but im getting 404 error  while clicking the button.

Even I tried adding that routerspecifications in route config.

   routes.MapRoute(
            name: "login",
           url: "{controller}/{action}/{id}",
           defaults: new { controller = "Dashboard", action = "LoginResult", id = UrlParameter.Optional }
        );

and modified the cshtml again. But this is also not working.

 @using (Html.BeginForm("login", "Dashboard", FormMethod.Post))
    {
     @Html.EditorFor(model =>model.username)
    <button type="button" id="ajax_method">submit Via AJAX</button>

    }

It may be a silly error but it spoil my day. Can anyone extend a hand to solve this issue.

Body:
In my case, deleting default routing caused me issue.

 routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { action = "Index", id = UrlParameter.Optional }
            );

adding this resolved the issue for me. as mine is hybrid project of webforms and mvc. i didn't notice it.


问:
Liferay LDAP authentication ignoring password
I've configured an LDAP authentication on my Liferay Portal 6.2 CE.

The problem I figured out is that when users login, my portal ignore completely the password check.

This is the current user mapping:

```<code>UUID:
Username: sAMAccountName
Email: userPrincipalName
Password: unicodePwd
Name: givenName
Second name: middleName
Surname: sn
Fullname: cn
Gruppo: memberOf
</code>```

Moreover, the portal is configured to ignore Liferay internal password authentication, delegating to LDAP:

```<code>auth.pipeline.enable.liferay.check=false
</code>```

答: It was mandatory to specify forcing ldap authentication flag as true. This configuration solved the problem.</p>

Body:
I've configured an LDAP authentication on my Liferay Portal 6.2 CE.

The problem I figured out is that when users login, my portal ignore completely the password check.

This is the current user mapping:

UUID:
Username: sAMAccountName
Email: userPrincipalName
Password: unicodePwd
Name: givenName
Second name: middleName
Surname: sn
Fullname: cn
Gruppo: memberOf

Moreover, the portal is configured to ignore Liferay internal password authentication, delegating to LDAP:

auth.pipeline.enable.liferay.check=false