问:
Ensuring that two column values are related in SQL Server
I'm using Microsoft SQL Server 2017 and was curious about how to constrain a specific relationship. I'm having a bit of trouble articulating so I'd prefer to share through an example.

Consider the following hypothetical database.

```<code>Customers
+---------------+
|  Id  |  Name  |
+---------------+
|  1   |  Sam   |
|  2   |  Jane  |
+---------------+
</code>```

```<code>Addresses
+----------------------------------------+
|  Id  |  CustomerId  |  Address         |
+----------------------------------------+
|  1   |  1           |  105 Easy St     |
|  2   |  1           |  9 Gale Blvd     |
|  3   |  2           |  717 Fourth Ave  |
+------+--------------+------------------+
</code>```

```<code>Orders
+-----------------------------------+
|  Id  |  CustomerId  |  AddressId  |
+-----------------------------------+
|  1   |  1           |  1          |
|  2   |  2           |  3          |
|  3   |  1           |  3          |  <--- Invalid Customer/Address Pair
+-----------------------------------+
</code>```

Notice that the final Order links a customer to an address that isn't theirs. I'm looking for a way to prevent this.

(You may ask why I need the CustomerId in the Orders table at all. To be clear, I recognize that the Address already offers me the same information without the possibility of invalid pairs. However, I'd prefer to have an Order flattened such that I don't have to channel through an address to retrieve a customer.)

From the related reading I was able to find, it seems that one method may be to enable a CHECK constraint targeting a User-Defined Function. This User-Defined Function would be something like the following:

```<code>WHERE EXISTS (SELECT 1 FROM Addresses WHERE Id = Order.AddressId AND CustomerId = Order.CustomerId)
</code>```

While I imagine this would work, given the somewhat "generality" of the articles I was able to find, I don't feel entirely confident that this is my best option.

An alternative might be to remove the CustomerId column from the Addresses table entirely, and instead add another table with Id, CustomerId, AddressId. The Order would then reference this Id instead. Again, I don't love the idea of having to channel through an auxiliary table to get a Customer or Address.

Is there a cleaner way to do this? Or am I simply going about this all wrong?

答:
You may ask why I need the CustomerId in the Orders table at all. To be clear, I recognize that the Address already offers me the same information without the possibility of invalid pairs. However, I'd prefer to have an Order flattened such that I don't have to channel through an address to retrieve a customer.

If you face performance problems, the first thing is to create or amend proper indexes. And DBMS are usually good at join operations (with proper indexes). But yes normalization can sometimes help in performance tuning. But it should be a last resort. And if that route is taken, one should really know what one is doing and be very careful not to damage more at the end of a day, that one has gained. I have doubts, that you're out of options here and really need to go that path. You're likely barking up the wrong tree. Therefore I recommend you take the "normal", "sane" way and just drop customerid in orders and create proper indexes.

But if you really insist, you can try to make (id, customerid) a key in addresses (with a unique constraint) and then create a foreign key based on that.

```<code>ALTER TABLE addresses
            ADD UNIQUE (id,
                        customerid);

ALTER TABLE orders
            ADD FOREIGN KEY (addressid,
                             customerid)
                            REFERENCES addresses
                                       (id,
                                        customerid);
</code>```

Body:
I'm using Microsoft SQL Server 2017 and was curious about how to constrain a specific relationship. I'm having a bit of trouble articulating so I'd prefer to share through an example.

Consider the following hypothetical database.

Customers
+---------------+
|  Id  |  Name  |
+---------------+
|  1   |  Sam   |
|  2   |  Jane  |
+---------------+

Addresses
+----------------------------------------+
|  Id  |  CustomerId  |  Address         |
+----------------------------------------+
|  1   |  1           |  105 Easy St     |
|  2   |  1           |  9 Gale Blvd     |
|  3   |  2           |  717 Fourth Ave  |
+------+--------------+------------------+

Orders
+-----------------------------------+
|  Id  |  CustomerId  |  AddressId  |
+-----------------------------------+
|  1   |  1           |  1          |
|  2   |  2           |  3          |
|  3   |  1           |  3          |  <--- Invalid Customer/Address Pair
+-----------------------------------+

Notice that the final Order links a customer to an address that isn't theirs. I'm looking for a way to prevent this.

(You may ask why I need the CustomerId in the Orders table at all. To be clear, I recognize that the Address already offers me the same information without the possibility of invalid pairs. However, I'd prefer to have an Order flattened such that I don't have to channel through an address to retrieve a customer.)

From the related reading I was able to find, it seems that one method may be to enable a CHECK constraint targeting a User-Defined Function. This User-Defined Function would be something like the following:

WHERE EXISTS (SELECT 1 FROM Addresses WHERE Id = Order.AddressId AND CustomerId = Order.CustomerId)

While I imagine this would work, given the somewhat "generality" of the articles I was able to find, I don't feel entirely confident that this is my best option.

An alternative might be to remove the CustomerId column from the Addresses table entirely, and instead add another table with Id, CustomerId, AddressId. The Order would then reference this Id instead. Again, I don't love the idea of having to channel through an auxiliary table to get a Customer or Address.

Is there a cleaner way to do this? Or am I simply going about this all wrong?

Body:
You may ask why I need the CustomerId in the Orders table at all. To be clear, I recognize that the Address already offers me the same information without the possibility of invalid pairs. However, I'd prefer to have an Order flattened such that I don't have to channel through an address to retrieve a customer.

If you face performance problems, the first thing is to create or amend proper indexes. And DBMS are usually good at join operations (with proper indexes). But yes normalization can sometimes help in performance tuning. But it should be a last resort. And if that route is taken, one should really know what one is doing and be very careful not to damage more at the end of a day, that one has gained. I have doubts, that you're out of options here and really need to go that path. You're likely barking up the wrong tree. Therefore I recommend you take the "normal", "sane" way and just drop customerid in orders and create proper indexes.

But if you really insist, you can try to make (id, customerid) a key in addresses (with a unique constraint) and then create a foreign key based on that.

ALTER TABLE addresses
            ADD UNIQUE (id,
                        customerid);

ALTER TABLE orders
            ADD FOREIGN KEY (addressid,
                             customerid)
                            REFERENCES addresses
                                       (id,
                                        customerid);


来源: stackexchange

问:
Qt - Why won't my widgets line up using a vertical layout inside a splitter?
As per the screenshot below, why won't my widgets line up using a vertical layout inside a splitter?

```<code>/********************************************************************************
** Form generated from reading UI file 'test.ui'
**
** Created: Tue Apr 12 16:51:51 2011
**      by: Qt User Interface Compiler version 4.6.2
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/

#ifndef UI_TEST_H
#define UI_TEST_H

#include <QtCore/QVariant>
#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QButtonGroup>
#include <QtGui/QGridLayout>
#include <QtGui/QHeaderView>
#include <QtGui/QLineEdit>
#include <QtGui/QListWidget>
#include <QtGui/QMainWindow>
#include <QtGui/QSplitter>
#include <QtGui/QTreeWidget>
#include <QtGui/QVBoxLayout>
#include <QtGui/QWidget>

QT_BEGIN_NAMESPACE

class Ui_MainWindow
{
public:
    QWidget *centralwidget;
    QGridLayout *gridLayout;
    QSplitter *splitter;
    QTreeWidget *treeWidget;
    QWidget *widget;
    QVBoxLayout *verticalLayout;
    QLineEdit *lineEdit;
    QListWidget *listWidget;

    void setupUi(QMainWindow *MainWindow)
    {
    if (MainWindow->objectName().isEmpty())
        MainWindow->setObjectName(QString::fromUtf8("MainWindow"));
    MainWindow->resize(800, 600);
    centralwidget = new QWidget(MainWindow);
    centralwidget->setObjectName(QString::fromUtf8("centralwidget"));
    gridLayout = new QGridLayout(centralwidget);
    gridLayout->setObjectName(QString::fromUtf8("gridLayout"));
    splitter = new QSplitter(centralwidget);
    splitter->setObjectName(QString::fromUtf8("splitter"));
    splitter->setOrientation(Qt::Horizontal);
    treeWidget = new QTreeWidget(splitter);
    QTreeWidgetItem *__qtreewidgetitem = new QTreeWidgetItem();
    __qtreewidgetitem->setText(0, QString::fromUtf8("1"));
    treeWidget->setHeaderItem(__qtreewidgetitem);
    treeWidget->setObjectName(QString::fromUtf8("treeWidget"));
    splitter->addWidget(treeWidget);
    widget = new QWidget(splitter);
    widget->setObjectName(QString::fromUtf8("widget"));
    verticalLayout = new QVBoxLayout(widget);
    verticalLayout->setObjectName(QString::fromUtf8("verticalLayout"));
    verticalLayout->setContentsMargins(0, 0, 0, 0);
    lineEdit = new QLineEdit(widget);
    lineEdit->setObjectName(QString::fromUtf8("lineEdit"));

    verticalLayout->addWidget(lineEdit);

    listWidget = new QListWidget(widget);
    listWidget->setObjectName(QString::fromUtf8("listWidget"));

    verticalLayout->addWidget(listWidget);

    splitter->addWidget(widget);

    gridLayout->addWidget(splitter, 0, 0, 1, 1);

    MainWindow->setCentralWidget(centralwidget);

    retranslateUi(MainWindow);

    QMetaObject::connectSlotsByName(MainWindow);
    } // setupUi

    void retranslateUi(QMainWindow *MainWindow)
    {
    MainWindow->setWindowTitle(QApplication::translate("MainWindow", "MainWindow", 0, QApplication::UnicodeUTF8));
    } // retranslateUi

};

namespace Ui {
    class MainWindow: public Ui_MainWindow {};
} // namespace Ui

QT_END_NAMESPACE

#endif // UI_TEST_H
</code>```

This is just a dummy ui uploaded here for the purpose of the question. In my real ui design I've tried every imaginable combination, but as soon as I start using splitters, it all goes out of alignment.

答:
I pulled up designer and made your layout without any trouble at all.  As shown in the hierarchy in the top right of my screenshot, I created a line edit and a text edit.  Joined those in a vertical layout.  Created a treeWidget and joined that with the layout in a horizontal splitter.

I was able to get it to look like yours by editing the vertical layout properties so that there was a nonzero layout margin.  But it looks like the generated code is explicitly setting that to zero in yours...

ContentLicense: CC BY-SA 3.0

Body:
As per the screenshot below, why won't my widgets line up using a vertical layout inside a splitter?

