问:
MySQL (python 3.6) - SELECT * FROM table - returns number of rows instead of table
I am working with MySQL but I have some unexpected behaviour.
I have past experience with SQLite but I guess I am missing something here.

Using the query SELECT * FROM tableName I would expect the content of the table to be the output.
Instead I get an int, being the count of rows in the table.
Here is the piece of code I am using.

```<code>import MySQLdb

conn=MySQLdb.connect(host="xxx",user="xxx",passwd="xxx")
cursor = conn.cursor()
cursor.execute("create database if not exists Test;")
cursor.execute("use Test;")
cursor.execute("create table if not exists City (id int not null primary key auto_increment, city varchar(50), unique(city));")
cursor.execute("insert into City (city) values ('Firenze');")
cursor.execute("insert into City (city) values ('Roma');")
conn.commit()
print(cursor.execute("select city from City;"))
</code>```

I would expect to get:

```<code>Firenze
Roma
</code>```

Instead I get:
2

If I run the same query from a SQL client I get the expected output. Any clever idea?
Thanks :)

答:
The thing is print(cursor.execute("select city from City;") returns you the number of rows or rows count.

For the complete records use something like this

```<code>myresult = cursor.fetchall()
for x in myresult:
    print(x)
</code>```

Body:
I am working with MySQL but I have some unexpected behaviour.
I have past experience with SQLite but I guess I am missing something here.

Using the query SELECT * FROM tableName I would expect the content of the table to be the output.
Instead I get an int, being the count of rows in the table.
Here is the piece of code I am using.

import MySQLdb

conn=MySQLdb.connect(host="xxx",user="xxx",passwd="xxx")
cursor = conn.cursor()
cursor.execute("create database if not exists Test;")
cursor.execute("use Test;")
cursor.execute("create table if not exists City (id int not null primary key auto_increment, city varchar(50), unique(city));")
cursor.execute("insert into City (city) values ('Firenze');")
cursor.execute("insert into City (city) values ('Roma');")
conn.commit()
print(cursor.execute("select city from City;"))

I would expect to get:

Firenze
Roma

Instead I get:
2

If I run the same query from a SQL client I get the expected output. Any clever idea?
Thanks :)

Body:
The thing is print(cursor.execute("select city from City;") returns you the number of rows or rows count.

For the complete records use something like this

myresult = cursor.fetchall()
for x in myresult:
    print(x)


来源: stackexchange

问:
POST request URL not working when used directly
I am trying to scrape a cinema site showtimes. When I observe the POST requests the site is using to retrieve the showtimes (https://www.majorcineplex.com/booking2/search_showtime/cinema=1), it is working correctly.

However when I use the POST request (https://www.majorcineplex.com/ajaxbooking/ajax_showtime) directly in the browser. It is showing me "There is no information for this show".

I find this weird as both were fired from the same Chrome browser but I am getting different results.

I offer my appreciations in advance for any help/advice provided.

Update 29-May-2019

Here is my code for the Scrapy spider.

Basically from the response, I am trying to retrieve a div element with the class=book_st_contain.

I am sure this div element is in the HTML as I have checked using the Chrome Dev Tools. However it is just not there when I run the spider.

class SessionSpider(scrapy.Spider):
    name = 'session'
    start_urls = [
      'https://www.majorcineplex.com/booking2/search_showtime/cinema=1'
    ]

    def parse(self, response):
        f = open('response.txt', 'w')
        f.write(response.text)
```

答:
You need to ensure that the headers and posted body matches the one you are seeing in your browsers devtools:

A scrapy spider to replicate this would look something like this:

```<code>class MySpider(spider):
    name = 'major'

    showtime_url = "https://www.majorcineplex.com/ajaxbooking/ajax_showtime"
    showtime_headers = {
        'Accept': "*/*",
        'X-Requested-With': "XMLHttpRequest",
        'Content-Type': "application/x-www-form-urlencoded; charset=UTF-8",
    }
    showtime_payload = "movie_text=&cinema_text={}".format

    def start_requests():
        # crawl cinemas with ids 1 to 10
        for cinema in range(1, 10):
            payload = self.showtime_payload(cinema)
            yield Request(
                self.showtime_url,
                headers=self.showtime_headers,
                body=payload,
                method='POST'
            )
</code>```

Primarily you have to ensure Content-Type and X-Requested-With headers are present and match the values you see in your inspector.

ContentLicense: CC BY-SA 4.0

Body:
You need to ensure that the headers and posted body matches the one you are seeing in your browsers devtools:

A scrapy spider to replicate this would look something like this:

class MySpider(spider):
    name = 'major'

    showtime_url = "https://www.majorcineplex.com/ajaxbooking/ajax_showtime"
    showtime_headers = {
        'Accept': "*/*",
        'X-Requested-With': "XMLHttpRequest",
        'Content-Type': "application/x-www-form-urlencoded; charset=UTF-8",
    }
    showtime_payload = "movie_text=&cinema_text={}".format

    def start_requests():
        # crawl cinemas with ids 1 to 10
        for cinema in range(1, 10):
            payload = self.showtime_payload(cinema)
            yield Request(
                self.showtime_url,
                headers=self.showtime_headers,
                body=payload,
                method='POST'
            )

Primarily you have to ensure Content-Type and X-Requested-With headers are present and match the values you see in your inspector.


问:
Unable to clone github library to python
i trying to clone https://github.com/zhangchiyu10/pyC45 this repo to my python.

i was using
pip install git+https://github.com/zhangchiyu10/pyC45.git

```<code>ERROR: Complete output from command python setup.py egg_info:
  ERROR: Traceback (most recent call last):
    File "<string>", line 1, in <module>
    File "c:\python37\lib\tokenize.py", line 447, in open
      buffer = _builtin_open(filename, 'rb')
  FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\YULIAN~1\\AppData\\Local\\Temp\\pip-req-build-sqgmxgf8\\setup.py'
  ----------------------------------------
ERROR: Command "python setup.py egg_info" failed with error code 1 in C:\Users\YULIAN~1\AppData\Local\Temp\pip-req-build-sqgmxgf8\
</code>```

any idea about how to use github library?

答: that's not really a "package" (i.e. it does not provide tools to install via pip like proper setup.py). just download pyC45.py into your working directory/project

Body:
i trying to clone https://github.com/zhangchiyu10/pyC45 this repo to my python.

i was using
pip install git+https://github.com/zhangchiyu10/pyC45.git

ERROR: Complete output from command python setup.py egg_info:
  ERROR: Traceback (most recent call last):
    File "<string>", line 1, in <module>
    File "c:\python37\lib\tokenize.py", line 447, in open
      buffer = _builtin_open(filename, 'rb')
  FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\YULIAN~1\\AppData\\Local\\Temp\\pip-req-build-sqgmxgf8\\setup.py'
  ----------------------------------------
ERROR: Command "python setup.py egg_info" failed with error code 1 in C:\Users\YULIAN~1\AppData\Local\Temp\pip-req-build-sqgmxgf8\

any idea about how to use github library?


问:
grep multiple strings from multiple files and stop processing other files when first match found
I have ca 270 .bz2 log files (25 day logs) and one text file with ca 1500 usernames. What I need to do is find who of theese users are logged in in last 25 days. So I need to grep usernames from list of files and stop grepping when username is found in first file (when first match found).

My code works, but if in first file match found I do not need to process other files, break and search for another username, if it is found i.e. in third file, break and search for another username:

```<code>for i in $(cat /tmp/usernames.txt); do for j in $(ls *.bz2); do
bzgrep -o -m1 $i $j; done; done
</code>```

Here, if in fist file match found it breaks (-m1 flag) and starts searching for the same username in second file, but I do not need that anymore.

Problem: I need to inspect users who are not logged in in last 25 days. So I can reduce their permissions in the application. If user is logged at least once in last 25 days, I do not reduce his permissions.

Question is: I need to find whom of theese usernames exist in my log files. If username is found in one of the files at least one time stop searching for this user and start searching for another user.

Example: if user1 is found in file1, print it and stop searching for this user any more in this or other files. If user2 is found in file8, print it one time and stop searching in file9, file10, file11 ... file250. Hope it makes sense.

答:
If disk space isn't a concern I would ask bzip2 to decompress all the archives to a single file and invoke grep -m1 on that file for each username :

```<code>bzcat *.bz2 > merged
while IFS='' read -r username; do
  grep -om1 "$username" merged
done < /tmp/usernames.txt
rm merged
</code>```

Body:
I have ca 270 .bz2 log files (25 day logs) and one text file with ca 1500 usernames. What I need to do is find who of theese users are logged in in last 25 days. So I need to grep usernames from list of files and stop grepping when username is found in first file (when first match found).

My code works, but if in first file match found I do not need to process other files, break and search for another username, if it is found i.e. in third file, break and search for another username:

for i in $(cat /tmp/usernames.txt); do for j in $(ls *.bz2); do
bzgrep -o -m1 $i $j; done; done

Here, if in fist file match found it breaks (-m1 flag) and starts searching for the same username in second file, but I do not need that anymore.

Problem: I need to inspect users who are not logged in in last 25 days. So I can reduce their permissions in the application. If user is logged at least once in last 25 days, I do not reduce his permissions.

Question is: I need to find whom of theese usernames exist in my log files. If username is found in one of the files at least one time stop searching for this user and start searching for another user.

Example: if user1 is found in file1, print it and stop searching for this user any more in this or other files. If user2 is found in file8, print it one time and stop searching in file9, file10, file11 ... file250. Hope it makes sense.

Body:
If disk space isn't a concern I would ask bzip2 to decompress all the archives to a single file and invoke grep -m1 on that file for each username :

bzcat *.bz2 > merged
while IFS='' read -r username; do
  grep -om1 "$username" merged
done < /tmp/usernames.txt
rm merged


问:
There is no frame but still there is an error element is not found
Below is my code, the line =>
driver.findElement(By.xpath("//*[@id=\"quote_password\"]")).sendKeys("password"); throws exception that element is not found

```<code>@Test
public void mytest()
{
    System.setProperty("webdriver.chrome.driver","Drivers/chromedriver.exe");
    WebDriver driver = new ChromeDriver();
    driver.manage().window().maximize();
    driver.get("http://billing.scriptinglogic.net/index.php/sessions/login");
    driver.findElement(By.xpath("//*[@id='email']")).sendKeys("email");
    driver.findElement(By.xpath("//*[@id='password']")).sendKeys("password");
    driver.findElement(By.xpath("/html/body/div/div/form/input")).click();
    driver.findElement(By.xpath("//*[text()='Quotes']")).click();
    driver.findElement(By.xpath("//*[text()='Create Quote']")).click();
    driver.findElement(By.xpath("//*[@id=\"quote_password\"]")).sendKeys("password");

}
</code>```

答:
Quick and dirty solution:

```<code>WebDriverWait wait = new WebDriverWait(driver, 15, 100);

driver.get("http://billing.scriptinglogic.net/index.php/sessions/login");
driver.findElement(By.id("email")).sendKeys("<EMAIL>");
driver.findElement(By.id("password")).sendKeys("<PASSWORD>");
driver.findElement(By.name("btn_login")).click();

wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[text()='Quotes']"))).click();
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".create-quote"))).click();
wait.until(ExpectedConditions.elementToBeClickable(By.id("quote_password"))).sendKeys("password");
</code>```

Updated based on the credentials supplied in the comment below.  I've tweaked the selectors to use ID, name and class where applicable.  There is no need to use complex XPath locators when they aren't needed.

The explicit waits are required based on the way the site is working and I've added JeffC's suggestion of using an elementToBeClickable expected condition for the input element (I don't think it's really required in this instance though since the site doesn't seem to ever disable the input field, so a visibilityOfElementLocated expected condition is just as good really).

This solution is working for me in Chrome and Firefox in standard mode and Firefox in headless mode.  It's not working in headless mode in Chrome because the screen size is smaller and when the screen width goes below 1000px the header changes and the text "Quotes" is never displayed.  Below 767px the header is completely removed and you get a side menu.  This means that the flow of the script needs to change slightly based on resolution.

I would suggest asking your developer to add an ID to the menu items, it will make it easier to locate them and use the site in its various states.  The quick and dirty solution to this problem is ensure the browser is a certain size while the test runs, you can do this by setting the size in the first line of your script:

```<code>driver.manage().window().setSize(new Dimension(1024, 768));
</code>```

When you do this it passes in Firefox and Chrome in standard and headless mode.

Note: The lines with an explicit wait that result in an element being clicked are anchor elements so there is no point waiting for the element to be clickable as the condition is always going to return true.

Body:
Below is my code, the line =>
driver.findElement(By.xpath("//*[@id=\"quote_password\"]")).sendKeys("password"); throws exception that element is not found

@Test
public void mytest()
{
    System.setProperty("webdriver.chrome.driver","Drivers/chromedriver.exe");
    WebDriver driver = new ChromeDriver();
    driver.manage().window().maximize();
    driver.get("http://billing.scriptinglogic.net/index.php/sessions/login");
    driver.findElement(By.xpath("//*[@id='email']")).sendKeys("email");
    driver.findElement(By.xpath("//*[@id='password']")).sendKeys("password");
    driver.findElement(By.xpath("/html/body/div/div/form/input")).click();
    driver.findElement(By.xpath("//*[text()='Quotes']")).click();
    driver.findElement(By.xpath("//*[text()='Create Quote']")).click();
    driver.findElement(By.xpath("//*[@id=\"quote_password\"]")).sendKeys("password");

}

Body:
Quick and dirty solution:

WebDriverWait wait = new WebDriverWait(driver, 15, 100);

driver.get("http://billing.scriptinglogic.net/index.php/sessions/login");
driver.findElement(By.id("email")).sendKeys("<EMAIL>");
driver.findElement(By.id("password")).sendKeys("<PASSWORD>");
driver.findElement(By.name("btn_login")).click();

wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[text()='Quotes']"))).click();
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".create-quote"))).click();
wait.until(ExpectedConditions.elementToBeClickable(By.id("quote_password"))).sendKeys("password");

Updated based on the credentials supplied in the comment below.  I've tweaked the selectors to use ID, name and class where applicable.  There is no need to use complex XPath locators when they aren't needed.

The explicit waits are required based on the way the site is working and I've added JeffC's suggestion of using an elementToBeClickable expected condition for the input element (I don't think it's really required in this instance though since the site doesn't seem to ever disable the input field, so a visibilityOfElementLocated expected condition is just as good really).

This solution is working for me in Chrome and Firefox in standard mode and Firefox in headless mode.  It's not working in headless mode in Chrome because the screen size is smaller and when the screen width goes below 1000px the header changes and the text "Quotes" is never displayed.  Below 767px the header is completely removed and you get a side menu.  This means that the flow of the script needs to change slightly based on resolution.

I would suggest asking your developer to add an ID to the menu items, it will make it easier to locate them and use the site in its various states.  The quick and dirty solution to this problem is ensure the browser is a certain size while the test runs, you can do this by setting the size in the first line of your script:

driver.manage().window().setSize(new Dimension(1024, 768));

When you do this it passes in Firefox and Chrome in standard and headless mode.

Note: The lines with an explicit wait that result in an element being clicked are anchor elements so there is no point waiting for the element to be clickable as the condition is always going to return true.


问:
vertical centering of list items
I have read many articles about vertical centering but I’m afraid not many of them are intuitive, hence unable to apply it to my problem. Basically, I have a main div and in there, I’ve got unordered list which has an image and paragraph tag within it and are displayed using inline-block. This aspect of the work is fine.

The problem or what I am trying to achieve is to have the list centered in the middle of the screen. So for instance, if I have got just one item in the list, it should be in the middle and then move upwards as more items are entered in the list.

```<code><div id = "main">
    <ul>
        <li>
            <img src="test.jpg" alt="#" />
            <p>Lorem ipsum</p>
        </li>
    </ul>
