问:
How to dynamically iterate an index based on a repeating series in one column in a pandas dataframe
I have a dataframe that's a set of data recordings that are each 400 channels long, with each channel number listed under the channel column of my dataframe, like so,

```<code>index   channel input   Baseline
0       0       2129    2129
1       1       2128    2129
2       2       2129    2129
3       3       2129    2129
4       4       2129    2129
5       5       2129    2129

...

396     396     2128    2127
397     397     2128    2127
398     398     2127    2127
399     399     2127    2127
400     0       2130    2128
401     1       2130    2128
402     2       2131    2128

...
</code>```

and so on

What I am trying to do is set the index so each series of 400 channels is individually indexed like this,

```<code>index   channel input   Baseline
0       0       2129    2129
        1       2128    2129
        2       2129    2129
        3       2129    2129
        4       2129    2129
        5       2129    2129

...

        396     2128    2127
        397     2128    2127
        398     2127    2127
        399     2127    2127
1       0       2130    2128
        1       2130    2128
        2       2131    2128

...
</code>```

Apologies if this is something that's blindingly obvious but I am a bit of a beginner at working with python and code in general

edit: thanks for the help! Surprising that the groupby function is bugged in python3

Body:
I have a dataframe that's a set of data recordings that are each 400 channels long, with each channel number listed under the channel column of my dataframe, like so,

index   channel input   Baseline
0       0       2129    2129
1       1       2128    2129
2       2       2129    2129
3       3       2129    2129
4       4       2129    2129
5       5       2129    2129

...

396     396     2128    2127
397     397     2128    2127
398     398     2127    2127
399     399     2127    2127
400     0       2130    2128
401     1       2130    2128
402     2       2131    2128

...

and so on

What I am trying to do is set the index so each series of 400 channels is individually indexed like this,

index   channel input   Baseline
0       0       2129    2129
        1       2128    2129
        2       2129    2129
        3       2129    2129
        4       2129    2129
        5       2129    2129

...

        396     2128    2127
        397     2128    2127
        398     2127    2127
        399     2127    2127
1       0       2130    2128
        1       2130    2128
        2       2131    2128

...

Apologies if this is something that's blindingly obvious but I am a bit of a beginner at working with python and code in general

edit: thanks for the help! Surprising that the groupby function is bugged in python3

Body:
I think you need cumcount for counting with set_index:

df = df.set_index(df.groupby('channel').cumcount())
print (df)
   channel  input  Baseline
0        0   2129      2129
0        1   2128      2129
0        2   2129      2129
0        3   2129      2129
0        4   2129      2129
0        5   2129      2129
0      396   2128      2127
0      397   2128      2127
0      398   2127      2127
0      399   2127      2127
1        0   2130      2128
1        1   2130      2128
1        2   2131      2128

Or maybe if need MultiIndex:

df = df.set_index([df.groupby('channel').cumcount(), 'channel'])
print (df)
           input  Baseline
  channel
0 0         2129      2129
  1         2128      2129
  2         2129      2129
  3         2129      2129
  4         2129      2129
  5         2129      2129
  396       2128      2127
  397       2128      2127
  398       2127      2127
  399       2127      2127
1 0         2130      2128
  1         2130      2128
  2         2131      2128

Or create new column first:

df['idx'] = df.groupby('channel').cumcount()
df = df.set_index(['idx', 'channel'])
print (df)
             input  Baseline
idx channel
0   0         2129      2129
    1         2128      2129
    2         2129      2129
    3         2129      2129
    4         2129      2129
    5         2129      2129
    396       2128      2127
    397       2128      2127
    398       2127      2127
    399       2127      2127
1   0         2130      2128
    1         2130      2128
    2         2131      2128


来源: stackexchange

问:
Default string arguments
```<code>myPreciousFunction(std::string s1 = "", std::string s2 = "")
{
}

int main()
{
    myPreciousFunction();
}
</code>```

<p>Can i make the arguments look more pretty?
I want there to be empty strings if no arguments were supplied. </p>

答:
You could use a braced initialisation:</p>

```<code>myPreciousFunction(const std::string& s1 = {}, const std::string& s2 = {})
{
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Default string arguments

Body:
myPreciousFunction(std::string s1 = "", std::string s2 = "")
{
}

int main()
{
    myPreciousFunction();
}

Can i make the arguments look more pretty?
I want there to be empty strings if no arguments were supplied.

Body:
You could use a braced initialisation:

myPreciousFunction(const std::string& s1 = {}, const std::string& s2 = {})
{
}


问:
RatingBar cuts off progressDrawable
The RatingBar cuts of my progressDrawable, no matter how I set it's height (wrap_content, exact Drawable's height do not work). It seems, that the RatingBar does not play well with non square images. Any ideas how to avoid the clipping? The image do have some transparent padding, the size is hinted with blue border in the screenshot.

```<code><RatingBar android:layout_width="wrap_content"
                   android:layout_height="wrap_content"
                   android:numStars="1"
                   android:progressDrawable="@drawable/selector_person_bar"
                   android:rating="0"
                   android:stepSize="1"/>
</code>```

答: Got it, due to a bug in the implementation of the ProgressBar, android:maxHeight has to be set to avoid clipping.

Title: RatingBar cuts off progressDrawable

Body:
The RatingBar cuts of my progressDrawable, no matter how I set it's height (wrap_content, exact Drawable's height do not work). It seems, that the RatingBar does not play well with non square images. Any ideas how to avoid the clipping? The image do have some transparent padding, the size is hinted with blue border in the screenshot.

<RatingBar android:layout_width="wrap_content"
                   android:layout_height="wrap_content"
                   android:numStars="1"
                   android:progressDrawable="@drawable/selector_person_bar"
                   android:rating="0"
                   android:stepSize="1"/>


问:
Can I use Existing Certificate, private key, public key for my hyperledger fabric user rather than creating new from CA or cryptogen?
I am working on Hyperledger fabric 1.0 beta release. So far I have noticed that if a transaction is done on a peer using Node sdk, it internally sends a call to CA to get crypto material for new user(Cert, private key, public key). If I already have a user certificate, private key, public key, how can I use them to send request to peers instead of using crypto material provided by CA.
I have noticed that Cryptogen utility also generates crypto artifacts for users. How can I use those artifacts to make a transaction on peer instead of making a call to CA first?</p>

答:
Please share how to solve this problem in GO SDK. I can move to GO
  application layer if necessary.

```<code>func TestExample(t *testing.T) {
    conf, err := config.InitConfig("config.yaml")
    assert.NoError(t, err)
    cl := fabricclient.NewClient(conf)
    bccspFactory.InitFactories(nil)
    cryptoSuite := bccspFactory.GetDefault()
    privKey := "/home/yacovm/fabricDeployment/crypto-config/peerOrganizations/hrl.ibm.il/users/Admin@hrl.ibm.il/msp/keystore/213d24d189babc01e1f2e4e4cc2fd1a68bcfe95a2bdd0981ef2f9c39a00fb3f2_sk"
    pubKey := "/home/yacovm/fabricDeployment/crypto-config/peerOrganizations/hrl.ibm.il/users/Admin@hrl.ibm.il/msp/signcerts/Admin@hrl.ibm.il-cert.pem"
    user ,err := fabapi.NewPreEnrolledUser(conf, privKey, pubKey, "yacov", "PeerOrg", bccspFactory.GetDefault())
    cl.SetCryptoSuite(cryptoSuite)
    assert.NotNil(t, user)
    assert.NoError(t, err)
    cl.SetUserContext(user)
    o, err := orderer2.NewOrderer("vm1:7050",
        "/home/yacovm/fabricDeployment/crypto-config/ordererOrganizations/hrl.ibm.il/orderers/vm1.hrl.ibm.il/tls/ca.crt",
    "", conf)
    assert.NoError(t, err)
    p, err := peer.NewPeerTLSFromCert("vm2:7051", "/home/yacovm/fabricDeployment/crypto-config/peerOrganizations/hrl.ibm.il/peers/vm2.hrl.ibm.il/tls/ca.crt", "", conf)
    assert.NoError(t, err)
    ch, err := cl.NewChannel("yacov")
    ch.AddOrderer(o)
    ch.AddPeer(p)
    cl.SaveUserToStateStore(user, true)
    tp, err := ch.CreateTransactionProposal("exampleCC", "yacov", []string{"invoke", "a", "b", "1"}, true, nil)
    assert.NoError(t, err)
    assert.NotNil(t, tp)
    resp, err := channel.SendTransactionProposal(tp, 1, []apitxn.ProposalProcessor{p})
    assert.NoError(t, err)
    fmt.Println(string(resp[0].TransactionProposalResult.ProposalResponse.Response.Payload))
    txn, err := ch.CreateTransaction(resp)
    assert.NoError(t, err)
    txnResp, err := ch.SendTransaction(txn)
    assert.NoError(t, err)
    fmt.Println(txnResp[0])

    time.Sleep(time.Second * 5)

    tp, err = ch.CreateTransactionProposal("exampleCC", "yacov", []string{"query", "a"}, true, nil)
    resp, err = channel.SendTransactionProposal(tp, 1, []apitxn.ProposalProcessor{p})
    fmt.Println(string(resp[0].TransactionProposalResult.ProposalResponse.Response.Payload))
}
</code>```

Body:
Please share how to solve this problem in GO SDK. I can move to GO
  application layer if necessary.

func TestExample(t *testing.T) {
    conf, err := config.InitConfig("config.yaml")
    assert.NoError(t, err)
    cl := fabricclient.NewClient(conf)
    bccspFactory.InitFactories(nil)
    cryptoSuite := bccspFactory.GetDefault()
    privKey := "/home/yacovm/fabricDeployment/crypto-config/peerOrganizations/hrl.ibm.il/users/Admin@hrl.ibm.il/msp/keystore/213d24d189babc01e1f2e4e4cc2fd1a68bcfe95a2bdd0981ef2f9c39a00fb3f2_sk"
    pubKey := "/home/yacovm/fabricDeployment/crypto-config/peerOrganizations/hrl.ibm.il/users/Admin@hrl.ibm.il/msp/signcerts/Admin@hrl.ibm.il-cert.pem"
    user ,err := fabapi.NewPreEnrolledUser(conf, privKey, pubKey, "yacov", "PeerOrg", bccspFactory.GetDefault())
    cl.SetCryptoSuite(cryptoSuite)
    assert.NotNil(t, user)
    assert.NoError(t, err)
    cl.SetUserContext(user)
    o, err := orderer2.NewOrderer("vm1:7050",
        "/home/yacovm/fabricDeployment/crypto-config/ordererOrganizations/hrl.ibm.il/orderers/vm1.hrl.ibm.il/tls/ca.crt",
    "", conf)
    assert.NoError(t, err)
    p, err := peer.NewPeerTLSFromCert("vm2:7051", "/home/yacovm/fabricDeployment/crypto-config/peerOrganizations/hrl.ibm.il/peers/vm2.hrl.ibm.il/tls/ca.crt", "", conf)
    assert.NoError(t, err)
    ch, err := cl.NewChannel("yacov")
    ch.AddOrderer(o)
    ch.AddPeer(p)
    cl.SaveUserToStateStore(user, true)
    tp, err := ch.CreateTransactionProposal("exampleCC", "yacov", []string{"invoke", "a", "b", "1"}, true, nil)
    assert.NoError(t, err)
    assert.NotNil(t, tp)
    resp, err := channel.SendTransactionProposal(tp, 1, []apitxn.ProposalProcessor{p})
    assert.NoError(t, err)
    fmt.Println(string(resp[0].TransactionProposalResult.ProposalResponse.Response.Payload))
    txn, err := ch.CreateTransaction(resp)
    assert.NoError(t, err)
    txnResp, err := ch.SendTransaction(txn)
    assert.NoError(t, err)
    fmt.Println(txnResp[0])

    time.Sleep(time.Second * 5)

    tp, err = ch.CreateTransactionProposal("exampleCC", "yacov", []string{"query", "a"}, true, nil)
    resp, err = channel.SendTransactionProposal(tp, 1, []apitxn.ProposalProcessor{p})
    fmt.Println(string(resp[0].TransactionProposalResult.ProposalResponse.Response.Payload))
}


问:
Create a multidimensional array in a loop
I am trying to create an array like this in a loop:

```<code>$dataPoints = array(
    array('x' => 4321, 'y' => 2364),
    array('x' => 3452, 'y' => 4566),
    array('x' => 1245, 'y' => 3452),
    array('x' => 700, 'y' => 900),
    array('x' => 900, 'y' => 700));