/********************************************************************************
** Form generated from reading UI file 'test.ui'
**
** Created: Tue Apr 12 16:51:51 2011
**      by: Qt User Interface Compiler version 4.6.2
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/

#ifndef UI_TEST_H
#define UI_TEST_H

#include <QtCore/QVariant>
#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QButtonGroup>
#include <QtGui/QGridLayout>
#include <QtGui/QHeaderView>
#include <QtGui/QLineEdit>
#include <QtGui/QListWidget>
#include <QtGui/QMainWindow>
#include <QtGui/QSplitter>
#include <QtGui/QTreeWidget>
#include <QtGui/QVBoxLayout>
#include <QtGui/QWidget>

QT_BEGIN_NAMESPACE

class Ui_MainWindow
{
public:
    QWidget *centralwidget;
    QGridLayout *gridLayout;
    QSplitter *splitter;
    QTreeWidget *treeWidget;
    QWidget *widget;
    QVBoxLayout *verticalLayout;
    QLineEdit *lineEdit;
    QListWidget *listWidget;

    void setupUi(QMainWindow *MainWindow)
    {
    if (MainWindow->objectName().isEmpty())
        MainWindow->setObjectName(QString::fromUtf8("MainWindow"));
    MainWindow->resize(800, 600);
    centralwidget = new QWidget(MainWindow);
    centralwidget->setObjectName(QString::fromUtf8("centralwidget"));
    gridLayout = new QGridLayout(centralwidget);
    gridLayout->setObjectName(QString::fromUtf8("gridLayout"));
    splitter = new QSplitter(centralwidget);
    splitter->setObjectName(QString::fromUtf8("splitter"));
    splitter->setOrientation(Qt::Horizontal);
    treeWidget = new QTreeWidget(splitter);
    QTreeWidgetItem *__qtreewidgetitem = new QTreeWidgetItem();
    __qtreewidgetitem->setText(0, QString::fromUtf8("1"));
    treeWidget->setHeaderItem(__qtreewidgetitem);
    treeWidget->setObjectName(QString::fromUtf8("treeWidget"));
    splitter->addWidget(treeWidget);
    widget = new QWidget(splitter);
    widget->setObjectName(QString::fromUtf8("widget"));
    verticalLayout = new QVBoxLayout(widget);
    verticalLayout->setObjectName(QString::fromUtf8("verticalLayout"));
    verticalLayout->setContentsMargins(0, 0, 0, 0);
    lineEdit = new QLineEdit(widget);
    lineEdit->setObjectName(QString::fromUtf8("lineEdit"));

    verticalLayout->addWidget(lineEdit);

    listWidget = new QListWidget(widget);
    listWidget->setObjectName(QString::fromUtf8("listWidget"));

    verticalLayout->addWidget(listWidget);

    splitter->addWidget(widget);

    gridLayout->addWidget(splitter, 0, 0, 1, 1);

    MainWindow->setCentralWidget(centralwidget);

    retranslateUi(MainWindow);

    QMetaObject::connectSlotsByName(MainWindow);
    } // setupUi

    void retranslateUi(QMainWindow *MainWindow)
    {
    MainWindow->setWindowTitle(QApplication::translate("MainWindow", "MainWindow", 0, QApplication::UnicodeUTF8));
    } // retranslateUi

};

namespace Ui {
    class MainWindow: public Ui_MainWindow {};
} // namespace Ui

QT_END_NAMESPACE

#endif // UI_TEST_H

This is just a dummy ui uploaded here for the purpose of the question. In my real ui design I've tried every imaginable combination, but as soon as I start using splitters, it all goes out of alignment.


问:
How can I use activation-group while calling kie api container?
I have been tring to use activation-group  but I don't have any idea how to call activation-group from Api rest ? Please help me how to add activation-group inside of the request below.

```<code>
package com.myteam.arduinodevre2;

//from row number: 1
rule "Row 1 Rulduino"
activation-group "gold"
    dialect "mvel"
    when
        f1 : ArduinoEntity( switchOn == true , voltaj >= 1000 , voltaj < 2000 )
    then
        modify( f1 ) {
                setLightOn( true )
        }
end

//from row number: 2
rule "Row 2 Rulduino"
activation-group "gold"
    dialect "mvel"
    when
        f1 : ArduinoEntity( switchOn == true , voltaj >= 5000.0 , voltaj < 10000.0 )
    then
        modify( f1 ) {
                setLightOn( false )
        }
end

//from row number: 3
rule "Row 3 Rulduino"
activation-group "gold"
    dialect "mvel"
    when
        f1 : ArduinoEntity( switchOn == false )
    then
        modify( f1 ) {
                setLightOn( false )
        }
end

//from row number: 4
rule "Row 4 Rulduino"
activation-group "silver"
    dialect "mvel"
    when
        f1 : ArduinoEntity( switchOn == true , voltaj >= 1.0 , voltaj < 3.0 )
    then
        modify( f1 ) {
                setLightOn( false )
        }
end

</code>```

```<code>
{

  "commands": [
    {
      "insert": {
        "object": {
          "com.myteam.arduinodevre2.ArduinoEntity": {
            "switchOn": true,
            "voltaj": 1100

          }
        },
        "out-identifier": "ArduinoEntity",
        "return-object": true
      }
    },
    {
      "fire-all-rules": "" ,
            "fire-targetgroup": "silver"
    }
  ]
}

</code>```

How can I fire  my target activation-group by using this kinnd of thing ->"fire-all-rules": "silver"  But I cound not find valuable answer by googling.

答:
You don't call an activation group. What you might be referring to is an agenda group. You can set focus on an agenda group and all rules with that agenda group will be eligible for firing.

You can go further and add the activation-group to your rules, which will then cause only one rule in that group to fire.

In order to "call" agenda group from the REST API, you need to set focus like this:

```<code>{
  "commands": [
    {
      "set-focus": "myAgendaGroup"
    },
    {
      "insert": {
        "object": {
          "com.myteam.arduinodevre2.ArduinoEntity": {
            "switchOn": true,
            "voltaj": 1100
          }
        }
      }
    },
    {
      "fire-all-rules": {}
    }
  ]
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have been tring to use activation-group  but I don't have any idea how to call activation-group from Api rest ? Please help me how to add activation-group inside of the request below.

package com.myteam.arduinodevre2;

//from row number: 1
rule "Row 1 Rulduino"
activation-group "gold"
    dialect "mvel"
    when
        f1 : ArduinoEntity( switchOn == true , voltaj >= 1000 , voltaj < 2000 )
    then
        modify( f1 ) {
                setLightOn( true )
        }
end

//from row number: 2
rule "Row 2 Rulduino"
activation-group "gold"
    dialect "mvel"
    when
        f1 : ArduinoEntity( switchOn == true , voltaj >= 5000.0 , voltaj < 10000.0 )
    then
        modify( f1 ) {
                setLightOn( false )
        }
end

//from row number: 3
rule "Row 3 Rulduino"
activation-group "gold"
    dialect "mvel"
    when
        f1 : ArduinoEntity( switchOn == false )
    then
        modify( f1 ) {
                setLightOn( false )
        }
end

//from row number: 4
rule "Row 4 Rulduino"
activation-group "silver"
    dialect "mvel"
    when
        f1 : ArduinoEntity( switchOn == true , voltaj >= 1.0 , voltaj < 3.0 )
    then
        modify( f1 ) {
                setLightOn( false )
        }
end

{

  "commands": [
    {
      "insert": {
        "object": {
          "com.myteam.arduinodevre2.ArduinoEntity": {
            "switchOn": true,
            "voltaj": 1100

          }
        },
        "out-identifier": "ArduinoEntity",
        "return-object": true
      }
    },
    {
      "fire-all-rules": "" ,
            "fire-targetgroup": "silver"
    }
  ]
}

How can I fire  my target activation-group by using this kinnd of thing ->"fire-all-rules": "silver"  But I cound not find valuable answer by googling.

Body:
You don't call an activation group. What you might be referring to is an agenda group. You can set focus on an agenda group and all rules with that agenda group will be eligible for firing.

You can go further and add the activation-group to your rules, which will then cause only one rule in that group to fire.

In order to "call" agenda group from the REST API, you need to set focus like this:

{
  "commands": [
    {
      "set-focus": "myAgendaGroup"
    },
    {
      "insert": {
        "object": {
          "com.myteam.arduinodevre2.ArduinoEntity": {
            "switchOn": true,
            "voltaj": 1100
          }
        }
      }
    },
    {
      "fire-all-rules": {}
    }
  ]
}


问:
How can I draw a black shadow in webkit browsers?
How can I draw a BLACK shadow in webkit browsers with the HTML5 canvas?</p>

答:
On Canvas?

It should be the same as any other browser:

```<code>ctx.shadowColor = "rgba(0, 0, 0, 1)";
</code>```

See an example here:

http://jsfiddle.net/LpvFF/4/

Tested on Safari 5 and Chrome 12

Body:
On Canvas?

It should be the same as any other browser:

ctx.shadowColor = "rgba(0, 0, 0, 1)";

See an example here:

http://jsfiddle.net/LpvFF/4/

Tested on Safari 5 and Chrome 12


问:
IIS7 folder permissions for web application
I am using windows authentication without impersonation on my company's intranet website with IIS7.

Under IIS7, what account is used to access the folder which contains my web app using these settings?

Would it be IIS_IUSRS? Or NETWORK SERVICE? Or another I don't know about?

答:
Worked for me in 30 seconds, short and sweet:

In IIS Manager (run inetmgr)

Go to ApplicationPool -> Advanced Settings

Set ApplicationPoolIdentity to NetworkService

Go to the file, right click properties, go to security, click edit, click add, enter Network Service (with space, then click 'check names'), and give full control (or just whatever permissions you need)

ContentLicense: CC BY-SA 2.5


问:
Variable not updating in score tracking system for ios app
I programmed a variable to track scores in a mini-game but it is not reflecting the updated value after some code is executed.

I'm making a basic quiz mini-game which is embedded in an iOS app. It operates in an independent view controller and does not interface with any other section of the app. My code is giving no errors, but when I try to set a UILabel to the variable's value it reflects no change...

```<code>@IBOutlet weak var imgItemImage: UIImageView!
@IBOutlet weak var lblItemName: UILabel!
@IBOutlet weak var lblScore: UILabel!

@IBAction func btnRedBin(_ sender: Any) {
    trackScore(binChoice: "red")
}

@IBAction func btnYellowBin(_ sender: Any) {
    trackScore(binChoice: "yellow")
}

@IBAction func btnGreenBin(_ sender: Any) {
    trackScore(binChoice: "green")
}

var trashList:[String] = ["Can", "Brick", "Sandwich"]
var itemChoice:Int = 0
var score:Int = 0
var gameRound:Int = 0

func itemChange() {
    if gameRound <= 3 {
        itemChoice = Int.random(in: 0...((trashList.count)-1))
        lblItemName.text = trashList[itemChoice]
        imgItemImage.image = UIImage(named: (trashList[itemChoice]))
    } else {
        lblItemName.text = "You scored \(score) points!"
    }
    gameRound += 1
    lblScore.text = "\(score)"
}

func trackScore(binChoice:String){
    switch trashList{
    case ["Can"]:
        if binChoice == "red"{
            score = score - 1
        } else if binChoice == "yellow" {
            score = score + 10
        } else {
            score = score - 5
        }

    case ["Brick"]:
        if binChoice == "red"{
            score = score + 10
        } else if binChoice == "yellow" {
            score = score - 1
        } else {
            score = score - 5
        }

    case ["Sandwich"]:
        if binChoice == "red"{
            score = score + 10
        } else if binChoice == "yellow" {
            score = score - 1
        } else {
            score = score - 5
        }
    default:
        break
    }
    trashList.remove(at: itemChoice)
    itemChange()
}
</code>```

I expect the variable "score" to change when one of the buttons (actions) is pressed. But when I do so and try to check by setting a UILabel "lblScore" to its value I always get 0.

答:
This is how your trackScore function should look like </p>

```<code>func trackScore(binChoice:String){
    switch binChoice:String{
    case "Can":
        if binChoice == "red"{
            score = score - 1
        } else if binChoice == "yellow" {
            score = score + 10
        } else {
            score = score - 5
        }

    case "Brick":
        if binChoice == "red"{
            score = score + 10
        } else if binChoice == "yellow" {
            score = score - 1
        } else {
            score = score - 5
        }

    case "Sandwich":
        if binChoice == "red"{
            score = score + 10
        } else if binChoice == "yellow" {
            score = score - 1
        } else {
            score = score - 5
        }
    default:
        break
    }
    trashList.remove(at: itemChoice)
    itemChange()
}
</code>```

Body:
I programmed a variable to track scores in a mini-game but it is not reflecting the updated value after some code is executed.

I'm making a basic quiz mini-game which is embedded in an iOS app. It operates in an independent view controller and does not interface with any other section of the app. My code is giving no errors, but when I try to set a UILabel to the variable's value it reflects no change...

@IBOutlet weak var imgItemImage: UIImageView!
@IBOutlet weak var lblItemName: UILabel!
@IBOutlet weak var lblScore: UILabel!

@IBAction func btnRedBin(_ sender: Any) {
    trackScore(binChoice: "red")
}

@IBAction func btnYellowBin(_ sender: Any) {
    trackScore(binChoice: "yellow")
}

@IBAction func btnGreenBin(_ sender: Any) {
    trackScore(binChoice: "green")
}

var trashList:[String] = ["Can", "Brick", "Sandwich"]
var itemChoice:Int = 0
var score:Int = 0
var gameRound:Int = 0

func itemChange() {
    if gameRound <= 3 {
        itemChoice = Int.random(in: 0...((trashList.count)-1))
        lblItemName.text = trashList[itemChoice]
        imgItemImage.image = UIImage(named: (trashList[itemChoice]))
    } else {
        lblItemName.text = "You scored \(score) points!"
    }
    gameRound += 1
    lblScore.text = "\(score)"
}

func trackScore(binChoice:String){
    switch trashList{
    case ["Can"]:
        if binChoice == "red"{
            score = score - 1
        } else if binChoice == "yellow" {
            score = score + 10
        } else {
            score = score - 5
        }

    case ["Brick"]:
        if binChoice == "red"{
            score = score + 10
        } else if binChoice == "yellow" {
            score = score - 1
        } else {
            score = score - 5
        }

    case ["Sandwich"]:
        if binChoice == "red"{
            score = score + 10
        } else if binChoice == "yellow" {
            score = score - 1
        } else {
            score = score - 5
        }
    default:
        break
    }
    trashList.remove(at: itemChoice)
    itemChange()
}

I expect the variable "score" to change when one of the buttons (actions) is pressed. But when I do so and try to check by setting a UILabel "lblScore" to its value I always get 0.

Body:
This is how your trackScore function should look like

func trackScore(binChoice:String){
    switch binChoice:String{
    case "Can":
        if binChoice == "red"{
            score = score - 1
        } else if binChoice == "yellow" {
            score = score + 10
        } else {
            score = score - 5
        }

    case "Brick":
        if binChoice == "red"{
            score = score + 10
        } else if binChoice == "yellow" {
            score = score - 1
        } else {
            score = score - 5
        }

    case "Sandwich":
        if binChoice == "red"{
            score = score + 10
        } else if binChoice == "yellow" {
            score = score - 1
        } else {
            score = score - 5
        }
    default:
        break
    }
    trashList.remove(at: itemChoice)
    itemChange()
}


问:
Can autoprefixer solve the issue of CSS variables for Internet Explorer?
I am using css variables in my angular7 application. Everything works fine on other browsers. But IE is not supporting css variables. Is there a way to make it work on IE. Can Autoprefixer do this?</p>

```<code>color: var(--primary, #7F583F);
</code>```

答:
According to caniuse.com, of current browsers only IE, Edge (older versions) and Opera Mini do not support CSS variables. This polyfil appears to work on all three really well.

This is an attempt at a very basic CSS variables (custom properties) polyfil. In reality this is more of a partial polyfill as it will not cover variables inside of variables, DOM scoping or anything else "fancy". Just taking variables declared anywhere in the CSS and then re-parsing the CSS for var() statements and replacing them in browsers that don't natively support CSS variables.

I try to test this polyfil in IE 11 and looks like it is working with it.

/*!
 * css-var-polyfill.js - v1.0.0
 *
 * Copyright (c) 2018 Aaron Barker <http://aaronbarker.net>
 * Released under the MIT license
 *
 * Date: 2018-03-09
 */