</div>

#main {
    margin: 60px auto;
    height: 400px;
}
#main ul li {
    display: inline-block;
    vertical-align: top;
    margin: 0 13px 72px 22px;
    height: 100px;
}

#main ul {
    text-align: center;
}
</code>```

答:
Here's an example using the flexible box model in css3: http://jsfiddle.net/zgzct/1/

The spec for the flexbox just changed quite a bit and browser support isn't consistent so go with Diodeus' solution if it works for you.

ContentLicense: CC BY-SA 3.0

Title: vertical centering of list items

Body:
I have read many articles about vertical centering but I’m afraid not many of them are intuitive, hence unable to apply it to my problem. Basically, I have a main div and in there, I’ve got unordered list which has an image and paragraph tag within it and are displayed using inline-block. This aspect of the work is fine.

The problem or what I am trying to achieve is to have the list centered in the middle of the screen. So for instance, if I have got just one item in the list, it should be in the middle and then move upwards as more items are entered in the list.

Lorem ipsum

#main {
    margin: 60px auto;
    height: 400px;
}
#main ul li {
    display: inline-block;
    vertical-align: top;
    margin: 0 13px 72px 22px;
    height: 100px;
}

#main ul {
    text-align: center;
}


问:
String is immutable?
Just have a problem with this, how do we rewrite the above code so that only a single String object is created?

String is immutable, isnt studentDetails already one single String object

```<code>public void displayString(Student[] students)
{
   String studentDetails = "";
   for (Student stu : students)
   {
       studentDetails += stu.getFirstName();
       studentDetails += " ";
       studentDetails += stu.getLastName();
       studentDetails += " ";
       studentDetails += stu.getAge();
       studentDetails += "\n";
   }
   System.out.println("Student Details are: ");
   System.out.println(studentDetails);
}
</code>```

答:
Yes, String object is immutable, that is why one need to work with StringBuilder or StringBuffer. Below are steps shown to work with StringBuilder

Create variable of type StringBuilder

Use append() method to concnat String

Call toString() to convert it into String

Title: String is immutable?

Body:
Just have a problem with this, how do we rewrite the above code so that only a single String object is created?

String is immutable, isnt studentDetails already one single String object

public void displayString(Student[] students)
{
   String studentDetails = "";
   for (Student stu : students)
   {
       studentDetails += stu.getFirstName();
       studentDetails += " ";
       studentDetails += stu.getLastName();
       studentDetails += " ";
       studentDetails += stu.getAge();
       studentDetails += "\n";
   }
   System.out.println("Student Details are: ");
   System.out.println(studentDetails);
}


问:
TabbedForm - displaying toolbar (submit button) conditionally on FormTab
is there a way to remove submit button (toolbar) conditionally in specific Tabs, when using TabbedForm? (react-admin)

答:
Here is how I did it using a custom toolbar:

<TabbedForm toolbar={<PostEditToolbar {...props} />}>...
```

<p>The toolbar looks like this:</p>

<pre class="lang-js prettyprint-override"><code>const PostEditToolbar = props => {
  const { hasList, hasEdit, hasShow, hasCreate, redirect, ...rest } = props
  return (
    <Toolbar {...props}>
      <Route exact path={'/Posts/:id/:tab_index'} render={props => ''} />
      <Route
        exact
        path={'/Posts/:id'}
        render={props => (
          <SaveButton redirect={`/Posts/${rest.id}`} {...rest} />
        )}
      />
    </Toolbar>
  )
}
</code>```

You will need to import { Route } from 'react-router-dom' for this and also adjust the route paths as needed.

Body:
Here is how I did it using a custom toolbar:

<TabbedForm toolbar={<PostEditToolbar {...props} />}>...

The toolbar looks like this:

const PostEditToolbar = props => {
  const { hasList, hasEdit, hasShow, hasCreate, redirect, ...rest } = props
  return (
    <Toolbar {...props}>
      <Route exact path={'/Posts/:id/:tab_index'} render={props => ''} />
      <Route
        exact
        path={'/Posts/:id'}
        render={props => (
          <SaveButton redirect={`/Posts/${rest.id}`} {...rest} />
        )}
      />
    </Toolbar>
  )
}

You will need to import { Route } from 'react-router-dom' for this and also adjust the route paths as needed.


问:
How to implement an interface member correctly?
I am coding a simple application that works with collections. How do I properly implement an interface method in the case below? Currently, it shows an error "not all code paths return a value".

This is my home task. The class "Time" is already implemented and works properly. I tried to find any examples of successful implementation of this method on the Internet but failed.

```<code>class MyCollection : ICollection<Time>
    {
        List<Time> arr = new List<Time>();

        int ICollection<Time>.Count
        {

            get
            {
                arr.Count();
            }
        }
     }
</code>```

I am getting an error:

CS0161 "MyCollection.ICollection.Count.get': not all code paths
  return a value"

答:
You are missing a return statement on your getter .

```<code>class MyCollection : ICollection<Time>
{
    List<Time> arr = new List<Time>();

    int ICollection<Time>.Count
    {

        get
        {
            return arr.Count();
        }
    }
 }
</code>```

Body:
I am coding a simple application that works with collections. How do I properly implement an interface method in the case below? Currently, it shows an error "not all code paths return a value".

This is my home task. The class "Time" is already implemented and works properly. I tried to find any examples of successful implementation of this method on the Internet but failed.

class MyCollection : ICollection<Time>
    {
        List<Time> arr = new List<Time>();

        int ICollection<Time>.Count
        {

            get
            {
                arr.Count();
            }
        }
     }

I am getting an error:

CS0161 "MyCollection.ICollection.Count.get': not all code paths
  return a value"

Body:
You are missing a return statement on your getter .

class MyCollection : ICollection<Time>
{
    List<Time> arr = new List<Time>();

    int ICollection<Time>.Count
    {

        get
        {
            return arr.Count();
        }
    }
 }


问:
How to find start(min) and end(max) date in xml file?
I have an XML file. I should find for same field2 start(min) date and End(max) date from field3. Maybe xsl have some function to find it.Because I try do it trying to find min month and min day and max month, max day.
XML:

```<code><document>
    <line id="0">
        <field id="2">X111</field>
        <field id="3">2011-03-31</field>
    </line>
    <line id="1">
        <field id="2">X111</field>
        <field id="3">2011-04-04</field>
    </line>
    <line id="2">
        <field id="2">X111</field>
        <field id="3">2011-04-02</field>
    </line>
    <line id="3">
        <field id="2">X222</field>
        <field id="3">2011-04-04</field>
    </line>
    <line id="4">
        <field id="2">X222</field>
        <field id="3">2011-04-01</field>
    </line>
    <line id="4">
        <field id="2">X333</field>
        <field id="3">2011-04-01</field>
    </line>
