问:
Parsing of a huge xml file with `pythons etree.iterparse()` does not work right. Is there a logic error in the code?
I want to parse a huge file xml-file. The records in this huge file do look for example like this. And in general the file looks like this

```<code><?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE dblp SYSTEM "dblp.dtd">
<dblp>
    record_1
    ...
    record_n
</dblp>
</code>```

I wrote some code, that shall get me a selection of recordings from this file.

If I let the code run (takes nearly 50 Minutes including storage in the MySQL-Database) I notice, that there is a record, which seams to have nearly a million authors. This must be wrong. I even checked up on it by looking into the file make sure, that the file has no errors in it. The paper has only 5 or 6 authors, so all is fine wirh dblp.xml. So I assume a logic error in my code. But I can't figure out where this could be. Perhaps someone can tell me, where the error is?

The code stops in the line if len(auth) > 2000.

```<code>import sys
import MySQLdb
from lxml import etree

elements = ['article', 'inproceedings', 'proceedings', 'book', 'incollection']
tags = ["author", "title", "booktitle", "year", "journal"]

def fast_iter(context, cursor):
    mydict = {} # represents a paper with all its tags.
    auth = [] # a list of authors who have written the paper "together".
    counter = 0 # counts the papers

    for event, elem in context:
        if elem.tag in elements and event == "start":
            mydict["element"] = elem.tag
            mydict["mdate"] = elem.get("mdate")
            mydict["key"] = elem.get("key")

        elif elem.tag == "title" and elem.text != None:
            mydict["title"] = elem.text
        elif elem.tag == "booktitle" and elem.text != None:
            mydict["booktitle"] = elem.text
        elif elem.tag == "year" and elem.text != None:
            mydict["year"] = elem.text
        elif elem.tag == "journal" and elem.text != None:
            mydict["journal"] = elem.text
        elif elem.tag == "author" and elem.text != None:
            auth.append(elem.text)
        elif event == "end" and elem.tag in elements:
            counter += 1
            print counter
            #populate_database(mydict, auth, cursor)
            mydict.clear()
            auth = []
            if mydict or auth:
                sys.exit("Program aborted because auth or mydict was not deleted properly!")
        if len(auth) > 200: # There are up to ~150 authors per paper.
            sys.exit("auth: It seams there is a paper which has too many authors.!")
        if len(mydict) > 50: # A paper can have much metadata.
            sys.exit("mydict: It seams there is a paper which has too many tags.")

        elem.clear()
        while elem.getprevious() is not None:
            del elem.getparent()[0]
    del context

def main():
        cursor = connectToDatabase()
        cursor.execute("""SET NAMES utf8""")

        context = etree.iterparse(PATH_TO_XML, dtd_validation=True, events=("start", "end"))
        fast_iter(context, cursor)

        cursor.close()

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

EDIT:

I was totally misguided, when I wrote this function. I made a huge mistake by overlooking, that while trying to skip some unwanted recordings the get messed up with some wanted recordings. And at a certain point in the file, where I skiped nearly a million records in a row, the following wanted record got blown up.

With the help of John and Paul I managed to rewrite my code. It is parsing right now, and seams to do it well. I'll report back, if some unexpected errors remained unsolved. Elsewise thank you all for your help! I really appreciated it!

```<code>def fast_iter2(context, cursor):
    elements = set([
        'article', 'inproceedings', 'proceedings', 'book', 'incollection',
        'phdthesis', "mastersthesis", "www"
        ])
    childElements = set(["title", "booktitle", "year", "journal", "ee"])

    paper = {} # represents a paper with all its tags.
    authors = []   # a list of authors who have written the paper "together".
    paperCounter = 0
    for event, element in context:
        tag = element.tag
        if tag in childElements:
            if element.text:
                paper[tag] = element.text
                # print tag, paper[tag]
        elif tag == "author":
            if element.text:
                authors.append(element.text)
                # print "AUTHOR:", authors[-1]
        elif tag in elements:
            paper["element"] = tag
            paper["mdate"] = element.get("mdate")
            paper["dblpkey"] = element.get("key")
            # print tag, element.get("mdate"), element.get("key"), event
            if paper["element"] in ['phdthesis', "mastersthesis", "www"]:
                pass
            else:
                populate_database(paper, authors, cursor)
            paperCounter += 1
            print paperCounter
            paper = {}
            authors = []
            # if paperCounter == 100:
            #     break
            element.clear()
            while element.getprevious() is not None:
                del element.getparent()[0]
    del context
</code>```

答:
Add print statements in the blocks of code where you detect start and stop of a tag in elements, to make sure you are detecting these properly.  I suspect that for some reason you aren't getting to the code that clears the authors list.

Try commenting out this code (or at least, move it into the "end" handling block):

```<code>    elem.clear()
    while elem.getprevious() is not None:
        del elem.getparent()[0]
</code>```

Python should take care of clearing these elements for you as you traverse the XML.  The "del context" is also superfluous. Let the reference counters do the work for you here.

Body:
I want to parse a huge file xml-file. The records in this huge file do look for example like this. And in general the file looks like this

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE dblp SYSTEM "dblp.dtd">
<dblp>
    record_1
    ...
    record_n
</dblp>

I wrote some code, that shall get me a selection of recordings from this file.

If I let the code run (takes nearly 50 Minutes including storage in the MySQL-Database) I notice, that there is a record, which seams to have nearly a million authors. This must be wrong. I even checked up on it by looking into the file make sure, that the file has no errors in it. The paper has only 5 or 6 authors, so all is fine wirh dblp.xml. So I assume a logic error in my code. But I can't figure out where this could be. Perhaps someone can tell me, where the error is?

The code stops in the line if len(auth) > 2000.

import sys
import MySQLdb
from lxml import etree

elements = ['article', 'inproceedings', 'proceedings', 'book', 'incollection']
tags = ["author", "title", "booktitle", "year", "journal"]

def fast_iter(context, cursor):
    mydict = {} # represents a paper with all its tags.
    auth = [] # a list of authors who have written the paper "together".
    counter = 0 # counts the papers

    for event, elem in context:
        if elem.tag in elements and event == "start":
            mydict["element"] = elem.tag
            mydict["mdate"] = elem.get("mdate")
            mydict["key"] = elem.get("key")

        elif elem.tag == "title" and elem.text != None:
            mydict["title"] = elem.text
        elif elem.tag == "booktitle" and elem.text != None:
            mydict["booktitle"] = elem.text
        elif elem.tag == "year" and elem.text != None:
            mydict["year"] = elem.text
        elif elem.tag == "journal" and elem.text != None:
            mydict["journal"] = elem.text
        elif elem.tag == "author" and elem.text != None:
            auth.append(elem.text)
        elif event == "end" and elem.tag in elements:
            counter += 1
            print counter
            #populate_database(mydict, auth, cursor)
            mydict.clear()
            auth = []
            if mydict or auth:
                sys.exit("Program aborted because auth or mydict was not deleted properly!")
        if len(auth) > 200: # There are up to ~150 authors per paper.
            sys.exit("auth: It seams there is a paper which has too many authors.!")
        if len(mydict) > 50: # A paper can have much metadata.
            sys.exit("mydict: It seams there is a paper which has too many tags.")

        elem.clear()
        while elem.getprevious() is not None:
            del elem.getparent()[0]
    del context

def main():
        cursor = connectToDatabase()
        cursor.execute("""SET NAMES utf8""")

        context = etree.iterparse(PATH_TO_XML, dtd_validation=True, events=("start", "end"))
        fast_iter(context, cursor)

        cursor.close()

if __name__ == '__main__':
    main()

EDIT:

I was totally misguided, when I wrote this function. I made a huge mistake by overlooking, that while trying to skip some unwanted recordings the get messed up with some wanted recordings. And at a certain point in the file, where I skiped nearly a million records in a row, the following wanted record got blown up.

With the help of John and Paul I managed to rewrite my code. It is parsing right now, and seams to do it well. I'll report back, if some unexpected errors remained unsolved. Elsewise thank you all for your help! I really appreciated it!

def fast_iter2(context, cursor):
    elements = set([
        'article', 'inproceedings', 'proceedings', 'book', 'incollection',
        'phdthesis', "mastersthesis", "www"
        ])
    childElements = set(["title", "booktitle", "year", "journal", "ee"])

    paper = {} # represents a paper with all its tags.
    authors = []   # a list of authors who have written the paper "together".
    paperCounter = 0
    for event, element in context:
        tag = element.tag
        if tag in childElements:
            if element.text:
                paper[tag] = element.text
                # print tag, paper[tag]
        elif tag == "author":
            if element.text:
                authors.append(element.text)
                # print "AUTHOR:", authors[-1]
        elif tag in elements:
            paper["element"] = tag
            paper["mdate"] = element.get("mdate")
            paper["dblpkey"] = element.get("key")
            # print tag, element.get("mdate"), element.get("key"), event
            if paper["element"] in ['phdthesis', "mastersthesis", "www"]:
                pass
            else:
                populate_database(paper, authors, cursor)
            paperCounter += 1
            print paperCounter
            paper = {}
            authors = []
            # if paperCounter == 100:
            #     break
            element.clear()
            while element.getprevious() is not None:
                del element.getparent()[0]
    del context

Body:
Add print statements in the blocks of code where you detect start and stop of a tag in elements, to make sure you are detecting these properly.  I suspect that for some reason you aren't getting to the code that clears the authors list.

Try commenting out this code (or at least, move it into the "end" handling block):

    elem.clear()
    while elem.getprevious() is not None:
        del elem.getparent()[0]

Python should take care of clearing these elements for you as you traverse the XML.  The "del context" is also superfluous. Let the reference counters do the work for you here.


来源: stackexchange

问:
Date in response is different than from MongoDB
I am using Mongoose as MongoDB client, with Node and I am getting the date in respnse with -5:30 time.

Date in DB

```<code>"createdAt" : ISODate("2020-02-18T05:17:43.368+05:30"),
</code>```

Date in Response

```<code>"createdAt": "2020-02-17T23:47:43.368Z"
</code>```

It is affecting my applications data. is there any way to get the date as it is in the
DataBase.
Thanks.
Please write if more information required.

Mongoose Schema

```<code>const price = Schema({

}, {
  timestamps: true
})
</code>```

Query

```<code>  return Price.find(obj)
  .sort({
    _id: -1
  })
  .limit(parseInt(query.size) || 100)
  .skip((parseInt(query.size) || 100) * (parseInt(query.page) || 0))
  .populate('item')
  .lean()