</code>```

with this code

```<code>$dataPoints = array();
$brands = array("COCACOLA","DellChannel","ebayfans","google",
    "microsoft","nikeplus","amazon");
foreach ($brands as $value) {
    $resp = GetTwitter($value);
    $dataPoints = array(
        "x"=>$resp['friends_count'],
        "y"=>$resp['statuses_count']);
}
</code>```

but when loop completes my array looks like this:

```<code>Array ( [x] => 24 [y] => 819 )
</code>```

答:
This is because you're re-assigning $dataPoints as a new array on each loop.

Change it to:

```<code>$dataPoints[] = array("x"=>$resp['friends_count'],"y"=>$resp ['statuses_count']);
</code>```

This will append a new array to the end of $dataPoints

Body:
I am trying to create an array like this in a loop:

$dataPoints = array(
    array('x' => 4321, 'y' => 2364),
    array('x' => 3452, 'y' => 4566),
    array('x' => 1245, 'y' => 3452),
    array('x' => 700, 'y' => 900),
    array('x' => 900, 'y' => 700));

with this code

$dataPoints = array();
$brands = array("COCACOLA","DellChannel","ebayfans","google",
    "microsoft","nikeplus","amazon");
foreach ($brands as $value) {
    $resp = GetTwitter($value);
    $dataPoints = array(
        "x"=>$resp['friends_count'],
        "y"=>$resp['statuses_count']);
}

but when loop completes my array looks like this:

Array ( [x] => 24 [y] => 819 )

Body:
This is because you're re-assigning $dataPoints as a new array on each loop.

Change it to:

$dataPoints[] = array("x"=>$resp['friends_count'],"y"=>$resp ['statuses_count']);

This will append a new array to the end of $dataPoints

ContentLicense: CC BY-SA 2.5


问:
Javascript Browserify, require function and run it
I have this little browserify problem. I want to require a self made module and run it instantly.

Main File:

```<code>(function() {
    require('./modules/initScrollReveal')();
    require('./modules/initChart')();
    require('./modules/initDatamap')();
  })();
</code>```

Module:

```<code>exports.initChart = function () {
  // do stuff
};
</code>```

now i get an error with the Message
"require(...) is not a function" at require('./modules/initScrollReveal')();

Browserify is running via Watchify with

```<code>watchify public-modules/res/js/main.js -o public/res/js/main.js
</code>```

答:
module.exports allows the initChart function to be called like a function when required. Simply setting exports wouldn't allow the function to be exported because node exports the object module.exports references.

change

```<code>exports.initChart = function () {
  // do stuff
};
</code>```

to

```<code>module.exports = function initChart  () {
  // do stuff
};
</code>```

More details : browserify-handbook#exports

Body:
I have this little browserify problem. I want to require a self made module and run it instantly.

Main File:

(function() {
    require('./modules/initScrollReveal')();
    require('./modules/initChart')();
    require('./modules/initDatamap')();
  })();

Module:

exports.initChart = function () {
  // do stuff
};

now i get an error with the Message
"require(...) is not a function" at require('./modules/initScrollReveal')();

Browserify is running via Watchify with

watchify public-modules/res/js/main.js -o public/res/js/main.js

Body:
module.exports allows the initChart function to be called like a function when required. Simply setting exports wouldn't allow the function to be exported because node exports the object module.exports references.

change

exports.initChart = function () {
  // do stuff
};

to

module.exports = function initChart  () {
  // do stuff
};

More details : browserify-handbook#exports


问:
Color Scheme Plugin JAR file cant be imported, but individual files inside jar can be imported
I am a developer of an IntelliJ Plugin. It is a color scheme where I only change the editor colors (not the colors of the IDE). I originally had only one color scheme file for my whole plugin (one .icls file), and that code is live and working online.

Recently, I updated my color scheme to include two additional color schemes, which meant I had to add two new .icls files. This works on my local IDE that I am developing on; however, when I tested the finished plugin, the new instance of IntelliJ IDEA CE cannot extract the content from the new files.

Problem

I need a working JAR file that I can upload into the JetBrain Plugin Repository; however, I cannot create a working Jar file anymore.

Note: I am not looking to import a color scheme. I am a developer of a color scheme that needs to upload my plugin into the Jetbrain Plugin Repository

When I tested the Color Scheme through build, deploy, and run, the new instance of the IDE will fail to find any color scheme. I cannot seem to narrow down why the IDE cannot load the color scheme; however, I was able to do the following...

From the deployed JAR file, rename the file to be a zip file

Extract the content of the zip file

then...

try Settings >> Editor >> Color Scheme >> Import Scheme... >> Settings (.jar) and find the JAR file. Nothing happens. No color schemes were imported.

...but...

try Settings >> Editor >> Color Scheme >> Import Scheme... >> IntelliJ IDEA color scheme (.icls) and find each of the .icls files. Each individual color scheme is successfully found and loaded into the IDE.

Additional Information

Originally, I was receiving the following issue that I filed in JetBrain's Issue Tracker. However, after some tinkering, I was receiving a different set of issues. So, I started a new project and just copied the source files and plugin.xml file into the new project. Built, Deployed, and tested. No errors, no warnings (that I saw), but the color schemes are still not being loaded into the IDE.

答:
File -> Import Settings -> select settings file.

In the settings file: top-level dir colors where .icls files located.


问:
WebPack: Change in module numbers do not change chunkhash
I am using webpack to bundle my files into two file: app.js and lib.js and I create and append unique chunkhash for each of my files that get download by browser. Both these files are built together in the same build output. It would look like this:

```<code>lib.747c2ee515b25d871bd0.js
app.e6a0b36a5bb2bff41393.js
</code>```

I have following caching set on these files:

```<code>Cache-Control:private, max-age=31536000
</code>```

This means that these files will be cached for an year or when a new file arrives. And this would work independently for each file.

Since our application is closer to release, there more changes in app than in lib.

Problem: The problem I am facing is that in a new build, contents of the lib are not changed but module ids are changed. This is causing module ids to change but chunkhash doesn't change; causing downloading of app but not lib resulting into broken app. On Ctrl+F5 everything starts working again as expected.

Questions: Isn't the changed module ids considered as part of chunkash? How do I fix this problem? Is it possible to add auto-increment explicit version number to file names through WebPack?

Any help will be much appreciated.

答:
If you're using webpack-md5-hash plugin to change the webpack chunkhash then you might be hitting this issue.

Also these two articles might help Predictable long term caching and Long term caching of static assets with webpack.

Body:
I am using webpack to bundle my files into two file: app.js and lib.js and I create and append unique chunkhash for each of my files that get download by browser. Both these files are built together in the same build output. It would look like this:

lib.747c2ee515b25d871bd0.js
app.e6a0b36a5bb2bff41393.js

I have following caching set on these files:

Cache-Control:private, max-age=31536000

This means that these files will be cached for an year or when a new file arrives. And this would work independently for each file.

Since our application is closer to release, there more changes in app than in lib.

Problem: The problem I am facing is that in a new build, contents of the lib are not changed but module ids are changed. This is causing module ids to change but chunkhash doesn't change; causing downloading of app but not lib resulting into broken app. On Ctrl+F5 everything starts working again as expected.

Questions: Isn't the changed module ids considered as part of chunkash? How do I fix this problem? Is it possible to add auto-increment explicit version number to file names through WebPack?

Any help will be much appreciated.


问:
Why isn't my code storing the items in localStorage? Rest everything is fine
This code cannot store the added items into the localStorage.
But its running fine
When I am reloading the page, all my items vanish.
Please help.

var list = [];
        var add = document.getElementById('add');
        add.addEventListener('click', function() {
            var task = document.getElementById('task').value;
            list.push(task);
            localStorage.setItem('todo', JSON.stringify(list));
            var todo_str = localStorage.getItem('todo');
            var todos = JSON.parse(todo_str);
            var html = '';
            for(var i=0; i<todos.length; i++) {
                html += '
' + todos[i] + '
';
            }
            document.getElementById('todos').innerHTML = html;
        });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
    <title>Todo List</title>

    <!--Let browser know website is optimized for mobile-->
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <!-- Compiled and minified CSS -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.99.0/css/materialize.min.css">
</head>
<body>
    <div class="container">
        <input id="task"><button class="btn" id="add">Add</button>
        <ul id="todos" class="collection"></ul>
    </div>
    <script type="text/javascript">

    </script>
</body>
</html></code>```

答:
Since list is initially empty and you are saving it in localStorage when the add button is clicked all the previously added items will be overriden

```<code>localStorage.setItem('todo', JSON.stringify(list)); // This is overriding your items from the last session
</code>```

You could initialize list with localStorage instead of an empty array if you want to persist the items from the last session

```<code>list = JSON.parse(localStorage.getItem('todo')); // This will persist your items from the last session
</code>```

Body:
This code cannot store the added items into the localStorage.
But its running fine
When I am reloading the page, all my items vanish.
Please help.

var list = [];
        var add = document.getElementById('add');
        add.addEventListener('click', function() {
            var task = document.getElementById('task').value;
            list.push(task);
            localStorage.setItem('todo', JSON.stringify(list));
            var todo_str = localStorage.getItem('todo');
            var todos = JSON.parse(todo_str);
            var html = '';
            for(var i=0; i<todos.length; i++) {
                html += '
' + todos[i] + '
';
            }
            document.getElementById('todos').innerHTML = html;
        });

<!DOCTYPE html>

    <title>Todo List</title>

    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.99.0/css/materialize.min.css">

        <input id="task"><button class="btn" id="add">Add</button>

Body:
Since list is initially empty and you are saving it in localStorage when the add button is clicked all the previously added items will be overriden

localStorage.setItem('todo', JSON.stringify(list)); // This is overriding your items from the last session

You could initialize list with localStorage instead of an empty array if you want to persist the items from the last session

list = JSON.parse(localStorage.getItem('todo')); // This will persist your items from the last session


