问:
Datagrid vs Gridview

Possible Duplicate:

  The Difference Between a DataGrid and a GridView in ASP.NET?

What is main difference between Data grid and Grid View in asp.net?

答:
DataGrid has been around since .NET 1.1 while GridView was introduced in .NET 2.0. So basically GridView is the successor of DataGrid. Here's a nice article on MSDN comparing both.

Both the DataGrid and GridView controls are derived from the
  WebControl class. Although it has a similar object model to that of
  the DataGrid control, the GridView control also has a number of new
  features and advantages over the DataGrid control, which include:
  Richer design-time capabilities. Improved data source binding
  capabilities. Automatic handling of sorting, paging, updates, and
  deletes. Additional column types and design-time column operations. A
  Customized pager user interface (UI) with the PagerTemplate property.
  Differences between the GridView control and the DataGrid control
  include: Different custom-paging support. Different event models.

Title: Datagrid vs Gridview


来源: stackexchange

问:
Is there any legal syntax that would allow for a quotation mark to appear right next to an identifier character in javascript? (like"so")
I'm trying to embed a .js file into a c++ project without using any of the compiler/platform specific resource tools while the .js file is still 100% valid javascript (as in you could plug it straight into a html document and it would run).

Currently I'm trying to figure out how to hide the raw string literal from js but no luck so far.

in loader.h I have:

```<code>#define var const char*
#include "test.js"
</code>```

and in test.js

```<code>var my_js_source = R"###(";

for (var i = 0; i < 100; i++) {
    console.log(i, i);
}

alert("hey");

//)###";
</code>```

It is the literal that is tripping me up, R"( in its most minimal form. Since I've found no way to hide it from js, I'm wondering if there is any syntax in js that would allow for R" to appear without being inside a string or a comment?

Doesn't matter if it can't execute as the first command as long as the syntax is valid since I can wrap it in a try block pretty easily.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to embed a .js file into a c++ project without using any of the compiler/platform specific resource tools while the .js file is still 100% valid javascript (as in you could plug it straight into a html document and it would run).

Currently I'm trying to figure out how to hide the raw string literal from js but no luck so far.

in loader.h I have:

#define var const char*
#include "test.js"

and in test.js

var my_js_source = R"###(";

for (var i = 0; i < 100; i++) {
    console.log(i, i);
}

alert("hey");

//)###";

It is the literal that is tripping me up, R"( in its most minimal form. Since I've found no way to hide it from js, I'm wondering if there is any syntax in js that would allow for R" to appear without being inside a string or a comment?

Doesn't matter if it can't execute as the first command as long as the syntax is valid since I can wrap it in a try block pretty easily.

Body:
I finally figured it out.

I managed to hide the raw string literal after all by using html style single line comment <!--, which, given some context is a valid sequence of operators in c++.

On the c++ side I have js_loader.h:

#pragma once
#define var bool
int js_loader_dummy_int = 1024;

// include js files here
#include "test.js"

#undef var

On the js side, each of the js files must contain special first and last lines. test.js:

var js_loader_dummy_bool_2935623962 = 1<!--js_loader_dummy_int; const char* test_js = R"###(

for (var i = 0; i < 100; i++) {
    console.log(i);
}
alert("hey");

//)###";

Both the names of the 2 variables declared on the first line must be unique.

The first line as interpreted by C++ creates a dummy boolean value and assigns the result of 1<!--js_loader_dummy_int to it. Then creates a const char* and uses the raw string literal to capture the entire rest of the .js file.

When interpreted by js, it creates a dummy variable and assigns the value of 1 to it, then reaches the comment delimiter and ignores the rest.

The last line is commented out as far as js is concerned, for C++ it contains the end delimiter for the string literal.

So far I've tested this in MSVC, latest chrome and firefox without any problems.

Its not perfect though, some concerns:

As seen by js, the first statement doesn't end with a semicolon. Not sure what js specification has to say about it but the browsers don't seem to mind

Using a html style comment inside js. This has always worked AFAIK but again, not sure how well it goes with the js specification.


问:
jq error syntax error, unexpected '=', expecting '}' (Unix shell quoting issues?) at <top-level>
```<code>cat test.json | jq 'map(if ParameterKey == "Project"           then . + {"ParameterValue" = "jess-project"}             else .             end           )'

jq: error: syntax error, unexpected '=', expecting '}' (Unix shell quoting issues?) at <top-level>, line 1:
map(if ParameterKey == "Project"           then . + {"ParameterValue" = "jess-project"}             else .             end           )
jq: 1 compile error
</code>```

答:
Object construction in jq uses syntax similar to JavaScript Object Notation (JSON).

{"ParameterValue" = "jess-project"} is not valid in JSON. Did you mean {"ParameterValue": "jess-project"}?


问:
Not able to insert data into oracle Table
I have created one table called as Booking.

Structure of Booking is

I am inserting the data using below syntax :-

```<code>INSERT INTO Booking (
(id,price,date1,c_id)
values(1,1235.01,'2016-10-11', 1));
</code>```

but I am getting ORA-00928: missing SELECT keyword error.
I am using Oracle apex application.

what is the problem with this query?

答:
```<code>INSERT INTO Booking(id,price,date1,c_id) values(1,1235.01,'2016-10-11', 1);

INSERT INTO Booking (id,price,date1,c_id)values(1,1235.01,to_date('2016-10-11','yyyy-mm-dd'), 1)
;
</code>```

Both of these are correct answers.

I would definitely recommend you use references as they would help you in further understanding and writing better and complex queries in the future.

I usually follow W3Schools for that purpose.

I am attaching a link here so that you can access that particular web page for more info.

Body:
I have created one table called as Booking.

Structure of Booking is

I am inserting the data using below syntax :-

INSERT INTO Booking (
(id,price,date1,c_id)
values(1,1235.01,'2016-10-11', 1));

but I am getting ORA-00928: missing SELECT keyword error.
I am using Oracle apex application.

what is the problem with this query?

Body:
INSERT INTO Booking(id,price,date1,c_id) values(1,1235.01,'2016-10-11', 1);

INSERT INTO Booking (id,price,date1,c_id)values(1,1235.01,to_date('2016-10-11','yyyy-mm-dd'), 1)
;

Both of these are correct answers.

I would definitely recommend you use references as they would help you in further understanding and writing better and complex queries in the future.

I usually follow W3Schools for that purpose.

I am attaching a link here so that you can access that particular web page for more info.


问:
Paste MS Excel data to SQL Server
I have a bunch of rows in Excel that I want to paste into a new table in MS SQL. Is there a simple way ?</p>

答:
Excel

In Excel, highlight and copy the data you want to paste into SQL.

SQL

Create the table with the desired column names and give you table a name.
*Make sure Identity Specification is Yes, so it will auto increment your
Identity column.

Find your table, and right click on it and choose Edit Top 200 Rows from the dialog-box.

Right click on the empty row with the * sign and select paste from the dialog-box

OwnerDisplayName: Bajji

ContentLicense: CC BY-SA 2.5

Title: Paste MS Excel data to SQL Server


问:
Automatic refresh of excel where connection is password protected
I am trying to perform the following steps either by Python 2.7 or AutoIt scripts. Preferable is Python though.

Open excel file.

Press 'refresh all'

Enter userid and password in a dialog box.

Save excel after refresh

Quit excel

I am stuck automating the 3rd steps when the excel file in question asks for credentials for executing a web query. The files do not allow to save credentials as well so for every refresh it asks for credentials. Can someone please help on automating of this part.

答:
One way you could do this is by using a python module called pyautogui.
http://pyautogui.readthedocs.io/en/latest/

pyautogui is a module that allows you to move the mouse to a coordinate on the screen and also do keyboard functions. You could have it [every once in a while] open up the excel file, move the mouse and click the button, then enter the username and password and so on. Go ahead and check out the link.


问:
Qt Qml connect to a signal of a QObject property of a Context Property
So this may seem like a strange setup. I have a C++ object that inherits from QObject called "MasterGuiLogic" for simplicity. It is created with a pointer to another object called "MainEventBroker" which as you might guess handles all of my applications events. The MasterGuiLogic object is registered with qml as a context property so that it's properties can be used anywhere in my qml. So main.cpp looks like this:

```<code>int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QGuiApplication app(argc, argv);

    MasterEventBroker *MainEventBroker = new MasterEventBroker();
    MasterGuiLogic *MainGuiLogic = new MasterGuiLogic(*MainEventBroker);

    qmlRegisterUncreatableType<MasterGuiLogic>("GrblCom", 1, 0, "MasterGuiLogic", "");
    qmlRegisterUncreatableType<GuiLogic_SerialCom>("GrblCom", 1, 0, "GuiLogic_SerialCom", "");

    QQmlApplicationEngine engine;
    QQmlContext* context = engine.rootContext();

    context->setContextProperty("MasterGuiLogic", &(*MainGuiLogic));

    engine.load(QUrl(QLatin1String("qrc:/QmlGui/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

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

MasterGuiLogic creates an instance of another class called SerialCom, which is set as a Q_PROPERTY so that it's properties and public slots can be reached in qml through the MasterGuiLogic property.

MasterGuiLogic.h:

```<code>class MasterGuiLogic : public QObject
{
    Q_OBJECT
    Q_PROPERTY(GuiLogic_SerialCom* serialCom READ serialCom CONSTANT)
public:
    MasterEventBroker *eventBroker;

    explicit MasterGuiLogic(MasterEventBroker &ev, QObject *parent = nullptr);

    GuiLogic_SerialCom* serialCom() const {
        return Gui_SerialCom;
    }

private:

    GuiLogic_SerialCom *Gui_SerialCom;
</code>```

MasterGuiLogic.cpp:

```<code>MasterGuiLogic::MasterGuiLogic(MasterEventBroker &ev, QObject *parent) : QObject(parent)
{
    this->eventBroker = &ev;
    this->Gui_SerialCom = new GuiLogic_SerialCom(this);
}
</code>```

SerialCom.h:

```<code>//Forward Declare our parent
class MasterGuiLogic;

class GuiLogic_SerialCom : public QObject
{
    Q_OBJECT
    Q_PROPERTY(QStringList portNames READ portNames NOTIFY portNamesChanged)
    Q_PROPERTY(bool connectedToPort READ connectedToPort NOTIFY connectedToPortChanged)
public:

    MasterGuiLogic *parent;
    explicit GuiLogic_SerialCom(MasterGuiLogic *parent = nullptr);

    std::map<QString, QSerialPortInfo> portsMap;

    QStringList portNames() {
        return _portNames;
    }

    bool connectedToPort() {
        return _connectedToPort;
    }

private:

    QStringList _portNames;
    bool _connectedToPort = false;

signals:

    void portNamesChanged(const QStringList &);
    void connectedToPortChanged(const bool &);

public slots:

    void connectToPort(const QString portName);
    void disconnectFromPort(const QString portName);

};
</code>```

SerialCom.cpp:

```<code>GuiLogic_SerialCom::GuiLogic_SerialCom(MasterGuiLogic *parent) : QObject(qobject_cast<QObject *>(parent))
{
    this->parent = parent;

    QList<QSerialPortInfo> allPorts = QSerialPortInfo::availablePorts();

    for (int i = 0; i < allPorts.size(); ++i) {
        this->_portNames.append(allPorts.at(i).portName());
        this->portsMap[allPorts.at(i).portName()] = allPorts.at(i);
    }

    emit portNamesChanged(_portNames);

}

void GuiLogic_SerialCom::connectToPort(const QString portName) {
    //TODO: Connect To Port Logic Here;

    //Set Connected
    this->_connectedToPort = true;
    emit connectedToPortChanged(this->_connectedToPort);

    qDebug() << portName;
}

void GuiLogic_SerialCom::disconnectFromPort(const QString portName) {
    //TODO: DisConnect To Port Logic Here;

    //Set DisConnected
    this->_connectedToPort = false;
    emit connectedToPortChanged(this->_connectedToPort);

    qDebug() << portName;
}
</code>```

So from qml it's pretty easy to read any of these properties and even send signals from qml to c++

For example, this works just fine:

```<code>connectCom.onClicked: {
        if (MasterGuiLogic.serialCom.connectedToPort === false) {
            MasterGuiLogic.serialCom.connectToPort(comPort.currentText);
        } else {
            MasterGuiLogic.serialCom.disconnectFromPort(comPort.currentText);
        }
    }
</code>```

The problem is, I can't seem to find a way to connect to signals that are emitted from SerialCom. I thought I would be able to do something like this:

```<code>Connections: {
        target: MasterGuiLogic.serialCom;
        onConnectedToPortChanged: {
            if (MasterGuiLogic.serialCom.connectedToPort === false) {
                connectCom.text = "Disconnect";
                comPort.enabled = false;
            } else {
                connectCom.text = "Connect";
                comPort.enabled = true;
            }
        }
    }
</code>```

This should listen to the boolean property on SerialCom to change, but I get the following error:

```<code>QQmlApplicationEngine failed to load component
qrc:/QmlGui/main.qml:21 Type Page1 unavailable
qrc:/QmlGui/Page1.qml:49 Invalid attached object assignment
</code>```

This just means that I can't "connect" using the target line above. Is there any other way I can connect to signals from a Q_PROPERTY of type QObject inside a ContextProperty?

答:
Ok, I found the problem... The provided answers, while indeed helpful for other reasons, were not the correct solution. After going over the code by @Xplatforms, I couldn't figure out what the difference was between what I was doing and what he did.... until I saw this in my own code:

```<code>Connections: {
        target: MasterGuiLogic.serialCom;
        onConnectedToPortChanged: {
            ...
        }
    }
</code>```

There isn't supposed to be a colon(:) there...

```<code>Connections {
        target: MasterGuiLogic.serialCom;
        onConnectedToPortChanged: {
            ...
        }
    }
</code>```

Never try programming while sleepy...lol

Body:
So this may seem like a strange setup. I have a C++ object that inherits from QObject called "MasterGuiLogic" for simplicity. It is created with a pointer to another object called "MainEventBroker" which as you might guess handles all of my applications events. The MasterGuiLogic object is registered with qml as a context property so that it's properties can be used anywhere in my qml. So main.cpp looks like this:

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QGuiApplication app(argc, argv);

    MasterEventBroker *MainEventBroker = new MasterEventBroker();
    MasterGuiLogic *MainGuiLogic = new MasterGuiLogic(*MainEventBroker);

    qmlRegisterUncreatableType<MasterGuiLogic>("GrblCom", 1, 0, "MasterGuiLogic", "");
    qmlRegisterUncreatableType<GuiLogic_SerialCom>("GrblCom", 1, 0, "GuiLogic_SerialCom", "");

    QQmlApplicationEngine engine;
    QQmlContext* context = engine.rootContext();

    context->setContextProperty("MasterGuiLogic", &(*MainGuiLogic));

    engine.load(QUrl(QLatin1String("qrc:/QmlGui/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    return app.exec();
}

MasterGuiLogic creates an instance of another class called SerialCom, which is set as a Q_PROPERTY so that it's properties and public slots can be reached in qml through the MasterGuiLogic property.

MasterGuiLogic.h:

class MasterGuiLogic : public QObject
{
    Q_OBJECT
    Q_PROPERTY(GuiLogic_SerialCom* serialCom READ serialCom CONSTANT)
public:
    MasterEventBroker *eventBroker;

    explicit MasterGuiLogic(MasterEventBroker &ev, QObject *parent = nullptr);

    GuiLogic_SerialCom* serialCom() const {
        return Gui_SerialCom;
    }

private:

    GuiLogic_SerialCom *Gui_SerialCom;

MasterGuiLogic.cpp:

MasterGuiLogic::MasterGuiLogic(MasterEventBroker &ev, QObject *parent) : QObject(parent)
{
    this->eventBroker = &ev;
    this->Gui_SerialCom = new GuiLogic_SerialCom(this);
}

SerialCom.h:

//Forward Declare our parent
class MasterGuiLogic;

class GuiLogic_SerialCom : public QObject
{
    Q_OBJECT
    Q_PROPERTY(QStringList portNames READ portNames NOTIFY portNamesChanged)
    Q_PROPERTY(bool connectedToPort READ connectedToPort NOTIFY connectedToPortChanged)
public:

    MasterGuiLogic *parent;
    explicit GuiLogic_SerialCom(MasterGuiLogic *parent = nullptr);

    std::map<QString, QSerialPortInfo> portsMap;

    QStringList portNames() {
        return _portNames;
    }

    bool connectedToPort() {
        return _connectedToPort;
    }

private:

    QStringList _portNames;
    bool _connectedToPort = false;

signals:

    void portNamesChanged(const QStringList &);
    void connectedToPortChanged(const bool &);

public slots:

    void connectToPort(const QString portName);
    void disconnectFromPort(const QString portName);

};

SerialCom.cpp:

GuiLogic_SerialCom::GuiLogic_SerialCom(MasterGuiLogic *parent) : QObject(qobject_cast<QObject *>(parent))
{
    this->parent = parent;

    QList<QSerialPortInfo> allPorts = QSerialPortInfo::availablePorts();

    for (int i = 0; i < allPorts.size(); ++i) {
        this->_portNames.append(allPorts.at(i).portName());
        this->portsMap[allPorts.at(i).portName()] = allPorts.at(i);
    }

    emit portNamesChanged(_portNames);

}

void GuiLogic_SerialCom::connectToPort(const QString portName) {
    //TODO: Connect To Port Logic Here;

    //Set Connected
    this->_connectedToPort = true;
    emit connectedToPortChanged(this->_connectedToPort);

    qDebug() << portName;
}

void GuiLogic_SerialCom::disconnectFromPort(const QString portName) {
    //TODO: DisConnect To Port Logic Here;

    //Set DisConnected
    this->_connectedToPort = false;
    emit connectedToPortChanged(this->_connectedToPort);

    qDebug() << portName;
}

So from qml it's pretty easy to read any of these properties and even send signals from qml to c++

For example, this works just fine:

connectCom.onClicked: {
        if (MasterGuiLogic.serialCom.connectedToPort === false) {
            MasterGuiLogic.serialCom.connectToPort(comPort.currentText);
        } else {
            MasterGuiLogic.serialCom.disconnectFromPort(comPort.currentText);
        }
    }

The problem is, I can't seem to find a way to connect to signals that are emitted from SerialCom. I thought I would be able to do something like this:

Connections: {
        target: MasterGuiLogic.serialCom;
        onConnectedToPortChanged: {
            if (MasterGuiLogic.serialCom.connectedToPort === false) {
                connectCom.text = "Disconnect";
                comPort.enabled = false;
            } else {
                connectCom.text = "Connect";
                comPort.enabled = true;
            }
        }
    }

This should listen to the boolean property on SerialCom to change, but I get the following error:

QQmlApplicationEngine failed to load component
qrc:/QmlGui/main.qml:21 Type Page1 unavailable
qrc:/QmlGui/Page1.qml:49 Invalid attached object assignment

This just means that I can't "connect" using the target line above. Is there any other way I can connect to signals from a Q_PROPERTY of type QObject inside a ContextProperty?

Body:
Ok, I found the problem... The provided answers, while indeed helpful for other reasons, were not the correct solution. After going over the code by @Xplatforms, I couldn't figure out what the difference was between what I was doing and what he did.... until I saw this in my own code:

Connections: {
        target: MasterGuiLogic.serialCom;
        onConnectedToPortChanged: {
            ...
        }
    }

There isn't supposed to be a colon(:) there...

Connections {
        target: MasterGuiLogic.serialCom;
        onConnectedToPortChanged: {
            ...
        }
    }

Never try programming while sleepy...lol


问:
Calling a class based on the selected item in a listview in javafx
I have a ListView and every time the selection is changed, I want to call a class with that name. For example, if the item is called "Text String" then the class TextString should be called. The code that I currently have is giving me an error saying The method insert(ArrayList<Element>) is undefined for the type Object ... Eclipse gives me a suggestion to cast the object as Element, but that doesn't do anything.  The Element class is a superclass and TextString would implement that class.

Here is the code I have so far:

```<code>   elementList.itemsProperty().bind(listProperty);
        listProperty.set(FXCollections.observableArrayList(elementListItems));
        elementList.setOnMouseClicked(new EventHandler<MouseEvent>() {

            public String selectedElement = "Text String";
            @Override
            public void handle(MouseEvent event) {
                selectedElement  = (String)elementList.getSelectionModel().getSelectedItem();
                selectedElement = selectedElement.replace(" ", "");
                Class<?> clazz;
                try {
                    clazz = Class.forName("elements."+selectedElement);
                    Constructor<?> ctor = clazz.getConstructor();
                    Object object = ctor.newInstance();
                    Method meth = clazz.getClass().getMethod("insert", new Class<?>[] { Canvas.class, ArrayList.class, GraphicsContext.class });
                    meth.invoke(object, canvas, objects, gc);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (SecurityException e) {
                    e.printStackTrace();
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        });
</code>```

Element.java

```<code>   public abstract class Element {
    public String name;
    public String description;
    public Canvas canvas;
    public ArrayList<Element> objects;
    public GraphicsContext gc;

    void remove(){

    }
    void toggle(){

    }
    void setBounds(int x, int y, int w, int h){

    }
    public abstract void insert(Canvas canvas, ArrayList<Element> objects, GraphicsContext gc);
}
</code>```

TextString.java

```<code>   public class TextString extends Element {
    private GraphicsContext gc;

    TextString() {
        super();
        this.name = "Text String";
        this.description = "A literal readable string of text.";
    }
    @Override
    public void insert(Canvas canvas, ArrayList<Element> objects, GraphicsContext gc) {
        this.gc = gc;
        this.canvas = canvas;
        this.objects = objects;
        System.out.println("Text string created.");
    }

}
</code>```

How can I cast the object to whatever object is being selected by the listview?

答:
I believe you are over complicating everything by trying to use reflection. It is optimal but sometimes I usually just rather do things simpler.

Why don't you make a factory helper that would import all the classes you might need and then use a switch to return the instance that you need?

Like:

```<code>public MyInterface returnClass(String type){

   switch (type){

   case: "Text String":
   return new TextString():

//And so on

}

}
</code>```

Body:
I have a ListView and every time the selection is changed, I want to call a class with that name. For example, if the item is called "Text String" then the class TextString should be called. The code that I currently have is giving me an error saying The method insert(ArrayList<Element>) is undefined for the type Object ... Eclipse gives me a suggestion to cast the object as Element, but that doesn't do anything.  The Element class is a superclass and TextString would implement that class.

Here is the code I have so far:

   elementList.itemsProperty().bind(listProperty);
        listProperty.set(FXCollections.observableArrayList(elementListItems));
        elementList.setOnMouseClicked(new EventHandler<MouseEvent>() {

            public String selectedElement = "Text String";
            @Override
            public void handle(MouseEvent event) {
                selectedElement  = (String)elementList.getSelectionModel().getSelectedItem();
                selectedElement = selectedElement.replace(" ", "");
                Class<?> clazz;
                try {
                    clazz = Class.forName("elements."+selectedElement);
                    Constructor<?> ctor = clazz.getConstructor();
                    Object object = ctor.newInstance();
                    Method meth = clazz.getClass().getMethod("insert", new Class<?>[] { Canvas.class, ArrayList.class, GraphicsContext.class });
                    meth.invoke(object, canvas, objects, gc);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (SecurityException e) {
                    e.printStackTrace();
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        });

Element.java

   public abstract class Element {
    public String name;
    public String description;
    public Canvas canvas;
    public ArrayList<Element> objects;
    public GraphicsContext gc;

    void remove(){

    }
    void toggle(){

    }
    void setBounds(int x, int y, int w, int h){

    }
    public abstract void insert(Canvas canvas, ArrayList<Element> objects, GraphicsContext gc);
}

TextString.java

   public class TextString extends Element {
    private GraphicsContext gc;

    TextString() {
        super();
        this.name = "Text String";
        this.description = "A literal readable string of text.";
    }
    @Override
    public void insert(Canvas canvas, ArrayList<Element> objects, GraphicsContext gc) {
        this.gc = gc;
        this.canvas = canvas;
        this.objects = objects;
        System.out.println("Text string created.");
    }

}

How can I cast the object to whatever object is being selected by the listview?

Body:
I believe you are over complicating everything by trying to use reflection. It is optimal but sometimes I usually just rather do things simpler.

Why don't you make a factory helper that would import all the classes you might need and then use a switch to return the instance that you need?

Like:

public MyInterface returnClass(String type){

   switch (type){

   case: "Text String":
   return new TextString():

//And so on

}

}


问:
Haskell defined a simple parser to recognise symbols. failure in some testing
I was currently reading "write yourself a scheme in 48 hours", and in the chapter 2 it defines a simple parser 'symbol' to recognise symbols and then define a function 'readExpr' to call the parser.

```<code>module Main where

import System.Environment
import Text.ParserCombinators.Parsec hiding (spaces)

main :: IO ()
main = do args <- getArgs
          putStrLn (readExpr (args !! 0))

symbol :: Parser Char
symbol = oneOf "!$%&|*+-/:<=?>@^_~#"

readExpr :: String -> String
readExpr input = case parse symbol "lisp" input of
    Left err -> "Not Found" ++ show err
    Right val -> "Found value" ++ show val
</code>```

However when I try some testing:

```<code>>>> ghc -package parsec -o hii C1.hs

>>> ./hii *
</code>```

it says:

```<code>Not Found"lisp" (line 1, column 1):
unexpected "A"
</code>```

Also, some other symbols like & or # also won't work and give an 'index too large error'. But symbols like: %,@,! etc. these works properly.
I don't understand why some symbols works while others doesn't.

In addition, if I add quote marks over that symbol:

```<code>./hi "#"

Found value'#'
</code>```

Now all the symbols work ...

Can someone please explain these to me since I'm really not familiar with monad stuff?

答:
* is expanded to all files in current working directory. I guess if you execute ls, the first file name is starting with A.

# is for comments begin, so there is no args passed to hii. & brings job to backgroud.

quotes prevents shell to translate *#!, so try to quote every arg passed, it'll be fine.

http://tldp.org/LDP/abs/html/special-chars.html

Body:
I was currently reading "write yourself a scheme in 48 hours", and in the chapter 2 it defines a simple parser 'symbol' to recognise symbols and then define a function 'readExpr' to call the parser.

module Main where

import System.Environment
import Text.ParserCombinators.Parsec hiding (spaces)

main :: IO ()
main = do args <- getArgs
          putStrLn (readExpr (args !! 0))

symbol :: Parser Char
symbol = oneOf "!$%&|*+-/:<=?>@^_~#"

readExpr :: String -> String
readExpr input = case parse symbol "lisp" input of
    Left err -> "Not Found" ++ show err
    Right val -> "Found value" ++ show val

However when I try some testing:

>>> ghc -package parsec -o hii C1.hs

>>> ./hii *

it says:

Not Found"lisp" (line 1, column 1):
unexpected "A"

Also, some other symbols like & or # also won't work and give an 'index too large error'. But symbols like: %,@,! etc. these works properly.
I don't understand why some symbols works while others doesn't.

In addition, if I add quote marks over that symbol:

./hi "#"

Found value'#'

Now all the symbols work ...

Can someone please explain these to me since I'm really not familiar with monad stuff?


问:
Typescript Firebase Cloud Store. Typo Issue
I'm trying to get data from Firebase Cloud Store following de sample of angularfire2 library:

```<code>import { Component } from '@angular/core';
import { AngularFirestore, AngularFirestoreDocument } from 'angularfire2/firestore';
import { Observable } from 'rxjs/Observable';

@Component({
  selector: 'app-root',
  template: `
    <div>
      {{ (item | async)?.name }}
    </div>
  `
})
export class AppComponent {
  private itemDoc: AngularFirestoreDocument<Item>;
  item: Observable<Item>;
  constructor(private afs: AngularFirestore) {
    this.itemDoc = afs.doc<Item>('items/1');
    this.item = this.itemDoc.valueChanges();
  }
  update(item: Item) {
    this.itemDoc.update(item);
  }
}
</code>```

But Typescript remarks with error the <Item> and says the name 'Item' has not found.

What would be the solution for this issue?

答:
You haven't defined an Item interface, just drop <Item> and the example should operate normally or you can define it:

```<code>interface Item {
   something: string;
   somethingElse: string;
}
</code>```

Body:
I'm trying to get data from Firebase Cloud Store following de sample of angularfire2 library:

import { Component } from '@angular/core';
import { AngularFirestore, AngularFirestoreDocument } from 'angularfire2/firestore';
import { Observable } from 'rxjs/Observable';

@Component({
  selector: 'app-root',
  template: `

      {{ (item | async)?.name }}

  `
})
export class AppComponent {
  private itemDoc: AngularFirestoreDocument<Item>;
  item: Observable<Item>;
  constructor(private afs: AngularFirestore) {
    this.itemDoc = afs.doc<Item>('items/1');
    this.item = this.itemDoc.valueChanges();
  }
  update(item: Item) {
    this.itemDoc.update(item);
  }
}

But Typescript remarks with error the <Item> and says the name 'Item' has not found.

What would be the solution for this issue?

Body:
You haven't defined an Item interface, just drop <Item> and the example should operate normally or you can define it:

interface Item {
   something: string;
   somethingElse: string;
}


问:
Eigen matrix ros/cols not working out right
I can't get this to compile:

```<code>Eigen::Map<Eigen::Matrix<const T, EA::ColsAtCompileTime, 1>> x(vec);
auto result = a_ * x - b_; // a(60r,1200c) * x(1200r,1c) - b(60r,1c)
</code>```

The two errors (about 1000 lines each) eventually conclude that the * and - operators can't be "overloaded" (their term, not mine).

a_ is of this type: typedef Eigen::Map<Eigen::Matrix<double, ROWS, COLS>> EA;

b_ is of this type: typedef Eigen::Map<Eigen::Matrix<double, ROWS, 1>> EB;

T is the Ceres Solver Jet type. The errors seem to bespeak a column/row mismatch rather than a type problem. I could be wrong, though; the output is entirely too verbose. Did I misunderstand how the rows and columns work with Eigen matrix operators?

Update: I followed the "fatal-errors" suggestion:

```<code>In file included from /usr/include/eigen3/Eigen/Core:437:0,
                 from /usr/local/include/ceres/jet.h:165,
                 from /usr/local/include/ceres/internal/autodiff.h:145,
                 from /usr/local/include/ceres/autodiff_cost_function.h:132,
                 from /usr/local/include/ceres/ceres.h:37,
                 from /home/brannon/Workspace/Solver/music_solver.cpp:3:
/usr/include/eigen3/Eigen/src/Core/PlainObjectBase.h: In instantiation of ‘class Eigen::PlainObjectBase<Eigen::Matrix<const double, 1200, 1, 0, 1200, 1> >’:
/usr/include/eigen3/Eigen/src/Core/Matrix.h:178:7:   required from ‘class Eigen::Matrix<const double, 1200, 1, 0, 1200, 1>’
/usr/include/eigen3/Eigen/src/Core/Map.h:24:32:   required from ‘struct Eigen::internal::traits<Eigen::Map<Eigen::Matrix<const double, 1200, 1, 0, 1200, 1>, 0, Eigen::Stride<0, 0> > >’
/usr/include/eigen3/Eigen/src/Core/util/ForwardDeclarations.h:32:54:   required from ‘struct Eigen::internal::accessors_level<Eigen::Map<Eigen::Matrix<const double, 1200, 1, 0, 1200, 1>, 0, Eigen::Stride<0, 0> > >’
/usr/include/eigen3/Eigen/src/Core/util/ForwardDeclarations.h:113:75:   required from ‘class Eigen::Map<Eigen::Matrix<const double, 1200, 1, 0, 1200, 1>, 0, Eigen::Stride<0, 0> >’
/home/brannon/Workspace/Solver/music_solver.cpp:18:72:   required from ‘bool MusicCostFunctor<MATRIX_A, MATRIX_B>::operator()(const T*, T*) const [with T = double; MATRIX_A = Eigen::Map<Eigen::Matrix<double, 60, 1200, 0, 60, 1200>, 0, Eigen::Stride<0, 0> >; MATRIX_B = Eigen::Map<Eigen::Matrix<double, 60, 1, 0, 60, 1>, 0, Eigen::Stride<0, 0> >]’
/usr/local/include/ceres/internal/variadic_evaluate.h:175:19:   required from ‘static bool ceres::internal::VariadicEvaluate<Functor, T, N0, 0, 0, 0, 0, 0, 0, 0, 0, 0>::Call(const Functor&, const T* const*, T*) [with Functor = MusicCostFunctor<Eigen::Map<Eigen::Matrix<double, 60, 1200, 0, 60, 1200>, 0, Eigen::Stride<0, 0> >, Eigen::Map<Eigen::Matrix<double, 60, 1, 0, 60, 1>, 0, Eigen::Stride<0, 0> > >; T = double; int N0 = 1200]’
/usr/local/include/ceres/autodiff_cost_function.h:208:17:   required from ‘bool ceres::AutoDiffCostFunction<CostFunctor, kNumResiduals, N0, N1, N2, N3, N4, N5, N6, N7, N8, N9>::Evaluate(const double* const*, double*, double**) const [with CostFunctor = MusicCostFunctor<Eigen::Map<Eigen::Matrix<double, 60, 1200, 0, 60, 1200>, 0, Eigen::Stride<0, 0> >, Eigen::Map<Eigen::Matrix<double, 60, 1, 0, 60, 1>, 0, Eigen::Stride<0, 0> > >; int kNumResiduals = 1; int N0 = 1200; int N1 = 0; int N2 = 0; int N3 = 0; int N4 = 0; int N5 = 0; int N6 = 0; int N7 = 0; int N8 = 0; int N9 = 0]’
/home/brannon/Workspace/Solver/music_solver.cpp:115:1:   required from here
/usr/include/eigen3/Eigen/src/Core/PlainObjectBase.h:585:27: error: ‘static Eigen::PlainObjectBase<Derived>::MapType Eigen::PlainObjectBase<Derived>::Map(Eigen::PlainObjectBase<Derived>::Scalar*) [with Derived = Eigen::Matrix<const double, 1200, 1, 0, 1200, 1>; Eigen::PlainObjectBase<Derived>::MapType = Eigen::Map<Eigen::Matrix<const double, 1200, 1, 0, 1200, 1>, 0, Eigen::Stride<0, 0> >; Eigen::PlainObjectBase<Derived>::Scalar = const double]’ cannot be overloaded
     static inline MapType Map(Scalar* data)
                           ^~~
</code>```

答:
After looking again at this example:
https://groups.google.com/d/msg/ceres-solver/7ZH21XX6HWU/Z3E-k2fbAwAJ

I realized that I put the const in the wrong spot. It's supposed to be Map<const... rather than <const T.

Body:
I can't get this to compile:

Eigen::Map<Eigen::Matrix<const T, EA::ColsAtCompileTime, 1>> x(vec);
auto result = a_ * x - b_; // a(60r,1200c) * x(1200r,1c) - b(60r,1c)

The two errors (about 1000 lines each) eventually conclude that the * and - operators can't be "overloaded" (their term, not mine).

a_ is of this type: typedef Eigen::Map<Eigen::Matrix<double, ROWS, COLS>> EA;

b_ is of this type: typedef Eigen::Map<Eigen::Matrix<double, ROWS, 1>> EB;

T is the Ceres Solver Jet type. The errors seem to bespeak a column/row mismatch rather than a type problem. I could be wrong, though; the output is entirely too verbose. Did I misunderstand how the rows and columns work with Eigen matrix operators?

Update: I followed the "fatal-errors" suggestion:

In file included from /usr/include/eigen3/Eigen/Core:437:0,
                 from /usr/local/include/ceres/jet.h:165,
                 from /usr/local/include/ceres/internal/autodiff.h:145,
                 from /usr/local/include/ceres/autodiff_cost_function.h:132,
                 from /usr/local/include/ceres/ceres.h:37,
                 from /home/brannon/Workspace/Solver/music_solver.cpp:3:
/usr/include/eigen3/Eigen/src/Core/PlainObjectBase.h: In instantiation of ‘class Eigen::PlainObjectBase<Eigen::Matrix<const double, 1200, 1, 0, 1200, 1> >’:
/usr/include/eigen3/Eigen/src/Core/Matrix.h:178:7:   required from ‘class Eigen::Matrix<const double, 1200, 1, 0, 1200, 1>’
/usr/include/eigen3/Eigen/src/Core/Map.h:24:32:   required from ‘struct Eigen::internal::traits<Eigen::Map<Eigen::Matrix<const double, 1200, 1, 0, 1200, 1>, 0, Eigen::Stride<0, 0> > >’
/usr/include/eigen3/Eigen/src/Core/util/ForwardDeclarations.h:32:54:   required from ‘struct Eigen::internal::accessors_level<Eigen::Map<Eigen::Matrix<const double, 1200, 1, 0, 1200, 1>, 0, Eigen::Stride<0, 0> > >’
/usr/include/eigen3/Eigen/src/Core/util/ForwardDeclarations.h:113:75:   required from ‘class Eigen::Map<Eigen::Matrix<const double, 1200, 1, 0, 1200, 1>, 0, Eigen::Stride<0, 0> >’
/home/brannon/Workspace/Solver/music_solver.cpp:18:72:   required from ‘bool MusicCostFunctor<MATRIX_A, MATRIX_B>::operator()(const T*, T*) const [with T = double; MATRIX_A = Eigen::Map<Eigen::Matrix<double, 60, 1200, 0, 60, 1200>, 0, Eigen::Stride<0, 0> >; MATRIX_B = Eigen::Map<Eigen::Matrix<double, 60, 1, 0, 60, 1>, 0, Eigen::Stride<0, 0> >]’
/usr/local/include/ceres/internal/variadic_evaluate.h:175:19:   required from ‘static bool ceres::internal::VariadicEvaluate<Functor, T, N0, 0, 0, 0, 0, 0, 0, 0, 0, 0>::Call(const Functor&, const T* const*, T*) [with Functor = MusicCostFunctor<Eigen::Map<Eigen::Matrix<double, 60, 1200, 0, 60, 1200>, 0, Eigen::Stride<0, 0> >, Eigen::Map<Eigen::Matrix<double, 60, 1, 0, 60, 1>, 0, Eigen::Stride<0, 0> > >; T = double; int N0 = 1200]’
/usr/local/include/ceres/autodiff_cost_function.h:208:17:   required from ‘bool ceres::AutoDiffCostFunction<CostFunctor, kNumResiduals, N0, N1, N2, N3, N4, N5, N6, N7, N8, N9>::Evaluate(const double* const*, double*, double**) const [with CostFunctor = MusicCostFunctor<Eigen::Map<Eigen::Matrix<double, 60, 1200, 0, 60, 1200>, 0, Eigen::Stride<0, 0> >, Eigen::Map<Eigen::Matrix<double, 60, 1, 0, 60, 1>, 0, Eigen::Stride<0, 0> > >; int kNumResiduals = 1; int N0 = 1200; int N1 = 0; int N2 = 0; int N3 = 0; int N4 = 0; int N5 = 0; int N6 = 0; int N7 = 0; int N8 = 0; int N9 = 0]’
/home/brannon/Workspace/Solver/music_solver.cpp:115:1:   required from here
/usr/include/eigen3/Eigen/src/Core/PlainObjectBase.h:585:27: error: ‘static Eigen::PlainObjectBase<Derived>::MapType Eigen::PlainObjectBase<Derived>::Map(Eigen::PlainObjectBase<Derived>::Scalar*) [with Derived = Eigen::Matrix<const double, 1200, 1, 0, 1200, 1>; Eigen::PlainObjectBase<Derived>::MapType = Eigen::Map<Eigen::Matrix<const double, 1200, 1, 0, 1200, 1>, 0, Eigen::Stride<0, 0> >; Eigen::PlainObjectBase<Derived>::Scalar = const double]’ cannot be overloaded
     static inline MapType Map(Scalar* data)
                           ^~~


问:
What does the ^M character mean in Vim?
I keep getting the ^M character in my .vimrc and it breaks my
configuration.

答:
If you didn't specify a different fileformat intentionally (say, :e ++ff=unix for a Windows file), it's likely that the target file has mixed EOLs.

For example, if a file has some lines with <CR><NL> endings and others with
<NL> endings, and fileformat is set to unix automatically by Vim when reading it, ^M (<CR>) will appear.
In such cases, fileformats (note: there's an extra s) comes into play. See :help ffs for the details.

ContentLicense: CC BY-SA 4.0

Title: What does the ^M character mean in Vim?


问:
DBVisualizer Hive SSH Tunnel Ignoring Server Information
I'm attempting to setup a connection to our Hadoop cluster via DBVisualizer.

In order to connect I need to SSH into a server on the domain and then I need to run the command to a remote server (I've not ssh'd onto the Hadoop cluster directly)

I have (figuratively)

```<code>Database Server: abcd.efg
Database Port: 12345
Database: Hello
</code>```

configured for the Database section

```<code>SSH Host: hijk.efg
SSH Port: 678
</code>```

When I attempt a connection, it returns

Could not open client transport with JDBC Uri:
  jdbc:hive2://127.0.0.1:-----
  Where 127.0.0.1 and ----- appear to be the defaults instead of what I entered.

Any idea how I get the SSH tunnel to use the server configuration I specify?

答:
The SSH Tunnel is set up locally on the client, so connecting to the port on localhost tunnels you to the SSH Host/Port, which then sets up a connection to the database server/port you have specified. This page may help:

http://confluence.dbvis.com/display/UG100/Using+an+SSH+Tunnel

Best Regards,
Hans

Body:
I'm attempting to setup a connection to our Hadoop cluster via DBVisualizer.

In order to connect I need to SSH into a server on the domain and then I need to run the command to a remote server (I've not ssh'd onto the Hadoop cluster directly)

I have (figuratively)

Database Server: abcd.efg
Database Port: 12345
Database: Hello

configured for the Database section

SSH Host: hijk.efg
SSH Port: 678

When I attempt a connection, it returns

Could not open client transport with JDBC Uri:
  jdbc:hive2://127.0.0.1:-----
  Where 127.0.0.1 and ----- appear to be the defaults instead of what I entered.

Any idea how I get the SSH tunnel to use the server configuration I specify?


问:
Nicely selecting and grouping by expressions, without using case-when
In MySQL, you can do nice things like

```<code>select bar > 2, count(*) from foo group by (bar > 2)
</code>```

to get a result like

```
    bar > 2  count
    --------------
      0        12
      1        26
```

to indicate that there are 12 rows with bar <= 12 and 26 with bar > 12.

I would like to do the same on a DB2 database on an AS/400. It doesn't like expressions in the select or group by clause, but you can work around that using

```<code>select when (bar > 2) then 1 else 0 end, count(*) from foo
  group by when (bar > 2) then 1 else 0 end
</code>```

This works, but of course it is extremely ugly. My question is: is there a nicer way to do this, especially considering that I will probably be retrieving consolidated values over dozens of expressions this way? Perhaps there is even a standards-compliant way of doing this that I'm overlooking?

Edit: It turns out the case-when IS the standards-compliant way of doing it.

答:
Don't think there is any fancy way, there doesn't even seem to be a way to cast from boolean to int directly.  CASE WHEN is standards compliant, and you can subquery it so as not to repeat the expression.

```<code>select bar2, count(*)
from
(
    select CASE when (bar > 2) then 1 else 0 end as bar2
    from foo
) SQ
group by bar2
</code>```

Or with many fields

```<code>select bar2, foobar2, count(other1)
from
(
    select
        CASE when (bar > 2) then 1 else 0 end as bar2,
        other1,
        CASE when foobar=1 then 2 when foobar<10 then 1 else 0 end as foobar2
    from foo
) SQ
group by bar2, foobar2
</code>```

SQL-92 text is available at http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt at time of this notes, the link itself was lifted from Wikipedia.  The spec on CASE statements cover 2 cases:

```<code>     <simple case> ::=
          CASE <case operand>
            <simple when clause>...
            [ <else clause> ]
          END

     <searched case> ::=
          CASE
            <searched when clause>...
            [ <else clause> ]
          END
</code>```

Body:
In MySQL, you can do nice things like

select bar > 2, count(*) from foo group by (bar > 2)

to get a result like

    bar > 2  count
    --------------
      0        12
      1        26

to indicate that there are 12 rows with bar <= 12 and 26 with bar > 12.

I would like to do the same on a DB2 database on an AS/400. It doesn't like expressions in the select or group by clause, but you can work around that using

select when (bar > 2) then 1 else 0 end, count(*) from foo
  group by when (bar > 2) then 1 else 0 end

This works, but of course it is extremely ugly. My question is: is there a nicer way to do this, especially considering that I will probably be retrieving consolidated values over dozens of expressions this way? Perhaps there is even a standards-compliant way of doing this that I'm overlooking?

Edit: It turns out the case-when IS the standards-compliant way of doing it.

Body:
Don't think there is any fancy way, there doesn't even seem to be a way to cast from boolean to int directly.  CASE WHEN is standards compliant, and you can subquery it so as not to repeat the expression.

select bar2, count(*)
from
(
    select CASE when (bar > 2) then 1 else 0 end as bar2
    from foo
) SQ
group by bar2

Or with many fields

select bar2, foobar2, count(other1)
from
(
    select
        CASE when (bar > 2) then 1 else 0 end as bar2,
        other1,
        CASE when foobar=1 then 2 when foobar<10 then 1 else 0 end as foobar2
    from foo
) SQ
group by bar2, foobar2

SQL-92 text is available at http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt at time of this notes, the link itself was lifted from Wikipedia.  The spec on CASE statements cover 2 cases:

     <simple case> ::=
          CASE <case operand>
            <simple when clause>...
            [ <else clause> ]
          END

     <searched case> ::=
          CASE
            <searched when clause>...
            [ <else clause> ]
          END


问:
Passing a structure member name to a function in C++
Here is a basic code that does not work.

```<code>struct s_date {
   int day;
   int month;
   int year;
} date;

void showMonth(date.month);

int main()
{

cout << "Enter a number";
cin >> date.month;

showMonth(date.month);

return 0;
}

void showMonth(date.month) {
switch (date.month) {
    case 1:
    cout << "January";
    break;

    //...
    }
}
</code>```

How can I pass a specific structure member name (such as date.month) to a function as shown here?

答: C++ is not reflective like Java, C#, Python, Ruby, et al. languages. So you have to provide the string yourself (e.g. "date.month") but it is up to you to sync with the actual struct definition.</p>

Body:
Here is a basic code that does not work.

struct s_date {
   int day;
   int month;
   int year;
} date;

void showMonth(date.month);

int main()
{

cout << "Enter a number";
cin >> date.month;

showMonth(date.month);

return 0;
}

void showMonth(date.month) {
switch (date.month) {
    case 1:
    cout << "January";
    break;

    //...
    }
}

How can I pass a specific structure member name (such as date.month) to a function as shown here?


问:
Kendo UI Grid - Build Columns Dynamically
I have an array with the list of column names, that needs to be displayed in the grid. So, while initializing the grid, I need to loop through each column in the datasource - and if that column is present in the Array, then I need to display it.

For example,

```<code>var ColumnNames = ["col1","col3"];
var dataSource = [ {
                    "col1": "a",
                    "col2": "1",
                    "col3": "11",
                    "col4": "1111"
                  },
                  {
                   "col1": "b",
                   "col2": "2",
                   "col3": "22",
                   "col4": "2222"
                  },
                  {
                    "col1": "c",
                    "col2": "3",
                    "col3": "33",
                    "col4": "3333"
                  },
                .....]
</code>```

The grid should display only with the columns present in the array. Here, as shown below:

```<code>col1    col3
---------------
a        11
b        22
c        33
.......
</code>```

The ColumnNames Array and dataSource actually comes from DB, based on the user selection. So, I can not hardcode column names. I tried various options (using column templates, foreach loops for building the model, etc) , but facing one or the other issue. Can someone help me out on this please?

Thanks in advance!

Regards

Neelima

答:
Tri This :

var ColumnNames = ["col1","col3"];
var dataSource = [ {
                    "col1": "a",
                    "col2": "1",
                    "col3": "11",
                    "col4": "1111"
                  },
                  {
                   "col1": "b",
                   "col2": "2",
                   "col3": "22",
                   "col4": "2222"
                  },
                  {
                    "col1": "c",
                    "col2": "3",
                    "col3": "33",
                    "col4": "3333"
                  }]

$(document).ready(function(){
    createGrid();
})
function createGrid(){
  var columns =  generateColumns(dataSource);
  $("#grid").kendoGrid({
      dataSource : dataSource,
      columns  :columns
  });
}

function generateColumns(_dataSource){
  if(_dataSource.length > 0) {
    return Object.keys(_dataSource[0]);
  }
}

$("#btnUpdate").click(function(){
 var grid = $("#grid").data("kendoGrid");
 grid.destroy();
 $("#grid").empty();
 dataSource = [ {
                    "col1": "a",
                    "col2": "1",
                    "col4": "1111"
                  },
                  {
                   "col1": "b",
                   "col2": "2",
                   "col4": "2222"
                  },
                  {
                    "col1": "c",
                    "col2": "3",
                    "col4": "3333"
                  }];
 createGrid();

})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://kendo.cdn.telerik.com/2017.3.1026/styles/kendo.common.min.css" rel="stylesheet"/>
<link href="https://kendo.cdn.telerik.com/2017.3.1026/styles/kendo.rtl.min.css" rel="stylesheet"/>
<link href="https://kendo.cdn.telerik.com/2017.3.1026/styles/kendo.silver.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2017.3.1026/js/kendo.all.min.js"></script>

<div id = "grid">
</div>
<button id="btnUpdate">update</button></code>```

Body:
I have an array with the list of column names, that needs to be displayed in the grid. So, while initializing the grid, I need to loop through each column in the datasource - and if that column is present in the Array, then I need to display it.

For example,

var ColumnNames = ["col1","col3"];
var dataSource = [ {
                    "col1": "a",
                    "col2": "1",
                    "col3": "11",
                    "col4": "1111"
                  },
                  {
                   "col1": "b",
                   "col2": "2",
                   "col3": "22",
                   "col4": "2222"
                  },
                  {
                    "col1": "c",
                    "col2": "3",
                    "col3": "33",
                    "col4": "3333"
                  },
                .....]

The grid should display only with the columns present in the array. Here, as shown below:

col1    col3
---------------
a        11
b        22
c        33
.......

The ColumnNames Array and dataSource actually comes from DB, based on the user selection. So, I can not hardcode column names. I tried various options (using column templates, foreach loops for building the model, etc) , but facing one or the other issue. Can someone help me out on this please?

Thanks in advance!

Regards

Neelima

Body:
Tri This :

var ColumnNames = ["col1","col3"];
var dataSource = [ {
                    "col1": "a",
                    "col2": "1",
                    "col3": "11",
                    "col4": "1111"
                  },
                  {
                   "col1": "b",
                   "col2": "2",
                   "col3": "22",
                   "col4": "2222"
                  },
                  {
                    "col1": "c",
                    "col2": "3",
                    "col3": "33",
                    "col4": "3333"
                  }]

$(document).ready(function(){
    createGrid();
})
function createGrid(){
  var columns =  generateColumns(dataSource);
  $("#grid").kendoGrid({
      dataSource : dataSource,
      columns  :columns
  });
}

function generateColumns(_dataSource){
  if(_dataSource.length > 0) {
    return Object.keys(_dataSource[0]);
  }
}

$("#btnUpdate").click(function(){
 var grid = $("#grid").data("kendoGrid");
 grid.destroy();
 $("#grid").empty();
 dataSource = [ {
                    "col1": "a",
                    "col2": "1",
                    "col4": "1111"
                  },
                  {
                   "col1": "b",
                   "col2": "2",
                   "col4": "2222"
                  },
                  {
                    "col1": "c",
                    "col2": "3",
                    "col4": "3333"
                  }];
 createGrid();

})

<link href="https://kendo.cdn.telerik.com/2017.3.1026/styles/kendo.common.min.css" rel="stylesheet"/>
<link href="https://kendo.cdn.telerik.com/2017.3.1026/styles/kendo.rtl.min.css" rel="stylesheet"/>
<link href="https://kendo.cdn.telerik.com/2017.3.1026/styles/kendo.silver.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2017.3.1026/js/kendo.all.min.js"></script>

<div id = "grid">
</div>
<button id="btnUpdate">update</button>


问:
Adding multiple Date Fields in Django model
I am trying to add a field that would let me add multiple show dates in a Django Model. Sometimes the show date will contain 3 dates, sometimes 1 or sometimes 7. How am I able to add this in a model and have it so I can add multiple dates in the Django admin?</p>

答:
If you are using postgres you can use an ArrayField for this purpose.

```<code>from django.db import models
from django.contrib.postgres.fields import ArrayField

class MyModel(models.Model):
    dates = ArrayField(
        models.DateTimeField(),
    )
</code>```

Here is the documentation

An alternate approach would be to declare a ShowDate model and set a ForeignKey linking back to your Show model.

Body:
If you are using postgres you can use an ArrayField for this purpose.

from django.db import models
from django.contrib.postgres.fields import ArrayField

class MyModel(models.Model):
    dates = ArrayField(
        models.DateTimeField(),
    )

Here is the documentation

An alternate approach would be to declare a ShowDate model and set a ForeignKey linking back to your Show model.


问:
Setting Shop thumbnail images in Woocommerce in Wordpress
How do I set a different image for the shop thumbnails for Woocommerce in Wordpress?

I tried it using the content in CSS but the slide cart images and the cart page are not changing.

答:
Place this code in your functions.php file.  It will modify all the shop catalog images to whatever new URL you override the images with.</p>

```<code>function modify_woocommerce_product_get_image( $image, $product, $size, $attr, $placeholder ) {
    if( $size = 'shop_catalog' )
        return '<img src="">';

    return $image;
}

add_filter( 'woocommerce_product_get_image', 'modify_woocommerce_product_get_image', 10, 5 );
</code>```

Body:
Place this code in your functions.php file.  It will modify all the shop catalog images to whatever new URL you override the images with.

function modify_woocommerce_product_get_image( $image, $product, $size, $attr, $placeholder ) {
    if( $size = 'shop_catalog' )
        return '<img src="">';

    return $image;
}

add_filter( 'woocommerce_product_get_image', 'modify_woocommerce_product_get_image', 10, 5 );


问:
javascript image problem
how cand i add a value to the class element in an image?

for src and align it works, and it adds the values to src and align:

```<code>src : this.inputs['src'].value,
align : this.inputs['align'].value,
</code>```

but when i write class it becomes highlighted and it dosen't add the value to the class element in the images html:

```<code>class: this.inputs['class'].value,
</code>```

is 'class' a reserved word in javascript? if yes is there another solution for my prolem?

答:
class is a reserved word.

You can still use reserved words as member names in objects by quoting them:

```<code>{
    'class': 'foo'
}
</code>```

Regardless, the class attribute is actually set via className in JavaScript:

```<code>{
    src: 'foo.jpg',
    align: 'left',
    className: 'something'
}
</code>```

Bear in mind that setting this will overwrite any existing classes you have defined: to combat this you can simply append the new class to the existing value:

```<code>this.className += ' another class';
</code>```

To replace an existing class you can do:

```<code>this.className = (" " + this.className + " ").replace(' yourOldClass ','  yourNewClass ');
</code>```

Title: javascript image problem

Body:
how cand i add a value to the class element in an image?

for src and align it works, and it adds the values to src and align:

src : this.inputs['src'].value,
align : this.inputs['align'].value,

but when i write class it becomes highlighted and it dosen't add the value to the class element in the images html:

class: this.inputs['class'].value,

is 'class' a reserved word in javascript? if yes is there another solution for my prolem?

Body:
class is a reserved word.

You can still use reserved words as member names in objects by quoting them:

{
    'class': 'foo'
}

Regardless, the class attribute is actually set via className in JavaScript:

{
    src: 'foo.jpg',
    align: 'left',
    className: 'something'
}

Bear in mind that setting this will overwrite any existing classes you have defined: to combat this you can simply append the new class to the existing value:

this.className += ' another class';

To replace an existing class you can do:

this.className = (" " + this.className + " ").replace(' yourOldClass ','  yourNewClass ');


问:
Error UnhandledPromiseRejectionWarning trying to testing
i get this error when try run my test:

```<code>UnhandledPromiseRejectionWarning: Unhandled promise rejection
(rejection id: 1): TypeError: Cannot read property 'body' of undefine
</code>```

i just need that "captcha" get true result. Any change that I have applied to my code gives me the same result, I tried removing the asynchronous functions, but I still have the same problem.

here my testing code:

```<code>import proxyquire from 'proxyquire';
import assert from 'assert';
import chai from 'chai';
const expect = chai.expect;

const loggerStub ={
  log:()=>{
  return;
  }
}

const lodashStub = ()=>{
 result = undefined;
}
const validationStub = {
  validation:()=>{
   return Promise.resolve({
   data:{
     success:true
        }
      });
     }
    }

const req = {
 body:{
 captchaResponse: true
   }
  }

 const res = {
  status: (status) => {
   return {
   send: () => {
    return;
    }
   }
  }
 }

 describe('Probando captcha', ()=>{
 describe('Validación de captcha', ()=>{
  it('Captcha validado OK', (done)=>{
    const captcha = proxyquire('../src/controllers/captcha',{
      '../domain/captcha': validationStub,
      '../core/logger': loggerStub,
      'lodash': lodashStub
    });
    const next = () => {
      console.log('llegó al next');
      expect(captcha.validation()).to.be.true;
      done();
    }
    setTimeout(() => {
      captcha.validation(req, res, next);
    }, 200);
   });
 });
});
</code>```

here my code:

```<code>import { get } from "lodash";
import captcha from "../domain/captcha";
import logger from "../core/logger";
require("babel-polyfill");

const validation = async (req, res, next) => {
 if (!req.body.captchaResponse) {
  logger.log("info", "MISSING CAPTCHA PARAMETERS");
  return res.status(422).send();
 }
 const captchaResponse = req.body.captchaResponse;
 console.log(req.body.captchaResponse);

 try {

   const result = await captcha.validation(captchaResponse);
    if (get(result, "data.success")) {
     logger.log("info", "CAPTCHA VALIDATION OK");
     next();
     return;
   } else {
   logger.log("info", "FAIL CAPTCHA VALIDATION");
  return res.status(422).send();
  }
 } catch (e) {
 console.log(e);
 logger.log("info", "ERROR CAPTCHA VALIDATION");
 return res.status(422).send();
 }
};

export default { validation };
</code>```

My package.json test:

"test": "mocha --compilers js:babel-register babel-polyfill ./test/ --
 recursive"

答:
The following line in the definition of next () causes problems

```<code>expect(captcha.validation()).to.be.true;
</code>```

You either need to include req, res, next into captcha.validation(), or remove this line at all.

Why? Because function expects three arguments, and as it gets none, you get undefined on req.body.

Body:
i get this error when try run my test:

UnhandledPromiseRejectionWarning: Unhandled promise rejection
(rejection id: 1): TypeError: Cannot read property 'body' of undefine

i just need that "captcha" get true result. Any change that I have applied to my code gives me the same result, I tried removing the asynchronous functions, but I still have the same problem.

here my testing code:

import proxyquire from 'proxyquire';
import assert from 'assert';
import chai from 'chai';
const expect = chai.expect;

const loggerStub ={
  log:()=>{
  return;
  }
}

const lodashStub = ()=>{
 result = undefined;
}
const validationStub = {
  validation:()=>{
   return Promise.resolve({
   data:{
     success:true
        }
      });
     }
    }

const req = {
 body:{
 captchaResponse: true
   }
  }

 const res = {
  status: (status) => {
   return {
   send: () => {
    return;
    }
   }
  }
 }

 describe('Probando captcha', ()=>{
 describe('Validación de captcha', ()=>{
  it('Captcha validado OK', (done)=>{
    const captcha = proxyquire('../src/controllers/captcha',{
      '../domain/captcha': validationStub,
      '../core/logger': loggerStub,
      'lodash': lodashStub
    });
    const next = () => {
      console.log('llegó al next');
      expect(captcha.validation()).to.be.true;
      done();
    }
    setTimeout(() => {
      captcha.validation(req, res, next);
    }, 200);
   });
 });
});

here my code:

import { get } from "lodash";
import captcha from "../domain/captcha";
import logger from "../core/logger";
require("babel-polyfill");

const validation = async (req, res, next) => {
 if (!req.body.captchaResponse) {
  logger.log("info", "MISSING CAPTCHA PARAMETERS");
  return res.status(422).send();
 }
 const captchaResponse = req.body.captchaResponse;
 console.log(req.body.captchaResponse);

 try {

   const result = await captcha.validation(captchaResponse);
    if (get(result, "data.success")) {
     logger.log("info", "CAPTCHA VALIDATION OK");
     next();
     return;
   } else {
   logger.log("info", "FAIL CAPTCHA VALIDATION");
  return res.status(422).send();
  }
 } catch (e) {
 console.log(e);
 logger.log("info", "ERROR CAPTCHA VALIDATION");
 return res.status(422).send();
 }
};

export default { validation };

My package.json test:

"test": "mocha --compilers js:babel-register babel-polyfill ./test/ --
 recursive"

Body:
The following line in the definition of next () causes problems

expect(captcha.validation()).to.be.true;

You either need to include req, res, next into captcha.validation(), or remove this line at all.

Why? Because function expects three arguments, and as it gets none, you get undefined on req.body.


问:
Permission Denial for Broadcast Receiver
Im trying to set up a receiver to relaunch my applications alarms/notifications once the phone reboots.

Im getting stuck with a permission denial error:

```<code>W/BroadcastQueue: Permission Denial: receiving Intent { act=android.intent.action.BOOT_COMPLETED flg=0x9000010 (has extras) } to com.closedbracket.trackit/.BootBroadcastReceiver requires android.permission.RECEIVE_BOOT_COMPLETED due to sender null (uid 1000)
</code>```

I've looked at a lot of SO questions simillar to this but haven't found a solution yet.

This is my manifest:

```<code>    <uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
    <uses-permission android:name="com.android.permission.RECEIVE_BOOT_COMPLETED" />
<application
....
<receiver
            android:name="com.closedbracket.trackit.BootBroadcastReceiver"
            android:enabled="true"
            android:exported="false"
            android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <action android:name="android.intent.action.QUICKBOOT_POWERON" />
            </intent-filter>
        </receiver>
</application>
</code>```

And this is my BootBroadcastReceiver:

```<code>public class BootBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    Log.i("BootBroadcastReceiver", "Received");
}}
</code>```

I am testing this with the Android Stuido Emulator by doing the restart functionality. I then check the logs and see the Permission Denial line in reference to my broadcast receiver and don't see my log of the onReceive method.

Literally tried everything I could, even changing the manifest's android:enable/export values, and adding the permission inside of it. Made no difference.

If anyone has any ideas, please let me know. Thank you.

答:
You can only have one action per intent filter. That's your issue.
For some reason it falls back to the last one on the list, in your case QUICKBOOT_POWERUN.
Add 2 intent filters in the broadcast receiver, each one with 1 action only and it will successfully receive both broadcasts.</p>

Body:
Im trying to set up a receiver to relaunch my applications alarms/notifications once the phone reboots.

Im getting stuck with a permission denial error:

W/BroadcastQueue: Permission Denial: receiving Intent { act=android.intent.action.BOOT_COMPLETED flg=0x9000010 (has extras) } to com.closedbracket.trackit/.BootBroadcastReceiver requires android.permission.RECEIVE_BOOT_COMPLETED due to sender null (uid 1000)

I've looked at a lot of SO questions simillar to this but haven't found a solution yet.

This is my manifest:

    <uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
    <uses-permission android:name="com.android.permission.RECEIVE_BOOT_COMPLETED" />
<application
....
<receiver
            android:name="com.closedbracket.trackit.BootBroadcastReceiver"
            android:enabled="true"
            android:exported="false"
            android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <action android:name="android.intent.action.QUICKBOOT_POWERON" />
            </intent-filter>
        </receiver>
</application>

And this is my BootBroadcastReceiver:

public class BootBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    Log.i("BootBroadcastReceiver", "Received");
}}

I am testing this with the Android Stuido Emulator by doing the restart functionality. I then check the logs and see the Permission Denial line in reference to my broadcast receiver and don't see my log of the onReceive method.

Literally tried everything I could, even changing the manifest's android:enable/export values, and adding the permission inside of it. Made no difference.

If anyone has any ideas, please let me know. Thank you.


问:
Can I have terraform keep the old versions of objects?
New to terraform, so perhaps it just not supposed to work this way. I want to use aws_s3_bucket_object to upload a package to a bucket- this is part of an app deploy. Im going to be changing the package for each deploy and I want to keep the old versions.

```<code>resource "aws_s3_bucket_object" "object" {
    bucket = "mybucket-app-versions"
    key    = "version01.zip"
    source = "version01.zip"
}
</code>```

But after running this for a future deploy I will want to upload version02 and then version03 etc. Terraform replaces the old zip with the new one- expected behavior.

But is there a way to have terraform not destroy the old version? Is this a supported use case here or is this not how I'm supposed to use terraform? I wouldn't want to force this with an ugly hack if terraform doesn't have official support for doing something like what I'm trying to do here.

I could of course just call the S3 api via script, but it would be great to have this defined with the rest of the terraform definition for this app.

答:
When using Terraform for application deployment, the recommended approach is to separate the build step from the deploy step and use Terraform only for the latter.

The responsibility of the build step -- which is implemented using a separate tool, depending on the method of deployment -- is to produce some artifact (an archive, a docker container, a virtual machine image, etc), publish it somewhere, and then pass its location or identifier to Terraform for deployment.

This separation between build and deploy allows for more complex situations, such as rolling back to an older artifact (without rebuilding it) if the new version has problems.

In simple scenarios it is possible to pass the artifact location to Terraform using Input Variables. For example, in your situation where the build process would write a zip file to S3, you might define a variable like this:

```<code>variable "archive_name" {
}
</code>```

This can then be passed to whatever resource needs it using ${var.archive_name} interpolation syntax. To deploy a particular artifact, pass its name on the command line using -var:

```<code>$ terraform apply -var="archive_name=version01.zip"
</code>```

Some organizations prefer to keep a record of the "current" version of each application in some kind of data store, such as HashiCorp Consul, and read it using a data source. This approach can be easier to orchestrate in an automated build pipeline, since it allows this separate data store to be used to indirectly pass the archive name between the build and deploy steps, without needing to pass any unusual arguments to Terraform itself.

Body:
New to terraform, so perhaps it just not supposed to work this way. I want to use aws_s3_bucket_object to upload a package to a bucket- this is part of an app deploy. Im going to be changing the package for each deploy and I want to keep the old versions.

resource "aws_s3_bucket_object" "object" {
    bucket = "mybucket-app-versions"
    key    = "version01.zip"
    source = "version01.zip"
}

But after running this for a future deploy I will want to upload version02 and then version03 etc. Terraform replaces the old zip with the new one- expected behavior.

But is there a way to have terraform not destroy the old version? Is this a supported use case here or is this not how I'm supposed to use terraform? I wouldn't want to force this with an ugly hack if terraform doesn't have official support for doing something like what I'm trying to do here.

I could of course just call the S3 api via script, but it would be great to have this defined with the rest of the terraform definition for this app.

Body:
When using Terraform for application deployment, the recommended approach is to separate the build step from the deploy step and use Terraform only for the latter.

The responsibility of the build step -- which is implemented using a separate tool, depending on the method of deployment -- is to produce some artifact (an archive, a docker container, a virtual machine image, etc), publish it somewhere, and then pass its location or identifier to Terraform for deployment.

This separation between build and deploy allows for more complex situations, such as rolling back to an older artifact (without rebuilding it) if the new version has problems.

In simple scenarios it is possible to pass the artifact location to Terraform using Input Variables. For example, in your situation where the build process would write a zip file to S3, you might define a variable like this:

variable "archive_name" {
}

This can then be passed to whatever resource needs it using ${var.archive_name} interpolation syntax. To deploy a particular artifact, pass its name on the command line using -var:

$ terraform apply -var="archive_name=version01.zip"

Some organizations prefer to keep a record of the "current" version of each application in some kind of data store, such as HashiCorp Consul, and read it using a data source. This approach can be easier to orchestrate in an automated build pipeline, since it allows this separate data store to be used to indirectly pass the archive name between the build and deploy steps, without needing to pass any unusual arguments to Terraform itself.


问:
Print a threading function in curses, Python
In my project I have to print some data stored in a database on the console. I have two functions that return string.  I should print those data in two columns.
I thought of using the module curses in python to create those two columns.
So far all is good.
Another thing, is that my two function use the threading.Timer. So the string generated changes every 10 seconds for example if I set my Timer on 10.
So when I put the result of my function on the addstr() of a column, it prints the first String correctly, but nothing changes even if my string change. Otherwise when I resize for example the console, I notice that the  string changes.
Here is my code : </p>

```<code>import sys,os
import curses , curses.panel
import datetime
import time
import threading

def time_func():
    printStr = threading.Timer(10,time_func)
    printStr.start()
    s = "Simple example that display datetime \n" + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    return s

def draw_menu():

    k = 0
    cursor_x = 0
    cursor_y = 0

    # Clear and refresh the screen
    stdscr = curses.initscr()
    stdscr.clear()
    stdscr.refresh()

    # Initialize colors in curses
    curses.start_color()
    curses.init_pair(1, curses.COLOR_CYAN, curses.COLOR_BLACK)
    curses.init_pair(2, curses.COLOR_RED, curses.COLOR_BLACK)
    curses.init_pair(3, curses.COLOR_BLACK, curses.COLOR_WHITE)
    curses.curs_set(0)
    # Loop where k is the last character pressed
    while (k != ord('q')):

        # Declaration of strings
        statusbarstr = "Press 'q' to exit | STATUS BAR "

        '''Draw borders of the different columns'''
        height, width = stdscr.getmaxyx()
        stdscr.border()
        stdscr.vline(1, 3 * height // 4, '|', width - 2)
        stdscr.vline(1, height // 4, '|', width - 2)
        stdscr.refresh()

        '''Initialize the Statistics column'''
        column_one = curses.newwin(height - 2, 3 * width // 4, 1,
                                           1)
        _, a_x = column_one.getmaxyx()
        column_one.attron(curses.color_pair(1))
        column_one.attron(curses.A_BOLD)
        column_one.addstr(0, a_x // 2 - 2, "column one")
        column_one.hline(1, 0, '-', a_x)
        column_one.attroff(curses.color_pair(1))
        column_one.attroff(curses.A_BOLD)

        # I want to add my string here for example :
        line = time_func()
        column_one.addstr(3,1, line)

        column_one.noutrefresh()

        '''Initialize the Alerts column'''
        column_two = curses.newwin(height - 2, width // 4, 1,
                                       3 * width // 4 )
        _, s_x = column_two.getmaxyx()
        column_two.attron(curses.color_pair(1))
        column_two.attron(curses.A_BOLD)
        column_two.addstr(0, s_x // 2 - 5, "column two")
        column_two.hline(1, 0, '-', s_x)
        column_two.attroff(curses.color_pair(1))
        column_two.attroff(curses.A_BOLD)

        column_two.addstr(3, s_x // 2 - 5,"test")

        column_two.noutrefresh()

        # Render status bar
        stdscr.attron(curses.color_pair(3))
        stdscr.addstr(height-1, 0, statusbarstr)
        stdscr.addstr(height-1, len(statusbarstr), " " * (width - len(statusbarstr) - 1))
        stdscr.attroff(curses.color_pair(3))

        # Turning on attributes for title
        stdscr.attron(curses.color_pair(2))
        stdscr.attron(curses.A_BOLD)

        # Rendering title

        # Turning off attributes for title
        stdscr.attroff(curses.color_pair(2))
        stdscr.attroff(curses.A_BOLD)

        # Print rest of text

        stdscr.move(height - 2, width - 2)

        # Refresh the screen
        stdscr.refresh()
        # Wait for next input
        k = stdscr.getch()

def main():
    curses.wrapper(draw_menu())

if __name__ == "__main__":
    main()
</code>```

答:
The curses function draw_menu is waiting for input at the end of the loop.  If you resize the terminal, that

```<code>k = stdscr.getch()
</code>```

returns a KEY_RESIZE, and runs through the loop again.

You could change that to wait a short time before giving up on the getch.  That would return a -1.

Usually that's done using timeout (in curses), e.g., 50 milliseconds.  There's a wrapper for that in Python (and by the way its description is incorrect).  You should read the ncurses manual page for timeout.

Sometimes people say to use nodelay, which is usually poor advice since it would make the draw_menu thread use most of the CPU time.

Body:
In my project I have to print some data stored in a database on the console. I have two functions that return string.  I should print those data in two columns.
I thought of using the module curses in python to create those two columns.
So far all is good.
Another thing, is that my two function use the threading.Timer. So the string generated changes every 10 seconds for example if I set my Timer on 10.
So when I put the result of my function on the addstr() of a column, it prints the first String correctly, but nothing changes even if my string change. Otherwise when I resize for example the console, I notice that the  string changes.
Here is my code :

import sys,os
import curses , curses.panel
import datetime
import time
import threading

def time_func():
    printStr = threading.Timer(10,time_func)
    printStr.start()
    s = "Simple example that display datetime \n" + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    return s

def draw_menu():

    k = 0
    cursor_x = 0
    cursor_y = 0

    # Clear and refresh the screen
    stdscr = curses.initscr()
    stdscr.clear()
    stdscr.refresh()

    # Initialize colors in curses
    curses.start_color()
    curses.init_pair(1, curses.COLOR_CYAN, curses.COLOR_BLACK)
    curses.init_pair(2, curses.COLOR_RED, curses.COLOR_BLACK)
    curses.init_pair(3, curses.COLOR_BLACK, curses.COLOR_WHITE)
    curses.curs_set(0)
    # Loop where k is the last character pressed
    while (k != ord('q')):

        # Declaration of strings
        statusbarstr = "Press 'q' to exit | STATUS BAR "

        '''Draw borders of the different columns'''
        height, width = stdscr.getmaxyx()
        stdscr.border()
        stdscr.vline(1, 3 * height // 4, '|', width - 2)
        stdscr.vline(1, height // 4, '|', width - 2)
        stdscr.refresh()

        '''Initialize the Statistics column'''
        column_one = curses.newwin(height - 2, 3 * width // 4, 1,
                                           1)
        _, a_x = column_one.getmaxyx()
        column_one.attron(curses.color_pair(1))
        column_one.attron(curses.A_BOLD)
        column_one.addstr(0, a_x // 2 - 2, "column one")
        column_one.hline(1, 0, '-', a_x)
        column_one.attroff(curses.color_pair(1))
        column_one.attroff(curses.A_BOLD)

        # I want to add my string here for example :
        line = time_func()
        column_one.addstr(3,1, line)

        column_one.noutrefresh()

        '''Initialize the Alerts column'''
        column_two = curses.newwin(height - 2, width // 4, 1,
                                       3 * width // 4 )
        _, s_x = column_two.getmaxyx()
        column_two.attron(curses.color_pair(1))
        column_two.attron(curses.A_BOLD)
        column_two.addstr(0, s_x // 2 - 5, "column two")
        column_two.hline(1, 0, '-', s_x)
        column_two.attroff(curses.color_pair(1))
        column_two.attroff(curses.A_BOLD)

        column_two.addstr(3, s_x // 2 - 5,"test")

        column_two.noutrefresh()

        # Render status bar
        stdscr.attron(curses.color_pair(3))
        stdscr.addstr(height-1, 0, statusbarstr)
        stdscr.addstr(height-1, len(statusbarstr), " " * (width - len(statusbarstr) - 1))
        stdscr.attroff(curses.color_pair(3))

        # Turning on attributes for title
        stdscr.attron(curses.color_pair(2))
        stdscr.attron(curses.A_BOLD)

        # Rendering title

        # Turning off attributes for title
        stdscr.attroff(curses.color_pair(2))
        stdscr.attroff(curses.A_BOLD)

        # Print rest of text

        stdscr.move(height - 2, width - 2)

        # Refresh the screen
        stdscr.refresh()
        # Wait for next input
        k = stdscr.getch()

def main():
    curses.wrapper(draw_menu())

if __name__ == "__main__":
    main()

Body:
The curses function draw_menu is waiting for input at the end of the loop.  If you resize the terminal, that

k = stdscr.getch()

returns a KEY_RESIZE, and runs through the loop again.

You could change that to wait a short time before giving up on the getch.  That would return a -1.

Usually that's done using timeout (in curses), e.g., 50 milliseconds.  There's a wrapper for that in Python (and by the way its description is incorrect).  You should read the ncurses manual page for timeout.

Sometimes people say to use nodelay, which is usually poor advice since it would make the draw_menu thread use most of the CPU time.


问:
Compute of randomly sampling matrix
I have a matrix of 30 rows:

```<code>set.seed(1234)
m = matrix(rnorm(300), 30)
</code>```

I want to randomly divide it into three sub-matrix (each one will contain 10 rows) and calculate the colMeans of each sub-groups.

How I can do it?

答:
I would use sample to get the random grouping, rowsum to get the group column sums and then divide by 3 to get the mean.

Here,

```<code>rowsum(myMat, sample(rep(1:3, length.out=nrow(myMat)), nrow(myMat))) / 3
</code>```

The length.out argument to rep assures that sample will have 30 elements to permute, 10 1s, 10 2s, and 10 3s. sample(rep(1:3, length.out=nrow(myMat)), nrow(myMat)) returns a random permutation of this set of integers that rowsums uses for the grouping.

The first five columns of this calculation returns

```<code>        [,1]       [,2]        [,3]      [,4]       [,5]
1 -1.5317639 -2.4137994  0.88905767 0.5783829  0.2593529
2 -0.6781386 -0.5701739 -0.03524136 0.3623384  1.4022571
3 -0.7543473 -2.5322095  0.53218802 0.1745588 -0.5748851
</code>```

data

```<code>set.seed(1234)
matrix(rnorm(300), 30)
</code>```

Title: Compute of randomly sampling matrix

Body:
I have a matrix of 30 rows:

set.seed(1234)
m = matrix(rnorm(300), 30)

I want to randomly divide it into three sub-matrix (each one will contain 10 rows) and calculate the colMeans of each sub-groups.

How I can do it?

Body:
I would use sample to get the random grouping, rowsum to get the group column sums and then divide by 3 to get the mean.

Here,

rowsum(myMat, sample(rep(1:3, length.out=nrow(myMat)), nrow(myMat))) / 3

The length.out argument to rep assures that sample will have 30 elements to permute, 10 1s, 10 2s, and 10 3s. sample(rep(1:3, length.out=nrow(myMat)), nrow(myMat)) returns a random permutation of this set of integers that rowsums uses for the grouping.

The first five columns of this calculation returns

        [,1]       [,2]        [,3]      [,4]       [,5]
1 -1.5317639 -2.4137994  0.88905767 0.5783829  0.2593529
2 -0.6781386 -0.5701739 -0.03524136 0.3623384  1.4022571
3 -0.7543473 -2.5322095  0.53218802 0.1745588 -0.5748851

data

set.seed(1234)
matrix(rnorm(300), 30)


问:
assign column value based on multiple conditional criteria
I have been trying to figure out how to assign a value based on some criteria.

I have a dataset that simplistically looks like:

```<code>fish <- data.frame ("method"=c("cryptic", "cryptic", "cryptic",
                               "quad", "quad", "quad",
                               "fish",
                               "1mquad", "1mquad"),
                    "species"= c("A", "B", "C",
                                 "A", "B", "D",
                                 "A",
                                 "A", "B"),
                  "cut"=1)
</code>```

I want to change the value of cut to 0 if a species has both the method cryptic and quad or cryptic and 1mquad.

I've tried a few different things and keep getting stuck. When I do an if statement I get weird warnings. Some things I've tried are making a subset df with just cryptic

```<code>cryptic <- fish [fish$method == "cryptic",]
</code>```

and then trying to subset

```<code>fish$cut [match(fish$species, cryptic$species) & fish$method =="quad"] <- 0
fish$cut [match(fish$species, cryptic$species) & fish$method =="1mquad"] <- 0
</code>```

but that doesn't work. I also tried creating conditions:

```<code>cond3 <- fish$species %in% intersect(fish$species, cryptic$species)
cond4 <- fish$method %in% c ("1mquad", "quad", "cryptic")
</code>```

and doing an if statement with that, but to no avail. Also, I have a few other conditions prior that changes cut to 0, so I can't use an ifelse statement because it overwrites those other conditions. Any suggestions?

答:
You were pretty close with the conditions. Here's an adjusted way:

```<code>crypt = unique(fish$species[fish$method == "cryptic"])
quad = unique(fish$species[fish$method %in% c("quad", "1mquad")])
to_change = intersect(crypt, quad)
fish$cut = ifelse(fish$species %in% to_change, 0, fish$cut)
fish
#    method species cut
# 1 cryptic       A   0
# 2 cryptic       B   0
# 3 cryptic       C   1
# 4    quad       A   0
# 5    quad       B   0
# 6    quad       D   1
# 7    fish       A   0
# 8  1mquad       A   0
# 9  1mquad       B   0
</code>```

Using the ifelse statement with fish$cut as the "else" means that if the condition is not met, whatever is there will stay there.

Demo

Body:
I have been trying to figure out how to assign a value based on some criteria.

I have a dataset that simplistically looks like:

fish <- data.frame ("method"=c("cryptic", "cryptic", "cryptic",
                               "quad", "quad", "quad",
                               "fish",
                               "1mquad", "1mquad"),
                    "species"= c("A", "B", "C",
                                 "A", "B", "D",
                                 "A",
                                 "A", "B"),
                  "cut"=1)

I want to change the value of cut to 0 if a species has both the method cryptic and quad or cryptic and 1mquad.

I've tried a few different things and keep getting stuck. When I do an if statement I get weird warnings. Some things I've tried are making a subset df with just cryptic

cryptic <- fish [fish$method == "cryptic",]

and then trying to subset

fish$cut [match(fish$species, cryptic$species) & fish$method =="quad"] <- 0
fish$cut [match(fish$species, cryptic$species) & fish$method =="1mquad"] <- 0

but that doesn't work. I also tried creating conditions:

cond3 <- fish$species %in% intersect(fish$species, cryptic$species)
cond4 <- fish$method %in% c ("1mquad", "quad", "cryptic")

and doing an if statement with that, but to no avail. Also, I have a few other conditions prior that changes cut to 0, so I can't use an ifelse statement because it overwrites those other conditions. Any suggestions?

Body:
You were pretty close with the conditions. Here's an adjusted way:

crypt = unique(fish$species[fish$method == "cryptic"])
quad = unique(fish$species[fish$method %in% c("quad", "1mquad")])
to_change = intersect(crypt, quad)
fish$cut = ifelse(fish$species %in% to_change, 0, fish$cut)
fish
#    method species cut
# 1 cryptic       A   0
# 2 cryptic       B   0
# 3 cryptic       C   1
# 4    quad       A   0
# 5    quad       B   0
# 6    quad       D   1
# 7    fish       A   0
# 8  1mquad       A   0
# 9  1mquad       B   0

Using the ifelse statement with fish$cut as the "else" means that if the condition is not met, whatever is there will stay there.

Demo


问:
How do I convert the following data serialization format into POJO or JSON?
I was expecting a JSON string while testing an API using Postman, but instead got this:

{city=Shanghai, work=112-454-7895, fax=788-899-7899}

Obviously I cannot put that into Google and ask what format is it, hence I am asking it here. Postman also says it is a 'bad string'.

I have never seen the above data serialization format. If someone can point the format out to me I would be able to find and use a converter. Additional suggestion with converting it to POJO or JSON are welcome as well.

答: I figured out that the above format is a stringified version of a HashMap<String, String>, and that there is no direct way to convert it into JSON/POJO. Converting it into json string requires additional work but is fairly straightforward.


问:
Pandas sampling every nth value, or closest matching value to nth value
I have a bit of a peculiar problem. I have a very large dataframe that I'm trying to sample.

My data looks something like this (two columns x and y):

```<code>x,y
1,'a'
1,'b'
1,'c'
3,'a'
3,'b'
3,'c'
6,'a'
6,'b'
6,'c'
</code>```

I want to sample based on the value of 'x'. I'd like one sample out of every 32 x values (based on the change in x, so I want to sample once between 1 and 32, even if there is only one value of x between 1 and 32).

I wanted to do something like: df[df['x'] % 32 == 0]. The problem is that the values of x are not necessarily evenly spaced (they are "approximately" though, but not always -- such as in the example given). For example, if all the values of x in a particular subproblem are odd, the above sampling will return an empty dataframe. Effectively, I want to sample once every 32 'x's, or take the closest value to the 32nd value (it is acceptable to approximate closest -- for example, taking the next available value is fine) if no such value exists.

So if I had a series of X's [0, 10, 32, 39, 64, 70, 73, 74, 97, 100, 110, 129], I'd like to sample the rows with x values matching [0, 32, 64, 97, 129].

Ideally, I could also vectorize this operation, as the dataframes are often quite large.

答:
```<code>df = pd.DataFrame({'x': [1, 1, 1, 3, 3, 3, 6, 6, 6],
                   'y': ['a', 'b', 'c'] * 3})

x = [0, 10, 32, 39, 64, 70, 73, 74, 97, 100, 110, 129]
spacer = 32

X = pd.Series(x)
# For each value `n` in the range 0, 32, 64, ..., 129, find the index location of the
# nearest value in X via `X.sub(n).abs().idxmin()`. Then use these index locations
# to find the actual target values in X via `loc`.
target_vals = X.loc[[X.sub(n).abs().idxmin()
                     for n in xrange(0, x[-1], spacer)]].tolist()  # `range` in Python 3.
>>> target_vals
[0, 32, 64, 97, 129]

# Sample the target values, taking a sample size of 1.
df[df['x'].isin(target_vals)].groupby('x').apply(lambda group: group.sample(1))
</code>```

Body:
I have a bit of a peculiar problem. I have a very large dataframe that I'm trying to sample.

My data looks something like this (two columns x and y):

x,y
1,'a'
1,'b'
1,'c'
3,'a'
3,'b'
3,'c'
6,'a'
6,'b'
6,'c'

I want to sample based on the value of 'x'. I'd like one sample out of every 32 x values (based on the change in x, so I want to sample once between 1 and 32, even if there is only one value of x between 1 and 32).

I wanted to do something like: df[df['x'] % 32 == 0]. The problem is that the values of x are not necessarily evenly spaced (they are "approximately" though, but not always -- such as in the example given). For example, if all the values of x in a particular subproblem are odd, the above sampling will return an empty dataframe. Effectively, I want to sample once every 32 'x's, or take the closest value to the 32nd value (it is acceptable to approximate closest -- for example, taking the next available value is fine) if no such value exists.

So if I had a series of X's [0, 10, 32, 39, 64, 70, 73, 74, 97, 100, 110, 129], I'd like to sample the rows with x values matching [0, 32, 64, 97, 129].

Ideally, I could also vectorize this operation, as the dataframes are often quite large.


问:
Retrieving codes within parenthesis in ColdFusion version 4.5
I have a string retrieved from the database that can contain a series of codes in either {} or [] brackets as well as plain, user entered text. For example, each of the following would be possible values:

```<code>[code]

[code1][code2]

{code}

{code1}{code2}

{code1} Some user entered text. {code2}{code3} Some more user entered text.

Etc. etc.
</code>```

What I need to do using ColdFusion is extract the codes within the {} and [] brackets so I can retrieve their descriptions from a database. For example:

```<code>{code1} Some user entered text. {code2}{code3} Some more user entered text.
</code>```

Would become a list similar to:

```<code>{code1}|{code2}|{code3}
</code>```

Normally I could just do something like REMatch but unfortunately I'm stuck doing this on a server running ColdFusion version 4.5 (groan) so my options are limited.

I'm thinking maybe I could do some Replaces on the string to convert it into a pipe delimited list that I can then easily process but I'm not sure if there might be a more straight forward approach? I'm not even really sure what a sensible way to process this using a Replace would be.

答:
```<code><cfset myString = "{code1} Some user entered text {code2}{code3} More user entered text" />
<cfset myArray = listToArray(myString, "{[") />

<cfloop index="i" from="1" to="#arrayLen(myArray)#">
  <cfset myArray[i] = "{" & listFirst(myArray[i], "}]") & "}" />
</cfloop>

<cfdump var="#myArray#" />
<hr>

<cfset myList = arrayToList(myArray, "|") />
<cfdump var="#myList#" />
</code>```

TryCF.com Gist:

https://trycf.com/gist/6035ddc5cd3daa81bc0943f1af33323a/lucee5?theme=monokai

Body:
I have a string retrieved from the database that can contain a series of codes in either {} or [] brackets as well as plain, user entered text. For example, each of the following would be possible values:

[code]

[code1][code2]

{code}

{code1}{code2}

{code1} Some user entered text. {code2}{code3} Some more user entered text.

Etc. etc.

What I need to do using ColdFusion is extract the codes within the {} and [] brackets so I can retrieve their descriptions from a database. For example:

{code1} Some user entered text. {code2}{code3} Some more user entered text.

Would become a list similar to:

{code1}|{code2}|{code3}

Normally I could just do something like REMatch but unfortunately I'm stuck doing this on a server running ColdFusion version 4.5 (groan) so my options are limited.

I'm thinking maybe I could do some Replaces on the string to convert it into a pipe delimited list that I can then easily process but I'm not sure if there might be a more straight forward approach? I'm not even really sure what a sensible way to process this using a Replace would be.

Body:
<cfset myString = "{code1} Some user entered text {code2}{code3} More user entered text" />
<cfset myArray = listToArray(myString, "{[") />

<cfloop index="i" from="1" to="#arrayLen(myArray)#">
  <cfset myArray[i] = "{" & listFirst(myArray[i], "}]") & "}" />
</cfloop>

<cfdump var="#myArray#" />
<hr>

<cfset myList = arrayToList(myArray, "|") />
<cfdump var="#myList#" />

TryCF.com Gist:

https://trycf.com/gist/6035ddc5cd3daa81bc0943f1af33323a/lucee5?theme=monokai


问:
Does Azure App Service for Linux support http2?
SSL configuration is handled upstream on Azure App Service.

So running an App Service as Docker container and configuring Nginx for server { listen 443 ssl h2; } is not necessary and in fact, will not render a webpage.

How do I modify the configuration on Azure App Service for Linux to run as http2 protocol when SSL w/ customer domain is setup on the service?

Thanks,

答:
This feature now exists for both Linux and Windows and is in the same section of the Azure Portal for Web App Services.

Go to your Web App Service

Go to Settings

Go to Configuration

Select the tab for General Settings

Beneath Platform Settings, choose the "2.0" from the Http version drop down.

See image for details.