</document>
</code>```

Output:

```<code><document>
<Message>
    <ID>X111</ID>
    <dateStart>2011-03-31</dateStart>
    <dateEnd>2011-04-04</dateEnd>
</Message>
<Message>
    <ID>X222</ID>
    <dateStart>2011-04-01</dateStart>
    <dateEnd>2011-04-04</dateEnd>
</Message>
<Message>
    <ID>X333</ID>
    <dateStart>2011-04-01</dateStart>
    <dateEnd>2011-04-01</dateEnd>
</Message>
</document>
</code>```

Please help to solve it. I'm working with stylesheet version="1.0".

答:
This can probably be optimized but it returns the requested results:</p>

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
    <xsl:key name="test" match="line" use="field[@id=2]"/>
    <xsl:template match="/">
        <document>
            <xsl:for-each select="//line[generate-id()=generate-id(key('test',field[@id=2]))]">
                <xsl:sort select="field[@id=2]"/>
                <Message>
                    <ID>
                        <xsl:value-of select="field[@id=2]"/>
                    </ID>
                    <xsl:apply-templates select="key('test',field[@id=2])">
                        <xsl:sort select="field[@id=3]"/>
                    </xsl:apply-templates>
                </Message>
            </xsl:for-each>
        </document>
    </xsl:template>
    <xsl:template match="line">
        <xsl:if test="position()=1">
            <dateStart>
                <xsl:value-of select="field[@id=3]"/>
            </dateStart>
        </xsl:if>
        <xsl:if test="position()=last()">
            <dateEnd>
                <xsl:value-of select="field[@id=3]"/>
            </dateEnd>
        </xsl:if>
    </xsl:template>
</xsl:stylesheet>
</code>```

Body:
I have an XML file. I should find for same field2 start(min) date and End(max) date from field3. Maybe xsl have some function to find it.Because I try do it trying to find min month and min day and max month, max day.
XML:

<document>
    <line id="0">
        <field id="2">X111</field>
        <field id="3">2011-03-31</field>
    </line>
    <line id="1">
        <field id="2">X111</field>
        <field id="3">2011-04-04</field>
    </line>
    <line id="2">
        <field id="2">X111</field>
        <field id="3">2011-04-02</field>
    </line>
    <line id="3">
        <field id="2">X222</field>
        <field id="3">2011-04-04</field>
    </line>
    <line id="4">
        <field id="2">X222</field>
        <field id="3">2011-04-01</field>
    </line>
    <line id="4">
        <field id="2">X333</field>
        <field id="3">2011-04-01</field>
    </line>
</document>

Output:

<document>
<Message>
    <ID>X111</ID>
    <dateStart>2011-03-31</dateStart>
    <dateEnd>2011-04-04</dateEnd>
</Message>
<Message>
    <ID>X222</ID>
    <dateStart>2011-04-01</dateStart>
    <dateEnd>2011-04-04</dateEnd>
</Message>
<Message>
    <ID>X333</ID>
    <dateStart>2011-04-01</dateStart>
    <dateEnd>2011-04-01</dateEnd>
</Message>
</document>

Please help to solve it. I'm working with stylesheet version="1.0".

Body:
This can probably be optimized but it returns the requested results:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
    <xsl:key name="test" match="line" use="field[@id=2]"/>
    <xsl:template match="/">
        <document>
            <xsl:for-each select="//line[generate-id()=generate-id(key('test',field[@id=2]))]">
                <xsl:sort select="field[@id=2]"/>
                <Message>
                    <ID>
                        <xsl:value-of select="field[@id=2]"/>
                    </ID>
                    <xsl:apply-templates select="key('test',field[@id=2])">
                        <xsl:sort select="field[@id=3]"/>
                    </xsl:apply-templates>
                </Message>
            </xsl:for-each>
        </document>
    </xsl:template>
    <xsl:template match="line">
        <xsl:if test="position()=1">
            <dateStart>
                <xsl:value-of select="field[@id=3]"/>
            </dateStart>
        </xsl:if>
        <xsl:if test="position()=last()">
            <dateEnd>
                <xsl:value-of select="field[@id=3]"/>
            </dateEnd>
        </xsl:if>
    </xsl:template>
</xsl:stylesheet>


问:
Testing localStorage using mocks or spies in Angular 7 Applications using latest jest setup
I am trying to unit test my Angular 7 application using jest and want to test if a method is called by setting localStorage. But I understand that setting the real localStorage is not ideal when testing, hence have to use mocks or spies. Since I'm new to unit-testing, I would like to know if there is a better method to test this and if my approach is correct.

I'm mainly asking this again here is because of this issue. It says jest now provides localStorage support out of the box. So, in the following methodology, is the localStorage mocked automatically or is my approach wrong?

login.component.spec.ts

    test('Call onSubmit() when localStorage is set', () => {
        const mockSubmit = jest.spyOn(component, 'onSubmit');
        localStorage.setItem('auth', 'abcd');
        component.ngOnInit();

        expect(mockSubmit).toBeCalled();
    });
```

<hr>

<h3>login.component.ts</h3>

<pre class="lang-js prettyprint-override"><code>    ngOnInit(): void {
        if (localStorage.getItem('auth') !== null) {

            this.onSubmit();
        }
    }
</code>```

Mocking and Spying in jest is a bit confusing for me, so any advice or help is appreciated.

答: It's a bad practice to work with localStorage in your components, better move it logic to separate service (for example: AuthService ), and after that in your tests you can spyOn service methods and check that they toHaveBeenCalled

Body:
I am trying to unit test my Angular 7 application using jest and want to test if a method is called by setting localStorage. But I understand that setting the real localStorage is not ideal when testing, hence have to use mocks or spies. Since I'm new to unit-testing, I would like to know if there is a better method to test this and if my approach is correct.

I'm mainly asking this again here is because of this issue. It says jest now provides localStorage support out of the box. So, in the following methodology, is the localStorage mocked automatically or is my approach wrong?

login.component.spec.ts

    test('Call onSubmit() when localStorage is set', () => {
        const mockSubmit = jest.spyOn(component, 'onSubmit');
        localStorage.setItem('auth', 'abcd');
        component.ngOnInit();

        expect(mockSubmit).toBeCalled();
    });

login.component.ts

    ngOnInit(): void {
        if (localStorage.getItem('auth') !== null) {

            this.onSubmit();
        }
    }

Mocking and Spying in jest is a bit confusing for me, so any advice or help is appreciated.


答:
yes, strings are immutable, just use a StringBuilder, or a stringBuffer if thread safe is required....</p>

```<code>   StringBuilder studentDetails = "";
   for (Student stu : students)
   {
       studentDetails.append(stu.getFirstName());
       studentDetails.append(" ");
       studentDetails.append(stu.getLastName());
       studentDetails.append(" ");
       studentDetails.append(stu.getAge());
       studentDetails.append("\n");
   }
</code>```

Title: String is immutable?

Body:
yes, strings are immutable, just use a StringBuilder, or a stringBuffer if thread safe is required....

   StringBuilder studentDetails = "";
   for (Student stu : students)
   {
       studentDetails.append(stu.getFirstName());
       studentDetails.append(" ");
       studentDetails.append(stu.getLastName());
       studentDetails.append(" ");
       studentDetails.append(stu.getAge());
       studentDetails.append("\n");
   }


问:
Different colors for text on same label using string format
I have a xaml code as below:

```<code> <Label Text="{Binding Id,StringFormat='{0} *'}" HorizontalOptions="StartAndExpand" HorizontalTextAlignment="Center">
</code>```

here,is this possible to get Id is in one color and * is in another color?

答:
In Xamarin.IOS
Use Like this,

```<code>var attributedText = new NSMutableAttributedString("Complete it in " + HowManySecondsString + " to reach");
var range = attributedText.MutableString.LocalizedStandardRangeOfString(new NSString(HowManySecondsString));
attributedText.AddAttribute(UIStringAttributeKey.ForegroundColor, UIColor.Red, range);
label.AttributedText = attributedText;
</code>```

Body:
I have a xaml code as below:

here,is this possible to get Id is in one color and * is in another color?

Body:
In Xamarin.IOS
Use Like this,

var attributedText = new NSMutableAttributedString("Complete it in " + HowManySecondsString + " to reach");
var range = attributedText.MutableString.LocalizedStandardRangeOfString(new NSString(HowManySecondsString));
attributedText.AddAttribute(UIStringAttributeKey.ForegroundColor, UIColor.Red, range);
label.AttributedText = attributedText;


问:
How to change Text color based on background Image - Flutter
I want to change text (and Icon) colors based on the background image for visibility.

I've tried:
Using palette_generator package, to check the Dominant Color of the background Image and useWhiteForgroundForColor  function (returns a bool) from flutter_statusbarcolor package to select black or white color for the my text (and Icon) colors.

The Problem: Sometimes dominant color turns out null. In my tests, this happens with black and white colors and I don't know of any ways to find out which one.

```<code>Future<bool> useWhiteTextColor(String imageUrl) async {
  PaletteGenerator paletteGenerator =
      await PaletteGenerator.fromImageProvider(
    NetworkImage(imageUrl),

    // Images are square
    size: Size(300, 300),

    // I want the dominant color of the top left section of the image
    region: Offset.zero & Size(40, 40),
  );

  Color dominantColor = paletteGenerator.dominantColor?.color;

  // Here's the problem
  // Sometimes dominantColor returns null
  // With black and white background colors in my tests
  if (dominantColor == null) print('Dominant Color null');

  return useWhiteForeground(dominantColor);
}
</code>```

I found other methods for other languages, but I don't know a way to implement the same method in dart.

Additional note:
My actual code includes some additional complications. I am using a SliverAppBar and here I want to determine the title and icons colors for when the flexibleSpace is expanded. I change their colors when collapsed with the help of the community based on this.

答:
i use the below method to find out which one to be used (either black or white).    </p>

```<code>Color getTextColor(Color color) {
int d = 0;

// Counting the perceptive luminance - human eye favors green color...
double luminance =
    (0.299 * color.red + 0.587 * color.green + 0.114 * color.blue) / 255;

if (luminance > 0.5)
  d = 0; // bright colors - black font
else
  d = 255; // dark colors - white font

return Color.fromARGB(color.alpha, d, d, d);   }
</code>```

Body:
I want to change text (and Icon) colors based on the background image for visibility.

I've tried:
Using palette_generator package, to check the Dominant Color of the background Image and useWhiteForgroundForColor  function (returns a bool) from flutter_statusbarcolor package to select black or white color for the my text (and Icon) colors.

The Problem: Sometimes dominant color turns out null. In my tests, this happens with black and white colors and I don't know of any ways to find out which one.

Future<bool> useWhiteTextColor(String imageUrl) async {
  PaletteGenerator paletteGenerator =
      await PaletteGenerator.fromImageProvider(
    NetworkImage(imageUrl),

    // Images are square
    size: Size(300, 300),

    // I want the dominant color of the top left section of the image
    region: Offset.zero & Size(40, 40),
  );

  Color dominantColor = paletteGenerator.dominantColor?.color;

  // Here's the problem
  // Sometimes dominantColor returns null
  // With black and white background colors in my tests
  if (dominantColor == null) print('Dominant Color null');

  return useWhiteForeground(dominantColor);
}