问:
Overflow in div tag
I have a div tag with fixed width. Now i want that if there is a condition of overflow then text should go to next line automatically. I used overflow:auto but its giving a horizontal scroll bar. There should not be any scroll bar, text should go to next line.

Any idea how to do it with css???

答: to add to the link David's pasted, if you want the vertical scrollbar to show up, then the height property of the div should be fixed.

Title: Overflow in div tag


问:
How to keep a foreground app running 24/7?
I am looking into how to keep my Android app running in the foreground.

It will be a privately distributed app, so I can do anything possible to make sure it runs constantly on the device (HDMI TV Stick)

So, how can I make sure that the app stays running no matter what? The app is pretty light weight in terms of resource usage, so having it run 24/7 should hopefully not be a problem.

I read about the persistent parameter in the manifest, but it looks like it might only apply to system apps?

Should I make my app a system app? How would I do that and would it help?

答:
I solved that issue by having a sticky service running that relaunches the app when the activity is getting closed.

```<code>//Your activity

@Override
public void onPause() {
    super.onPause();

    if (yourservice != null) {
        yourservice.validateActivityOnPause();
    }
}
</code>```

and in the validateActivityOnPause() have something like:

```<code>//Your service

public void validateLynxActivityOnPause() {
    //Do some stuff here

    Intent startActivityIntent = new Intent(this, LynxActivity.class);
    startActivityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    this.startActivity(startActivityIntent);
}
</code>```

Body:
I solved that issue by having a sticky service running that relaunches the app when the activity is getting closed.

//Your activity

@Override
public void onPause() {
    super.onPause();

    if (yourservice != null) {
        yourservice.validateActivityOnPause();
    }
}

and in the validateActivityOnPause() have something like:

//Your service

public void validateLynxActivityOnPause() {
    //Do some stuff here

    Intent startActivityIntent = new Intent(this, LynxActivity.class);
    startActivityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    this.startActivity(startActivityIntent);
}


问:
How to make a form secure in redux-form
I am trying to use redux-form to build a credit card info form. However, when the user put in their card details on it, this pop up appear:

it said

Automatic credit card filling is disabled because this form does not use a secure connection

So my question is how to make a form secure using redux-form?

This is the code where I input the Payment redux-form

```<code>import React from 'react'
import { connect } from 'react-redux'
import PaymentView from './Payment.js'
import { reduxForm } from 'redux-form'

class Payment extends React.Component{

    render() {
        const { cardDetail } = this.props
        return(<PaymentView onCheckOut={()=>console.log(cardDetail)} />)
    }
}

Payment = reduxForm({
    form: 'payment'
})(Payment)

const mapStateToProps = state => ({
    cardDetail : state.form.payment ? state.form.payment.values : null
})

export default connect(mapStateToProps)(Payment)
</code>```

This is the code for my Payment View

```<code>import React from 'react'
import { Panel, Button, Row, Col } from 'react-bootstrap'
import { TextInput } from '.Form'

export default ({onCheckOut})=> <div>
    <Row>
        <Col sm={12} md={8} lg={6} mdOffset={2} lgOffset={3}>
            <Panel className="scb" header="bank transfer">
                123-456-789
            </Panel>
        </Col>
    </Row>
    <Row>
        <Col sm={12} md={8} mdOffset={2} lg={6} lgOffset={3}>
        <Panel className="credit-card" header="credit card" >
            <Row>
                <Col sm={12} md={8} lg={6}>
                <TextInput
                    name="creditCard"
                    label="credit card number"
                    type="text"
                    validateState="success"
                    controlId="credit-card"
                    value="12345678910111213"
                    placeholder="xxxx xxxx xxxx xxxx"
                    onChange={()=>{}}
                    helptext="16card number"
                >
                    card number
                </TextInput>
                </Col>
            </Row>
            <Row>
                <Col sm={12} md={8} lg={6}>
                    <TextInput
                        name="name"
                        label="name"
                        type="text"
                        validateState="success"
                        controlId="name-card"
                        value="steve jobs"
                        placeholder="steve jobs"
                        onChange={()=>{}}
                        helptext="name on card"
                    >
                        Name on Card
                    </TextInput>
                </Col>
            </Row>
            <Row>
                <Col sm={8} md={8} lg={8}>
                    <h5>Expiry Date</h5>
                </Col>
            </Row>
            <Row>
                <Col sm={4} md={2} lg={2}>
                    <TextInput
                        name="month"
                        label="month"
                        type="text"
                        validateState="success"
                        controlId="month"
                        value="12"
                        placeholder="01"
                        onChange={()=>{}}
                        helptext="month"
                    >
                        month
                    </TextInput>
                </Col>
                <Col sm={4} md={2} lg={2}>
                    <TextInput
                        name="year"
                        label="year"
                        type="text"
                        validateState="success"
                        controlId="year"
                        value="18"
                        placeholder="18"
                        onChange={()=>{}}
                        helptext="year"
                    >
                        Year
                    </TextInput>
                </Col>
            </Row>
            <Row>
                <Col sm={12} md={4} lg={4}>
                    <TextInput
                        name="cvv"
                        label="cvv"
                        type="text"
                        validateState="cvv"
                        controlId="cvv"
                        value="123"
                        placeholder="123"
                        onChange={()=>{}}
                        helptext="cvv"
                    >
                        Cvv
                    </TextInput>
                </Col>
            </Row>
            <Row>
                <Col sm={12} md={4} lg={4}>
                    <Button bsStyle="primary" bsSize="large" block onClick={onCheckOut}>
                        Pay Now
                    </Button>
                </Col>
            </Row>
        </Panel>
        </Col>
    </Row>
</div>
</code>```

This is my TextInput

```<code>export const TextInput = (
    {
        type,
        name,
        placeholder,
        helpTextArray,
        status,
        label,
        value
    }
) =>
<FormGroup
    name="formBasicText"
    validationState={status || null}
>
    <ControlLabel>{label}</ControlLabel>
    <Field
        className="form-control"
        id="formBasicText"
        name={name}
        component="input"
        type={type}
        placeholder={placeholder}
    />
    <FormControl.Feedback />
    {
        value !== null?
        helpTextArray.map( (helpText, key) =>
            <HelpBlock key={key}>{helpText}</HelpBlock>
        ): null
    }
</FormGroup>
</code>```

答:
This is most likely happening because the web page where that form is found is not served over HTTPS. Chrome automatically disables credit card information autofilling in those cases to stop your credit card information from falling into malicious hands through for example

Network traffic snooping (your credit card details being transmitted over a public Wi-Fi or other network in plaintext)

Man-in-the-Middle injection (somebody intercepting the non-encrypted HTTP traffic and injecting malicious code that captures credit card details)

Even if your page is served over HTTPS already, this issue might pop up if your page has content like images or external scripts that are served over a regular HTTP connection.

Title: How to make a form secure in redux-form

Body:
I am trying to use redux-form to build a credit card info form. However, when the user put in their card details on it, this pop up appear:

it said

Automatic credit card filling is disabled because this form does not use a secure connection

So my question is how to make a form secure using redux-form?

This is the code where I input the Payment redux-form

import React from 'react'
import { connect } from 'react-redux'
import PaymentView from './Payment.js'
import { reduxForm } from 'redux-form'

class Payment extends React.Component{

    render() {
        const { cardDetail } = this.props
        return(<PaymentView onCheckOut={()=>console.log(cardDetail)} />)
    }
}

Payment = reduxForm({
    form: 'payment'
})(Payment)

const mapStateToProps = state => ({
    cardDetail : state.form.payment ? state.form.payment.values : null
})

export default connect(mapStateToProps)(Payment)

This is the code for my Payment View

import React from 'react'
import { Panel, Button, Row, Col } from 'react-bootstrap'
import { TextInput } from '.Form'

export default ({onCheckOut})=>

    <Row>
        <Col sm={12} md={8} lg={6} mdOffset={2} lgOffset={3}>
            <Panel className="scb" header="bank transfer">
                123-456-789
            </Panel>
        </Col>
    </Row>
    <Row>
        <Col sm={12} md={8} mdOffset={2} lg={6} lgOffset={3}>
        <Panel className="credit-card" header="credit card" >
            <Row>
                <Col sm={12} md={8} lg={6}>
                <TextInput
                    name="creditCard"
                    label="credit card number"
                    type="text"
                    validateState="success"
                    controlId="credit-card"
                    value="12345678910111213"
                    placeholder="xxxx xxxx xxxx xxxx"
                    onChange={()=>{}}
                    helptext="16card number"
                >
                    card number
                </TextInput>
                </Col>
            </Row>
            <Row>
                <Col sm={12} md={8} lg={6}>
                    <TextInput
                        name="name"
                        label="name"
                        type="text"
                        validateState="success"
                        controlId="name-card"
                        value="steve jobs"
                        placeholder="steve jobs"
                        onChange={()=>{}}
                        helptext="name on card"
                    >
                        Name on Card
                    </TextInput>
                </Col>
            </Row>
            <Row>
                <Col sm={8} md={8} lg={8}>

Expiry Date

                </Col>
            </Row>
            <Row>
                <Col sm={4} md={2} lg={2}>
                    <TextInput
                        name="month"
                        label="month"
                        type="text"
                        validateState="success"
                        controlId="month"
                        value="12"
                        placeholder="01"
                        onChange={()=>{}}
                        helptext="month"
                    >
                        month
                    </TextInput>
                </Col>
                <Col sm={4} md={2} lg={2}>
                    <TextInput
                        name="year"
                        label="year"
                        type="text"
                        validateState="success"
                        controlId="year"
                        value="18"
                        placeholder="18"
                        onChange={()=>{}}
                        helptext="year"
                    >
                        Year
                    </TextInput>
                </Col>
            </Row>
            <Row>
                <Col sm={12} md={4} lg={4}>
                    <TextInput
                        name="cvv"
                        label="cvv"
                        type="text"
                        validateState="cvv"
                        controlId="cvv"
                        value="123"
                        placeholder="123"
                        onChange={()=>{}}
                        helptext="cvv"
                    >
                        Cvv
                    </TextInput>
                </Col>
            </Row>
            <Row>
                <Col sm={12} md={4} lg={4}>
                    <Button bsStyle="primary" bsSize="large" block onClick={onCheckOut}>
                        Pay Now
                    </Button>
                </Col>
            </Row>
        </Panel>
        </Col>
    </Row>

This is my TextInput

export const TextInput = (
    {
        type,
        name,
        placeholder,
        helpTextArray,
        status,
        label,
        value
    }
) =>
<FormGroup
    name="formBasicText"
    validationState={status || null}
>
    <ControlLabel>{label}</ControlLabel>
    <Field
        className="form-control"
        id="formBasicText"
        name={name}
        component="input"
        type={type}
        placeholder={placeholder}
    />
    <FormControl.Feedback />
    {
        value !== null?
        helpTextArray.map( (helpText, key) =>
            <HelpBlock key={key}>{helpText}</HelpBlock>
        ): null
    }
</FormGroup>


问:
Creating a multidimentional array from a flat JSON file
Firstly, I'm very new to nodeJS... like day 5. So bear with me.

I'm building an FAQ app to get into it and I have written a controller and a model which is returning this JSON file:

```<code>[
    {
        faq_id: 1,
        faq_question: "This is a question?",
        faq_answer: "And a lovely answer",
        tab_title: "Tab title here",
        tab_id: 1
    },
    {
        faq_id: 2,
        faq_question: "Another question",
        faq_answer: "With an answer",
        tab_title: "Tab title",
        tab_id: 2
    }
]
</code>```

}

The requirements are that all the questions are categorised into tabs on the FE. So two tables, one for tabs and one for faqs.

Where each question has an appropriate tab_id associated with it to make the relationship.

What I need to do is create top level nesting in the JSON file to be all the tabs, then iterate over the questions and match the faq_tab_id with the tab_id and nest the question into the appropriate tab.

I have started with looking into using an UnderscoreJS map?

Not sure how much sense it makes or if any more code would be required, but any advice would be welcome. I'm not clued up on the terminology yet so I struggled to find an already asked question to do something like this.

Thanks!

答:
Depending on what you intend to do, Underscore.js groupBy function may be enough:</p>

```<code>// This will group the objects by their 'tab_id' property
var grouped = _.groupBy(myData, 'tab_id');
</code>```

Body:
Firstly, I'm very new to nodeJS... like day 5. So bear with me.

I'm building an FAQ app to get into it and I have written a controller and a model which is returning this JSON file:

[
    {
        faq_id: 1,
        faq_question: "This is a question?",
        faq_answer: "And a lovely answer",
        tab_title: "Tab title here",
        tab_id: 1
    },
    {
        faq_id: 2,
        faq_question: "Another question",
        faq_answer: "With an answer",
        tab_title: "Tab title",
        tab_id: 2
    }
]

}

The requirements are that all the questions are categorised into tabs on the FE. So two tables, one for tabs and one for faqs.

Where each question has an appropriate tab_id associated with it to make the relationship.

What I need to do is create top level nesting in the JSON file to be all the tabs, then iterate over the questions and match the faq_tab_id with the tab_id and nest the question into the appropriate tab.

I have started with looking into using an UnderscoreJS map?

Not sure how much sense it makes or if any more code would be required, but any advice would be welcome. I'm not clued up on the terminology yet so I struggled to find an already asked question to do something like this.

Thanks!

Body:
Depending on what you intend to do, Underscore.js groupBy function may be enough:

// This will group the objects by their 'tab_id' property
var grouped = _.groupBy(myData, 'tab_id');


问:
How do i exit the program when i type a specific word, in my case "end"?
I'm having a problem. I'm currently doing a school project for a ChatBot. This is a game section for the chatbot. It's a word scramble game. I can enter the wrong answer and the program would prompt me to retype the answer. But, if I type the correct answer, the program just stops there, the program didn't stop.

What I would like to do is to repeat the code, like keeping playing the game, until I type the word "end", but I don't know how to implement it. Also, most of the words kept repeating. For example, the word [animal] would usually be scrambled into [anialm].

So I would like to get some help on improving the code too. Thank you very much!! I am still a Year 1 who just started learning to program.

```<code>public static void main(String[] args) {
        Scanner userinput = new Scanner(System.in);
        String guess = "";
        String scramble = "";
        String[] questions = {"animal", "duck", "dinosaur", "butterfly", "dog", "horse", "cow", "cat", "elephant", "crocodile", "alligator"};
        char charArr[] = null;
        String wordToGuess = questions[new Random().nextInt(questions.length)];// questions[0]

        for (int a = 0; a < wordToGuess.length(); a++) {
            charArr = wordToGuess.toCharArray();  //0a 1n 2i 3m 4a 5l 6s
            //generating a random number from the length of word to guess. Example: Animal, generated no = "1"
            int rdm = new Random().nextInt(charArr.length);
            //shuffling the words
            char temp = charArr[a];     //charArr[0] is the letter "A" which is moved to temp
            charArr[a] = charArr[rdm];  //A is then moved to charArr[rdm] which is index 1, so the word is currently "AAimals'
            charArr[rdm] = temp;        //charArr[1] contains n which is then moved to temmp, which is 0, becoming nAimal
        }
        scramble = new String(charArr);
        System.out.println("Your word is: " + scramble);

        do {
            while (!guess.equals(wordToGuess)) {
                System.out.print(">>> ");
                guess = userinput.nextLine();
                if (!guess.equals(wordToGuess)) {
                    System.out.print(">>> ");
                    System.out.println("Please try again!");
                } else {
                    System.out.println(">>> Great Job getting the answer!");
                }
            }
        }while (!guess.equalsIgnoreCase("end"));
    }
}
</code>```

答:
```<code>if(guess.equalsIgnoreCase("end")){
      System.exit(0);
  }
</code>```

Body:
I'm having a problem. I'm currently doing a school project for a ChatBot. This is a game section for the chatbot. It's a word scramble game. I can enter the wrong answer and the program would prompt me to retype the answer. But, if I type the correct answer, the program just stops there, the program didn't stop.

What I would like to do is to repeat the code, like keeping playing the game, until I type the word "end", but I don't know how to implement it. Also, most of the words kept repeating. For example, the word [animal] would usually be scrambled into [anialm].

So I would like to get some help on improving the code too. Thank you very much!! I am still a Year 1 who just started learning to program.

public static void main(String[] args) {
        Scanner userinput = new Scanner(System.in);
        String guess = "";
        String scramble = "";
        String[] questions = {"animal", "duck", "dinosaur", "butterfly", "dog", "horse", "cow", "cat", "elephant", "crocodile", "alligator"};
        char charArr[] = null;
        String wordToGuess = questions[new Random().nextInt(questions.length)];// questions[0]

        for (int a = 0; a < wordToGuess.length(); a++) {
            charArr = wordToGuess.toCharArray();  //0a 1n 2i 3m 4a 5l 6s
            //generating a random number from the length of word to guess. Example: Animal, generated no = "1"
            int rdm = new Random().nextInt(charArr.length);
            //shuffling the words
            char temp = charArr[a];     //charArr[0] is the letter "A" which is moved to temp
            charArr[a] = charArr[rdm];  //A is then moved to charArr[rdm] which is index 1, so the word is currently "AAimals'
            charArr[rdm] = temp;        //charArr[1] contains n which is then moved to temmp, which is 0, becoming nAimal
        }
        scramble = new String(charArr);
        System.out.println("Your word is: " + scramble);

        do {
            while (!guess.equals(wordToGuess)) {
                System.out.print(">>> ");
                guess = userinput.nextLine();
                if (!guess.equals(wordToGuess)) {
                    System.out.print(">>> ");
                    System.out.println("Please try again!");
                } else {
                    System.out.println(">>> Great Job getting the answer!");
                }
            }
        }while (!guess.equalsIgnoreCase("end"));
    }
}


问:
Timer not firing on WatchOS 3
I'm calling startTimer() and getting "start timer" printed in the console, but the scheduled timer never fires. Any thoughts?

```<code>func startTimer() {
    print("start timer")
    let timerDidFire: (Timer) -> Void = { timer in
        print("timer")
        self.updateLabels()
    }

    timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: timerDidFire)
}
</code>```

答:
Be sure that you're executing your timer in main thread.
You can check current execution in thread by:

```<code>print(Thread.current)
</code>```

If not main, call your timer here:

```<code>DispatchQueue.main.async {
    // here is your timer
}
</code>```

Title: Timer not firing on WatchOS 3

Body:
I'm calling startTimer() and getting "start timer" printed in the console, but the scheduled timer never fires. Any thoughts?

func startTimer() {
    print("start timer")
    let timerDidFire: (Timer) -> Void = { timer in
        print("timer")
        self.updateLabels()
    }

    timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: timerDidFire)
}

Body:
Be sure that you're executing your timer in main thread.
You can check current execution in thread by:

print(Thread.current)

If not main, call your timer here:

DispatchQueue.main.async {
    // here is your timer
}


问:
How to prevent user from selecting the same value from more than one combobox in wpf
I have a simple class as such:

```<code>public class Item
{
   public int ID{get;set;}
   public string Name{get;set;}
}
</code>```

I have a List of this class in my Mainwindow.xaml.cs as such:

```<code>public List<Item> AllItems=GetAllItems();
</code>```

I have four properties of Item class in my Mainwindow.xaml.cs as such:

```<code>public Item Item1{get;set;}
public Item Item2{get;set;}
public Item Item3{get;set;}
public Item Item4{get;set;}
</code>```

This List:AllItems is databinded to four Comboboxes as under:

```<code> <ComboBox x:Name="cmbCode1" ItemsSource="{Binding AllItems}" DisplayMemberPath="ID" SelectedValuePath="ID" SelectedValue="{Binding Item1.ID,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" SelectedItem="{Binding Item1,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
 <ComboBox x:Name="cmbCode2" ItemsSource="{Binding AllItems}"  DisplayMemberPath="ID" SelectedValuePath="ID" SelectedValue="{Binding Item1.ID,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" SelectedItem="{Binding Item1,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
 <ComboBox x:Name="cmbCode3" ItemsSource="{Binding AllItems}" DisplayMemberPath="ID" SelectedValuePath="ID" SelectedValue="{Binding Item1.ID,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" SelectedItem="{Binding Item1,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
 <ComboBox x:Name="cmbCode4" ItemsSource="{Binding AllItems}" DisplayMemberPath="ID" SelectedValuePath="ID" SelectedValue="{Binding Item1.ID,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" SelectedItem="{Binding Item1,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
</code>```

I have four TextBoxes corresponding to these four Comboboxes as such:

```<code><TextBlock x:Name="txtName1" Text="{Binding Item1.Name,Mode=OneWay,UpdateSourceTrigger=PropertyChanged}"/>
<TextBlock x:Name="txtName2" Text="{Binding Item2.Name,Mode=OneWay,UpdateSourceTrigger=PropertyChanged}"/>
<TextBlock x:Name="txtName3" Text="{Binding Item3.Name,Mode=OneWay,UpdateSourceTrigger=PropertyChanged}"/>
<TextBlock x:Name="txtName4" Text="{Binding Item4.Name,Mode=OneWay,UpdateSourceTrigger=PropertyChanged}"/>
</code>```

What i want is that the user should never be able to select the same ID from more than one combobox.
Is there some simple way that could be done,especially using xaml only?How can i hide or show the items selected/unselected from other comboboxes so that the user can't select the same ID from more than one combobox ever?
So far i have tried to send the selected Item and the entire List to a MultivalueConverter and eliminating/adding items to the Lists there itself,but this seems too meesy.Any other better idea would be appreciated.

答:
You should handle this kind of logic in your view models. Here is an example for you that should give you the idea:

View Model:

```<code>public partial class MainWindow : Window, INotifyPropertyChanged
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;
        AllItems = new List<Item>() { new Item { Name = "1" }, new Item { Name = "2" }, new Item { Name = "3" }, new Item { Name = "4" } };
    }

    public List<Item> AllItems { get; set; }

    private Item _item1;
    public Item Item1
    {
        get { return _item1; }
        set
        {
            _item1 = value;
            NotifyPropertyChanged();
            if (value != null)
                value.CanSelect = false;
        }
    }

    private Item _item2;
    public Item Item2
    {
        get { return _item2; }
        set
        {
            _item2 = value;
            NotifyPropertyChanged();
            if (value != null)
                value.CanSelect = false;
        }
    }

    private Item _item3;
    public Item Item3
    {
        get { return _item3; }
        set
        {
            _item3 = value; NotifyPropertyChanged();
            if (value != null)
                value.CanSelect = false;
        }
    }

    private Item _item4;
    public Item Item4
    {
        get { return _item4; }
        set
        {
            _item4 = value;
            NotifyPropertyChanged();
            if (value != null)
                value.CanSelect = false;
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));

    }
}

public class Item : INotifyPropertyChanged
{
    public int ID { get; set; }
    public string Name { get; set; }

    private bool _canSelect = true;
    public bool CanSelect
    {
        get { return _canSelect; }
        set { _canSelect = value; NotifyPropertyChanged(); }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}
</code>```

XAML:

```<code><Style x:Key="icstyle" TargetType="ComboBoxItem">
    <Setter Property="IsEnabled" Value="{Binding CanSelect}" />
</Style>
...
<ComboBox x:Name="cmbCode1" ItemsSource="{Binding AllItems}" SelectedItem="{Binding Item1}" DisplayMemberPath="Name" ItemContainerStyle="{StaticResource icstyle}"/>
<ComboBox x:Name="cmbCode2" ItemsSource="{Binding AllItems}" SelectedItem="{Binding Item2}" DisplayMemberPath="Name" ItemContainerStyle="{StaticResource icstyle}"/>
<ComboBox x:Name="cmbCode3" ItemsSource="{Binding AllItems}" SelectedItem="{Binding Item3}" DisplayMemberPath="Name" ItemContainerStyle="{StaticResource icstyle}"/>
<ComboBox x:Name="cmbCode4" ItemsSource="{Binding AllItems}" SelectedItem="{Binding Item4}" DisplayMemberPath="Name" ItemContainerStyle="{StaticResource icstyle}"/>
</code>```

Body:
I have a simple class as such:

public class Item
{
   public int ID{get;set;}
   public string Name{get;set;}
}

I have a List of this class in my Mainwindow.xaml.cs as such:

public List<Item> AllItems=GetAllItems();

I have four properties of Item class in my Mainwindow.xaml.cs as such:

public Item Item1{get;set;}
public Item Item2{get;set;}
public Item Item3{get;set;}
public Item Item4{get;set;}

This List:AllItems is databinded to four Comboboxes as under:

 <ComboBox x:Name="cmbCode1" ItemsSource="{Binding AllItems}" DisplayMemberPath="ID" SelectedValuePath="ID" SelectedValue="{Binding Item1.ID,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" SelectedItem="{Binding Item1,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
 <ComboBox x:Name="cmbCode2" ItemsSource="{Binding AllItems}"  DisplayMemberPath="ID" SelectedValuePath="ID" SelectedValue="{Binding Item1.ID,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" SelectedItem="{Binding Item1,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
 <ComboBox x:Name="cmbCode3" ItemsSource="{Binding AllItems}" DisplayMemberPath="ID" SelectedValuePath="ID" SelectedValue="{Binding Item1.ID,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" SelectedItem="{Binding Item1,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
 <ComboBox x:Name="cmbCode4" ItemsSource="{Binding AllItems}" DisplayMemberPath="ID" SelectedValuePath="ID" SelectedValue="{Binding Item1.ID,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" SelectedItem="{Binding Item1,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>

I have four TextBoxes corresponding to these four Comboboxes as such:

<TextBlock x:Name="txtName1" Text="{Binding Item1.Name,Mode=OneWay,UpdateSourceTrigger=PropertyChanged}"/>
<TextBlock x:Name="txtName2" Text="{Binding Item2.Name,Mode=OneWay,UpdateSourceTrigger=PropertyChanged}"/>
<TextBlock x:Name="txtName3" Text="{Binding Item3.Name,Mode=OneWay,UpdateSourceTrigger=PropertyChanged}"/>
<TextBlock x:Name="txtName4" Text="{Binding Item4.Name,Mode=OneWay,UpdateSourceTrigger=PropertyChanged}"/>

What i want is that the user should never be able to select the same ID from more than one combobox.
Is there some simple way that could be done,especially using xaml only?How can i hide or show the items selected/unselected from other comboboxes so that the user can't select the same ID from more than one combobox ever?
So far i have tried to send the selected Item and the entire List to a MultivalueConverter and eliminating/adding items to the Lists there itself,but this seems too meesy.Any other better idea would be appreciated.

Body:
You should handle this kind of logic in your view models. Here is an example for you that should give you the idea:

View Model:

public partial class MainWindow : Window, INotifyPropertyChanged
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;
        AllItems = new List<Item>() { new Item { Name = "1" }, new Item { Name = "2" }, new Item { Name = "3" }, new Item { Name = "4" } };
    }

    public List<Item> AllItems { get; set; }

    private Item _item1;
    public Item Item1
    {
        get { return _item1; }
        set
        {
            _item1 = value;
            NotifyPropertyChanged();
            if (value != null)
                value.CanSelect = false;
        }
    }

    private Item _item2;
    public Item Item2
    {
        get { return _item2; }
        set
        {
            _item2 = value;
            NotifyPropertyChanged();
            if (value != null)
                value.CanSelect = false;
        }
    }

    private Item _item3;
    public Item Item3
    {
        get { return _item3; }
        set
        {
            _item3 = value; NotifyPropertyChanged();
            if (value != null)
                value.CanSelect = false;
        }
    }

    private Item _item4;
    public Item Item4
    {
        get { return _item4; }
        set
        {
            _item4 = value;
            NotifyPropertyChanged();
            if (value != null)
                value.CanSelect = false;
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));

    }
}

public class Item : INotifyPropertyChanged
{
    public int ID { get; set; }
    public string Name { get; set; }

