问:
What exactly happens when awaiting a promise in JavaScript?
One point that I can’t seem to find anywhere in documentation or related resources is what the procedure is, in regards to the calling function and the event loop, when JS hits the await keyword.

Here’s what the specs state:

The await expression causes async function execution to pause until a Promise is resolved, that is fulfilled or rejected, and to resume execution of the async function after fulfillment. When resumed, the value of the await expression is that of the fulfilled Promise.

That all makes sense, but what really is meant by pause? Does the function immediately return to the caller and then when the promise that’s being awaited resolves, it and the rest of the async method gets added to the microtask queue for handling? I know that async/await is syntactic sugar for the Promise API, so I’m assuming that this is sorta what happens, but I want to make sure I’m really understanding the “magic” that happens when an await is reached.

From what I’ve read, this seems to be what’s done in C#, but I’m not exactly sure how it translates to JS.

答:
await/async means that we execute the code synchronously. It will follow the order of the await function is called within async function.
for example: It will process the execution line by line like it waits it the response is returned from await and then it proceeds further.

```<code> `function doubleAfter2Seconds(x) {
    return new Promise(resolve => {
      setTimeout(() => {
        resolve(x * 2);
      }, 2000);
    });
  }

  async function addAsync(x) {
     console.log("Here I am before first await");
    const a = await doubleAfter2Seconds(10);
    console.log("A ouput is ",a);
    const b = await doubleAfter2Seconds(20);
    console.log("B ouput is ",b);
    const c = await doubleAfter2Seconds(30);
    console.log("C ouput is ",c);
    return x + a + b + c;
  }

  addAsync(10).then((sum) => {
    console.log(sum);
  });`
</code>```

The above code will output the result like below:

Hope this helps to understand async/await

Body:
await/async means that we execute the code synchronously. It will follow the order of the await function is called within async function.
for example: It will process the execution line by line like it waits it the response is returned from await and then it proceeds further.

 `function doubleAfter2Seconds(x) {
    return new Promise(resolve => {
      setTimeout(() => {
        resolve(x * 2);
      }, 2000);
    });
  }

  async function addAsync(x) {
     console.log("Here I am before first await");
    const a = await doubleAfter2Seconds(10);
    console.log("A ouput is ",a);
    const b = await doubleAfter2Seconds(20);
    console.log("B ouput is ",b);
    const c = await doubleAfter2Seconds(30);
    console.log("C ouput is ",c);
    return x + a + b + c;
  }

  addAsync(10).then((sum) => {
    console.log(sum);
  });`

The above code will output the result like below:

Hope this helps to understand async/await


来源: stackexchange

问:
Finding the items changed in Observable Collection
I have a class from a EF db context which I have displayed in a datagrid based on an ObservableCollection. The user can edit the the grid and this all displays fine.

However I now need to send the data back to the database. I do not want to send all the items in the collection to my save method, so can I find only the items that have been have change in the collection?

答:
just as an idea (not professing this to be an ideal solution) i have run into a similar issue, looked around for potential solutions and none of those were exactly what i wanted.

i had to pass a collection to WPF DataGrid and it seemed to complain about using List, hence i turned to ObservableCollection

i did not want to work directly with the EF context for multiple reasons primarily because i wanted to grab items and pass them to intermediate transaction factory to be processed (business logic).

so decided to stick with ObservableCollection and instead make slight modification to the ViewModel since this i was free to do it.

my model ended up to look like this:

```<code>internal class databaseItemModel
{
    int _id;
    string _description;
    decimal _price;
    decimal _quantity;
    decimal _cost;
    bool _modified;

    public databaseItemModel()
    {
        _modified = false;
    }

    public int id { get { return _id; } }
    public bool modified { get { return _modified; } }
    public string description { get { return _description; } set { _description = value; _modified = true; } }
    public decimal price { get { return _price; } set { _price = value; _modified = true; } }
    public decimal quantity { get { return _quantity; } set { _quantity = value; _modified = true; } }
    public decimal cost { get { return _cost; } set { _cost = value; _modified = true; } }
    public bool selected { get; set; }

    public void setId(int _idvalue)
    {
        _id = _idvalue;
    }
    public decimal value
    {
        get { return price * quantity; }
    }
    public void setDescription(string _descr)
    {
        _description = _descr;
    }
    public void setPrice(decimal _pr)
    {
        _price = _pr;
    }
    public void setQuantity(decimal _qty)
    {
        _quantity = _qty;
    }
    public void setCost(decimal _cst)
    {
        _cost = _cst;
    }
}
</code>```

Basically, the plain idea behind it is that i would use functions to populate data rather than using properties direct and then pass the item to ObservableCollection which then would become the source for the DataGrid.ItemsSource

since DataGrid/ObservableCollection would work with properties - modified objects would be marked as modified and i would then be able to pick up the collection on exit and collect the modified items.

hope this is helpful.

ContentLicense: CC BY-SA 3.0

Body:
just as an idea (not professing this to be an ideal solution) i have run into a similar issue, looked around for potential solutions and none of those were exactly what i wanted.

i had to pass a collection to WPF DataGrid and it seemed to complain about using List, hence i turned to ObservableCollection

i did not want to work directly with the EF context for multiple reasons primarily because i wanted to grab items and pass them to intermediate transaction factory to be processed (business logic).

so decided to stick with ObservableCollection and instead make slight modification to the ViewModel since this i was free to do it.

my model ended up to look like this:

internal class databaseItemModel
{
    int _id;
    string _description;
    decimal _price;
    decimal _quantity;
    decimal _cost;
    bool _modified;

    public databaseItemModel()
    {
        _modified = false;
    }

    public int id { get { return _id; } }
    public bool modified { get { return _modified; } }
    public string description { get { return _description; } set { _description = value; _modified = true; } }
    public decimal price { get { return _price; } set { _price = value; _modified = true; } }
    public decimal quantity { get { return _quantity; } set { _quantity = value; _modified = true; } }
    public decimal cost { get { return _cost; } set { _cost = value; _modified = true; } }
    public bool selected { get; set; }

    public void setId(int _idvalue)
    {
        _id = _idvalue;
    }
    public decimal value
    {
        get { return price * quantity; }
    }
    public void setDescription(string _descr)
    {
        _description = _descr;
    }
    public void setPrice(decimal _pr)
    {
        _price = _pr;
    }
    public void setQuantity(decimal _qty)
    {
        _quantity = _qty;
    }
    public void setCost(decimal _cst)
    {
        _cost = _cst;
    }
}

Basically, the plain idea behind it is that i would use functions to populate data rather than using properties direct and then pass the item to ObservableCollection which then would become the source for the DataGrid.ItemsSource

since DataGrid/ObservableCollection would work with properties - modified objects would be marked as modified and i would then be able to pick up the collection on exit and collect the modified items.

hope this is helpful.

ContentLicense: CC BY-SA 4.0


问:
I accidentally deleted my files while using git, need some help recovering
I was trying to upload a project to a new git repository and I was receiving an error over and over and nothing I tried could fix it. So I decided, maybe like an idiot, to delete the .git folder. Well, that didn't fix the error so I decided to copy my files to a new directory and initialize git from there.

Well, it worked! however, all of my files were deleted. What I don't understand is my project had about 10 vue files in it and a few other assets.

When I copied my other files over to the new folder, I commited and pushed to my new repository without error. All good - however, when checking the repository - it appears that it was just a blank vue project... Now I can't find my original project, each file contained about 300 or so lines of code.

Here's what I have: I have my original directory and the .git folder there. That folder is full of objects, (00, 0b, 0d, 0e, 01, 1a, etc...). The folder now only has the .git folder in it. Is there any way to recover these files based on only have the .git folder from before?

答: You can recover your project only if you have original .git folder before creating new repository. With original .git folder you can use options of git reset or git reflog. If you are not able to find original .git folder then you cannot recover your files because .git folder is "the magic wand" which makes a normal project a "the git project" so now without .git its just a normal directory.


问:
How to get x -coordinates and y- coordinates on tap in bokeh
I am facing problem with how to show  x and y coordinates on graph in bokeh using Tap tool

I have tried following code. Now i want to write a call back for tap tool how do i do that. how do i show  on clicking the square the x an y coordinates

```<code>  from bokeh.models import ColumnDataSource, OpenURL, TapTool
  from bokeh.plotting import figure, output_file, show

  output_file("openurl.html")

  p = figure(plot_width=400, plot_height=400,
               tools="tap", title="Click the Dots")

  source = ColumnDataSource(data=dict(x=[1, 2, 3, 4, 5], y=[2, 5, 8, 2,
                         7]))

  p.square('x', 'y', color='green', size=20, source=source)

  taptool = p.select(type=TapTool)

  show(p)
</code>```

答:
You can get the x and y coordinates on tap by writing a callback that is called when the selection changes. The indexes of the currently selected glyphs can be found in source.selected.indices. These indexes can be used to get the x and y coordinates from source.data. This piece of code prints the x and y coordinates in the console in your browser (F12).</p>

```<code>from bokeh.models import ColumnDataSource, TapTool, CustomJS
from bokeh.plotting import figure, output_file, show

output_file("openurl.html")

p = figure(plot_width=400, plot_height=400,
             tools="tap", title="Click the Dots")

source = ColumnDataSource(data=dict(x=[1, 2, 3, 4, 5], y=[2, 5, 8, 2, 7]))

p.square('x', 'y', color='green', size=20, source=source)

callback = CustomJS(args=dict(source=source), code="""
    var selectedIndex = source.selected.indices;
    for (var i = 0; i < selectedIndex.length; i++) {
        console.log("Index:", selectedIndex[i]);
        console.log("x:", source.data['x'][selectedIndex[i]]);
        console.log("y:", source.data['y'][selectedIndex[i]]);
    }
""")

taptool = p.select(type=TapTool)
source.selected.js_on_change('indices', callback)
show(p)
</code>```

Body:
I am facing problem with how to show  x and y coordinates on graph in bokeh using Tap tool

I have tried following code. Now i want to write a call back for tap tool how do i do that. how do i show  on clicking the square the x an y coordinates

  from bokeh.models import ColumnDataSource, OpenURL, TapTool
  from bokeh.plotting import figure, output_file, show

  output_file("openurl.html")

  p = figure(plot_width=400, plot_height=400,
               tools="tap", title="Click the Dots")

  source = ColumnDataSource(data=dict(x=[1, 2, 3, 4, 5], y=[2, 5, 8, 2,
                         7]))

  p.square('x', 'y', color='green', size=20, source=source)

  taptool = p.select(type=TapTool)

  show(p)

Body:
You can get the x and y coordinates on tap by writing a callback that is called when the selection changes. The indexes of the currently selected glyphs can be found in source.selected.indices. These indexes can be used to get the x and y coordinates from source.data. This piece of code prints the x and y coordinates in the console in your browser (F12).

from bokeh.models import ColumnDataSource, TapTool, CustomJS
from bokeh.plotting import figure, output_file, show