I found other methods for other languages, but I don't know a way to implement the same method in dart.

Additional note:
My actual code includes some additional complications. I am using a SliverAppBar and here I want to determine the title and icons colors for when the flexibleSpace is expanded. I change their colors when collapsed with the help of the community based on this.

Body:
i use the below method to find out which one to be used (either black or white).

Color getTextColor(Color color) {
int d = 0;

// Counting the perceptive luminance - human eye favors green color...
double luminance =
    (0.299 * color.red + 0.587 * color.green + 0.114 * color.blue) / 255;

if (luminance > 0.5)
  d = 0; // bright colors - black font
else
  d = 255; // dark colors - white font

return Color.fromARGB(color.alpha, d, d, d);   }


问:
Multiple application authentication using one login
I have an application running on asp.net with Identity for user management.

Now I am in production of another application having technologies asp.net core and Angular 7.

I have tried using same DB for both application for login but it didn't worked since Identity on .net and .net core have different Hashing algorithms.

can I use my .net app verification same for .net core and angular 7 app by just giving any Button link from the first application?

When I proceed like above i found some problems listing below:-

How to avoid user directly accessing the second application .net core ?

How can i proceed with this scenario?

Any help will be appreciated.

答:
Since ASP.NET Core Identity uses a more secure hashing mechanism for the passwords, by default you cannot use an older ASP.NET Identity to access the same database since it doesn’t understand the new mechanism. What works out of the box however is to use ASP.NET Core Identity with old hashes since the hash is actually versioned to allow easy migration from an older database.

If you want ASP.NET Core Identity and ASP.NET Identity to co-exist using the same database, you will have to use the older hashing algorithm since that is the only one ASP.NET Identity supports. Luckily, you can configure ASP.NET Core Identity to only use that algorithm itself.

The configuration is explained in the documentation and looks like this:

```<code>services.Configure<PasswordHasherOptions>(option =>
{
    option.CompatibilityMode = PasswordHasherCompatibilityMode.IdentityV2;
});
</code>```

This will effectively downgrade ASP.NET Core Identity to use the older algorithm, allowing full compatibility with ASP.NET Identity.

Body:
Since ASP.NET Core Identity uses a more secure hashing mechanism for the passwords, by default you cannot use an older ASP.NET Identity to access the same database since it doesn’t understand the new mechanism. What works out of the box however is to use ASP.NET Core Identity with old hashes since the hash is actually versioned to allow easy migration from an older database.

If you want ASP.NET Core Identity and ASP.NET Identity to co-exist using the same database, you will have to use the older hashing algorithm since that is the only one ASP.NET Identity supports. Luckily, you can configure ASP.NET Core Identity to only use that algorithm itself.

The configuration is explained in the documentation and looks like this:

services.Configure<PasswordHasherOptions>(option =>
{
    option.CompatibilityMode = PasswordHasherCompatibilityMode.IdentityV2;
});

This will effectively downgrade ASP.NET Core Identity to use the older algorithm, allowing full compatibility with ASP.NET Identity.


问:
Regarding (count down) timer for application in asp.net c#
Hi
I have created online quiz. I have added Count-down timer,label for question & radiobuttonlist for answers and next button for next question. I have code for timer but this timer gets start again when i click next button as i want count down timer for whole questions(Quiz).
Count down timer code(Javascript) is as follows:</p>

```<code>var hour=0;  //specify hours for counter
var min= '<%= Session["timer"] %>';      // specify minutes

var second = '<%= Session["second"] %>';    // specify the seconds
var lab = 'cd';  // id of the entry on the page where the counter(for question) is to be inserted & cd is span id in aspx page where i am displaying countdown timer

function start()
{
    displayCountdown(setCountdown(hour,min,second),lab);
}
loaded(lab,start);
var pageLoaded = 0;
window.onload = function() {pageLoaded = 1;}
function loaded(i,f)
{
    if (document.getElementById && document.getElementById(i) != null)
        f();
    else if (!pageLoaded)
        setTimeout('loaded(\''+i+'\','+f+')',100);
}
function setCountdown(hour,min,second)
{
    if(hour>0)
    min=min*hour*60;
    c = setC(min,second);
return c;
}
function setC(min,second)
{
if(min>0)
second=min*60*second;
return Math.floor(second);
}
function displayCountdown(countdn,cd)
{
    if (countdn < 0)
    {
        document.getElementById(cd).innerHTML = "Sorry, you are too late.";
        __doPostBack('__Page');
    }
    else
    {
        var secs = countdn % 60;
        if (secs < 10)
            secs = '0'+secs;
        var countdn1 = (countdn - secs) / 60;
        var mins = countdn1 % 60;
        if (mins < 10)
            mins = '0'+mins;
        countdn1 = (countdn1 - mins) / 60;
        var hours = countdn1 % 24;
        document.getElementById(cd).innerHTML = hours+' : '+mins+' : '+secs;
        setTimeout('displayCountdown('+(countdn-1)+',\''+cd+'\');',999);
    }
}
</code>```

答:
You must keep a reference on "present" time relatively of the "start" time and the duration of the quiz.  So, you would substract "present" time from start time.

```<code>    protected int HoursDuration {
        get {
            if (Session["HoursDuration"] == null) { Session["HoursDuration"] = 0; }
            return Convert.ToInt32(Session["HoursDuration"]);
        }
        set { Session["HoursDuration"] = value; }
    }

    protected int MinutesDuration {
        get {
            if (Session["MinutesDuration"] == null) { Session["MinutesDuration"] = 0; }
            return Convert.ToInt32(Session["MinutesDuration"]);
        }
        set { Session["MinutesDuration"] = value; }
    }

    protected int SecondsDuration {
        get {
            if (Session["SecondsDuration"] == null) { Session["SecondsDuration"] = 0; }
            return Convert.ToInt32(Session["SecondsDuration"]);
        }
        set { Session["SecondsDuration"] = value; }
    }

    protected int HoursLeft {
        get {
            return (this.EndTime - this.BeginTime).Hours;
        }
    }

    protected int MinutesLeft {
        get {
            return (this.EndTime - this.BeginTime).Minutes;
        }
    }

    protected int SecondsLeft {
        get {
            return (this.EndTime - this.BeginTime).Seconds;
        }
    }

    protected DateTime EndTime {
        get {
            if (Session["EndTime"] == null) { Session["EndTime"] = DateTime.Now; }
            return Convert.ToDateTime(Session["EndTime"]);
        }
        set { ViewState["EndTime"] = value; }
    }

    protected DateTime BeginTime {
        get {
            if (Session["BeginTime"] == null) { Session["BeginTime"] = DateTime.Now; }
            return Convert.ToDateTime(Session["BeginTime"]);
        }
        set { ViewState["BeginTime"] = value; }
    }

    protected override void OnInit(EventArgs e) {
        this.BeginTime = DateTime.Now; // Present time
        if (!IsPostBack) {
            // The countdown
            this.HoursDuration = 0;
            this.MinutesDuration = 10;
            this.SecondsDuration = 0;
            // Only on !postback, you set up when it ends
            this.EndTime = this.BeginTime.AddHours(this.HoursDuration)
                                       .AddMinutes(this.MinutesDuration)
                                       .AddSeconds(this.SecondsDuration);
        }
        base.OnInit(e);
    }
</code>```

Then, in you javascript, call the HoursLeft, MinutesLeft and secondeLeft. I think this should work.

Body:
Hi
I have created online quiz. I have added Count-down timer,label for question & radiobuttonlist for answers and next button for next question. I have code for timer but this timer gets start again when i click next button as i want count down timer for whole questions(Quiz).
Count down timer code(Javascript) is as follows:

var hour=0;  //specify hours for counter
var min= '<%= Session["timer"] %>';      // specify minutes

var second = '<%= Session["second"] %>';    // specify the seconds
var lab = 'cd';  // id of the entry on the page where the counter(for question) is to be inserted & cd is span id in aspx page where i am displaying countdown timer

function start()
{
    displayCountdown(setCountdown(hour,min,second),lab);
}
loaded(lab,start);
var pageLoaded = 0;
window.onload = function() {pageLoaded = 1;}
function loaded(i,f)
{
    if (document.getElementById && document.getElementById(i) != null)
        f();
    else if (!pageLoaded)
        setTimeout('loaded(\''+i+'\','+f+')',100);
}
function setCountdown(hour,min,second)
{
    if(hour>0)
    min=min*hour*60;
    c = setC(min,second);
return c;
}
function setC(min,second)
{
if(min>0)
second=min*60*second;
return Math.floor(second);
}
function displayCountdown(countdn,cd)
{
    if (countdn < 0)
    {
        document.getElementById(cd).innerHTML = "Sorry, you are too late.";
        __doPostBack('__Page');
    }
    else
    {
        var secs = countdn % 60;
        if (secs < 10)
            secs = '0'+secs;
        var countdn1 = (countdn - secs) / 60;
        var mins = countdn1 % 60;
        if (mins < 10)
            mins = '0'+mins;
        countdn1 = (countdn1 - mins) / 60;
        var hours = countdn1 % 24;
        document.getElementById(cd).innerHTML = hours+' : '+mins+' : '+secs;
        setTimeout('displayCountdown('+(countdn-1)+',\''+cd+'\');',999);
    }
}

Body:
You must keep a reference on "present" time relatively of the "start" time and the duration of the quiz.  So, you would substract "present" time from start time.

    protected int HoursDuration {
        get {
            if (Session["HoursDuration"] == null) { Session["HoursDuration"] = 0; }
            return Convert.ToInt32(Session["HoursDuration"]);
        }
        set { Session["HoursDuration"] = value; }
    }

    protected int MinutesDuration {
        get {
            if (Session["MinutesDuration"] == null) { Session["MinutesDuration"] = 0; }
            return Convert.ToInt32(Session["MinutesDuration"]);
        }
        set { Session["MinutesDuration"] = value; }
    }

    protected int SecondsDuration {
        get {
            if (Session["SecondsDuration"] == null) { Session["SecondsDuration"] = 0; }
            return Convert.ToInt32(Session["SecondsDuration"]);
        }
        set { Session["SecondsDuration"] = value; }
    }

    protected int HoursLeft {
        get {
            return (this.EndTime - this.BeginTime).Hours;
        }
    }

    protected int MinutesLeft {
        get {
            return (this.EndTime - this.BeginTime).Minutes;
        }
    }

    protected int SecondsLeft {
        get {
            return (this.EndTime - this.BeginTime).Seconds;
        }
    }

    protected DateTime EndTime {
        get {
            if (Session["EndTime"] == null) { Session["EndTime"] = DateTime.Now; }
            return Convert.ToDateTime(Session["EndTime"]);
        }
        set { ViewState["EndTime"] = value; }
    }

    protected DateTime BeginTime {
        get {
            if (Session["BeginTime"] == null) { Session["BeginTime"] = DateTime.Now; }
            return Convert.ToDateTime(Session["BeginTime"]);
        }
        set { ViewState["BeginTime"] = value; }
    }

    protected override void OnInit(EventArgs e) {
        this.BeginTime = DateTime.Now; // Present time
        if (!IsPostBack) {
            // The countdown
            this.HoursDuration = 0;
            this.MinutesDuration = 10;
            this.SecondsDuration = 0;
            // Only on !postback, you set up when it ends
            this.EndTime = this.BeginTime.AddHours(this.HoursDuration)
                                       .AddMinutes(this.MinutesDuration)
                                       .AddSeconds(this.SecondsDuration);
        }
        base.OnInit(e);
    }