let cssVarPoly = {
  init: function() {
    // first lets see if the browser supports CSS variables
    // No version of IE supports window.CSS.supports, so if that isn't supported in the first place we know CSS variables is not supported
    // Edge supports supports, so check for actual variable support
    if (window.CSS && window.CSS.supports && window.CSS.supports('(--foo: red)')) {
      // this browser does support variables, abort
      console.log('your browser supports CSS variables, aborting and letting the native support handle things.');
      return;
    } else {
      // edge barfs on console statements if the console is not open... lame!
      console.log('no support for you! polyfill all (some of) the things!!');
      document.querySelector('body').classList.add('cssvars-polyfilled');
    }

    cssVarPoly.ratifiedVars = {};
    cssVarPoly.varsByBlock = {};
    cssVarPoly.oldCSS = {};

    // start things off
    cssVarPoly.findCSS();
    cssVarPoly.updateCSS();
  },

  // find all the css blocks, save off the content, and look for variables
  findCSS: function() {
    let styleBlocks = document.querySelectorAll('style:not(.inserted),link[rel="stylesheet"]');

    // we need to track the order of the style/link elements when we save off the CSS, set a counter
    let counter = 1;

    // loop through all CSS blocks looking for CSS variables being set
    [].forEach.call(styleBlocks, function(block) {
      // console.log(block.nodeName);
      let theCSS;
      if (block.nodeName === 'STYLE') {
        // console.log("style");
        theCSS = block.innerHTML;
        cssVarPoly.findSetters(theCSS, counter);
      } else if (block.nodeName === 'LINK') {
        // console.log("link");
        cssVarPoly.getLink(block.getAttribute('href'), counter, function(counter, request) {
          cssVarPoly.findSetters(request.responseText, counter);
          cssVarPoly.oldCSS[counter] = request.responseText;
          cssVarPoly.updateCSS();
        });
        theCSS = '';
      }
      // save off the CSS to parse through again later. the value may be empty for links that are waiting for their ajax return, but this will maintain the order
      cssVarPoly.oldCSS[counter] = theCSS;
      counter++;
    });
  },

  // find all the "--variable: value" matches in a provided block of CSS and add them to the master list
  findSetters: function(theCSS, counter) {
    // console.log(theCSS);
    cssVarPoly.varsByBlock[counter] = theCSS.match(/(--.+:.+;)/g) || [];
  },

  // run through all the CSS blocks to update the variables and then inject on the page
  updateCSS: function() {
    // first lets loop through all the variables to make sure later vars trump earlier vars
    cssVarPoly.ratifySetters(cssVarPoly.varsByBlock);

    // loop through the css blocks (styles and links)
    for (let curCSSID in cssVarPoly.oldCSS) {
      // console.log("curCSS:",oldCSS[curCSSID]);
      let newCSS = cssVarPoly.replaceGetters(cssVarPoly.oldCSS[curCSSID], cssVarPoly.ratifiedVars);
      // put it back into the page
      // first check to see if this block exists already
      if (document.querySelector('#inserted' + curCSSID)) {
        // console.log("updating")
        document.querySelector('#inserted' + curCSSID).innerHTML = newCSS;
      } else {
        // console.log("adding");
        var style = document.createElement('style');
        style.type = 'text/css';
        style.innerHTML = newCSS;
        style.classList.add('inserted');
        style.id = 'inserted' + curCSSID;
        document.getElementsByTagName('head')[0].appendChild(style);
      }
    };
  },

  // parse a provided block of CSS looking for a provided list of variables and replace the --var-name with the correct value
  replaceGetters: function(curCSS, varList) {
    // console.log(varList);
    for (let theVar in varList) {
      // console.log(theVar);
      // match the variable with the actual variable name
      let getterRegex = new RegExp('var\\(\\s*' + theVar + '\\s*\\)', 'g');
      // console.log(getterRegex);
      // console.log(curCSS);
      curCSS = curCSS.replace(getterRegex, varList[theVar]);

      // now check for any getters that are left that have fallbacks
      let getterRegex2 = new RegExp('var\\(\\s*.+\\s*,\\s*(.+)\\)', 'g');
      // console.log(getterRegex);
      // console.log(curCSS);
      let matches = curCSS.match(getterRegex2);
      if (matches) {
        // console.log("matches",matches);
        matches.forEach(function(match) {
          // console.log(match.match(/var\(.+,\s*(.+)\)/))
          // find the fallback within the getter
          curCSS = curCSS.replace(match, match.match(/var\(.+,\s*(.+)\)/)[1]);
        });

      }

      // curCSS = curCSS.replace(getterRegex2,varList[theVar]);
    };
    // console.log(curCSS);
    return curCSS;
  },

  // determine the css variable name value pair and track the latest
  ratifySetters: function(varList) {
    // console.log("varList:",varList);
    // loop through each block in order, to maintain order specificity
    for (let curBlock in varList) {
      let curVars = varList[curBlock];
      // console.log("curVars:",curVars);
      // loop through each var in the block
      curVars.forEach(function(theVar) {
        // console.log(theVar);
        // split on the name value pair separator
        let matches = theVar.split(/:\s*/);
        // console.log(matches);
        // put it in an object based on the varName. Each time we do this it will override a previous use and so will always have the last set be the winner
        // 0 = the name, 1 = the value, strip off the ; if it is there
        cssVarPoly.ratifiedVars[matches[0]] = matches[1].replace(/;/, '');
      });
    };
    // console.log(ratifiedVars);
  },

  // get the CSS file (same domain for now)
  getLink: function(url, counter, success) {
    var request = new XMLHttpRequest();
    request.open('GET', url, true);
    request.overrideMimeType('text/css;');
    request.onload = function() {
      if (request.status >= 200 && request.status < 400) {
        // Success!
        // console.log(request.responseText);
        if (typeof success === 'function') {
          success(counter, request);
        }
      } else {
        // We reached our target server, but it returned an error
        console.warn('an error was returned from:', url);
      }
    };

    request.onerror = function() {
      // There was a connection error of some sort
      console.warn('we could not get anything from:', url);
    };

    request.send();
  }
};