</code>```

Server timedatectl

```<code>Local time: Wed 2020-02-19 12:47:29 IST
Universal time: Wed 2020-02-19 07:17:29 UTC
RTC time: Wed 2020-02-19 07:17:29
Time zone: Asia/Kolkata (IST, +0530)
System clock synchronized: yes
ystemd-timesyncd.service active: yes
RTC in local TZ: no
</code>```

答:
MongoDB will convert your date to GMT time during saving. But if you pull your date again to local time zone you will have appropriate time.

The ISODate is in UTC.

The browser converts to local time zone.

Is this okay for you?

z.toUTCString()

ContentLicense: CC BY-SA 4.0

Body:
I am using Mongoose as MongoDB client, with Node and I am getting the date in respnse with -5:30 time.

Date in DB

"createdAt" : ISODate("2020-02-18T05:17:43.368+05:30"),

Date in Response

"createdAt": "2020-02-17T23:47:43.368Z"

It is affecting my applications data. is there any way to get the date as it is in the
DataBase.
Thanks.
Please write if more information required.

Mongoose Schema

const price = Schema({

}, {
  timestamps: true
})

Query

  return Price.find(obj)
  .sort({
    _id: -1
  })
  .limit(parseInt(query.size) || 100)
  .skip((parseInt(query.size) || 100) * (parseInt(query.page) || 0))
  .populate('item')
  .lean()

Server timedatectl

Local time: Wed 2020-02-19 12:47:29 IST
Universal time: Wed 2020-02-19 07:17:29 UTC
RTC time: Wed 2020-02-19 07:17:29
Time zone: Asia/Kolkata (IST, +0530)
System clock synchronized: yes
ystemd-timesyncd.service active: yes
RTC in local TZ: no


问:
Azure function poison queue will crash whole job function?
I think it's a wire question, my situation is someone register an account to azure function, this function will add this account email and some messages to the queue. Queue trigger will trigger SendGrid to send something.

But a few days ago, some of the poison queues occurs, I find someone email format is incorrect. The strange thing is just one job function occurs poison, other job functions will not work, but redeploy will let it work for a while.
According to Microsoft document queue just execute 5 times and move to poison queue when all these fail.

The question is

When redeploying Azure job function, this poison queue will be retry?

Is it possible for such one job function error to cause the whole job function shutdown?

答:
No, it wont retry poison queue

No, if the message errors - it gets put into a poison queue after a certain amount of retries and thats it for that message


问:
How can I fill some data of the cell of the new column that is in accord with a substring of the original data using pandas?
There are 2 dataframes, and they have simillar data.

```<code>A dataframe

Index Business Address
1     Oils     Moskva, Russia
2     Foods    Tokyo, Japan
3     IT       California, USA
... etc.
</code>```

```<code>B dataframe

Index Country Country Calling Codes
1     USA     +1
2     Egypt   +20
3     Russia  +7
4     Korea   +82
5     Japan   +81
... etc.
</code>```

I will add a column named 'Country Calling Codes' to A dataframe, too.

After this, 'Country' column in B dataframe will be compared with the data of 'Address' column. If the  string of 'A.Address' includes string of 'B.Country', 'B.Country Calling Codes' will be inserted to 'A.Country Calling Codes' of compared row.

Result is:

```<code>Index Business Address         Country Calling Codes
1     Oils     Moskva, Russia  +7
2     Foods    Tokyo, Japan    +81
3     IT       California, USA +1
</code>```

I don't know how to deal with the issue because I don't have much experience using pandas. I should be very grateful to you if you might help me.

答:
Use Series.str.extract for get possible strings by Country column and then Series.map by Series:

```<code>d = B.drop_duplicates('Country').set_index('Country')['Country Calling Codes']
s = A['Address'].str.extract(f'({"|".join(d.keys())})', expand=False)
A['Country Calling Codes'] = s.map(d)
print (A)
   Index Business          Address Country Calling Codes
0      1     Oils   Moskva, Russia                    +7
1      2    Foods     Tokyo, Japan                   +81
2      3       IT  California, USA                    +1
</code>```

Detail:

```<code>print (A['Address'].str.extract(f'({"|".join(d.keys())})', expand=False))
0    Russia
1     Japan
2       USA
Name: Address, dtype: object
</code>```

Body:
There are 2 dataframes, and they have simillar data.

A dataframe

Index Business Address
1     Oils     Moskva, Russia
2     Foods    Tokyo, Japan
3     IT       California, USA
... etc.

B dataframe

Index Country Country Calling Codes
1     USA     +1
2     Egypt   +20
3     Russia  +7
4     Korea   +82
5     Japan   +81
... etc.

I will add a column named 'Country Calling Codes' to A dataframe, too.

After this, 'Country' column in B dataframe will be compared with the data of 'Address' column. If the  string of 'A.Address' includes string of 'B.Country', 'B.Country Calling Codes' will be inserted to 'A.Country Calling Codes' of compared row.

Result is:

Index Business Address         Country Calling Codes
1     Oils     Moskva, Russia  +7
2     Foods    Tokyo, Japan    +81
3     IT       California, USA +1

I don't know how to deal with the issue because I don't have much experience using pandas. I should be very grateful to you if you might help me.

Body:
Use Series.str.extract for get possible strings by Country column and then Series.map by Series:

d = B.drop_duplicates('Country').set_index('Country')['Country Calling Codes']
s = A['Address'].str.extract(f'({"|".join(d.keys())})', expand=False)
A['Country Calling Codes'] = s.map(d)
print (A)
   Index Business          Address Country Calling Codes
0      1     Oils   Moskva, Russia                    +7
1      2    Foods     Tokyo, Japan                   +81
2      3       IT  California, USA                    +1

Detail:

print (A['Address'].str.extract(f'({"|".join(d.keys())})', expand=False))
0    Russia
1     Japan
2       USA
Name: Address, dtype: object


问:
Using two array values in foreach loop
I have the following loop:

```<code>var array = ["Value 1", "Value 2", "Value 3"];
var textArray = ["Text 1", "Text 2", "Text 3"];

array.forEach(function(arr) {
  $(".department").append('<option value="' + array + '">' + textArray + '</option>');
});
</code>```

What I'm trying to achieve is the <option> label to use the text but its value to use the array array.

If I do the following:

```<code>$(".filterSection .department").append('<option value="'+array+'">'+textArray+'</option>');
</code>```

My output looks like this:

```<code><option value="Value 1,Value 2,Value 3">Text 1</option>
<option value="Value 1,Value 2,Value 3">Text 2</option>
</code>```

Whereas I'm looking for:

```<code><option value="Value 1">Text 1</option>
<option value="Value 2">Text 2</option>
</code>```

答:
Using map and literal templating.

NOTE: The append will only perform one DOM update which is recommended

NOTE: It seems .join("") is not even needed in the append

var array = ["Value 1", "Value 2", "Value 3"],
textArray = ["Text 1", "Text 2", "Text 3"],
options   = array.map((val,i) => `<option value="${val}">${textArray[i]}</option>`);

$(".department").append(options);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="department">
<option value="">Please select</option>
</select></code>```

Title: Using two array values in foreach loop

Body:
I have the following loop:

var array = ["Value 1", "Value 2", "Value 3"];
var textArray = ["Text 1", "Text 2", "Text 3"];

array.forEach(function(arr) {
  $(".department").append('<option value="' + array + '">' + textArray + '</option>');
});

What I'm trying to achieve is the <option> label to use the text but its value to use the array array.

If I do the following:

$(".filterSection .department").append('<option value="'+array+'">'+textArray+'</option>');

My output looks like this:

<option value="Value 1,Value 2,Value 3">Text 1</option>
<option value="Value 1,Value 2,Value 3">Text 2</option>

Whereas I'm looking for:

<option value="Value 1">Text 1</option>
<option value="Value 2">Text 2</option>

Body:
Using map and literal templating.

NOTE: The append will only perform one DOM update which is recommended

NOTE: It seems .join("") is not even needed in the append

var array = ["Value 1", "Value 2", "Value 3"],
textArray = ["Text 1", "Text 2", "Text 3"],
options   = array.map((val,i) => `<option value="${val}">${textArray[i]}</option>`);

$(".department").append(options);

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="department">
<option value="">Please select</option>
</select>


问:
How to allow single mouse click in Gtk.FileChooserDialog?
Below is a simplified example code for a Gtk.FileChooserDialog widget that I had adapted from the Gtk documentation. To select a file or a folder or activate any in this widget, presently I have to place the mouse pointer over the item and double click it. What I would like instead to happen is to use a single mouse click to do the selection and activation. How do I set this up for this widget?

```<code>import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk

class FileChooserWindow(Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self, title="FileChooser Example")

        box = Gtk.Box(spacing=6)
        self.add(box)

        button1 = Gtk.Button("Choose File")
        button1.connect("clicked", self.on_file_clicked)
        box.add(button1)

    def on_file_clicked(self, widget):
        dialog = Gtk.FileChooserDialog("Please choose a file", self,
            Gtk.FileChooserAction.OPEN,
            (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
             Gtk.STOCK_OPEN, Gtk.ResponseType.OK))

        response = dialog.run()
        if response == Gtk.ResponseType.OK:
            print("Open clicked")
            print("File selected: " + dialog.get_filename())
        elif response == Gtk.ResponseType.CANCEL:
            print("Cancel clicked")

        dialog.destroy()

win = FileChooserWindow()
win.connect("destroy", Gtk.main_quit)
win.show_all()
Gtk.main()
</code>```

答:
You can use the "selection-changed" signal like this:

def selection_changed (filechooser, udata):
    print ("selected ", filechooser.get_filename()) # GtkFileChooser method
    if True:                                        # some selection checking
        filechooser.response(Gtk.ResponseType.OK)   # GtkDialog method

dialog = Gtk.FileChooserDialog(...)
dialog.connect ("selection-changed", selection_changed, None)
response = dialog.run()
if response == Gtk.ResponseType.OK:
    pass
elif response == Gtk.ResponseType.CANCEL:
    pass