Then, in you javascript, call the HoursLeft, MinutesLeft and secondeLeft. I think this should work.


问:
Empty Constructors in C++:
In my code I am doing the following, but I am not sure if I am "allowed" to or if it is a good designing technique. I need to create an empty constructor, but I also need a constructor that initializes the variables given the parameters. So I am doing the following:

This is the C.h file.

```<code> class C
 {
   private:
    string A;
    double B;
   public:
   //empty constructor
   C();
   C(string, double);
 }
</code>```

And my C.cpp file:

```<code>//this is how I declare the empty constructor
 C::C()
  {

  }

  C::C(string a, double b)
  {
         A = a;
         B = b;
  }
</code>```

Is the way I am declaring the empty constructor right or do I need to set A= NULL and B=0.0?

答:
In C++11 and later you can use the following to generate a default no-param constructor:

```<code>C() = default;
</code>```

This is neater than C(){}.

This doesn't initialize members. In C++11 you can initialize members in the same line of declaration:

```<code>int m_member = 0; // this is a class member
</code>```

Those 2 features avoids having to create your own no param constructor to default initialize members. So your class can look like this when applying those 2 features:

```<code>class C
{
private:
    string A;
    double B = 0;

public:
   C() = default;
   C(string, double);
}
</code>```

Title: Empty Constructors in C++:

Body:
In my code I am doing the following, but I am not sure if I am "allowed" to or if it is a good designing technique. I need to create an empty constructor, but I also need a constructor that initializes the variables given the parameters. So I am doing the following:

This is the C.h file.

 class C
 {
   private:
    string A;
    double B;
   public:
   //empty constructor
   C();
   C(string, double);
 }

And my C.cpp file:

//this is how I declare the empty constructor
 C::C()
  {

  }

  C::C(string a, double b)
  {
         A = a;
         B = b;
  }

Is the way I am declaring the empty constructor right or do I need to set A= NULL and B=0.0?

Body:
In C++11 and later you can use the following to generate a default no-param constructor:

C() = default;

This is neater than C(){}.

This doesn't initialize members. In C++11 you can initialize members in the same line of declaration:

int m_member = 0; // this is a class member

Those 2 features avoids having to create your own no param constructor to default initialize members. So your class can look like this when applying those 2 features:

class C
{
private:
    string A;
    double B = 0;

public:
   C() = default;
   C(string, double);
}


问:
pick from first occurrences till last values in array column in pyspark df
I have problem in which is have to search for first occurrence of "Employee_ID" in "Mapped_Project_ID", Need to pick the values in the array till last value from the first matching occurrences

I have one dataframe like below :

```<code>Employee_Name|Employee_ID|Mapped_Project_ID
Name1|E101|[E101, E102, E103]
Name2|E102|[E101, E102, E103]
Name3|E103|[E101, E102, E103, E104, E105]
</code>```

I want to have output df like below:

```<code>Employee_Name|Employee_ID|Mapped_Project_ID
Name1|E101|[E101, E102, E103]
Name2|E102|[E102, E103]
Name3|E103|[E103, E104, E105]
</code>```

Not sure, How to achieve this.

Can someone provide an help on this or logic to handle this in spark without need of any UDFs?

答:
Once you have your dataframe you can use spark 2.4's higher order array function (see https://docs.databricks.com/_static/notebooks/apache-spark-2.4-functions.html) to filter out any values within the array that are lower than the value in the Employee_ID column like so:</p>

```<code>myDataframe
  .selectExpr(
    "Employee_Name",
    "Employee_ID",
    "filter(Mapped_Project_ID, x -> x >= Employee_ID) as Mapped_Project_ID"
  );
</code>```

Body:
I have problem in which is have to search for first occurrence of "Employee_ID" in "Mapped_Project_ID", Need to pick the values in the array till last value from the first matching occurrences

I have one dataframe like below :

Employee_Name|Employee_ID|Mapped_Project_ID
Name1|E101|[E101, E102, E103]
Name2|E102|[E101, E102, E103]
Name3|E103|[E101, E102, E103, E104, E105]

I want to have output df like below:

Employee_Name|Employee_ID|Mapped_Project_ID
Name1|E101|[E101, E102, E103]
Name2|E102|[E102, E103]
Name3|E103|[E103, E104, E105]

Not sure, How to achieve this.

Can someone provide an help on this or logic to handle this in spark without need of any UDFs?

Body:
Once you have your dataframe you can use spark 2.4's higher order array function (see https://docs.databricks.com/_static/notebooks/apache-spark-2.4-functions.html) to filter out any values within the array that are lower than the value in the Employee_ID column like so:

myDataframe
  .selectExpr(
    "Employee_Name",
    "Employee_ID",
    "filter(Mapped_Project_ID, x -> x >= Employee_ID) as Mapped_Project_ID"
  );


问:
Merging two multidimensional arrays in Javascript by value
I have two arrays:

```<code>var array1 = [['email1', object1],['email2', object2],['email3', object3],['email4',object4]]
var array2 = [['email1',[['a1','b1']]],['email3',[['a3','b3']]], ['email4',[['a4','b4'],['a4a','b4a']]]
</code>```

I need to merge them by email so the resulting array will look like, without duplicate email:

```<code>var mergedarray =
[['email1', object1, [['a1', 'b1']]],['email2', object2],['email3', object3, ['a3', 'b3']],['email4',object4,[['a4','b4'],['a4a','b4a']]]]
</code>```

My brain hurts looking at those multimultidimensions..Any advice?

答:
Couldn't implement any of the advices (probably because of my low skill), I ended up turning arrays into objects to assign key-value pairs, so new data looked like:

```<code>var array1 = [{email:'email1', obj:object1, data:[]},{email:'email2', obj:object2, data:[]},{email:'email3', obj:object3, data:[]},{email:'email4',obj:object4, data:[]}];
var array2 = [{email:'email1',data:[{'a1','b1'}]},{email:'email3',data:[{'a3','b3'}]}, {email:'email4',data:[{'a4','b4'}]},{email:'email4',data:[{'a4a','b4a'}]}];
</code>```

After that I used a loop to push objects data from one array into another:

```<code> for (var x in array1) {
    var res = array1[x].email;

    for (var z in array2) {
      var cod = array2[z].email;
      var q = 0;
      if (res == cod) {
        array1[x].data.push(array2[z].data[0]);
        q++;
      }

    }
  }
</code>```

And the result is:

```<code>var array1 = [{email:'email1',obj:object1,data:[{'a1','b1'}]},{email:'email2',obj:object2,data:[]},{email:'email3',data:[{'a3','b3'}]},{email:'email4',obj:object4,data:[{'a4','b4'},{'a4a','b4a'}]}];
</code>```

Body:
I have two arrays:

var array1 = [['email1', object1],['email2', object2],['email3', object3],['email4',object4]]
var array2 = [['email1',[['a1','b1']]],['email3',[['a3','b3']]], ['email4',[['a4','b4'],['a4a','b4a']]]

I need to merge them by email so the resulting array will look like, without duplicate email:

var mergedarray =
[['email1', object1, [['a1', 'b1']]],['email2', object2],['email3', object3, ['a3', 'b3']],['email4',object4,[['a4','b4'],['a4a','b4a']]]]

My brain hurts looking at those multimultidimensions..Any advice?

Body:
Couldn't implement any of the advices (probably because of my low skill), I ended up turning arrays into objects to assign key-value pairs, so new data looked like:

var array1 = [{email:'email1', obj:object1, data:[]},{email:'email2', obj:object2, data:[]},{email:'email3', obj:object3, data:[]},{email:'email4',obj:object4, data:[]}];
var array2 = [{email:'email1',data:[{'a1','b1'}]},{email:'email3',data:[{'a3','b3'}]}, {email:'email4',data:[{'a4','b4'}]},{email:'email4',data:[{'a4a','b4a'}]}];

After that I used a loop to push objects data from one array into another:

 for (var x in array1) {
    var res = array1[x].email;

    for (var z in array2) {
      var cod = array2[z].email;
      var q = 0;
      if (res == cod) {
        array1[x].data.push(array2[z].data[0]);
        q++;
      }

    }
  }

And the result is:

var array1 = [{email:'email1',obj:object1,data:[{'a1','b1'}]},{email:'email2',obj:object2,data:[]},{email:'email3',data:[{'a3','b3'}]},{email:'email4',obj:object4,data:[{'a4','b4'},{'a4a','b4a'}]}];


问:
NuxtServerInit not working on Vuex module mode - Nuxt.js
NuxtServerInit is not working on initial page render on nuxt js vuex module mode. But it works on Classic mode. Following code is the flow I used.

My api call

api/CategoryApi.js

```<code>import axios from 'axios';

const HEADERS = {
    Accept: 'application/json'
};

export default {
    getCategory(payload) {
        return axios.get(`${process.env.apiUrl}/category`, {
            payload,
            headers: HEADERS
        });
    }
}
</code>```

store/modules/CategoryStore.js

```<code>import api from '~/api/CategoryApi'

const state = () => ({
    categories: []
});

const getters = {
    allCategories: state => state.categories
};

const actions = {
    async nuxtServerInit({commit}) {
        const payload = {
            per_page: 6,
            page: 1
        };
        const response = await api.getCategory(payload);
        commit('setCategories', response.data.data);
    },
};

const mutations = {
    setCategories: (state, data) => {
        state.categories = data;
    }
};

export default {
    state,
    getters,
    actions,
    mutations
}
</code>```

pages/index.vue

```<code><template>
    <div>
        <v-flex xs6 sm4 md2 class="text-xs-center my-2 pa-2" v-for="category in allCategories" :key="category.id">
            {{ category.name }}
        </v-flex>
    </div>
</template>

<script>
    import { mapGetters } from 'vuex';

    export default {
        layout: 'default',
        computed: {
            ...mapGetters({
                allCategories: 'modules/CategoryStore/allCategories',
            })
        },
    }
</script>
</code>```

Am I doing this wrong? :/ I want to know the right way to implement this.

Edit: How I did with Aldarund answer (This might help someone)

Edited store/modules/CategoryStore.js

```<code>const actions = {
    async fetchCategories({commit}) {
        const payload = {
            per_page: 6,
            page: 1
        };
        const response = await api.getCategory(payload);
        commit('setCategories', response.data.data);
    },
};
</code>```

Added store/index.js

```<code>const actions = {
    async nuxtServerInit({dispatch}) {
        await dispatch('modules/CategoryStore/fetchCategories');
    },
};

export default {
    actions
}
</code>```

答:
try use that code, clear file index.js, and run.. on server console you see message.

```<code>     export const actions = {

  nuxtServerInit ({ dispatch }) {
    console.log("troololollo")
  }
}
</code>```

maybe also can try nuxt.config.js

```<code>module.exports = {
  //mode: 'spa',
  mode: 'universal',
</code>```

Body:
NuxtServerInit is not working on initial page render on nuxt js vuex module mode. But it works on Classic mode. Following code is the flow I used.

My api call

api/CategoryApi.js

import axios from 'axios';

const HEADERS = {
    Accept: 'application/json'
};

export default {
    getCategory(payload) {
        return axios.get(`${process.env.apiUrl}/category`, {
            payload,
            headers: HEADERS
        });
    }
}

store/modules/CategoryStore.js

import api from '~/api/CategoryApi'

const state = () => ({
    categories: []
});

const getters = {
    allCategories: state => state.categories
};

const actions = {
    async nuxtServerInit({commit}) {
        const payload = {
            per_page: 6,
            page: 1
        };
        const response = await api.getCategory(payload);
        commit('setCategories', response.data.data);
    },
};

const mutations = {
    setCategories: (state, data) => {
        state.categories = data;
    }
};

export default {
    state,
    getters,
    actions,
    mutations
}

pages/index.vue

<template>

        <v-flex xs6 sm4 md2 class="text-xs-center my-2 pa-2" v-for="category in allCategories" :key="category.id">
            {{ category.name }}
        </v-flex>

</template>

Am I doing this wrong? :/ I want to know the right way to implement this.

Edit: How I did with Aldarund answer (This might help someone)

Edited store/modules/CategoryStore.js

const actions = {
    async fetchCategories({commit}) {
        const payload = {
            per_page: 6,
            page: 1
        };
        const response = await api.getCategory(payload);
        commit('setCategories', response.data.data);
    },
};

Added store/index.js

const actions = {
    async nuxtServerInit({dispatch}) {
        await dispatch('modules/CategoryStore/fetchCategories');
    },
};

export default {
    actions
}

Body:
try use that code, clear file index.js, and run.. on server console you see message.

     export const actions = {

  nuxtServerInit ({ dispatch }) {
    console.log("troololollo")
  }
}

maybe also can try nuxt.config.js

module.exports = {
  //mode: 'spa',
  mode: 'universal',


问:
How to assign a return value from a SQL Server Function to a Variable
I have function that returns a Date value. I need to assign that return value to a declared variable.

```<code>Declare @Duedate Date
Set @Duedate = SELECT dbo.TATDueDateCaluator('2019-05-10',2)
Select @Duedate
</code>```

Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword 'SELECT'.

答:
If the function is scalar valued you don't even need a SELECT. Just

```<code>SET @duedate = dbo.tatduedatecaluator('2019-05-10', 2);
</code>```

should do.

Body:
I have function that returns a Date value. I need to assign that return value to a declared variable.

Declare @Duedate Date
Set @Duedate = SELECT dbo.TATDueDateCaluator('2019-05-10',2)
Select @Duedate

Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword 'SELECT'.

Body:
If the function is scalar valued you don't even need a SELECT. Just

SET @duedate = dbo.tatduedatecaluator('2019-05-10', 2);

should do.


问:
Haskell - error by execution
I try to write a this monad

```<code>data W x = W x [String]

instance Monad W where
return x = W x []
W a h1 >>= f = case f a of
    W b h2 -> W b (h1++h2)
</code>```

But, now when i will use this monad and try to write return or >>= in code I get by compilation the warnings:

No explicit method nor default method for Prelude.return in the instance declaration.
  No explicit method nor default method for Prelude.>>= in the instance declaration.

Does anyone know how to fix this warnings?

thank you very much

答: Assuming that the layout of the code is exactly as displayed in your question, the problem is that your return and >>= definitions are not indented, so they are being defined as new top-level functions unrelated to the Monad class.  Indent them and it should work.

Title: Haskell - error by execution

Body:
I try to write a this monad

data W x = W x [String]

instance Monad W where
return x = W x []
W a h1 >>= f = case f a of
    W b h2 -> W b (h1++h2)

But, now when i will use this monad and try to write return or >>= in code I get by compilation the warnings:

No explicit method nor default method for Prelude.return in the instance declaration.
  No explicit method nor default method for Prelude.>>= in the instance declaration.

Does anyone know how to fix this warnings?

thank you very much


问:
How are rest_framework.serializers and rest_framework.renderers related?
I am currently following the tutorial : https://thinkster.io/tutorials/django-json-api/profiles, where the serializer and Renderer are used.

Serializer : when a user submits information(such as creating an instance) through the API, the serializer,validates it and converts it into something Django can slot into a model instance.Similarly, deserializer converts python data-types into models or querysets(complex data-types)

Renderer classes: allow you to return responses with various media types.When a view is entered REST framework will perform content negotiation on the incoming request, and determine the most appropriate renderer to satisfy the request

I am not able to draw a distinction between the two.Request anyone to clearly outline the distinction between the two if possible with an example.

Any help is much appreciated.

答:
The serializer is concerned with taking the original item - in most cases, the model instance - and converting it into Python primitives: strings, ints etc, contained in a single dictionary.

The renderer is concerned with how that is presented to the user; usually, converting that dictionary to JSON.


问:
Can laravel Route have no URL?
I have more kind of general question about Laravel.
I am new to it.

I've created a form:

```<code>{!! Form::model($tourists, ['action' => 'TouristController@store', 'id' => 'passengers_form', 'class' => 'inline' ] ) !!}

{!! Form::close()!!}
</code>```

It outputted: "Action App\Http\Controllers\TouristController@store not defined."

Though TouristController and method store did existed.
I tried this and that and then discovered that It works when I add this to my web.php file (routes.php in previous versions):

```<code>"Route::post('/addtourist', 'TouristController@store');"
</code>```

Ok, I get it, in order to make method work, I should add it to "web.php" (routes).

But what if i have a method which I want to work without 'url'?

For example, I want to send information from form above (or from any other view) to 'TouristController@store' directly, not using '/addtourist'?

smth like

```<code> Route::justMakeMethodWorkWithoutAnyURL('TouristController@store');
</code>```

Is that possible?

Sorry if my question is confusing itself. I want to deeper understand Laravel.

答:
It's an old question, but I believe this is what you were looking for:

action('TouristController@store');
```

From the documentation:

The action function generates a URL for the given controller action.

Title: Can laravel Route have no URL?

Body:
I have more kind of general question about Laravel.
I am new to it.

I've created a form:

{!! Form::model($tourists, ['action' => 'TouristController@store', 'id' => 'passengers_form', 'class' => 'inline' ] ) !!}

{!! Form::close()!!}

It outputted: "Action App\Http\Controllers\TouristController@store not defined."

Though TouristController and method store did existed.
I tried this and that and then discovered that It works when I add this to my web.php file (routes.php in previous versions):

"Route::post('/addtourist', 'TouristController@store');"

Ok, I get it, in order to make method work, I should add it to "web.php" (routes).

But what if i have a method which I want to work without 'url'?

For example, I want to send information from form above (or from any other view) to 'TouristController@store' directly, not using '/addtourist'?

smth like

 Route::justMakeMethodWorkWithoutAnyURL('TouristController@store');

Is that possible?

Sorry if my question is confusing itself. I want to deeper understand Laravel.

Body:
It's an old question, but I believe this is what you were looking for:

action('TouristController@store');

From the documentation:

The action function generates a URL for the given controller action.


问:
Istio Ingress resulting in "no healthy upstream"
I am using deploying an outward facing service, that is exposed behind a nodeport and then an istio ingress. The deployment is using manual sidecar injection. Once the deployment, nodeport and ingress are running, I can make a request to the istio ingress.

For some unkown reason, the request does not route through to my deployment and instead displays the text "no healthy upstream". Why is this, and what is causing it?

I can see in the http response that the status code is 503 (Service Unavailable) and the server is "envoy". The deployment is functioning as I can map a port forward to it and everything works as expected.

答: I faced the issue, when I my pod was in ContainerCreating state. So, it resulted in 503 error. Also as @pegaldon, explained it can also occur due to incorrect route configuration or there are no gateways created by user.


问:
How do I avoid getting "Missing return statement" when calling a method that throws an exception, from within another method?
I have a method that handles different error codes and always throws unchecked exception. This method is used in many places across the class. When I try to call it inside another method that has not void return type as shown below:

```<code>public Object someMethod() {
   ....
   if(success){
     return result;
   } else {
      callMethodThatAlwaysThrowsUncheckedExceptions();
   }
}
</code>```

java compiler says that the method is missing return statement.

Only two options come to my mind how to solve this problem:

replace method call with its content

add a return statement just after method call that returns an empty object

However I don't really like any of these options: the first one because of code duplication and the second one because of the need to write code that will never be executed.

Is there any other way to solve this problem?

答:
To indicate that you don't expect a line to be reachable (after your call to the throwing method) you can

throw new AssertionError("comment to your co-developers why this never gets reached")

Body:
I have a method that handles different error codes and always throws unchecked exception. This method is used in many places across the class. When I try to call it inside another method that has not void return type as shown below:

public Object someMethod() {
   ....
   if(success){
     return result;
   } else {
      callMethodThatAlwaysThrowsUncheckedExceptions();
   }
}

java compiler says that the method is missing return statement.

Only two options come to my mind how to solve this problem:

replace method call with its content

add a return statement just after method call that returns an empty object

However I don't really like any of these options: the first one because of code duplication and the second one because of the need to write code that will never be executed.

Is there any other way to solve this problem?


问:
Is the order of an unordered_map deterministic?
I'm wondering if there's any guarantee that the order of an unordered_map will always be the same across all CPUs, threads, etc.

I realize there may be no obvious pattern to the particular order itself (hence, 'unordered' map), but if I run my process on another machine, or multiple times in succession, or on different threads, will the order of inserted items always be the same if the hash functions and insertion order remains the same? In other words, if my code doesn't change, will every execution of my process result in the elements of the map being in the same order?

I've run a few tests, and the order of items after insertion seems to be the same each time, but that could merely be a fluke, and I only have this single machine to test on. I need to know whether the order can be influenced by any other factors such as CPU/memory architecture, OS (Windows 8 vs Windows 10), etc.

答:
I got the different output orders when running the following code in different hardware platforms.

#include <iostream>
#include <set>
#include <unordered_set>
#include <vector>
#include <functional>
#include <string>

struct hash_func {
    std::size_t operator()(const std::string &key) const {
        std::size_t hash = 0U;
        const std::size_t mask = 0xF0000000;
        for (std::string::size_type i = 0; i < key.length(); ++i) {
            hash = (hash << 4U) + key[i];
            std::size_t x = hash & mask;
            if (x != 0)
                hash ^= (x >> 24);
            hash &= ~x;
        }
        std::cout << "for key " << key << " hash " << hash << std::endl;

        return hash;
    }
};

void show() {
    std::vector<std::string> v;
    v.push_back("n1YxyaBzoRogNh72eri7HBGijCAtcHpf9nm,");
    v.push_back("n1GV9UScgncwU6KKL9T18mCo2S6uAE69SWs,");
    v.push_back("n1X2SXyEKej7GZgAreXDCkiT59qaYKBDcYi,");

    std::unordered_set<std::string, hash_func> s;
    for (auto it = v.begin(); it != v.end(); it++) {
        s.insert(*it);
    }

    for (auto it = s.begin(); it != s.end(); it++) {
        std::cout << *it << std::endl;
    }
}

int main() {
    show();

    return 0;
}
```

<p>The results are:</p>

<p><strong>1) Intel(R) Xeon(R) CPU E5-2680 v4 @ 2.40GHz</strong></p>

<pre class="lang-none prettyprint-override"><code>for key n1YxyaBzoRogNh72eri7HBGijCAtcHpf9nm, hash 43411516
for key n1GV9UScgncwU6KKL9T18mCo2S6uAE69SWs, hash 93983804
for key n1X2SXyEKej7GZgAreXDCkiT59qaYKBDcYi, hash 17984604
n1X2SXyEKej7GZgAreXDCkiT59qaYKBDcYi,
n1GV9UScgncwU6KKL9T18mCo2S6uAE69SWs,
n1YxyaBzoRogNh72eri7HBGijCAtcHpf9nm,
</code>```

2) AMD EPYC 7501 32-Core Processor

for key n1YxyaBzoRogNh72eri7HBGijCAtcHpf9nm, hash 43411516
for key n1GV9UScgncwU6KKL9T18mCo2S6uAE69SWs, hash 93983804
for key n1X2SXyEKej7GZgAreXDCkiT59qaYKBDcYi, hash 17984604
n1X2SXyEKej7GZgAreXDCkiT59qaYKBDcYi,
n1YxyaBzoRogNh72eri7HBGijCAtcHpf9nm,
n1GV9UScgncwU6KKL9T18mCo2S6uAE69SWs,
```

Body:
I got the different output orders when running the following code in different hardware platforms.

#include <iostream>
#include <set>
#include <unordered_set>
#include <vector>
#include <functional>
#include <string>

struct hash_func {
    std::size_t operator()(const std::string &key) const {
        std::size_t hash = 0U;
        const std::size_t mask = 0xF0000000;
        for (std::string::size_type i = 0; i < key.length(); ++i) {
            hash = (hash << 4U) + key[i];
            std::size_t x = hash & mask;
            if (x != 0)
                hash ^= (x >> 24);
            hash &= ~x;
        }
        std::cout << "for key " << key << " hash " << hash << std::endl;

        return hash;
    }
};

void show() {
    std::vector<std::string> v;
    v.push_back("n1YxyaBzoRogNh72eri7HBGijCAtcHpf9nm,");
    v.push_back("n1GV9UScgncwU6KKL9T18mCo2S6uAE69SWs,");
    v.push_back("n1X2SXyEKej7GZgAreXDCkiT59qaYKBDcYi,");

    std::unordered_set<std::string, hash_func> s;
    for (auto it = v.begin(); it != v.end(); it++) {
        s.insert(*it);
    }

    for (auto it = s.begin(); it != s.end(); it++) {
        std::cout << *it << std::endl;
    }
}

int main() {
    show();

    return 0;
}

The results are:

1) Intel(R) Xeon(R) CPU E5-2680 v4 @ 2.40GHz