cssVarPoly.init();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>:root {
  --externalcolor: red;
  --samename: orange;
  --samename: #0f0;
  --foo: green;
  --FOO: #0f0;
  --halfsuccess: orange;
  --success: green;
  --success2: #0f0;
}
html {
  font-family: var(--fontsans);
}
.success {
  color: green;
}

.fail {
  color: red;
}

span {
  display: inline-block;
  margin: 5px;
}

.samename {
  color: var(--samename);
}

.demo1 {
  color: #f00;
  color: var(--success);
}

.demo2 {
  color: #f00;
  color: var( --success2);
}

.demo3 {
  color: #f00;
  color: var(--halfsuccess);
  color: var(--success);
}

.demo4 {
  color: red;
  border-color: #f00;
}

.inlineoverlink {
  color: #f00;
}

p {
  padding: var(--spacing-l);
}

.lower {
  color: var(--foo);
}

.upper {
  color: var(--FOO);
}

.externalcolor {
  color: var(--externalcolor);
}

.fallback {
  color: #f00;
  color: var(--wrongname, green);
}

// for the top documentation
.supports {
  color: green;
  .no {
    display:none;
  }
}
.showforpolyfill {
  display:none;
}

.cssvars-polyfilled {
  .supports {
    color: red;
    .no {
      display:inline;
    }
  }
  .showforpolyfill {
    display:inline;
  }
  .hideforpolyfill {
    display:none;
  }
}
.hide,
.hide-the-docs .documentation {
  display:none;
}
/* declare some font-family stuff at bottom of file to reflect on stuff above it*/

:root {
  --fontsans: arial;
}</code>```

CSS Variables Polyfill

This is now managed (and available for PRs) at https://github.com/aaronbarker/css-variables-polyfill.

      This is an attempt at a very basic CSS variables (custom properties) polyfil. In reality this is more of a partial polyfill as it will not cover variables inside of variables, DOM scoping or anything else "fancy". Just taking variables declared anywhere in the CSS and
      then re-parsing the CSS for var() statements and replacing them in browsers that don't natively support CSS variables.

According to caniuse.com, of current browsers only IE, Edge and Opera Mini do not support CSS variables. This polyfil appears to work on all three really well. I don't see why this wouldn't work on older browsers as well, but I haven't been able to test it on them yet.

As far as we can tell your browser does not support native CSS variables. That means if you see green tests results below, it is thanks to the polyfill :). All the green test results below are actually native CSS Variable support.  Good job using a good browser :)

Does this work on externally CSS files?

Yes!

Even ones loaded from another domain?

To go across domain, CSS needs to be served up with Access-Control-Allow-Origin:* headers.

  Toggle documentation (for Opera Mini vs Codepen issue)

Tests

On mosts tests (unless otherwise noted) success will be green text. We start with a color:red; and then override it with a color:var(--success); (or similar) which is green.

declare same variable over and over

no whitespace on var() calls

whitespace on var() calls

Multiple variables in same call. orange means first var worked, green var worked

orange if link won, green if style after link won

--foo: lowercase foo

--FOO: uppercase FOO

uses fallback --var(--wrongname, green)

css declared in an @import - not polyfilled yet. Identfied with a suggested fix, but will require a bit of a re-write (to use document.styleSheets), so haven't done it yet.

Tests on external, cross-domain file

Edge appears to be working well on Edge 13. Edge 12 was having some problems.

Opera mini seems to work well too. This demo fails because not all the page is displayed, but I think that is a codepen issue, not a polyfill issue.  When the upper documentation is removed, all tests display well.

IE 11 seems to do fine.

Gets stuff from external .css file. Should start red and change to green on LINK load. border proves the CSS loaded, missing colors means script didn't get parsed and reinserted

--externalcolor: should start red and change to green on LINK load

uses fallback. should be green

Another set of text under the test for Opera Mini testing.

  ```

Testing result:

References:

(1) Codepen example link

(2) aaronbarker/css-variables-polyfill

Body:
I am using css variables in my angular7 application. Everything works fine on other browsers. But IE is not supporting css variables. Is there a way to make it work on IE. Can Autoprefixer do this?