dialog.destroy()
```

But this signal is emitted every time user interacts with filechooser, even when user changes folder with breadcrumb-buttons. It will be up to you to determine, whether it's time to respond with Ok, Cancel or don't respond at all.

Futhermore, the user may be confused, that a dialog which requires pressing Ok or Enter in literally every other app behaves otherwise in your app.

Body:
Below is a simplified example code for a Gtk.FileChooserDialog widget that I had adapted from the Gtk documentation. To select a file or a folder or activate any in this widget, presently I have to place the mouse pointer over the item and double click it. What I would like instead to happen is to use a single mouse click to do the selection and activation. How do I set this up for this widget?

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk

class FileChooserWindow(Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self, title="FileChooser Example")

        box = Gtk.Box(spacing=6)
        self.add(box)

        button1 = Gtk.Button("Choose File")
        button1.connect("clicked", self.on_file_clicked)
        box.add(button1)

    def on_file_clicked(self, widget):
        dialog = Gtk.FileChooserDialog("Please choose a file", self,
            Gtk.FileChooserAction.OPEN,
            (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
             Gtk.STOCK_OPEN, Gtk.ResponseType.OK))

        response = dialog.run()
        if response == Gtk.ResponseType.OK:
            print("Open clicked")
            print("File selected: " + dialog.get_filename())
        elif response == Gtk.ResponseType.CANCEL:
            print("Cancel clicked")

        dialog.destroy()

win = FileChooserWindow()
win.connect("destroy", Gtk.main_quit)
win.show_all()
Gtk.main()

Body:
You can use the "selection-changed" signal like this:

def selection_changed (filechooser, udata):
    print ("selected ", filechooser.get_filename()) # GtkFileChooser method
    if True:                                        # some selection checking
        filechooser.response(Gtk.ResponseType.OK)   # GtkDialog method

dialog = Gtk.FileChooserDialog(...)
dialog.connect ("selection-changed", selection_changed, None)
response = dialog.run()
if response == Gtk.ResponseType.OK:
    pass
elif response == Gtk.ResponseType.CANCEL:
    pass
dialog.destroy()

But this signal is emitted every time user interacts with filechooser, even when user changes folder with breadcrumb-buttons. It will be up to you to determine, whether it's time to respond with Ok, Cancel or don't respond at all.

Futhermore, the user may be confused, that a dialog which requires pressing Ok or Enter in literally every other app behaves otherwise in your app.


问:
How to build a TreeView nodes with custom structure?
I am trying to build up a Treeview in Winform (using c#) with similar structure like the attached image.
Let say I have the Lowest node information with all their parent nodes info. For example: I have information of the lowest child node name is: "a", it's parent node is : "b", then grand node is "c" and so on "d". I will have all the lowest child nodes with all of their parents info, so need to create and gruop them in the correct group. So I just wonder how to do that ?

Thank you :).

答:
You can try using Tag to keep the instance corresponds with its node, e.g.

```<code>using System.Linq;

...

private static TreeNode AddNodes<T>(TreeView tree, IEnumerable<T> items) {
  if (null == tree)
    throw new ArgumentNullException(nameof(tree));
  else if (null == items)
    throw new ArgumentNullException(nameof(items));

  bool found = true;
  TreeNodeCollection nodes = tree.Nodes;
  TreeNode node = null;

  foreach (var item in items.Reverse()) {
    if (found) {
      node = nodes.OfType<TreeNode>().FirstOrDefault(nd => object.Equals(nd.Tag, item));

      found = node != null;
    }

    if (!found) {
      node = new TreeNode(item?.ToString());
      node.Tag = item;
      nodes.Add(node);
    }

    nodes = node.Nodes;
  }

  return node;
}
</code>```

Usage:

```<code>myTreeView.BeginUpdate();

try {
  // Items from child to parent
  AddNodes(myTreeView, new string[] { "leaf", "parent", "root"});
  AddNodes(myTreeView, new string[] { "child", "parent", "root" });
  AddNodes(myTreeView, new string[] { "child", "branch", "root" });
}
finally {
  myTreeView.EndUpdate();
}
</code>```

And you'll have

```<code>root
  parent
    leaf
    child
  branch
    child
</code>```

structure

Body:
You can try using Tag to keep the instance corresponds with its node, e.g.

using System.Linq;

...

private static TreeNode AddNodes<T>(TreeView tree, IEnumerable<T> items) {
  if (null == tree)
    throw new ArgumentNullException(nameof(tree));
  else if (null == items)
    throw new ArgumentNullException(nameof(items));

  bool found = true;
  TreeNodeCollection nodes = tree.Nodes;
  TreeNode node = null;

  foreach (var item in items.Reverse()) {
    if (found) {
      node = nodes.OfType<TreeNode>().FirstOrDefault(nd => object.Equals(nd.Tag, item));

      found = node != null;
    }

    if (!found) {
      node = new TreeNode(item?.ToString());
      node.Tag = item;
      nodes.Add(node);
    }

    nodes = node.Nodes;
  }

  return node;
}

Usage:

myTreeView.BeginUpdate();

try {
  // Items from child to parent
  AddNodes(myTreeView, new string[] { "leaf", "parent", "root"});
  AddNodes(myTreeView, new string[] { "child", "parent", "root" });
  AddNodes(myTreeView, new string[] { "child", "branch", "root" });
}
finally {
  myTreeView.EndUpdate();
}

And you'll have

root
  parent
    leaf
    child
  branch
    child

structure


答:
Do not use ,monotonically_increasing_id function to generate rowId. It gives random number which will fail your join logic. So go with row_number function that will give you correct rowId in all your cases.

```<code>scala> import org.apache.spark.sql.expressions.Window

scala> df.show()
+-------+------------------+
|     id|              name|
+-------+------------------+
|S703401|      RyanPCassidy|
|S703401|ChristopherJMat...|
|S703401|      FrankELaSota|
|S703401|      RyanPCassidy|
|S703401|AnthonyLLocricchio|
|S703401|        JasonMonte|
+-------+------------------+

scala> df1.show()
+-------+------+
|     id|   nic|
+-------+------+
|S703401|  RC82|
|S703401|    NA|
|S703401|   FL3|
|S703401|  RC82|
|S703401|    NA|
|S703401|JM2080|
+-------+------+

scala> val w = Window.partitionBy(col("id")).orderBy(lit(1))

scala> df.withColumn("rw", row_number.over(w))
         .join(df1.withColumn("rw", row_number.over(w)), List("id", "rw"),"left")
         .drop("rw")
         .show(false)