for key n1YxyaBzoRogNh72eri7HBGijCAtcHpf9nm, hash 43411516
for key n1GV9UScgncwU6KKL9T18mCo2S6uAE69SWs, hash 93983804
for key n1X2SXyEKej7GZgAreXDCkiT59qaYKBDcYi, hash 17984604
n1X2SXyEKej7GZgAreXDCkiT59qaYKBDcYi,
n1GV9UScgncwU6KKL9T18mCo2S6uAE69SWs,
n1YxyaBzoRogNh72eri7HBGijCAtcHpf9nm,

2) AMD EPYC 7501 32-Core Processor

for key n1YxyaBzoRogNh72eri7HBGijCAtcHpf9nm, hash 43411516
for key n1GV9UScgncwU6KKL9T18mCo2S6uAE69SWs, hash 93983804
for key n1X2SXyEKej7GZgAreXDCkiT59qaYKBDcYi, hash 17984604
n1X2SXyEKej7GZgAreXDCkiT59qaYKBDcYi,
n1YxyaBzoRogNh72eri7HBGijCAtcHpf9nm,
n1GV9UScgncwU6KKL9T18mCo2S6uAE69SWs,


问:
Concept of vert.x concerning a webserver?
I don't quite get how vert.x is applied for a webserver.

The concept I know for webserver is the thread-based one.

You start your webserver, which then is running.

Then for every client that connects, you get a socket, which is then passed to its own thread handler.

The thread handler then processes the tasks for this specific socket.

So it is clearly defined which thread is doing the work for which socket.
However for every socket you need a new thread, which is expensive in the long run for many sockets.

Then there is the event-based concept that vert.x supplies.
So far I have understood, it should work anyhow like this:

The Vertx instance deploys Verticles.

Verticles run in background threads, but not every Verticle has its own thread. As an example there could be 1000 verticles deployed in a Vertx instance, but the Vertx instance handles only 8 threads (nr of cores * 2).

Then there are the event loops. I'm not sure how they refer to verticles. I've read that every verticle has 2 event loops, but don't really know how that works.

As a webserver example:

```<code>class WebServer: AbstractVerticle() {
    lateinit var server: HttpServer

    override fun start() {
        server = vertx.createHttpServer(HttpServerOptions().setPort(1234).setHost("localhost"))
        var router = Router.router(vertx);
        router.route("/test").handler { routingContext ->
            var response = routingContext.response();
            response.end("Hello from my first HttpServer")
        }
        server.requestHandler(router).listen()
    }
}
</code>```

This WebServer can be deployed multiple times in a Vertx instance. And as it seems, each WebServer instance gets its own thread. When I try to connect 100 Clients and reply with a simple response, it seems like each Client is handled synchronously. Because when I do a Thread.sleep statement in each server handler, then the every second one client gets a response. However it should be that all server handlers should start their 1 second sleep and then almost identically reply to all clients after this time.

This is the code to start 100 clients:

```<code>fun main(){
    Vertx.vertx().deployVerticle(object : AbstractVerticle(){
        override fun start() {
            for(i in 0 .. 100)
                MyWebClient(vertx)
        }
    })
}

class MyWebClient(val vertx: Vertx) {
    init {
        println("Client starting ...")
        val webClient = WebClient.create(vertx, WebClientOptions().setDefaultPort(1234).setDefaultHost("localhost"))
        webClient.get("/test").send { ar ->
            if(ar.succeeded()){
                val response: HttpResponse<Buffer> = ar.result()

                println("Received response with status code ${response.statusCode()} + ${response.body()}")
            } else {
                println("Something went wrong " + ar.cause().message)
            }
        }
    }
}
</code>```

Does anybody know an explanation for this?

答:
The issue with your code is that by default Vert.x only uses a maximum of one thread per verticle (if there are more verticles than available threads, a single thread has to handle multiple verticles).

Therefore, if you perform 100 requests against a single instance of a single verticle, the requests are processed by a single thread.

To solve your issue, you should deploy multiple instances of your verticle, i.e.

```<code>vertx.deployVerticle(MainVerticle::class.java.name, DeploymentOptions().setInstances(4))
</code>```

when doing that, always 4 responses will be received at nearly the same time, because 4 instances of the verticle are running and thus 4 threads are utilized.

In previous versions of Vert.x, you could also simply configure multi-threading for a verticle if you didn't want to set a specific amount of instances.

```<code>vertx.deployVerticle(MainVerticle::class.java.name, DeploymentOptions().setWorker(true).setMultiThreaded(true))
</code>```

However, this feature has been deprecated and replaced with customer worker pools.

For more information concerning this topic, I encourage you to take a look at the  Vert.x-core Kotlin documentation

Body:
I don't quite get how vert.x is applied for a webserver.

The concept I know for webserver is the thread-based one.

You start your webserver, which then is running.

Then for every client that connects, you get a socket, which is then passed to its own thread handler.

The thread handler then processes the tasks for this specific socket.

So it is clearly defined which thread is doing the work for which socket.
However for every socket you need a new thread, which is expensive in the long run for many sockets.

Then there is the event-based concept that vert.x supplies.
So far I have understood, it should work anyhow like this:

The Vertx instance deploys Verticles.

Verticles run in background threads, but not every Verticle has its own thread. As an example there could be 1000 verticles deployed in a Vertx instance, but the Vertx instance handles only 8 threads (nr of cores * 2).

Then there are the event loops. I'm not sure how they refer to verticles. I've read that every verticle has 2 event loops, but don't really know how that works.

As a webserver example:

class WebServer: AbstractVerticle() {
    lateinit var server: HttpServer

    override fun start() {
        server = vertx.createHttpServer(HttpServerOptions().setPort(1234).setHost("localhost"))
        var router = Router.router(vertx);
        router.route("/test").handler { routingContext ->
            var response = routingContext.response();
            response.end("Hello from my first HttpServer")
        }
        server.requestHandler(router).listen()
    }
}

This WebServer can be deployed multiple times in a Vertx instance. And as it seems, each WebServer instance gets its own thread. When I try to connect 100 Clients and reply with a simple response, it seems like each Client is handled synchronously. Because when I do a Thread.sleep statement in each server handler, then the every second one client gets a response. However it should be that all server handlers should start their 1 second sleep and then almost identically reply to all clients after this time.

This is the code to start 100 clients:

fun main(){
    Vertx.vertx().deployVerticle(object : AbstractVerticle(){
        override fun start() {
            for(i in 0 .. 100)
                MyWebClient(vertx)
        }
    })
}

class MyWebClient(val vertx: Vertx) {
    init {
        println("Client starting ...")
        val webClient = WebClient.create(vertx, WebClientOptions().setDefaultPort(1234).setDefaultHost("localhost"))
        webClient.get("/test").send { ar ->
            if(ar.succeeded()){
                val response: HttpResponse<Buffer> = ar.result()

                println("Received response with status code ${response.statusCode()} + ${response.body()}")
            } else {
                println("Something went wrong " + ar.cause().message)
            }
        }
    }
}

Does anybody know an explanation for this?

Body:
The issue with your code is that by default Vert.x only uses a maximum of one thread per verticle (if there are more verticles than available threads, a single thread has to handle multiple verticles).

Therefore, if you perform 100 requests against a single instance of a single verticle, the requests are processed by a single thread.

To solve your issue, you should deploy multiple instances of your verticle, i.e.

vertx.deployVerticle(MainVerticle::class.java.name, DeploymentOptions().setInstances(4))

when doing that, always 4 responses will be received at nearly the same time, because 4 instances of the verticle are running and thus 4 threads are utilized.

In previous versions of Vert.x, you could also simply configure multi-threading for a verticle if you didn't want to set a specific amount of instances.

vertx.deployVerticle(MainVerticle::class.java.name, DeploymentOptions().setWorker(true).setMultiThreaded(true))

However, this feature has been deprecated and replaced with customer worker pools.

For more information concerning this topic, I encourage you to take a look at the  Vert.x-core Kotlin documentation


问:
How to extract number suffix from a filename
In Java I have a filename example ABC.12.txt.gz, I want to extract number 12 from the filename. Currently I am using last index method and extracting substring multiple times.</p>

答:
You could try using pattern matching

import java.util.regex.Pattern;
import java.util.regex.Matcher;

// ... Other features

String fileName = "..."; // Filename with number extension
Pattern pattern = Pattern.compile("^.*(\\d+).*$"); // Pattern to extract number