color: var(--primary, #7F583F);

Body:
According to caniuse.com, of current browsers only IE, Edge (older versions) and Opera Mini do not support CSS variables. This polyfil appears to work on all three really well.

This is an attempt at a very basic CSS variables (custom properties) polyfil. In reality this is more of a partial polyfill as it will not cover variables inside of variables, DOM scoping or anything else "fancy". Just taking variables declared anywhere in the CSS and then re-parsing the CSS for var() statements and replacing them in browsers that don't natively support CSS variables.

I try to test this polyfil in IE 11 and looks like it is working with it.

/*!
 * css-var-polyfill.js - v1.0.0
 *
 * Copyright (c) 2018 Aaron Barker <http://aaronbarker.net>
 * Released under the MIT license
 *
 * Date: 2018-03-09
 */
let cssVarPoly = {
  init: function() {
    // first lets see if the browser supports CSS variables
    // No version of IE supports window.CSS.supports, so if that isn't supported in the first place we know CSS variables is not supported
    // Edge supports supports, so check for actual variable support
    if (window.CSS && window.CSS.supports && window.CSS.supports('(--foo: red)')) {
      // this browser does support variables, abort
      console.log('your browser supports CSS variables, aborting and letting the native support handle things.');
      return;
    } else {
      // edge barfs on console statements if the console is not open... lame!
      console.log('no support for you! polyfill all (some of) the things!!');
      document.querySelector('body').classList.add('cssvars-polyfilled');
    }

    cssVarPoly.ratifiedVars = {};
    cssVarPoly.varsByBlock = {};
    cssVarPoly.oldCSS = {};

    // start things off
    cssVarPoly.findCSS();
    cssVarPoly.updateCSS();
  },

  // find all the css blocks, save off the content, and look for variables
  findCSS: function() {
    let styleBlocks = document.querySelectorAll('style:not(.inserted),link[rel="stylesheet"]');

    // we need to track the order of the style/link elements when we save off the CSS, set a counter
    let counter = 1;

    // loop through all CSS blocks looking for CSS variables being set
    [].forEach.call(styleBlocks, function(block) {
      // console.log(block.nodeName);
      let theCSS;
      if (block.nodeName === 'STYLE') {
        // console.log("style");
        theCSS = block.innerHTML;
        cssVarPoly.findSetters(theCSS, counter);
      } else if (block.nodeName === 'LINK') {
        // console.log("link");
        cssVarPoly.getLink(block.getAttribute('href'), counter, function(counter, request) {
          cssVarPoly.findSetters(request.responseText, counter);
          cssVarPoly.oldCSS[counter] = request.responseText;
          cssVarPoly.updateCSS();
        });
        theCSS = '';
      }
      // save off the CSS to parse through again later. the value may be empty for links that are waiting for their ajax return, but this will maintain the order
      cssVarPoly.oldCSS[counter] = theCSS;
      counter++;
    });
  },

  // find all the "--variable: value" matches in a provided block of CSS and add them to the master list
  findSetters: function(theCSS, counter) {
    // console.log(theCSS);
    cssVarPoly.varsByBlock[counter] = theCSS.match(/(--.+:.+;)/g) || [];
  },

  // run through all the CSS blocks to update the variables and then inject on the page
  updateCSS: function() {
    // first lets loop through all the variables to make sure later vars trump earlier vars
    cssVarPoly.ratifySetters(cssVarPoly.varsByBlock);

    // loop through the css blocks (styles and links)
    for (let curCSSID in cssVarPoly.oldCSS) {
      // console.log("curCSS:",oldCSS[curCSSID]);
      let newCSS = cssVarPoly.replaceGetters(cssVarPoly.oldCSS[curCSSID], cssVarPoly.ratifiedVars);
      // put it back into the page
      // first check to see if this block exists already
      if (document.querySelector('#inserted' + curCSSID)) {
        // console.log("updating")
        document.querySelector('#inserted' + curCSSID).innerHTML = newCSS;
      } else {
        // console.log("adding");
        var style = document.createElement('style');
        style.type = 'text/css';
        style.innerHTML = newCSS;
        style.classList.add('inserted');
        style.id = 'inserted' + curCSSID;
        document.getElementsByTagName('head')[0].appendChild(style);
      }
    };
  },

  // parse a provided block of CSS looking for a provided list of variables and replace the --var-name with the correct value
  replaceGetters: function(curCSS, varList) {
    // console.log(varList);
    for (let theVar in varList) {
      // console.log(theVar);
      // match the variable with the actual variable name
      let getterRegex = new RegExp('var\\(\\s*' + theVar + '\\s*\\)', 'g');
      // console.log(getterRegex);
      // console.log(curCSS);
      curCSS = curCSS.replace(getterRegex, varList[theVar]);

      // now check for any getters that are left that have fallbacks
      let getterRegex2 = new RegExp('var\\(\\s*.+\\s*,\\s*(.+)\\)', 'g');
      // console.log(getterRegex);
      // console.log(curCSS);
      let matches = curCSS.match(getterRegex2);
      if (matches) {
        // console.log("matches",matches);
        matches.forEach(function(match) {
          // console.log(match.match(/var\(.+,\s*(.+)\)/))
          // find the fallback within the getter
          curCSS = curCSS.replace(match, match.match(/var\(.+,\s*(.+)\)/)[1]);
        });

      }

      // curCSS = curCSS.replace(getterRegex2,varList[theVar]);
    };
    // console.log(curCSS);
    return curCSS;
  },

  // determine the css variable name value pair and track the latest
  ratifySetters: function(varList) {
    // console.log("varList:",varList);
    // loop through each block in order, to maintain order specificity
    for (let curBlock in varList) {
      let curVars = varList[curBlock];
      // console.log("curVars:",curVars);
      // loop through each var in the block
      curVars.forEach(function(theVar) {
        // console.log(theVar);
        // split on the name value pair separator
        let matches = theVar.split(/:\s*/);
        // console.log(matches);
        // put it in an object based on the varName. Each time we do this it will override a previous use and so will always have the last set be the winner
        // 0 = the name, 1 = the value, strip off the ; if it is there
        cssVarPoly.ratifiedVars[matches[0]] = matches[1].replace(/;/, '');
      });
    };
    // console.log(ratifiedVars);
  },

  // get the CSS file (same domain for now)
  getLink: function(url, counter, success) {
    var request = new XMLHttpRequest();
    request.open('GET', url, true);
    request.overrideMimeType('text/css;');
    request.onload = function() {
      if (request.status >= 200 && request.status < 400) {
        // Success!
        // console.log(request.responseText);
        if (typeof success === 'function') {
          success(counter, request);
        }
      } else {
        // We reached our target server, but it returned an error
        console.warn('an error was returned from:', url);
      }
    };

    request.onerror = function() {
      // There was a connection error of some sort
      console.warn('we could not get anything from:', url);
    };

    request.send();
  }
};

cssVarPoly.init();

:root {
  --externalcolor: red;
  --samename: orange;
  --samename: #0f0;
  --foo: green;
  --FOO: #0f0;
  --halfsuccess: orange;
  --success: green;
  --success2: #0f0;
}
html {
  font-family: var(--fontsans);
}
.success {
  color: green;
}

.fail {
  color: red;
}

span {
  display: inline-block;
  margin: 5px;
}

.samename {
  color: var(--samename);
}

.demo1 {
  color: #f00;
  color: var(--success);
}

.demo2 {
  color: #f00;
  color: var( --success2);
}

.demo3 {
  color: #f00;
  color: var(--halfsuccess);
  color: var(--success);
}

.demo4 {
  color: red;
  border-color: #f00;
}

.inlineoverlink {
  color: #f00;
}

p {
  padding: var(--spacing-l);
}

.lower {
  color: var(--foo);
}

.upper {
  color: var(--FOO);
}

.externalcolor {
  color: var(--externalcolor);
}

.fallback {
  color: #f00;
  color: var(--wrongname, green);
}

// for the top documentation
.supports {
  color: green;
  .no {
    display:none;
  }
}
.showforpolyfill {
  display:none;
}

.cssvars-polyfilled {
  .supports {
    color: red;
    .no {
      display:inline;
    }
  }
  .showforpolyfill {
    display:inline;
  }
  .hideforpolyfill {
    display:none;
  }
}
.hide,
.hide-the-docs .documentation {
  display:none;
}
/* declare some font-family stuff at bottom of file to reflect on stuff above it*/

:root {
  --fontsans: arial;
}

<!-- Copy below for codepen update -->
    <h1>CSS Variables Polyfill</h1>
    <p>This is now managed (and available for PRs) at <a href="https://github.com/aaronbarker/css-variables-polyfill">https://github.com/aaronbarker/css-variables-polyfill</a>.</p>
    <p>
      This is an attempt at a very basic <a href="https://drafts.csswg.org/css-variables/">CSS variables (custom properties)</a> polyfil. In reality this is more of a <em>partial</em> polyfill as it will not cover variables inside of variables, DOM scoping or anything else "fancy". Just taking variables declared anywhere in the CSS and
      then re-parsing the CSS for var() statements and replacing them in browsers that don't natively support CSS variables.
    </p>
    <p>According to <a href="http://caniuse.com/#feat=css-variables">caniuse.com</a>, of current browsers only IE, Edge and Opera Mini do not support CSS variables. This polyfil appears to work on all three really well. I don't see why this wouldn't work on older browsers as well, but I haven't been able to test it on them yet.</p>

    <p>As far as we can tell your browser <span class="supports">does <span class="no">not</span> support</span> native CSS variables. <span class="showforpolyfill">That means if you see green tests results below, it is thanks to the polyfill :).</span> <span class="hideforpolyfill">All the green test results below are actually native CSS Variable support.  Good job using a good browser :)</span></p>

    <h3>Does this work on externally CSS files?</h3>
    <p>Yes!</p>
    <h3>Even ones loaded from another domain?</h3>
    <p>To go across domain, CSS needs to be served up with <code>Access-Control-Allow-Origin:*</code> headers.</p>

  </div>
  <a href="#d" class="hide-docs">Toggle documentation</a> (for Opera Mini vs Codepen issue)
  <style>
    :root {
      --newcolor: #0f0;
    }

    .inlineoverlink {
      color: var(--success2);
    }
  </style>
  <h2>Tests</h2>
  <p>On mosts tests (unless otherwise noted) success will be green text. We start with a <code>color:red;</code> and then override it with a <code>color:var(--success);</code> (or similar) which is green.</p>
  <ul>
    <li><span class="samename">declare same variable over and over</span></li>
    <li><span class="demo1">no whitespace on var() calls</span></li>
    <li><span class="demo2">whitespace on var() calls</span></li>
    <li><span class="demo3">Multiple variables in same call. orange means first var worked, green var worked</span></li>
    <li><span class="inlineoverlink">orange if link won, green if style after link won</span></li>
    <li><span class="lower">--foo: lowercase foo</span></li>
    <li><span class="upper">--FOO: uppercase FOO</span></li>
    <li><span class="fallback">uses fallback <code>--var(--wrongname, green)</code></span></li>
    <li><span class="demo-import">css declared in an <code>@import</code></span> - not polyfilled yet. <a href="https://gist.github.com/stramel/91d05253f801f771da38b3bc7d3c765f#gistcomment-2258818">Identfied with a suggested fix</a>, but will require a bit of a re-write (to use document.styleSheets), so haven't done it yet.</li>
  </ul>

  <h2>Tests on external, cross-domain file</h2>
  <div class="documentation">
    <p><strong>Edge</strong> appears to be working well on Edge 13. Edge 12 was having some problems.</p>
    <p><strong>Opera mini</strong> seems to work well too. This demo fails because not all the page is displayed, but I think that is a codepen issue, not a polyfill issue.  When the upper documentation is removed, all tests display well.</p>
    <p><strong>IE 11</strong> seems to do fine.</p>
  </div>

  <ul>
    <li><span class="demo4">Gets stuff from external .css file. Should start red and change to green on LINK load. border proves the CSS loaded, missing colors means script didn't get parsed and reinserted</span></li>
    <li><span class="externalcolor">--externalcolor: should start red and change to green on LINK load</span></li>
    <li><span class="externalfallback">uses fallback. should be green</span></li>
  </ul>

  <p>Another set of text under the test for Opera Mini testing.</p>
  <!-- Copy above for codepen update -->

Testing result:

References:

(1) Codepen example link

(2) aaronbarker/css-variables-polyfill


问:
Cassandra datastax | TimeoutException
I have a problem with cassandra I have the following error.
I link a picture

Code syntaxe :

```<code> public function find($db_table = null, $db_id = null) {
        $filter = "";
        $return = array();

        $cluster = $this->cluster();
        $session = $cluster->connect($this->keyspace);

        if(isset($db_table)) {
            $filter .= " WHERE db_table like '%".$db_table."%' ";

            if($db_id != null) {
                $filter .= " AND db_id = '".$db_id."' ALLOW FILTERING";
            }
        }

        $query  = new Cassandra\SimpleStatement("SELECT * FROM ".$this->keyspace.".log $filter;");
        $result = $session->executeAsync($query);
        $rows   = $result->get();
</code>```

Cassandra Error picture

