问:
How to create a branch with two parents
I have two dev branches, dev_common and dev_huawei(variant for special device). There are only few differences between them, so I need a master branch which parents are these two dev branches to commit public features.

For example, I create feature branch from master branch and do some public changes. Then, I can start pull request A(feature into dev_common) and pull request B(feature into dev_huawei) at the same time. My purpose is to avoid creating feature_common and feature_huawei with the same changes.

I've only used git before in a very basic form. Is my "For example" feasible? What is this operation called? Rebase or something else? Can I have my master with two parents in GUI(Sourcetree and Github)?

Thanks.

dev_common:

line1 for common device

line2 some public features

dev_huawei:

line1 for huawei device

line2 some public features

I start a new branch feature from master, and commit my change:

+line3 a new public feature

Merge feature into dev_common(commit1). Now dev_common is

line1 for common device

line2 some public features

line3 a new public feature

Merge feature into dev_huawei(commit2). Now dev_huawei is

line1 for huawei device // Here it does not mess up what should be kept

line2 some public features

line3 a new public feature

Merge dev_common into master, and I can begin from master again when add next feature.

答:
If I understand your question : you need the master branch to have both content from the dev_common branch and dev_huawei branch

in this case, you can do the following :

go to a one of the branches : let's go to dev_common branch (if you have uncommitted files in the current branch, make sure to commit them before you switch to other branch)

```<code>git switch dev_common
</code>```