    private bool _canSelect = true;
    public bool CanSelect
    {
        get { return _canSelect; }
        set { _canSelect = value; NotifyPropertyChanged(); }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

XAML:

<Style x:Key="icstyle" TargetType="ComboBoxItem">
    <Setter Property="IsEnabled" Value="{Binding CanSelect}" />
</Style>
...
<ComboBox x:Name="cmbCode1" ItemsSource="{Binding AllItems}" SelectedItem="{Binding Item1}" DisplayMemberPath="Name" ItemContainerStyle="{StaticResource icstyle}"/>
<ComboBox x:Name="cmbCode2" ItemsSource="{Binding AllItems}" SelectedItem="{Binding Item2}" DisplayMemberPath="Name" ItemContainerStyle="{StaticResource icstyle}"/>
<ComboBox x:Name="cmbCode3" ItemsSource="{Binding AllItems}" SelectedItem="{Binding Item3}" DisplayMemberPath="Name" ItemContainerStyle="{StaticResource icstyle}"/>
<ComboBox x:Name="cmbCode4" ItemsSource="{Binding AllItems}" SelectedItem="{Binding Item4}" DisplayMemberPath="Name" ItemContainerStyle="{StaticResource icstyle}"/>


问:
TStream with Datasnap Rest and Close-session
I build a datasnap REST application and I can't close the session.

For example if I call my URL 4 times in my web browser:
http://127.0.0.1:4445/REST/image?json=false

There is 4 sessions opened.

Here is my function:

```<code>function TV1.TestImage:TStream;
var
ContentType : String;
FileStream : TFileStream;
begin
    FileStream := TFileStream.Create('C:\santiago.jpg', fmOpenRead or fmShareDenyNone);
    ContentType := 'image/jpg';

    GetInvocationMetadata.ResponseContentType := ContentType;
    ContentTypeHeaderToUse := ContentType;
    GetInvocationMetadata().ResponseCode := 200;

    result := FileStream;

    //Can't call CloseSession with TStream, pointer exception
    //GetInvocationMetaData.CloseSession := True;

end;
</code>```

And I use the WebModuleAfterDispatch like that:

```<code>  procedure TWebModule2.WebModuleAfterDispatch(Sender: TObject;
  Request: TWebRequest; Response: TWebResponse; var Handled: Boolean);
  var session : TDSSession;
  begin
      response.FreeContentStream := true;

      if ContentTypeHeaderToUse<>'' then begin
          Response.ContentType := ContentTypeHeaderToUse;
          ContentTypeHeaderToUse := ''; // Reset global variable
      end;

  end;
</code>```

As you can see, GetInvocationMetaData.CloseSession := True; can't be used here.

Do you know how to close session after sending the TStream?

答:
On a REST server I prefer to return a base64 string, it's easier to deal for the client app than the JSON representation of a Delphi TStream (an array of bytes).

The EncodeBase64 function on the Soap.EncdDecd unit does the transformation very easily :

```<code>function TV1.TestImage:string;
var MemoryStream: TMemoryStream;
begin
  MemoryStream := TMemoryStream.Create;
  MemoryStream.LoadFromFile('C:\santiago.jpg');
  Result := EncodeBase64(MemoryStream.Memory, MemoryStream.Size);
  MemoryStream.Free; // Now you can free the Stream yourself
end;
</code>```

An additional benefit is that you can now release your Stream and not depend on Datasnap doing it. So you should be able to manually close your connection without that pointer exception and solve the problem of multiple sessions remaining open.

You can directly use that base64 image string on your web application. You only need to add their type at the start of an  tag.

Example :

```<code><img src="data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUgAAABkAAAAZCAYAAADE6YVjAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyJpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMy1jMDExIDY2LjE0NTY2MSwgMjAxMi8wMi8wNi0xNDo1NjoyNyAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNiAoV2luZG93cykiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6MEVBMTczNDg3QzA5MTFFNjk3ODM5NjQyRjE2RjA3QTkiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6MEVBMTczNDk3QzA5MTFFNjk3ODM5NjQyRjE2RjA3QTkiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDowRUExNzM0NjdDMDkxMUU2OTc4Mzk2NDJGMTZGMDdBOSIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDowRUExNzM0NzdDMDkxMUU2OTc4Mzk2NDJGMTZGMDdBOSIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/PjjUmssAAAGASURBVHjatJaxTsMwEIbpIzDA6FaMMPYJkDKzVYU+QFeEGPIKfYU8AETkCYI6wANkZQwIKRNDB1hA0Jrf0rk6WXZ8BvWkb4kv99vn89kDrfVexBSYgVNwDA7AN+jAK3gEd+AlGMGIBFDgFvzouK3JV/lihQTOwLtOtw9wIRG5pJn91Tbgqk9kSk7GViADrTD4HCyZ0NQnomi51sb0fUyCMQEbp2WpU67IjfNjwcYyoUDhjJVcZBjYBy40j4wXgaobWoe8Z6Y80CJBwFpunepIzt2AUgFjtXXshNXjVmMh+K+zzp/CMs0CqeuzrxSRpbOKfdCkiMTS1VBQ41uxMyQR2qbrXiiwYN3ACh1FDmsdK2Eu4J6Tlo31dYVtCY88h5ELZIJJ+IRMzBHfyJINrigNkt5VsRiub9nXICdsYyVd2NcVvA3ScE5t2rb5JuEeyZnAhmLt9NK63vX1O5Pe8XaPSuGq1uTrfUgMEp9EJ+CQvr+BJ/AAKvAcCiAR+bf9CjAAluzmdX4AEIIAAAAASUVORK5CYII=">
</code>```

Body:
I build a datasnap REST application and I can't close the session.

For example if I call my URL 4 times in my web browser:
http://127.0.0.1:4445/REST/image?json=false

There is 4 sessions opened.

Here is my function:

function TV1.TestImage:TStream;
var
ContentType : String;
FileStream : TFileStream;
begin
    FileStream := TFileStream.Create('C:\santiago.jpg', fmOpenRead or fmShareDenyNone);
    ContentType := 'image/jpg';

    GetInvocationMetadata.ResponseContentType := ContentType;
    ContentTypeHeaderToUse := ContentType;
    GetInvocationMetadata().ResponseCode := 200;

    result := FileStream;

    //Can't call CloseSession with TStream, pointer exception
    //GetInvocationMetaData.CloseSession := True;

end;

And I use the WebModuleAfterDispatch like that:

  procedure TWebModule2.WebModuleAfterDispatch(Sender: TObject;
  Request: TWebRequest; Response: TWebResponse; var Handled: Boolean);
  var session : TDSSession;
  begin
      response.FreeContentStream := true;

      if ContentTypeHeaderToUse<>'' then begin
          Response.ContentType := ContentTypeHeaderToUse;
          ContentTypeHeaderToUse := ''; // Reset global variable
      end;

  end;

As you can see, GetInvocationMetaData.CloseSession := True; can't be used here.

Do you know how to close session after sending the TStream?

Body:
On a REST server I prefer to return a base64 string, it's easier to deal for the client app than the JSON representation of a Delphi TStream (an array of bytes).

The EncodeBase64 function on the Soap.EncdDecd unit does the transformation very easily :

function TV1.TestImage:string;
var MemoryStream: TMemoryStream;
begin
  MemoryStream := TMemoryStream.Create;
  MemoryStream.LoadFromFile('C:\santiago.jpg');
  Result := EncodeBase64(MemoryStream.Memory, MemoryStream.Size);
  MemoryStream.Free; // Now you can free the Stream yourself
end;

An additional benefit is that you can now release your Stream and not depend on Datasnap doing it. So you should be able to manually close your connection without that pointer exception and solve the problem of multiple sessions remaining open.

You can directly use that base64 image string on your web application. You only need to add their type at the start of an < img > tag.

Example :

<img src="data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUgAAABkAAAAZCAYAAADE6YVjAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyJpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMy1jMDExIDY2LjE0NTY2MSwgMjAxMi8wMi8wNi0xNDo1NjoyNyAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNiAoV2luZG93cykiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6MEVBMTczNDg3QzA5MTFFNjk3ODM5NjQyRjE2RjA3QTkiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6MEVBMTczNDk3QzA5MTFFNjk3ODM5NjQyRjE2RjA3QTkiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDowRUExNzM0NjdDMDkxMUU2OTc4Mzk2NDJGMTZGMDdBOSIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDowRUExNzM0NzdDMDkxMUU2OTc4Mzk2NDJGMTZGMDdBOSIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/PjjUmssAAAGASURBVHjatJaxTsMwEIbpIzDA6FaMMPYJkDKzVYU+QFeEGPIKfYU8AETkCYI6wANkZQwIKRNDB1hA0Jrf0rk6WXZ8BvWkb4kv99vn89kDrfVexBSYgVNwDA7AN+jAK3gEd+AlGMGIBFDgFvzouK3JV/lihQTOwLtOtw9wIRG5pJn91Tbgqk9kSk7GViADrTD4HCyZ0NQnomi51sb0fUyCMQEbp2WpU67IjfNjwcYyoUDhjJVcZBjYBy40j4wXgaobWoe8Z6Y80CJBwFpunepIzt2AUgFjtXXshNXjVmMh+K+zzp/CMs0CqeuzrxSRpbOKfdCkiMTS1VBQ41uxMyQR2qbrXiiwYN3ACh1FDmsdK2Eu4J6Tlo31dYVtCY88h5ELZIJJ+IRMzBHfyJINrigNkt5VsRiub9nXICdsYyVd2NcVvA3ScE5t2rb5JuEeyZnAhmLt9NK63vX1O5Pe8XaPSuGq1uTrfUgMEp9EJ+CQvr+BJ/AAKvAcCiAR+bf9CjAAluzmdX4AEIIAAAAASUVORK5CYII=">


问:
Include all Files in Bin folder in Wix installer
I'm new in Wix, I succefully create an MSI installer for my project, but my Bin folder have a lot of DLL's files with EXE main file, I want to include all these files with the installer

I found THIS solution, that seems right but unfortunately I can not accomplish this solution in my Wix file, Here's my Wix file:

```<code><Product Id="*" Name="Setup"
       Language="1033" Version="1.0.1.0"
       Manufacturer="ORDER MS"
       UpgradeCode="a4f0a0d0-ae64-4f62-9bb3-efa7e75072e0">

<Package InstallerVersion="200"
         Compressed="yes"
         InstallScope="perMachine" />

<MajorUpgrade Schedule="afterInstallInitialize"
              DowngradeErrorMessage="A newer version of [ProductName] is already installed." />

<MediaTemplate />

<Feature Id="ProductFeature" Title="Setup" Level="1">
  <ComponentGroupRef Id="ProductComponents" />
  <ComponentRef Id="ApplicationShortcutDesktop" />
  <ComponentRef Id="ApplicationShortcut" />
</Feature>

<Icon Id="Icon.exe" SourceFile="$(sys.CURRENTDIR)\icon.ico"/>
<Property Id="ARPPRODUCTICON" Value="icon.exe" />
</code>```

```<code><ComponentGroup Id="ProductComponents" Directory="INSTALLFOLDER">
  <Component Id="ProductComponent">
    <File Source="$(var.Order.TargetPath)" />
  </Component>

  <Component Guid="A7C42303-1D77-4C70-8D5C-0FD0F9158EB4" Id="CopyComponent">
    <CopyFile Id="SomeId"
              SourceProperty="SOURCEDIRECTORY"
              DestinationDirectory="CopyTestDir" SourceName="*" />
  </Component>
</ComponentGroup>
</code>```

I get this Error:

Error 1   ICE18: KeyPath for Component: 'CopyComponent' is Directory: 'INSTALLFOLDER'. The Directory/Component pair must be listed in the CreateFolders table.

答:
This solution works with WIX 3.11.

To harvest an entire directory, you can use Heat from the WIX toolset. With Heat we can automatically include all files from a given source directory on every build. To do that we first need to edit the Setup.wixproj:

Define the Harvestpath for Heat:

```<code><PropertyGroup>
  <DefineConstants>HarvestPath=...\Deploy</DefineConstants>
</PropertyGroup>
</code>```

Heat will create a .wxs file. So we need to add this file to the compile ItemGroup:

```<code><ItemGroup>
  <Compile Include="Product.wxs" /> <!-- This will be your default one -->
  <Compile Include="HeatGeneratedFileList.wxs" /> <!-- This is the Heat created one -->
</ItemGroup>
</code>```

Then execute Heat in the BeforeBuild build target:

```<code><Target Name="BeforeBuild">
  <HeatDirectory Directory="..\Deploy"
    PreprocessorVariable="var.HarvestPath"
    OutputFile="HeatGeneratedFileList.wxs"
    ComponentGroupName="HeatGenerated"
    DirectoryRefId="INSTALLFOLDER"
    AutogenerateGuids="true"
    ToolPath="$(WixToolPath)"
    SuppressFragments="true"
    SuppressRegistry="true"
    SuppressRootDirectory="true" />
</Target>
</code>```

This will generate the HeatGeneratedFileList.wxs every time the WIX installer is built. The directory ..\Deploy has to be set to the directory of the files to include.
The only thing we have to do to include these files in our installer is to edit the main .wxs file (like Product.wxs in this example). Heat will create a ComponentGroup with the given name from above. This component needs to be referenced in the Feature section of the Product.wxs:

```<code><Feature Id="ProductFeature" Title="DiBA Tool" Level="1">
  <...>
  <ComponentGroupRef Id="HeatGenerated" />
</Feature>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm new in Wix, I succefully create an MSI installer for my project, but my Bin folder have a lot of DLL's files with EXE main file, I want to include all these files with the installer

I found THIS solution, that seems right but unfortunately I can not accomplish this solution in my Wix file, Here's my Wix file:

<Product Id="*" Name="Setup"
       Language="1033" Version="1.0.1.0"
       Manufacturer="ORDER MS"
       UpgradeCode="a4f0a0d0-ae64-4f62-9bb3-efa7e75072e0">

<Package InstallerVersion="200"
         Compressed="yes"
         InstallScope="perMachine" />

<MajorUpgrade Schedule="afterInstallInitialize"
              DowngradeErrorMessage="A newer version of [ProductName] is already installed." />

<MediaTemplate />

<Feature Id="ProductFeature" Title="Setup" Level="1">
  <ComponentGroupRef Id="ProductComponents" />
  <ComponentRef Id="ApplicationShortcutDesktop" />
  <ComponentRef Id="ApplicationShortcut" />
</Feature>

<Icon Id="Icon.exe" SourceFile="$(sys.CURRENTDIR)\icon.ico"/>
<Property Id="ARPPRODUCTICON" Value="icon.exe" />

<ComponentGroup Id="ProductComponents" Directory="INSTALLFOLDER">
  <Component Id="ProductComponent">
    <File Source="$(var.Order.TargetPath)" />
  </Component>

  <Component Guid="A7C42303-1D77-4C70-8D5C-0FD0F9158EB4" Id="CopyComponent">
    <CopyFile Id="SomeId"
              SourceProperty="SOURCEDIRECTORY"
              DestinationDirectory="CopyTestDir" SourceName="*" />
  </Component>
</ComponentGroup>

I get this Error:

Error 1   ICE18: KeyPath for Component: 'CopyComponent' is Directory: 'INSTALLFOLDER'. The Directory/Component pair must be listed in the CreateFolders table.

Body:
This solution works with WIX 3.11.

To harvest an entire directory, you can use Heat from the WIX toolset. With Heat we can automatically include all files from a given source directory on every build. To do that we first need to edit the Setup.wixproj:

Define the Harvestpath for Heat:

<PropertyGroup>
  <DefineConstants>HarvestPath=...\Deploy</DefineConstants>
</PropertyGroup>

Heat will create a .wxs file. So we need to add this file to the compile ItemGroup:

<ItemGroup>
  <Compile Include="Product.wxs" /> <!-- This will be your default one -->
  <Compile Include="HeatGeneratedFileList.wxs" /> <!-- This is the Heat created one -->
</ItemGroup>

Then execute Heat in the BeforeBuild build target:

<Target Name="BeforeBuild">
  <HeatDirectory Directory="..\Deploy"
    PreprocessorVariable="var.HarvestPath"
    OutputFile="HeatGeneratedFileList.wxs"
    ComponentGroupName="HeatGenerated"
    DirectoryRefId="INSTALLFOLDER"
    AutogenerateGuids="true"
    ToolPath="$(WixToolPath)"
    SuppressFragments="true"
    SuppressRegistry="true"
    SuppressRootDirectory="true" />
</Target>

This will generate the HeatGeneratedFileList.wxs every time the WIX installer is built. The directory ..\Deploy has to be set to the directory of the files to include.
The only thing we have to do to include these files in our installer is to edit the main .wxs file (like Product.wxs in this example). Heat will create a ComponentGroup with the given name from above. This component needs to be referenced in the Feature section of the Product.wxs:

<Feature Id="ProductFeature" Title="DiBA Tool" Level="1">
  <...>
  <ComponentGroupRef Id="HeatGenerated" />
</Feature>


问:
Using a CTE to split results across a CROSS APPLY
I have some data that I need to output as rows containing markup tags, which I'm doing inside a table valued function.

This has been working fine up to a point using code in the format below, using the search query to gather my data, and then inserting into my returned table using the output from results.

I now need to take a longer data field and split it up over a number of rows, and I'm at something of a loss as to how to achieve this.

I started with the idea that I wanted to use a CTE to process the data from my query, but I can't see a way to get the data from my search query into my CTE and from there into my results set.

I guess I can see an alternative way of doing this by creating another table valued function in the database that returns a results set if I feed it my comment_text column, but it seems like a waste to do it that way.

Does anyone see a route through to a solution?

Example "Real" Table:

```<code>DECLARE @Comments TABLE
(
    id INT NOT NULL IDENTITY PRIMARY KEY CLUSTERED,
    comment_date DATETIME NOT NULL,
    first_name VARCHAR(50) NOT NULL,
    last_name VARCHAR(50) NOT NULL,
    comment_title VARCHAR(50) NOT NULL,
    comment_text char(500)
);
</code>```

Add Comment Rows:

```<code>INSERT INTO @Comments VALUES(CURRENT_TIMESTAMP, 'Bob', 'Example','Bob''s Comment', 'Text of Bob''s comment.');
INSERT INTO @Comments VALUES(CURRENT_TIMESTAMP, 'Alice', 'Example','Alice''s Comment', 'Text of Alice''s comment that is much longer and will need to be split over multiple rows.');
</code>```

Format of returned results table:

```<code>DECLARE @return_table TABLE
(
   comment_date DATETIME,
   commenter_name VARCHAR(101),
   markup VARCHAR(100)
);
</code>```

Naive query (Can't run because the variable comment_text in the SplitComment CTE can't be identified.

```<code>WITH SplitComment(note,start_idx) AS
(
   SELECT '<Note>'+SUBSTRING(comment_text,0,50)+'</Note>', 0
   UNION ALL
   SELECT '<Text>'+SUBSTRING(note,start_idx,50)+'</Text>', start_idx+50 FROM SplitComment WHERE (start_idx+50) < LEN(note)
)
INSERT INTO @return_table
SELECT results.* FROM
(
   SELECT
   comment_date,
   CAST(first_name+' '+last_name AS VARCHAR(101)) commenter,
   comment_title,
   comment_text
   FROM @Comments
) AS search
CROSS APPLY
(
           SELECT comment_date, commenter, '<title>'+comment_title+'</title>' markup
 UNION ALL SELECT comment_date, commenter, SplitComment
) AS results;

SELECT * FROM @return_table;
</code>```

Results (when the function is run without the CTE):

```<code>comment_date            commenter_name                                                                                markup
2017-07-07 11:53:57.240 Bob Example                                                                                <title>Bob's Comment</title>
2017-07-07 11:53:57.240 Alice Example                                                                                <title>Alice's Comment</title>
</code>```

Ideally, I'd like to get one additional row for Bob's comment, and two rows for Alice's comment. Something like this:

```<code>comment_date            commenter_name   markup
2017-07-07 11:53:57.240 Bob Example      <title>Bob's Comment</title>
2017-07-07 11:53:57.240 Bob Example      <Note>Bob's Comment</Note>
2017-07-07 11:53:57.240 Alice Example    <title>Alice's Comment</title>
2017-07-07 11:53:57.240 Alice Example    <Note>Text of Alice''s comment that is much longer and w</Note>
2017-07-07 11:53:57.240 Alice Example    <Text>ill need to be split over multiple rows.</Text>
</code>```

答:
Here's a solution that also allows sorting the resultset

It uses a recursive CTE to calculate the positions in the long text.
And by joining the table to the CTE, the text can be sliced up into rows.

```<code>with cte as
(
  select id, 1 as lvl, len(comment_text) as posmax, 1 pos1, 50 limit
  from @Comments
  union all
  select id, lvl + 1, posmax, iif(pos1+limit<posmax,pos1+limit,posmax), limit
  from cte
  where pos1+limit<posmax
)
, CTE2 AS
(
select id, 0 as lvl,
 comment_date,
 concat(first_name,' ',last_name) as commenter,
 '<Title>'+rtrim(comment_title)+'</Title>' as markup
from @Comments
union all
select t.id, c.lvl,
 comment_date,
 concat(first_name,' ',last_name) as commenter_name,
 concat(iif(lvl=1,'<Note>','<Text>'),substring(comment_text,pos1,limit),iif(lvl=1,'</Note>','</Text>')) as markup
from @Comments t
join cte c on c.id = t.id
)
select comment_date, commenter, markup
from CTE2
order by id, lvl;
</code>```

Output:

```<code>comment_date             commenter     markup
-----------------------  ------------  -------------------------------------
2017-07-07 15:06:31.293  Bob Example   <Title>Bob's Comment</Title>
2017-07-07 15:06:31.293  Bob Example   <Note>Text of Bob's comment.</Note>
2017-07-07 15:06:31.293  Alice Example <Title>Alice's Comment</Title>
2017-07-07 15:06:31.293  Alice Example <Note>Text of Alice's comment that is much longer and wi</Note>
2017-07-07 15:06:31.293  Alice Example <Text>ll need to be split over multiple rows.</Text>
</code>```

Body:
I have some data that I need to output as rows containing markup tags, which I'm doing inside a table valued function.

This has been working fine up to a point using code in the format below, using the search query to gather my data, and then inserting into my returned table using the output from results.

I now need to take a longer data field and split it up over a number of rows, and I'm at something of a loss as to how to achieve this.

I started with the idea that I wanted to use a CTE to process the data from my query, but I can't see a way to get the data from my search query into my CTE and from there into my results set.

I guess I can see an alternative way of doing this by creating another table valued function in the database that returns a results set if I feed it my comment_text column, but it seems like a waste to do it that way.

Does anyone see a route through to a solution?

Example "Real" Table:

DECLARE @Comments TABLE
(
    id INT NOT NULL IDENTITY PRIMARY KEY CLUSTERED,
    comment_date DATETIME NOT NULL,
    first_name VARCHAR(50) NOT NULL,
    last_name VARCHAR(50) NOT NULL,
    comment_title VARCHAR(50) NOT NULL,
    comment_text char(500)
);

Add Comment Rows:

INSERT INTO @Comments VALUES(CURRENT_TIMESTAMP, 'Bob', 'Example','Bob''s Comment', 'Text of Bob''s comment.');
INSERT INTO @Comments VALUES(CURRENT_TIMESTAMP, 'Alice', 'Example','Alice''s Comment', 'Text of Alice''s comment that is much longer and will need to be split over multiple rows.');

Format of returned results table:

DECLARE @return_table TABLE
(
   comment_date DATETIME,
   commenter_name VARCHAR(101),
   markup VARCHAR(100)
);

Naive query (Can't run because the variable comment_text in the SplitComment CTE can't be identified.

WITH SplitComment(note,start_idx) AS
(
   SELECT '<Note>'+SUBSTRING(comment_text,0,50)+'</Note>', 0
   UNION ALL
   SELECT '<Text>'+SUBSTRING(note,start_idx,50)+'</Text>', start_idx+50 FROM SplitComment WHERE (start_idx+50) < LEN(note)
)
INSERT INTO @return_table
SELECT results.* FROM
(
   SELECT
   comment_date,
   CAST(first_name+' '+last_name AS VARCHAR(101)) commenter,
   comment_title,
   comment_text
   FROM @Comments
) AS search
CROSS APPLY
(
           SELECT comment_date, commenter, '<title>'+comment_title+'</title>' markup
 UNION ALL SELECT comment_date, commenter, SplitComment
) AS results;

SELECT * FROM @return_table;

Results (when the function is run without the CTE):

comment_date            commenter_name                                                                                markup
2017-07-07 11:53:57.240 Bob Example                                                                                <title>Bob's Comment</title>
2017-07-07 11:53:57.240 Alice Example                                                                                <title>Alice's Comment</title>

Ideally, I'd like to get one additional row for Bob's comment, and two rows for Alice's comment. Something like this:

comment_date            commenter_name   markup
2017-07-07 11:53:57.240 Bob Example      <title>Bob's Comment</title>
2017-07-07 11:53:57.240 Bob Example      <Note>Bob's Comment</Note>
2017-07-07 11:53:57.240 Alice Example    <title>Alice's Comment</title>
2017-07-07 11:53:57.240 Alice Example    <Note>Text of Alice''s comment that is much longer and w</Note>
2017-07-07 11:53:57.240 Alice Example    <Text>ill need to be split over multiple rows.</Text>

Body:
Here's a solution that also allows sorting the resultset

It uses a recursive CTE to calculate the positions in the long text.
And by joining the table to the CTE, the text can be sliced up into rows.

with cte as
(
  select id, 1 as lvl, len(comment_text) as posmax, 1 pos1, 50 limit
  from @Comments
  union all
  select id, lvl + 1, posmax, iif(pos1+limit<posmax,pos1+limit,posmax), limit
  from cte
  where pos1+limit<posmax
)
, CTE2 AS
(
select id, 0 as lvl,
 comment_date,
 concat(first_name,' ',last_name) as commenter,
 '<Title>'+rtrim(comment_title)+'</Title>' as markup
from @Comments
union all
select t.id, c.lvl,
 comment_date,
 concat(first_name,' ',last_name) as commenter_name,
 concat(iif(lvl=1,'<Note>','<Text>'),substring(comment_text,pos1,limit),iif(lvl=1,'</Note>','</Text>')) as markup
from @Comments t
join cte c on c.id = t.id
)
select comment_date, commenter, markup
from CTE2
order by id, lvl;

Output:

comment_date             commenter     markup
-----------------------  ------------  -------------------------------------
2017-07-07 15:06:31.293  Bob Example   <Title>Bob's Comment</Title>
2017-07-07 15:06:31.293  Bob Example   <Note>Text of Bob's comment.</Note>
2017-07-07 15:06:31.293  Alice Example <Title>Alice's Comment</Title>
2017-07-07 15:06:31.293  Alice Example <Note>Text of Alice's comment that is much longer and wi</Note>
2017-07-07 15:06:31.293  Alice Example <Text>ll need to be split over multiple rows.</Text>


问:
How to test if function was called with defined parameters ( toHaveBeenCalledWith ) with Jest
I want to test, if particular function was called in my test and with the correct parameters. From JEST documentation I'm not able to figure out, what is the correct way to do it.

Let's say I have something like this:

```<code>// add.js

function child(ch) {
   const t = ch + 1;
   // no return value here. Function has some other "side effect"
}

function main(a) {
  if (a == 2) {
    child(a + 2);
  }

  return a + 1;
}

exports.main = main;
exports.child = child;
</code>```

Now in unit test:

1.
I want to run main(1) and test that it returned 2 and child() was not called.

2.
And then I want to run main(2) and thest that it returned 3 and child(4) was called exactly once.

I have something like this now:

```<code>// add-spec.js
module = require('./add');

describe('main', () => {

  it('should add one and not call child Fn', () => {
    expect(module.main(1)).toBe(2);
    // TODO: child() was not called
  });

  it('should add one andcall child Fn', () => {

    expect(module.main(2)).toBe(3);
    // TODO: child() was called with param 4 exactly once
    // expect(module.child).toHaveBeenCalledWith(4);
  });

});
</code>```

I'm testing this in https://repl.it/languages/jest , so a working example in this REPL will be much appreciated.

答:
OK, I've figured it out. The trick is, to split functions into separate files. So the code is (and works in https://repl.it/languages/jest ):

```<code>// add.js
child = require('./child').child;

function main(a) {
  if (a == 2) {
    child(a + 2);
  }

  return a + 1;
}

exports.main = main;
</code>```

extracted child.js file:

```<code>// child.js

function child(ch) {
   const t = ch + 1;
   // no return value here. Function has some other "side effect"
}

exports.child = child;
</code>```

main test file:

```<code>// add-spec.js
main = require('./add').main;
child = require('./child').child;

child = jest.fn();

describe('main', () => {

  it('should add one and not call child Fn', () => {
    expect(main(1)).toBe(2);

    expect(child).toHaveBeenCalledTimes(0);
  });

  it('should add one andcall child Fn', () => {
    expect(main(2)).toBe(3);

    expect(child).toHaveBeenCalledWith(4);
    expect(child).toHaveBeenCalledTimes(1);
  });

});
</code>```

Body:
I want to test, if particular function was called in my test and with the correct parameters. From JEST documentation I'm not able to figure out, what is the correct way to do it.

Let's say I have something like this:

// add.js

function child(ch) {
   const t = ch + 1;
   // no return value here. Function has some other "side effect"
}

function main(a) {
  if (a == 2) {
    child(a + 2);
  }

  return a + 1;
}

exports.main = main;
exports.child = child;

Now in unit test:

1.
I want to run main(1) and test that it returned 2 and child() was not called.

2.
And then I want to run main(2) and thest that it returned 3 and child(4) was called exactly once.

I have something like this now:

// add-spec.js
module = require('./add');

describe('main', () => {

  it('should add one and not call child Fn', () => {
    expect(module.main(1)).toBe(2);
    // TODO: child() was not called
  });

  it('should add one andcall child Fn', () => {

    expect(module.main(2)).toBe(3);
    // TODO: child() was called with param 4 exactly once
    // expect(module.child).toHaveBeenCalledWith(4);
  });

});

I'm testing this in https://repl.it/languages/jest , so a working example in this REPL will be much appreciated.

Body:
OK, I've figured it out. The trick is, to split functions into separate files. So the code is (and works in https://repl.it/languages/jest ):

// add.js
child = require('./child').child;

function main(a) {
  if (a == 2) {
    child(a + 2);
  }

  return a + 1;
}

exports.main = main;

extracted child.js file:

// child.js

function child(ch) {
   const t = ch + 1;
   // no return value here. Function has some other "side effect"
}

exports.child = child;

main test file:

// add-spec.js
main = require('./add').main;
child = require('./child').child;

child = jest.fn();

describe('main', () => {

  it('should add one and not call child Fn', () => {
    expect(main(1)).toBe(2);

    expect(child).toHaveBeenCalledTimes(0);
  });

  it('should add one andcall child Fn', () => {
    expect(main(2)).toBe(3);

    expect(child).toHaveBeenCalledWith(4);
    expect(child).toHaveBeenCalledTimes(1);
  });

});


问:
HTML Form Value = Javascript variable
I want to display "something" on the HTML forms textbox
this value should be a javascript variable

var paramvalue = "something"
document.getElementById("client_id").value = paramvalue```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form action="login.php" method="post">
       <input type="hidden" name="clientID" id="client_id" value="" />
       <button>Login</button>
</form></code>```

答:
You have to put the script after the HTML, since when it is run, the input field doesn't exist yet, so it will return an error.</p>

```<code><form action="login.php" method="post">
    <input type="hidden" name="clientID" id="client_id" value="" />
    <button>Login</button>
</form>
<script type="text/javascript">
    var paramvalue = "something";
    document.getElementById("client_id").value = paramvalue;
</script>
</code>```

Title: HTML Form Value = Javascript variable

Body:
I want to display "something" on the HTML forms textbox
this value should be a javascript variable

var paramvalue = "something"
document.getElementById("client_id").value = paramvalue

<form action="login.php" method="post">
       <input type="hidden" name="clientID" id="client_id" value="" />
       <button>Login</button>
</form>

Body:
You have to put the script after the HTML, since when it is run, the input field doesn't exist yet, so it will return an error.

<form action="login.php" method="post">
    <input type="hidden" name="clientID" id="client_id" value="" />
    <button>Login</button>
</form>
<script type="text/javascript">
    var paramvalue = "something";
    document.getElementById("client_id").value = paramvalue;
</script>


问:
Approach to make a one line script into a one line command?
Below is my "one liner" in a script.

```<code>#!/usr/bin/ruby

puts ARGF.read.gsub(/\\caption\{((?:[^{}]+|\{\g<1>\})+)\}/m) { |xx, yy|
  Regexp.last_match[0].gsub(/([^\\])#/,'\1\\#') }
</code>```

If I just insert in ruby -pe '' I get

```<code>-e:1: syntax error, unexpected $undefined, expecting ')'
...ast_match[0].gsub(/([^\\])#/,1\#) }
...                               ^
</code>```

With double quotes I get

```<code>-e:1: premature end of char-class: /([^\])#/
</code>```

Question

So the question is what is the approach to make it work in ruby -pe ''?

答:
I don't know what you are trying to do, but the standard way to escape strings to be used in a shell is something like this:</p>

```<code>require "shellwords"

`some_command #{Shellwords.escape(some_command_written_in_ruby_string)}`
</code>```

Body:
Below is my "one liner" in a script.

#!/usr/bin/ruby

puts ARGF.read.gsub(/\\caption\{((?:[^{}]+|\{\g<1>\})+)\}/m) { |xx, yy|
  Regexp.last_match[0].gsub(/([^\\])#/,'\1\\#') }

If I just insert in ruby -pe '' I get

-e:1: syntax error, unexpected $undefined, expecting ')'
...ast_match[0].gsub(/([^\\])#/,1\#) }
...                               ^

With double quotes I get

-e:1: premature end of char-class: /([^\])#/

Question

So the question is what is the approach to make it work in ruby -pe ''?

Body:
I don't know what you are trying to do, but the standard way to escape strings to be used in a shell is something like this:

require "shellwords"

`some_command #{Shellwords.escape(some_command_written_in_ruby_string)}`


问:
Using Razor inside VueJs Component
To avoid repeat re-writing the same code multiple times,I'm using VueJs component feature to make a component that includes the Select dropdown list.
The code goes like this

```<code> Vue.component('select-component', {
        template: `
            <label>elType</label>
            <div class="col-md-colwidth">
            <select>
                <option value=""></option>
                @foreach (elType s in ViewBag.elTypes)
                {
                    <option value="@s[elType+"ID"]">@s["Designation"+elType]</option>
                }
            </select>
            <input type="hidden" v-model="elTarget">
            </div>
            `,
        props: {
            elType: {
                type: String,
                default: 'User'
            },
            elTarget: {
                type: String,
                default: 'user'
            },
            colwidth: {
                type: int,
                default: '3'},

        }
    })
</code>```

As you can see, I'm requiring some data list I brought from the ViewBag
but all i get is that the Razor is always ignoring that it is inside a Vue Component and giving "The type or namespace name 'elType' could not be found ".

P.S:
1) the input Hidden is used in the original code to manipulate the bs jQuery select2

2)Don't mind the elTarget and elType :p it's actually same thing except I'm lazy to camelCase the word :p

3)I tried to wrap the  inside @{    } but still toggle the same error

答:
You can't use Razor 'inside' a Vue component because Razor generates the page server-side before Vue gets to do its stuff in the browser. What you have there is a Vue component inside a Razor page. elType is defined as a Vue prop, so it likely isn't in your view bag?

In any case, please don't do this! Use Razor or Vue. If you choose Vue, your vue components are static .js or .vue files, your data arrives via AJAX calls, and you loop through elTypes with v-for, in the browser. Any other way will lead to madness :-)

Title: Using Razor inside VueJs Component

Body:
To avoid repeat re-writing the same code multiple times,I'm using VueJs component feature to make a component that includes the Select dropdown list.
The code goes like this

 Vue.component('select-component', {
        template: `
            elType

            <select>
                <option value=""></option>
                @foreach (elType s in ViewBag.elTypes)
                {
                    <option value="@s[elType+"ID"]">@s["Designation"+elType]</option>
                }
            </select>
            <input type="hidden" v-model="elTarget">

            `,
        props: {
            elType: {
                type: String,
                default: 'User'
            },
            elTarget: {
                type: String,
                default: 'user'
            },
            colwidth: {
                type: int,
                default: '3'},

        }
    })

As you can see, I'm requiring some data list I brought from the ViewBag
but all i get is that the Razor is always ignoring that it is inside a Vue Component and giving "The type or namespace name 'elType' could not be found ".

P.S:
1) the input Hidden is used in the original code to manipulate the bs jQuery select2

2)Don't mind the elTarget and elType :p it's actually same thing except I'm lazy to camelCase the word :p