output_file("openurl.html")

p = figure(plot_width=400, plot_height=400,
             tools="tap", title="Click the Dots")

source = ColumnDataSource(data=dict(x=[1, 2, 3, 4, 5], y=[2, 5, 8, 2, 7]))

p.square('x', 'y', color='green', size=20, source=source)

callback = CustomJS(args=dict(source=source), code="""
    var selectedIndex = source.selected.indices;
    for (var i = 0; i < selectedIndex.length; i++) {
        console.log("Index:", selectedIndex[i]);
        console.log("x:", source.data['x'][selectedIndex[i]]);
        console.log("y:", source.data['y'][selectedIndex[i]]);
    }
""")

taptool = p.select(type=TapTool)
source.selected.js_on_change('indices', callback)
show(p)


问:
How to get single items count in a slice with go?
For example, this is a slice:

```<code>[1, 2, 3, 3, 4]
</code>```

want to get single data 1, 2, 4 's count and return count = 3.

Maybe remove duplicate items(include itself) is an idea, but didn't find suitalbe method.

What I tried:

```<code>  func removeDuplicateItems() {
      intSlice := []int{1, 2, 3, 3, 4}
      fmt.Println(intSlice)

      keys := make(map[int]bool)
      list := []int{}
      for _, entry := range intSlice {
          if _, value := keys[entry]; !value {
              keys[entry] = true
              list = append(list, entry)
          }
      }

      fmt.Println(list)
  }
</code>```

Got

```<code>[1 2 3 3 4]
[1 2 3 4]
</code>```

答:
I just changed your function a little bit:

```<code>func removeDuplicateItems() {
    intSlice := []int{1, 2, 3, 3, 4}
    fmt.Println(intSlice)

    keys := make(map[int]int)
    list := []int{}
    for _, entry := range intSlice {
        keys[entry]++
    }
    for k, v := range keys {
        if v == 1 {
            list = append(list, k)
        }
    }

    fmt.Println(list)
}
</code>```

https://play.golang.org/p/ESFLhC4VC-l

At this point the list is not sorted. If you want to sort your list afterward you need to use the sortpackage.

Body:
For example, this is a slice:

[1, 2, 3, 3, 4]

want to get single data 1, 2, 4 's count and return count = 3.

Maybe remove duplicate items(include itself) is an idea, but didn't find suitalbe method.

What I tried:

  func removeDuplicateItems() {
      intSlice := []int{1, 2, 3, 3, 4}
      fmt.Println(intSlice)

      keys := make(map[int]bool)
      list := []int{}
      for _, entry := range intSlice {
          if _, value := keys[entry]; !value {
              keys[entry] = true
              list = append(list, entry)
          }
      }

      fmt.Println(list)
  }

Got

[1 2 3 3 4]
[1 2 3 4]

Body:
I just changed your function a little bit:

func removeDuplicateItems() {
    intSlice := []int{1, 2, 3, 3, 4}
    fmt.Println(intSlice)

    keys := make(map[int]int)
    list := []int{}
    for _, entry := range intSlice {
        keys[entry]++
    }
    for k, v := range keys {
        if v == 1 {
            list = append(list, k)
        }
    }

    fmt.Println(list)
}

https://play.golang.org/p/ESFLhC4VC-l

At this point the list is not sorted. If you want to sort your list afterward you need to use the sortpackage.


问:
Opening URL's on same browser in different tab from CSV in Python
I am trying to open a list of URLs in new tabs in a single window, but it instead opens them in new windows. Please help. This is my URL.csv

```<code>SN,Title,URL
1,Google,https://google.com
2,youtube,https://youtube.com
</code>```

```<code>import csv

from selenium import webdriver

def csv_url_reader(url_obj):
    reader = csv.DictReader(url_obj, delimiter=',')

    for line in reader:
        url = line["URL"]
        title = line["Title"]
        print(url + title)
        driver = webdriver.Chrome(r'C:\chromedriver_win32\chromedriver')
        driver.get(url)

if __name__ == "__main__":
    with open("URL.csv") as url_obj:
        csv_url_reader(url_obj)
</code>```

答:
In the piece of code that you posted you are opening the URL in the driver instance and not a new tab.

Instead, you should try opening new tabs like this:

```<code>import csv

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Chrome(r'C:\chromedriver_win32\chromedriver')
def csv_url_reader(url_obj):
    reader = csv.DictReader(url_obj, delimiter=',')

    for line in reader:
        url = line["URL"]
        title = line["Title"]
        print(url + title)
        driver.execute_script("window.open(" + url + ",'_blank');")

if __name__ == "__main__":
    with open("URL.csv") as url_obj:
        csv_url_reader(url_obj)
</code>```

Body:
I am trying to open a list of URLs in new tabs in a single window, but it instead opens them in new windows. Please help. This is my URL.csv

SN,Title,URL
1,Google,https://google.com
2,youtube,https://youtube.com

import csv

from selenium import webdriver

def csv_url_reader(url_obj):
    reader = csv.DictReader(url_obj, delimiter=',')

    for line in reader:
        url = line["URL"]
        title = line["Title"]
        print(url + title)
        driver = webdriver.Chrome(r'C:\chromedriver_win32\chromedriver')
        driver.get(url)

if __name__ == "__main__":
    with open("URL.csv") as url_obj:
        csv_url_reader(url_obj)

Body:
In the piece of code that you posted you are opening the URL in the driver instance and not a new tab.

Instead, you should try opening new tabs like this:

import csv

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Chrome(r'C:\chromedriver_win32\chromedriver')
def csv_url_reader(url_obj):
    reader = csv.DictReader(url_obj, delimiter=',')

    for line in reader:
        url = line["URL"]
        title = line["Title"]
        print(url + title)
        driver.execute_script("window.open(" + url + ",'_blank');")

if __name__ == "__main__":
    with open("URL.csv") as url_obj:
        csv_url_reader(url_obj)


问:
Javascript - Group by one property of object in an array of objects
I know that, there are countless of questions about group by one property from an array of object. But what I want to do is a litte more specific:

```<code>const lists = [
{ groupKey: 'ABC', key: 'r8', timestamp: '2014', index: 2 },
{ groupKey: 'ABC', key: 'q8', timestamp: '2012', index: 0 },
{ groupKey: 'ABC', key: 'w8', timestamp: '2013', index: 1 },
{ groupKey: 'CDE', key: 'r7', timestamp: '2019', index: 0 }
]
</code>```

Result should be grouped by groupKey and sorted by index

(indexes here are iterators 0,1,2,3... so no need to actually be sorted but rather to be placed in a right order of an array. Example: array[index] = ... ).

This should look like:

```<code>{
  ABC: [
    {  key: 'q8', timestamp: '2012', index: 0 },
    {  key: 'w8', timestamp: '2013', index: 1 },
    {  key: 'r8', timestamp: '2014', index: 2 }
  ],
  CDE: [
    { key: 'r7', timestamp: '2019', index: 0 }
  ]
}
</code>```

I have tried to group by without sorting:

```<code>const result = lists.reduce((r, item) => {
      let { groupKey, ...rest } = item
      r[item.groupKey] = [...(r[item.groupKey] || []), rest]
      return r
    }, {})
</code>```

And with sorting, not successful but you know what I mean:

```<code>const result = lists.reduce((r, item) => {
          let { groupKey, ...rest } = item
          r[item.groupKey][item.index] = rest //err: can not set property 2 of undefined
          return r
        }, {})
</code>```

Any suggestions are appreciated

答:
Try like this

const lists = [
{ groupKey: 'ABC', key: 'r8', timestamp: '2014', index: 2 },
{ groupKey: 'ABC', key: 'q8', timestamp: '2012', index: 0 },
{ groupKey: 'ABC', key: 'w8', timestamp: '2013', index: 1 },
{ groupKey: 'CDE', key: 'r7', timestamp: '2019', index: 0 }
]

var groupBy = function(datas, key) {
  return datas.reduce(function(data, x) {
    var dKey = x[key];
    delete x[key];
    (data[dKey] = data[dKey] || []).push(x);

    return data;
  }, {});
};

console.log(groupBy(lists, 'groupKey'));```

Body:
I know that, there are countless of questions about group by one property from an array of object. But what I want to do is a litte more specific:

const lists = [
{ groupKey: 'ABC', key: 'r8', timestamp: '2014', index: 2 },
{ groupKey: 'ABC', key: 'q8', timestamp: '2012', index: 0 },
{ groupKey: 'ABC', key: 'w8', timestamp: '2013', index: 1 },
{ groupKey: 'CDE', key: 'r7', timestamp: '2019', index: 0 }
]

Result should be grouped by groupKey and sorted by index

(indexes here are iterators 0,1,2,3... so no need to actually be sorted but rather to be placed in a right order of an array. Example: array[index] = ... ).

This should look like:

{
  ABC: [
    {  key: 'q8', timestamp: '2012', index: 0 },
    {  key: 'w8', timestamp: '2013', index: 1 },
    {  key: 'r8', timestamp: '2014', index: 2 }
  ],
  CDE: [
    { key: 'r7', timestamp: '2019', index: 0 }
  ]
}

I have tried to group by without sorting:

const result = lists.reduce((r, item) => {
      let { groupKey, ...rest } = item
      r[item.groupKey] = [...(r[item.groupKey] || []), rest]
      return r
    }, {})

And with sorting, not successful but you know what I mean:

const result = lists.reduce((r, item) => {
          let { groupKey, ...rest } = item
          r[item.groupKey][item.index] = rest //err: can not set property 2 of undefined
          return r
        }, {})

Any suggestions are appreciated


问:
Is it ok to unit-test an abstract class by instantiating it as a mock object?
It has come to my attention that you can unit-test an abstract class by instantiating it as a mock object. Thereby you mock the abstract properties and methods, while being able to test the implemented ones.

However, I am accustomed to distinguish between the class to test and the injected dependencies to mock/stub. So, in this early stage of my new enlightenment I wonder if there are any pitfalls to this way of testing?? Any thoughts on this?

Regards,
Morten

答:
If there isn't a concrete implementation in the part I'm testing, I usually write a test-implementation. In the unit test I do something similar as the user of my classes does. If he inherits my class, I inherit in the test.

On the other side, I wouldn't say that it is bad to use a mock framework to create an implementation. In my cases I usually doesn't work, usually because I need to write ORM mapping files for that class and thing like this.


问:
Actuator with Spring boot Jersey
I'm using Jersey starter in my web application.

   org.springframework.boot spring-boot-starter-jersey  1.4.2.RELEASE

Trying to integrate the Actuator endpoints into my application.Used the following maven dependency

      org.springframework.boot
        spring-boot-starter-actuator
        1.5.2.RELEASE
        org.springframework.boot
        spring-boot-starter-web
        1.5.2.RELEASE

When I access the health endpoint, it was giving me 404 error.
http://localhost:8080/context/health

Do I need to add any other configuration class to my application that will initialize the actuator?
Can anyone point me in the correct direction?

答:
This is how i was able to ti get this working

Step 1
By default Jersey will be set up resource configured by extends ResourceConfig  as serverlate. We need to tell spring boot to use it as filter.
Set it as using below property

```<code>spring .jersey.type: filter
</code>```

Step 2

I was using below configuration for registering resources

```<code>   @component
    public class MyResourceConfig extends ResourceConfig  {

        public MyResourceConfig () {
            try {
                register(XXX.class);

            } catch (Exception e) {
                LOGGER.error("Exception: ", e);
            }
        }

    }