答:
using "LIKE" on cassandra i dont think so :(

your query :(  try do something more clean instead use  ".$db_table." do the properly bind  use . ? and then inside your exec(query,['value'])

what do your mean ? with SELECT * FROM ".$this->keyspace.".log
this is not a query ! if you use this in php, the syntax definitely this is completely wrong.
you wrote
SELECT * FROM keyspace_name.log WHERE table like 'wherever' and id = 'something' :(
and worse select ALL

this never gonna happen

u use $this for invoke your cluster from where ? did this come from ?

ok i can enumerate 10 different reasons to your code doesn't work, but this is not my goal i want help u so just try something simple.

____ good_____

```<code><?

$cluster   = Cassandra::cluster()
               ->withContactPoints('127.0.0.1')
               ->build();
$session   = $cluster->connect("your_k_space");

$table_list = $session->execute("SELECT table_name FROM system_schema.tables WHERE keyspace_name = 'your_k_space'");

if (in_array($db_table, $table_list)) {
   $options = array('arguments' => [$db_table,$db_id]);
    $result = $session->execute("SELECT * FROM ? WHERE db_id = ?  ALLOW FILTERING",$options);
    foreach ($result as $key => $value) print_r($value);

}else{
    die('table not found');
}
</code>```

Title: Cassandra datastax | TimeoutException

Body:
I have a problem with cassandra I have the following error.
I link a picture

Code syntaxe :

 public function find($db_table = null, $db_id = null) {
        $filter = "";
        $return = array();

        $cluster = $this->cluster();
        $session = $cluster->connect($this->keyspace);

        if(isset($db_table)) {
            $filter .= " WHERE db_table like '%".$db_table."%' ";

            if($db_id != null) {
                $filter .= " AND db_id = '".$db_id."' ALLOW FILTERING";
            }
        }

        $query  = new Cassandra\SimpleStatement("SELECT * FROM ".$this->keyspace.".log $filter;");
        $result = $session->executeAsync($query);
        $rows   = $result->get();

Cassandra Error picture

Body:
using "LIKE" on cassandra i dont think so :(

your query :(  try do something more clean instead use  ".$db_table." do the properly bind  use . ? and then inside your exec(query,['value'])

what do your mean ? with SELECT * FROM ".$this->keyspace.".log
this is not a query ! if you use this in php, the syntax definitely this is completely wrong.
you wrote
SELECT * FROM keyspace_name.log WHERE table like 'wherever' and id = 'something' :(
and worse select ALL

this never gonna happen

u use $this for invoke your cluster from where ? did this come from ?

ok i can enumerate 10 different reasons to your code doesn't work, but this is not my goal i want help u so just try something simple.

____ good_____

<?

$cluster   = Cassandra::cluster()
               ->withContactPoints('127.0.0.1')
               ->build();
$session   = $cluster->connect("your_k_space");

$table_list = $session->execute("SELECT table_name FROM system_schema.tables WHERE keyspace_name = 'your_k_space'");

if (in_array($db_table, $table_list)) {
   $options = array('arguments' => [$db_table,$db_id]);
    $result = $session->execute("SELECT * FROM ? WHERE db_id = ?  ALLOW FILTERING",$options);
    foreach ($result as $key => $value) print_r($value);

}else{
    die('table not found');
}


问:
Is there any inbuilt function in C to check for special characters (like space and tab) just like isdigit() function
Wanted to know if there is any inbuilt function in C to check for special characters like space, tab just like the isdigit() function?

答:
Look up and learn the functions defined by the C11 standard in the §7.4 Character handling <ctype.h> functions.

The isspace() function looks for a fairly general set of white space characters:

```<code>' ', '\t', '\r', '\f', '\n', '\v'
</code>```

The isblank() function looks for the set you want:

```<code>' ', '\t'
</code>```

To some extent, the POSIX variants are locale dependent — the POSIX specifications for isspace() and isblank() are less emphatic about which characters are matched, but disclaim conflict with the C standard, so in the C locale, the behaviour is as required by the C standard.

Body:
Look up and learn the functions defined by the C11 standard in the §7.4 Character handling <ctype.h> functions.

The isspace() function looks for a fairly general set of white space characters:

' ', '\t', '\r', '\f', '\n', '\v'

The isblank() function looks for the set you want:

' ', '\t'

To some extent, the POSIX variants are locale dependent — the POSIX specifications for isspace() and isblank() are less emphatic about which characters are matched, but disclaim conflict with the C standard, so in the C locale, the behaviour is as required by the C standard.


问:
Why does my ASP.NET webpage throw custom 404 error with certain file extensions
So, I have a folder on my server such like this:

You can access this resources by the URL:

Image:

Text:

But the kmz, instead of opening the file (maybe like the text in the xml, I'm not expecting to visualize it) it returns a strange 404:

Is there any way of allowing all files to be accessed without an error?
Thank you very much.

答:
As far as I know, if you wants to access the kmz file in the browser, you will face 404.3 error.

Error details:

```<code>The page you are requesting cannot be served because of the extension configuration. If the page is a script, add a handler. If the file should be downloaded, add a MIME map.
</code>```

To solve this issue, you should add the MIME map for kmz file.

I suggest you could add below config file into the web.confil, then it will work well.

```<code>  <system.webServer>
    <staticContent>
      <remove fileExtension=".kml" />
      <mimeMap fileExtension=".kml" mimeType="application/vnd.google-earth.kml+xml" />
      <remove fileExtension=".kmz" />
      <mimeMap fileExtension=".kmz" mimeType="application/vnd.google-earth.kmz" />
    </staticContent>
  </system.webServer>
</code>```

Body:
As far as I know, if you wants to access the kmz file in the browser, you will face 404.3 error.

Error details:

The page you are requesting cannot be served because of the extension configuration. If the page is a script, add a handler. If the file should be downloaded, add a MIME map.

To solve this issue, you should add the MIME map for kmz file.

I suggest you could add below config file into the web.confil, then it will work well.

  <system.webServer>
    <staticContent>
      <remove fileExtension=".kml" />
      <mimeMap fileExtension=".kml" mimeType="application/vnd.google-earth.kml+xml" />
      <remove fileExtension=".kmz" />
      <mimeMap fileExtension=".kmz" mimeType="application/vnd.google-earth.kmz" />
    </staticContent>
  </system.webServer>


问:
Searching And Parsing HTML custom tags via PHP
I've created a set of custom tags that go inside their own wrapper (see example below & there can be many different tags on a page at once) that I'm trying to find the best method for getting the tags and their info, and easiest for the server to process.

All the content I've been able to find on this is dated a few years at least and I figured maybe someone in the community would have ideas to help point me in a better direction.

```<code>[sl_heading tag='h3' padding='10' heading='Our Most Recent Posts' color='' style='' size='' subheading_active='' subheading_size='15' custom_class=''][/sl_heading ]

[sl_posts posts_type='general' categories='24' link='category' posts_style='posts-grid' columns='4' contents='title_read_more' content_length='excerpt_read_more' preview_mode='auto' image_size='thumbnail' items='-1' offset='0' paginate='no']
</code>```

So basically what I'm trying to do is the editor saves this to the database, and I'm trying to efficiently and quickly parse this out to the proper code on the website side. So my method is detecting the tag, determine what it is and what the tag values are, and show the proper HTML code in return.

I've already got everything but the parsing out the code part done, and I'm stuck on how to properly search and find the tags and their values effectively.

PS. Any help is appreciated, and I've searched through a lot of SO posts so what I'm trying to do hasn't been asked about in years (outdated posts) for what I can only understandably assume were much earlier versions of PHP.

答:
So I took a lot of time out and studied a few different systems that are open source, and figured out an effective, and fast working solution. I took a simple function I seen and reworked it to work for me. This finds all instances of substring text I look for (something like [start] and [end] ) and gets all the content between it for me. It then replaces that entire string and replaces it with the appropriate content.

See code below, copy paste into PHPfiddle.org for quick run.

```<code><?php

function getContents($str, $startDelimiter, $endDelimiter) {
    $contents = array();
    $startDelimiterLength = strlen($startDelimiter);
    $endDelimiterLength = strlen($endDelimiter);
    $startFrom = 0;
    $contentStart = 0;
    $contentEnd = 0;
    while (false !== ($contentStart = strpos($str, $startDelimiter, $startFrom))) {
        $contentStart += $startDelimiterLength;
        $contentEnd = strpos($str, $endDelimiter, $contentStart);
        if (false === $contentEnd) { break; }

        $content_length = $contentEnd - $contentStart;
        $the_content = substr($str, $contentStart, $content_length);
        $replace_this = "$startDelimiter$the_content$endDelimiter";
        $contents[] = array($the_content, $replace_this);
        $startFrom = $contentEnd + $endDelimiterLength;
  }

  return $contents;
}

$thiss = "This is a test text area, filled with dummy text such as: Lorem ipsum dolor sit amet. [advertisers-display]123[/advertisers-display] This is a test text area, filled with dummy text such as: Lorem ipsum dolor sit amet. [advertisers-display]456[/advertisers-display] This is a test text area, filled with dummy text such as: Lorem ipsum dolor sit amet. [advertisers-display]789[/advertisers-display]";

$tag_start = "[advertisers-display]";
$tag_end = "[/advertisers-display]";

$this_array_get = getContents($thiss, $tag_start, $tag_end);
foreach($this_array_get as $this_get) {
    if(isset($this_get[1])) {
        echo "ID $this_get[0] | REPLACE THIS -> $this_get[1] WITH THIS -> [ REPLACED $this_get[0] ]<br />";
        $thiss = str_replace($this_get[1], "[ REPLACED $this_get[0] ]", $thiss, $num);
    }
}
echo "<br /> $thiss";

?>
</code>```

Body:
I've created a set of custom tags that go inside their own wrapper (see example below & there can be many different tags on a page at once) that I'm trying to find the best method for getting the tags and their info, and easiest for the server to process.

All the content I've been able to find on this is dated a few years at least and I figured maybe someone in the community would have ideas to help point me in a better direction.

[sl_heading tag='h3' padding='10' heading='Our Most Recent Posts' color='' style='' size='' subheading_active='' subheading_size='15' custom_class=''][/sl_heading ]

[sl_posts posts_type='general' categories='24' link='category' posts_style='posts-grid' columns='4' contents='title_read_more' content_length='excerpt_read_more' preview_mode='auto' image_size='thumbnail' items='-1' offset='0' paginate='no']

So basically what I'm trying to do is the editor saves this to the database, and I'm trying to efficiently and quickly parse this out to the proper code on the website side. So my method is detecting the tag, determine what it is and what the tag values are, and show the proper HTML code in return.

I've already got everything but the parsing out the code part done, and I'm stuck on how to properly search and find the tags and their values effectively.

PS. Any help is appreciated, and I've searched through a lot of SO posts so what I'm trying to do hasn't been asked about in years (outdated posts) for what I can only understandably assume were much earlier versions of PHP.

Body:
So I took a lot of time out and studied a few different systems that are open source, and figured out an effective, and fast working solution. I took a simple function I seen and reworked it to work for me. This finds all instances of substring text I look for (something like [start] and [end] ) and gets all the content between it for me. It then replaces that entire string and replaces it with the appropriate content.

See code below, copy paste into PHPfiddle.org for quick run.

<?php

function getContents($str, $startDelimiter, $endDelimiter) {
    $contents = array();
    $startDelimiterLength = strlen($startDelimiter);
    $endDelimiterLength = strlen($endDelimiter);
    $startFrom = 0;
    $contentStart = 0;
    $contentEnd = 0;
    while (false !== ($contentStart = strpos($str, $startDelimiter, $startFrom))) {
        $contentStart += $startDelimiterLength;
        $contentEnd = strpos($str, $endDelimiter, $contentStart);
        if (false === $contentEnd) { break; }

        $content_length = $contentEnd - $contentStart;
        $the_content = substr($str, $contentStart, $content_length);
        $replace_this = "$startDelimiter$the_content$endDelimiter";
        $contents[] = array($the_content, $replace_this);
        $startFrom = $contentEnd + $endDelimiterLength;
  }

  return $contents;
}

$thiss = "This is a test text area, filled with dummy text such as: Lorem ipsum dolor sit amet. [advertisers-display]123[/advertisers-display] This is a test text area, filled with dummy text such as: Lorem ipsum dolor sit amet. [advertisers-display]456[/advertisers-display] This is a test text area, filled with dummy text such as: Lorem ipsum dolor sit amet. [advertisers-display]789[/advertisers-display]";

$tag_start = "[advertisers-display]";
$tag_end = "[/advertisers-display]";

$this_array_get = getContents($thiss, $tag_start, $tag_end);
foreach($this_array_get as $this_get) {
    if(isset($this_get[1])) {
        echo "ID $this_get[0] | REPLACE THIS -> $this_get[1] WITH THIS -> [ REPLACED $this_get[0] ]<br />";
        $thiss = str_replace($this_get[1], "[ REPLACED $this_get[0] ]", $thiss, $num);
    }
}
echo "<br /> $thiss";

?>


问:
Failed to use MSGraph with python MSAL
I'm trying to develop an easy app that will be launch from crontab.
This App must connect to my outlook (Office360) calendar and download all event, after that i'll insert in my MariaDb.
I thought that was easy but i'm lose my mind in the last 4 days.
I try to follow Microsoft doc using NodeJs but i can't find a silent mode (a mode to request auth without signin all times) to receive token and data.
Then i try with Python in different approch, first using EWS but i read that will be deprecated in future, and in the last 2 days i'm trying with MSAL and ADAL.
The MSAL approach seem like more diffuse but i still have a this issue when i launch my script also with acquire_token_by_username_password or acquire_token_by_device_flow

AADSTS7000218: The request body must contain the following parameter: 'client_assertion' or 'client_secret'.

My code is the same of the GitHub https://github.com/AzureAD/microsoft-authentication-library-for-python/tree/dev/sample
I change my config in parameter.json and insert mine:

```<code>{
    "authority": "https://login.microsoftonline.com/organizations",
    "client_id": "ClinetIdOfApp Set in Azure",
    "username": "myaccont@account.xx",
    "scope": ["User.Read","Calendars.Read"],
    "password": "MyPassword*****"
}
</code>```

Please, anybody can tell me some suggestion for jump this rock?
Thanks

答:
You are using Resource owner password credential, you need to treat your application as a public client.

Login Azure portal->click Azure Active Directory->click App registrations->find your application->click Authentication->change the default client type to public client.

The result:

Title: Failed to use MSGraph with python MSAL

Body:
I'm trying to develop an easy app that will be launch from crontab.
This App must connect to my outlook (Office360) calendar and download all event, after that i'll insert in my MariaDb.
I thought that was easy but i'm lose my mind in the last 4 days.
I try to follow Microsoft doc using NodeJs but i can't find a silent mode (a mode to request auth without signin all times) to receive token and data.
Then i try with Python in different approch, first using EWS but i read that will be deprecated in future, and in the last 2 days i'm trying with MSAL and ADAL.
The MSAL approach seem like more diffuse but i still have a this issue when i launch my script also with acquire_token_by_username_password or acquire_token_by_device_flow

AADSTS7000218: The request body must contain the following parameter: 'client_assertion' or 'client_secret'.

My code is the same of the GitHub https://github.com/AzureAD/microsoft-authentication-library-for-python/tree/dev/sample
I change my config in parameter.json and insert mine:

{
    "authority": "https://login.microsoftonline.com/organizations",
    "client_id": "ClinetIdOfApp Set in Azure",
    "username": "myaccont@account.xx",
    "scope": ["User.Read","Calendars.Read"],
    "password": "MyPassword*****"
}

Please, anybody can tell me some suggestion for jump this rock?
Thanks


问:
Nesting (first) custom directive another (second) directive moves (first) custom directive to childscope instead of scope
The following is a template that works to the point that webix-ui directive points to childscope because it is inside of an ng-if...

I need ng-if to wait for the $scope.init() to finish getting data before I intitalize the ui component configuration objects.

How do I point to scope, not childscope in my webix-ui directive?

```<code>   <div id="formcontainer" ng-app="Risk" ng-controller="CreateRiskController" get-risk>
        <div id="mycreateform" class="container" type="space" layout-padding="">
            <form id="form" name="CreateRisk" role="form" ng-submit="valid() && submit()" novalidate>
                <div id="details" class="layout table" border="1">
                    <div class="tr">
                        <div class="td label">
                            Title
                        </div>
                        <div class="td locked">
                           <div ng-if="initDone">
                              <div webix-ui="config.risktitle" width="500"
                                   height="30" type="text" id="risktitle"
                                   name="risktitle">
                              </div>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
         </div>
    </div>
</code>```

This points to scope properly as it is not nested in ng-if

```<code>angular.module('Risk').directive('getRisk', getRisk);

function getRisk(){
     return {
            restrict: 'A',
            controller: function ($scope, $http, $sce){

                $scope.risklevels = {
                    riskmaximum: '',
                    riskhigh: '',
                    riskmedium: '',
                    riskminimum: ''
                }

                $scope.riskMatrix = [];
                for(var l = 1; l <= 5; l++)
                {
                    $scope.riskMatrix[l] = [];
                    for (var c = 0; c <= 5; c++)
                    {
                        $scope.riskMatrix[l][c] = '';
                    }
                }

                $scope.initDone = false;

                $scope.init = function(){
                      angular.element(document.querySelector('link[href="/app/tool/risk/CreateRisk.css"]')).remove();
                      angular.element(document.querySelector('head')).append('<link type="text/css" rel="stylesheet" href="/app/tool/risk/CreateRisk.css"/>');

                      return $http.get('/api/riskconfig').then(function(response){
                           if (response.data.Succeeded){
                                $scope.risklevels.riskmaximum = response.data.Result.Levels[0].riskmaximum;
                                $scope.risklevels.riskhigh = response.data.Result.Levels[0].riskhigh;
                                $scope.risklevels.riskmedium = response.data.Result.Levels[0].riskmedium;
                                $scope.risklevels.riskminimum = response.data.Result.Levels[0].riskminimum;

                                for (var idx = 0; idx < response.data.Result.Thresholds.length; idx++)
                                {
                                    var l = response.data.Result.Thresholds[idx].likelihood;
                                    var c = response.data.Result.Thresholds[idx].consequence;
                                    v = response.data.Result.Thresholds[idx].level;
                                    $scope.riskMatrix[l][c] = v;
                                }

                                return response.data.Result;
                           }
                           else{
                                $scope.msg = $sce.trustAsHtml(response.data);
                           }
                      });
                }

                $scope.init().then(function(){
                    $scope.initDone = true;
                    return $scope.initDone;
                });
            }
     }
}
</code>```

Currently This Points to ChildScope (should point to Scope Instead) because it is nested inside ng-if in template

```<code>angular.module('Risk').directive('webixUi', WebixElement);

function WebixElement(DOMops, ValidationService){
      var directive = {
            restrict: 'A',
            link: linkFn,
            controller: webixUiController,
            bindToController: true
      }

      function linkFn(scope, element, attrs) {
      }

      return directive;
}

function webixUiController($scope, $attrs, DOMops, ValidationService){
    var attr = $attrs.name;
    var type = $attrs.type;
    var width = $attrs.width;
    var height = $attrs.height;
    var maxlength = $attrs.hasOwnProperty('maxlength')? $attrs.maxlength: null;

    var view;
    if (type == "level")
        view = "text";
    else
        view = type;

    var config =
    {
        view: view,
        value: $scope.risk[attr],
        on: {
            "onTimedKeyPress": function(code){
                var obj = this.eventSource || this;
                ValidationService.handleKeyPress(obj, code, attr);
                if (type == "level")
                    DOMops.assignRiskLevel(scope, obj);
            },
            "onBlur": function(code){
                var obj = this.eventSource || this;
                ValidationService.updateAndValidate(obj,code,attr);
            }
        },
        responsive: true,
        width: width,
        height: height
    };
    if (maxlength)
        config.attributes = {maxlength : maxlength};
    $scope.config[$attrs.name] = config;
}
</code>```

答:
One approach to setting values from an attribute component is to use scope.$eval
to manually evaluate an expression attribute:

```<code>$scope.$eval($attrs.onConfig, {$config: config});
</code>```

Usage:

```<code><div webix-ui="config.risktitle" width="500"
     height="30" type="text" id="risktitle"
     name="risktitle" on-config="config.risktitle = $config">
</div>
</code>```

When the directive initializes, it evaluates the expression in the on-config attribute with $config as a local.

Scope inheritance is normally straightfoward... until you need 2-way data binding (i.e., form elements, ng-model) in the child scope. Ng-repeat, ng-switch, and ng-include can trip you up if you try to bind to a primitive (e.g., number, string, boolean) in the parent scope from inside the child scope. It doesn't work the way most people expect it should work. The child scope gets its own property that hides/shadows the parent property of the same name.

The way to make it work is to define objects in the parent for your model, then reference a property of that object in the child.

So in the parent controller define the object:

```<code> $scope.config = {};
</code>```

This follows the best practice of "always have a '.' in your models".

For more information, see

What are the nuances of scope prototypal / prototypical inheritance in AngularJS?

AngularJS scope/rootScope Type API Reference - $eval

Body:
The following is a template that works to the point that webix-ui directive points to childscope because it is inside of an ng-if...

I need ng-if to wait for the $scope.init() to finish getting data before I intitalize the ui component configuration objects.

How do I point to scope, not childscope in my webix-ui directive?

            <form id="form" name="CreateRisk" role="form" ng-submit="valid() && submit()" novalidate>

                            Title

            </form>

This points to scope properly as it is not nested in ng-if

angular.module('Risk').directive('getRisk', getRisk);

function getRisk(){
     return {
            restrict: 'A',
            controller: function ($scope, $http, $sce){

                $scope.risklevels = {
                    riskmaximum: '',
                    riskhigh: '',
                    riskmedium: '',
                    riskminimum: ''
                }

                $scope.riskMatrix = [];
                for(var l = 1; l <= 5; l++)
                {
                    $scope.riskMatrix[l] = [];
                    for (var c = 0; c <= 5; c++)
                    {
                        $scope.riskMatrix[l][c] = '';
                    }
                }

                $scope.initDone = false;

                $scope.init = function(){
                      angular.element(document.querySelector('link[href="/app/tool/risk/CreateRisk.css"]')).remove();
                      angular.element(document.querySelector('head')).append('<link type="text/css" rel="stylesheet" href="/app/tool/risk/CreateRisk.css"/>');

                      return $http.get('/api/riskconfig').then(function(response){
                           if (response.data.Succeeded){
                                $scope.risklevels.riskmaximum = response.data.Result.Levels[0].riskmaximum;
                                $scope.risklevels.riskhigh = response.data.Result.Levels[0].riskhigh;
                                $scope.risklevels.riskmedium = response.data.Result.Levels[0].riskmedium;
                                $scope.risklevels.riskminimum = response.data.Result.Levels[0].riskminimum;

                                for (var idx = 0; idx < response.data.Result.Thresholds.length; idx++)
                                {
                                    var l = response.data.Result.Thresholds[idx].likelihood;
                                    var c = response.data.Result.Thresholds[idx].consequence;
                                    v = response.data.Result.Thresholds[idx].level;
                                    $scope.riskMatrix[l][c] = v;
                                }

                                return response.data.Result;
                           }
                           else{
                                $scope.msg = $sce.trustAsHtml(response.data);
                           }
                      });
                }

                $scope.init().then(function(){
                    $scope.initDone = true;
                    return $scope.initDone;
                });
            }
     }
}

Currently This Points to ChildScope (should point to Scope Instead) because it is nested inside ng-if in template

angular.module('Risk').directive('webixUi', WebixElement);

function WebixElement(DOMops, ValidationService){
      var directive = {
            restrict: 'A',
            link: linkFn,
            controller: webixUiController,
            bindToController: true
      }

      function linkFn(scope, element, attrs) {
      }

      return directive;
}

function webixUiController($scope, $attrs, DOMops, ValidationService){
    var attr = $attrs.name;
    var type = $attrs.type;
    var width = $attrs.width;
    var height = $attrs.height;
    var maxlength = $attrs.hasOwnProperty('maxlength')? $attrs.maxlength: null;

    var view;
    if (type == "level")
        view = "text";
    else
        view = type;

    var config =
    {
        view: view,
        value: $scope.risk[attr],
        on: {
            "onTimedKeyPress": function(code){
                var obj = this.eventSource || this;
                ValidationService.handleKeyPress(obj, code, attr);
                if (type == "level")
                    DOMops.assignRiskLevel(scope, obj);
            },
            "onBlur": function(code){
                var obj = this.eventSource || this;
                ValidationService.updateAndValidate(obj,code,attr);
            }
        },
        responsive: true,
        width: width,
        height: height
    };
    if (maxlength)
        config.attributes = {maxlength : maxlength};
    $scope.config[$attrs.name] = config;
}

Body:
One approach to setting values from an attribute component is to use scope.$eval
to manually evaluate an expression attribute:

$scope.$eval($attrs.onConfig, {$config: config});

Usage:

<div webix-ui="config.risktitle" width="500"
     height="30" type="text" id="risktitle"
     name="risktitle" on-config="config.risktitle = $config">
</div>

When the directive initializes, it evaluates the expression in the on-config attribute with $config as a local.

Scope inheritance is normally straightfoward... until you need 2-way data binding (i.e., form elements, ng-model) in the child scope. Ng-repeat, ng-switch, and ng-include can trip you up if you try to bind to a primitive (e.g., number, string, boolean) in the parent scope from inside the child scope. It doesn't work the way most people expect it should work. The child scope gets its own property that hides/shadows the parent property of the same name.

The way to make it work is to define objects in the parent for your model, then reference a property of that object in the child.

So in the parent controller define the object:

 $scope.config = {};

This follows the best practice of "always have a '.' in your models".

For more information, see

What are the nuances of scope prototypal / prototypical inheritance in AngularJS?

AngularJS scope/rootScope Type API Reference - $eval


问:
I want to show my csv data row by row consequently in a modal box by clicking button through mapping in react
I can read CSV data thru table & I want to show that data by individual row in a modal box by onClick or onDoubleClick function in react. I can't get it how to do it. Any kind of help would be appreciable. I am new to reactjs

```<code>render() {
        const {data, header} = this.props;
        const rows = [...data.split("\n")];
        const contentRows = header ? rows.slice(1,rows.length) : rows;

return (
            <div>
                 <Table>
                    {header && (
                        <TableHeader>
                            <TableRow>
                                {this.rowParser(rows[0]).map((value, index) => (
                                    <TableHeaderColumn key={index}>{value}</TableHeaderColumn>
                                ))}
                            </TableRow>
                        </TableHeader>
                    )}
            <TableBody displayRowCheckbox={false}>
                        {contentRows.map((row, index) => (

                            <TableRow key={index}>
                                {this.rowParser(row).map((value, index) => (
                                    <TableRowColumn key={index} data={value}>{value}
 </TableRowColumn>
                                ))}
                        <button type="button" id={index} onClick={this.handleClickOpen}>Edit</button>
                            </TableRow>
</code>```

I want header and individual row of csv table comes up in a modal box by clicking button.

答:
You have to store the rowContents into this.state, then when click on button, retrieve back the rowData using this.state.rowContents[i]</p>

```<code>constructor(props) {
   super(props)
   const {data, header} = this.props;
   const rows = [...data.split("\n")];
   const contentRows = header ? rows.slice(1,rows.length) : rows;
   this.state = {
     header: header,
     contentRows: contentRows,
   }
}

componentDidMount() {

}

handleClickOpen(rowIndex) {
   // Do whatever you want with the row data
   const rowData = this.state.contentsRow[rowIndex]
   console.log(rowData)
}

render() {
   // other stuff here
   {
     contentRows.map((row, rowIndex) => (
       <TableRow key={rowIndex}>
        {
          this.rowParser(row).map((value, colIndex) => (
            <TableRowColumn key={colIndex} data={value}>
              {value}
            </TableRowColumn>
          ))
        }
        <button type="button" id ={rowIndex}
          onClick={() => this.handleClickOpen(rowIndex)}>
           Edit
         </button>
      </TableRow>
    }
}
</code>```

Body:
I can read CSV data thru table & I want to show that data by individual row in a modal box by onClick or onDoubleClick function in react. I can't get it how to do it. Any kind of help would be appreciable. I am new to reactjs

render() {
        const {data, header} = this.props;
        const rows = [...data.split("\n")];
        const contentRows = header ? rows.slice(1,rows.length) : rows;

return (

                    {header && (
                        <TableHeader>
                            <TableRow>
                                {this.rowParser(rows[0]).map((value, index) => (
                                    <TableHeaderColumn key={index}>{value}</TableHeaderColumn>
                                ))}
                            </TableRow>
                        </TableHeader>
                    )}
            <TableBody displayRowCheckbox={false}>
                        {contentRows.map((row, index) => (

                            <TableRow key={index}>
                                {this.rowParser(row).map((value, index) => (
                                    <TableRowColumn key={index} data={value}>{value}
 </TableRowColumn>
                                ))}
                        <button type="button" id={index} onClick={this.handleClickOpen}>Edit</button>
                            </TableRow>

I want header and individual row of csv table comes up in a modal box by clicking button.

Body:
You have to store the rowContents into this.state, then when click on button, retrieve back the rowData using this.state.rowContents[i]

constructor(props) {
   super(props)
   const {data, header} = this.props;
   const rows = [...data.split("\n")];
   const contentRows = header ? rows.slice(1,rows.length) : rows;
   this.state = {
     header: header,
     contentRows: contentRows,
   }
}

componentDidMount() {

}

handleClickOpen(rowIndex) {
   // Do whatever you want with the row data
   const rowData = this.state.contentsRow[rowIndex]
   console.log(rowData)
}

render() {
   // other stuff here
   {
     contentRows.map((row, rowIndex) => (
       <TableRow key={rowIndex}>
        {
          this.rowParser(row).map((value, colIndex) => (
            <TableRowColumn key={colIndex} data={value}>
              {value}
            </TableRowColumn>
          ))
        }
        <button type="button" id ={rowIndex}
          onClick={() => this.handleClickOpen(rowIndex)}>
           Edit
         </button>
      </TableRow>
    }
}


答:
In trackScore() you are switch-ing on trashList, but it often contains multiple items, so it won't match your cases.

Instead, you want:

```<code>func trackScore(binChoice:String){
    switch trashList[itemChoice] {
    case "Can":
        if binChoice == "red"{
            score = score - 1
        } else if binChoice == "yellow" {
            score = score + 10
        } else {
            score = score - 5
        }

    case "Brick":
        if binChoice == "red"{
            score = score + 10
        } else if binChoice == "yellow" {
            score = score - 1
        } else {
            score = score - 5
        }

    case "Sandwich":
        if binChoice == "red"{
            score = score + 10
        } else if binChoice == "yellow" {
            score = score - 1
        } else {
            score = score - 5
        }
    default:
        break
    }
    trashList.remove(at: itemChoice)
    itemChange()
}
</code>```

Title: Variable not updating in score tracking system for ios app

Body:
In trackScore() you are switch-ing on trashList, but it often contains multiple items, so it won't match your cases.

Instead, you want:

func trackScore(binChoice:String){
    switch trashList[itemChoice] {
    case "Can":
        if binChoice == "red"{
            score = score - 1
        } else if binChoice == "yellow" {
            score = score + 10
        } else {
            score = score - 5
        }

    case "Brick":
        if binChoice == "red"{
            score = score + 10
        } else if binChoice == "yellow" {
            score = score - 1
        } else {
            score = score - 5
        }

    case "Sandwich":
        if binChoice == "red"{
            score = score + 10
        } else if binChoice == "yellow" {
            score = score - 1
        } else {
            score = score - 5
        }
    default:
        break
    }
    trashList.remove(at: itemChoice)
    itemChange()
}


问:
How can you run a python function stored in a different file
I know how to do this in C, but I'm not sure how to do it in python. I'm trying to make a python program which will read from an external file, then execute a function name which was read from that file. Example:

File structure:

```<code>main.py
map.py
Scripts/
  script1.py
</code>```

map.py contains just an array and a function to get the correct array index:

```<code>map = ["One","script1.function_one","Two","scrip1.function_two"]
def return_mapping(str):
  for i in range(0,len(map)):
    if str in map[i]:
      return map[i+1]
</code>```

The functions: "function_one()" and "function_two()" are defined in script1.py.
main.py will contain something like this:

```<code>selection = raw_input("What function would you like to run?")
function_ptr = map.return_mapping(selection)
#This is where I don't know what the correct code is... I want to now execute
#whatever function was returned.
</code>```

Any suggestions?

答:
You need to use import. This might be what you're looking for:

```<code>from Scripts.script1 import function_one, function_two
print choices:
print "function_one"
print "function_two"
selection = raw_input("What function would you like to run?")
if selection == "function_one":
    function_one()
elif selection == "function_two":
    function_two()
else:
    print "not a choice"
</code>```

Edit: Given your additional requirements, consider this:

main.py

```<code>from Scripts.script1 import functions
print choices:
for func in script1.functions:
    print func
selection = raw_input("What function would you like to run?")
script1.functions[selection]()
</code>```

and in script1.py

```<code>from collections import defaultdict
def _no_function(*args, *kwargs):
    print "No such function"

functions = defaultdict(_no_function)
def function_one():
    pass

functions['function_one'] = function_one
</code>```

This solution permits you to call arbitrary functions without using eval as long as they are added to the dictionary in their respective source files. Furthermore, by using a defaultdict you can provide a function when the one requested is not present. Ultimately, import is still what you need.

Body:
I know how to do this in C, but I'm not sure how to do it in python. I'm trying to make a python program which will read from an external file, then execute a function name which was read from that file. Example:

File structure:

main.py
map.py
Scripts/
  script1.py

map.py contains just an array and a function to get the correct array index:

map = ["One","script1.function_one","Two","scrip1.function_two"]
def return_mapping(str):
  for i in range(0,len(map)):
    if str in map[i]:
      return map[i+1]

The functions: "function_one()" and "function_two()" are defined in script1.py.
main.py will contain something like this:

selection = raw_input("What function would you like to run?")
function_ptr = map.return_mapping(selection)
#This is where I don't know what the correct code is... I want to now execute
#whatever function was returned.

Any suggestions?

Body:
You need to use import. This might be what you're looking for:

from Scripts.script1 import function_one, function_two
print choices:
print "function_one"
print "function_two"
selection = raw_input("What function would you like to run?")
if selection == "function_one":
    function_one()
elif selection == "function_two":
    function_two()
else:
    print "not a choice"

Edit: Given your additional requirements, consider this:

main.py

from Scripts.script1 import functions
print choices:
for func in script1.functions:
    print func
selection = raw_input("What function would you like to run?")
script1.functions[selection]()

and in script1.py

from collections import defaultdict
def _no_function(*args, *kwargs):
    print "No such function"

functions = defaultdict(_no_function)
def function_one():
    pass

functions['function_one'] = function_one

This solution permits you to call arbitrary functions without using eval as long as they are added to the dictionary in their respective source files. Furthermore, by using a defaultdict you can provide a function when the one requested is not present. Ultimately, import is still what you need.