3)I tried to wrap the  inside @{    } but still toggle the same error


问:
How to update a table which is being used in nested queries?
I am trying to update a table and getting the following error message:

You can't specify target table 'nodeassociation' for update in FROM clause

This is related to updating a table which is being used in nested or inner subqueries.

This is my SQL query:

```<code>UPDATE nodeassociation
SET sink_node_id = 11608
WHERE sink_node_entity = 'WorkflowScheme'
  AND source_node_id IN (SELECT source_node_id
                         FROM nodeassociation
                         WHERE SINK_NODE_ENTITY = 'WorkflowScheme'
                           AND sink_node_id = 11604
                           AND SOURCE_NODE_ID IN (SELECT source_node_id
                                                  FROM nodeassociation
                                                  WHERE association_type = 'ProjectCategory'
                                                    AND sink_node_id = 11400));
</code>```

The inner queries run fine separately.

Could anyone please tell me how to fix this query?

Thanks

答: You can create the temporary table from your subselect and then use it in the update.</p>

Body:
I am trying to update a table and getting the following error message:

You can't specify target table 'nodeassociation' for update in FROM clause

This is related to updating a table which is being used in nested or inner subqueries.

This is my SQL query:

UPDATE nodeassociation
SET sink_node_id = 11608
WHERE sink_node_entity = 'WorkflowScheme'
  AND source_node_id IN (SELECT source_node_id
                         FROM nodeassociation
                         WHERE SINK_NODE_ENTITY = 'WorkflowScheme'
                           AND sink_node_id = 11604
                           AND SOURCE_NODE_ID IN (SELECT source_node_id
                                                  FROM nodeassociation
                                                  WHERE association_type = 'ProjectCategory'
                                                    AND sink_node_id = 11400));

The inner queries run fine separately.

Could anyone please tell me how to fix this query?

Thanks