+-------+------------------+------+
|id     |name              |nic   |
+-------+------------------+------+
|S703401|RyanPCassidy      |RC82  |
|S703401|ChristopherJMat...|NA    |
|S703401|FrankELaSota      |FL3   |
|S703401|RyanPCassidy      |RC82  |
|S703401|AnthonyLLocricchio|NA    |
|S703401|JasonMonte        |JM2080|
+-------+------------------+------+
</code>```

Title: How to achieve inner join using Java SparkSql

Body:
I have two datasets as

DATASET1

+-------+--------------------+
|     id|                name|
+-------+--------------------+
|S703401|      Ryan P Cassidy|
|S703401|Christopher J Mat...|
|S703401|      Frank E LaSota|
|S703401|      Ryan P Cassidy|
|S703401|Anthony L Locricchio|
|S703401|         Jason Monte|
+-------+--------------------+

DATASET2

+-------+------+
|     id|   nic|
+-------+------+
|S703401|  RC82|
|S703401|    NA|
|S703401|   FL3|
|S703401|  RC82|
|S703401|    NA|
|S703401|JM2080|
+-------+------+

and i want to join them on id so that i can have output as

+-------+--------------------+-----------+
|     id|                name|       nic |
+-------+--------------------+-----------+
|S703401|      Ryan P Cassidy|       RC82|
|S703401|Christopher J Mat...|         NA|
|S703401|      Frank E LaSota|        FL3|
|S703401|      Ryan P Cassidy|       RC82|
|S703401|Anthony L Locricchio|         NA|
|S703401|         Jason Monte|     JM2080|
+-------+--------------------+-----------+

I am using java spark  Dataset  joined = dataset1.join(dataset2,"id");   but them i am getting cartesian product for all the rows like

+-------+--------------------+------+
|     id |                 name|   nic|
+-------+--------------------+------+
|S703401|      Ryan P Cassidy|JM2080|
|S703401|      Ryan P Cassidy|    NA|
|S703401|      Ryan P Cassidy|  RC82|
|S703401|      Ryan P Cassidy|   FL3|
|S703401|      Ryan P Cassidy|    NA|
|S703401|      Ryan P Cassidy|  RC82|
|S703401|Christopher J Mat...|JM2080|
|S703401|Christopher J Mat...|    NA|
|S703401|Christopher J Mat...|  RC82|
|S703401|Christopher J Mat...|   FL3|
|S703401|Christopher J Mat...|    NA|
|S703401|Christopher J Mat...|  RC82|
|S703401|      Frank E LaSota|JM2080|
|S703401|      Frank E LaSota|    NA|
|S703401|      Frank E LaSota|  RC82|
|S703401|      Frank E LaSota|   FL3|
|S703401|      Frank E LaSota|    NA|
|S703401|      Frank E LaSota|  RC82|
|S703401|      Ryan P Cassidy|JM2080|
|S703401|      Ryan P Cassidy|    NA|
+-------+--------------------+------+

So what am i missing here?

Body:
Do not use ,monotonically_increasing_id function to generate rowId. It gives random number which will fail your join logic. So go with row_number function that will give you correct rowId in all your cases.

scala> import org.apache.spark.sql.expressions.Window

scala> df.show()
+-------+------------------+
|     id|              name|
+-------+------------------+
|S703401|      RyanPCassidy|
|S703401|ChristopherJMat...|
|S703401|      FrankELaSota|
|S703401|      RyanPCassidy|
|S703401|AnthonyLLocricchio|
|S703401|        JasonMonte|
+-------+------------------+

scala> df1.show()
+-------+------+
|     id|   nic|
+-------+------+
|S703401|  RC82|
|S703401|    NA|
|S703401|   FL3|
|S703401|  RC82|
|S703401|    NA|
|S703401|JM2080|
+-------+------+

scala> val w = Window.partitionBy(col("id")).orderBy(lit(1))

scala> df.withColumn("rw", row_number.over(w))
         .join(df1.withColumn("rw", row_number.over(w)), List("id", "rw"),"left")
         .drop("rw")
         .show(false)
+-------+------------------+------+
|id     |name              |nic   |
+-------+------------------+------+
|S703401|RyanPCassidy      |RC82  |
|S703401|ChristopherJMat...|NA    |
|S703401|FrankELaSota      |FL3   |
|S703401|RyanPCassidy      |RC82  |
|S703401|AnthonyLLocricchio|NA    |
|S703401|JasonMonte        |JM2080|
+-------+------------------+------+


问:
How can i redirect unstructured link like (https://example.com/digital-marketing.php/ercbierubcrei) using .htaccess?
There is a issue of unstructured link like (https://example.com/digital-marketing.php/ercbierubcrei)

How can I redirect its to main root?

My .htaccess not working, I'm using below code in .htaccess:-

```<code>RewriteEngine On
ErrorDocument 404 /example.com
</code>```

答:
Please refer to below .htaccess examples:

Redirect http://yourdomain/digital-marketing.php/apple to http://yourdomain/:

```<code>RewriteEngine On
RewriteCond %{REQUEST_URI} /digital-marketing.php/*
RewriteRule ^ / [L,R=301]
</code>```

Redirect http://yourdomain/digital-marketing.php/orange to http://yourdomain/ref?code=orange:

```<code>RewriteEngine On
RewriteCond %{REQUEST_URI} /digital-marketing.php/*
RewriteRule ^digital-marketing.php/(.*)$ /ref?code=$1 [L,R=301]
</code>```

Body:
There is a issue of unstructured link like (https://example.com/digital-marketing.php/ercbierubcrei)

How can I redirect its to main root?

My .htaccess not working, I'm using below code in .htaccess:-

RewriteEngine On
ErrorDocument 404 /example.com

Body:
Please refer to below .htaccess examples:

Redirect http://yourdomain/digital-marketing.php/apple to http://yourdomain/:

RewriteEngine On
RewriteCond %{REQUEST_URI} /digital-marketing.php/*
RewriteRule ^ / [L,R=301]

Redirect http://yourdomain/digital-marketing.php/orange to http://yourdomain/ref?code=orange:

RewriteEngine On
RewriteCond %{REQUEST_URI} /digital-marketing.php/*
RewriteRule ^digital-marketing.php/(.*)$ /ref?code=$1 [L,R=301]


问:
How to allow only lower case as input arguments in Bash
I want to allow only lower case in my input. I've tried [a-z], [a-z^A-Z] and also [:lower:]. But it doesn't help.

All the expressions are going to else loop only if the whole string in uppercase.

Example:

If 1. Demo --- It says syntax valid
   2. demo --- It says syntax valid
   3. DEMO --- It says syntax invalid

But I need the syntax invalid even if the input is similar to example 1.

```<code>#!/bin/bash
client_name=$1

if [[ "$client_name" =~ [:lower:] ]]
        then
        echo " CLIENT Name Syntax is Valid"
        else
        echo -e "CLIENT Name Syntax is Invalid"
        exit 01
fi
</code>```

Any suggestion would be much appreciated. Thanks

答:
[[:lower:]] matches a single lower case character. Hence you are testing whether your string contains a lower case character somewhere.

What you are looking for is to find whether there is a character which is not a lower case character, and then issue an error. This can be done for instance with

```<code>if [[ $client_name =~ [^[:lower:]] ]]
then
  echo $client_name contains at least one non-lower case character
else
  echo OK
fi
</code>```

The ^ negates the elements of the character set in the regexp.

Body:
I want to allow only lower case in my input. I've tried [a-z], [a-z^A-Z] and also [:lower:]. But it doesn't help.

All the expressions are going to else loop only if the whole string in uppercase.

Example:

If 1. Demo --- It says syntax valid
   2. demo --- It says syntax valid
   3. DEMO --- It says syntax invalid

But I need the syntax invalid even if the input is similar to example 1.

#!/bin/bash
client_name=$1

if [[ "$client_name" =~ [:lower:] ]]
        then
        echo " CLIENT Name Syntax is Valid"
        else
        echo -e "CLIENT Name Syntax is Invalid"
        exit 01
fi

Any suggestion would be much appreciated. Thanks

Body:
[[:lower:]] matches a single lower case character. Hence you are testing whether your string contains a lower case character somewhere.

What you are looking for is to find whether there is a character which is not a lower case character, and then issue an error. This can be done for instance with

if [[ $client_name =~ [^[:lower:]] ]]
then
  echo $client_name contains at least one non-lower case character
else
  echo OK
fi

The ^ negates the elements of the character set in the regexp.


问:
Code does not output Thai symbols, but Chinese works
When testing my test c++ code, the English and Chinese characters are displayed  correctly, but the Thai characters lead to ???. I am using Visual Studio as IDE.

This is my code

#include <iostream>
using namespace std;

int main()
{
    std::cout << "Hello World!\n";
    cout << "ยบางนา-ตราด 25 แขวงบางนาเหนือ 10260 บางนา กรุงเทพฯ 我爱北京天安门" << endl;
}
```

<p>Here is the result</p>

```Hello World!
??????-???? 25 ?????????????? 10260 ????? ???????? 我爱北京天安门
```

答:
I found the answer.

https://blog.csdn.net/longyanbuhui/article/details/104019268

this method solve my question.

Body:
When testing my test c++ code, the English and Chinese characters are displayed  correctly, but the Thai characters lead to ???. I am using Visual Studio as IDE.

This is my code

#include <iostream>
using namespace std;

int main()
{
    std::cout << "Hello World!\n";
    cout << "ยบางนา-ตราด 25 แขวงบางนาเหนือ 10260 บางนา กรุงเทพฯ 我爱北京天安门" << endl;
}

Here is the result

Hello World!
??????-???? 25 ?????????????? 10260 ????? ???????? 我爱北京天安门


问:
How do I access external functions in a class using GroovyScript
I have a simple script like this...

```<code>def createEntry(service){
    ...
}
class Service {
    ...
    void create(){
        createEntry(this)
    }
}
</code>```

But when I run this code I get the following...

hudson.remoting.ProxyException: groovy.lang.MissingMethodException: No signature of method: Service.createEntry() is applicable for argument types: (Service) values: [Service@64bbfb0d]

答:
I found this answer on the Groovy forum.

It's terrible, but at least it's possible...

```<code>def g = { x, y -> x * y }

class MyFunc {
   def fun
   def run(x, y) { fun(x, y) }
}

def  fn = new MyFunc(fun: g)

println fn.run(4, 9)
</code>```

Body:
I have a simple script like this...

def createEntry(service){
    ...
}
class Service {
    ...
    void create(){
        createEntry(this)
    }
}

But when I run this code I get the following...

hudson.remoting.ProxyException: groovy.lang.MissingMethodException: No signature of method: Service.createEntry() is applicable for argument types: (Service) values: [Service@64bbfb0d]

Body:
I found this answer on the Groovy forum.

It's terrible, but at least it's possible...

def g = { x, y -> x * y }

class MyFunc {
   def fun
   def run(x, y) { fun(x, y) }
}

def  fn = new MyFunc(fun: g)

println fn.run(4, 9)


问:
How to clear/reset a select box option when i select the first option of another selectbox using jquery?
I want to reset the value of a select box every time I select the first option of another select box. As you can see in my code below I am using 2 select boxes. The first one contains some dates and the second select box contain some hours. I need to reset the value of the second select box when I select the first option of the dates select box. I can't figure out where I went wrong.

$( document ).on( "change", ".date_list", function() {
if ( $('select[name=d_date]')[0].selectedIndex === 0 )
{
$("#d_time").val();
alert('HOLLA');
}
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

<select class="date_list" name="d_date" id="d_date">
<option value="2020-02-19">Wednesday 19 February</option>
<option value="2020-02-20">Thursday 20 February</option>
<option value="2020-02-21">Friday 21 February</option>
<option value="2020-02-24">Monday 24 February</option>
<option value="2020-02-25">Tuesday 25 February</option>
<option value="2020-02-26">Wednesday 26 February</option>
</select>

<select class="time_list" name="d_time" id="d_time"><option value="9:56:00">09:56</option><option value="10:56:00">10:56</option><option value="11:56:00">11:56</option><option value="12:56:00">12:56</option><option value="13:56:00">13:56</option><option value="14:56:00">14:56</option><option value="15:56:00">15:56</option><option value="16:56:00">16:56</option><option value="17:56:00">17:56</option><option value="18:56:00">18:56</option><option value="19:56:00">19:56</option><option value="20:56:00">20:56</option><option value="21:56:00">21:56</option></select></code>```

答:
just setting an empty string $("#d_time").val("");
Adding an empty option in the select box is highly recommended.

$( document ).on( "change", ".date_list", function() {
if ( $('select[name=d_date]')[0].selectedIndex === 0 )
{
$("#d_time").val("");

}
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

<select class="date_list" name="d_date" id="d_date">
<option value="2020-02-19">Wednesday 19 February</option>
<option value="2020-02-20">Thursday 20 February</option>
<option value="2020-02-21">Friday 21 February</option>
<option value="2020-02-24">Monday 24 February</option>
<option value="2020-02-25">Tuesday 25 February</option>
<option value="2020-02-26">Wednesday 26 February</option>
</select>

<select class="time_list" name="d_time" id="d_time"><option value="9:56:00">09:56</option><option value="10:56:00">10:56</option><option value="11:56:00">11:56</option><option value="12:56:00">12:56</option><option value="13:56:00">13:56</option><option value="14:56:00">14:56</option><option value="15:56:00">15:56</option><option value="16:56:00">16:56</option><option value="17:56:00">17:56</option><option value="18:56:00">18:56</option><option value="19:56:00">19:56</option><option value="20:56:00">20:56</option><option value="21:56:00">21:56</option></select></code>```

Body:
I want to reset the value of a select box every time I select the first option of another select box. As you can see in my code below I am using 2 select boxes. The first one contains some dates and the second select box contain some hours. I need to reset the value of the second select box when I select the first option of the dates select box. I can't figure out where I went wrong.

$( document ).on( "change", ".date_list", function() {
if ( $('select[name=d_date]')[0].selectedIndex === 0 )
{
$("#d_time").val();
alert('HOLLA');
}
});

<select class="date_list" name="d_date" id="d_date">
<option value="2020-02-19">Wednesday 19 February</option>
<option value="2020-02-20">Thursday 20 February</option>
<option value="2020-02-21">Friday 21 February</option>
<option value="2020-02-24">Monday 24 February</option>
<option value="2020-02-25">Tuesday 25 February</option>
<option value="2020-02-26">Wednesday 26 February</option>
</select>

<select class="time_list" name="d_time" id="d_time"><option value="9:56:00">09:56</option><option value="10:56:00">10:56</option><option value="11:56:00">11:56</option><option value="12:56:00">12:56</option><option value="13:56:00">13:56</option><option value="14:56:00">14:56</option><option value="15:56:00">15:56</option><option value="16:56:00">16:56</option><option value="17:56:00">17:56</option><option value="18:56:00">18:56</option><option value="19:56:00">19:56</option><option value="20:56:00">20:56</option><option value="21:56:00">21:56</option></select>

Body:
just setting an empty string $("#d_time").val("");
Adding an empty option in the select box is highly recommended.

$( document ).on( "change", ".date_list", function() {
if ( $('select[name=d_date]')[0].selectedIndex === 0 )
{
$("#d_time").val("");

}
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

<select class="date_list" name="d_date" id="d_date">
<option value="2020-02-19">Wednesday 19 February</option>
<option value="2020-02-20">Thursday 20 February</option>
<option value="2020-02-21">Friday 21 February</option>
<option value="2020-02-24">Monday 24 February</option>
<option value="2020-02-25">Tuesday 25 February</option>
<option value="2020-02-26">Wednesday 26 February</option>
</select>

<select class="time_list" name="d_time" id="d_time"><option value="9:56:00">09:56</option><option value="10:56:00">10:56</option><option value="11:56:00">11:56</option><option value="12:56:00">12:56</option><option value="13:56:00">13:56</option><option value="14:56:00">14:56</option><option value="15:56:00">15:56</option><option value="16:56:00">16:56</option><option value="17:56:00">17:56</option><option value="18:56:00">18:56</option><option value="19:56:00">19:56</option><option value="20:56:00">20:56</option><option value="21:56:00">21:56</option></select>


问:
How to hide Tab conditionally in react-navigation?
I want to hide one of my tabs conditionally if user login,

So I have 5 Tabs If user login\register I get a boolean from a redux store,
if this user login i want to how a "Library tab" if not login, i don't want to show this tab "Library" with others and just keep 4 tabs in the App

Code

```<code>import {createAppContainer} from 'react-navigation';
import {createBottomTabNavigator} from 'react-navigation-tabs';

let {isLogin} = store.getState().user;

const TabHome = createBottomTabNavigator(
  {
    Home: {
      screen: Home,
      navigationOptions: {
        tabBarLabel: 'Home',
      },
    },
    Browse: {
      screen: Browse,
      navigationOptions: {
        tabBarLabel: 'Browse',
      },
    },
    Search: {
      screen: Search,
      navigationOptions: {
        tabBarLabel: 'Search',
        headerShown: false,
      },
    },
    Radio: {
      screen: Radio,
      navigationOptions: {
        tabBarLabel: 'Radio',
      },
    },
    Library: isLogin ? (
      {
        screen: YourLibrary,
        navigationOptions: {
          tabBarLabel: 'Library',
        },
      }
    ) : (
      <View /> // Or :null => Not work and got the under error msg
    ),
    // Library: {
    //   screen: YourLibrary,
    // },
  },
)

export default createAppContainer(TabHome);
</code>```

Error: The component for route 'Library' must be a React component.
  For example:

import MyScreen from './MyScreen'; ... Library: MyScreen, }

You can also use a navigator:

import MyNavigator from './MyNavigator'; ... Library: MyNavigator, }

答:
remove Library tab definition from TabHome and add it just before exporting the component:

```<code>if(isLogin) {
  TabHome.Library = {
    screen: YourLibrary,
    navigationOptions: {
      tabBarLabel: 'Library',
    }
  }
}

export default createAppContainer(TabHome)
</code>```

Body:
I want to hide one of my tabs conditionally if user login,

So I have 5 Tabs If user login\register I get a boolean from a redux store,
if this user login i want to how a "Library tab" if not login, i don't want to show this tab "Library" with others and just keep 4 tabs in the App

Code

import {createAppContainer} from 'react-navigation';
import {createBottomTabNavigator} from 'react-navigation-tabs';

let {isLogin} = store.getState().user;

const TabHome = createBottomTabNavigator(
  {
    Home: {
      screen: Home,
      navigationOptions: {
        tabBarLabel: 'Home',
      },
    },
    Browse: {
      screen: Browse,
      navigationOptions: {
        tabBarLabel: 'Browse',
      },
    },
    Search: {
      screen: Search,
      navigationOptions: {
        tabBarLabel: 'Search',
        headerShown: false,
      },
    },
    Radio: {
      screen: Radio,
      navigationOptions: {
        tabBarLabel: 'Radio',
      },
    },
    Library: isLogin ? (
      {
        screen: YourLibrary,
        navigationOptions: {
          tabBarLabel: 'Library',
        },
      }
    ) : (
      <View /> // Or :null => Not work and got the under error msg
    ),
    // Library: {
    //   screen: YourLibrary,
    // },
  },
)

export default createAppContainer(TabHome);

Error: The component for route 'Library' must be a React component.
  For example:

import MyScreen from './MyScreen'; ... Library: MyScreen, }

You can also use a navigator:

import MyNavigator from './MyNavigator'; ... Library: MyNavigator, }

Body:
remove Library tab definition from TabHome and add it just before exporting the component:

if(isLogin) {
  TabHome.Library = {
    screen: YourLibrary,
    navigationOptions: {
      tabBarLabel: 'Library',
    }
  }
}

export default createAppContainer(TabHome)


问:
Unable to access resx file in .net Core 3
Have added new .Resx file into Resources folder under .Net Core Web 3 project.

When try to access resx file its not available on controller or validation attribute.

What is the right way to work with Resx files in .Net Core.

答:
For Configuring Localization in Controller, you could refer to the following steps

1.Configure Localization in the Startup.ConfigureServices method and set cultures in  the Startup.Configure method. The localization middleware must be configured before any middleware which might check the request culture :

```<code>public void ConfigureServices(IServiceCollection services)
    {
       //Adds the localization services to the services container. The code above also sets the resources path to "Resources"
        services.AddLocalization(options => options.ResourcesPath = "Resources");

        services.AddControllersWithViews()
            .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
            .AddDataAnnotationsLocalization();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        var supportedCultures = new[]
        {
            new CultureInfo("en-US"),
            new CultureInfo("fr"),
        };

        app.UseRequestLocalization(new RequestLocalizationOptions
        {
            DefaultRequestCulture = new RequestCulture("en-US"),
            // Formatting numbers, dates, etc.
            SupportedCultures = supportedCultures,
            // UI strings that we have localized.
            SupportedUICultures = supportedCultures
        });

        ...
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });
    }
</code>```

2.The ConfigureServices method sets the ResourcesPath to "Resources", so the project relative path for the home controller's French resource file is Resources/Controllers.HomeController.fr.resx. Alternatively, you can use folders to organize resource files. For the home controller, the path would be Resources/Controllers/HomeController.fr.resx.

Then use IStringLocalizer which uses the ResourceManager and ResourceReader to provide culture-specific resources at run time to access Resx files in Controller .

```<code>public class HomeController : Controller
{
    private readonly IStringLocalizer<HomeController> _localizer;

    public HomeController(IStringLocalizer<HomeController> localizer)
    {
        _localizer = localizer;
    }

    public IActionResult About()
    {
        ViewData["Message"] = _localizer["Your application description page."];

        return View();
    }
}
</code>```

For more details , you could refer to the official doc which contains the sample code and DataAnnotations localization.

Body:
For Configuring Localization in Controller, you could refer to the following steps

1.Configure Localization in the Startup.ConfigureServices method and set cultures in  the Startup.Configure method. The localization middleware must be configured before any middleware which might check the request culture :

public void ConfigureServices(IServiceCollection services)
    {
       //Adds the localization services to the services container. The code above also sets the resources path to "Resources"
        services.AddLocalization(options => options.ResourcesPath = "Resources");

        services.AddControllersWithViews()
            .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
            .AddDataAnnotationsLocalization();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        var supportedCultures = new[]
        {
            new CultureInfo("en-US"),
            new CultureInfo("fr"),
        };

        app.UseRequestLocalization(new RequestLocalizationOptions
        {
            DefaultRequestCulture = new RequestCulture("en-US"),
            // Formatting numbers, dates, etc.
            SupportedCultures = supportedCultures,
            // UI strings that we have localized.
            SupportedUICultures = supportedCultures
        });

        ...
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });
    }

2.The ConfigureServices method sets the ResourcesPath to "Resources", so the project relative path for the home controller's French resource file is Resources/Controllers.HomeController.fr.resx. Alternatively, you can use folders to organize resource files. For the home controller, the path would be Resources/Controllers/HomeController.fr.resx.

Then use IStringLocalizer which uses the ResourceManager and ResourceReader to provide culture-specific resources at run time to access Resx files in Controller .

public class HomeController : Controller
{
    private readonly IStringLocalizer<HomeController> _localizer;

    public HomeController(IStringLocalizer<HomeController> localizer)
    {
        _localizer = localizer;
    }

    public IActionResult About()
    {
        ViewData["Message"] = _localizer["Your application description page."];

        return View();
    }
}

For more details , you could refer to the official doc which contains the sample code and DataAnnotations localization.


问:
Why is std::vector slower than an array?
When I run the following program (with optimization on), the for loop with the std::vector takes about 0.04 seconds while the for loop with the array takes 0.0001 seconds.

```<code>#include <iostream>
#include <vector>
#include <chrono>

int main()
{
    int len = 800000;
    int* Data = new int[len];

    int arr[3] = { 255, 0, 0 };
    std::vector<int> vec = { 255, 0, 0 };

    auto start = std::chrono::high_resolution_clock::now();
    for (int i = 0; i < len; i++) {
        Data[i] = vec[0];
    }
    auto finish = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double> elapsed = finish - start;
    std::cout << "The vector took " << elapsed.count() << "seconds\n";

    start = std::chrono::high_resolution_clock::now();
    for (int i = 0; i < len; i++) {
        Data[i] = arr[0];
    }
    finish = std::chrono::high_resolution_clock::now();
    elapsed = finish - start;
    std::cout << "The array took " << elapsed.count() << "seconds \n";

    char s;
    std::cin >> s;
    delete[] Data;
}
</code>```

The code is a simplified version of a performance issue I was having while writing a raycaster.  The len variable corresponds to how many times the loop in the original program needs to run (400 pixels * 400 pixels * 50 maximum render distance).  For complicated reasons (perhaps that I don't fully understand how to use arrays) I have to use a vector rather than an array in the actual raycaster.  However, as this program demonstrates, that would only give me 20 frames per second as opposed to the envied 10,000 frames per second that using an array would supposedly give me (obviously, this is just a simplified performance test).  But regardless of how accurate those numbers are, I still want to boost my frame rate as much as possible.  So, why is the vector performing so much slower than the array?  Is there a way to speed it up?  Thanks for your help.  And if there's anything else I'm doing weirdly that might be affecting performance, please let me know.  I didn't even know about optimization until researching an answer for this question, so if there are any more things like that which might boost the performance, please let me know (and I'd prefer if you explained where those settings are in the properties manager rather than command line since I don't yet know how to use the command line)

答:
Let us observe how GCC optimizes this test program:

```<code>#include <vector>

int main()
{
    int len = 800000;
    int* Data = new int[len];

    int arr[3] = { 255, 0, 0 };
    std::vector<int> vec = { 255, 0, 0 };

    for (int i = 0; i < len; i++) {
        Data[i] = vec[0];
    }
    for (int i = 0; i < len; i++) {
        Data[i] = arr[0];
    }
    delete[] Data;
}
</code>```

The compiler rightly notices that the vector is constant, and eliminates it. Exactly same code is generated for both loops. Therefore it should be irrelevant whether the first loop uses array or vector.

```<code>.L2:
    movups  XMMWORD PTR [rcx], xmm0
    add     rcx, 16
    cmp     rsi, rcx
    jne     .L2
</code>```

What makes difference in your test program is the order of loops. The comments point out that when a third loop is added to the beginning, both loops take the same time.

I would expect that with a modern compiler accessing a vector would be approximately as fast as accessing an array, when optimization is enabled and debug is disabled. If there is an observable difference in your actual program, the problem lies somewhere else.

Body:
When I run the following program (with optimization on), the for loop with the std::vector takes about 0.04 seconds while the for loop with the array takes 0.0001 seconds.

#include <iostream>
#include <vector>
#include <chrono>

int main()
{
    int len = 800000;
    int* Data = new int[len];

    int arr[3] = { 255, 0, 0 };
    std::vector<int> vec = { 255, 0, 0 };

    auto start = std::chrono::high_resolution_clock::now();
    for (int i = 0; i < len; i++) {
        Data[i] = vec[0];
    }
    auto finish = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double> elapsed = finish - start;
    std::cout << "The vector took " << elapsed.count() << "seconds\n";

    start = std::chrono::high_resolution_clock::now();
    for (int i = 0; i < len; i++) {
        Data[i] = arr[0];
    }
    finish = std::chrono::high_resolution_clock::now();
    elapsed = finish - start;
    std::cout << "The array took " << elapsed.count() << "seconds \n";

    char s;
    std::cin >> s;
    delete[] Data;
}

The code is a simplified version of a performance issue I was having while writing a raycaster.  The len variable corresponds to how many times the loop in the original program needs to run (400 pixels * 400 pixels * 50 maximum render distance).  For complicated reasons (perhaps that I don't fully understand how to use arrays) I have to use a vector rather than an array in the actual raycaster.  However, as this program demonstrates, that would only give me 20 frames per second as opposed to the envied 10,000 frames per second that using an array would supposedly give me (obviously, this is just a simplified performance test).  But regardless of how accurate those numbers are, I still want to boost my frame rate as much as possible.  So, why is the vector performing so much slower than the array?  Is there a way to speed it up?  Thanks for your help.  And if there's anything else I'm doing weirdly that might be affecting performance, please let me know.  I didn't even know about optimization until researching an answer for this question, so if there are any more things like that which might boost the performance, please let me know (and I'd prefer if you explained where those settings are in the properties manager rather than command line since I don't yet know how to use the command line)

Body:
Let us observe how GCC optimizes this test program:

#include <vector>

int main()
{
    int len = 800000;
    int* Data = new int[len];

    int arr[3] = { 255, 0, 0 };
    std::vector<int> vec = { 255, 0, 0 };

    for (int i = 0; i < len; i++) {
        Data[i] = vec[0];
    }
    for (int i = 0; i < len; i++) {
        Data[i] = arr[0];
    }
    delete[] Data;
}

The compiler rightly notices that the vector is constant, and eliminates it. Exactly same code is generated for both loops. Therefore it should be irrelevant whether the first loop uses array or vector.

.L2:
    movups  XMMWORD PTR [rcx], xmm0
    add     rcx, 16
    cmp     rsi, rcx
    jne     .L2

What makes difference in your test program is the order of loops. The comments point out that when a third loop is added to the beginning, both loops take the same time.

I would expect that with a modern compiler accessing a vector would be approximately as fast as accessing an array, when optimization is enabled and debug is disabled. If there is an observable difference in your actual program, the problem lies somewhere else.


问:
How to set all the bits in a char array to zeros?
I am creating a char pointer to an array and wanted to initilaize it so that all elements in the array have 0 (in bits). So for example:

```<code>char* buffer = new char[bufferSize];
</code>```

buffer[0] to buffer[bufferSize] will have '00000000' stored in each index. I am trying to store 8 bits of zeros in each cell.

How can i initialize it? I am also supposed to use fill().

So far,

```<code>fill(&buffer, &buffer[bufferSize], 0)
</code>```

doesn't work.

答:
Best way to do this is with a string:

```<code>std::string buffer(bufferSize, '\0');
</code>```

if you insist on using a char*, use calloc:

```<code>char* buffer = static_cast<char*>(std::calloc(bufferSize, 1));
</code>```

If you already have the buffer, you can zero it out with memset:

```<code>std::memset(buffer, 0, bufferSize);
</code>```

Body:
I am creating a char pointer to an array and wanted to initilaize it so that all elements in the array have 0 (in bits). So for example:

char* buffer = new char[bufferSize];

buffer[0] to buffer[bufferSize] will have '00000000' stored in each index. I am trying to store 8 bits of zeros in each cell.

How can i initialize it? I am also supposed to use fill().

So far,

fill(&buffer, &buffer[bufferSize], 0)

doesn't work.

Body:
Best way to do this is with a string:

std::string buffer(bufferSize, '\0');

if you insist on using a char*, use calloc:

char* buffer = static_cast<char*>(std::calloc(bufferSize, 1));

If you already have the buffer, you can zero it out with memset:

std::memset(buffer, 0, bufferSize);


问:
How to assert an integer is within range by using Unittest in Python?
I have a file to validate the label

```<code>#configmanager.py

class FunctionNode(object):
    def __validate_func_label(self, func_label):
        pattern = re.compile('^fn[1-9][0-9]{0,1}$')
        if not pattern.match(func_label):
            raise Exception(
                f"Invalid value {func_label} for function label in function config.")

</code>```

and I have to write a test case for it using Unit Testing. Test case will check if user enters fn is between 1 and 99, it will pass. Otherwise if fn out of range such as fn0 or fn100 then it fail. I writed a TestClass

```<code>#test__validate_func_label.py

import unittest
from configmanager import FunctionNode

class TestValidateFuncLabel(unittest.TestCase):
    def setUp(self):
        pass

    def test_fn_within_range(self):
        for i in range(1,99):
            self.assertEqual(fn(i),output[i])

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

But I feel like I'm not on the right track.
Is there any way i can assert fn is within range from 1 to 99?

Any help is appreciated.

答:
Another solution is:

https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertIn

```<code>self.assertIn(fn, range(1, 100))
</code>```

Body:
I have a file to validate the label

#configmanager.py

class FunctionNode(object):
    def __validate_func_label(self, func_label):
        pattern = re.compile('^fn[1-9][0-9]{0,1}$')
        if not pattern.match(func_label):
            raise Exception(
                f"Invalid value {func_label} for function label in function config.")

and I have to write a test case for it using Unit Testing. Test case will check if user enters fn is between 1 and 99, it will pass. Otherwise if fn out of range such as fn0 or fn100 then it fail. I writed a TestClass

#test__validate_func_label.py

import unittest
from configmanager import FunctionNode

class TestValidateFuncLabel(unittest.TestCase):
    def setUp(self):
        pass

    def test_fn_within_range(self):
        for i in range(1,99):
            self.assertEqual(fn(i),output[i])

if __name__ == "__main__":
    unittest.main()

But I feel like I'm not on the right track.
Is there any way i can assert fn is within range from 1 to 99?

Any help is appreciated.

Body:
Another solution is:

https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertIn

self.assertIn(fn, range(1, 100))


问:
react-native-image-picker not returning data from camera
I'm using react-native-image-picker to load photos. This seems to work well for photos pulled out of the camera roll, but if the user chooses to take a photo, there's no data in the response, just an empty string.

I'm using these options:

```<code>{
  title: 'Upload Photo',
  cancelButtonTitle: 'Cancel',
  takePhotoButtonTitle: 'Take Photo...',
  chooseFromLibraryButtonTitle: 'Choose from Library...',
  noData: false,
  mediaType: 'photo',
  quality: 0.2,
}
</code>```

and launching the image picker with:

```<code>UIImagePickerManager.showImagePicker(options, (response) => {
  console.log(response);
});
</code>```

will work fine for images picked out of the camera roll, but will give me an empty string for response.data when an new image is taken with the camera.

What gives?

答:
if you want to show image using data (noData:false)
use this:

```<code>UIImagePickerManager.showImagePicker(options, response => {
    if (response.didCancel) {
        console.log('User cancelled image picker');
    } else if (response.error) {
        console.log('ImagePicker Error: ', response.error);
    } else if (response.customButton) {
        console.log('User tapped custom button: ', response.customButton);
    } else {
        const source = {uri: 'data:image/jpeg;base64,' + response.data};
        this.setState({
            avatarSource: source,
        });
    }
});
</code>```

and set avatarSource state for image source

ContentLicense: CC BY-SA 3.0

Body:
I'm using react-native-image-picker to load photos. This seems to work well for photos pulled out of the camera roll, but if the user chooses to take a photo, there's no data in the response, just an empty string.

I'm using these options:

{
  title: 'Upload Photo',
  cancelButtonTitle: 'Cancel',
  takePhotoButtonTitle: 'Take Photo...',
  chooseFromLibraryButtonTitle: 'Choose from Library...',
  noData: false,
  mediaType: 'photo',
  quality: 0.2,
}

and launching the image picker with:

UIImagePickerManager.showImagePicker(options, (response) => {
  console.log(response);
});

will work fine for images picked out of the camera roll, but will give me an empty string for response.data when an new image is taken with the camera.

What gives?

Body:
if you want to show image using data (noData:false)
use this:

UIImagePickerManager.showImagePicker(options, response => {
    if (response.didCancel) {
        console.log('User cancelled image picker');
    } else if (response.error) {
        console.log('ImagePicker Error: ', response.error);
    } else if (response.customButton) {
        console.log('User tapped custom button: ', response.customButton);
    } else {
        const source = {uri: 'data:image/jpeg;base64,' + response.data};
        this.setState({
            avatarSource: source,
        });
    }
});

and set avatarSource state for image source


问:
Regex Excel Remove Middle Part of String
I have some address data that needs to be corrected. It is intending to show a range of addresses, but this will not work for geocoding. What is an effective way to to remove everything between the hyphen and the first space using regex in excel? Example:

```<code>    29-45  SICKLES ST
    31-39  SHERMAN AV
    36-44  ARDEN ST
   118-22  NAGLE AV
</code>```

Becomes

```<code>    29 SICKLES ST
    31 SHERMAN AV
    36 ARDEN ST
   118 NAGLE AV
</code>```

答: You will create a new column by = REGEXREPLACE(current_column,"-\d+ ","")

Body:
I have some address data that needs to be corrected. It is intending to show a range of addresses, but this will not work for geocoding. What is an effective way to to remove everything between the hyphen and the first space using regex in excel? Example:

    29-45  SICKLES ST
    31-39  SHERMAN AV
    36-44  ARDEN ST
   118-22  NAGLE AV

Becomes

    29 SICKLES ST
    31 SHERMAN AV
    36 ARDEN ST
   118 NAGLE AV


问:
Is a way to curry multiple ramda's assocPath methods in a redux reducer?
So wanted to know if there is any way I could curry multiple assocPath methods in redux reducer. What I wish to do is update the state of an object and array in my redux reducer without mutating it. For which I have to set a value in multiple object/ arrays. The way I am trying to do it is via creating a clone of the object and updating it and then again set it to the state, this I am doing in my components state.
So currently I am do something like this in my components state. I wish to do the similar in the redux reducer

```<code> let newState;
    newState = _.assocPath(["project", "value"], project, this.state);
    newState = _.assocPath(["project", "error"], false, newState);
    this.setState(newState);
</code>```

But the problem is in redux reducer I ma not able to do it. I have to curry the methods one after the other.

Please let me know if you want more info.
Thank you

答:
I would create the reducer using R.mergeDeepLeft with the object that I wish to merge with the original state, and then call it on the old state.

Example:

const state = { project: { value: null, error: true, other: 'other' } }
const project = {}

const reducer = R.mergeDeepLeft({
  project: {
    value: project,
    error: false
  }
})

const newState = reducer(state)

console.log(newState)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js"></script></code>```

Body:
So wanted to know if there is any way I could curry multiple assocPath methods in redux reducer. What I wish to do is update the state of an object and array in my redux reducer without mutating it. For which I have to set a value in multiple object/ arrays. The way I am trying to do it is via creating a clone of the object and updating it and then again set it to the state, this I am doing in my components state.
So currently I am do something like this in my components state. I wish to do the similar in the redux reducer

 let newState;
    newState = _.assocPath(["project", "value"], project, this.state);
    newState = _.assocPath(["project", "error"], false, newState);
    this.setState(newState);

But the problem is in redux reducer I ma not able to do it. I have to curry the methods one after the other.

Please let me know if you want more info.
Thank you

Body:
I would create the reducer using R.mergeDeepLeft with the object that I wish to merge with the original state, and then call it on the old state.

Example:

const state = { project: { value: null, error: true, other: 'other' } }
const project = {}

const reducer = R.mergeDeepLeft({
  project: {
    value: project,
    error: false
  }
})

const newState = reducer(state)

console.log(newState)

<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js"></script>


问:
How do style a specific angular material component?
I'm using angular material 2, but I think this also applies to angular material 1.

Let's say I want to use the angular material tabs, but I want to hide the tabs or add some specific styling to it.

So I have the following html/angular material code:

```<code><md-tab-group>
    <md-tab>
        <template md-tab-label> <--- I want to style or hide all these. e.g. "height: 0"
            Some tab
        </template>
        <template md-tab-content>
            Some content. Perhaps other tab components.
        </template>
    </md-tab>
    <md-tab>
        <template md-tab-label> <--- I want to style or hide all these. e.g. "height: 0"
            Some tab
        </template>
        <template md-tab-content>
            Some content. Perhaps other tab components.
        </template>
    </md-tab>
</md-tab-group>
</code>```

If I add a class to the "template md-tab-label"-tag it isn't added anywhere in the DOM structure.
I can't just style the "md-tab-label"-class because that would apply the style everywhere and to all tabs.
If I scope it from a parent element, it would apply to all nested tab components, that might be present in the tab content.
If I try limiting the depth and create a really really specific selector based on the final DOM representation, I would be applying a style on a structure that I have no control over and which could change at any update.

Is there a right way to do this or do I just have to create a selector by deconstructing the DOM structure?

答:
I would recommend to avoid /deep/, >>>, and ::ng-deep, because it is going to be depreciated. (And it does not look so clean)

As a solution i would deactivate view encapsulation on a component level.

```<code>@Component({
  selector: 'app-card-list',
  templateUrl: './card-list.component.html',
  styleUrls: ['./card-list.component.scss'],
  encapsulation: ViewEncapsulation.None
})
</code>```

After that i would create a surrounding div with scss for the angular material component.

```<code>.surrounding-div {
  .mat-dialog {
    display: flex;
    flex-direction: row;
    ...
  }
}
</code>```

This is my favourite approach to style Angular Material Components. Have fun!

Body:
I'm using angular material 2, but I think this also applies to angular material 1.

Let's say I want to use the angular material tabs, but I want to hide the tabs or add some specific styling to it.

So I have the following html/angular material code:

<md-tab-group>
    <md-tab>
        <template md-tab-label> <--- I want to style or hide all these. e.g. "height: 0"
            Some tab
        </template>
        <template md-tab-content>
            Some content. Perhaps other tab components.
        </template>
    </md-tab>
    <md-tab>
        <template md-tab-label> <--- I want to style or hide all these. e.g. "height: 0"
            Some tab
        </template>
        <template md-tab-content>
            Some content. Perhaps other tab components.
        </template>
    </md-tab>
</md-tab-group>

If I add a class to the "template md-tab-label"-tag it isn't added anywhere in the DOM structure.
I can't just style the "md-tab-label"-class because that would apply the style everywhere and to all tabs.
If I scope it from a parent element, it would apply to all nested tab components, that might be present in the tab content.
If I try limiting the depth and create a really really specific selector based on the final DOM representation, I would be applying a style on a structure that I have no control over and which could change at any update.

Is there a right way to do this or do I just have to create a selector by deconstructing the DOM structure?

Body:
I would recommend to avoid /deep/, >>>, and ::ng-deep, because it is going to be depreciated. (And it does not look so clean)

As a solution i would deactivate view encapsulation on a component level.

@Component({
  selector: 'app-card-list',
  templateUrl: './card-list.component.html',
  styleUrls: ['./card-list.component.scss'],
  encapsulation: ViewEncapsulation.None
})

After that i would create a surrounding div with scss for the angular material component.

.surrounding-div {
  .mat-dialog {
    display: flex;
    flex-direction: row;
    ...
  }
}

This is my favourite approach to style Angular Material Components. Have fun!


答:
The following query will give you the results in the format mentioned in the question if you want to return records based on the query running date

```<code>SELECT [USer], FORMAT ([Time], 'MM-dd') as [time]
from [Table1]
where FORMAT ([Time], 'MM-dd')=FORMAT (getdate(), 'MM-dd') and [user]="B"
</code>```

If you want results based on hard-coded date the following query will work

```<code>SELECT [USer], FORMAT ([Time], 'MM-dd') as [time]
from [Table1]
where FORMAT ([Time], 'MM-dd')='02-11' and [user]="B"
</code>```

Title: How to DATETIME regex and split

Body:
USER  TIME
 A     2020-02-18 12:00:13.037
 B     2020-02-19 12:00:13.037
 B     2020-02-11 11:00:13.037
 B     2020-02-11 14:00:13.037
 B     2020-02-11 08:00:13.037
 C     2020-02-09 12:00:13.037

I want result like this:

USER  TIME
 B     02-11
 B     02-11
 B     02-11

Query time is 02-11 and split time to month and data

How can I do? My query:

SELECT * FROM my_table WHERE USER = 'B' AND TIME REGEXP '02/11"

Body:
The following query will give you the results in the format mentioned in the question if you want to return records based on the query running date

SELECT [USer], FORMAT ([Time], 'MM-dd') as [time]
from [Table1]
where FORMAT ([Time], 'MM-dd')=FORMAT (getdate(), 'MM-dd') and [user]="B"

If you want results based on hard-coded date the following query will work

SELECT [USer], FORMAT ([Time], 'MM-dd') as [time]
from [Table1]
where FORMAT ([Time], 'MM-dd')='02-11' and [user]="B"


Title: How to DATETIME regex and split

Body:
Get the month and the date from your date and use DATEPART:

DECLARE @DataSource TABLE
(
    [User] CHAR(1)
   ,[Time] DATETIME2
);

INSERT INTO @DataSource ([User], [Time])
VALUES ('A', '2020-02-18 12:00:13.037')
      ,('B', '2020-02-19 12:00:13.037')
      ,('B', '2020-02-11 11:00:13.037')
      ,('B', '2020-02-11 14:00:13.037')
      ,('B', '2020-02-11 08:00:13.037')
      ,('C', '2020-02-09 12:00:13.037');

SELECT *
FROM @DataSource
WHERE [User] = 'B'
    AND DATEPART(MONTH, [Time]) = 2
    AND DATEPART(DAY, [Time]) = 11


问:
How can I remove or reset the tab order in VS 2010
I have a tab order set, but have rearranged a lot of controls, added more, removed some.
So now when I click view Tab Order it show the tab oeders by cluttering the screen with tons of numbers. Is there a way to clear these and start over?
I tried setting tabstop to false on the controls, hoping it would 'clear' their entries in the View Tab Order, but when I go back to view the tab order they still have numbers in them.

Any assistance would be greatly appreciated.

答:
I use in VS2019 :

replace : .TabIndex = .\d+
with : .TabIndex = 0


问:
From Text file to a pandas dataframe
I have a file which contains list of lists, its a text file, and it looks like that:

```<code>    [[ שומר
 ,קולורבי
 ,קיווי
 ,"תפו""ע פינק ליידי"
 ,גזר
 ,עגבניה
 ,Unknown
 ] ,
[ מארז נייצ'ר ואלי שיבולת שועל עם שבבי שוקולד
 ,פיטנס חטיפי פריכיות דקות קינמון 60 גרם
 ,פריכיות משולשות פלפל
 ,מארז נייצ'ר ואלי שיבולת שועל עם שבבי שוקולד
 ,Unknown
 ,בננה
 ,"תפו""ע פינק ליידי"
 ,"תפו""ע גרנד"
 ,מארז 5 חטיפי פרי דגנים תמר תפוח ללא סוכר
 ,Unknown
 ] ,
[ "תפו""א לבן ארוז דוד משה"
 ,כרוב לבן
 ,קישוא
 ,גזר
 ,בטטה
 ] ,
[ Unknown..........
</code>```

I need to convert it to pandas DataFrame, like wide columnstore, just one list = one row.
Any help would be amazing! I am working with Jupyter Notebook - Python 3.

答:
```<code>import json
with open('txt.txt') as f:
    lst = json.load(f)

df = pd.DataFrame(lst)
</code>```

Should give you what you want.

Title: From Text file to a pandas dataframe

Body:
I have a file which contains list of lists, its a text file, and it looks like that:

    [[ שומר
 ,קולורבי
 ,קיווי
 ,"תפו""ע פינק ליידי"
 ,גזר
 ,עגבניה
 ,Unknown
 ] ,
[ מארז נייצ'ר ואלי שיבולת שועל עם שבבי שוקולד
 ,פיטנס חטיפי פריכיות דקות קינמון 60 גרם
 ,פריכיות משולשות פלפל
 ,מארז נייצ'ר ואלי שיבולת שועל עם שבבי שוקולד
 ,Unknown
 ,בננה
 ,"תפו""ע פינק ליידי"
 ,"תפו""ע גרנד"
 ,מארז 5 חטיפי פרי דגנים תמר תפוח ללא סוכר
 ,Unknown
 ] ,
[ "תפו""א לבן ארוז דוד משה"
 ,כרוב לבן
 ,קישוא
 ,גזר
 ,בטטה
 ] ,
[ Unknown..........

I need to convert it to pandas DataFrame, like wide columnstore, just one list = one row.
Any help would be amazing! I am working with Jupyter Notebook - Python 3.

Body:
import json
with open('txt.txt') as f:
    lst = json.load(f)

df = pd.DataFrame(lst)

Should give you what you want.


问:
Play MP4 video using JMF
How to play MP4 video using JMF?

I am creating Java application. I want to play MP4 file using JMF. I tried to play MP4 file but it throws exception

```<code>Could not create player for filename.mp4
</code>```

Mpg format working fine for me. But I have only MP4 files.

Code:

```<code>Player mediaPlayer = Manager.createRealizedPlayer( mediaURL );
mediaPlayer.start();
</code>```

答:
JMF is obsolete and buggy.

JavaCV is a modern library for processing video based on OpenCV / FFMPEG and also supports 64bit which JMF does not.

Title: Play MP4 video using JMF

Body:
How to play MP4 video using JMF?

I am creating Java application. I want to play MP4 file using JMF. I tried to play MP4 file but it throws exception

Could not create player for filename.mp4

Mpg format working fine for me. But I have only MP4 files.

Code:

Player mediaPlayer = Manager.createRealizedPlayer( mediaURL );
mediaPlayer.start();


问:
how to access validation error property name in Laravel?
I have from in Laravel and I try to get validate it and see errors for each input, I already loop through $error->all() but I need to show the errors of each input under it and I use this code $errors->has('password') to show input have an error but I need to show message too.
I get print_r($errors) and It return this:

```<code>Illuminate\Support\ViewErrorBag Object
(
    [bags:protected] => Array
        (
            [default] => Illuminate\Support\MessageBag Object
                (
                    [messages:protected] => Array
                        (
                            [firstName] => Array
                                (
                                    [0] => The first name field is required.
                                )

                            [lastName] => Array
                                (
                                    [0] => The last name field is required.
                                )

                            [email] => Array
                                (
                                    [0] => The email must be a valid email address.
                                    [1] => The email field is required.
                                )

                            [password] => Array
                                (
                                    [0] => The password field is required.
                                )

                            [password_confirmation] => Array
                                (
                                    [0] => The password confirmation field is required.
                                )

                        )

                    [format:protected] => :message
                )

        )

)
</code>```

My problem is I can't how can access the messages?

答:
AS per Laravel Documentation you can use @error directive to achieve the same

The $errors variable is bound to the view by the
  Illuminate\View\Middleware\ShareErrorsFromSession middleware, which is
  provided by the web middleware group. When this middleware is applied
  an $errors variable will always be available in your views, allowing
  you to conveniently assume the $errors variable is always defined and
  can be safely used.

for e.g

```<code><label for="title">Post Title</label>

<input id="title" type="text" class="@error('title') is-invalid @enderror">

@error('title')
    <div class="alert alert-danger">{{ $message }}</div>
@enderror
</code>```

Laravel -> Validation -> Displaying The Validation Errors

Body:
I have from in Laravel and I try to get validate it and see errors for each input, I already loop through $error->all() but I need to show the errors of each input under it and I use this code $errors->has('password') to show input have an error but I need to show message too.
I get print_r($errors) and It return this:

Illuminate\Support\ViewErrorBag Object
(
    [bags:protected] => Array
        (
            [default] => Illuminate\Support\MessageBag Object
                (
                    [messages:protected] => Array
                        (
                            [firstName] => Array
                                (
                                    [0] => The first name field is required.
                                )

                            [lastName] => Array
                                (
                                    [0] => The last name field is required.
                                )

                            [email] => Array
                                (
                                    [0] => The email must be a valid email address.
                                    [1] => The email field is required.
                                )

                            [password] => Array
                                (
                                    [0] => The password field is required.
                                )

                            [password_confirmation] => Array
                                (
                                    [0] => The password confirmation field is required.
                                )

                        )

                    [format:protected] => :message
                )

        )

)

My problem is I can't how can access the messages?

Body:
AS per Laravel Documentation you can use @error directive to achieve the same

The $errors variable is bound to the view by the
  Illuminate\View\Middleware\ShareErrorsFromSession middleware, which is
  provided by the web middleware group. When this middleware is applied
  an $errors variable will always be available in your views, allowing
  you to conveniently assume the $errors variable is always defined and
  can be safely used.

for e.g

<label for="title">Post Title</label>

<input id="title" type="text" class="@error('title') is-invalid @enderror">

@error('title')
    <div class="alert alert-danger">{{ $message }}</div>
@enderror

Laravel -> Validation -> Displaying The Validation Errors


问:
With KotlinPoet or similar; generating a non-raw Kotlin string literal
Straightforward; is there a way to generate a valid Kotlin string literal (non-raw, as in non-triple-quote) from a string; I'm currently trying to accomplish this with KotlinPoet.

For clarity sake, example input:

Hello, how are you?
I'm doing "great"!
I hope you are too!
It'll cost you $2.
```

<p>Desired example output:</p>

```"Hello, how are you?\nI'm doing \"great\"!\nI hope you are too!\nIt'll cost you \$2."
```

<hr>

<p>With KotlinPoet, the best I can manage from the API I've learned thus far is:</p>

```"""
|Hello, how are you?
|I'm doing "great"!
|I hope you are too!
|It'll cost you ${'$'}2.
|""".trimMargin()
```

Which, while functional, is not what I'm trying to achieve.

I've been able to accomplish something functionally close, with Jackson's ObjectMapper::writeValueAsString, however, I'm sure there's plenty of caveats with using this to generate valid Kotlin code.

答:
Unfortunately, the relevant function in KotlinPoet is internal, or you could just call it with isConstantContext = true as in this test.

So as a workaround, you can put the string in a constant context, such as const val x = ... or @A(...) (where ... is your string), generate code for it and then remove everything but the literal.

Body:
Straightforward; is there a way to generate a valid Kotlin string literal (non-raw, as in non-triple-quote) from a string; I'm currently trying to accomplish this with KotlinPoet.

For clarity sake, example input:

Hello, how are you?
I'm doing "great"!
I hope you are too!
It'll cost you $2.

Desired example output:

"Hello, how are you?\nI'm doing \"great\"!\nI hope you are too!\nIt'll cost you \$2."

With KotlinPoet, the best I can manage from the API I've learned thus far is:

"""
|Hello, how are you?
|I'm doing "great"!
|I hope you are too!
|It'll cost you ${'$'}2.
|""".trimMargin()

Which, while functional, is not what I'm trying to achieve.

I've been able to accomplish something functionally close, with Jackson's ObjectMapper::writeValueAsString, however, I'm sure there's plenty of caveats with using this to generate valid Kotlin code.


问:
Can you use Roslyn compiler from a regular .net application?
I am currently using the old CSharp Compiler (Microsoft.CSharp.CSharpCodeProvider) and would like to upgrade my app to use the Roslyn Compiler to take advantage of all the new language features.

Looking at the Nuget Packages, it appears that to compile code at run-time in my application using the Roslyn Compiler, it needs to be a .NET Standard Library?

I've seen plenty of examples of how to use the Roslyn Compiler at run-time, however, all the packages they mention won't install in a .NET 4.5.2 project.

答: You must target at least .NET 4.6.1 to consume .NET Standard packages. See the documentation on .NET Standard compatibility here</p>


问:
can anybody help me. I am stuck at this step where Django is not able to show requested page
I am doing this Django project and I am stuck at this. I have created a new url path which will return the value which will be given after movies/__ in url.
here is my code:
note: movie is one the app in my application

movies/urls.py

```<code>from django.urls import path
from . import views
urlpatterns = [
   path("", views.index, name="movie_index"),
   path("< movie_id >", views.detail, name="movie_detail")
]
</code>```

movies/views.py

```<code>from django.http import HttpResponse
from django.shortcuts import render
from .models import movie
def index(request):
    movies = movie.objects.all()
    return render(request, "movies/index.html", {"movies": movies})

def detail(request, movie_id):
       return HttpResponse(movie_id)
</code>```

views.py in root folder

```<code>urlpatterns = [
path('admin/', admin.site.urls),
path('movies/', include('movies.urls'))
]
</code>```

my error :
enter image description here

I am using Django 2.1 and python 3.8
thanks in advance.......

答:
```<code>path("<int:movie_id>", views.detail, name="movie_detail")
</code>```

<p>instead of </p>

```<code>path("< movie_id >", views.detail, name="movie_detail")
</code>```

Body:
I am doing this Django project and I am stuck at this. I have created a new url path which will return the value which will be given after movies/__ in url.
here is my code:
note: movie is one the app in my application

movies/urls.py

from django.urls import path
from . import views
urlpatterns = [
   path("", views.index, name="movie_index"),
   path("< movie_id >", views.detail, name="movie_detail")
]

movies/views.py

from django.http import HttpResponse
from django.shortcuts import render
from .models import movie
def index(request):
    movies = movie.objects.all()
    return render(request, "movies/index.html", {"movies": movies})

def detail(request, movie_id):
       return HttpResponse(movie_id)

views.py in root folder

urlpatterns = [
path('admin/', admin.site.urls),
path('movies/', include('movies.urls'))
]

my error :
enter image description here

I am using Django 2.1 and python 3.8
thanks in advance.......

Body:
path("<int:movie_id>", views.detail, name="movie_detail")

instead of

path("< movie_id >", views.detail, name="movie_detail")


问:
I am trying to compare two arrays inside For Loops
I am creating a Lottery Program where I want to compare the winning numbers with the players numbers and if any numbers match, they win a prize. I have used count to do this in my match() method but it comes up with an error when I try to compare two arrays - getWinningNumbers() and getNumbers() which are from the other classes PLAYER and WINNINGNUMBERS. The error I am getting is "actual and formal parameters differ in length" but I am unsure how to fix this. I am using linked lists for the first time as well. Any help would be much appreciated.

The piece of code I am having trouble with is in the method match() in the Lottery Class.

```<code>public void matches() {
        PLAYER currentPlayer = pHead;
        int count = 0;
        for(int i = 0; i<6; i++) {
            for(int j = 0; j< 6; j++) {
                if (win.getWinningNumbers(i) == currentPlayer.getNumbers(j)) {
                    count++;
                }
            }
        }

``````````````````````````````````````````````````````````````````````````
</code>```

答:
Change the following snippet in matches():

```<code>if (win.getWinningNumbers(i) == currentPlayer.getNumbers(j)) {
                count++;
            }
</code>```

To

```<code>if (win.getWinningNumbers()[i] == currentPlayer.getNumbers()[j]) {
                count++;
            }
</code>```

Body:
I am creating a Lottery Program where I want to compare the winning numbers with the players numbers and if any numbers match, they win a prize. I have used count to do this in my match() method but it comes up with an error when I try to compare two arrays - getWinningNumbers() and getNumbers() which are from the other classes PLAYER and WINNINGNUMBERS. The error I am getting is "actual and formal parameters differ in length" but I am unsure how to fix this. I am using linked lists for the first time as well. Any help would be much appreciated.

The piece of code I am having trouble with is in the method match() in the Lottery Class.

public void matches() {
        PLAYER currentPlayer = pHead;
        int count = 0;
        for(int i = 0; i<6; i++) {
            for(int j = 0; j< 6; j++) {
                if (win.getWinningNumbers(i) == currentPlayer.getNumbers(j)) {
                    count++;
                }
            }
        }

``````````````````````````````````````````````````````````````````````````

Body:
Change the following snippet in matches():

if (win.getWinningNumbers(i) == currentPlayer.getNumbers(j)) {
                count++;
            }

To

if (win.getWinningNumbers()[i] == currentPlayer.getNumbers()[j]) {
                count++;
            }