// Then try matching
Matcher matcher = pattern.matcher(fileName);
String numberExt = "";
if(matcher.matches()) {
    numberExt = matcher.group(1);
} else {
    // The filename has no numeric value in it.
}

// Use your numberExt here.
```


问:
How to use C3P0 in a spring boot hibernate multi tenant application to manage connection pool?
I am trying yo implement a multi tenant application using hibernate's MultiTenantConnectionProvider and CurrentTenantIdentifierResolver. I am not sure how the pooling is managed by hibernate and whether it is a good practice to leave it to Hibernate. Can I use C3P0 in this multi tenant application.

Here is my initial code:

```<code>@Bean(name = "dataSources" )
public Map<String, DataSource> dataSources() {
    Map<String, DataSource> result = new HashMap<>();
    for (DataSourceProperties dsProperties : this.multiTenantProperties.getDataSources()) {
        DataSourceBuilder factory = DataSourceBuilder
            .create()
            .url(dsProperties.getUrl())
            .username(dsProperties.getUsername())
            .password(dsProperties.getPassword())
            .driverClassName(dsProperties.getDriverClassName());
        result.put(dsProperties.getTenantId(), factory.build());
    }
    return result;
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(MultiTenantConnectionProvider DataSourceMultiTenantConnectionProviderImpl ,
    CurrentTenantIdentifierResolver currentTenantIdentifierResolver) {

    Map<String, Object> hibernateProps = new LinkedHashMap<>();
    hibernateProps.putAll(this.jpaProperties.getProperties());
    hibernateProps.put(Environment.MULTI_TENANT, MultiTenancyStrategy.DATABASE);
    hibernateProps.put(Environment.MULTI_TENANT_CONNECTION_PROVIDER, multiTenantConnectionProvider);
    hibernateProps.put(Environment.MULTI_TENANT_IDENTIFIER_RESOLVER, TenantIdentifierResolverImpl );

    // No dataSource is set to resulting entityManagerFactoryBean
    LocalContainerEntityManagerFactoryBean result = new LocalContainerEntityManagerFactoryBean();
    result.setPackagesToScan(new String[] { Test.class.getPackage().getName() });
    result.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
    result.setJpaPropertyMap(hibernateProps);

    return result;
}
</code>```

This is the Connection provider configured in hibernate

```<code>public class DataSourceMultiTenantConnectionProviderImpl extends
AbstractDataSourceBasedMultiTenantConnectionProviderImpl {

private static final long serialVersionUID = 1L;

@Autowired
private Map<String, DataSource> dataSources;

@Override
protected DataSource selectAnyDataSource() {
    return this.dataSources.values().iterator().next();
}

@Override
protected DataSource selectDataSource(String tenantIdentifier) {
    return this.dataSources.get(tenantIdentifier);
}
}
</code>```

This is the tenant resolver provided to hibernate

```<code>public class TenantIdentifierResolverImpl implements
CurrentTenantIdentifierResolver {

private static String DEFAULT_TENANT_ID = "tenant_1";

@Override
public String resolveCurrentTenantIdentifier() {
    String currentTenantId = TenantContext.getTenantId();
    return (currentTenantId != null) ? currentTenantId : DEFAULT_TENANT_ID;
}

@Override
public boolean validateExistingCurrentSessions() {
    return true;
}
}
</code>```

How to handle connection pooling here?

答:
You might need to change your datasources bean to this:

```<code>    @Bean(name = "dataSources" )
public Map<String, ComboPooledDataSource> dataSources() throws PropertyVetoException {
    Map<String, ComboPooledDataSource> result = new HashMap<>();
    for (DataSourceProperties dsProperties : this.multiTenantProperties.getDataSources()) {
        ComboPooledDataSource ds = new ComboPooledDataSource();
        ds.setDriverClass(dsProperties.getDriverClassName());
        ds.setJdbcUrl(dsProperties.getUrl());
        ds.setUser(dsProperties.getUsername());
        ds.setPassword(dsProperties.getPassword());
        ds.setInitialPoolSize(5);
        ds.setMinPoolSize(1);
        ds.setAcquireIncrement(1);
        ds.setMaxPoolSize(5);
        result.put(dsProperties.getTenantId(), ds);
    }

    return result;
}
</code>```

And add this method to your DataSourceMultiTenantConnectionProviderImpl

```<code>@Override
public Connection getConnection(String tenantIdentifier) throws SQLException {
    return this.dataSources.get(tenantIdentifier).getConnection();
}
</code>```

This should be enough to start connection pooling using C3P0.

Body:
I am trying yo implement a multi tenant application using hibernate's MultiTenantConnectionProvider and CurrentTenantIdentifierResolver. I am not sure how the pooling is managed by hibernate and whether it is a good practice to leave it to Hibernate. Can I use C3P0 in this multi tenant application.

Here is my initial code:

@Bean(name = "dataSources" )
public Map<String, DataSource> dataSources() {
    Map<String, DataSource> result = new HashMap<>();
    for (DataSourceProperties dsProperties : this.multiTenantProperties.getDataSources()) {
        DataSourceBuilder factory = DataSourceBuilder
            .create()
            .url(dsProperties.getUrl())
            .username(dsProperties.getUsername())
            .password(dsProperties.getPassword())
            .driverClassName(dsProperties.getDriverClassName());
        result.put(dsProperties.getTenantId(), factory.build());
    }
    return result;
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(MultiTenantConnectionProvider DataSourceMultiTenantConnectionProviderImpl ,
    CurrentTenantIdentifierResolver currentTenantIdentifierResolver) {

    Map<String, Object> hibernateProps = new LinkedHashMap<>();
    hibernateProps.putAll(this.jpaProperties.getProperties());
    hibernateProps.put(Environment.MULTI_TENANT, MultiTenancyStrategy.DATABASE);
    hibernateProps.put(Environment.MULTI_TENANT_CONNECTION_PROVIDER, multiTenantConnectionProvider);
    hibernateProps.put(Environment.MULTI_TENANT_IDENTIFIER_RESOLVER, TenantIdentifierResolverImpl );

    // No dataSource is set to resulting entityManagerFactoryBean
    LocalContainerEntityManagerFactoryBean result = new LocalContainerEntityManagerFactoryBean();
    result.setPackagesToScan(new String[] { Test.class.getPackage().getName() });
    result.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
    result.setJpaPropertyMap(hibernateProps);

    return result;
}

This is the Connection provider configured in hibernate

public class DataSourceMultiTenantConnectionProviderImpl extends
AbstractDataSourceBasedMultiTenantConnectionProviderImpl {

private static final long serialVersionUID = 1L;

@Autowired
private Map<String, DataSource> dataSources;

@Override
protected DataSource selectAnyDataSource() {
    return this.dataSources.values().iterator().next();
}

@Override
protected DataSource selectDataSource(String tenantIdentifier) {
    return this.dataSources.get(tenantIdentifier);
}
}

This is the tenant resolver provided to hibernate

public class TenantIdentifierResolverImpl implements
CurrentTenantIdentifierResolver {

private static String DEFAULT_TENANT_ID = "tenant_1";

@Override
public String resolveCurrentTenantIdentifier() {
    String currentTenantId = TenantContext.getTenantId();
    return (currentTenantId != null) ? currentTenantId : DEFAULT_TENANT_ID;
}

@Override
public boolean validateExistingCurrentSessions() {
    return true;
}
}

How to handle connection pooling here?

Body:
You might need to change your datasources bean to this:

    @Bean(name = "dataSources" )
public Map<String, ComboPooledDataSource> dataSources() throws PropertyVetoException {
    Map<String, ComboPooledDataSource> result = new HashMap<>();
    for (DataSourceProperties dsProperties : this.multiTenantProperties.getDataSources()) {
        ComboPooledDataSource ds = new ComboPooledDataSource();
        ds.setDriverClass(dsProperties.getDriverClassName());
        ds.setJdbcUrl(dsProperties.getUrl());
        ds.setUser(dsProperties.getUsername());
        ds.setPassword(dsProperties.getPassword());
        ds.setInitialPoolSize(5);
        ds.setMinPoolSize(1);
        ds.setAcquireIncrement(1);
        ds.setMaxPoolSize(5);
        result.put(dsProperties.getTenantId(), ds);
    }

    return result;
}

And add this method to your DataSourceMultiTenantConnectionProviderImpl

@Override
public Connection getConnection(String tenantIdentifier) throws SQLException {
    return this.dataSources.get(tenantIdentifier).getConnection();
}

This should be enough to start connection pooling using C3P0.


问:
Map array values to collection of items
How would one do the following elegantly with laravel collections ?

Map the values of the $baseMap  as keys to the collection.

The baseMap :

```<code>$baseMap = [
            'name' => 'new_name',
            'year' => 'new_year',
        ];
</code>```

The collection :

```<code> $items = collect([
            [
                'name' => 'name1',
                'year' => '1000',
                'not_in_basemap' => 'foo'
            ],
            [
                'name' => 'name2',
                'year' => '2000',
                'not_in_basemap' => 'foo'
            ],
            //...
        ]);
</code>```

The end result :

```<code>$result =[
            [
                'new_name' => 'name1',
                'new_year' => '1000',

            ],
            [
                'new_name'=> 'name2',
                'new_year' => '2000',

            ],
        ];
</code>```

I know how to do it in plain php , just wondering what a nice collection version would be. Thanks!

答:
Here are my two cents, using map. Don't know how dynamic your collection should be, but knowing the keys I would do the following:

```<code>$baseMap = [
    'name' => 'new_name',
    'year' => 'new_year',
];

$items = collect([
    [
      'name' => 'name1',
      'year' => '1000',
      'not_in_basemap' => 'foo'
    ],
    [
      'name' => 'name2',
      'year' => '2000',
      'not_in_basemap' => 'foo'
    ],

  ])->map(function($item, $key) use ($baseMap) {
        return [
             $baseMap['name'] => $item['name'],
             $baseMap['year'] => $item['year']
        ];
  });
</code>```

Title: Map array values to collection of items

Body:
How would one do the following elegantly with laravel collections ?

Map the values of the $baseMap  as keys to the collection.

The baseMap :

$baseMap = [
            'name' => 'new_name',
            'year' => 'new_year',
        ];

The collection :

 $items = collect([
            [
                'name' => 'name1',
                'year' => '1000',
                'not_in_basemap' => 'foo'
            ],
            [
                'name' => 'name2',
                'year' => '2000',
                'not_in_basemap' => 'foo'
            ],
            //...
        ]);

The end result :

$result =[
            [
                'new_name' => 'name1',
                'new_year' => '1000',

            ],
            [
                'new_name'=> 'name2',
                'new_year' => '2000',

            ],
        ];

I know how to do it in plain php , just wondering what a nice collection version would be. Thanks!

Body:
Here are my two cents, using map. Don't know how dynamic your collection should be, but knowing the keys I would do the following:

$baseMap = [
    'name' => 'new_name',
    'year' => 'new_year',
];

$items = collect([
    [
      'name' => 'name1',
      'year' => '1000',
      'not_in_basemap' => 'foo'
    ],
    [
      'name' => 'name2',
      'year' => '2000',
      'not_in_basemap' => 'foo'
    ],

  ])->map(function($item, $key) use ($baseMap) {
        return [
             $baseMap['name'] => $item['name'],
             $baseMap['year'] => $item['year']
        ];
  });