问:
How to map translations to a database
I want in the moment that an user register in my system, he chooses the language (tbParam[language]) and based on the language that he choose the Countries available to him are already translated

When the user register in my system he's able to choose a language, that gets stored into tbParam[language], and with that choosen language the rest of the website would get translated accordingly.

First I thought about doing it via resources on my C#, with a Key and Value, as so:
Resources screenshot on the left it's the name in the default language (portuguese) and the value is the key translated to English, it works just fine for one language but I pretend on doing it for Spanish, German, and English. Then I thought about all the work on doing it and I thought of the second way.

Second way: Using a database

I was thinking about creating some tables that contains the languages, the countries and the translations. Which all of them are linked to each other, by the time that you choose the language, the database for the translations by the language key and handle the result of the query in my c# code.

I would like to know which way is the best, if it's the Database one then what would be the best approach regarding the table relantionships.

答:
You can use a resource file for each language. All you need is to include several resources files to your project:

e.g. add resource file names YourResourceFileName.resx.
them to add a resource file for a specific language add the resource file named YourResourceFileName.[CULTURECODE].resx
For spanish add YourResourceFileName.es.resx
For German add YourResourceFileName.de.resx
(You can even use a resource file por a specific culture like en-US or en-GB)

Then consider edit the .csproj file directly and include the new files as dependencies of the previous one(you can right click the project, select "Unload Project" then right click again and select "Edit .csproj" - when done, reload the project via the right click.

You will need to change:

```<code><Compile Include="YourResourceFileName.es.Designer.cs">
  <DependentUpon>YourResourceFileName.es.resx</DependentUpon>
</Compile>
<Compile Include="YourResourceFileName.es.resx">
</code>```

to:

```<code><Compile Include="YourResourceFileName.es.resx">
  <DependentUpon>YourResourceFileName.resx</DependentUpon>
</Compile>
</code>```

This will put both YourResourceFileName.es.resx and YourResourceFileName.es.Designer.cs under the YourResourceFileName.resx node.

Do the same to the German resource file, change:

```<code><Compile Include="YourResourceFileName.de.Designer.cs">
  <DependentUpon>YourResourceFileName.de.resx</DependentUpon>
</Compile>
<Compile Include="YourResourceFileName.de.resx">
</code>```

to:

```<code><Compile Include="YourResourceFileName.de.resx">
  <DependentUpon>YourResourceFileName.resx</DependentUpon>
</Compile>
</code>```

You will end up having something like this:

Title: How to map translations to a database

Body:
You can use a resource file for each language. All you need is to include several resources files to your project:

e.g. add resource file names YourResourceFileName.resx.
them to add a resource file for a specific language add the resource file named YourResourceFileName.[CULTURECODE].resx
For spanish add YourResourceFileName.es.resx
For German add YourResourceFileName.de.resx
(You can even use a resource file por a specific culture like en-US or en-GB)

Then consider edit the .csproj file directly and include the new files as dependencies of the previous one(you can right click the project, select "Unload Project" then right click again and select "Edit .csproj" - when done, reload the project via the right click.

You will need to change:

<Compile Include="YourResourceFileName.es.Designer.cs">
  <DependentUpon>YourResourceFileName.es.resx</DependentUpon>
</Compile>
<Compile Include="YourResourceFileName.es.resx">

to:

<Compile Include="YourResourceFileName.es.resx">
  <DependentUpon>YourResourceFileName.resx</DependentUpon>
</Compile>

This will put both YourResourceFileName.es.resx and YourResourceFileName.es.Designer.cs under the YourResourceFileName.resx node.

Do the same to the German resource file, change:

<Compile Include="YourResourceFileName.de.Designer.cs">
  <DependentUpon>YourResourceFileName.de.resx</DependentUpon>
</Compile>
<Compile Include="YourResourceFileName.de.resx">

to:

<Compile Include="YourResourceFileName.de.resx">
  <DependentUpon>YourResourceFileName.resx</DependentUpon>
</Compile>

You will end up having something like this:


来源: stackexchange

问:
Image src breaks when in another page other than homepage
My images are located in

images/icons/artist_default.png

So, when I'm on the homepage, the image is shown and if I see the path it looks like this:

http://localhost:7777/images/icons/artist_default.png

However, in a users page like this one http://localhost:7777/user/giorgio-martini it breaks and the path looks like this:

http://localhost:7777/user/images/icons/artist_default.png

As you can see, its wrong, it adds the users parameter before it.. so it breaks.

I don't know how to fix this, I shouldn't add a full path, it doesn't feel right... but how do I make the img points to the right place?

Thanks

答:
start image source with a slash('/'). It means it will always start from the basepath.
Instead of,

```<code><img src="images/icons/artist_default.png">
</code>```

use this,

```<code><img src="/images/icons/artist_default.png">
</code>```

ContentLicense: CC BY-SA 4.0

Body:
start image source with a slash('/'). It means it will always start from the basepath.
Instead of,

<img src="images/icons/artist_default.png">

use this,

<img src="/images/icons/artist_default.png">


问:
Cannot Use Text String with Comparison Operator as Input to Filter()
I am trying to use selected items from a slicer as the input to a filter statement. To get the slicer selections, I am building up a text string, which has a comparison operator.  The chart that I am using this in, then gives an error, 'Calculation error in measure ... of type text to type true/false'.

I have a measure that I created to count the number of items opened & closed within a given timeframe.  I have a date slicer, from which I am successfully pulling the start/stop dates and using those as inputs to my Filter statement, and counting the rows returned.

I am now trying to add a name selection from a slicer to the Filter statement and not having much luck.

I am pulling the names selected from a slicer with the following code.

```<code>Names = CONCATENATEX(
ALLSELECTED(Table[Column]),
"Table[Column]="&Table[Column],
"  || ")
</code>```

This gives me a text string like, 'Table[Column]="John Smith" || Table[column] "Jane Smith"

When I put this into my filter statement

```<code>Filter(Working Filters && (Names))
</code>```

That's when I get my error.  If I type the statement in directly, it works.  But that doesn't help me, since I will not know what is selected

```<code>Filter(Working Filters && (Table[Column]="John Smith" || Table[column] "Jane Smith")
</code>```

How can I use my text String as the input to the filter?  Or is there a different way that i could get my slicer selections into filter?

答:
The FILTER function doesn't take text arguments like that. To read values from a slicer, you can use SELECTEDVALUE (for a single value) or VALUES (for possibly multiple values). However, most of the time, if your tables and relationships are set up correctly, you shouldn't have to do that manually unless you are using a slicer to set a parameter rather than as a filter.

Let's say you have Table1 and Table2 that are not related and you are using Table2[Column2] as a slicer. Then you could write a filter like this:

```<code>FILTER( Table1, Table1[Column1] IN VALUES( Table2[Column2] ) )
</code>```

Thus even though Table1 and Table2 are not related, you are only allowing values in Table1[Column1] that match the values you've selected with your Table2[Column2] slicer.

Body:
I am trying to use selected items from a slicer as the input to a filter statement. To get the slicer selections, I am building up a text string, which has a comparison operator.  The chart that I am using this in, then gives an error, 'Calculation error in measure ... of type text to type true/false'.

I have a measure that I created to count the number of items opened & closed within a given timeframe.  I have a date slicer, from which I am successfully pulling the start/stop dates and using those as inputs to my Filter statement, and counting the rows returned.

I am now trying to add a name selection from a slicer to the Filter statement and not having much luck.

I am pulling the names selected from a slicer with the following code.

Names = CONCATENATEX(
ALLSELECTED(Table[Column]),
"Table[Column]="&Table[Column],
"  || ")

This gives me a text string like, 'Table[Column]="John Smith" || Table[column] "Jane Smith"

When I put this into my filter statement

Filter(Working Filters && (Names))

That's when I get my error.  If I type the statement in directly, it works.  But that doesn't help me, since I will not know what is selected

Filter(Working Filters && (Table[Column]="John Smith" || Table[column] "Jane Smith")

How can I use my text String as the input to the filter?  Or is there a different way that i could get my slicer selections into filter?

Body:
The FILTER function doesn't take text arguments like that. To read values from a slicer, you can use SELECTEDVALUE (for a single value) or VALUES (for possibly multiple values). However, most of the time, if your tables and relationships are set up correctly, you shouldn't have to do that manually unless you are using a slicer to set a parameter rather than as a filter.

Let's say you have Table1 and Table2 that are not related and you are using Table2[Column2] as a slicer. Then you could write a filter like this:

FILTER( Table1, Table1[Column1] IN VALUES( Table2[Column2] ) )

Thus even though Table1 and Table2 are not related, you are only allowing values in Table1[Column1] that match the values you've selected with your Table2[Column2] slicer.


问:
Get Signed Download URL of pdf uploaded to Firebase Storage with Firebase Functions
After much time spent on Google and countless hours of documentation reading, I've come here to place this question as I'm not making any more progress.

I'm trying to upload a file to Firebase Storage using a firebase function and then get the download url to send back at the finalization of the firebase function.

To start with, I've included the firebase-admin and @google-cloud/storage at the top of my index.js. And initialized them.

```<code>const storage = require('@google-cloud/storage');
const functions = require('firebase-functions');
const admin = require("firebase-admin");

admin.initializeApp({
   credential: admin.credential.cert({
       // removed for security
       // This block was provided by Firebase Admin SDK
       // under service accounts in settings of Firebase.
   }),
   databaseUrl: //removed for security,
   storageBucket: //removed for security
});
</code>```

Then finally, my function that creates a firebase database record, generates a PDF and stores that file in firebase storage and then should return me a valid url to get the pdf.

```<code>exports.createInvoice = functions.https.onRequest((req, res) => {
    cors(req, res, () => {
        if(req.method == 'POST') {
            generateInvoiceNumber().then((number) => {
                req.body.number = number.number;
                req.body.created = admin.database.ServerValue.TIMESTAMP;
                var total = 0;
                var items = req.body.items;
                for (var i = items.length - 1; i >= 0; i--) {
                    total = total + (items[i].cost * items[i].qty);
                }
                req.body.total = total.toFixed(2);
                admin.database().ref('invoices').push(req.body).then(function(response){
                    var html = // removed for brevity;
                    var file = admin.storage().bucket().file('/tmp/invoice-'+number.number+'.pdf');
                    htmlPdf.create(html).toStream(function(err, stream){
                        stream.pipe(file.createWriteStream());
                        //stream.on('finish', function(){
                            const config = {
                                action: 'read',
                                expires: '03-09-2491',
                                contentType: 'application/pdf'
                            };
                            admin.storage().bucket().file('tmp/invoice-'+number.number+'.pdf').getSignedUrl(config).then(signedUrls => {
                                res.status(200).send(signedUrls);
                            })
                        //});
                    });
                });
            }).catch(error => {
                res.status(500).send(error);
            })
        } else {
            res.status(405).send('Method Not Allowed');
        }
    });
});
</code>```

The only portion that is not working correctly is the returned URL near the end of my function.

```<code>admin.storage().bucket().file('tmp/invoice-'+number.number+'.pdf').getSignedUrl(config).then(signedUrls => {
  res.status(200).send(signedUrls);
});
</code>```

When I try to access the returned url in my browser, I get the following error.

```<code>The request signature we calculated does not match the signature you provided. Check your Google secret key and signing method.
</code>```

答:
Well, what I'm doing because I'm using something like this, I found that the key you are looking for in the metadata, is mediaLink. Here is my code examp.

```<code>                  admin.storage().bucket().file(`home/home-carousel/${filename}`).save(file, (data) => {
                if(!data){
                  res(admin.storage().bucket().file(`home/home-carousel/${filename}`).getMetadata().mediaLink)
                }
              } )
</code>```

The res() is the portion you want!

EDIT: getMetadata returns a promise you have to resolve in order to get metadata, if you don't to this, your mediaLink will be undefined. And, there are several arguments passed back from the promise, access them like an array, I provided a code example.

```<code>const saveLocation = storage.bucket('salesportal-8b7ef.appspot.com').file(`home/home-carousel/${webPFileName}`)
                  saveLocation.save(data, (stuff) => {
                    if(!stuff){
                      saveLocation.makePublic().then( () => {
                        saveLocation.getMetadata()
                        .then( (meta) => {
                          metadata = meta[0]
                            admin.firestore().collection("Pages").doc("home-carousel").set({ homeCarousel : {[`${filename}`] : { webPUrl : `${metadata.mediaLink}`}} }, {merge: true}).then(
                              () => {
                                resolve()
                              })
                        })

                      })
                    }
</code>```

Body:
After much time spent on Google and countless hours of documentation reading, I've come here to place this question as I'm not making any more progress.

I'm trying to upload a file to Firebase Storage using a firebase function and then get the download url to send back at the finalization of the firebase function.

To start with, I've included the firebase-admin and @google-cloud/storage at the top of my index.js. And initialized them.

const storage = require('@google-cloud/storage');
const functions = require('firebase-functions');
const admin = require("firebase-admin");

admin.initializeApp({
   credential: admin.credential.cert({
       // removed for security
       // This block was provided by Firebase Admin SDK
       // under service accounts in settings of Firebase.
   }),
   databaseUrl: //removed for security,
   storageBucket: //removed for security
});

Then finally, my function that creates a firebase database record, generates a PDF and stores that file in firebase storage and then should return me a valid url to get the pdf.

exports.createInvoice = functions.https.onRequest((req, res) => {
    cors(req, res, () => {
        if(req.method == 'POST') {
            generateInvoiceNumber().then((number) => {
                req.body.number = number.number;
                req.body.created = admin.database.ServerValue.TIMESTAMP;
                var total = 0;
                var items = req.body.items;
                for (var i = items.length - 1; i >= 0; i--) {
                    total = total + (items[i].cost * items[i].qty);
                }
                req.body.total = total.toFixed(2);
                admin.database().ref('invoices').push(req.body).then(function(response){
                    var html = // removed for brevity;
                    var file = admin.storage().bucket().file('/tmp/invoice-'+number.number+'.pdf');
                    htmlPdf.create(html).toStream(function(err, stream){
                        stream.pipe(file.createWriteStream());
                        //stream.on('finish', function(){
                            const config = {
                                action: 'read',
                                expires: '03-09-2491',
                                contentType: 'application/pdf'
                            };
                            admin.storage().bucket().file('tmp/invoice-'+number.number+'.pdf').getSignedUrl(config).then(signedUrls => {
                                res.status(200).send(signedUrls);
                            })
                        //});
                    });
                });
            }).catch(error => {
                res.status(500).send(error);
            })
        } else {
            res.status(405).send('Method Not Allowed');
        }
    });
});

The only portion that is not working correctly is the returned URL near the end of my function.

admin.storage().bucket().file('tmp/invoice-'+number.number+'.pdf').getSignedUrl(config).then(signedUrls => {
  res.status(200).send(signedUrls);
});

When I try to access the returned url in my browser, I get the following error.

The request signature we calculated does not match the signature you provided. Check your Google secret key and signing method.

Body:
Well, what I'm doing because I'm using something like this, I found that the key you are looking for in the metadata, is mediaLink. Here is my code examp.

                  admin.storage().bucket().file(`home/home-carousel/${filename}`).save(file, (data) => {
                if(!data){
                  res(admin.storage().bucket().file(`home/home-carousel/${filename}`).getMetadata().mediaLink)
                }
              } )

The res() is the portion you want!

EDIT: getMetadata returns a promise you have to resolve in order to get metadata, if you don't to this, your mediaLink will be undefined. And, there are several arguments passed back from the promise, access them like an array, I provided a code example.

const saveLocation = storage.bucket('salesportal-8b7ef.appspot.com').file(`home/home-carousel/${webPFileName}`)
                  saveLocation.save(data, (stuff) => {
                    if(!stuff){
                      saveLocation.makePublic().then( () => {
                        saveLocation.getMetadata()
                        .then( (meta) => {
                          metadata = meta[0]
                            admin.firestore().collection("Pages").doc("home-carousel").set({ homeCarousel : {[`${filename}`] : { webPUrl : `${metadata.mediaLink}`}} }, {merge: true}).then(
                              () => {
                                resolve()
                              })
                        })

                      })
                    }


问:
Why is a period in a character class not matching only a literal period
```<code>console.log("<p>email@address.com</p>".match(/([a-zA-Z0-9.-_+]+@[a-zA-Z0-9.-]+\.[a-z]{2,10})/g))
</code>```

["
email@address.com"]

Can someone help me understand why the < > characters are matching this regular expression? I always thought that a . in a character class [] was interpreted literally.

When I remove the ., it no longer returns that paragraph tag.

答:
There is a potential hidden problem in your regex:

```<code>([a-zA-Z0-9.-_+]+@[a-zA-Z0-9.-]+\.[a-z]{2,10}
</code>```

If you look closely at the first character class, you will see that hyphen defines a range between . and _.  This could be unintentionally including characters which you don't want.  Try moving the hyphen to the end of the character class:

```<code>([a-zA-Z0-9._+-]+@[a-zA-Z0-9.-]+\.[a-z]{2,10}
</code>```

Here is a regex demo for [a-zA-Z0-9.-_+] before and after.  Note that @ and ^ were being matched in the original version, but then stopped being matched after moving - to the end of the class.

Body:
console.log("
email@address.com
".match(/([a-zA-Z0-9.-_+]+@[a-zA-Z0-9.-]+\.[a-z]{2,10})/g))

["
email@address.com"]

Can someone help me understand why the < > characters are matching this regular expression? I always thought that a . in a character class [] was interpreted literally.

When I remove the ., it no longer returns that paragraph tag.

Body:
There is a potential hidden problem in your regex:

([a-zA-Z0-9.-_+]+@[a-zA-Z0-9.-]+\.[a-z]{2,10}

If you look closely at the first character class, you will see that hyphen defines a range between . and _.  This could be unintentionally including characters which you don't want.  Try moving the hyphen to the end of the character class:

([a-zA-Z0-9._+-]+@[a-zA-Z0-9.-]+\.[a-z]{2,10}

Here is a regex demo for [a-zA-Z0-9.-_+] before and after.  Note that @ and ^ were being matched in the original version, but then stopped being matched after moving - to the end of the class.


问:
How to use CSPs on iFrames
I am using an iFrame to contain an external html source https://good.com/main.html

```<code><iframe src=“https://good.com/main.html" scrolling="no" style="overflow: hidden; height: 700px;"></iframe>
</code>```

But good.com/main.html imports and executes the following javascript

```<code>https://good.com/a.js
https://good.com/b.js
https://bad.com/c.js
</code>```

Is there a way to prevent good.com/main.html importing and executing bad.com/c.js? More specifically, prevent any resource that does not have the same domain as https://good.com?

I tried sandboxing the iFrame

```<code><iframe sandbox=“allow-same-origin allow-scripts” src=“https://good.com/main.html” scrolling="no" style="overflow: hidden; height: 700px;"></iframe>
</code>```

But it still imports and executes the https://bad.com/c.js

Is there a way to prevent the source from importing and executing any external js?

I read about CSPs on iFrames, but I am unsure of it’s usage.

答:
Broadly speaking, you can't.  Iframes have their own CSP and you can't pass a policy in from the parent page.

That said, the "csp" attribute of the iframe element, that you link to in the question, somewhat allows this.  It allows you to request that the iframe source apply the CSP that you set in the "csp" attribute; but you can't enforce it, merely ask. So you can theoretically do:

The source of the iframe may or may not implement the CSP you request.

Note this is brand new and is (reportedly) only supported in Chrome and Opera.

Title: How to use CSPs on iFrames

Body:
I am using an iFrame to contain an external html source https://good.com/main.html

But good.com/main.html imports and executes the following javascript

https://good.com/a.js
https://good.com/b.js
https://bad.com/c.js

Is there a way to prevent good.com/main.html importing and executing bad.com/c.js? More specifically, prevent any resource that does not have the same domain as https://good.com?

I tried sandboxing the iFrame

But it still imports and executes the https://bad.com/c.js

Is there a way to prevent the source from importing and executing any external js?

I read about CSPs on iFrames, but I am unsure of it’s usage.

Body:
Broadly speaking, you can't.  Iframes have their own CSP and you can't pass a policy in from the parent page.

That said, the "csp" attribute of the iframe element, that you link to in the question, somewhat allows this.  It allows you to request that the iframe source apply the CSP that you set in the "csp" attribute; but you can't enforce it, merely ask. So you can theoretically do:

<iframe csp="default-src 'none';" ...>

The source of the iframe may or may not implement the CSP you request.

Note this is brand new and is (reportedly) only supported in Chrome and Opera.


问:
Where should I place the event listener?
I made many of objects such as JButton, JLabel, JCheckBox, etc. And I've added an event listener to the object. Like this.
object obj = new obj();
obj.listneraddActionListener(){};
However, if listener uses other objects, that objects must be created before listener code.
I'm thinking about whether I should sort object definition in advance or pull all listeners to below.
What should I do for this?

Edit:: I'm sorry, I didn't post because the code was too big. the below is part of the code. I got error message from checkboxes(chkName, chkAddress, chkType, chkComment)

```<code>    JButton btnSearch = new JButton("");
    btnSearch.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            String str = "";
            ResultSet rsSid, rsNM = null;
            int count = 0;

            if (chkName.isSelected()) {str += "(SELECT " + tableName + "_SID FROM " + tableName + " WHERE " + tableName + "_NM LIKE '%" + txtSearch.getText() + "%') UNION "; ++count;}
            if (chkAddress.isSelected()) {str += "(SELECT " + tableName + "_SID FROM " + tableName + " WHERE " + "ADDR LIKE '%" + txtSearch.getText() +"%') UNION "; ++count;}
            if (chkType.isSelected()) {str += "(SELECT " + tableName + "_SID FROM " + tableName + " WHERE " + "TYPE LIKE '%" + txtSearch.getText() +"%') UNION "; ++count;}
            if (chkComment.isSelected()) {str += "(SELECT " + tableName + "_SID FROM " + tableName + " WHERE " + "COMMENT LIKE '%" + txtSearch.getText() +"%') UNION "; ++count;}
            if (count == 0) return;

            if (txtSearch.getText() != "")
                str = str.substring(0, str.length() - 7) + ';';
            else
                str = "SELECT * FROM " + tableName;

            rsSid = jdbc.executeQuery(conn, str);
            try {
                behindList.clear();
                lstSRmodel.clear();
                TableSummary temp = new TableSummary();
                while(rsSid.next()) {
                    for (int i = 1; i <= rsSid.getMetaData().getColumnCount(); ++i) {
                        temp.TABLE_SID = rsSid.getInt(i);
                        rsNM = jdbc.executeQuery(conn, "SELECT " + tableName + "_NM FROM " + tableName + " WHERE " + tableName + "_SID = " + temp.TABLE_SID + ";");
                        if (rsNM.next()) {
                            temp.TABLE_NM = rsNM.getString(1);
                            behindList.add(new TableSummary(temp.TABLE_SID, temp.TABLE_NM));
                            lstSRmodel.addElement(temp.TABLE_NM);
                        }
                    }
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    });

    JCheckBox chkAll = new JCheckBox("\uC804\uCCB4");

    chkAll.setBounds(14, 75, 131, 27);
    contentPane.add(chkAll);

    JCheckBox chkName = new JCheckBox("\uC774\uB984");
    chkName.setBounds(14, 106, 131, 27);
    contentPane.add(chkName);

    JCheckBox chkAddress = new JCheckBox("\uC704\uCE58");
    chkAddress.setBounds(14, 137, 131, 27);
    contentPane.add(chkAddress);

    JCheckBox chkType = new JCheckBox("\uD0C0\uC785");
    chkType.setBounds(14, 168, 131, 27);
    contentPane.add(chkType);

    JCheckBox chkComment = new JCheckBox("\uC138\uBD80\uC0AC\uD56D");
    chkComment.setBounds(14, 199, 131, 27);
    contentPane.add(chkComment);
</code>```

答:
You should split your ActionListener and your business code: your should not execute a long running query in an ActionListener because it would freeze your application by blocking the EDT (Event Dispatch Thread).

I would preferably do the following when dealing with Swing (or other framework such as Java FX, SWT, ...):

Create GUI component such as field, ...

Configure or "init" the layout, that is add the component to their parent and so on

Configure any event listener

That would be (replace "init" by "configure" if you prefer):

```<code>private JCheckBox checkBox;

MyClass() { // constructor
  this.init();
}

void init() {
  initComponents();
  initEventListeners();
}

void initComponents() {
  this.checkBox = new JCheckBox("..."); // or in the constructor if you want final field.

  // layout for the parent component
  this.add(new JLabel("Label 1"));
  this.add(checkBox);
}

void initEventListeners() {
  this.checkBox.addActionListener(System.out::println);
}
</code>```

Also, event you attach to a Swing component should be kept as simple as possible if they are lambda or anonymous classes: instead, create a private method and use its reference:

```<code>  btnSearch.addActionListener(this::searchActionListener);
</code>```

And the method in which I use another thread (ForkJoinPool.commonPool()) to execute long running work outside the EDT (Event Dispatch Thread). Otherwise, the interface would be frozen. The business method is done outside, in another object (called business here).

The search button should be disabled, otherwise the user (in that case) could spam the button leading to unwanted issues on the database...

```<code>private void searchActionListener(ActionEvent event) {
    btnSearch.setEnabled(false);  // user should not be able to search while it's running

    // extract Swing data before running outside the EDT
    String query = txtSearch.getText()
    boolean useName = chkName.isSelected();
    boolean useAddress = chkAddress.isSelected();
    // ... and so on

    // do work OUTSIDE the EDT
    ForkJoinPool.commonPool().execute(() -> {
      Result result = business.find(query, useName, useAddress);
      SwingUtilities.invokeLater(() -> {
        processResult(result); // do whatever is needed
        btnSearch.setEnabled(true);
      });
    });
  }
</code>```

As you can see, if you created your Swing component (chkName, ...) before the event listener, you may not reference them in the method: you should create them as field to the class rather than as variable.

Otherwise, you're bound to create them before the event listener.

Also, while not discussed in the question, you should rewrite your query because your are injecting SQL:

```<code>"(SELECT " + tableName + "_SID FROM " + tableName + " WHERE " + tableName + "_NM LIKE '%" + txtSearch.getText() + "%') UNION ";
</code>```

The '%" + txtSearch.getText() + "%' should be replaced by ? and you should use a PreparedStatement to pass parameter rather than injecting it.

Body:
I made many of objects such as JButton, JLabel, JCheckBox, etc. And I've added an event listener to the object. Like this.
object obj = new obj();
obj.listneraddActionListener(){};
However, if listener uses other objects, that objects must be created before listener code.
I'm thinking about whether I should sort object definition in advance or pull all listeners to below.
What should I do for this?

Edit:: I'm sorry, I didn't post because the code was too big. the below is part of the code. I got error message from checkboxes(chkName, chkAddress, chkType, chkComment)

    JButton btnSearch = new JButton("");
    btnSearch.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            String str = "";
            ResultSet rsSid, rsNM = null;
            int count = 0;

            if (chkName.isSelected()) {str += "(SELECT " + tableName + "_SID FROM " + tableName + " WHERE " + tableName + "_NM LIKE '%" + txtSearch.getText() + "%') UNION "; ++count;}
            if (chkAddress.isSelected()) {str += "(SELECT " + tableName + "_SID FROM " + tableName + " WHERE " + "ADDR LIKE '%" + txtSearch.getText() +"%') UNION "; ++count;}
            if (chkType.isSelected()) {str += "(SELECT " + tableName + "_SID FROM " + tableName + " WHERE " + "TYPE LIKE '%" + txtSearch.getText() +"%') UNION "; ++count;}
            if (chkComment.isSelected()) {str += "(SELECT " + tableName + "_SID FROM " + tableName + " WHERE " + "COMMENT LIKE '%" + txtSearch.getText() +"%') UNION "; ++count;}
            if (count == 0) return;

            if (txtSearch.getText() != "")
                str = str.substring(0, str.length() - 7) + ';';
            else
                str = "SELECT * FROM " + tableName;

            rsSid = jdbc.executeQuery(conn, str);
            try {
                behindList.clear();
                lstSRmodel.clear();
                TableSummary temp = new TableSummary();
                while(rsSid.next()) {
                    for (int i = 1; i <= rsSid.getMetaData().getColumnCount(); ++i) {
                        temp.TABLE_SID = rsSid.getInt(i);
                        rsNM = jdbc.executeQuery(conn, "SELECT " + tableName + "_NM FROM " + tableName + " WHERE " + tableName + "_SID = " + temp.TABLE_SID + ";");
                        if (rsNM.next()) {
                            temp.TABLE_NM = rsNM.getString(1);
                            behindList.add(new TableSummary(temp.TABLE_SID, temp.TABLE_NM));
                            lstSRmodel.addElement(temp.TABLE_NM);
                        }
                    }
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    });

    JCheckBox chkAll = new JCheckBox("\uC804\uCCB4");

    chkAll.setBounds(14, 75, 131, 27);
    contentPane.add(chkAll);

    JCheckBox chkName = new JCheckBox("\uC774\uB984");
    chkName.setBounds(14, 106, 131, 27);
    contentPane.add(chkName);

    JCheckBox chkAddress = new JCheckBox("\uC704\uCE58");
    chkAddress.setBounds(14, 137, 131, 27);
    contentPane.add(chkAddress);

    JCheckBox chkType = new JCheckBox("\uD0C0\uC785");
    chkType.setBounds(14, 168, 131, 27);
    contentPane.add(chkType);

    JCheckBox chkComment = new JCheckBox("\uC138\uBD80\uC0AC\uD56D");
    chkComment.setBounds(14, 199, 131, 27);
    contentPane.add(chkComment);

Body:
You should split your ActionListener and your business code: your should not execute a long running query in an ActionListener because it would freeze your application by blocking the EDT (Event Dispatch Thread).

I would preferably do the following when dealing with Swing (or other framework such as Java FX, SWT, ...):

Create GUI component such as field, ...

Configure or "init" the layout, that is add the component to their parent and so on

Configure any event listener

That would be (replace "init" by "configure" if you prefer):

private JCheckBox checkBox;

MyClass() { // constructor
  this.init();
}

void init() {
  initComponents();
  initEventListeners();
}

void initComponents() {
  this.checkBox = new JCheckBox("..."); // or in the constructor if you want final field.

  // layout for the parent component
  this.add(new JLabel("Label 1"));
  this.add(checkBox);
}

void initEventListeners() {
  this.checkBox.addActionListener(System.out::println);
}

Also, event you attach to a Swing component should be kept as simple as possible if they are lambda or anonymous classes: instead, create a private method and use its reference:

  btnSearch.addActionListener(this::searchActionListener);

And the method in which I use another thread (ForkJoinPool.commonPool()) to execute long running work outside the EDT (Event Dispatch Thread). Otherwise, the interface would be frozen. The business method is done outside, in another object (called business here).

The search button should be disabled, otherwise the user (in that case) could spam the button leading to unwanted issues on the database...

private void searchActionListener(ActionEvent event) {
    btnSearch.setEnabled(false);  // user should not be able to search while it's running

    // extract Swing data before running outside the EDT
    String query = txtSearch.getText()
    boolean useName = chkName.isSelected();
    boolean useAddress = chkAddress.isSelected();
    // ... and so on

    // do work OUTSIDE the EDT
    ForkJoinPool.commonPool().execute(() -> {
      Result result = business.find(query, useName, useAddress);
      SwingUtilities.invokeLater(() -> {
        processResult(result); // do whatever is needed
        btnSearch.setEnabled(true);
      });
    });
  }

As you can see, if you created your Swing component (chkName, ...) before the event listener, you may not reference them in the method: you should create them as field to the class rather than as variable.

Otherwise, you're bound to create them before the event listener.

Also, while not discussed in the question, you should rewrite your query because your are injecting SQL:

"(SELECT " + tableName + "_SID FROM " + tableName + " WHERE " + tableName + "_NM LIKE '%" + txtSearch.getText() + "%') UNION ";

The '%" + txtSearch.getText() + "%' should be replaced by ? and you should use a PreparedStatement to pass parameter rather than injecting it.


问:
SBT not removing previously downloaded versions
I'm running Scala 2.11 with SBT and I ran into a problem where, a dependency that I'm importing fresh into my project, has a conflict with another one already in the project which happens to be used by the newly one.

When I say conflict, I mean different classes which happen to implement different interfaces.

Guava 19.0 (local lib version) doesn't seem to work with the Guava
  version being used in that previously mentioned dependency.

And what I did to solve this problem was to update the local Guava version to 26.0-jre.

So far so good, problem solved (apparently).

After performing the code check I wanted to do for a newly created feature and seeing that everything works alright, I revert by build.sbt file and come back again to Guava 19.0.

I relaunch the project and the issue is no longer there. What could be going on? Shouldn't I get the previously mentioned issue?

I went into .ivy2 dir to check versions in there and all those are 19.0 (they don't even get updated to 26.0-jre or whatever in there). Hope that sheds some light.

答:
That is expected. Once you have dowloaded, it will be there (.ivy2 folder) for ever. As for why your project still works fine, just because class loader load version 26 this time. So this is depends on class loader loading order which your sbt cannot guranteed. Maven also have similar problem. Usually, we need use exclude to remove such potential problem.  Hope this can help.

libraryDependencies +=
  "log4j" % "log4j" % "1.2.15" exclude("javax.jms", "jms")


问:
Count if matching items in same column
The Set Up:

I have a single column, with three cells.
These cells are drop-down lists. (177 options in the drop-down).

Trying to figure out:
I want to automate matching (if two or all three items match in the same column, to each other) and return a specific number.

Column that needs to match. Output in other column.

So a normal "countif" isn't going to work, as I would need to specify what is being counted. I need it to "see" that there is a match and spit out a specific number.

Sample in works.

答:
Cries out for COUNTUNIQUE. Assuming relevant dropdowns are in B10:B12 :

```<code>=countunique(B10:B12)
</code>```

and if 1, 2, and 3 are not suitable for the "specific number" then these can be mapped to suitable alternatives (I chose 7 for all the same, 0 if all different, and 3 otherwise):

```<code>=choose(countunique(B10:B12),7,3,0)
</code>```

Title: Count if matching items in same column

Body:
Cries out for COUNTUNIQUE. Assuming relevant dropdowns are in B10:B12 :

=countunique(B10:B12)

and if 1, 2, and 3 are not suitable for the "specific number" then these can be mapped to suitable alternatives (I chose 7 for all the same, 0 if all different, and 3 otherwise):

=choose(countunique(B10:B12),7,3,0)


问:
Splitting rows that contain a list of postcode prefixes into multiple rows, based on postcode area
I have a table with several columns of data, one of which contains a list of different combined postcode prefixes on the same row.

Here's an example of the table layout:

```<code>+------+-----------------------------+
| Col1 |            Col2             |
+------+-----------------------------+
| a    | AB10; AB11;  DD10; DD9      |
| b    | S5; SS7; AA1; AA4           |
| c    | AB33; AB34; AB36; GG10; GS9 |
+------+-----------------------------+
</code>```

I'm looking to split the postcode prefixes into multiple rows, based on the area of the postcode, as below:

```<code>+------+------------------+
| Col1 |       Col2       |
+------+------------------+
| a    | AB10; AB11       |
| a    | DD10; DD9        |
| b    | S5               |
| b    | SS7              |
| b    | AA1; AA4         |
| c    | AB33; AB34; AB36 |
| c    | GG10             |
| c    | GS9              |
+------+------------------+
</code>```

I've found a VBA solution that splits, using the semicolon as a delimiter, but not how I need it done.

Sub splitByColB()
    Dim r As Range, i As Long, ar
    Set r = Worksheets("Sheet1").Range("B4").End(xlUp)
    Do While r.Row > 1
        ar = Split(r.Value, ";")
        If UBound(ar) >= 0 Then r.Value = ar(0)
        For i = UBound(ar) To 1 Step -1
            r.EntireRow.Copy
            r.Offset(1).EntireRow.Insert
            r.Offset(1).Value = ar(i)
        Next
        Set r = r.Offset(-1)
    Loop
End Sub
```

I could import the table in SQLExpress, so an SQL solution would also be welcome.

答:
you could use nested dictionary objects:

```<code>Sub splitByColB()
    Dim r As Range, ar, val1, val2, prefix As String
    Dim obj1 As Object, obj2 As Object

    Set obj1 = CreateObject("Scripting.Dictionary")

    With Worksheets("Sheet1")

        For Each r In .Range("B2:B4")
            Set obj2 = CreateObject("Scripting.Dictionary")
            With obj2
                For Each val2 In Split(Replace(r.Value2, " ", vbNullString), ";")
                    prefix = GetLetters(CStr(val2))
                    .Item(prefix) = .Item(prefix) & val2 & " "
                Next
            End With
            Set obj1.Item(r.Offset(, -1).Value2) = obj2
        Next

        .Range("A2:B4").ClearContents
        For Each val1 In obj1.keys
            .Cells(.Rows.Count, 1).End(xlUp).Offset(1).Resize(obj1(val1).Count).Value = val1
            For Each val2 In obj1(val1).keys
                .Cells(.Rows.Count, 2).End(xlUp).Offset(1).Value = obj1(val1)(val2)
            Next
        Next
    End With
End Sub

Function GetLetters(s As String) As String
    Dim i As Long
    Do While Not IsNumeric(Mid(s, i + 1, 1))
        i = i + 1
    Loop
    GetLetters = Left(s, i)
End Function
</code>```

Body:
I have a table with several columns of data, one of which contains a list of different combined postcode prefixes on the same row.

Here's an example of the table layout:

+------+-----------------------------+
| Col1 |            Col2             |
+------+-----------------------------+
| a    | AB10; AB11;  DD10; DD9      |
| b    | S5; SS7; AA1; AA4           |
| c    | AB33; AB34; AB36; GG10; GS9 |
+------+-----------------------------+

I'm looking to split the postcode prefixes into multiple rows, based on the area of the postcode, as below:

+------+------------------+
| Col1 |       Col2       |
+------+------------------+
| a    | AB10; AB11       |
| a    | DD10; DD9        |
| b    | S5               |
| b    | SS7              |
| b    | AA1; AA4         |
| c    | AB33; AB34; AB36 |
| c    | GG10             |
| c    | GS9              |
+------+------------------+

I've found a VBA solution that splits, using the semicolon as a delimiter, but not how I need it done.

Sub splitByColB()
    Dim r As Range, i As Long, ar
    Set r = Worksheets("Sheet1").Range("B4").End(xlUp)
    Do While r.Row > 1
        ar = Split(r.Value, ";")
        If UBound(ar) >= 0 Then r.Value = ar(0)
        For i = UBound(ar) To 1 Step -1
            r.EntireRow.Copy
            r.Offset(1).EntireRow.Insert
            r.Offset(1).Value = ar(i)
        Next
        Set r = r.Offset(-1)
    Loop
End Sub

I could import the table in SQLExpress, so an SQL solution would also be welcome.

Body:
you could use nested dictionary objects:

Sub splitByColB()
    Dim r As Range, ar, val1, val2, prefix As String
    Dim obj1 As Object, obj2 As Object

    Set obj1 = CreateObject("Scripting.Dictionary")

    With Worksheets("Sheet1")

        For Each r In .Range("B2:B4")
            Set obj2 = CreateObject("Scripting.Dictionary")
            With obj2
                For Each val2 In Split(Replace(r.Value2, " ", vbNullString), ";")
                    prefix = GetLetters(CStr(val2))
                    .Item(prefix) = .Item(prefix) & val2 & " "
                Next
            End With
            Set obj1.Item(r.Offset(, -1).Value2) = obj2
        Next

        .Range("A2:B4").ClearContents
        For Each val1 In obj1.keys
            .Cells(.Rows.Count, 1).End(xlUp).Offset(1).Resize(obj1(val1).Count).Value = val1
            For Each val2 In obj1(val1).keys
                .Cells(.Rows.Count, 2).End(xlUp).Offset(1).Value = obj1(val1)(val2)
            Next
        Next
    End With
End Sub

Function GetLetters(s As String) As String
    Dim i As Long
    Do While Not IsNumeric(Mid(s, i + 1, 1))
        i = i + 1
    Loop
    GetLetters = Left(s, i)
End Function


问:
How do I read a custom error message returned when HttpWebRequest.GetResponse throws a WebException?
I've a NET.Core API with simple test method:

```<code>public async Task<IActionResult> TestApi()
{
    try
    {
        throw new UnauthorizedAccessException("My custom error");

        return Ok();
    }
    catch (UnauthorizedAccessException ex)
    {
        return StatusCode(401,ex.Message);
    }
    catch (Exception ex)
    {
        throw;
    }

}
</code>```

I need to retrieve the message from a client like this:

```<code>var request = WebRequest.Create($"{baseUrl}{url}") as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/json";
request.Expect = "application/json";
request.ContentLength = 0;

if (parameters != null)
{
    request.ContentLength = serializedObject.Length;
    using (var writer = new StreamWriter(request.GetRequestStream()))
    {
        writer.Write(serializedObject);
    }
}

var response = request.GetResponse() as HttpWebResponse;
var responseEncoding = Encoding.GetEncoding(response.CharacterSet);

using (var sr = new StreamReader(response.GetResponseStream(), responseEncoding))
{
    var result = sr.ReadToEnd();
    return JsonConvert.DeserializeObject<T>(result);
}
</code>```

Now request.GetResponse() as HttpWebResponse returns me:

```<code>The remote server returned an error: (401) Unauthorized.
</code>```

instead of My custom error. Can someone point me in the right direction?

答:
Return an ActionResult

```<code>Task<ActionResult>
</code>```

You can then wrap up the unauthorized error in an UnauthorizedObjectResult

```<code>return Unauthorized(new UnauthorizedObjectResult(errorModel));
</code>```

Body:
I've a NET.Core API with simple test method:

public async Task<IActionResult> TestApi()
{
    try
    {
        throw new UnauthorizedAccessException("My custom error");

        return Ok();
    }
    catch (UnauthorizedAccessException ex)
    {
        return StatusCode(401,ex.Message);
    }
    catch (Exception ex)
    {
        throw;
    }

}

I need to retrieve the message from a client like this:

var request = WebRequest.Create($"{baseUrl}{url}") as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/json";
request.Expect = "application/json";
request.ContentLength = 0;

if (parameters != null)
{
    request.ContentLength = serializedObject.Length;
    using (var writer = new StreamWriter(request.GetRequestStream()))
    {
        writer.Write(serializedObject);
    }
}

var response = request.GetResponse() as HttpWebResponse;
var responseEncoding = Encoding.GetEncoding(response.CharacterSet);

using (var sr = new StreamReader(response.GetResponseStream(), responseEncoding))
{
    var result = sr.ReadToEnd();
    return JsonConvert.DeserializeObject<T>(result);
}

Now request.GetResponse() as HttpWebResponse returns me:

The remote server returned an error: (401) Unauthorized.

instead of My custom error. Can someone point me in the right direction?

Body:
Return an ActionResult

Task<ActionResult>

You can then wrap up the unauthorized error in an UnauthorizedObjectResult

return Unauthorized(new UnauthorizedObjectResult(errorModel));


问:
Only extract those words from a list that include no repeating letters, using regex
I have a large word list file with one word per line. I would like to filter out the words with repeating alphabets.

```<code>INPUT:
  abducts
  abe
  abeam
  abel
  abele

OUTPUT:
  abducts
  abe
  abel
</code>```

I'd like to do this using Regex (grep or perl or python). Is that possible?

答:
It's much easier to write a regex that matches words that do have repeating letters, and then negate the match:

```<code>my @input = qw(abducts abe abeam abel abele);
my @output = grep { not /(\w).*\1/ } @input;
</code>```

(This code assumes that @input contains one word per entry.) But this problem isn't necessarily best solved with a regex.

I've given the code in Perl, but it could easily be translated into any regex flavor that supports backreferences, including grep (which also has the -v switch to negate the match).

ContentLicense: CC BY-SA 3.0

Body:
I have a large word list file with one word per line. I would like to filter out the words with repeating alphabets.

INPUT:
  abducts
  abe
  abeam
  abel
  abele

OUTPUT:
  abducts
  abe
  abel

I'd like to do this using Regex (grep or perl or python). Is that possible?

Body:
It's much easier to write a regex that matches words that do have repeating letters, and then negate the match:

my @input = qw(abducts abe abeam abel abele);
my @output = grep { not /(\w).*\1/ } @input;

(This code assumes that @input contains one word per entry.) But this problem isn't necessarily best solved with a regex.

I've given the code in Perl, but it could easily be translated into any regex flavor that supports backreferences, including grep (which also has the -v switch to negate the match).


问:
Cassandra PHP PDO not retrieving all records
I'm attempting to work Cassandra 2.0 with PHP and the PDO extension.
It seems to be working however I'm having trouble retrieving records.

My code is as follows

```<code>// Connect to two hosts
 $dsn = "cassandra:host=localhost;port=9160,host=localhost,port=9160";
 $db = new PDO($dsn);
// Select Keyspace
 $db->exec("USE mykeyspace");
// Create and Excecute query
 $stmt = $db->prepare("SELECT * FROM users");
 $result = $stmt->execute();
// Dump to data
 var_dump($stmt->fetchAll());
</code>```

And this is the result of my var_dump

array(3) { [0]=> array(6) { ["user_id"]=> int(1745) [0]=> int(1745) [""]=> string(5) "smith" [1]=> string(0) "" [2]=> string(4) "john" [3]=> string(5) "smith" } [1]=> array(6) { ["user_id"]=> int(1744) [0]=> int(1744) [""]=> string(3) "doe" [1]=> string(0) "" [2]=> string(4) "john" [3]=> string(3) "doe" } [2]=> array(6) { ["user_id"]=> int(1746) [0]=> int(1746) [""]=> string(5) "smith" [1]=> string(0) "" [2]=> string(4) "john" [3]=> string(5) "smith" } }

The data is there, but it's not organized at all. Why there no fname is there which one of the names of my columns. The data is there but some of it only another numeral array keys.

The table structure is the Cassandra sample (getting started) data as follows

```<code> user_id | fname | lname
---------+-------+-------
    1745 |  john | smith
    1744 |  john |   doe
    1746 |  john | smith
</code>```

Have I done something wrong?

Thanks

答: try change your driver this cassandra pdo is very old , im use dataStax and work very well</p>

Body:
I'm attempting to work Cassandra 2.0 with PHP and the PDO extension.
It seems to be working however I'm having trouble retrieving records.

My code is as follows

// Connect to two hosts
 $dsn = "cassandra:host=localhost;port=9160,host=localhost,port=9160";
 $db = new PDO($dsn);
// Select Keyspace
 $db->exec("USE mykeyspace");
// Create and Excecute query
 $stmt = $db->prepare("SELECT * FROM users");
 $result = $stmt->execute();
// Dump to data
 var_dump($stmt->fetchAll());

And this is the result of my var_dump

array(3) { [0]=> array(6) { ["user_id"]=> int(1745) [0]=> int(1745) [""]=> string(5) "smith" [1]=> string(0) "" [2]=> string(4) "john" [3]=> string(5) "smith" } [1]=> array(6) { ["user_id"]=> int(1744) [0]=> int(1744) [""]=> string(3) "doe" [1]=> string(0) "" [2]=> string(4) "john" [3]=> string(3) "doe" } [2]=> array(6) { ["user_id"]=> int(1746) [0]=> int(1746) [""]=> string(5) "smith" [1]=> string(0) "" [2]=> string(4) "john" [3]=> string(5) "smith" } }

The data is there, but it's not organized at all. Why there no fname is there which one of the names of my columns. The data is there but some of it only another numeral array keys.

The table structure is the Cassandra sample (getting started) data as follows

 user_id | fname | lname
---------+-------+-------
    1745 |  john | smith
    1744 |  john |   doe
    1746 |  john | smith

Have I done something wrong?

Thanks


问:
Can set some type for FormControl value?
Framework which I use (Angular 7).

I want set some type for FormControl like this.

```<code>    startDate: FormControl<NgbDate>;
    endDate: FormControl<NgbDate>;
</code>```

Do you have any experience with it or it is not posible in angular?

答: For now it's not possibile. Check this issue to Angular GitHub Reactive forms are not strongly typed</p>

Body:
Framework which I use (Angular 7).

I want set some type for FormControl like this.

    startDate: FormControl<NgbDate>;
    endDate: FormControl<NgbDate>;

Do you have any experience with it or it is not posible in angular?


问:
Navigation's back stack is lost when navigation is nested
I have a navigation which looks like this

```<code>Frag1 -> Frag2 -> Frag3
</code>```

Inside Frag2 there is a NavHostFragment with its own navigation

```<code>InnerFrag1 -> InnerFrag2
</code>```

If I do this

Navigate to Frag2

Navigate to InnerFrag2 inside Frag2

Navigate to Frag3

Go back

then I'll see InnerFrag2 inside Frag2, when I press back normally I would go from InnerFrag2 to InnerFrag1 inside Frag2 but now it's going to Frag1 instead.

Here is my navigation handling inside Frag2

```<code>
    private val backPressedCallback = OnBackPressedCallback {
        navHostFragment.navController.navigateUp()
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        requireActivity().addOnBackPressedCallback(backPressedCallback)
    }

    override fun onDestroyView() {
        activity?.removeOnBackPressedCallback(backPressedCallback)
        super.onDestroyView()
    }

    private val navHostFragment: NavHostFragment
        get() = childFragmentManager.findFragmentById(R.id.innerNavHostFragment) as NavHostFragment

</code>```

When going back to Frag2 the fragment in the nav host is the correct one, but navigating back moves away from Frag2 because inner nav host's back stack is lost. Can I persist it somehow or fix it some other way?

EDIT: actually when going from Frag3 to Frag2 I see InnerFrag1 inside, the both look alike, that's why going back at this point brings me back to Frag1

EDIT2: I found my problem, I inflate Frag2s navigation from code in onViewCreated like this

```<code>    val navHostFragment = (frag2NavHostFragment as? NavHostFragment) ?: return
    val inflater = navHostFragment.navController.navInflater
    val graph = inflater.inflate(navigationId)
    navHostFragment.navController.graph = graph
</code>```

setting it in xml makes it work, I still need to set it from code somehow, Frag2 chooses which navigation to use depending on its arguments

Now my question changes from Navigation's back stack is lost to How to preserve NavHostFragment's state when settings it's graph from code

答:
After looking into this for a little, original question doesn't make much sense, I'd delete it but it got 2 upvotes ¯\_(ツ)_/¯

I solved my problem by adding a check before inflating graph, so that NavHostFragment's graph is set only if it doesn't already have one.

```<code>    try {
        navHostFragment.navController.graph
    } catch (e: IllegalStateException) {
        val inflater = navHostFragment.navController.navInflater
        val graph = inflater.inflate(navigationId)
        navHostFragment.navController.graph = graph
    }
</code>```

NavController.getGraph doesn't return null, instead it throws IllegalStateException, hence the weird check

Body:
I have a navigation which looks like this

Frag1 -> Frag2 -> Frag3

Inside Frag2 there is a NavHostFragment with its own navigation

InnerFrag1 -> InnerFrag2

If I do this

Navigate to Frag2

Navigate to InnerFrag2 inside Frag2

Navigate to Frag3

Go back

then I'll see InnerFrag2 inside Frag2, when I press back normally I would go from InnerFrag2 to InnerFrag1 inside Frag2 but now it's going to Frag1 instead.

Here is my navigation handling inside Frag2

    private val backPressedCallback = OnBackPressedCallback {
        navHostFragment.navController.navigateUp()
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        requireActivity().addOnBackPressedCallback(backPressedCallback)
    }

    override fun onDestroyView() {
        activity?.removeOnBackPressedCallback(backPressedCallback)
        super.onDestroyView()
    }

    private val navHostFragment: NavHostFragment
        get() = childFragmentManager.findFragmentById(R.id.innerNavHostFragment) as NavHostFragment

When going back to Frag2 the fragment in the nav host is the correct one, but navigating back moves away from Frag2 because inner nav host's back stack is lost. Can I persist it somehow or fix it some other way?

EDIT: actually when going from Frag3 to Frag2 I see InnerFrag1 inside, the both look alike, that's why going back at this point brings me back to Frag1

EDIT2: I found my problem, I inflate Frag2s navigation from code in onViewCreated like this

    val navHostFragment = (frag2NavHostFragment as? NavHostFragment) ?: return
    val inflater = navHostFragment.navController.navInflater
    val graph = inflater.inflate(navigationId)
    navHostFragment.navController.graph = graph

setting it in xml makes it work, I still need to set it from code somehow, Frag2 chooses which navigation to use depending on its arguments

Now my question changes from Navigation's back stack is lost to How to preserve NavHostFragment's state when settings it's graph from code

Body:
After looking into this for a little, original question doesn't make much sense, I'd delete it but it got 2 upvotes ¯\_(ツ)_/¯

I solved my problem by adding a check before inflating graph, so that NavHostFragment's graph is set only if it doesn't already have one.

    try {
        navHostFragment.navController.graph
    } catch (e: IllegalStateException) {
        val inflater = navHostFragment.navController.navInflater
        val graph = inflater.inflate(navigationId)
        navHostFragment.navController.graph = graph
    }

NavController.getGraph doesn't return null, instead it throws IllegalStateException, hence the weird check


问:
Corda explicit contract upgrade NoSuchElementException: List is empty
I am trying to upgrade the Corda contracts. Currently we have an uber jar having state, flows and contracts. We are using explicit upgrade mechanism by utilising UpgradeContractUsingLegacyConstraint interface to break uber jars in separate jars.

In our network, there is one observer node, which tracks all the transactions happening between other nodes in the network. Thus, in this scenario, we ran Authorise flow in all the nodes in network and then ran Initiate flow in the observer node. While authorise flow ran successfully in all nodes without any error, Initiate flow has two issues.

Some of the flows are failing. We are getting error multiple instance of NoSuchElementException. The stack trace is mentioned below

Some of the flows remain pending. In Jolokia monitoring, we are getting similar statistics where some remain in in-flight state. In Corda SSH shell too, we are getting pending trades after running flow watch command. We tried to restart the system, but the issue remains persistent in observer node.

What should be the next step or recommended way to upgrade the contracts. I am using Corda v3.3 on Ubuntu 16.04, Cordite network map and taking reference from github repository to upgrade the contract ( https://github.com/amolpednekar/contract-state-upgrades/blob/master/cordapp/src/main/kotlin/com/upgrade/Client.kt ).

Stacktrace:

```<code>[WARN ] 2019-05-22T22:16:31,568Z [Node thread-1] flow.[fa8a213f-8de7-4cd8-8d41-8493bbc9cecf].run - Terminated by unexpected exception {}
java.util.NoSuchElementException: List is empty.
    at kotlin.collections.CollectionsKt___CollectionsKt.single(_Collections.kt:472) ~[kotlin-stdlib-1.1.60.jar:1.1.60-release-55 (1.1.60)]
    at kotlin.collections.CollectionsKt___CollectionsKt.single(_Collections.kt:454) ~[kotlin-stdlib-1.1.60.jar:1.1.60-release-55 (1.1.60)]
    at net.corda.core.flows.ContractUpgradeFlow$Initiate.assembleTx(ContractUpgradeFlow.kt:77) ~[corda-core-3.3-corda.jar:?]
    at net.corda.core.flows.AbstractStateReplacementFlow$Instigator.call(AbstractStateReplacementFlow.kt:64) ~[corda-core-3.3-corda.jar:?]
    at net.corda.core.flows.AbstractStateReplacementFlow$Instigator.call(AbstractStateReplacementFlow.kt:50) ~[corda-core-3.3-corda.jar:?]
    at net.corda.node.services.statemachine.FlowStateMachineImpl.run(FlowStateMachineImpl.kt:96) [corda-node-3.3-corda.jar:?]
    at net.corda.node.services.statemachine.FlowStateMachineImpl.run(FlowStateMachineImpl.kt:44) [corda-node-3.3-corda.jar:?]
    at co.paralleluniverse.fibers.Fiber.run1(Fiber.java:1092) [quasar-core-0.7.9-jdk8.jar:0.7.9]
    at co.paralleluniverse.fibers.Fiber.exec(Fiber.java:788) [quasar-core-0.7.9-jdk8.jar:0.7.9]
    at co.paralleluniverse.fibers.RunnableFiberTask.doExec(RunnableFiberTask.java:100) [quasar-core-0.7.9-jdk8.jar:0.7.9]
    at co.paralleluniverse.fibers.RunnableFiberTask.run(RunnableFiberTask.java:91) [quasar-core-0.7.9-jdk8.jar:0.7.9]
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) [?:1.8.0_201]
    at java.util.concurrent.FutureTask.run(FutureTask.java:266) [?:1.8.0_201]
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180) [?:1.8.0_201]
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293) [?:1.8.0_201]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [?:1.8.0_201]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [?:1.8.0_201]
    at net.corda.node.utilities.AffinityExecutor$ServiceAffinityExecutor$1$thread$1.run(AffinityExecutor.kt:62) [corda-node-3.3-corda.jar:?]
[WARN ] 2019-05-22T22:16:31,574Z [Node thread-1] flow.[5856148a-d233-43c4-ac20-396b9a91f6c0].run - Terminated by unexpected exception {}
</code>```

EDIT: Some other errors captured:

```<code>[WARN ] 2019-06-03T16:36:22,357Z [Node thread-1] flow.[2aec6ee2-2e14-43f5-81ce-b301c4876e0a].run - Terminated by unexpected exception {}
java.lang.ClassCastException: io.corp.contract.DefaultContract cannot be cast to net.corda.core.contracts.UpgradedContract
        at net.corda.core.flows.ContractUpgradeFlow$Authorise.call(ContractUpgradeFlow.kt:38) ~[corda-core-3.3-corda.jar:?]
        at net.corda.core.flows.ContractUpgradeFlow$Authorise.call(ContractUpgradeFlow.kt:31) ~[corda-core-3.3-corda.jar:?]
        at net.corda.node.services.statemachine.FlowStateMachineImpl.run(FlowStateMachineImpl.kt:96) [corda-node-3.3-corda.jar:?]
        at net.corda.node.services.statemachine.FlowStateMachineImpl.run(FlowStateMachineImpl.kt:44) [corda-node-3.3-corda.jar:?]
        at co.paralleluniverse.fibers.Fiber.run1(Fiber.java:1092) [quasar-core-0.7.9-jdk8.jar:0.7.9]
        at co.paralleluniverse.fibers.Fiber.exec(Fiber.java:788) [quasar-core-0.7.9-jdk8.jar:0.7.9]
        at co.paralleluniverse.fibers.RunnableFiberTask.doExec(RunnableFiberTask.java:100) [quasar-core-0.7.9-jdk8.jar:0.7.9]
        at co.paralleluniverse.fibers.RunnableFiberTask.run(RunnableFiberTask.java:91) [quasar-core-0.7.9-jdk8.jar:0.7.9]
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) [?:1.8.0_201]
        at java.util.concurrent.FutureTask.run(FutureTask.java:266) [?:1.8.0_201]
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180) [?:1.8.0_201]
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293) [?:1.8.0_201]
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [?:1.8.0_201]
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [?:1.8.0_201]
        at net.corda.node.utilities.AffinityExecutor$ServiceAffinityExecutor$1$thread$1.run(AffinityExecutor.kt:62) [corda-node-3.3-corda.jar:?]
</code>```

Also this was found for one our contract upgrade

```<code>[WARN ] 2019-06-03T17:44:26,859Z [Messaging DLJKqkjV9pKTqG5nKbQQ3o5B1hPj1zjrYxDYpbhPENXdR] messaging.P2PMessagingClient.sendWithRetry - Reached the maximum number of retries (3) for message ClientMessageImpl[messageID=0, durable=true, address=internal.peers.DL8itTRrD1LvKjd5sQ9DwX59KmZ42PTa964nJPfL6jf1VC,userID=null,properties=TypedProperties[platform-version=3,corda-vendor=Corda Open Source,release-version=3.3-corda,platform-topic=platform.session,_AMQ_DUPL_ID=23190134-6514-4165-8277-0e3df48e2678,corda_p2p_message_type=session_init]] redelivery to internal.peers.DL8itTRrD1LvKjd5sQ9DwX59KmZ42PTa964nJPfL6jf1VC {}
[WARN ] 2019-06-03T17:44:26,941Z [Messaging DLJKqkjV9pKTqG5nKbQQ3o5B1hPj1zjrYxDYpbhPENXdR] messaging.P2PMessagingClient.sendWithRetry - Reached the maximum number of retries (3) for message ClientMessageImpl[messageID=0, durable=true, address=internal.peers.DL8itTRrD1LvKjd5sQ9DwX59KmZ42PTa964nJPfL6jf1VC,userID=null,properties=TypedProperties[platform-version=3,corda-vendor=Corda Open Source,release-version=3.3-corda,platform-topic=platform.session,_AMQ_DUPL_ID=2e2cde97-1e3d-4ce9-b7af-01ab61a88114,corda_p2p_message_type=session_init]] redelivery to internal.peers.DL8itTRrD1LvKjd5sQ9DwX59KmZ42PTa964nJPfL6jf1VC {}
</code>```

答: From the stacktrace, it looks like the initiator is not a participant in the original state.</p>

Body:
I am trying to upgrade the Corda contracts. Currently we have an uber jar having state, flows and contracts. We are using explicit upgrade mechanism by utilising UpgradeContractUsingLegacyConstraint interface to break uber jars in separate jars.

In our network, there is one observer node, which tracks all the transactions happening between other nodes in the network. Thus, in this scenario, we ran Authorise flow in all the nodes in network and then ran Initiate flow in the observer node. While authorise flow ran successfully in all nodes without any error, Initiate flow has two issues.

Some of the flows are failing. We are getting error multiple instance of NoSuchElementException. The stack trace is mentioned below

Some of the flows remain pending. In Jolokia monitoring, we are getting similar statistics where some remain in in-flight state. In Corda SSH shell too, we are getting pending trades after running flow watch command. We tried to restart the system, but the issue remains persistent in observer node.

What should be the next step or recommended way to upgrade the contracts. I am using Corda v3.3 on Ubuntu 16.04, Cordite network map and taking reference from github repository to upgrade the contract ( https://github.com/amolpednekar/contract-state-upgrades/blob/master/cordapp/src/main/kotlin/com/upgrade/Client.kt ).

Stacktrace:

[WARN ] 2019-05-22T22:16:31,568Z [Node thread-1] flow.[fa8a213f-8de7-4cd8-8d41-8493bbc9cecf].run - Terminated by unexpected exception {}
java.util.NoSuchElementException: List is empty.
    at kotlin.collections.CollectionsKt___CollectionsKt.single(_Collections.kt:472) ~[kotlin-stdlib-1.1.60.jar:1.1.60-release-55 (1.1.60)]
    at kotlin.collections.CollectionsKt___CollectionsKt.single(_Collections.kt:454) ~[kotlin-stdlib-1.1.60.jar:1.1.60-release-55 (1.1.60)]
    at net.corda.core.flows.ContractUpgradeFlow$Initiate.assembleTx(ContractUpgradeFlow.kt:77) ~[corda-core-3.3-corda.jar:?]
    at net.corda.core.flows.AbstractStateReplacementFlow$Instigator.call(AbstractStateReplacementFlow.kt:64) ~[corda-core-3.3-corda.jar:?]
    at net.corda.core.flows.AbstractStateReplacementFlow$Instigator.call(AbstractStateReplacementFlow.kt:50) ~[corda-core-3.3-corda.jar:?]
    at net.corda.node.services.statemachine.FlowStateMachineImpl.run(FlowStateMachineImpl.kt:96) [corda-node-3.3-corda.jar:?]
    at net.corda.node.services.statemachine.FlowStateMachineImpl.run(FlowStateMachineImpl.kt:44) [corda-node-3.3-corda.jar:?]
    at co.paralleluniverse.fibers.Fiber.run1(Fiber.java:1092) [quasar-core-0.7.9-jdk8.jar:0.7.9]
    at co.paralleluniverse.fibers.Fiber.exec(Fiber.java:788) [quasar-core-0.7.9-jdk8.jar:0.7.9]
    at co.paralleluniverse.fibers.RunnableFiberTask.doExec(RunnableFiberTask.java:100) [quasar-core-0.7.9-jdk8.jar:0.7.9]
    at co.paralleluniverse.fibers.RunnableFiberTask.run(RunnableFiberTask.java:91) [quasar-core-0.7.9-jdk8.jar:0.7.9]
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) [?:1.8.0_201]
    at java.util.concurrent.FutureTask.run(FutureTask.java:266) [?:1.8.0_201]
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180) [?:1.8.0_201]
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293) [?:1.8.0_201]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [?:1.8.0_201]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [?:1.8.0_201]
    at net.corda.node.utilities.AffinityExecutor$ServiceAffinityExecutor$1$thread$1.run(AffinityExecutor.kt:62) [corda-node-3.3-corda.jar:?]
[WARN ] 2019-05-22T22:16:31,574Z [Node thread-1] flow.[5856148a-d233-43c4-ac20-396b9a91f6c0].run - Terminated by unexpected exception {}

EDIT: Some other errors captured:

[WARN ] 2019-06-03T16:36:22,357Z [Node thread-1] flow.[2aec6ee2-2e14-43f5-81ce-b301c4876e0a].run - Terminated by unexpected exception {}
java.lang.ClassCastException: io.corp.contract.DefaultContract cannot be cast to net.corda.core.contracts.UpgradedContract
        at net.corda.core.flows.ContractUpgradeFlow$Authorise.call(ContractUpgradeFlow.kt:38) ~[corda-core-3.3-corda.jar:?]
        at net.corda.core.flows.ContractUpgradeFlow$Authorise.call(ContractUpgradeFlow.kt:31) ~[corda-core-3.3-corda.jar:?]
        at net.corda.node.services.statemachine.FlowStateMachineImpl.run(FlowStateMachineImpl.kt:96) [corda-node-3.3-corda.jar:?]
        at net.corda.node.services.statemachine.FlowStateMachineImpl.run(FlowStateMachineImpl.kt:44) [corda-node-3.3-corda.jar:?]
        at co.paralleluniverse.fibers.Fiber.run1(Fiber.java:1092) [quasar-core-0.7.9-jdk8.jar:0.7.9]
        at co.paralleluniverse.fibers.Fiber.exec(Fiber.java:788) [quasar-core-0.7.9-jdk8.jar:0.7.9]
        at co.paralleluniverse.fibers.RunnableFiberTask.doExec(RunnableFiberTask.java:100) [quasar-core-0.7.9-jdk8.jar:0.7.9]
        at co.paralleluniverse.fibers.RunnableFiberTask.run(RunnableFiberTask.java:91) [quasar-core-0.7.9-jdk8.jar:0.7.9]
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) [?:1.8.0_201]
        at java.util.concurrent.FutureTask.run(FutureTask.java:266) [?:1.8.0_201]
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180) [?:1.8.0_201]
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293) [?:1.8.0_201]
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [?:1.8.0_201]
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [?:1.8.0_201]
        at net.corda.node.utilities.AffinityExecutor$ServiceAffinityExecutor$1$thread$1.run(AffinityExecutor.kt:62) [corda-node-3.3-corda.jar:?]

Also this was found for one our contract upgrade

[WARN ] 2019-06-03T17:44:26,859Z [Messaging DLJKqkjV9pKTqG5nKbQQ3o5B1hPj1zjrYxDYpbhPENXdR] messaging.P2PMessagingClient.sendWithRetry - Reached the maximum number of retries (3) for message ClientMessageImpl[messageID=0, durable=true, address=internal.peers.DL8itTRrD1LvKjd5sQ9DwX59KmZ42PTa964nJPfL6jf1VC,userID=null,properties=TypedProperties[platform-version=3,corda-vendor=Corda Open Source,release-version=3.3-corda,platform-topic=platform.session,_AMQ_DUPL_ID=23190134-6514-4165-8277-0e3df48e2678,corda_p2p_message_type=session_init]] redelivery to internal.peers.DL8itTRrD1LvKjd5sQ9DwX59KmZ42PTa964nJPfL6jf1VC {}
[WARN ] 2019-06-03T17:44:26,941Z [Messaging DLJKqkjV9pKTqG5nKbQQ3o5B1hPj1zjrYxDYpbhPENXdR] messaging.P2PMessagingClient.sendWithRetry - Reached the maximum number of retries (3) for message ClientMessageImpl[messageID=0, durable=true, address=internal.peers.DL8itTRrD1LvKjd5sQ9DwX59KmZ42PTa964nJPfL6jf1VC,userID=null,properties=TypedProperties[platform-version=3,corda-vendor=Corda Open Source,release-version=3.3-corda,platform-topic=platform.session,_AMQ_DUPL_ID=2e2cde97-1e3d-4ce9-b7af-01ab61a88114,corda_p2p_message_type=session_init]] redelivery to internal.peers.DL8itTRrD1LvKjd5sQ9DwX59KmZ42PTa964nJPfL6jf1VC {}


问:
Why Docker exec need --interactive? --tty should be enough?
I new to docker, when i play with docker exec. I have below question:

Command  docker exec -t 26b318e534c0 bash, already have tty, this should be interactive? Why must use docker exec **-it** 26b318e534c0 bash?

答:
You can create a pseudo tty without any input to the tty device. This allows an application generating output to do so using content recognized by the tty device (e.g. color output). If you want to be able to interactively type in that tty, then you need to pass the input option, from a terminal with tty support (not from a shell script, and not from some windows command prompts), to attach your console to the stdin of that container.

As a simple example with docker run, these two commands will look different:

```<code>docker run -t --rm debian ls -al --color=always

docker run --rm debian ls -al --color=always
</code>```

The first will have color output, the second will not, and neither will allow you to type input to the ls command being run inside the container.

Body:
You can create a pseudo tty without any input to the tty device. This allows an application generating output to do so using content recognized by the tty device (e.g. color output). If you want to be able to interactively type in that tty, then you need to pass the input option, from a terminal with tty support (not from a shell script, and not from some windows command prompts), to attach your console to the stdin of that container.

As a simple example with docker run, these two commands will look different:

docker run -t --rm debian ls -al --color=always

docker run --rm debian ls -al --color=always

The first will have color output, the second will not, and neither will allow you to type input to the ls command being run inside the container.


问:
How do I get values separated by a space and put them in a new list?
I want to get the values from a list=[[x,y,a b c],[x,y, d e f],[x,y, g h i]] and put the values from the third element splitted by a space on a new list.

I have tried using 2 for loops to iterate in each list and looking for the 3rd element (the text), split it using a space and storing each word in a new list.

list=[['x','y','a b c'],
['x','y','d e f'],
['x','y','g h i']]

wordsInput=[]
for words in list:
    for palabrasinList in range(len(words)):
        list[words][wordsinList].split(" ")
        individual=list[words][2].split(" ")[wordsinList]
        wordsInput.append(individual)

#Expected result:
    newList=[a,b,c,d,e,f,g,h,i]
```

<p>I would like the new list to be newList=[a,b,c,d,e,f,g,h,i], but somehow the notebook throws me an error. Please help :(.</p>

<p>[EDIT]
This is the error im getting:</p>

<pre class="lang-py prettyprint-override"><code>---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-73-aaefcd3cda7c> in <module>()
      2 for words in list:
      3     for wordsinList in range(len(words)):
----> 4         individual=list[words][2].split(" ")[wordsinList]
      5         wordsInput.append(individual)

TypeError: list indices must be integers or slices, not list
</code>```

答:
Assuming those are strings, not variables:

```<code>list = [['x', 'y', 'a b c'],
        ['x', 'y', 'd e f'],
        ['x', 'y', 'g h i']]
wordsInput=[]
for words in list:
    wordsInput+=words[2].split(" ")
print(wordsInput)
</code>```

OUTPUT

```<code>['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
</code>```

Body:
I want to get the values from a list=[[x,y,a b c],[x,y, d e f],[x,y, g h i]] and put the values from the third element splitted by a space on a new list.

I have tried using 2 for loops to iterate in each list and looking for the 3rd element (the text), split it using a space and storing each word in a new list.

list=[['x','y','a b c'],
['x','y','d e f'],
['x','y','g h i']]

wordsInput=[]
for words in list:
    for palabrasinList in range(len(words)):
        list[words][wordsinList].split(" ")
        individual=list[words][2].split(" ")[wordsinList]
        wordsInput.append(individual)

#Expected result:
    newList=[a,b,c,d,e,f,g,h,i]

I would like the new list to be newList=[a,b,c,d,e,f,g,h,i], but somehow the notebook throws me an error. Please help :(.

[EDIT]
This is the error im getting:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-73-aaefcd3cda7c> in <module>()
      2 for words in list:
      3     for wordsinList in range(len(words)):
----> 4         individual=list[words][2].split(" ")[wordsinList]
      5         wordsInput.append(individual)

TypeError: list indices must be integers or slices, not list

Body:
Assuming those are strings, not variables:

list = [['x', 'y', 'a b c'],
        ['x', 'y', 'd e f'],
        ['x', 'y', 'g h i']]
wordsInput=[]
for words in list:
    wordsInput+=words[2].split(" ")
print(wordsInput)

OUTPUT

['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']


问:
How do you detect a string within a file name in batch?
I am trying to sort a series of folders containing thousands of company documents into an alphabetically sorted list of individual folders with the naming scheme "last name, first name".

The documents I am trying to sort have the name of their subject in the file's name. For example, one file could be called "Baggins_Frodo_Resume" or "Snow, Jon - Resume". I need to sort those files into folders called "Snow, John" and "Baggins, Frodo" respectively.

I have the name of each folder on a text file called "list of names.txt" in the format:

```<code>Last First
Baggins Frodo
Snow Jon
</code>```

Written out in plain English, I would like to have the batch file follow the steps outlined below. I used brackets around terms that should be variables.

Read the first line in the file "list of names.txt"

Assign the last name from the list to the variable [last name] and the first name to the variable [first name]

Within directory [C:\folder that needs sorting]...

if [file name] contains the text [last name] AND [first name] then...

Copy [file] to a folder called [last name, first name]

Repeat until no more files containing the name exist

Move on to the next line on "list of names.txt" and repeat.

I apologize in advance for my erroneous code, I am usually just barely able to figure out the basics of batch when I need it but this time I'm really struggling.

I had some trouble formatting the code below so here is a link to what I have with adjusted spacing and highlights.

```<code>SETLOCAL ENABLEDELAYEDEXPANSION
rem Read the first name on the list and assign it to a variable
for /f "tokens=*" %%f in ("list of names.txt") do (
    for /f "tokens=*" %%F in ('dir /S /B /A:-D "%%f"') do (
        for %%N in ("%%F") do (
            set name=%%~NN
            set dest="%%~NN"
            set the directory
            cd /d %userprofile%\desktop\"folder to sort"
            rem find each file within the directory that contains the current name from the list
            find /I . -name "*%%~NN*" ! -name "*:*" -print if errorlevel 0 then(
                rem copy matching files to their respective folder
                copy "%%F" "%%~NN"\!name!!ext!"
            ) else (
echo No additional matches found
pause
end
            )
        )
    )
)
</code>```

There are a couple of issues here that I would really appreciate help fixing.

As my question suggests I'm not sure how to search just the name of each file for matches and not the entire contents of the file.

Additionally, I'm not sure how to separate the first/last names from "list of names.txt" to assign them to separate variables.

This is my first post on stackoverflow and in the future, I would like to be able to adjust the color of my code properly. I see in the help section that " In many cases, the syntax highlighting language will be inferred from the question's tags," but that didn't occur in my case. Is there anything obvious I'm missing?

Thanks in advance for your time, I really appreciate it!

答:
May I offer you a different approach?</p>

```<code>@echo off
setlocal EnableDelayedExpansion

rem Within directory [C:\folder that needs sorting]...
cd "C:\folder that needs sorting"

rem Process the list of folder names. Note that %%a=Last and %%b=First
rem Note that "usebackq" option is needed because the file name is enclosed in quotes
for /F "usebackq tokens=1,2" %%a in ("C:\folder\of\list of names.txt") do (

   rem Move all file names with the name scheme "Last*First*.*" into "Last, First" folder
   move "%%a*%%b*.*" "C:\base\folder\of\%%a, %%b"

)
</code>```

Body:
I am trying to sort a series of folders containing thousands of company documents into an alphabetically sorted list of individual folders with the naming scheme "last name, first name".

The documents I am trying to sort have the name of their subject in the file's name. For example, one file could be called "Baggins_Frodo_Resume" or "Snow, Jon - Resume". I need to sort those files into folders called "Snow, John" and "Baggins, Frodo" respectively.

I have the name of each folder on a text file called "list of names.txt" in the format:

Last First
Baggins Frodo
Snow Jon

Written out in plain English, I would like to have the batch file follow the steps outlined below. I used brackets around terms that should be variables.

Read the first line in the file "list of names.txt"

Assign the last name from the list to the variable [last name] and the first name to the variable [first name]

Within directory [C:\folder that needs sorting]...

if [file name] contains the text [last name] AND [first name] then...

Copy [file] to a folder called [last name, first name]

Repeat until no more files containing the name exist

Move on to the next line on "list of names.txt" and repeat.

I apologize in advance for my erroneous code, I am usually just barely able to figure out the basics of batch when I need it but this time I'm really struggling.

I had some trouble formatting the code below so here is a link to what I have with adjusted spacing and highlights.

SETLOCAL ENABLEDELAYEDEXPANSION
rem Read the first name on the list and assign it to a variable
for /f "tokens=*" %%f in ("list of names.txt") do (
    for /f "tokens=*" %%F in ('dir /S /B /A:-D "%%f"') do (
        for %%N in ("%%F") do (
            set name=%%~NN
            set dest="%%~NN"
            set the directory
            cd /d %userprofile%\desktop\"folder to sort"
            rem find each file within the directory that contains the current name from the list
            find /I . -name "*%%~NN*" ! -name "*:*" -print if errorlevel 0 then(
                rem copy matching files to their respective folder
                copy "%%F" "%%~NN"\!name!!ext!"
            ) else (
echo No additional matches found
pause
end
            )
        )
    )
)

There are a couple of issues here that I would really appreciate help fixing.

As my question suggests I'm not sure how to search just the name of each file for matches and not the entire contents of the file.

Additionally, I'm not sure how to separate the first/last names from "list of names.txt" to assign them to separate variables.

This is my first post on stackoverflow and in the future, I would like to be able to adjust the color of my code properly. I see in the help section that " In many cases, the syntax highlighting language will be inferred from the question's tags," but that didn't occur in my case. Is there anything obvious I'm missing?

Thanks in advance for your time, I really appreciate it!

Body:
May I offer you a different approach?

@echo off
setlocal EnableDelayedExpansion

rem Within directory [C:\folder that needs sorting]...
cd "C:\folder that needs sorting"

rem Process the list of folder names. Note that %%a=Last and %%b=First
rem Note that "usebackq" option is needed because the file name is enclosed in quotes
for /F "usebackq tokens=1,2" %%a in ("C:\folder\of\list of names.txt") do (

   rem Move all file names with the name scheme "Last*First*.*" into "Last, First" folder
   move "%%a*%%b*.*" "C:\base\folder\of\%%a, %%b"

)


问:
c++ Global Variables Across Multiple Files
I have some code spread over three files and I would like to use a fourth "gloabls" file to store some physical constants such as the value of pi.  This would avoid repetitive definitions of pi = 4*atan(1.0).  After poking around, what I've tried is creating a global header file:

```<code>/*globals.h*/
extern double g_pi;
</code>```

and a global cpp file:

```<code>/*globals.cpp*/
#include "math.h"
#include "globals.h"
double g_pi = 4*atan(1.0);
</code>```

Then I include these file in my main files:

```<code>/*mainFile.cpp*/
//Include math and other libraries
#include globals.h"
int main() {
/*
....
*/
double x = 2*g_pi
/*
....
*/
}
</code>```

This gives me an undefined reference error to g_pi. I'm using a g++ compiler on Ubuntu.  Hopefully its a simple fix! Your suggestions are much appreciated.  If more details are necessary I'll be happy to supply them.

答: I had the same problem. I was using CMAKE, the problem was I didn't put my globals.cpp file into CMAKE executable. This problem should be something similar, nothing wrong with the implementation itself.</p>

Body:
I have some code spread over three files and I would like to use a fourth "gloabls" file to store some physical constants such as the value of pi.  This would avoid repetitive definitions of pi = 4*atan(1.0).  After poking around, what I've tried is creating a global header file:

/*globals.h*/
extern double g_pi;

and a global cpp file:

/*globals.cpp*/
#include "math.h"
#include "globals.h"
double g_pi = 4*atan(1.0);

Then I include these file in my main files:

/*mainFile.cpp*/
//Include math and other libraries
#include globals.h"
int main() {
/*
....
*/
double x = 2*g_pi
/*
....
*/
}

This gives me an undefined reference error to g_pi. I'm using a g++ compiler on Ubuntu.  Hopefully its a simple fix! Your suggestions are much appreciated.  If more details are necessary I'll be happy to supply them.


问:
Difference between (eval '(+ 1 2)) and (eval (+ 1 2))?
In clisp, what is the difference?

```<code>(eval '(+ 1 2))

(eval (+ 1 2))
</code>```

答:
The first will pass the list (+ 1 2), which is similar to what you would get if you wrote (cons '+ (cons 1 (cons 2 nil)), to the eval function, which will then evaluate that expression, and produce the answer, 3. The expression '(+ 1 2) is a way of quoting an expression, so that it the expression can be passed literally as data, rather than evaluated immediately. Passing it to the eval function will then evaluate it.

The second will evaluate the expression (+ 1 2) to get the result 3, which is then passed to the eval function. A number evaluates to itself, so it will return the same answer as the first case, 3.

OwnerDisplayName: KayKay

Body:
In clisp, what is the difference?

(eval '(+ 1 2))

(eval (+ 1 2))


问:
Oracle Update with Subselect with Multiple Joins
I'm trying to write a script that includes an Oracle query to update the scheduled finish date of a project to the revised end date that was submitted through a change request, but the date is not being updated upon running the script.

I'm unsure whether this is a problem with my query or something else. Before I delve any deeper, does this query look like it should work? (I'm currently unable to test the query against the database itself.)

```<code>UPDATE Project pr
SET pr.ScheduledFinish = (SELECT ch.RevisedEndDate
                          FROM Change ch
                          JOIN ChangeRequests cr ON cr.ID = ch.ID
                          JOIN RisksAndIssues ri ON ri.ID = cr.ID
                          JOIN Project pr ON pr.ID = ri.PK_ID
                          WHERE pr.ID = ?)
WHERE pr.ID = (SELECT ID
               FROM Change ch
               WHERE ch.ID = ?)
</code>```

Note: The ? in the query is a bind variable that will take on the value of the record currently being worked on. ie. If the Change Request being operated on has an ID of 1214, the ? will be 1214 once the script runs.

Thanks in advance.

Update:

I believe this is the correct logic:

```<code>UPDATE Project pr
SET pr.ScheduledFinish = (SELECT ch.RevisedEndDate
                          FROM Change ch
                          JOIN ChangeRequests cr ON cr.ID = ch.ID
                          JOIN RisksAndIssues ri ON ri.ID = cr.ID
                          JOIN Project pr ON pr.ID = ri.PK_ID
                          WHERE pr.ID = ?)
WHERE pr.ID = (SELECT ID
               FROM RisksAndIssues ri
               JOIN ChangeRequests cr ON cr.ID = ri.ID
               JOIN Change ch ON ch.ID = cr.ID
               JOIN Project pr ON pr.ID = ri.PK_ID
               WHERE pr.ID = ?)
</code>```

Gordon, you were correct. I was trying to match a Change ID with a Project ID, but they don't correlate. So this new subselect in the WHERE clause of the update should fix the linkage issue.

答:
```<code>UPDATE Project pr
SET pr.ScheduledFinish = (SELECT ch.RevisedEndDate
                          FROM Change ch
                          JOIN ChangeRequests cr ON cr.ID = ch.ID
                          JOIN RisksAndIssues ri ON ri.ID = cr.ID
                          JOIN Project pr ON pr.ID = ri.PK_ID
                          WHERE pr.ID = ?)
WHERE pr.ID = (SELECT ID
               FROM RisksAndIssues ri
               JOIN ChangeRequests cr ON cr.ID = ri.ID
               JOIN Change ch ON ch.ID = cr.ID
               JOIN Project pr ON pr.ID = ri.PK_ID
               WHERE pr.ID = ?);
</code>```

There are a few issues with your query - for a start, you haven't aliased the ID column in the second subquery - which ID are you after? pr, ch, ri, ... ?
Also, you've got an unnecessary join to project in your subqueries; you could correlate that to the table you're updating, since it's the same table.

You could rewrite this to something like:

```<code>UPDATE Project pr
SET pr.ScheduledFinish = (SELECT ch.RevisedEndDate
                          FROM Change ch
                          INNER JOIN ChangeRequests cr ON cr.ID = ch.ID
                          INNER JOIN RisksAndIssues ri ON ri.ID = cr.ID
                          WHERE ri.PK_ID = pr.ID)
WHERE pr.ID = ?
AND   EXISTS (SELECT NULL
               FROM RisksAndIssues ri
               JOIN ChangeRequests cr ON cr.ID = ri.ID
               JOIN Change ch ON ch.ID = cr.ID
               WHERE ri.pk_id = pr.ID);
</code>```

Or, even better, you could avoid repeating the subquery by using a MERGE statement, e.g.:

```<code>MERGE INTO project tgt
  USING (SELECT ri.pk_id,
                ch.revisedenddate
         FROM   CHANGE ch
         INNER JOIN ChangeRequests cr ON cr.ID = ch.ID
         INNER JOIN RisksAndIssues ri ON ri.ID = cr.ID
         WHERE  ri.pk_id = ?) src
    ON (tgt.id = src.pk_id)
WHEN MATCHED THEN
  UPDATE SET tgt.scheduledfinish = src.revisedenddate;
</code>```

Body:
I'm trying to write a script that includes an Oracle query to update the scheduled finish date of a project to the revised end date that was submitted through a change request, but the date is not being updated upon running the script.

I'm unsure whether this is a problem with my query or something else. Before I delve any deeper, does this query look like it should work? (I'm currently unable to test the query against the database itself.)

UPDATE Project pr
SET pr.ScheduledFinish = (SELECT ch.RevisedEndDate
                          FROM Change ch
                          JOIN ChangeRequests cr ON cr.ID = ch.ID
                          JOIN RisksAndIssues ri ON ri.ID = cr.ID
                          JOIN Project pr ON pr.ID = ri.PK_ID
                          WHERE pr.ID = ?)
WHERE pr.ID = (SELECT ID
               FROM Change ch
               WHERE ch.ID = ?)

Note: The ? in the query is a bind variable that will take on the value of the record currently being worked on. ie. If the Change Request being operated on has an ID of 1214, the ? will be 1214 once the script runs.

Thanks in advance.

Update:

I believe this is the correct logic:

UPDATE Project pr
SET pr.ScheduledFinish = (SELECT ch.RevisedEndDate
                          FROM Change ch
                          JOIN ChangeRequests cr ON cr.ID = ch.ID
                          JOIN RisksAndIssues ri ON ri.ID = cr.ID
                          JOIN Project pr ON pr.ID = ri.PK_ID
                          WHERE pr.ID = ?)
WHERE pr.ID = (SELECT ID
               FROM RisksAndIssues ri
               JOIN ChangeRequests cr ON cr.ID = ri.ID
               JOIN Change ch ON ch.ID = cr.ID
               JOIN Project pr ON pr.ID = ri.PK_ID
               WHERE pr.ID = ?)

Gordon, you were correct. I was trying to match a Change ID with a Project ID, but they don't correlate. So this new subselect in the WHERE clause of the update should fix the linkage issue.

Body:
UPDATE Project pr
SET pr.ScheduledFinish = (SELECT ch.RevisedEndDate
                          FROM Change ch
                          JOIN ChangeRequests cr ON cr.ID = ch.ID
                          JOIN RisksAndIssues ri ON ri.ID = cr.ID
                          JOIN Project pr ON pr.ID = ri.PK_ID
                          WHERE pr.ID = ?)
WHERE pr.ID = (SELECT ID
               FROM RisksAndIssues ri
               JOIN ChangeRequests cr ON cr.ID = ri.ID
               JOIN Change ch ON ch.ID = cr.ID
               JOIN Project pr ON pr.ID = ri.PK_ID
               WHERE pr.ID = ?);

There are a few issues with your query - for a start, you haven't aliased the ID column in the second subquery - which ID are you after? pr, ch, ri, ... ?
Also, you've got an unnecessary join to project in your subqueries; you could correlate that to the table you're updating, since it's the same table.

You could rewrite this to something like:

UPDATE Project pr
SET pr.ScheduledFinish = (SELECT ch.RevisedEndDate
                          FROM Change ch
                          INNER JOIN ChangeRequests cr ON cr.ID = ch.ID
                          INNER JOIN RisksAndIssues ri ON ri.ID = cr.ID
                          WHERE ri.PK_ID = pr.ID)
WHERE pr.ID = ?
AND   EXISTS (SELECT NULL
               FROM RisksAndIssues ri
               JOIN ChangeRequests cr ON cr.ID = ri.ID
               JOIN Change ch ON ch.ID = cr.ID
               WHERE ri.pk_id = pr.ID);

Or, even better, you could avoid repeating the subquery by using a MERGE statement, e.g.:

MERGE INTO project tgt
  USING (SELECT ri.pk_id,
                ch.revisedenddate
         FROM   CHANGE ch
         INNER JOIN ChangeRequests cr ON cr.ID = ch.ID
         INNER JOIN RisksAndIssues ri ON ri.ID = cr.ID
         WHERE  ri.pk_id = ?) src
    ON (tgt.id = src.pk_id)
WHEN MATCHED THEN
  UPDATE SET tgt.scheduledfinish = src.revisedenddate;