</code>```

Change @component to @Configuration and also add below property property(ServletProperties.FILTER_FORWARD_ON_404, true);

Final Configuration

```<code>@Configuration
        public class LimitResourceConfig extends ResourceConfig  {

            public LimitResourceConfig() {
                try {
                    register(XXX.class);
                    property(ServletProperties.FILTER_FORWARD_ON_404, true);

                } catch (Exception e) {
                    LOGGER.error("Exception: ", e);
                }
            }

        }
</code>```

Title: Actuator with Spring boot Jersey

Body:
This is how i was able to ti get this working

Step 1
By default Jersey will be set up resource configured by extends ResourceConfig  as serverlate. We need to tell spring boot to use it as filter.
Set it as using below property

spring .jersey.type: filter

Step 2

I was using below configuration for registering resources

   @component
    public class MyResourceConfig extends ResourceConfig  {

        public MyResourceConfig () {
            try {
                register(XXX.class);

            } catch (Exception e) {
                LOGGER.error("Exception: ", e);
            }
        }

    }

Change @component to @Configuration and also add below property property(ServletProperties.FILTER_FORWARD_ON_404, true);

Final Configuration

@Configuration
        public class LimitResourceConfig extends ResourceConfig  {

            public LimitResourceConfig() {
                try {
                    register(XXX.class);
                    property(ServletProperties.FILTER_FORWARD_ON_404, true);

                } catch (Exception e) {
                    LOGGER.error("Exception: ", e);
                }
            }

        }


问:
Bitnami helm phpfpm / nginx does not serve css and js files
I followed this tutorial : https://docs.bitnami.com/kubernetes/how-to/deploy-php-application-kubernetes-helm/

At the end of the tutorial, everything works.
When I try to integrate CSS or JS into the page, I get a 404 error.

Furthermore, it is served as text/html instead css.

Here is the configuration of my vhost:

```<code>server {
    listen 0.0.0.0:80;
    server_name myapp.com;

    root /app;

    location / {
        index index.php;
    }

    location ~ \.php$ {
        # fastcgi_pass [PHP_FPM_LINK_NAME]:9000;
        fastcgi_pass phpfpm:9000;
        fastcgi_index index.php;
        include fastcgi.conf;
    }
}
</code>```

Regards

答:
It seems the tutorial is outdated.

The templates available at https://github.com/bitnami/tutorials/tree/master/phpfpm-k8s/helm-chart/templates are outdated. They're based on the Bitnami NGINX Helm chart available two years ago.

You can find the latest Bitnami NGINX Helm chart at: https://github.com/bitnami/charts/tree/master/bitnami/nginx

As you can see, the chart evolved significantly (also the Bitnami NGINX docker image evolved) and therefore, you need to adapt the way to configure NGINX to serve your php app. Check the README.md below for more information:

https://github.com/bitnami/charts/blob/master/bitnami/nginx/README.md

Body:
I followed this tutorial : https://docs.bitnami.com/kubernetes/how-to/deploy-php-application-kubernetes-helm/

At the end of the tutorial, everything works.
When I try to integrate CSS or JS into the page, I get a 404 error.

Furthermore, it is served as text/html instead css.

Here is the configuration of my vhost:

server {
    listen 0.0.0.0:80;
    server_name myapp.com;

    root /app;

    location / {
        index index.php;
    }

    location ~ \.php$ {
        # fastcgi_pass [PHP_FPM_LINK_NAME]:9000;
        fastcgi_pass phpfpm:9000;
        fastcgi_index index.php;
        include fastcgi.conf;
    }
}

Regards


问:
Sweet Alert 2 without npm
My app isn't npm and I need to use Sweet Alert 2.

I looked for information on the site https://sweetalert2.github.io, but without success.

Is there any way to use Sweet Alert 2 without npm?

Regards, Felipe.

答:
Just add cdn links in view:

```<code><link href="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/7.33.1/sweetalert2.css" rel="stylesheet" type="text/css">

<script src="https://code.jquery.com/jquery-3.4.1.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/7.33.1/sweetalert2.js"></script>
</code>```

Js code:

```<code><script>
    $(document).ready(function(){
        Swal.fire({
           type: 'success',
           title: 'Your work has been done',
           showConfirmButton: false,
           timer: 1500
        })
    });
</script>
</code>```

Title: Sweet Alert 2 without npm

Body:
Just add cdn links in view:

<link href="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/7.33.1/sweetalert2.css" rel="stylesheet" type="text/css">

<script src="https://code.jquery.com/jquery-3.4.1.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/7.33.1/sweetalert2.js"></script>

Js code:

<script>
    $(document).ready(function(){
        Swal.fire({
           type: 'success',
           title: 'Your work has been done',
           showConfirmButton: false,
           timer: 1500
        })
    });
</script>


问:
Can i send java object in a json response
For example i have java class post:

```<code>public class Post{
String title;
String text;
}
</code>```

If i create an instance of this class and convert it into ajax response in my servlet controller

```<code>@RestController
public class AjaxNewsController {
 @JsonView(Views.Public.class)
    @PostMapping(value = "/getPost")
    public AjaxResponseBody getSearchResultViaAjax(@RequestBody AjaxPostResponse postId) {
        AjaxResponseBody result = new AjaxResponseBody();
        result.setCode("200");
        result.setMsg("found POST");
        result.setResult(post);
        return result;

    }
}
</code>```

My question is: can i retrieve post fields title and text with javascript on a client side and if i can then how?

Here is an example of console with my response in browse
console

but how can i extract my post with fields in ajax and jquery?

UPD

after some reaserach i found that somehow my serlvet doesn't convert my java pojo into json. How should i do it?

UPD2

my request sends normaly but serlvet doesn't convert POST class into json.

here is my javascript :

```<code>function likePost(postId,ratingElem, ratingChange) {

    var search = {}
    search["postId"] = postId;
    search["rating"] = ratingChange;

    $.ajax({
        type : "POST",
        contentType : 'application/json; charset=utf-8',
        dataType : 'json',
        url : "likePost",
        data : JSON.stringify(search),
        timeout : 100000,
        success : function(data) {
            console.log("SUCCESS: ", data);
            changeRating(ratingElem,data.post.getTopic());
        },
        error : function(e) {
            console.log("ERROR: ", e);
            changeRating(ratingElem,'error');
        },
        done : function(e) {
            console.log("DONE");
            enableSearchButton(true);
        }
    });

}
</code>```

status and message is fine but result is empty.

答:
So i solved my problem. I use com.fasterxml.jackson.core so i just need to mark fields in my class that i want to convert into json with  @JsonView annotation like

```<code> @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "post_id",
            unique = true, nullable = false)
    @JsonView(Views.Public.class)
    private Integer postId;
</code>```

Everything that marked will be converted.

Body:
For example i have java class post:

public class Post{
String title;
String text;
}

If i create an instance of this class and convert it into ajax response in my servlet controller

@RestController
public class AjaxNewsController {
 @JsonView(Views.Public.class)
    @PostMapping(value = "/getPost")
    public AjaxResponseBody getSearchResultViaAjax(@RequestBody AjaxPostResponse postId) {
        AjaxResponseBody result = new AjaxResponseBody();
        result.setCode("200");
        result.setMsg("found POST");
        result.setResult(post);
        return result;

    }
}

My question is: can i retrieve post fields title and text with javascript on a client side and if i can then how?

Here is an example of console with my response in browse
console

but how can i extract my post with fields in ajax and jquery?

UPD

after some reaserach i found that somehow my serlvet doesn't convert my java pojo into json. How should i do it?

UPD2

my request sends normaly but serlvet doesn't convert POST class into json.

here is my javascript :

function likePost(postId,ratingElem, ratingChange) {

    var search = {}
    search["postId"] = postId;
    search["rating"] = ratingChange;

    $.ajax({
        type : "POST",
        contentType : 'application/json; charset=utf-8',
        dataType : 'json',
        url : "likePost",
        data : JSON.stringify(search),
        timeout : 100000,
        success : function(data) {
            console.log("SUCCESS: ", data);
            changeRating(ratingElem,data.post.getTopic());
        },
        error : function(e) {
            console.log("ERROR: ", e);
            changeRating(ratingElem,'error');
        },
        done : function(e) {
            console.log("DONE");
            enableSearchButton(true);
        }
    });

}

status and message is fine but result is empty.

Body:
So i solved my problem. I use com.fasterxml.jackson.core so i just need to mark fields in my class that i want to convert into json with  @JsonView annotation like

 @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "post_id",
            unique = true, nullable = false)
    @JsonView(Views.Public.class)
    private Integer postId;

Everything that marked will be converted.


答:
You're almost there, you just need to sort after the reduce is finished:

const lists = [{
    groupKey: 'ABC',
    key: 'r8',
    timestamp: '2014',
    index: 2
  },
  {
    groupKey: 'ABC',
    key: 'q8',
    timestamp: '2012',
    index: 0
  },
  {
    groupKey: 'ABC',
    key: 'w8',
    timestamp: '2013',
    index: 1
  },
  {
    groupKey: 'CDE',
    key: 'r7',
    timestamp: '2019',
    index: 0
  }
]
const result = lists.reduce((r, item) => {
  const { groupKey, ...rest } = item
  r[groupKey] = [...(r[groupKey] || []), rest];
  return r;
}, {})
Object.values(result).forEach((arr) => {
  arr.sort((a, b) => a.index - b.index);
});
console.log(result);```

Title: Javascript - Group by one property of object in an array of objects


问:
Updating versionCode for Android PhoneGap app
I have tried updating the config.xml file to include: versionCode="10002"

I've created a 'platforms/android/release-signing.properties' file and ran:

```<code>phonegap build --release android --versionCode=10002
</code>```

Nothing seems to make the versionCode=10002 stick. How can I fix this?

答:
It should work if you add android-versionCode instead of just versionCode to the <widget> in config.xml.

For example:

```<code><widget id="com.test.app"
    version="1.2.3"
    android-versionCode="10002">
</code>```

Body:
I have tried updating the config.xml file to include: versionCode="10002"

I've created a 'platforms/android/release-signing.properties' file and ran:

phonegap build --release android --versionCode=10002

Nothing seems to make the versionCode=10002 stick. How can I fix this?

Body:
It should work if you add android-versionCode instead of just versionCode to the <widget> in config.xml.

For example:

<widget id="com.test.app"
    version="1.2.3"
    android-versionCode="10002">


问:
How to get download complete event and downloaded file details in Cordova
I'm trying to create a hybrid application using Cordova to download a pdf file and need to read the downloaded file from application.

Now i'm trying to achieve this from cordova-plugin-inappbrowser .

```<code>window.open('https://www.google.com/search?q=sample+pdf+download&oq=sample+pdf+download', '_system', 'location=yes');

</code>```

So with this code line i could download the file and view it internally on the app.

But i need to get the downloaded completed event and downloaded file name. Because i need to read the file internally.( might need a another plugin)

I need to develop a hybrid application. so if there are any other good technologies to achieve this goal i would love to know.
(React native ,.. etc )

Thanks in advance.

答:
You can use a File Opener Plugin for Cordova like fileOpener2
https://github.com/pwlin/cordova-plugin-file-opener2
in this way you can use the plugin: </p>

```<code>cordova.plugins.fileOpener2.open(
'/Download/starwars.pdf', // You can also use a Cordova-style file uri: cdvfile://localhost/persistent/Downloads/starwars.pdf
'application/pdf',
{
    error : function(e) {
        console.log('Error status: ' + e.status + ' - Error message: ' + e.message);
    },
    success : function () {
        console.log('file opened successfully');
    }
});
</code>```

Body:
I'm trying to create a hybrid application using Cordova to download a pdf file and need to read the downloaded file from application.

Now i'm trying to achieve this from cordova-plugin-inappbrowser .

window.open('https://www.google.com/search?q=sample+pdf+download&oq=sample+pdf+download', '_system', 'location=yes');

So with this code line i could download the file and view it internally on the app.

But i need to get the downloaded completed event and downloaded file name. Because i need to read the file internally.( might need a another plugin)

I need to develop a hybrid application. so if there are any other good technologies to achieve this goal i would love to know.
(React native ,.. etc )

Thanks in advance.

Body:
You can use a File Opener Plugin for Cordova like fileOpener2
https://github.com/pwlin/cordova-plugin-file-opener2
in this way you can use the plugin:

cordova.plugins.fileOpener2.open(
'/Download/starwars.pdf', // You can also use a Cordova-style file uri: cdvfile://localhost/persistent/Downloads/starwars.pdf
'application/pdf',
{
    error : function(e) {
        console.log('Error status: ' + e.status + ' - Error message: ' + e.message);
    },
    success : function () {
        console.log('file opened successfully');
    }
});


问:
How to create instance specific methods for each instance of a class?
I'm making a card game in C++ and I've made a a Button Class with an onClick() method. Every card is going to be a button, but I wan't each card to do something different when clicked. Is there a way to do this by somehow overriding the onClick() function for every instance, instead of creating 50 different class methods or 50 different classes?

I've tried creating a function for each different instance and passing it as a field in the class. Then, the onClick() function acts as a wrapper for each instance and calls the function passed as an argument in the Button constructor, but I'm trying to avoid adding a function argument in the Button constructor.

答:
There are many possible solutions. One that popped up in my min is that you could have an array of 50 function pointers (or rather std::function objects) that each point to a function to handle the specific "card". Or just have a single such std::function object that you initialize to the correct function in the constructor initializer list (for example).

And if there's very little differing between the functions, perhaps it would be wiser to collect it into a single function anyway, and have e.g. a switch statement to do the little specific pieces that differs?


问:
Docker-Compose: Unable to connect NodeJS with Mongo & Redis [Connection Refused]
I am working with 3 Services:

api-knotain [main api service]

api-mongo [mongo db for api service]

api-redis [redis for api service]

The Dockerfile for api-knotain looks as follows

```<code>FROM node:latest
# Create app directory
WORKDIR /usr/src/app
# Install app dependencies
# A wildcard is used to ensure both package.json AND package-lock.json are copied
# where available (npm@5+)
COPY package*.json ./
RUN npm install
# If you are building your code for production
# RUN npm ci --only=production
# Bundle app source
COPY . .
CMD [ "npm", "start" ]
</code>```

my docker-compose file as such:

```<code>version: '3.3'
services:
  api-knotain:
    container_name: api-knotain
    restart: always
    build: ../notify.apiV2/src
    ports:
      - "7777:7777"
    links:
      - api-mongo
      - api-redis
    environment:
      - REDIS_URI=api-redis
      - REDIS_PORT=32770
      - MONGO_URI=api-mongo
      - MONGO_PORT=27017
      - RESEED=true
      - NODE_TLS_REJECT_UNAUTHORIZED=0
  api-mongo:
    container_name: api-mongo
    image: mongo
    volumes:
      - ./data:/data/db
    ports:
      - "27017:27017"
  api-redis:
    container_name: api-redis
    image: "redis:alpine"
    ports:
      - "32770:32770"
</code>```

runnin

docker-compose build

docker-compose up

output:

```<code>api-knotain    | connecting mongo ...: mongodb://api-mongo:27017/notify
api-knotain    | Redis error: Error: Redis connection to api-redis:32770 failed - connect ECONNREFUSED 172.21.0.2:32770
api-knotain    | mongo error:MongoNetworkError: failed to connect to server [api-mongo:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 172.21.0.3:27017]
api-knotain    | Example app listening on port 7777!
</code>```

neither mongo nor redis can be connected.
I tried the following things:

use localhost instead of container name

use different ports

use expose vs port

always with the same result

note:

i can connect without issue to both mongo & redis through local cli 'localhost:port'

what am I missing?

答: It looks like depend_on did not properly work in 3.3 version of docker compose. after updating the version to 3.7 all works perfectly without any changes to the compose file.</p>

Body:
I am working with 3 Services:

api-knotain [main api service]

api-mongo [mongo db for api service]

api-redis [redis for api service]

The Dockerfile for api-knotain looks as follows

FROM node:latest
# Create app directory
WORKDIR /usr/src/app
# Install app dependencies
# A wildcard is used to ensure both package.json AND package-lock.json are copied
# where available (npm@5+)
COPY package*.json ./
RUN npm install
# If you are building your code for production
# RUN npm ci --only=production
# Bundle app source
COPY . .
CMD [ "npm", "start" ]

my docker-compose file as such:

version: '3.3'
services:
  api-knotain:
    container_name: api-knotain
    restart: always
    build: ../notify.apiV2/src
    ports:
      - "7777:7777"
    links:
      - api-mongo
      - api-redis
    environment:
      - REDIS_URI=api-redis
      - REDIS_PORT=32770
      - MONGO_URI=api-mongo
      - MONGO_PORT=27017
      - RESEED=true
      - NODE_TLS_REJECT_UNAUTHORIZED=0
  api-mongo:
    container_name: api-mongo
    image: mongo
    volumes:
      - ./data:/data/db
    ports:
      - "27017:27017"
  api-redis:
    container_name: api-redis
    image: "redis:alpine"
    ports:
      - "32770:32770"

runnin

docker-compose build

docker-compose up

output:

api-knotain    | connecting mongo ...: mongodb://api-mongo:27017/notify
api-knotain    | Redis error: Error: Redis connection to api-redis:32770 failed - connect ECONNREFUSED 172.21.0.2:32770
api-knotain    | mongo error:MongoNetworkError: failed to connect to server [api-mongo:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 172.21.0.3:27017]
api-knotain    | Example app listening on port 7777!

neither mongo nor redis can be connected.
I tried the following things:

use localhost instead of container name

use different ports

use expose vs port

always with the same result

note:

i can connect without issue to both mongo & redis through local cli 'localhost:port'

what am I missing?


答:
What you are asking for is commonly known as higher-order programming and function-objects

In c++, you may want to use eg. std::function(std-function)  and store that on the card class - like you say. But since you don't want to pass it in the constructor (why ?) you could make the member optional eg. std::optional<std::function<void()> >

Title: How to create instance specific methods for each instance of a class?

Body:
I'm making a card game in C++ and I've made a a Button Class with an onClick() method. Every card is going to be a button, but I wan't each card to do something different when clicked. Is there a way to do this by somehow overriding the onClick() function for every instance, instead of creating 50 different class methods or 50 different classes?

I've tried creating a function for each different instance and passing it as a field in the class. Then, the onClick() function acts as a wrapper for each instance and calls the function passed as an argument in the Button constructor, but I'm trying to avoid adding a function argument in the Button constructor.


问:
using proper join in oracle kindly solve the problem
these are the table sructuresi am trying to solve the question using outer join but cant

Display the saleman id and names of salesmen who have not made any sales.

答:
As this is for homework, you can do it in two ways.

```<code>select salesman.sid,salesman.sname
from salesman
where not exists (select sale.sid
                  from sale
                  where sale.id=salesman.sid)
</code>```

I am almost sure your teacher wants you to use not exists. But you can do it grouping too and counting the ones that have less than 1 results:

```<code>select salesman.sid,salesman.sname
from salesman left join sale on sale.sid=salesman.sid
group by salesman.sid,salesman.sname
having count(sale.saleid)<1
</code>```

Body:
As this is for homework, you can do it in two ways.

select salesman.sid,salesman.sname
from salesman
where not exists (select sale.sid
                  from sale
                  where sale.id=salesman.sid)

I am almost sure your teacher wants you to use not exists. But you can do it grouping too and counting the ones that have less than 1 results:

select salesman.sid,salesman.sname
from salesman left join sale on sale.sid=salesman.sid
group by salesman.sid,salesman.sname
having count(sale.saleid)<1


问:
Buffering of grouped items with RxJava
I'm trying to implement a stream handling with RxJava.
I want to handle different steps.

I start with a publish subject where sensors data are pushed

I want to group these sensors data by their sensor type (an identifier)

For each group I want to buffer these sensors data

When the buffer is full or times out, I want to compute an average from all sensors value in that group

And finally I want to re-join all these groups into one single output stream

So far with the code example below, I have a buffer that is shared for all sensors data. I don't understand how to create a buffer for each group and then do my computation. As I'm new to RxJava, I don't understand all the concepts and I'm stuck with my issue.