then merge the content from dev_huawei to the current branch by : (this can give some merge conflicts, so fix them and continue

```<code>git merge dev_huawei
</code>```

and then go to the master branch and run

```<code>git merge dev_common
</code>```

This can give other conflicts, but if the master branch is the starting point without any commit that they are not in the other branchs, Git will do a fast-forward, and you'll not have any merge conflict.

Title: How to create a branch with two parents

Body:
If I understand your question : you need the master branch to have both content from the dev_common branch and dev_huawei branch

in this case, you can do the following :

go to a one of the branches : let's go to dev_common branch (if you have uncommitted files in the current branch, make sure to commit them before you switch to other branch)

git switch dev_common

then merge the content from dev_huawei to the current branch by : (this can give some merge conflicts, so fix them and continue

git merge dev_huawei

and then go to the master branch and run

git merge dev_common

This can give other conflicts, but if the master branch is the starting point without any commit that they are not in the other branchs, Git will do a fast-forward, and you'll not have any merge conflict.


来源: stackexchange

问:
Scrapy returns only the first product for each page
I try to learn Scrapy but I am stuck for 3 days with a problem, maybe some of you could help me with a solution or a suggestion.
I try to extract all the products from one category of a site, and for each product, I want only 3 categories: 2 from the main page when all the products are set, and 1 category from the details of the product(this is the cod of the product); and for this, I have accessed the link of each product.
All extracted products go to ItemLoader.
In the Items file, I have used the MapComposer and TakeFirst processor for all the items.

The problem is that my code extracts only the first product from each page.

This is the code:

```<code>import os
import scrapy
from scrapy.loader import ItemLoader
from ..items import CutotulItem

class CutotulSpiderLoader(scrapy.Spider):
    name = 'cutotul_spider_loader'
    start_urls = ['https://cutotul.ro/39-karcher-aspiratoare-profesionale']

    def __init__(self):
        self.model = ""

    def start_requests(self):
        yield scrapy.Request('https://cutotul.ro/39-karcher-aspiratoare-profesionale', callback=self.parse)

    def parse(self, response):
        products = response.css("div.columns-container")
        for product in products:
            # get details link
            details_link = product.xpath("//a[@class='lnk_view btn btn-default']/@href").get()

            # get details
            yield response.follow(url=details_link, callback=self.parse_details)
            product_name_xpath = "//span[@class='grid-name']/text()"
            product_price_xpath = "//span[@class='price product-price']/text()"
            product_model_xpath = "".join(self.model)

            # loader
            loader = ItemLoader(item=CutotulItem(), selector=product, response=response)
            loader.add_xpath("product_name", product_name_xpath)
            loader.add_xpath("product_price", product_price_xpath)
            loader.add_value("product_model", product_model_xpath)
            yield loader.load_item()

        # nav to next page
        # Get the next response for x items from the next page - persist until no more #

        next_page = response.xpath("//li[@class='pagination_next']//@href").get()
        if next_page:
            yield response.follow(url=next_page, callback=self.parse)

    def parse_details(self, response):
        # set variable to response for model
        self.model = response.css("span[itemprop='sku']").css("::text").get()
</code>```

How can I solve this problem?

Thanks a lot!

答:
You need to use relative xpath for each product (eg .//a instead of //a).

You aren't looping over the items, products is just the container of those items.

parse_details won't work - scrapy is asynchronous so it won't wait for self.model to update and you'll get an empty string. I fixed it as an example but you can fixed it however you want.

What's left for you to do is to check if the pagination works (I didn't check it), and fix (if you want) the price's format.

import os
import scrapy
from scrapy.loader import ItemLoader
# from ..items import CutotulItem

class CutotulItem(scrapy.Item):
    product_name = scrapy.Field()
    product_price = scrapy.Field()
    product_model = scrapy.Field()

class CutotulSpiderLoader(scrapy.Spider):
    name = 'cutotul_spider_loader'
    start_urls = ['https://cutotul.ro/39-karcher-aspiratoare-profesionale']

    def __init__(self):
        self.model = ""

    def start_requests(self):
        yield scrapy.Request('https://cutotul.ro/39-karcher-aspiratoare-profesionale', callback=self.parse)

    async def parse(self, response):
        # products = response.css("div.columns-container")
        products = response.css('div.product-container')
        for product in products:
            # get details link
            details_link = product.xpath(".//a[@class='lnk_view btn btn-default']/@href").get()

            # get details
            # yield response.follow(url=details_link, callback=self.parse_details)
            req = response.follow(url=details_link)
            resp = await self.crawler.engine.download(req, self)
            self.model = resp.css("span[itemprop='sku']").css("::text").get()

            product_name_xpath = ".//span[@class='grid-name']/text()"
            product_price_xpath = ".//span[@class='price product-price']/text()"
            product_model_xpath = "".join(self.model)

            # loader
            loader = ItemLoader(item=CutotulItem(), selector=product, response=response)
            loader.add_xpath("product_name", product_name_xpath)
            loader.add_xpath("product_price", product_price_xpath)
            loader.add_value("product_model", product_model_xpath)
            yield loader.load_item()

        # nav to next page
        # Get the next response for x items from the next page - persist until no more #

        next_page = response.xpath("//li[@class='pagination_next']//@href").get()
        if next_page:
            yield response.follow(url=next_page, callback=self.parse)

    def parse_details(self, response):
        # set variable to response for model
        self.model = response.css("span[itemprop='sku']").css("::text").get()
```

ContentLicense: CC BY-SA 4.0

Body:
I try to learn Scrapy but I am stuck for 3 days with a problem, maybe some of you could help me with a solution or a suggestion.
I try to extract all the products from one category of a site, and for each product, I want only 3 categories: 2 from the main page when all the products are set, and 1 category from the details of the product(this is the cod of the product); and for this, I have accessed the link of each product.
All extracted products go to ItemLoader.
In the Items file, I have used the MapComposer and TakeFirst processor for all the items.

The problem is that my code extracts only the first product from each page.

This is the code:

import os
import scrapy
from scrapy.loader import ItemLoader
from ..items import CutotulItem

class CutotulSpiderLoader(scrapy.Spider):
    name = 'cutotul_spider_loader'
    start_urls = ['https://cutotul.ro/39-karcher-aspiratoare-profesionale']

    def __init__(self):
        self.model = ""

    def start_requests(self):
        yield scrapy.Request('https://cutotul.ro/39-karcher-aspiratoare-profesionale', callback=self.parse)

    def parse(self, response):
        products = response.css("div.columns-container")
        for product in products:
            # get details link
            details_link = product.xpath("//a[@class='lnk_view btn btn-default']/@href").get()

            # get details
            yield response.follow(url=details_link, callback=self.parse_details)
            product_name_xpath = "//span[@class='grid-name']/text()"
            product_price_xpath = "//span[@class='price product-price']/text()"
            product_model_xpath = "".join(self.model)

            # loader
            loader = ItemLoader(item=CutotulItem(), selector=product, response=response)
            loader.add_xpath("product_name", product_name_xpath)
            loader.add_xpath("product_price", product_price_xpath)
            loader.add_value("product_model", product_model_xpath)
            yield loader.load_item()

        # nav to next page
        # Get the next response for x items from the next page - persist until no more #

        next_page = response.xpath("//li[@class='pagination_next']//@href").get()
        if next_page:
            yield response.follow(url=next_page, callback=self.parse)

    def parse_details(self, response):
        # set variable to response for model
        self.model = response.css("span[itemprop='sku']").css("::text").get()

How can I solve this problem?

Thanks a lot!


问:
How to update the object key's value in state using useState() hook?
I have a array of objects state that has two key-value pairs [{name: 'Max', value: 1}]

when updating the state i am receiving the name from api and comparing with api.name == state.name. if it is true i need to update the value like value + 1. How do i achieve with setState()?

答:
You could use spread operator, to update the state by only changing the object properties.

this.setState({ array: this.state.array.map((item) => {
  const condition = "..."; // Implement logic
  return {...item, value: condition ? item.value + 1 : item.value }
 })
})
```


问:
C#: Adding Null-Item of the same type of other Items to ComboBox
I have the problem that there are binding errors in my custom combobox (it derivates from the ComboBox from Windows Controls). There is a property called AddNullItem which adds a ComboBoxItem with the Content Empty.

compositeCollection.Add(new ComboBoxItem() { Content = "Empty" });

The Problem is that if you bind to this ComboBox and the Null-Item is selected, a binding error occurs, because the ComboBoxItems are not of the same type.

How can I add a ComboBoxItem of the same type of all other items or is there a better solution?

My solution was following:
compositeCollection.Add(Activator.CreateInstance(this.Items.GetType()));, but then occurs a XamlParseException.

答:
Okay, I got the solution:

I created the instance of the IEnumerable Items, not the single item.
I used following:

```<code>object obj = System.Runtime.Serialization.FormatterServices.GetUninitializedObject(t);
</code>```

Body:
Okay, I got the solution:

I created the instance of the IEnumerable Items, not the single item.
I used following:

object obj = System.Runtime.Serialization.FormatterServices.GetUninitializedObject(t);


问:
Access button class in javascript
I have a button class that is placed inside an iframe. Problem is that this button's class has such a long name and I do not understand how to reference it in my script.

```<code><button class="PDF-dmzpd5z6ckdkxkn8 PDF-5rbqp8nfgh6e11 PDF-tma5quj Toolbar-Button Tool-Button" title="SignUp" aria-label="myButton001" type="button"></button>
</code>```

I am using my javascript to reference this class as:

```<code>document.querySelector("iframe").contentWindow.document.querySelector(".PDF-dmzpd5z6ckdkxkn8").click();
</code>```

The above code does not work. Do I have to provide the complete class name for reference?

I am on right track because I have another button that looks like this:

```<code><button class="PDF-tdsfethgr51stg Next-Button Next-Previous-Button" title="Next" aria-label="Next" type="button"></button>
</code>```

And I can easily call/reference it via:

```<code>document.querySelector("iframe").contentWindow.document.querySelector(".PDF-tdsfethgr51stg").click();
</code>```

答:
Using Id in button is the best option

Example:

```<code><button class="PDF-dmzpd5z6ckdkxkn8 PDF-5rbqp8nfgh6e11 PDF-tma5quj Toolbar-Button Tool-Button" title="SignUp" aria-label="myButton001" type="button" id="exbtn1"></button>
</code>```
```<code>document.querySelector("iframe").contentWindow.document.querySelector("#exbtn1").click();
</code>```

Note: It's best option to define the tags in Query Selector (eg. document.querySelector("iframe")[0]). The index starts from 0.

Title: Access button class in javascript

Body:
I have a button class that is placed inside an iframe. Problem is that this button's class has such a long name and I do not understand how to reference it in my script.

<button class="PDF-dmzpd5z6ckdkxkn8 PDF-5rbqp8nfgh6e11 PDF-tma5quj Toolbar-Button Tool-Button" title="SignUp" aria-label="myButton001" type="button"></button>

I am using my javascript to reference this class as:

document.querySelector("iframe").contentWindow.document.querySelector(".PDF-dmzpd5z6ckdkxkn8").click();

The above code does not work. Do I have to provide the complete class name for reference?

I am on right track because I have another button that looks like this:

<button class="PDF-tdsfethgr51stg Next-Button Next-Previous-Button" title="Next" aria-label="Next" type="button"></button>

And I can easily call/reference it via:

document.querySelector("iframe").contentWindow.document.querySelector(".PDF-tdsfethgr51stg").click();

Body:
Using Id in button is the best option

Example:

<button class="PDF-dmzpd5z6ckdkxkn8 PDF-5rbqp8nfgh6e11 PDF-tma5quj Toolbar-Button Tool-Button" title="SignUp" aria-label="myButton001" type="button" id="exbtn1"></button>

document.querySelector("iframe").contentWindow.document.querySelector("#exbtn1").click();

Note: It's best option to define the tags in Query Selector (eg. document.querySelector("iframe")[0]). The index starts from 0.


问:
Getting the difference between two repositories
How can we get the difference between two git repositories?

The scenario:
We have a repo_a and repo_b. The latter was created as a copy of repo_a. There have been parallel development in both the repositories afterwards. Is there a way we can list the differences of the current versions of these two repositories?

答:
To follow up @iamamac answer to have a nice summary after this:

```<code>git remote add -f b path/to/repo_b.git
git remote update
</code>```

I would use diff-tree:

```<code>git diff-tree master remotes/b/master --compact-summary
</code>```

ContentLicense: CC BY-SA 3.0

Body:
To follow up @iamamac answer to have a nice summary after this:

git remote add -f b path/to/repo_b.git
git remote update

I would use diff-tree:

git diff-tree master remotes/b/master --compact-summary


问:
unable to take keyboard inputs in java using KeyListener
i am trying to take keyboard inputs to change the boolean's value but keylisteners are not working

those bolleans values will be used later in other class

heres the method i am having issues with

```<code>public boolean upPressed, downPressed, leftPressed, rightPressed;

    @Override
    public void keyPressed(KeyEvent e) {
        int code = e.getKeyCode();
        if(code == KeyEvent.VK_W){
            upPressed = true;}

        else if(code == KeyEvent.VK_S){
            downPressed = true;}

        else if(code == KeyEvent.VK_A){
            leftPressed = true;}

        else if(code == KeyEvent.VK_D){
            rightPressed = true;}

    }
</code>```

i am using a different class which extends JPanel, frame is in a different class and key listener is in a different class and i have this.setFocusable(true);this.addKeyListener(keyH);

and if u want, here's the full code : https://github.com/PROMAN8625/2dGAME

答:
Your code snippet looks fine. Maybe you didn't add KeyListener to the frame.

Here is a working example:

```<code>import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Label;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class KeyListenerExample implements KeyListener
{
    public boolean upPressed, downPressed, leftPressed, rightPressed;

    @Override
    public void keyTyped(KeyEvent e) {
    }

    @Override
    public void keyPressed(KeyEvent e)
    {
        int code = e.getKeyCode();
        if (code == KeyEvent.VK_W) {
            upPressed = true;
        }
        else if(code == KeyEvent.VK_S){
            downPressed = true;}

        else if(code == KeyEvent.VK_A){
            leftPressed = true;}

        else if(code == KeyEvent.VK_D){
            rightPressed = true;}

        System.out.println("The key Pressed was: " + e.getKeyChar());
        System.out.println("upPressed: " + upPressed);
        System.out.println("downPressed: " + downPressed);
        System.out.println("leftPressed: " + leftPressed);
        System.out.println("rightPressed: " + rightPressed);
        System.out.println("\n");

    }

    @Override
    public void keyReleased(KeyEvent e) {
    }

    public static void main(String[] args)
    {
        //Setting the Frame and Labels
        Frame f = new Frame("Demo");
        f.setLayout(new FlowLayout());
        f.setSize(500, 500);
        Label l = new Label();
        l.setText("This is a demonstration");
        f.add(l);
        f.setVisible(true);

        //Creating and adding the key listener
        KeyListenerExample k = new KeyListenerExample();
        f.addKeyListener(k);
    }
}
</code>```

Body:
i am trying to take keyboard inputs to change the boolean's value but keylisteners are not working

those bolleans values will be used later in other class

heres the method i am having issues with

public boolean upPressed, downPressed, leftPressed, rightPressed;

    @Override
    public void keyPressed(KeyEvent e) {
        int code = e.getKeyCode();
        if(code == KeyEvent.VK_W){
            upPressed = true;}

        else if(code == KeyEvent.VK_S){
            downPressed = true;}

        else if(code == KeyEvent.VK_A){
            leftPressed = true;}

        else if(code == KeyEvent.VK_D){
            rightPressed = true;}

    }

i am using a different class which extends JPanel, frame is in a different class and key listener is in a different class and i have this.setFocusable(true);this.addKeyListener(keyH);

and if u want, here's the full code : https://github.com/PROMAN8625/2dGAME

Body:
Your code snippet looks fine. Maybe you didn't add KeyListener to the frame.

Here is a working example:

import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Label;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class KeyListenerExample implements KeyListener
{
    public boolean upPressed, downPressed, leftPressed, rightPressed;

    @Override
    public void keyTyped(KeyEvent e) {
    }

    @Override
    public void keyPressed(KeyEvent e)
    {
        int code = e.getKeyCode();
        if (code == KeyEvent.VK_W) {
            upPressed = true;
        }
        else if(code == KeyEvent.VK_S){
            downPressed = true;}

        else if(code == KeyEvent.VK_A){
            leftPressed = true;}

        else if(code == KeyEvent.VK_D){
            rightPressed = true;}

        System.out.println("The key Pressed was: " + e.getKeyChar());
        System.out.println("upPressed: " + upPressed);
        System.out.println("downPressed: " + downPressed);
        System.out.println("leftPressed: " + leftPressed);
        System.out.println("rightPressed: " + rightPressed);
        System.out.println("\n");

    }

    @Override
    public void keyReleased(KeyEvent e) {
    }

    public static void main(String[] args)
    {
        //Setting the Frame and Labels
        Frame f = new Frame("Demo");
        f.setLayout(new FlowLayout());
        f.setSize(500, 500);
        Label l = new Label();
        l.setText("This is a demonstration");
        f.add(l);
        f.setVisible(true);

        //Creating and adding the key listener
        KeyListenerExample k = new KeyListenerExample();
        f.addKeyListener(k);
    }
}


问:
How can I programmatically select a specific subplot in Matplotlib?
So in a figure where three vertical subplots have been added with add_subplot, how can I select let's say the middle one?

Right now I do this list comprehension:

[r[0] for r in sorted([[ax, ax.get_geometry()[2]] for ax in self.figure.get_axes()], key=itemgetter(1))]

where I can simply select the index I want, with the corresponding axes. Is there a more straightforward way of doing this?

答:
From the matplotlib documentation:

If the figure already has a subplot with key (args, kwargs) then it will simply make that subplot current and return it.

Here's an example:

```<code>import matplotlib.pyplot as plt

fig = plt.figure()
for vplot in [1,2,3]:
    ax = fig.add_subplot(3,1,vplot)
    ax.plot(range(10),range(10))

ax_again = fig.add_subplot(3,1,2)
ax_again.annotate("The middle one",xy=(7,5),xytext=(7,5))

plt.show()
</code>```

The middle plot is called again so that it can be annotated.

What if I set the background with my original call, do I need to set it again when I get the subplot the second time?

Yes. The arguments and keywords for the original call are used to make a unique identifier. So for the figure to generate this unique identifier again, you need to pass the same arguments (grid definition, position) and keywords again. For example:

```<code>import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(2,1,1,axisbg='red')
ax.plot(range(10),range(10))
ax = fig.add_subplot(2,1,2)
ax.plot(range(10),range(10))

ax_again = fig.add_subplot(2,1,1,axisbg='red')
ax_again.annotate("The top one",xy=(7,5),xytext=(7,5))

plt.show()
</code>```

What if I use ax_again.change_geometry() ?

You would think change_geometry, e.g. from a 312 to a 422, would change how you use add_subplot, but it doesn't. There appears to be a bug or undefined behavior when you call change_geometry. The unique key that was original generated using the arguments and keywords, to the first add_subplot call, does not get updated. Therefore, if you want to get an axis back with an add_subplot call, you need to call add_subplot with the original arguments and keywords. For more info, follow this issue report:
https://github.com/matplotlib/matplotlib/issues/429

My guess for now is that if you change any property of the subplot after generating it with add_subplot call, the unique will not be adjusted. So just use the original arguments and keywords, and hopefully this will work out.

Body:
From the matplotlib documentation:

If the figure already has a subplot with key (args, kwargs) then it will simply make that subplot current and return it.

Here's an example:

import matplotlib.pyplot as plt

fig = plt.figure()
for vplot in [1,2,3]:
    ax = fig.add_subplot(3,1,vplot)
    ax.plot(range(10),range(10))

ax_again = fig.add_subplot(3,1,2)
ax_again.annotate("The middle one",xy=(7,5),xytext=(7,5))

plt.show()

The middle plot is called again so that it can be annotated.

What if I set the background with my original call, do I need to set it again when I get the subplot the second time?

Yes. The arguments and keywords for the original call are used to make a unique identifier. So for the figure to generate this unique identifier again, you need to pass the same arguments (grid definition, position) and keywords again. For example:

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(2,1,1,axisbg='red')
ax.plot(range(10),range(10))
ax = fig.add_subplot(2,1,2)
ax.plot(range(10),range(10))

ax_again = fig.add_subplot(2,1,1,axisbg='red')
ax_again.annotate("The top one",xy=(7,5),xytext=(7,5))

plt.show()

What if I use ax_again.change_geometry() ?

You would think change_geometry, e.g. from a 312 to a 422, would change how you use add_subplot, but it doesn't. There appears to be a bug or undefined behavior when you call change_geometry. The unique key that was original generated using the arguments and keywords, to the first add_subplot call, does not get updated. Therefore, if you want to get an axis back with an add_subplot call, you need to call add_subplot with the original arguments and keywords. For more info, follow this issue report:
https://github.com/matplotlib/matplotlib/issues/429

My guess for now is that if you change any property of the subplot after generating it with add_subplot call, the unique will not be adjusted. So just use the original arguments and keywords, and hopefully this will work out.


问:
Python basemap module impossible to import
I have troubles to import the basemap module of mpl_toolkits in python. Here is what I get when I run the test.py script from the module directory:

```<code>/usr/lib/python2.7/dist-packages/mpl_toolkits/basemap$ python test.py
Traceback (most recent call last):
File "test.py", line 1, in <module>
from mpl_toolkits.basemap import Basemap, shiftgrid
ImportError: No module named basemap
</code>```

I can't get it since sys.path gives a list of paths where I am sure the directory "basemap" is, in the "mpl_toolkits" directory. There is no problem to import mpl_toolkits. Here is a thing I tried, to manually add the path, and the result:

```<code>>>> import sys
>>> sys.path.append('/usr/lib/python2.7/dist-packages/mpl_toolkits/basemap')
>>> import basemap
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "basemap/__init__.py", line 30, in <module>
from mpl_toolkits.basemap import pyproj
ImportError: No module named basemap
</code>```

I tried to uninstall an reinstall basemap from source (carefully following these instructions), from apt-get, from conda, but it does not change anything: I can't import basemap.

Thank you for your help

答:
For me, a simple

```<code>pip3 install basemap
</code>```

did the trick.

Body:
I have troubles to import the basemap module of mpl_toolkits in python. Here is what I get when I run the test.py script from the module directory:

/usr/lib/python2.7/dist-packages/mpl_toolkits/basemap$ python test.py
Traceback (most recent call last):
File "test.py", line 1, in <module>
from mpl_toolkits.basemap import Basemap, shiftgrid
ImportError: No module named basemap

I can't get it since sys.path gives a list of paths where I am sure the directory "basemap" is, in the "mpl_toolkits" directory. There is no problem to import mpl_toolkits. Here is a thing I tried, to manually add the path, and the result:

>>> import sys
>>> sys.path.append('/usr/lib/python2.7/dist-packages/mpl_toolkits/basemap')
>>> import basemap
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "basemap/__init__.py", line 30, in <module>
from mpl_toolkits.basemap import pyproj
ImportError: No module named basemap

I tried to uninstall an reinstall basemap from source (carefully following these instructions), from apt-get, from conda, but it does not change anything: I can't import basemap.

Thank you for your help

Body:
For me, a simple

pip3 install basemap

did the trick.


问:
Closest subsequent index for a specified value
Consider a vector:

int = c(1, 1, 0, 5, 2, 0, 0, 2)
```
<p>I'd like to get the closest subsequent index (not the difference) for a specified value. The first parameter of the function should be the vector, while the second should be the value one wants to see the closest subsequent elements.</p>
<p>For instance,</p>
<pre class="lang-r prettyprint-override"><code>f(int, 0)
# [1] 2 1 0 2 1 0 0 NA
</code>```

Here, the first element of the vector (1) is two positions away from the first subsequent 0, (3 - 1 = 2), so it should return 2. Then the second element is 1 position away from a 0 (2 - 1 = 1). When there is no subsequent values that match the specified value, return NA (here it's the case for the last element, because no subsequent value is 0).

Other examples:

f(int, 1)
# [1] 0 0 NA NA NA NA NA NA

f(int, 2)
# [1] 4 3 2 1 0 2 1 0

f(int, 3)
# [1] NA NA NA NA NA NA NA NA
```
<p>This should also work for character vectors:</p>
<pre class="lang-r prettyprint-override"><code>char = c("A", "B", "C", "A", "A")

f(char, "A")
# [1] 0 2 1 0 0
</code>```

答:
Find the location of each value (numeric or character)

```<code>int = c(1, 1, 0, 5, 2, 0, 0, 2)
value = 0
idx = which(int == value)
## [1] 3 6 7
</code>```

Expand the index to indicate the nearest value of interest, using an NA after the last value in int.

```<code>nearest = rep(NA, length(int))
nearest[1:max(idx)] = rep(idx, diff(c(0, idx))),
## [1]  3  3  3  6  6  6  7 NA
</code>```

Use simple arithmetic to find the difference between the index of the current value and the index of the nearest value

```<code>abs(seq_along(int) - nearest)
## [1]  2  1  0  2  1  0  0 NA
</code>```

Written as a function

```<code>f <- function(x, value) {
    idx = which(x == value)
    nearest = rep(NA, length(x))
    if (length(idx)) # non-NA values only if `value` in `x`
        nearest[1:max(idx)] = rep(idx, diff(c(0, idx)))
    abs(seq_along(x) - nearest)
}
</code>```

We have

```<code>> f(int, 0)
[1]  2  1  0  2  1  0  0 NA
> f(int, 1)
[1]  0  0 NA NA NA NA NA NA
> f(int, 2)
[1] 4 3 2 1 0 2 1 0
> f(char, "A")
[1] 0 2 1 0 0
> f(char, "B")
[1]  1  0 NA NA NA
> f(char, "C")
[1]  2  1  0 NA NA
</code>```

The solution doesn't involve recursion or R-level loops, so should e fast even for long vectors.

Body:
Consider a vector:

int = c(1, 1, 0, 5, 2, 0, 0, 2)

I'd like to get the closest subsequent index (not the difference) for a specified value. The first parameter of the function should be the vector, while the second should be the value one wants to see the closest subsequent elements.

For instance,

f(int, 0)
# [1] 2 1 0 2 1 0 0 NA

Here, the first element of the vector (1) is two positions away from the first subsequent 0, (3 - 1 = 2), so it should return 2. Then the second element is 1 position away from a 0 (2 - 1 = 1). When there is no subsequent values that match the specified value, return NA (here it's the case for the last element, because no subsequent value is 0).

Other examples:

f(int, 1)
# [1] 0 0 NA NA NA NA NA NA

f(int, 2)
# [1] 4 3 2 1 0 2 1 0

f(int, 3)
# [1] NA NA NA NA NA NA NA NA

This should also work for character vectors:

char = c("A", "B", "C", "A", "A")

f(char, "A")
# [1] 0 2 1 0 0

Body:
Find the location of each value (numeric or character)

int = c(1, 1, 0, 5, 2, 0, 0, 2)
value = 0
idx = which(int == value)
## [1] 3 6 7

Expand the index to indicate the nearest value of interest, using an NA after the last value in int.

nearest = rep(NA, length(int))
nearest[1:max(idx)] = rep(idx, diff(c(0, idx))),
## [1]  3  3  3  6  6  6  7 NA

Use simple arithmetic to find the difference between the index of the current value and the index of the nearest value

abs(seq_along(int) - nearest)
## [1]  2  1  0  2  1  0  0 NA

Written as a function

f <- function(x, value) {
    idx = which(x == value)
    nearest = rep(NA, length(x))
    if (length(idx)) # non-NA values only if `value` in `x`
        nearest[1:max(idx)] = rep(idx, diff(c(0, idx)))
    abs(seq_along(x) - nearest)
}

We have

> f(int, 0)
[1]  2  1  0  2  1  0  0 NA
> f(int, 1)
[1]  0  0 NA NA NA NA NA NA
> f(int, 2)
[1] 4 3 2 1 0 2 1 0
> f(char, "A")
[1] 0 2 1 0 0
> f(char, "B")
[1]  1  0 NA NA NA
> f(char, "C")
[1]  2  1  0 NA NA

The solution doesn't involve recursion or R-level loops, so should e fast even for long vectors.


问:
Flutter: How to personalize a Card borders and to add a header text

I want to realize the card as shown in the image, but I have not found any ways to add the date on the top right and that particular border on the left.

答:
```<code>   Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(20),
          color: Colors.indigo,
        ),
        child: Container(
          decoration: const BoxDecoration(
            borderRadius: BorderRadius.only(
              topRight: Radius.circular(20),
              bottomRight: Radius.circular(20),
            ),
            color: Colors.white,
          ),
          margin: const EdgeInsets.fromLTRB(25, 2, 2, 2),
          padding: const EdgeInsets.all(20),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: const [
              Align(alignment: Alignment.centerRight, child: Text("01/02/2022",style: TextStyle(fontStyle:FontStyle.italic,
                  fontWeight: FontWeight.w300),)),
              Text("Avviso",style: TextStyle(fontSize: 19,
                  fontWeight: FontWeight.bold),),
              Text("Scadenza pagamento quota annulae",style: TextStyle(fontSize: 14),),
            ],
          )
        ),
      )
</code>```


问:
Spring JPA - JPQL Named Query Find All By Year And And month
I am trying to get all objects by specific month and year.
I have done this with Native Query

```<code>   @Query(value = "select * from transaction_log as t where year(t.insurance_period)=(:year) AND user_id =(:userId) AND t.employer_id is null", nativeQuery = true)
</code>```

And I want to be done with another way so I can use entity graphs etc.
I have try

```<code>@Query("select t from Transaction t where year(t.insuranceDate) = ?1 and month(t.insuranceDate) = ?2")
</code>```

And I get error on method Year () for unexcepted '('

and the following with the same error at EXTRACT method.

```<code>@Query("SELECT t FROM Transaction t WHERE EXTRACT (YEAR FROM t.insuranceDate) = :year AND EXTRACT (month FROMt.insuranceDate) = :month")
</code>```

答:
You could use BETWEEN first day of month and last day of month. According to jpql doc BETWEEN is inclusive.

The downside is doing some date calculations, but they are trivial with java.time classes. Let's say you want dates from February 2020. You could get first and last day like this:

```<code>int year = 2020;
int month = 2;
LocalDate firstDay = LocalDate.of(year, month, 1);
LocalDate lastDay = firstDay.withDayOfMonth(firstDay.lengthOfMonth());
</code>```

Then the query will look like this:

```<code>@Query("SELECT t FROM Transaction t WHERE t.insuranceDate BETWEEN :firstDay AND :lastDay")
</code>```

Body:
I am trying to get all objects by specific month and year.
I have done this with Native Query

   @Query(value = "select * from transaction_log as t where year(t.insurance_period)=(:year) AND user_id =(:userId) AND t.employer_id is null", nativeQuery = true)

And I want to be done with another way so I can use entity graphs etc.
I have try

@Query("select t from Transaction t where year(t.insuranceDate) = ?1 and month(t.insuranceDate) = ?2")

And I get error on method Year () for unexcepted '('

and the following with the same error at EXTRACT method.

@Query("SELECT t FROM Transaction t WHERE EXTRACT (YEAR FROM t.insuranceDate) = :year AND EXTRACT (month FROMt.insuranceDate) = :month")

Body:
You could use BETWEEN first day of month and last day of month. According to jpql doc BETWEEN is inclusive.

The downside is doing some date calculations, but they are trivial with java.time classes. Let's say you want dates from February 2020. You could get first and last day like this:

int year = 2020;
int month = 2;
LocalDate firstDay = LocalDate.of(year, month, 1);
LocalDate lastDay = firstDay.withDayOfMonth(firstDay.lengthOfMonth());

Then the query will look like this:

@Query("SELECT t FROM Transaction t WHERE t.insuranceDate BETWEEN :firstDay AND :lastDay")


问:
Function to check for NULL and concatenating the strings
I have a SQL statement that concatenates First Name and Last Name of the person. I use the following SQL statement.

```<code>ISNULL(FullName.FirstName, '') + ' ' + ISNULL(FullName.LastName, '')
</code>```

What I need is to change this to add the FirstName and LastName only if they are not both NULL. If one of them is not NULL, use that value.

Examples:

FirstName and LastName are NULL -> NULL

FirstName is John and LastName is NULL -> John

FirstName is NULL and LastName is Doe -> Doe

-> indicates the result

答:
A better SQL Server 2017 solution:

Use the new CONCAT_WS function, which concatenates with a separator, ignoring nulls

CREATE TABLE #emp (ID INT IDENTITY(1,1), FirstName VARCHAR(25), LastName VARCHAR(25));

INSERT INTO #emp
VALUES(null,null)
,('John',null)
,('Doe',null)
,('John', 'Doe');

SELECT FullName = CONCAT_WS(' ', FirstName, LastName)
    ,*
FROM #emp;
```

db<>fiddle

Body:
I have a SQL statement that concatenates First Name and Last Name of the person. I use the following SQL statement.

ISNULL(FullName.FirstName, '') + ' ' + ISNULL(FullName.LastName, '')

What I need is to change this to add the FirstName and LastName only if they are not both NULL. If one of them is not NULL, use that value.

Examples:

FirstName and LastName are NULL -> NULL

FirstName is John and LastName is NULL -> John

FirstName is NULL and LastName is Doe -> Doe

-> indicates the result

Body:
A better SQL Server 2017 solution:

Use the new CONCAT_WS function, which concatenates with a separator, ignoring nulls

CREATE TABLE #emp (ID INT IDENTITY(1,1), FirstName VARCHAR(25), LastName VARCHAR(25));

INSERT INTO #emp
VALUES(null,null)
,('John',null)
,('Doe',null)
,('John', 'Doe');

SELECT FullName = CONCAT_WS(' ', FirstName, LastName)
    ,*
FROM #emp;

db<>fiddle


问:
Object and Function are quite confusing
```<code>Object instanceof Object
true
Object instanceof Function
true
Function instanceof Object
true
Function instanceof Function
true
</code>```

so if Function is an Object and the Object is a Function how come

Function === Object and Function == Object are false?

I do understand that checking the instance of an object is not the same as comparison. So the question here is the fuzziness in the case where if two objects (which are actually types) are instances of each other, shouldn't the types be the same?

Note: Object is not an instance of a Number or an Array just an instance of Function.

答:
```<code> javascript:alert([ window.navigator.userAgent, Object ].join("\n\n") )
</code>```

displays

```<code>Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.3) Gecko/20100423
    Ubuntu/10.04 (lucid) Firefox/3.6.3

function Object() {
    [native code]
}
</code>```

reference: Is every JavaScript Object a function?

Title: Object and Function are quite confusing

Body:
Object instanceof Object
true
Object instanceof Function
true
Function instanceof Object
true
Function instanceof Function
true

so if Function is an Object and the Object is a Function how come

Function === Object and Function == Object are false?

I do understand that checking the instance of an object is not the same as comparison. So the question here is the fuzziness in the case where if two objects (which are actually types) are instances of each other, shouldn't the types be the same?

Note: Object is not an instance of a Number or an Array just an instance of Function.

Body:
 javascript:alert([ window.navigator.userAgent, Object ].join("\n\n") )

displays

Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.3) Gecko/20100423
    Ubuntu/10.04 (lucid) Firefox/3.6.3

function Object() {
    [native code]
}

reference: Is every JavaScript Object a function?


问:
Change 'checked' property of checkbox using jQuery and bootstrap (AdminLTE theme)
I'm using the AdminLTE theme (which implements bootstrap) and I have a checkbox on my page. It gets rendered as follows -

```<code><div class="icheckbox_minimal" style="position: relative;" aria-checked="false" aria-disabled="false">
<input id="subscribeAddress" type="checkbox" style="position: absolute; opacity: 0;">
<ins class="iCheck-helper" style="position: absolute; top: 0%; left: 0%; display: block; width: 100%; height: 100%; margin: 0px; padding: 0px; background: none repeat scroll 0% 0% rgb(255, 255, 255); border: 0px none; opacity: 0;"></ins>
</div>
</code>```

(note how a sprite is used to display the checkbox, while the actual input element is given an opacity of 0)

I now wish to change the checked property of the checkbox with jQuery. How would I go about doing this? I have tried the following without any luck -

```<code>$("#subscribeAddress").prop("checked", true);

$(".icheckbox_minimal").prop("aria-checked", true);
</code>```

Update: I have found a solution to my question and posted an answer below, but am still open to suggestions on better approaches.

答:
Try this

```<code>$('#checkAll').on('ifChanged', function(event){
    if(this.checked){
        $('input').iCheck('check')
    }
    else{
        $('input').iCheck('uncheck')
    }
})
</code>```

I hope this will help you.

Body:
I'm using the AdminLTE theme (which implements bootstrap) and I have a checkbox on my page. It gets rendered as follows -

<input id="subscribeAddress" type="checkbox" style="position: absolute; opacity: 0;">

(note how a sprite is used to display the checkbox, while the actual input element is given an opacity of 0)

I now wish to change the checked property of the checkbox with jQuery. How would I go about doing this? I have tried the following without any luck -

$("#subscribeAddress").prop("checked", true);

$(".icheckbox_minimal").prop("aria-checked", true);

Update: I have found a solution to my question and posted an answer below, but am still open to suggestions on better approaches.

Body:
Try this

$('#checkAll').on('ifChanged', function(event){
    if(this.checked){
        $('input').iCheck('check')
    }
    else{
        $('input').iCheck('uncheck')
    }
})

I hope this will help you.


问:
How to add one element of a list of the values of a dictionary when mapping the dictionary with a pandas data frame
I have a dictionary whose keys match with one of the column of a pandas data frame I have. I want to add in a new column the values of this dictionary. However, the values of this dictionary are in a list.

```<code>dicts
{'A1BG': [('chr19', 58345178, '+', 5304388456)],
 'A1CF': [('chr10', 50799409, '+', 12173607359)],
 'A2M': [('chr12', 9067664, '+', 12341034620)],
 'A2ML1': [('chr12', 8822472, '+', 12341034620)],...}
</code>```

I know how to add the complete list in a new column

```<code>loeuf['chromosome_hg38'] = loeuf['gene'].map(dicts)

</code>```

But I don't know how to add only the value ch19 instead of   ('chr19', 58345178, '+', 5304388456)]

First row of loeuf

```<code>gene transcript canonical       obs_mis exp_mis oe_mis  mu_mis  possible_mis    obs_mis_pphen   exp_mis_pphen   ... exac_pLI    exac_obs_lof    exac_exp_lof    exac_oe_lof brain_expression    chromosome  start_position  end_position    new chromosome_hg38
0    A1BG       ENST00000263100 True    298.0   293.85  1.01410 0.000019        3115.0  104.0   101.3900        ... 9.064900e-05    8.0 12.301  0.65033        NaN  chr19   58856544    58864865    [(chr19, 58345178, +, 5304388456)]  chr19
</code>```

答:
I make dict just like you:

```<code>dict = {'A1BG': [('chr19', 58345178, '+', 5304388456)],
'A1CF': [('chr10', 50799409, '+', 12173607359)],
'A2M': [('chr12', 9067664, '+', 12341034620)],
'A2ML1': [('chr12', 8822472, '+', 12341034620)]}
</code>```

next df:

```<code>loeuf = pd.DataFrame(['A1BG', 'A1CF', 'A2M', 'A2ML1'], columns=['gene'])
</code>```

Finally I did what you wanted like that (using for loop):

```<code>for index, row in loeuf.iterrows():
    temp_value = dict[row.gene][0][0]
    loeuf['chromosome_hg38'][index] = temp_value
</code>```

Output:

```<code>gene    chromosome_hg38
0   A1BG    chr19
1   A1CF    chr10
2   A2M chr12
3   A2ML1   chr12
</code>```

Body:
I have a dictionary whose keys match with one of the column of a pandas data frame I have. I want to add in a new column the values of this dictionary. However, the values of this dictionary are in a list.

dicts
{'A1BG': [('chr19', 58345178, '+', 5304388456)],
 'A1CF': [('chr10', 50799409, '+', 12173607359)],
 'A2M': [('chr12', 9067664, '+', 12341034620)],
 'A2ML1': [('chr12', 8822472, '+', 12341034620)],...}

I know how to add the complete list in a new column

loeuf['chromosome_hg38'] = loeuf['gene'].map(dicts)

But I don't know how to add only the value ch19 instead of   ('chr19', 58345178, '+', 5304388456)]

First row of loeuf

gene transcript canonical       obs_mis exp_mis oe_mis  mu_mis  possible_mis    obs_mis_pphen   exp_mis_pphen   ... exac_pLI    exac_obs_lof    exac_exp_lof    exac_oe_lof brain_expression    chromosome  start_position  end_position    new chromosome_hg38
0    A1BG       ENST00000263100 True    298.0   293.85  1.01410 0.000019        3115.0  104.0   101.3900        ... 9.064900e-05    8.0 12.301  0.65033        NaN  chr19   58856544    58864865    [(chr19, 58345178, +, 5304388456)]  chr19

Body:
I make dict just like you:

dict = {'A1BG': [('chr19', 58345178, '+', 5304388456)],
'A1CF': [('chr10', 50799409, '+', 12173607359)],
'A2M': [('chr12', 9067664, '+', 12341034620)],
'A2ML1': [('chr12', 8822472, '+', 12341034620)]}

next df:

loeuf = pd.DataFrame(['A1BG', 'A1CF', 'A2M', 'A2ML1'], columns=['gene'])

Finally I did what you wanted like that (using for loop):

for index, row in loeuf.iterrows():
    temp_value = dict[row.gene][0][0]
    loeuf['chromosome_hg38'][index] = temp_value

Output:

gene    chromosome_hg38
0   A1BG    chr19
1   A1CF    chr10
2   A2M chr12
3   A2ML1   chr12


问:
Blank screen when I put Drawer Navigator as the main navigator in index.tsx
If I put Drawer Navigator in index.tsx I only get a blank screen.

Tried wrapping NavigationContainer in index.tsx in a View with flex: 1 but it didn't work.
Also I don't have alignItems: 'center' in App.tsx to remove as this answer suggests. (https://stackoverflow.com/a/62647417/13117660)

index.tsx:

```<code>const Drawer = createDrawerNavigator();

export const store = configureStore({});

export default () => {
  return (
    <Provider store={store}>
      <DatabaseConnectionProvider>
        <NavigationContainer>
          <Drawer.Navigator drawerContent={(props: any) => <CustomDrawerContent {...props} />} screenOptions={{
              headerTitle: () => <Image source={require('../assets/logo_navbar.jpg')} style={{
                width: 120,
                height: 40,
                alignContent: 'center'
              }} />,
              headerTitleAlign: 'center',
              headerStyle: {
                backgroundColor: Colors.RED,
              }
            }} >
              <Drawer.Screen name='Home' component={HomeScreen}></Drawer.Screen>
            </Drawer.Navigator>
        </NavigationContainer>
      </DatabaseConnectionProvider>
    </Provider>
  );
};
</code>```

CustomDrawerContent.tsx:

```<code>const CustomDrawerContent: FC = (props: any) => {
  return (
    <View style={{ flex: 1, backgroundColor: Colors.RED }}>
      <DrawerContentScrollView {...props} style={styles.drawerContent2}>
        <View style={styles.drawerContent}>
          <Drawer.Section style={styles.drawerSection}>
            <DrawerItem
              labelStyle={{ color: Colors.WHITE, fontSize: 20, marginLeft: 20 }}
              label={"Home"}
              onPress={() => {
                props.navigation.navigate("Home");
              }}
            />
            <DrawerItem
              labelStyle={{ color: Colors.WHITE, fontSize: 20, marginLeft: 20 }}
              label={"About us"}
              onPress={() => {
                props.navigation.navigate("AboutUs");
              }}
            />
            <DrawerItem
              labelStyle={{ color: Colors.WHITE, fontSize: 20, marginLeft: 20 }}
              label={"Impresum"}
              onPress={() => {
                props.navigation.navigate("Impresum");
              }}
            />
            <DrawerItem
              labelStyle={{ color: Colors.WHITE, fontSize: 20, marginLeft: 20 }}
              label={"Contact"}
              onPress={() => {
                props.navigation.navigate("Contact");
              }}
            />
          </Drawer.Section>
        </View>
      </DrawerContentScrollView>
    </View>
  );
};

export default CustomDrawerContent;

const styles = StyleSheet.create({
  drawerContent: {
    flex: 1,
    backgroundColor: Colors.RED,
  },
  drawerContent2: {
    flex: 1,
  },
  labels: {
    fontSize: 30,
  },
  userInfoSection: {
    paddingLeft: 20,
  },
  title: {
    fontSize: 16,
    marginTop: 3,
    fontWeight: "bold",
  },
  caption: {
    fontSize: 14,
    lineHeight: 14,
  },
  row: {
    marginTop: 20,
    flexDirection: "row",
    alignItems: "center",
  },
  section: {
    flexDirection: "row",
    alignItems: "center",
    marginRight: 15,
  },
  paragraph: {
    fontWeight: "bold",
    marginRight: 3,
  },
  drawerSection: {
    marginTop: 15,
    fontWeight: "bold",
    backgroundColor: Colors.RED,
  },
});
</code>```

Edit:

Also when I use the Drawer Navigator like this in index.tsx it also shows just blank screen

```<code>return (
    <Provider store={store}>
      <DatabaseConnectionProvider>
        <NavigationContainer>
          <Drawer.Navigator>
              <Drawer.Screen name='Home' component={HomeScreen}></Drawer.Screen>
              <Drawer.Screen name='About' component={AboutUsScreen}></Drawer.Screen>
            </Drawer.Navigator>
        </NavigationContainer>
      </DatabaseConnectionProvider>
    </Provider>
  );
</code>```

When I put a breakpoint on the return of HomeScreen component it gets hit only the first time the app loads, but nothing renders on screen. If I reload the app than the HomeScreen breakpoint is not hit. I have to stop the server and run the app again every time. But the blank screen is always there.

If I change the Drawer Navigatior to Stack Navigatior than everything works. But I need the Drawer Navigator to be the main navigator.

I am using expo, @react-navigation/drawer 6.3.0 and @react-navigation/native 6.0.8

答:
So I found out what wasn't working. My debbuger was on and it was causing problems as explained here: https://github.com/react-navigation/react-navigation/issues/10253

I am debugging in VS code, not in Chrome Debugger but still when I turn off debugging it works. If the debugger is on you have to put

```<code>useLegacyImplementation={false}
</code>```

as a prop in Drawer.Navigator. It is little laggy but works.

I am using react-native-reanimated 2.4.0

Body:
If I put Drawer Navigator in index.tsx I only get a blank screen.

Tried wrapping NavigationContainer in index.tsx in a View with flex: 1 but it didn't work.
Also I don't have alignItems: 'center' in App.tsx to remove as this answer suggests. (https://stackoverflow.com/a/62647417/13117660)

index.tsx:

const Drawer = createDrawerNavigator();

export const store = configureStore({});

export default () => {
  return (
    <Provider store={store}>
      <DatabaseConnectionProvider>
        <NavigationContainer>
          <Drawer.Navigator drawerContent={(props: any) => <CustomDrawerContent {...props} />} screenOptions={{
              headerTitle: () => <Image source={require('../assets/logo_navbar.jpg')} style={{
                width: 120,
                height: 40,
                alignContent: 'center'
              }} />,
              headerTitleAlign: 'center',
              headerStyle: {
                backgroundColor: Colors.RED,
              }
            }} >
              <Drawer.Screen name='Home' component={HomeScreen}></Drawer.Screen>
            </Drawer.Navigator>
        </NavigationContainer>
      </DatabaseConnectionProvider>
    </Provider>
  );
};

CustomDrawerContent.tsx:

const CustomDrawerContent: FC = (props: any) => {
  return (
    <View style={{ flex: 1, backgroundColor: Colors.RED }}>
      <DrawerContentScrollView {...props} style={styles.drawerContent2}>
        <View style={styles.drawerContent}>
          <Drawer.Section style={styles.drawerSection}>
            <DrawerItem
              labelStyle={{ color: Colors.WHITE, fontSize: 20, marginLeft: 20 }}
              label={"Home"}
              onPress={() => {
                props.navigation.navigate("Home");
              }}
            />
            <DrawerItem
              labelStyle={{ color: Colors.WHITE, fontSize: 20, marginLeft: 20 }}
              label={"About us"}
              onPress={() => {
                props.navigation.navigate("AboutUs");
              }}
            />
            <DrawerItem
              labelStyle={{ color: Colors.WHITE, fontSize: 20, marginLeft: 20 }}
              label={"Impresum"}
              onPress={() => {
                props.navigation.navigate("Impresum");
              }}
            />
            <DrawerItem
              labelStyle={{ color: Colors.WHITE, fontSize: 20, marginLeft: 20 }}
              label={"Contact"}
              onPress={() => {
                props.navigation.navigate("Contact");
              }}
            />
          </Drawer.Section>
        </View>
      </DrawerContentScrollView>
    </View>
  );
};

export default CustomDrawerContent;

const styles = StyleSheet.create({
  drawerContent: {
    flex: 1,
    backgroundColor: Colors.RED,
  },
  drawerContent2: {
    flex: 1,
  },
  labels: {
    fontSize: 30,
  },
  userInfoSection: {
    paddingLeft: 20,
  },
  title: {
    fontSize: 16,
    marginTop: 3,
    fontWeight: "bold",
  },
  caption: {
    fontSize: 14,
    lineHeight: 14,
  },
  row: {
    marginTop: 20,
    flexDirection: "row",
    alignItems: "center",
  },
  section: {
    flexDirection: "row",
    alignItems: "center",
    marginRight: 15,
  },
  paragraph: {
    fontWeight: "bold",
    marginRight: 3,
  },
  drawerSection: {
    marginTop: 15,
    fontWeight: "bold",
    backgroundColor: Colors.RED,
  },
});

Edit:

Also when I use the Drawer Navigator like this in index.tsx it also shows just blank screen

return (
    <Provider store={store}>
      <DatabaseConnectionProvider>
        <NavigationContainer>
          <Drawer.Navigator>
              <Drawer.Screen name='Home' component={HomeScreen}></Drawer.Screen>
              <Drawer.Screen name='About' component={AboutUsScreen}></Drawer.Screen>
            </Drawer.Navigator>
        </NavigationContainer>
      </DatabaseConnectionProvider>
    </Provider>
  );

When I put a breakpoint on the return of HomeScreen component it gets hit only the first time the app loads, but nothing renders on screen. If I reload the app than the HomeScreen breakpoint is not hit. I have to stop the server and run the app again every time. But the blank screen is always there.

If I change the Drawer Navigatior to Stack Navigatior than everything works. But I need the Drawer Navigator to be the main navigator.

I am using expo, @react-navigation/drawer 6.3.0 and @react-navigation/native 6.0.8

Body:
So I found out what wasn't working. My debbuger was on and it was causing problems as explained here: https://github.com/react-navigation/react-navigation/issues/10253

I am debugging in VS code, not in Chrome Debugger but still when I turn off debugging it works. If the debugger is on you have to put

useLegacyImplementation={false}

as a prop in Drawer.Navigator. It is little laggy but works.

I am using react-native-reanimated 2.4.0


问:
How to access source data from a data point of a pivot datatable in Shiny
In Excel you can double click on any value in a Pivot Table and it will give you the data extract from your original source data set. Is there a way or similar feature to receive the same extract from a data point of a pivot datatable in Shiny?

Many thanks!

答:
```<code>library(tidyverse)
library(shiny)
library(DT)

shinyApp(
  ui = basicPage(
    dataTableOutput("pivot_table"),
    dataTableOutput("extract_table")
  ),
  server = function(input, output) {
    data <- iris

    pivot_data <- data %>% count(Species)

    extracted_data <- reactive(
      data %>% semi_join(pivot_data[input$pivot_table_rows_selected, ])
    )

    output$pivot_table <- renderDataTable(pivot_data)
    output$extract_table <- renderDataTable(extracted_data())
  }
)
</code>```


问:
Kubernetes NodePort not accesible from outside
I'm trying to use the latest bitnami postgres chart to deploy postgres to a local kubernetes cluster (mac os, docker desktop 4.4.2, kubernetes 1.22.5):
https://github.com/bitnami/bitnami-docker-postgresql

I have set the node port:

```<code>primary:
  service:
    # Kubernetes Service type
    type: NodePort
    nodePorts:
      # Node port for PostgreSQL
      postgresql: '30000'
</code>```

the service is visible:

```<code>NAME                             TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)          AGE
service/postgres-nodeport      NodePort    10.111.195.149   <none>        5432:30000/TCP   9m56s
</code>```

but I cant access it from outside, eg:

```<code>psql -h localhost -p 30000 -U myusername -d mydatabase
</code>```

but I think it is configured correctly, because when I execute port-forward postgres is available:

```<code>kubectl port-forward pod/postgres-nodeport-0 30000:5432
</code>```

答:
you need to call with node ip.
The format should be NodeIP of the Node where you are running your pods and the NodePort. Ref

The Template to call NodePort  service from outside the cluster is like this.

```<code><NodeIP>:<NodePort>
</code>```

Try this one:

```<code>psql -h 192.168.65.4 -p 30000 -U myusername -d mydatabase
</code>```

Body:
I'm trying to use the latest bitnami postgres chart to deploy postgres to a local kubernetes cluster (mac os, docker desktop 4.4.2, kubernetes 1.22.5):
https://github.com/bitnami/bitnami-docker-postgresql

I have set the node port:

primary:
  service:
    # Kubernetes Service type
    type: NodePort
    nodePorts:
      # Node port for PostgreSQL
      postgresql: '30000'

the service is visible:

NAME                             TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)          AGE
service/postgres-nodeport      NodePort    10.111.195.149   <none>        5432:30000/TCP   9m56s

but I cant access it from outside, eg:

psql -h localhost -p 30000 -U myusername -d mydatabase

but I think it is configured correctly, because when I execute port-forward postgres is available:

kubectl port-forward pod/postgres-nodeport-0 30000:5432

Body:
you need to call with node ip.
The format should be NodeIP of the Node where you are running your pods and the NodePort. Ref

The Template to call NodePort  service from outside the cluster is like this.

<NodeIP>:<NodePort>

Try this one:

psql -h 192.168.65.4 -p 30000 -U myusername -d mydatabase


问:
Disable buffering of repeated button clicks
When the user clicks a button, an action is started but if the user quickly clicks the button 10 times, it will execute 10 times.  I guess the disable doesn't take effect until control returns from the event.</p>

```<code>- (IBAction)btnQuickCheckClick:(id)sender {
  @try {
    self.btnQuickCheck.enabled = NO ;
    // Next line takes about 3 seconds to execute:
    [self pollRouter] ;
  }
  @finally {
    self.btnQuickCheck.enabled = YES ;
  }
}
</code>```

答:
You can update the UI by running the run loop after disabling the button before polling:

```<code>- (IBAction)btnQuickCheckClick:(id)sender {
    self.btnQuickCheck.enabled = NO;
    // give some time for the update to take place
    [self performSelector:@selector(pollRouterMethod) withObject:nil afterDelay:0.1];
}
- (void)pollRouterMethod {
    @try {
        [self pollRouter];
    } @catch (NSException * e) { }
    // re-enable the button
    self.btnQuickCheck.enabled = YES;
}
</code>```

Of course, this method is no substitute for running a time intensive task on another thread.  For long tasks, multithreading is almost always the way to go.

Body:
When the user clicks a button, an action is started but if the user quickly clicks the button 10 times, it will execute 10 times.  I guess the disable doesn't take effect until control returns from the event.

- (IBAction)btnQuickCheckClick:(id)sender {
  @try {
    self.btnQuickCheck.enabled = NO ;
    // Next line takes about 3 seconds to execute:
    [self pollRouter] ;
  }
  @finally {
    self.btnQuickCheck.enabled = YES ;
  }
}

Body:
You can update the UI by running the run loop after disabling the button before polling:

- (IBAction)btnQuickCheckClick:(id)sender {
    self.btnQuickCheck.enabled = NO;
    // give some time for the update to take place
    [self performSelector:@selector(pollRouterMethod) withObject:nil afterDelay:0.1];
}
- (void)pollRouterMethod {
    @try {
        [self pollRouter];
    } @catch (NSException * e) { }
    // re-enable the button
    self.btnQuickCheck.enabled = YES;
}

Of course, this method is no substitute for running a time intensive task on another thread.  For long tasks, multithreading is almost always the way to go.


问:
Why Vue doesn't see vuex?
I work with microfrontend single-spa (https://single-spa.js.org/)
I create a store

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
 state: {
 count: 0
},
mutations: {

}
})
```
<p>in src/main.js i import it</p>
<pre class="lang-js prettyprint-override"><code>import Vue from 'vue';
import singleSpaVue from 'single-spa-vue';
import 'devextreme/dist/css/dx.light.css';
import App from './App.vue';
import store from './store';
console.log(" ~ file: main.js ~ line 6 ~ store", store)

Vue.config.productionTip = false;
Vue.prototype.$bus = new Vue();

const vueLifecycles = singleSpaVue({
 store,
 Vue,
 appOptions: {
  render(h) {
  return h(App, {
    store,
    props: {
    },
  });
 },
},
});

export const bootstrap = vueLifecycles.bootstrap;
export const mount = vueLifecycles.mount;
export const unmount = vueLifecycles.unmount;
</code>```

in console.log store displayed, but in the app cnsole.log(this) does not contain store

I don't understand where I am connecting wrong?

答:
According to the docs, store should be a subproperty of appOptions:

const vueLifecycles = singleSpaVue({
  // store, ❌
  Vue,
  appOptions: {
    store, ✅
    render(h) {
      return h(App, {
        // store, ❌
        props: {},
      })
    },
  },
})
```

Title: Why Vue doesn't see vuex?

Body:
I work with microfrontend single-spa (https://single-spa.js.org/)
I create a store

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
 state: {
 count: 0
},
mutations: {

}
})

in src/main.js i import it

import Vue from 'vue';
import singleSpaVue from 'single-spa-vue';
import 'devextreme/dist/css/dx.light.css';
import App from './App.vue';
import store from './store';
console.log(" ~ file: main.js ~ line 6 ~ store", store)

Vue.config.productionTip = false;
Vue.prototype.$bus = new Vue();

const vueLifecycles = singleSpaVue({
 store,
 Vue,
 appOptions: {
  render(h) {
  return h(App, {
    store,
    props: {
    },
  });
 },
},
});

export const bootstrap = vueLifecycles.bootstrap;
export const mount = vueLifecycles.mount;
export const unmount = vueLifecycles.unmount;

in console.log store displayed, but in the app cnsole.log(this) does not contain store

I don't understand where I am connecting wrong?


问:
How can I launch Android Emulator without android studio on Mac M1
I'm trying to start the emulator with this command emulator -avd Pixel_4_API_30 but it gives me an error:

```<code>[8633370112]:ERROR:android/android-emu/android/qt/qt_setup.cpp:28:Qt library not found at ../emulator/lib64/qt/lib
Could not launch '/Users/primulax/../emulator/qemu/darwin-x86_64/qemu-system-aarch64': No such file or directory
</code>```

Android Studio specs:

```<code>Build #AI-203.7717.56.2031.7935034, built on November 21, 2021
Runtime version: 11.0.10+0-b96-7249189 aarch64
VM: OpenJDK 64-Bit Server VM by JetBrains s.r.o.
macOS 12.2
GC: G1 Young Generation, G1 Old Generation
Memory: 2048M
Cores: 8
Registry: external.system.auto.import.disabled=true
Non-Bundled Plugins: org.jetbrains.kotlin
</code>```

✅ I was able to run with ~/Library/Android/sdk/emulator/emulator -avd Pixel_4_API_30 with this command

答:
If you have Android Studio installed, you can run the emulator from terminal without having started Android Studio first.

First of all, run

```<code>cd ~/Android/Sdk/tools && ./emulator -list-avds
</code>```

to get a list of all the available Android virtual devices that you have installed.

Then, copy the name of the virtual device you want to use and run

```<code>cd ~/Android/Sdk/tools && ./emulator -avd YOUR_DEVICE_NAME
</code>```

where you replace "YOUR_DEVICE_NAME" with the name of a virtual device that was listed in the installed virtual devices list.

This info and more that you may find useful can be found in the official documentation.

Now for the error you get it's most possibly due to a wrong file path. It seems that others have also faced this issue and a bug has been opened before here. The most common solution proposed is to launch emulator from the

/path/to/android-sdk/tools

directory in command line.

Also, before trying this or any other solution listed in this issue tracker, firstly make sure that you have installed from the SDK Manager the Android Emulator in SDK Tools.

Body:
I'm trying to start the emulator with this command emulator -avd Pixel_4_API_30 but it gives me an error:

[8633370112]:ERROR:android/android-emu/android/qt/qt_setup.cpp:28:Qt library not found at ../emulator/lib64/qt/lib
Could not launch '/Users/primulax/../emulator/qemu/darwin-x86_64/qemu-system-aarch64': No such file or directory

Android Studio specs:

Build #AI-203.7717.56.2031.7935034, built on November 21, 2021
Runtime version: 11.0.10+0-b96-7249189 aarch64
VM: OpenJDK 64-Bit Server VM by JetBrains s.r.o.
macOS 12.2
GC: G1 Young Generation, G1 Old Generation
Memory: 2048M
Cores: 8
Registry: external.system.auto.import.disabled=true
Non-Bundled Plugins: org.jetbrains.kotlin

✅ I was able to run with ~/Library/Android/sdk/emulator/emulator -avd Pixel_4_API_30 with this command

Body:
If you have Android Studio installed, you can run the emulator from terminal without having started Android Studio first.

First of all, run

cd ~/Android/Sdk/tools && ./emulator -list-avds

to get a list of all the available Android virtual devices that you have installed.

Then, copy the name of the virtual device you want to use and run

cd ~/Android/Sdk/tools && ./emulator -avd YOUR_DEVICE_NAME

where you replace "YOUR_DEVICE_NAME" with the name of a virtual device that was listed in the installed virtual devices list.

This info and more that you may find useful can be found in the official documentation.

Now for the error you get it's most possibly due to a wrong file path. It seems that others have also faced this issue and a bug has been opened before here. The most common solution proposed is to launch emulator from the

/path/to/android-sdk/tools

directory in command line.

Also, before trying this or any other solution listed in this issue tracker, firstly make sure that you have installed from the SDK Manager the Android Emulator in SDK Tools.


问:
Performing different actions based on the list populating the recyclerview
How do I populate my android recyclerview with different lists such that different actions are performed based on the list. For example,clicking on an item of list A would do something different from clicking on an item on list B.
Do I have to create separate adapters for each.</p>

答:
better way is to create separate adapters (if list are not too many) put list inside framelayout in main file where you want to show list

```<code><FrameLayout.....</FrameLayout>
</code>```

then replace the frame on the basis of the list selected create different fragment for all list and handle them in that their respective fragment class

Body:
better way is to create separate adapters (if list are not too many) put list inside framelayout in main file where you want to show list

<FrameLayout.....</FrameLayout>

then replace the frame on the basis of the list selected create different fragment for all list and handle them in that their respective fragment class


问:
Calculate pairwise similarity of strings in column using tidyverse
If I have a df with the following columns and rows:

row
text

1
This sentence is very similar to the next sentence

2
This sentence is not very similar to the next sentence

3
You can't sneeze with your eyes opened

...
...

How can I apply a function that check for every value in the text column whether there is a similar sentence in another row of that column? What I want to do is to then remove rows in which the value of the text column is too similar. For example, how can I ensure that no cell in the column is more than 30, 40, or 80% similar to another string in that same column?

What I want to end up with is the following:

row
text

1
This sentence is very similar to the next sentence

3
You can't sneeze with your eyes opened

...
...

答:
Not the most elegant solution and slow on a large data.frame, but you can use stringdist::stringsim. This can compare text and returns different similarity measures (see the method argument). So given your data:

df <- tibble::tribble(
  ~row, ~text,
  1,    "This sentence is very similar to the next sentence",
  2,    "This sentence is not very similar to the next sentence",
  3,    "You can't sneeze with your eyes opened"
)

stringdist::stringsim(df$text[1], df$text)
#> [1] 1.0000000 0.9259259 0.2800000
```
<p>We can wrap this in a function to compare every text with all texts that came before and return a logical vector.</p>
<pre class="lang-r prettyprint-override"><code>library(dplyr)
find_dup <- function(string, thres) {
  purrr::map_lgl(seq_along(string), function(i) {
    sim <- stringdist::stringsim(string[i], string[0:(i - 1)])
    any(sim > thres)
  })
}
</code>```

Using mutate you can check if the result is correct and then remove the duplicated entries with filter():

df %>%
  mutate(dup = find_dup(text, 0.8))
#> # A tibble: 3 × 3
#>     row text                                                   dup
#>   <dbl> <chr>                                                  <lgl>
#> 1     1 This sentence is very similar to the next sentence     FALSE
#> 2     2 This sentence is not very similar to the next sentence TRUE
#> 3     3 You can't sneeze with your eyes opened                 FALSE

df %>%
  filter(!find_dup(text, 0.8))
#> # A tibble: 2 × 2
#>     row text
#>   <dbl> <chr>
#> 1     1 This sentence is very similar to the next sentence
#> 2     3 You can't sneeze with your eyes opened
```

Created on 2022-02-07 by the reprex package (v2.0.1)

Body:
Not the most elegant solution and slow on a large data.frame, but you can use stringdist::stringsim. This can compare text and returns different similarity measures (see the method argument). So given your data:

df <- tibble::tribble(
  ~row, ~text,
  1,    "This sentence is very similar to the next sentence",
  2,    "This sentence is not very similar to the next sentence",
  3,    "You can't sneeze with your eyes opened"
)

stringdist::stringsim(df$text[1], df$text)
#> [1] 1.0000000 0.9259259 0.2800000

We can wrap this in a function to compare every text with all texts that came before and return a logical vector.

library(dplyr)
find_dup <- function(string, thres) {
  purrr::map_lgl(seq_along(string), function(i) {
    sim <- stringdist::stringsim(string[i], string[0:(i - 1)])
    any(sim > thres)
  })
}

Using mutate you can check if the result is correct and then remove the duplicated entries with filter():

df %>%
  mutate(dup = find_dup(text, 0.8))
#> # A tibble: 3 × 3
#>     row text                                                   dup
#>   <dbl> <chr>                                                  <lgl>
#> 1     1 This sentence is very similar to the next sentence     FALSE
#> 2     2 This sentence is not very similar to the next sentence TRUE
#> 3     3 You can't sneeze with your eyes opened                 FALSE

df %>%
  filter(!find_dup(text, 0.8))
#> # A tibble: 2 × 2
#>     row text
#>   <dbl> <chr>
#> 1     1 This sentence is very similar to the next sentence
#> 2     3 You can't sneeze with your eyes opened

Created on 2022-02-07 by the reprex package (v2.0.1)


问:
Sequelize Mysql - Unable to Insert model with one to many relationship
Design Overview: I've an application with Invoice creation and Inventory management features in it. Let's first understand the database design with 2 entities that we have as below:

Invoices

Items

Now, here I've a M:N relationship between these 2 entities because one invoice can contain multiple items and one item can be included in many such invoices.

So, I've created a 3rd table which we call joining table to associate these entities as shown in the image below,

Problem Statemet: I'm unable to insert model in the child table(invoice_items) using include attribute. Look at the code below to understand what's wrong happening here?

3 Model Classes as below:

1. Invoice:

Note: Providing with fewer attributes to keep it short.

module.exports = (sequelize, DataTypes) => {
    const Invoice = sequelize.define('Invoice', {
        invoiceId: {
            type: DataTypes.INTEGER.UNSIGNED,
            allowNull: false,
            autoIncrement: true,
            primaryKey: true
        },

        invoiceNumber: {
            type: DataTypes.INTEGER(6).UNSIGNED.ZEROFILL,
            allowNull: false,
            unique: true
        },

        invoiceTotal: {
            type: DataTypes.DECIMAL(9,2),
            allowNull: false,
            defaultValue: 0.00
        },

        paymentTotal: {
            type: DataTypes.DECIMAL(9,2),
            allowNull: false,
            defaultValue: 0.00
        },

        invoiceDate: {
            type: DataTypes.DATEONLY,
            defaultValue: DataTypes.NOW,
            allowNull: false
        }

    }, {
        underscored: true
    });

    Invoice.associate = function (model) {
        Invoice.belongsTo(model.Customer, {
            as: 'customer',
            foreignKey: {
                name: "cust_id",
                allowNull: false
            }
        });

        // association with 3rd table
        Invoice.hasMany(model.InvoiceItem, {
            as: 'invoice_item',
            constraints: true,
            onDelete: 'NO ACTION',
            foreignKey: {
                name: "invoice_id",
                allowNull: false
            }
        });

    };

    return Invoice;
}```
</div>
</div>
</p>
<p><strong>2. Item:</strong></p>
<p><strong><code>Note:</code></strong> Providing with fewer attributes to keep it short.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>module.exports = (sequelize, DataTypes) => {
    const Item = sequelize.define('Item', {
        itemId: {
            type: DataTypes.INTEGER.UNSIGNED,
            allowNull: false,
            autoIncrement: true,
            primaryKey: true
        },

        itemName: {
            type: DataTypes.TEXT,
            allowNull: false,
            defaultValue: ''
        },

        // this is a opening stock
        quantityInStock: {
            type: DataTypes.INTEGER.UNSIGNED,
            allowNull: false,
            defaultValue: 0,
        },

        unitPrice: {
            type: DataTypes.DECIMAL(9,2),
            allowNull: false,
            defaultValue: 0.00
        }

    }, {
        underscored: true
    });

    Item.associate = function (model) {
        // association with 3rd table
        Item.hasMany(model.InvoiceItem, {
            as: 'invoice_item', // alias name of a model
            constraints: true,
            onDelete: 'NO ACTION',
            foreignKey: {
                name: "item_id",
                allowNull: false
            }
        });

    };

    return Item;
}</code>```

3. Invoice_Item:

Note: Providing with fewer attributes to keep it short.

module.exports = (sequelize, DataTypes) => {
    const InvoiceItem = sequelize.define('InvoiceItem', {
        invoiceItemId: {
            type: DataTypes.INTEGER.UNSIGNED,
            allowNull: false,
            autoIncrement: true,
            primaryKey: true
        },

        quantity: {
            type: DataTypes.INTEGER.UNSIGNED,
            allowNull: false,
            defaultValue: 0,
        },

        rate: {
            type: DataTypes.DECIMAL(9,2),
            allowNull: false,
            defaultValue: 0.00
        }
    }, {
        underscored: true
    });

    InvoiceItem.associate = function(model) {
        InvoiceItem.belongsTo(model.Invoice,          {
            as: 'invoice',
            foreignKey: {
                name: "invoice_id",
                allowNull: false
            }
        });

        InvoiceItem.belongsTo(model.Item, {
             as: 'item',
             foreignKey: {
                name: "item_id",
                allowNull: false
            }
        });
    }

    return InvoiceItem;
}```
</div>
</div>
</p>
<p><strong>Now, I'm using below code to create an invoice with the list of items in it. But, this is not inserting the child records in the joining table(<code>invoice_items</code>). What's wrong here in the code  below?</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>invoice = await Invoice.create({
                "invoiceNumber": req.body.invoiceNumber,
                "invoiceDate": req.body.invoiceDate,
                "invoiceTotal": req.body.invoiceTotal,
                "paymentTotal": req.body.paymentTotal,
                "cust_id": req.body.customer.custId,
                invoice_items: [{
                    item_id: 1,
                    quantity: 2,
                    rate: 300
                }]
            }, {
                include: [{
                    association: InvoiceItem,
                    as: 'invoice_item'
                }]
            });</code>```

答:
After trying so many variations, I understand that there was a problem in the association of my model classes. And, below is the way of associating both Invoice and Item model classes for M:N(Many to Many) relationships. I can now update the join table(invoice_items) by inserting the record in it for each invoice we create in the system with the items in it.

Invoice.associate = function (model) {
  // association in Invoice model class
  Invoice.belongsToMany(model.Item, {
    through: 'InvoiceItem',
    constraints: true,
    onDelete: 'NO ACTION',
    foreignKey: {
        name: "invoice_id", // foreign key column name in a table invoice_items table
        allowNull: false
    }
  });
};```
</div>
</div>
</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>Item.associate = function (model) {
  // association in Item model class
  Item.belongsToMany(model.Invoice, {
    through: 'InvoiceItem',
    constraints: true,
    onDelete: 'NO ACTION',
    foreignKey: {
        name: "item_id", // foreign key column name in a table invoice_items
        allowNull: false
    }
  });
};</code>```

Create Invoice with Items in it:

Note: Passing itemId (1) as a parameter in the addItems() method. If you have multiple items in an invoice then you can add forEach loop here to iterate over each item and individually pass the itemId, quantity and rate for an item sold to the customer.

// first create the invoice
invoice = await Invoice.create(invoice);

// Next, add record in the join table
await invoice.addItems([1], {
  through: {
      quantity: item.quantity,
      rate: item.rate
  }
});  ```

Database Tables with one Test Result:

1. Invoice Table:

2. Invoice_items Table(Join Table):

Body:
Design Overview: I've an application with Invoice creation and Inventory management features in it. Let's first understand the database design with 2 entities that we have as below:

Invoices

Items

Now, here I've a M:N relationship between these 2 entities because one invoice can contain multiple items and one item can be included in many such invoices.

So, I've created a 3rd table which we call joining table to associate these entities as shown in the image below,

Problem Statemet: I'm unable to insert model in the child table(invoice_items) using include attribute. Look at the code below to understand what's wrong happening here?

3 Model Classes as below:

1. Invoice:

Note: Providing with fewer attributes to keep it short.

module.exports = (sequelize, DataTypes) => {
    const Invoice = sequelize.define('Invoice', {
        invoiceId: {
            type: DataTypes.INTEGER.UNSIGNED,
            allowNull: false,
            autoIncrement: true,
            primaryKey: true
        },

        invoiceNumber: {
            type: DataTypes.INTEGER(6).UNSIGNED.ZEROFILL,
            allowNull: false,
            unique: true
        },

        invoiceTotal: {
            type: DataTypes.DECIMAL(9,2),
            allowNull: false,
            defaultValue: 0.00
        },

        paymentTotal: {
            type: DataTypes.DECIMAL(9,2),
            allowNull: false,
            defaultValue: 0.00
        },

        invoiceDate: {
            type: DataTypes.DATEONLY,
            defaultValue: DataTypes.NOW,
            allowNull: false
        }

    }, {
        underscored: true
    });

    Invoice.associate = function (model) {
        Invoice.belongsTo(model.Customer, {
            as: 'customer',
            foreignKey: {
                name: "cust_id",
                allowNull: false
            }
        });

        // association with 3rd table
        Invoice.hasMany(model.InvoiceItem, {
            as: 'invoice_item',
            constraints: true,
            onDelete: 'NO ACTION',
            foreignKey: {
                name: "invoice_id",
                allowNull: false
            }
        });

    };

    return Invoice;
}

2. Item:

Note: Providing with fewer attributes to keep it short.

module.exports = (sequelize, DataTypes) => {
    const Item = sequelize.define('Item', {
        itemId: {
            type: DataTypes.INTEGER.UNSIGNED,
            allowNull: false,
            autoIncrement: true,
            primaryKey: true
        },

        itemName: {
            type: DataTypes.TEXT,
            allowNull: false,
            defaultValue: ''
        },

        // this is a opening stock
        quantityInStock: {
            type: DataTypes.INTEGER.UNSIGNED,
            allowNull: false,
            defaultValue: 0,
        },

        unitPrice: {
            type: DataTypes.DECIMAL(9,2),
            allowNull: false,
            defaultValue: 0.00
        }

    }, {
        underscored: true
    });

    Item.associate = function (model) {
        // association with 3rd table
        Item.hasMany(model.InvoiceItem, {
            as: 'invoice_item', // alias name of a model
            constraints: true,
            onDelete: 'NO ACTION',
            foreignKey: {
                name: "item_id",
                allowNull: false
            }
        });

    };

    return Item;
}

3. Invoice_Item:

Note: Providing with fewer attributes to keep it short.

module.exports = (sequelize, DataTypes) => {
    const InvoiceItem = sequelize.define('InvoiceItem', {
        invoiceItemId: {
            type: DataTypes.INTEGER.UNSIGNED,
            allowNull: false,
            autoIncrement: true,
            primaryKey: true
        },

        quantity: {
            type: DataTypes.INTEGER.UNSIGNED,
            allowNull: false,
            defaultValue: 0,
        },

        rate: {
            type: DataTypes.DECIMAL(9,2),
            allowNull: false,
            defaultValue: 0.00
        }
    }, {
        underscored: true
    });

    InvoiceItem.associate = function(model) {
        InvoiceItem.belongsTo(model.Invoice,          {
            as: 'invoice',
            foreignKey: {
                name: "invoice_id",
                allowNull: false
            }
        });

        InvoiceItem.belongsTo(model.Item, {
             as: 'item',
             foreignKey: {
                name: "item_id",
                allowNull: false
            }
        });
    }

    return InvoiceItem;
}

Now, I'm using below code to create an invoice with the list of items in it. But, this is not inserting the child records in the joining table(invoice_items). What's wrong here in the code  below?

invoice = await Invoice.create({
                "invoiceNumber": req.body.invoiceNumber,
                "invoiceDate": req.body.invoiceDate,
                "invoiceTotal": req.body.invoiceTotal,
                "paymentTotal": req.body.paymentTotal,
                "cust_id": req.body.customer.custId,
                invoice_items: [{
                    item_id: 1,
                    quantity: 2,
                    rate: 300
                }]
            }, {
                include: [{
                    association: InvoiceItem,
                    as: 'invoice_item'
                }]
            });

Body:
After trying so many variations, I understand that there was a problem in the association of my model classes. And, below is the way of associating both Invoice and Item model classes for M:N(Many to Many) relationships. I can now update the join table(invoice_items) by inserting the record in it for each invoice we create in the system with the items in it.

Invoice.associate = function (model) {
  // association in Invoice model class
  Invoice.belongsToMany(model.Item, {
    through: 'InvoiceItem',
    constraints: true,
    onDelete: 'NO ACTION',
    foreignKey: {
        name: "invoice_id", // foreign key column name in a table invoice_items table
        allowNull: false
    }
  });
};

Item.associate = function (model) {
  // association in Item model class
  Item.belongsToMany(model.Invoice, {
    through: 'InvoiceItem',
    constraints: true,
    onDelete: 'NO ACTION',
    foreignKey: {
        name: "item_id", // foreign key column name in a table invoice_items
        allowNull: false
    }
  });
};

Create Invoice with Items in it:

Note: Passing itemId (1) as a parameter in the addItems() method. If you have multiple items in an invoice then you can add forEach loop here to iterate over each item and individually pass the itemId, quantity and rate for an item sold to the customer.

// first create the invoice
invoice = await Invoice.create(invoice);

// Next, add record in the join table
await invoice.addItems([1], {
  through: {
      quantity: item.quantity,
      rate: item.rate
  }
});

Database Tables with one Test Result:

1. Invoice Table:

2. Invoice_items Table(Join Table):


答:
Here is an approach using Reduce() and then some fiddling to get the NA values.

```<code>f <- function(vec, value) {
replace(
  Reduce(
    function(x, y)
      x  + (y * x) ,
    vec != value,
    right = TRUE,
    accumulate = TRUE
  ),
  max(tail(which(vec == value), 1), 0) < seq_along(vec),
  NA
)
}

f(int, 0)
[1]  2  1  0  2  1  0  0 NA

f(int, 1)
[1]  0  0 NA NA NA NA NA NA

f(int, 2)
[1] 4 3 2 1 0 2 1 0

f(int, 3)
[1] NA NA NA NA NA NA NA NA

char = c("A", "B", "C", "A", "A")

f(char, "A")
[1] 0 2 1 0 0
</code>```

Title: Closest subsequent index for a specified value

Body:
Consider a vector:

int = c(1, 1, 0, 5, 2, 0, 0, 2)

I'd like to get the closest subsequent index (not the difference) for a specified value. The first parameter of the function should be the vector, while the second should be the value one wants to see the closest subsequent elements.

For instance,

f(int, 0)
# [1] 2 1 0 2 1 0 0 NA

Here, the first element of the vector (1) is two positions away from the first subsequent 0, (3 - 1 = 2), so it should return 2. Then the second element is 1 position away from a 0 (2 - 1 = 1). When there is no subsequent values that match the specified value, return NA (here it's the case for the last element, because no subsequent value is 0).

Other examples:

f(int, 1)
# [1] 0 0 NA NA NA NA NA NA

f(int, 2)
# [1] 4 3 2 1 0 2 1 0

f(int, 3)
# [1] NA NA NA NA NA NA NA NA

This should also work for character vectors:

char = c("A", "B", "C", "A", "A")

f(char, "A")
# [1] 0 2 1 0 0

Body:
Here is an approach using Reduce() and then some fiddling to get the NA values.

f <- function(vec, value) {
replace(
  Reduce(
    function(x, y)
      x  + (y * x) ,
    vec != value,
    right = TRUE,
    accumulate = TRUE
  ),
  max(tail(which(vec == value), 1), 0) < seq_along(vec),
  NA
)
}

f(int, 0)
[1]  2  1  0  2  1  0  0 NA

f(int, 1)
[1]  0  0 NA NA NA NA NA NA

f(int, 2)
[1] 4 3 2 1 0 2 1 0

f(int, 3)
[1] NA NA NA NA NA NA NA NA

char = c("A", "B", "C", "A", "A")

f(char, "A")
[1] 0 2 1 0 0


问:
Does DotNetOpenAuth OpenId Provider actually work?
Using DotNetOpenAuth. I'm trying to get the Provider endpoint to work. When I set a break point on the code to accept OpenId request:

```<code>IRequest request = OpenIdProvider.GetRequest();
</code>```

This returns null when I use a relying party to call the provider. I hosted the solution and its the same problem. I added localhost to the whitelist also.

But the point is, the request reaches the provider but it is saying that there was no openId request. Here is the provider endpoint, if you want to test it.

答:
I think you may be confusing the "OP Identifier" or Claimed Identifier with the OP Endpoint.  Your page claims to be an OP Endpoint, which it probably is.  But no one can test that directly.  You need to type an OpenID identifier into an RP to kick start the process, and that identifier tells the RP which OP Endpoint to talk to.  So quite likely, if you're typing http://dev1.ncu.edu.jm/openid/provider into your RP, the RP is sending a discovery request to that URL and not seeing any identifier there.

Try pointing an Identifier to that OP Endpoint and passing that identifier to the RP instead.

Also, activating logging on the RP and OP will surely yield some helpful tips.

Body:
Using DotNetOpenAuth. I'm trying to get the Provider endpoint to work. When I set a break point on the code to accept OpenId request:

IRequest request = OpenIdProvider.GetRequest();

This returns null when I use a relying party to call the provider. I hosted the solution and its the same problem. I added localhost to the whitelist also.

But the point is, the request reaches the provider but it is saying that there was no openId request. Here is the provider endpoint, if you want to test it.


问:
Extract all icons of a file
First of all, I want to access all icons (16x16...256x256 and larger) in a ".exe" file.

As a result of my research, I found such code:

```<code>#ifndef __ICON_LIST_H__
#define __ICON_LIST_H__

#include <windows.h>
#include <vector>

class IconFile: public std::vector<HICON>{
public:

  IconFile(){};

  IconFile(std::string i_filename){
    addIconsFromFile(i_filename);
  };

  int addIconsFromFile(std::string i_fileName){
    int iCount=0;
    HANDLE file = CreateFile( i_fileName.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL,
OPEN_EXISTING, 0, NULL);
    if(file!=INVALID_HANDLE_VALUE){
      int   size   = GetFileSize(file,NULL);
      DWORD actRead;
      BYTE* buffer = new BYTE[size];
      ReadFile(file, buffer, size, &actRead, NULL);
      CloseHandle(file);
      int ind = -1;
      for(int p = 0; p< size-4; ++p){
        if(buffer[p]==40 && buffer[p+1]==0 && buffer[p+2]==0 && buffer[p+3]==0){
          HICON icon = CreateIconFromResourceEx(&buffer[p], size-p, true, 0x00030000,0,0,0);
          if(icon){
            ++iCount;
            this->push_back(icon);
          }
        }
      }
      delete[] buffer;
    }
    return iCount;
  };
};
#endif //__ICON_LIST_H__
</code>```

This code works fine but doesn't show 256x256 or larger icon, Code output:

```<code>std::vector(0x8ef2013, 0x64ce1867, 0x24681219)
</code>```

Currently, this is the icon list of the file:

How can I get the 256x256 icon?

答:
Use LoadLibraryEx to load the file, EnumResourceNames to enumerate icons, and CreateIconFromResourceEx to lead each icon.

Note that driving a class from std::vector and other C++ Standard Library containers is not recommended.

The example below uses LR_SHARED, you might want to change that.

```<code>#include <windows.h>
#include <vector>

BOOL CALLBACK EnumIcons(HMODULE hmodule, LPCTSTR type, LPTSTR lpszName,
    LONG_PTR ptr)
{
    if (!ptr)
        return FALSE;
    auto pvec = (std::vector<HICON>*)ptr;
    auto hRes = FindResource(hmodule, lpszName, type);
    if (!hRes)
        return TRUE;
    auto size = SizeofResource(hmodule, hRes);
    auto hg = LoadResource(hmodule, hRes);
    if (!hg)
        return TRUE;
    auto bytes = (BYTE*)LockResource(hg);
    auto hicon = CreateIconFromResourceEx(bytes, size, TRUE, 0x00030000,
        0, 0, LR_SHARED);
    if (hicon)
        pvec->push_back(hicon);
    return TRUE;
}

int main()
{
    std::vector<HICON> vec;
    const char* modulepath = "file.exe";
    HMODULE hmodule = LoadLibraryEx(modulepath, NULL,
        LOAD_LIBRARY_AS_IMAGE_RESOURCE);
    if (!hmodule)
        return 0;

    EnumResourceNames(hmodule, RT_ICON,(ENUMRESNAMEPROC)EnumIcons,(LONG_PTR)&vec);
    for (auto e : vec)
    {
        ICONINFOEX ii = { sizeof(ii) };
        if (!GetIconInfoEx(e, &ii) || !ii.hbmColor)
            continue;
        BITMAP bm;
        GetObject(ii.hbmColor, sizeof(bm), &bm);
        printf("%d %d %d\n", bm.bmWidth, bm.bmHeight, bm.bmBitsPixel);
    }

    //free icons...
    return 0;
}
</code>```

Title: Extract all icons of a file

Body:
First of all, I want to access all icons (16x16...256x256 and larger) in a ".exe" file.

As a result of my research, I found such code:

#ifndef __ICON_LIST_H__
#define __ICON_LIST_H__

#include <windows.h>
#include <vector>

class IconFile: public std::vector<HICON>{
public:

  IconFile(){};

  IconFile(std::string i_filename){
    addIconsFromFile(i_filename);
  };

  int addIconsFromFile(std::string i_fileName){
    int iCount=0;
    HANDLE file = CreateFile( i_fileName.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL,
OPEN_EXISTING, 0, NULL);
    if(file!=INVALID_HANDLE_VALUE){
      int   size   = GetFileSize(file,NULL);
      DWORD actRead;
      BYTE* buffer = new BYTE[size];
      ReadFile(file, buffer, size, &actRead, NULL);
      CloseHandle(file);
      int ind = -1;
      for(int p = 0; p< size-4; ++p){
        if(buffer[p]==40 && buffer[p+1]==0 && buffer[p+2]==0 && buffer[p+3]==0){
          HICON icon = CreateIconFromResourceEx(&buffer[p], size-p, true, 0x00030000,0,0,0);
          if(icon){
            ++iCount;
            this->push_back(icon);
          }
        }
      }
      delete[] buffer;
    }
    return iCount;
  };
};
#endif //__ICON_LIST_H__

This code works fine but doesn't show 256x256 or larger icon, Code output:

std::vector(0x8ef2013, 0x64ce1867, 0x24681219)

Currently, this is the icon list of the file:

How can I get the 256x256 icon?

Body:
Use LoadLibraryEx to load the file, EnumResourceNames to enumerate icons, and CreateIconFromResourceEx to lead each icon.

Note that driving a class from std::vector and other C++ Standard Library containers is not recommended.

The example below uses LR_SHARED, you might want to change that.

#include <windows.h>
#include <vector>

BOOL CALLBACK EnumIcons(HMODULE hmodule, LPCTSTR type, LPTSTR lpszName,
    LONG_PTR ptr)
{
    if (!ptr)
        return FALSE;
    auto pvec = (std::vector<HICON>*)ptr;
    auto hRes = FindResource(hmodule, lpszName, type);
    if (!hRes)
        return TRUE;
    auto size = SizeofResource(hmodule, hRes);
    auto hg = LoadResource(hmodule, hRes);
    if (!hg)
        return TRUE;
    auto bytes = (BYTE*)LockResource(hg);
    auto hicon = CreateIconFromResourceEx(bytes, size, TRUE, 0x00030000,
        0, 0, LR_SHARED);
    if (hicon)
        pvec->push_back(hicon);
    return TRUE;
}

int main()
{
    std::vector<HICON> vec;
    const char* modulepath = "file.exe";
    HMODULE hmodule = LoadLibraryEx(modulepath, NULL,
        LOAD_LIBRARY_AS_IMAGE_RESOURCE);
    if (!hmodule)
        return 0;

    EnumResourceNames(hmodule, RT_ICON,(ENUMRESNAMEPROC)EnumIcons,(LONG_PTR)&vec);
    for (auto e : vec)
    {
        ICONINFOEX ii = { sizeof(ii) };
        if (!GetIconInfoEx(e, &ii) || !ii.hbmColor)
            continue;
        BITMAP bm;
        GetObject(ii.hbmColor, sizeof(bm), &bm);
        printf("%d %d %d\n", bm.bmWidth, bm.bmHeight, bm.bmBitsPixel);
    }

    //free icons...
    return 0;
}