```<code>import io.reactivex.Observable;
import io.reactivex.subjects.PublishSubject;

import java.util.List;
import java.util.concurrent.TimeUnit;

public class Main {

    private static final int SENSOR_TEMPERATURE = 1;
    private static final int SENSOR_HUMIDITY = 2;

    private PublishSubject<Sensor> publishSubject = PublishSubject.create();

    static class Sensor {
        int type;
        float value;

        Sensor(int type, float value) {
            this.type = type;
            this.value = value;
        }
    }

    private PublishSubject<Sensor> listenSensors() {
        return publishSubject;
    }

    private static Sensor getValueAverage(List<Sensor> sensors) {
        int count = sensors.size();
        float total = sensors.stream().map(sensor -> sensor.value).reduce(Float::sum).orElse(0f);
        float avg = total / count;
        return new Sensor(sensors.get(0).type, avg);
    }

    //Map type
    private static String getStringType(int type) {
        if (type == SENSOR_HUMIDITY) {
            return "HUMIDITY";
        }
        else if (type == SENSOR_TEMPERATURE) {
            return "TEMPERATURE";
        }
        return "OTHER";
    }

    private static void emitRandomValue(PublishSubject<Sensor> sensorPublishSubject) throws InterruptedException {

        new Thread(() -> {
            int randomDelay = 0;

            while (true) {
                int randomType = (int) ((Math.random() * 10 % 2) + 1);
                randomDelay = (int) (Math.random() * 3000);
                float randomValue = (float) (Math.random() * 100);
                System.out.println("EMIT: " + getStringType(randomType) + " " + randomValue);
                sensorPublishSubject.onNext(new Sensor(randomType, randomValue));
                try {
                    Thread.sleep(randomDelay);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }).start();
    }
    static Observable<List<Sensor>> flatpMapSensor(List<Sensor> sensors) {
        return Observable
            .fromIterable(sensors)
            .groupBy(s -> s.type)
            .flatMapSingle(Observable::toList);
    }

    // Testing code
    static public void main(String args[]) throws InterruptedException {
        Main main = new Main();
        main.listenSensors()
            .publish(p -> p
                .buffer(20, TimeUnit.SECONDS, 10)
                .filter(list -> !list.isEmpty()))
            .flatMap(Main::flatpMapSensor)
            .map(Main::getValueAverage)
            .subscribe(sensor -> System.out.println("AVG " + getStringType(sensor.type) + " " + sensor.value));
        emitRandomValue(main.publishSubject);

        Thread.sleep(90000);

    }
}
</code>```

So my question is : How can I have a separate buffer for each sensor type ?

答:
What if you shift the buffer() and groupBy() calls?

static public void main(String args[]) throws InterruptedException {
   Main main = new Main();
   main.listenSensors()
       .groupBy(s -> s.type) // group by type
       .flatMap(l -> l.buffer(20, SECONDS, 10).map(Main::getValueAverage)) // buffer groups by type and compute the average
       .subscribe(sensor -> System.out.println("AVG " + getStringType(sensor.type) + " " + sensor.value));
   emitRandomValue(main.publishSubject);

   Thread.sleep(90000);
}
```

Title: Buffering of grouped items with RxJava

Body:
I'm trying to implement a stream handling with RxJava.
I want to handle different steps.

I start with a publish subject where sensors data are pushed

I want to group these sensors data by their sensor type (an identifier)

For each group I want to buffer these sensors data

When the buffer is full or times out, I want to compute an average from all sensors value in that group

And finally I want to re-join all these groups into one single output stream

So far with the code example below, I have a buffer that is shared for all sensors data. I don't understand how to create a buffer for each group and then do my computation. As I'm new to RxJava, I don't understand all the concepts and I'm stuck with my issue.

import io.reactivex.Observable;
import io.reactivex.subjects.PublishSubject;

import java.util.List;
import java.util.concurrent.TimeUnit;

public class Main {

    private static final int SENSOR_TEMPERATURE = 1;
    private static final int SENSOR_HUMIDITY = 2;

    private PublishSubject<Sensor> publishSubject = PublishSubject.create();

    static class Sensor {
        int type;
        float value;

        Sensor(int type, float value) {
            this.type = type;
            this.value = value;
        }
    }

    private PublishSubject<Sensor> listenSensors() {
        return publishSubject;
    }

    private static Sensor getValueAverage(List<Sensor> sensors) {
        int count = sensors.size();
        float total = sensors.stream().map(sensor -> sensor.value).reduce(Float::sum).orElse(0f);
        float avg = total / count;
        return new Sensor(sensors.get(0).type, avg);
    }

    //Map type
    private static String getStringType(int type) {
        if (type == SENSOR_HUMIDITY) {
            return "HUMIDITY";
        }
        else if (type == SENSOR_TEMPERATURE) {
            return "TEMPERATURE";
        }
        return "OTHER";
    }

    private static void emitRandomValue(PublishSubject<Sensor> sensorPublishSubject) throws InterruptedException {

        new Thread(() -> {
            int randomDelay = 0;

            while (true) {
                int randomType = (int) ((Math.random() * 10 % 2) + 1);
                randomDelay = (int) (Math.random() * 3000);
                float randomValue = (float) (Math.random() * 100);
                System.out.println("EMIT: " + getStringType(randomType) + " " + randomValue);
                sensorPublishSubject.onNext(new Sensor(randomType, randomValue));
                try {
                    Thread.sleep(randomDelay);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }).start();
    }
    static Observable<List<Sensor>> flatpMapSensor(List<Sensor> sensors) {
        return Observable
            .fromIterable(sensors)
            .groupBy(s -> s.type)
            .flatMapSingle(Observable::toList);
    }

    // Testing code
    static public void main(String args[]) throws InterruptedException {
        Main main = new Main();
        main.listenSensors()
            .publish(p -> p
                .buffer(20, TimeUnit.SECONDS, 10)
                .filter(list -> !list.isEmpty()))
            .flatMap(Main::flatpMapSensor)
            .map(Main::getValueAverage)
            .subscribe(sensor -> System.out.println("AVG " + getStringType(sensor.type) + " " + sensor.value));
        emitRandomValue(main.publishSubject);

        Thread.sleep(90000);

    }
}

So my question is : How can I have a separate buffer for each sensor type ?


Title: Calculating the modulus of large hexadecimal numbers without overflow

Body:
I'm trying to do some cryptography questions for signatures, but my values are hexadecimal and they're too high to be calculated on SageMaths without overflow in both python and sage. How would i get around this? My attempted sage code is below.

Trying it in python and sage

N = ZZ(0xe55c85be1e8f31b8cfa79da46e313545fe58d51308f427be1798373cce2304c0cee692f4ab78387dc5d3161b5a1f33df90858c5c0a8fe906579257043a527f33e37b3466b7929be81abec6e9979215abf92d71032caf5fffe4a5f1c176172d8fb62da7beecc255e45b75a44e30ebbeb91ecb97de7dc51a0c1d19f1cb0e5658b4a66cd4500252dc8f50076c357f5dece3f94ef1133cd2c592a5c9eb22a2e818f95252f0917caf47737807ece3a0f508f1af03b8eabd2f3d6cc881b27627e3cb5eda7862c25213592ebf1f8470dff22d7603d299ee69628101c75133d65618692aad5f3b2ffb3a22e1084a900cb0543107b02f8062737181eab4870cf25f0ed473cf4095530702314dd0a8cace3a6fd0169f2dfea254d3ab152381c3ae535f780a1b532fe040eae7ba864bf28543a6dec711e62878ec4471341c8ee00824e9cae7627c29de36f3678cbfe046dce37bd6c7639c51f9387e1b756bda7622efb9ee49fb258266b19fb359ef3f959ffabb0ebf3747bb923cf69899bfdcaba18bd4dbb7, 16)

D = ZZ(0x541af9701e04a45700ce962015c835a0d503fe1e5cca2b48a99e47a32473f2ea40f48c2eec31c98555657255d5565bcf3f4fb98886d6febc34a0950817dae88a3e808f569b3a47b1751d4013a861095166ae2322e6dfe8740d844c8284ab3b29d7c4261efcf2c64c56bd6ce2bf4db3426ee879683cf669f6c7351c55398cb03a8e4c9a0e3ccbe5d527a3912a8cea045414b7bdef2ffe9a348c56dec274ba676e05a224553543910fe6940169f73be36bbca1c0cd53525f53e4b2aa9e69423ef077b2d1bfe8d45927a677f74418240b95ed5c698e62fb429ece5fabbdcff8f64c480bff46bb6a448ae350739795abd156a5814378248b7100bfbaa07b039bc105a32a6fe74e07688577edecd515bd452a41cbfc017b9d26e76a5bec2ce433714a02f0f2c3784b65738adc849c3c31f8a731132e4bd8c2b2c0b33de87403c2b7ff12ab3d9582453844b4ff03142f899b256e407c3301adc46794d14bd668beac877e9cb5aa0602c447b75d3424d3a71495ed55a86fb1b01b5fbae2a766f6172301, 16)

M = ZZ(0x6b948843b86adb04a834cba6a76d5753da8ffbdcd01782a49d395f52f4c37a0cc39eeb41646ebc2b2003bacb203328e210604f248e02fa95aa6eec50751abe267f5c0b70f60901a4fd338f61bb2000acb3f2cf80d602acf85c5ee2f015667e9520e2d5c1aa84dcc69c9358a376846d2a0e9b52877fe17a76ce4bf6c46c7a46f61102d42869e0a594c4ad71a699a603654e4d6bdf83fc09b9741b70e82013302517efceebc9be49a7bc86ab89653f3281ffcc20824970410461510f4a9b538f8d5468b872cbef23a348b61576ae1f840138f14e7f8f13643aae1467cd534803555f8b2facb34fae15d53dc8c954bc8af0561597bfbb5a82c3b08bc83d349962aaaa6e164a138045b96dd9730aa7e1bb440838c42296ff2bdf53ca69f09c7e74c5e855455ffb052399e82e7e182d8efa08c96bdd166a00381d3fc53bb2a3d46b0aa6e2af8a45cd00e8bffe34fb7bafd20dade1efece7331b417136e2ed971c8f16e193948f3c6595e9f63a948610f1d3e2246e6603d0b039f9bdd50fc50baadef, 16)

Z = M^D

SIG = mod(Z, N)

print(SIG)

OverflowError: exponent must be at most 9223372036854775807


问:
Position imageView between two views and dynamically resize it to fit?
I have a simple layout with two buttons and a image view contained in a ConstraintLayout. The image view shows a vector graphic and is position between the two buttons horizontally.

```<code>____________
| Button    |
------------
____________
| ImageView |
------------
____________
| Button    |
------------
</code>```

The problem is that I cant seem to figure out how to properly constrain the image view vertically between the two buttons.

As long as I have layout_width and layout_height for the image view set to wrap_content the result will vary depending on the aspect ratio of the device display. I could set hardcoded height and width values but that also seems like a bad idea.

Isnt there some way to dynamically resize the ImageView based on the constraints?

```<code><ImageView
    android:id="@+id/imageView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/image"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@id/buttonTop"
    app:layout_constraintBottom_toTopOf="@id/buttonBottom"/>
</code>```

This works on tall aspect ratio devices but on small ones the bottom and/or top buttons overlap the imageView.

答: i think your layout width should be 0dp (match constraints).</p>

Body:
I have a simple layout with two buttons and a image view contained in a ConstraintLayout. The image view shows a vector graphic and is position between the two buttons horizontally.

____________
| Button    |
------------
____________
| ImageView |
------------
____________
| Button    |
------------

The problem is that I cant seem to figure out how to properly constrain the image view vertically between the two buttons.

As long as I have layout_width and layout_height for the image view set to wrap_content the result will vary depending on the aspect ratio of the device display. I could set hardcoded height and width values but that also seems like a bad idea.

Isnt there some way to dynamically resize the ImageView based on the constraints?

<ImageView
    android:id="@+id/imageView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/image"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@id/buttonTop"
    app:layout_constraintBottom_toTopOf="@id/buttonBottom"/>

This works on tall aspect ratio devices but on small ones the bottom and/or top buttons overlap the imageView.


问:
Redux-thunk dispatch function doesn't work on Laravel
I'm using React-Laravel for my project.
The problem is when I tried to use redux-thunk for the asynchronous dispatch function.
My dispatch function won't get executed.
Please do help me figure out this problem.

I have already tried to use promise or redux-devtools-extension library
https://codeburst.io/reactjs-app-with-laravel-restful-api-endpoint-part-2-aef12fe6db02

app.js

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import { createStore, combineReducers, applyMiddleware, compose } from 'redux';
import { Provider } from 'react-redux';
import thunk from 'redux-thunk';
import logger from 'redux-logger';

import Layout from './jsx/Layout/Layout';
import marketplaceReducer from './store/reducers/marketplace';

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

const appReducer = combineReducers({
    marketplace: marketplaceReducer
});

const rootReducer = (state, action) => {
    return appReducer(state, action);
}

const store = createStore(rootReducer, composeEnhancers(
    applyMiddleware(logger, thunk)
));

const render = (
    <Provider store={store}>
        <BrowserRouter>
            <Layout />
        </BrowserRouter>
    </Provider>
);

ReactDOM.render(render, document.getElementById('root'));
</code>```

marketplace.js (action)

```<code>import * as actionTypes from './actionTypes';
import axios from '../../axios';

export const loadMarketplace = () => {
    console.log("Load Marketplace");
    return {
        type: actionTypes.LOAD_MARKETPLACE
    };
}

export const successMarketplace = (data) => {
    console.log("Success Marketplace");
    return {
        type: actionTypes.SUCCESS_MARKETPLACE,
        data: data
    }
}

export const failedMarketplace = () => {
    console.log("Failed Marketplace");
    return {
        type: actionTypes.FAILED_MARKETPLACE
    }
}

export const showMarketplace = () => {
    console.log("Show Marketplace Action")
    return dispatch => {
        //This is the problem
        //Inside this function, I can't see any console.log, even loadMarketplace() didn't get called.
        console.log("Show Marketplace in dispatch");
        dispatch(loadMarketplace());
        axios.get('/marketplaces')
            .then(response => {
                dispatch(successMarketplace(response));
            })
            .catch(error => {
                dispatch(failedMarketplace());
            });
    };
}
</code>```

marketplace.js (reducer)

```<code>import * as actionTypes from '../actions/actionTypes';

const initial_state = {
    data: [],
    loading: false
}

const loadMarketplace = (state, action) => {
    console.log("Load Marketplace Reducer")
    return {
        ...state,
        loading: true
    };
}
const successMarketplace = (state, action) => {
    console.log("Success Marketplace Reducer", action.data)
    return {
        ...state,
        loading: false,
        data: action.data
    };
}

const failedMarketplace = (state, action) => {
    return {
        ...state,
        loading: false
    };
}

const reducer = (state = initial_state, action) => {
    //This is called when the first init, never got it through showMarketplace() function.
    console.log("Marketplace Reducer", action);
    switch (action.type) {
        case actionTypes.LOAD_MARKETPLACE: return loadMarketplace(state, action);
        case actionTypes.SUCCESS_MARKETPLACE: return successMarketplace(state, action);
        case actionTypes.FAILED_MARKETPLACE: return failedMarketplace(state, action);
        default: return state;
    }
}

export default reducer;
</code>```

Marketplace.js (jsx view)

```<code>import React, { Component } from 'react';
import { connect } from 'react-redux';

import * as actions from '../../../store/actions';

class Marketplace extends Component {
    componentDidMount() {
        console.log('[ComponentDidMount] Marketplace')
        this.props.showMarketplace();
    }

    render() {
        return (
            <React.Fragment>
                Marketplace
            </React.Fragment>
        );
    }
}

const mapDispatchToProps = dispatch => {
    return {
        showMarketplace: () => dispatch(actions.showMarketplace)
    };
}

export default connect(null, mapDispatchToProps)(Marketplace);
</code>```

This is the result of my console.log (when loading the first time for Marketplace.js)

Please do help, I've been struggling for 2 hours or more, only because of this problem. (This is my first time using React-Laravel).
Thank you.

答:
Edited: I think it is something about thunk is not added right to redux.

First of all try to add only thunk.

```<code>const store = createStore(rootReducer, composeEnhancers(
    applyMiddleware(thunk)
));
</code>```

If it works, maybe try to change the order of them.

Body:
I'm using React-Laravel for my project.
The problem is when I tried to use redux-thunk for the asynchronous dispatch function.
My dispatch function won't get executed.
Please do help me figure out this problem.

I have already tried to use promise or redux-devtools-extension library
https://codeburst.io/reactjs-app-with-laravel-restful-api-endpoint-part-2-aef12fe6db02

app.js

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import { createStore, combineReducers, applyMiddleware, compose } from 'redux';
import { Provider } from 'react-redux';
import thunk from 'redux-thunk';
import logger from 'redux-logger';

import Layout from './jsx/Layout/Layout';
import marketplaceReducer from './store/reducers/marketplace';

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

const appReducer = combineReducers({
    marketplace: marketplaceReducer
});

const rootReducer = (state, action) => {
    return appReducer(state, action);
}

const store = createStore(rootReducer, composeEnhancers(
    applyMiddleware(logger, thunk)
));

const render = (
    <Provider store={store}>
        <BrowserRouter>
            <Layout />
        </BrowserRouter>
    </Provider>
);

ReactDOM.render(render, document.getElementById('root'));

marketplace.js (action)

import * as actionTypes from './actionTypes';
import axios from '../../axios';

export const loadMarketplace = () => {
    console.log("Load Marketplace");
    return {
        type: actionTypes.LOAD_MARKETPLACE
    };
}

export const successMarketplace = (data) => {
    console.log("Success Marketplace");
    return {
        type: actionTypes.SUCCESS_MARKETPLACE,
        data: data
    }
}

export const failedMarketplace = () => {
    console.log("Failed Marketplace");
    return {
        type: actionTypes.FAILED_MARKETPLACE
    }
}

export const showMarketplace = () => {
    console.log("Show Marketplace Action")
    return dispatch => {
        //This is the problem
        //Inside this function, I can't see any console.log, even loadMarketplace() didn't get called.
        console.log("Show Marketplace in dispatch");
        dispatch(loadMarketplace());
        axios.get('/marketplaces')
            .then(response => {
                dispatch(successMarketplace(response));
            })
            .catch(error => {
                dispatch(failedMarketplace());
            });
    };
}

marketplace.js (reducer)

import * as actionTypes from '../actions/actionTypes';

const initial_state = {
    data: [],
    loading: false
}

const loadMarketplace = (state, action) => {
    console.log("Load Marketplace Reducer")
    return {
        ...state,
        loading: true
    };
}
const successMarketplace = (state, action) => {
    console.log("Success Marketplace Reducer", action.data)
    return {
        ...state,
        loading: false,
        data: action.data
    };
}

const failedMarketplace = (state, action) => {
    return {
        ...state,
        loading: false
    };
}

const reducer = (state = initial_state, action) => {
    //This is called when the first init, never got it through showMarketplace() function.
    console.log("Marketplace Reducer", action);
    switch (action.type) {
        case actionTypes.LOAD_MARKETPLACE: return loadMarketplace(state, action);
        case actionTypes.SUCCESS_MARKETPLACE: return successMarketplace(state, action);
        case actionTypes.FAILED_MARKETPLACE: return failedMarketplace(state, action);
        default: return state;
    }
}

export default reducer;

Marketplace.js (jsx view)

import React, { Component } from 'react';
import { connect } from 'react-redux';

import * as actions from '../../../store/actions';

class Marketplace extends Component {
    componentDidMount() {
        console.log('[ComponentDidMount] Marketplace')
        this.props.showMarketplace();
    }

    render() {
        return (
            <React.Fragment>
                Marketplace
            </React.Fragment>
        );
    }
}

const mapDispatchToProps = dispatch => {
    return {
        showMarketplace: () => dispatch(actions.showMarketplace)
    };
}

export default connect(null, mapDispatchToProps)(Marketplace);

This is the result of my console.log (when loading the first time for Marketplace.js)

Please do help, I've been struggling for 2 hours or more, only because of this problem. (This is my first time using React-Laravel).
Thank you.

Body:
Edited: I think it is something about thunk is not added right to redux.

First of all try to add only thunk.

const store = createStore(rootReducer, composeEnhancers(
    applyMiddleware(thunk)
));

If it works, maybe try to change the order of them.


答:
You can first group by keys and then you need to sort based on index

const lists = [{ groupKey: 'ABC', key: 'r8', timestamp: '2014', index: 2 },{ groupKey: 'ABC', key: 'q8', timestamp: '2012', index: 0 }, { groupKey: 'ABC', key: 'w8', timestamp: '2013', index: 1 },{ groupKey: 'CDE', key: 'r7', timestamp: '2019', index: 0 } ]

// group by groupkey
let grouped = lists.reduce((op, inp) => {
  let groupKey = inp.groupKey
  op[groupKey] = op[groupKey] || []
  op[groupKey].push(inp)
  return op
},{})

// sort by index
let output = Object.entries(grouped).reduce((op,[key,value]) => {
  value = value.sort((a,b)=> a.index-b.index)
  op[key] = value
  return op
},{})

console.log(output)```

Body:
I know that, there are countless of questions about group by one property from an array of object. But what I want to do is a litte more specific:

const lists = [
{ groupKey: 'ABC', key: 'r8', timestamp: '2014', index: 2 },
{ groupKey: 'ABC', key: 'q8', timestamp: '2012', index: 0 },
{ groupKey: 'ABC', key: 'w8', timestamp: '2013', index: 1 },
{ groupKey: 'CDE', key: 'r7', timestamp: '2019', index: 0 }
]

Result should be grouped by groupKey and sorted by index

(indexes here are iterators 0,1,2,3... so no need to actually be sorted but rather to be placed in a right order of an array. Example: array[index] = ... ).

This should look like:

{
  ABC: [
    {  key: 'q8', timestamp: '2012', index: 0 },
    {  key: 'w8', timestamp: '2013', index: 1 },
    {  key: 'r8', timestamp: '2014', index: 2 }
  ],
  CDE: [
    { key: 'r7', timestamp: '2019', index: 0 }
  ]
}

I have tried to group by without sorting:

const result = lists.reduce((r, item) => {
      let { groupKey, ...rest } = item
      r[item.groupKey] = [...(r[item.groupKey] || []), rest]
      return r
    }, {})

And with sorting, not successful but you know what I mean:

const result = lists.reduce((r, item) => {
          let { groupKey, ...rest } = item
          r[item.groupKey][item.index] = rest //err: can not set property 2 of undefined
          return r
        }, {})

Any suggestions are appreciated


问:
Left swipe for delete and edit,delete
I am not able to find a way around this. Is it possible to have delete option using left swipe and also using edit and delete.

I have edit button on the left of the navigation bar.

```<code>self.navigationItem.leftBarButtonItem = self.editButtonItem;
</code>```

and commitEditingStyle method as below

```<code>- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

    if (editingStyle == UITableViewCellEditingStyleDelete) {
//delete code here
    }
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
    // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }
</code>```

}

After using this, the left swipe is not being detected at all. the only way to delete seems to be by going to the edit mode and deleting from there.
help would be appreciated.

I am a newbie so please go easy with me :)

答:
Make sure you have all of the delegates implemented below

```<code>tableView:commitEditingStyle:forRowAtIndexPath:
tableView:canEditRowAtIndexPath:
tableView:editingStyleForRowAtIndexPath
</code>```

:

Title: Left swipe for delete and edit,delete

Body:
I am not able to find a way around this. Is it possible to have delete option using left swipe and also using edit and delete.

I have edit button on the left of the navigation bar.

self.navigationItem.leftBarButtonItem = self.editButtonItem;

and commitEditingStyle method as below

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

    if (editingStyle == UITableViewCellEditingStyleDelete) {
//delete code here
    }
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
    // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }

}

After using this, the left swipe is not being detected at all. the only way to delete seems to be by going to the edit mode and deleting from there.
help would be appreciated.

I am a newbie so please go easy with me :)

Body:
Make sure you have all of the delegates implemented below

tableView:commitEditingStyle:forRowAtIndexPath:
tableView:canEditRowAtIndexPath:
tableView:editingStyleForRowAtIndexPath

:


问:
How to set up web.xml and dispatcher-servlet.xml for mapping?
I want to change from @WebServlet Mapping to SpringMVC Mapping. To get comfortable with things I set up an easy simple LoginApplication with use of @WebServlet.

Now I wanted to do the switch to springMVC by adding web.xml and dispatcher-servlet.xml

I have added all necessary dependencies to my build path, including commons-logging, jstl, servlet-api, spring-aop, spring-beans, spring-context, spring-core, spring-expression, spring-web and spring-webmvc. I added @Controller @RequestMapping("XXXXX") annotations to my controllers and @GetMapping to the methods performing redirects and stuff.

Part of my web.xml:

```<code><servlet>
        <servlet-name>sobster</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/sobster-servlet.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>sobster</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</code>```

Part of my sobster-servlet.xml:

```<code>    <context:component-scan base-package="com.sobster" />
    <mvc:annotation-driven />
</code>```

Where com.sobster is my package containing the controllers

Part of a controller:

```<code>    @RequestMapping("/")
    @Controller
    public class StartPageController extends HttpServlet {
      private static final long serialVersionUID = 1L;

      @GetMapping
      protected void doGet(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
        response.sendRedirect("login.jsp");
      }

    }
</code>```

I expected any request now to get handled by web.xml which looks up sobster-servlet.xml to get the controllers. sobster-servlet.xml now checks controllers in com.sobster and performs according action (redirecting to login.jsp after receiving call from "/" for example).

But all I get is HTTP Status 404 – Not Found

I appreciate any suggestions :-)

答:
The starPageController class should be like the below code. The response of the method login will redirect to loginPage.jsp. The complete URL is decided by the InternalResourceViewResolver class which is configured below

```<code>import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping(value = "/login")
public class StartPageController {
    @RequestMapping(method = RequestMethod.GET)
   public String login(HttpServletRequest req, HttpServletResponse response,ModelMap model) throws Exception {
       return "loginPage";
   }
}
</code>```

The sobster-servlet.xml should look like below. The bean class InternalResourceViewResolver is for redirecting to the jsp page with prefix as /pages and the suffix .jsp will now has the redirect path to "/pages/loginPage.jsp" within the war file.

```<code><beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-4.0.xsd
   http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

    <context:component-scan
        base-package="com.sobster" />
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/pages/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>
</code>```

Body:
I want to change from @WebServlet Mapping to SpringMVC Mapping. To get comfortable with things I set up an easy simple LoginApplication with use of @WebServlet.

Now I wanted to do the switch to springMVC by adding web.xml and dispatcher-servlet.xml

I have added all necessary dependencies to my build path, including commons-logging, jstl, servlet-api, spring-aop, spring-beans, spring-context, spring-core, spring-expression, spring-web and spring-webmvc. I added @Controller @RequestMapping("XXXXX") annotations to my controllers and @GetMapping to the methods performing redirects and stuff.

Part of my web.xml:

<servlet>
        <servlet-name>sobster</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/sobster-servlet.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>sobster</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

Part of my sobster-servlet.xml:

    <context:component-scan base-package="com.sobster" />
    <mvc:annotation-driven />

Where com.sobster is my package containing the controllers

Part of a controller:

    @RequestMapping("/")
    @Controller
    public class StartPageController extends HttpServlet {
      private static final long serialVersionUID = 1L;

      @GetMapping
      protected void doGet(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
        response.sendRedirect("login.jsp");
      }

    }

I expected any request now to get handled by web.xml which looks up sobster-servlet.xml to get the controllers. sobster-servlet.xml now checks controllers in com.sobster and performs according action (redirecting to login.jsp after receiving call from "/" for example).

But all I get is HTTP Status 404 – Not Found

I appreciate any suggestions :-)

Body:
The starPageController class should be like the below code. The response of the method login will redirect to loginPage.jsp. The complete URL is decided by the InternalResourceViewResolver class which is configured below

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping(value = "/login")
public class StartPageController {
    @RequestMapping(method = RequestMethod.GET)
   public String login(HttpServletRequest req, HttpServletResponse response,ModelMap model) throws Exception {
       return "loginPage";
   }
}

The sobster-servlet.xml should look like below. The bean class InternalResourceViewResolver is for redirecting to the jsp page with prefix as /pages and the suffix .jsp will now has the redirect path to "/pages/loginPage.jsp" within the war file.

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-4.0.xsd
   http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

    <context:component-scan
        base-package="com.sobster" />
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/pages/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>


问:
Large memory usage slows down unrelated code
I am maintaing the code for a Go project that reads and writes a lot of data and that has done so successfully for some time. Recently, I made a change: a CSV file with about 2 million records is loaded in a map with struct values at the beginning of the program. This map is only used in part B, but first part A is executed. And this first part already runs noticeably slower than before (processing time is quadrupled). That is very strange since that part of the logic did not change.
I have spent a week trying to explain how this can happen. Here are the steps I have taken (when I mention performance, I always refer to part A, which does not include the time to load the data in memory and actually has nothing to do with it):

The program was running on a server inside a Docker container. But I have been able to reproduce it on my laptop without container: the performance indeed decreases compared to when I run it without the data from the file loaded in memory.

The server had a huge amount of RAM. Although obviously more memory is used when the file is loaded, no limits are hit. I also did not see spikes or other strange patterns in memory usage and disk I/O. For these checks, I have used pprof, htop and iotop.

When the data is loaded but then the map set to nil, performance is OK again.

Loading the data in a slice instead of a map reduces the performance decrease from x4 to x2 (but the memory usage is more or less the same as with the map).

This made me wonder whether the map/slice is accessed somewhere in part A, even though it shouldn’t. The map is stored in a field of a struct type. I checked and this struct is always passed by pointer (including all goroutines). Making it a global variable instead of a pointer field did not solve the issue.

There is one dependency outside of the standard library. Is the problem caused by the library? It forces some garbage collects. Disabling this does not make a difference. I found another similar library that is unrelated and using this one as a replacement improves performance, but it still takes longer when the data of the file is loaded.

Here I have plotted the metrics with and without the data in memory:

What could cause this effect or how do I find it out?

答:
So if I get this right, your flow looks something like this:

Read 2 million rows from CSV into map -> struct

Run part A (which doesn't need data from CSV)

Run part B, using data from CSV

Why read the data before you need it, would be the first question, but that's perhaps besides the point.

What is likely is that 2 million structs in a map are routinely being accessed by the garbage collector, actually. Depending on what value GOGC has, the pacer component of the garbage collector is likely to kick in more often as the amount of memory allocated increases. Because this map is set aside for later use, there's nothing for the GC to do, but it's taking up cycles in checking the data regardless. There's a number of things you could do to verify, and account for this behaviour - all of these things should can help you rule out/confirm whether or not garbage collection is slowing you down.

Profile the code (obviously, important for diagnostics) IIRC, the CPU profile shows GC interventions more readily

Try disabling garbage collection (debug.SetGCPercent(-1))

Store the map in a sync.Pool. This is a type designed for you to keep stuff you'll manage manually, and move outside of regular GC cycles.

Only read the CSV when you need to, don't read it before "part A"

Stream the file, instead of reading it in a massive map. 2 million rows, what's the value of reading all of this in memory, rather than reading line by line?


问:
C# database update
I'm stuck on a little problem concerning database.

Once a month I get a XML file with customer information (Name, address, city,etc.). My primary key is a customer number which is provided in the XML file.

I have no trouble inserting the information in the database;

```<code>var cmd = new SqlCommand("insert into [customer_info]
   (customer_nr, firstname, lastname, address_1, address_2, address_3.......)");
//some code
cmd.ExecuteNonQuery();
</code>```

Now, I would like to update my table or just fill it with new information. How can I achieve this?

I've tried using TableAdapter but it does not work.

And I'm only permitted to add one XML because I can only have one customer_nr as primary key.

So basically how do I update or fill my table with new information?

Thanks.

答:
If I understand your question correctly - if the customer already exists you want to update their information, and if they don't already exist you want to insert a new row.

I have a lot of problems with hard-coded SQL commands in your code, so I would firstly be very tempted to refactor what you have done.  However, to achieve what you want, you will need to execute a SELECT on the primary key, if it returns any results you should execute an UPDATE else you should execute an INSERT.

It would be best to do this in something like a Stored Procedure - you can pass the information to the stored procedure at then it can make a decision on whether to UPDATE or INSERT - this would also reduce the overhead of making several calls for your code to the database (A stored procedure would be much quicker)

Title: C# database update

Body:
I'm stuck on a little problem concerning database.

Once a month I get a XML file with customer information (Name, address, city,etc.). My primary key is a customer number which is provided in the XML file.

I have no trouble inserting the information in the database;

var cmd = new SqlCommand("insert into [customer_info]
   (customer_nr, firstname, lastname, address_1, address_2, address_3.......)");
//some code
cmd.ExecuteNonQuery();

Now, I would like to update my table or just fill it with new information. How can I achieve this?

I've tried using TableAdapter but it does not work.

And I'm only permitted to add one XML because I can only have one customer_nr as primary key.

So basically how do I update or fill my table with new information?

Thanks.


问:
I have created a desktop assistant program but every time i run the program i keep getting this error. kindly help me
when i try to install pyaudio it is also showing the following error

Running setup.py clean for pyaudio Failed to build pyaudio Installing
  collected packages: pyaudio   Running setup.py install for pyaudio ...
  error
      Complete output from command c:\users\hp\appdata\local\programs\python\python37\python.exe -u -c
  "import setuptools,
  tokenize;file='C:\Users\HP\AppData\Local\Temp\pip-install-okii4l8n\pyaudio\setup.py';f=getattr(tokenize,
  'open', open)(file);code=f.read().replace('\r\n',
  '\n');f.close();exec(compile(code, file, 'exec'))" install
  --record C:\Users\HP\AppData\Local\Temp\pip-record-fpl5yt23\install-record.txt
  --single-version-externally-managed --compile:
      running install
      running build
      running build_py
      creating build
      creating build\lib.win-amd64-3.7
      copying src\pyaudio.py -> build\lib.win-amd64-3.7
      running build_ext
      building '_portaudio' extension
      error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools":
  http://landinghub.visualstudio.com/visual-cpp-build-tools

I have also tried to execute this in many different ids but it is not properly working.

Traceback (most recent call last):   File
  "C:\Users\HP\AppData\Local\Programs\Python\Python37\lib\site-packages\speech_recognition__init__.py",
  line 108, in get_pyaudio
      import pyaudio ModuleNotFoundError: No module named 'pyaudio'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):   File "E:/study material/python
  programs/practice programs/jarvis2.py", line 66, in
      query = takeCommand().lower()   File "E:/study material/python programs/practice programs/jarvis2.py", line 38, in takeCommand
      with sr.Microphone() as source:   File "C:\Users\HP\AppData\Local\Programs\Python\Python37\lib\site-packages\speech_recognition__init__.py",
  line 79, in init
      self.pyaudio_module = self.get_pyaudio()   File "C:\Users\HP\AppData\Local\Programs\Python\Python37\lib\site-packages\speech_recognition__init__.py",
  line 110, in get_pyaudio
      raise AttributeError("Could not find PyAudio; check installation") AttributeError: Could not find PyAudio; check installation

答:
It seems that you need "Microsoft Visual C++ Build Tools" from the website listed, but PyAudio is kinda broken...

I had the same error, so what you could do is create a condition that activates a text command line.
I have a similar code to yours on https://github.com/PythonGuy888/ATLAS where I created said condition as the PC I'm developing the code on can't install PyAudio either.


问:
Python) How to convert string to dict? (Strange type of string)
The string is..

```<code>{
   "version":"20131101",
   "logo":"http://image.aladin.co.kr/img/header/2011/aladin_logo_new.gif",
   "title":"알라딘 베스트셀러 리스트 - 철학사",
   "link":"http:\/\/www.aladin.co.kr\/shop\/common\/wbest.aspx?BestType=Bestseller&BranchType=1&CID=51441&Year=2019&Month=5&Week=4&partner=openAPI",
   "pubDate":"Mon, 27 May 2019 10:33:33 GMT",
   "totalResults":955,
   "startIndex":1,
   "itemsPerPage":10,
   "query":"QueryType=BESTSELLER;CategoryId=51441;Year=2019;Month=5;Week=4",
   "searchCategoryId":51441,
   "searchCategoryName":"철학사",
   "item":[
      {
         "title":"처음 읽는 서양철학사 (개정증보판) - 서양의 대표 철학자 40인과 시작하는 철학의 첫걸음",
         "link":"http:\/\/www.aladin.co.kr\/shop\/wproduct.aspx?ItemId=100442130&partner=openAPI&start=api",
         "author":"안광복 (지은이)",

      }
   ]
}
</code>```

I wanna convert string to dict.

This is what I want

I want to make this whole string to dictionary, So I want to get the value of "item"

```<code>"item" : [{"title: ", " : ", ... }, {"title: ", " : ", ...  }, { "title: ", " : ", ... }]
</code>```

I want the dictionaries(looks like dictionary but string) in the list(looks like list but str) so i want to use like dictionary

```<code>print(decoding_bestseller.find("item",370))
b=decoding_bestseller.split('"item"')
want_str=b[1]
want_str1=want_str.strip(':[]{}')
want_list=want_str1.split(',')
book_dic = {}
for i in range(0,len(want_list)):
    in_colon = ":" in want_list[i]
    if in_colon:
        split_list = want_list[i].split(':')
        book_key = split_list[0].strip('""')
        book_value = split_list[1].strip('""')
        book_dic[book_key] = book_value
</code>```

I did like that but I failed.

The string is like this
    {" : ", " : ", "item : [ {"title : ", "link : ", } {"title : ", "link : ",  }, " : "}

i want to make {"title : ", "link : ", ...} to REAL dictionary!

答:
Format of string you've provided is JSON. There's json module in python, which has function loads(). This function will convert your string to dict object.

But there's one problem in string you provided:

"author":"안광복 (지은이)">>>,<<<}]}

This coma violates JSON stardart and causes error in decoder. If it's just typo, than just delete it. If source string really contains this, you should delete it from string before decoding (i.g. string.replace(",}", "}"))

How to decode:

```<code>import json

string = """{
   "version":"20131101",
   "logo":"http://image.aladin.co.kr/img/header/2011/aladin_logo_new.gif",
   "title":"알라딘 베스트셀러 리스트 - 철학사",
   "link":"http:\/\/www.aladin.co.kr\/shop\/common\/wbest.aspx?BestType=Bestseller&BranchType=1&CID=51441&Year=2019&Month=5&Week=4&partner=openAPI",
   "pubDate":"Mon, 27 May 2019 10:33:33 GMT",
   "totalResults":955,
   "startIndex":1,
   "itemsPerPage":10,
   "query":"QueryType=BESTSELLER;CategoryId=51441;Year=2019;Month=5;Week=4",
   "searchCategoryId":51441,
   "searchCategoryName":"철학사",
   "item":[
      {
         "title":"처음 읽는 서양철학사 (개정증보판) - 서양의 대표 철학자 40인과 시작하는 철학의 첫걸음",
         "link":"http:\/\/www.aladin.co.kr\/shop\/wproduct.aspx?ItemId=100442130&partner=openAPI&start=api",
         "author":"안광복 (지은이)"
      }
   ]
}"""

object_from_string = json.loads(string)

value_of_item = object_from_string["item"]

for value in value_of_item:
    for k, v in value.items():
        print(f"{k} = {v}")
</code>```

Output:

```<code>title = 처음 읽는 서양철학사 (개정증보판) - 서양의 대표 철학자 40인과 시작하는 철학의 첫걸음
link = http://www.aladin.co.kr/shop/wproduct.aspx?ItemId=100442130&partner=openAPI&start=api
author = 안광복 (지은이)
</code>```

Body:
The string is..

{
   "version":"20131101",
   "logo":"http://image.aladin.co.kr/img/header/2011/aladin_logo_new.gif",
   "title":"알라딘 베스트셀러 리스트 - 철학사",
   "link":"http:\/\/www.aladin.co.kr\/shop\/common\/wbest.aspx?BestType=Bestseller&BranchType=1&CID=51441&Year=2019&Month=5&Week=4&partner=openAPI",
   "pubDate":"Mon, 27 May 2019 10:33:33 GMT",
   "totalResults":955,
   "startIndex":1,
   "itemsPerPage":10,
   "query":"QueryType=BESTSELLER;CategoryId=51441;Year=2019;Month=5;Week=4",
   "searchCategoryId":51441,
   "searchCategoryName":"철학사",
   "item":[
      {
         "title":"처음 읽는 서양철학사 (개정증보판) - 서양의 대표 철학자 40인과 시작하는 철학의 첫걸음",
         "link":"http:\/\/www.aladin.co.kr\/shop\/wproduct.aspx?ItemId=100442130&partner=openAPI&start=api",
         "author":"안광복 (지은이)",

      }
   ]
}

I wanna convert string to dict.

This is what I want

I want to make this whole string to dictionary, So I want to get the value of "item"

"item" : [{"title: ", " : ", ... }, {"title: ", " : ", ...  }, { "title: ", " : ", ... }]

I want the dictionaries(looks like dictionary but string) in the list(looks like list but str) so i want to use like dictionary

print(decoding_bestseller.find("item",370))
b=decoding_bestseller.split('"item"')
want_str=b[1]
want_str1=want_str.strip(':[]{}')
want_list=want_str1.split(',')
book_dic = {}
for i in range(0,len(want_list)):
    in_colon = ":" in want_list[i]
    if in_colon:
        split_list = want_list[i].split(':')
        book_key = split_list[0].strip('""')
        book_value = split_list[1].strip('""')
        book_dic[book_key] = book_value

I did like that but I failed.

The string is like this
    {" : ", " : ", "item : [ {"title : ", "link : ", } {"title : ", "link : ",  }, " : "}

i want to make {"title : ", "link : ", ...} to REAL dictionary!

Body:
Format of string you've provided is JSON. There's json module in python, which has function loads(). This function will convert your string to dict object.

But there's one problem in string you provided:

"author":"안광복 (지은이)">>>,<<<}]}

This coma violates JSON stardart and causes error in decoder. If it's just typo, than just delete it. If source string really contains this, you should delete it from string before decoding (i.g. string.replace(",}", "}"))

How to decode:

import json

string = """{
   "version":"20131101",
   "logo":"http://image.aladin.co.kr/img/header/2011/aladin_logo_new.gif",
   "title":"알라딘 베스트셀러 리스트 - 철학사",
   "link":"http:\/\/www.aladin.co.kr\/shop\/common\/wbest.aspx?BestType=Bestseller&amp;BranchType=1&amp;CID=51441&amp;Year=2019&amp;Month=5&amp;Week=4&amp;partner=openAPI",
   "pubDate":"Mon, 27 May 2019 10:33:33 GMT",
   "totalResults":955,
   "startIndex":1,
   "itemsPerPage":10,
   "query":"QueryType=BESTSELLER;CategoryId=51441;Year=2019;Month=5;Week=4",
   "searchCategoryId":51441,
   "searchCategoryName":"철학사",
   "item":[
      {
         "title":"처음 읽는 서양철학사 (개정증보판) - 서양의 대표 철학자 40인과 시작하는 철학의 첫걸음",
         "link":"http:\/\/www.aladin.co.kr\/shop\/wproduct.aspx?ItemId=100442130&amp;partner=openAPI&amp;start=api",
         "author":"안광복 (지은이)"
      }
   ]
}"""

object_from_string = json.loads(string)

value_of_item = object_from_string["item"]

for value in value_of_item:
    for k, v in value.items():
        print(f"{k} = {v}")

Output:

title = 처음 읽는 서양철학사 (개정증보판) - 서양의 대표 철학자 40인과 시작하는 철학의 첫걸음
link = http://www.aladin.co.kr/shop/wproduct.aspx?ItemId=100442130&amp;partner=openAPI&amp;start=api
author = 안광복 (지은이)