问:
HTML how to tell which elements are visible?
I have seen several solutions which determine when an element is visible in the viewport whilst scrolling the page, but I haven't seen any which do this for elements that are contained in a scrolling container div as in the example here.

How would I detect the items as they scroll into view via the scrolling div? And by contrast how would I detect them if they fell out of view. In all cases the overflow elements are not hidden at the outset.

HTML

```<code>    <div id="mainContainer" class="main">
        <div id="scrollContainer"class="scroller">
            <div id="picturesContainer"class="holder">
                <div id="pictureContainer1" class="picture position1">
                pictureContainer1</div>

                <div id="pictureContainer2" class="picture position2">
                pictureContainer2</div>
                <div id="pictureContainer3" class="picture position3">
                pictureContainer3</div>
                <div id="pictureContainer4" class="picture position4">
                pictureContainer4</div>
                <div id="pictureContainer5" class="picture position5">
                pictureContainer5</div>
                <div id="pictureContainer6" class="picture position6">
                pictureContainer6</div>
                <div id="pictureContainer7" class="picture position7">
                pictureContainer7</div>
                <div id="pictureContainer8" class="picture position8">
                pictureContainer8</div>
                <div id="pictureContainer9" class="picture position9">
                pictureContainer9</div>
            </div>

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

CSS

```<code>    .main{
        position:absolute;
        top:0px;
        left:0px;
        height: 200px;
        width:200px;
        background-color: grey;
        border: 1px solid black;
    }

    .scroller{
        position:absolute;
        top:0px;
        left:0px;
        height: 250px;
        width:250px;
        background-color: lightblue;
        border: 1px solid black;
        overflow: scroll;
    }

    .picture{
        position:absolute;
        height: 200px;
        width: 200px;
        background-color: lightyellow;
        border: 1px solid black;
    }

    .position1{
        top:0px;
        left:0px;
    }

    .position2{
        top:0px;
        left:200px;
    }

    .position3{
        top:0px;
        left:400px;
    }

    .position4{
        top:200px;
        left:0px;
    }

    .position5{
        top:200px;
        left:200px;
    }

    .position6{
        top:200px;
        left:400px;
    }

    .position7{
        top:400px;
        left:0px;
    }

    .position8{
        top:400px;
        left:200px;
    }

    .position9{
        top:400px;
        left:400px;
    }

    .holder{
        position:absolute;
        top:0px;
        left:0px;
        width:600px;
        height:600px;
        background-color:lightgreen;
    }
</code>```

答:
include jQuery library on page first.

```<code>function getObjDims(obj){
    if (!obj) return false;
    var off = $(obj).offset();
    var t = {
        top:off.top,
        left:off.left,
        width:$(obj).width(),
        height:$(obj).height()
    };
    return {x1:t.left, y1:t.top, x2:t.left+t.width,y2:t.top+t.height}
};
function testInside(pic,box){
    var d=getObjDims(pic);
    return (box.x1<=d.x1 && box.y1<=d.y1 && box.x2>=d.x2 && box.y2>=d.y2)?1:-1;
};
$(document).ready(function(){
    var inside={};
    var port=$('#scrollContainer');
    var box=getObjDims(port);
    $(window).resize(function(){
        box=getObjDims(port);
    });
    $(port).scroll(function(){
        var str=[];
        $('.picture').each(function(i){
            var oldState = inside[this.id]!=undefined?inside[this.id]:0;
            var newState = testInside(this,box);
            inside[this.id]=newState;
            if (oldState!=newState)
                switch (newState){
                    case 1:str.push(this.id);break;// go IN
                    case -1: break;// go OUT
                }
        });
        $('#picStatus').text(str.join(', '));
    });
});
</code>```

Add in HTML for results output:

```<code><div style='margin-top:280px;'>Pictures in window (numbers):</div>
<div id='picStatus'></div>
</code>```

It is code based on object's coords, witch are recalculated on scroll event. There are some things to know. IE and, seems to be, Opera takes into consideration width and height of scrollbars themselves, that demands curtain code tuning. I just have suggested solution direction and did not spent much time for debugging this.

And yet, maybe will be useful following (from jquery api about offset):

Note: jQuery does not support getting
  the offset coordinates of hidden
  elements or accounting for borders,
  margins, or padding set on the body
  element.

Body:
I have seen several solutions which determine when an element is visible in the viewport whilst scrolling the page, but I haven't seen any which do this for elements that are contained in a scrolling container div as in the example here.

How would I detect the items as they scroll into view via the scrolling div? And by contrast how would I detect them if they fell out of view. In all cases the overflow elements are not hidden at the outset.

HTML

                pictureContainer1

                pictureContainer2

                pictureContainer3

                pictureContainer4

                pictureContainer5

                pictureContainer6

                pictureContainer7

                pictureContainer8

                pictureContainer9

CSS

    .main{
        position:absolute;
        top:0px;
        left:0px;
        height: 200px;
        width:200px;
        background-color: grey;
        border: 1px solid black;
    }

    .scroller{
        position:absolute;
        top:0px;
        left:0px;
        height: 250px;
        width:250px;
        background-color: lightblue;
        border: 1px solid black;
        overflow: scroll;
    }

    .picture{
        position:absolute;
        height: 200px;
        width: 200px;
        background-color: lightyellow;
        border: 1px solid black;
    }

    .position1{
        top:0px;
        left:0px;
    }

    .position2{
        top:0px;
        left:200px;
    }

    .position3{
        top:0px;
        left:400px;
    }

    .position4{
        top:200px;
        left:0px;
    }

    .position5{
        top:200px;
        left:200px;
    }

    .position6{
        top:200px;
        left:400px;
    }

    .position7{
        top:400px;
        left:0px;
    }

    .position8{
        top:400px;
        left:200px;
    }

    .position9{
        top:400px;
        left:400px;
    }

    .holder{
        position:absolute;
        top:0px;
        left:0px;
        width:600px;
        height:600px;
        background-color:lightgreen;
    }

Body:
include jQuery library on page first.

function getObjDims(obj){
    if (!obj) return false;
    var off = $(obj).offset();
    var t = {
        top:off.top,
        left:off.left,
        width:$(obj).width(),
        height:$(obj).height()
    };
    return {x1:t.left, y1:t.top, x2:t.left+t.width,y2:t.top+t.height}
};
function testInside(pic,box){
    var d=getObjDims(pic);
    return (box.x1<=d.x1 && box.y1<=d.y1 && box.x2>=d.x2 && box.y2>=d.y2)?1:-1;
};
$(document).ready(function(){
    var inside={};
    var port=$('#scrollContainer');
    var box=getObjDims(port);
    $(window).resize(function(){
        box=getObjDims(port);
    });
    $(port).scroll(function(){
        var str=[];
        $('.picture').each(function(i){
            var oldState = inside[this.id]!=undefined?inside[this.id]:0;
            var newState = testInside(this,box);
            inside[this.id]=newState;
            if (oldState!=newState)
                switch (newState){
                    case 1:str.push(this.id);break;// go IN
                    case -1: break;// go OUT
                }
        });
        $('#picStatus').text(str.join(', '));
    });
});

Add in HTML for results output:

<div style='margin-top:280px;'>Pictures in window (numbers):</div>
<div id='picStatus'></div>

It is code based on object's coords, witch are recalculated on scroll event. There are some things to know. IE and, seems to be, Opera takes into consideration width and height of scrollbars themselves, that demands curtain code tuning. I just have suggested solution direction and did not spent much time for debugging this.

And yet, maybe will be useful following (from jquery api about offset):

Note: jQuery does not support getting
  the offset coordinates of hidden
  elements or accounting for borders,
  margins, or padding set on the body
  element.


来源: stackexchange

问:
Linux error while loading shared libraries: cannot open shared object file: No such file or directory
Program is part of the Xenomai test suite, cross-compiled from Linux PC into Linux+Xenomai ARM toolchain.

```<code># echo $LD_LIBRARY_PATH
/lib
# ls /lib
ld-2.3.3.so         libdl-2.3.3.so      libpthread-0.10.so
ld-linux.so.2       libdl.so.2          libpthread.so.0
libc-2.3.3.so       libgcc_s.so         libpthread_rt.so
libc.so.6           libgcc_s.so.1       libstdc++.so.6
libcrypt-2.3.3.so   libm-2.3.3.so       libstdc++.so.6.0.9
libcrypt.so.1       libm.so.6
# ./clocktest
./clocktest: error while loading shared libraries: libpthread_rt.so.1: cannot open shared object file: No such file or directory
</code>```

Is the .1 at the end part of the filename? What does that mean anyway?

答:
I use Ubuntu 18.04

Installing the corresponding -dev package worked for me,

```<code>sudo apt install libgconf2-dev
</code>```

Before installing the above package, I was getting the below error:

```<code>turtl: error while loading shared libraries: libgconf-2.so.4: cannot open shared object file: No such file or directory
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Program is part of the Xenomai test suite, cross-compiled from Linux PC into Linux+Xenomai ARM toolchain.

# echo $LD_LIBRARY_PATH
/lib
# ls /lib
ld-2.3.3.so         libdl-2.3.3.so      libpthread-0.10.so
ld-linux.so.2       libdl.so.2          libpthread.so.0
libc-2.3.3.so       libgcc_s.so         libpthread_rt.so
libc.so.6           libgcc_s.so.1       libstdc++.so.6
libcrypt-2.3.3.so   libm-2.3.3.so       libstdc++.so.6.0.9
libcrypt.so.1       libm.so.6
# ./clocktest
./clocktest: error while loading shared libraries: libpthread_rt.so.1: cannot open shared object file: No such file or directory

Is the .1 at the end part of the filename? What does that mean anyway?

Body:
I use Ubuntu 18.04

Installing the corresponding -dev package worked for me,

sudo apt install libgconf2-dev

Before installing the above package, I was getting the below error:

turtl: error while loading shared libraries: libgconf-2.so.4: cannot open shared object file: No such file or directory


问:
How do I update zsh to the latest version?
I recently switched to zsh on my Terminal.app on my OS X machine successfully. The version number of zsh is 4.3.11.</p>

答: I just switched the main shell to zsh. It suppresses the warnings and it isn't too complicated.</p>

ContentLicense: CC BY-SA 3.0


问:
How would I grow <TextInput> height upon text wrapping?
I'm trying to create a <TextInput> that can grow in height when the text wraps to the next line, similar to how Slack's message input grows with the text up to a point.

I have the multiline prop set, so it is wrapping but the docs don't seem to mention any event regarding wrapping, and the only thing I can think of is a really hacky strategy to character count to figure out when to increase height of the input. How would I accomplish this?
https://facebook.github.io/react-native/docs/textinput.html

答:
What I have done is set View for the Input max height, for example:

```<code>messageBox: {
maxHeight: 110,
width: '80%',
borderRadius: 10,
padding: 10,
backgroundColor: Color.White},
</code>```

and set the Input to multiline:

```<code><View style={[styles.messageBox, styles.managerMsg]}>
  <Input
    allowFontScaling={false}
    name="notes"
    blurOnSubmit={false}
    onChangeText={notes => console.log(notes)}
    returnKeyType="go"
    onSubmitEditing={() => Keyboard.dismiss()}
    multiline
  />
</View>
</code>```

This "Input" is just a simple custom component that receives all Props.

Body:
What I have done is set View for the Input max height, for example:

messageBox: {
maxHeight: 110,
width: '80%',
borderRadius: 10,
padding: 10,
backgroundColor: Color.White},

and set the Input to multiline:

<View style={[styles.messageBox, styles.managerMsg]}>
  <Input
    allowFontScaling={false}
    name="notes"
    blurOnSubmit={false}
    onChangeText={notes => console.log(notes)}
    returnKeyType="go"
    onSubmitEditing={() => Keyboard.dismiss()}
    multiline
  />
</View>

This "Input" is just a simple custom component that receives all Props.


问:
Scripting Workaround for 50,000 Character Cell Limit?
Problem:

In Google Sheets, I use the IMPORTDATA function with an API call to a 3rd party data provider that frequently produces a text string that is longer than the cell limit of 50,000 characters.  I have no control over the length of the text string that is provided to me, and when the 50,000 character limit is exceeded, I end up with no data at all.

Question:

Is there any way to use scripting for the API call (to avoid the 50,000 character limit) - and then parse that data to two or more cells so that the cell limit is not exceeded?

答:
My suggestion would be to use Google Apps Scripts to make the API call. That will return your data as JSON, a string, or some other data type depending on how the API returns data.

Once you have the data in your Google Apps Script you could split the data out into smaller chunks. There are lots of JavaScript string methods for that. You can convert JSON to a compact string using JSON.stringify(yourJSONObject). Once you have your data split out how you want, you can use the Google Sheets API (https://developers.google.com/sheets/api/quickstart/apps-script) to insert the cells you need.

On a side note, I know it says the character limit is 50K everywhere you look, but I have been adding cells that have close to 500K characters in them. Perhaps that is because it is my work account which has G Suite. I would like to read some documentation somewhere on why I can enter way more than 50K characters in a cell.

Documentation on API Calls in Google Apps Scripts:

https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app

https://developers.google.com/apps-script/guides/services/external


问:
How to hold plot figures in Python
I have this code, where c_X,c_Y,c_Z,X,Y,Z X_2,Y_2,Z_2,X_4,Y_4,Z_4, are lists of points (my data).

```<code>import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

for i in range (2):

    fig = plt.figure(i)
    ax = fig.add_subplot(111, projection='3d')

    ax.scatter(c_X,c_Y,c_Z, color = 'midnightblue')
    ax.scatter(X, Y, Z, color = 'mediumaquamarine')
    ax.scatter(X_2,Y_2,Z_2, color = 'cadetblue')
    ax.scatter(X_4,Y_4,Z_4, color = 'cadetblue')
    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.set_zlabel('z')
    plt.draw()
</code>```

How can i hold or get the 3 plots, in 3 different figures, in the end ?

答:
Modify your code as suggested in the comments to your question.

```<code>import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

for i in range (2):

    fig = plt.figure(i)
    ax = fig.add_subplot(111, projection='3d')

    ax.scatter(c_X,c_Y,c_Z, color = 'midnightblue')
    ax.scatter(X, Y, Z, color = 'mediumaquamarine')
    ax.scatter(X_2,Y_2,Z_2, color = 'cadetblue')
    ax.scatter(X_4,Y_4,Z_4, color = 'cadetblue')
    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.set_zlabel('z')
plt.show()
</code>```

I think this does what you want.

Title: How to hold plot figures in Python

Body:
I have this code, where c_X,c_Y,c_Z,X,Y,Z X_2,Y_2,Z_2,X_4,Y_4,Z_4, are lists of points (my data).

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

for i in range (2):

    fig = plt.figure(i)
    ax = fig.add_subplot(111, projection='3d')

    ax.scatter(c_X,c_Y,c_Z, color = 'midnightblue')
    ax.scatter(X, Y, Z, color = 'mediumaquamarine')
    ax.scatter(X_2,Y_2,Z_2, color = 'cadetblue')
    ax.scatter(X_4,Y_4,Z_4, color = 'cadetblue')
    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.set_zlabel('z')
    plt.draw()

How can i hold or get the 3 plots, in 3 different figures, in the end ?

Body:
Modify your code as suggested in the comments to your question.

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

for i in range (2):

    fig = plt.figure(i)
    ax = fig.add_subplot(111, projection='3d')

    ax.scatter(c_X,c_Y,c_Z, color = 'midnightblue')
    ax.scatter(X, Y, Z, color = 'mediumaquamarine')
    ax.scatter(X_2,Y_2,Z_2, color = 'cadetblue')
    ax.scatter(X_4,Y_4,Z_4, color = 'cadetblue')
    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.set_zlabel('z')
plt.show()

I think this does what you want.


问:
How might a broken netcat transfer be completed?
For reasons of speed, I've got netcat sending a big, single .tgz archive file from one computer to a remote computer. In my observations netcat is faster than rsync for this sort of transfer. The transfer was set up in a way like the following.

On the receiving machine, the following command was run first:

```<code>time nc -vl 33333 > archive.tgz
</code>```

On the sending machine, the following command was run second:

```<code>time nc -N $SERVERIP 33333 < archive.tgz
</code>```

On the receiving machine, the progress can be interpreted by measuring the (known) size of the file that is being received:

```<code>ls -al --block-size=M
</code>```

Now let's say the transfer were interrupted somehow. Say the sending computer has a power cut or the internet connection died. Under the assumption that restarting the transfer is excluded as an option (due to the time taken to transfer the large file), what would be a reasonable way to pick up the transfer? Could netcat somehow pick up the transfer again? Would rsync be able to pick up the pieces and complete the transfer?

答:
Yes, rsync will scan the file on each side in chunks, and transfer only the chunks that are missing.

Note that rsync (usually) transfers your data via an encrypted SSH tunnel, whereas netcat is transferring the data in clear text (you may be aware of this, but random readers should beware!)

Body:
For reasons of speed, I've got netcat sending a big, single .tgz archive file from one computer to a remote computer. In my observations netcat is faster than rsync for this sort of transfer. The transfer was set up in a way like the following.

On the receiving machine, the following command was run first:

time nc -vl 33333 > archive.tgz

On the sending machine, the following command was run second:

time nc -N $SERVERIP 33333 < archive.tgz

On the receiving machine, the progress can be interpreted by measuring the (known) size of the file that is being received:

ls -al --block-size=M

Now let's say the transfer were interrupted somehow. Say the sending computer has a power cut or the internet connection died. Under the assumption that restarting the transfer is excluded as an option (due to the time taken to transfer the large file), what would be a reasonable way to pick up the transfer? Could netcat somehow pick up the transfer again? Would rsync be able to pick up the pieces and complete the transfer?


问:
How to find out which Visual Studio extensions are installed on user's machines?
How to find out which Visual Studio extensions are installed on user's machines?

I want to track which VS extensions are installed on users' computers in AD environment. I think that's easy when an extension installs via Windows Installer (*.msi). But what about VSIX extensions (vsixinstaller.exe)?

答:
I suspect the IVsExtensionManager.GetInstalledExtensions API is what you're looking for.

Also, Mad's published an open source "Extension Manager 2019" extension, that implements an export/import extensions command, which you might find as a useful example.

The source for the extension can be found in the following github repo:

ExtensionPackTools

Sincerely


问:
unique keys are unique, are assigned to key prop, but still getting error... but only in one component
within my main App render function... I have this list generated.

```<code>    const buildings = this.state.buildings.map(buildingData=>
      {
       console.log("unique id is:", buildingData.id)
      return(
        <Building
          key={buildingData.id}
          name ={buildingData.name}
          handleBuildingBuy={this.handleBuildingBuy}
          buyPrice={buildingData.buyPrice}
          count = {buildingData.count}
          subjectsOfIncrease = {buildingData.subjectsOfIncrease}
          isBuyable = {buildingData.isBuyable}
          isUnlocked = {buildingData.isUnlocked}

        />)
    });

</code>```

but I still get the console output error, even though each key is both defined and unique....

```<code>App.js:224 unique id is: 0
App.js:224 unique id is: 1
App.js:224 unique id is: 2
App.js:224 unique id is: 3
App.js:224 unique id is: 4
App.js:224 unique id is: 5
App.js:224 unique id is: 6
App.js:224 unique id is: 7
index.js:1 Warning: Each child in a list should have a unique "key" prop.

Check the render method of `Building`. See react-warning-keys for more information.
    in div (at Building.js:11)
    in Building (at App.js:226)
    in div (at App.js:275)
    in div (at App.js:274)
    in App (at src/index.js:8)

</code>```

weirder still I have a similar loop for other things, where key is not acting weird.

```<code>    const resources = this.state.resources.map(resourceData=>
      {
       console.log("unique resourceName is:", resourceData.name)

        return(

        <Resource
          name ={resourceData.name}
          max = {resourceData.max}
          isUnlocked = {resourceData.isUnlocked}
          changePerTick = {resourceData.changePerTick}
          amount={resourceData.amount}
          key={resourceData.name} //change out to a number - names are in fact unique.

        />)
    });

</code>```

and that output is:

```<code>unique resourceName is: grey
App.js:240 unique resourceName is: red
App.js:240 unique resourceName is: green
App.js:240 unique resourceName is: blue
App.js:240 unique resourceName is: purple
App.js:240 unique resourceName is: teal
App.js:240 unique resourceName is: orange
</code>```

so I don't understand why the above isn't working while in the same page the below is.

can anyone shed any light as to what may be happening?

edit: in case it is relevant, the building component

```<code>function Building(props)
    {
    if(props.isUnlocked)
        {
        const buyClass = props.isBuyable ? "afford": "cantAfford";
        const PriceList = props.buyPrice.map(price=>
            {
            return(
                <div>
                    {price.name}: {price.cost}
                </div>
            )
        })

        return(

        <div className="building">
            <div className="buildingTitle"> BUY FOR:

                <div className={buyClass}>{PriceList}</div>

            </div>
             <div className="buildingBuyContainer">
                {props.isBuyable ?
                    <button name={props.name} onClick={props.handleBuildingBuy} className="buildingBuyBTN">{props.name}</button>
                    :
                    <button name={props.name} className="buildingNoBuyBTN">{props.name}</button>
                }
            </div>
            <div className="counter"> COUNT:{props.count}
        </div>
        </div>

        )
    }
    else{return null}
}

</code>```

答:
As indicated by the error message, the problem is within your <Building> component:

Check the render method of Building.

It even tells you where:

in div (at Building.js:11)

Valiant debugging efforts though!

eta: If your buyPrice array isn't going to change, the fix is straightforward:

```<code>const PriceList = props.buyPrice.map((price,index)=>
            {
            return(
                <div key={index}>
                    {price.name}: {price.cost}
                </div>
            )
        })
</code>```

Body:
within my main App render function... I have this list generated.

    const buildings = this.state.buildings.map(buildingData=>
      {
       console.log("unique id is:", buildingData.id)
      return(
        <Building
          key={buildingData.id}
          name ={buildingData.name}
          handleBuildingBuy={this.handleBuildingBuy}
          buyPrice={buildingData.buyPrice}
          count = {buildingData.count}
          subjectsOfIncrease = {buildingData.subjectsOfIncrease}
          isBuyable = {buildingData.isBuyable}
          isUnlocked = {buildingData.isUnlocked}

        />)
    });

but I still get the console output error, even though each key is both defined and unique....

App.js:224 unique id is: 0
App.js:224 unique id is: 1
App.js:224 unique id is: 2
App.js:224 unique id is: 3
App.js:224 unique id is: 4
App.js:224 unique id is: 5
App.js:224 unique id is: 6
App.js:224 unique id is: 7
index.js:1 Warning: Each child in a list should have a unique "key" prop.

Check the render method of `Building`. See react-warning-keys for more information.
    in div (at Building.js:11)
    in Building (at App.js:226)
    in div (at App.js:275)
    in div (at App.js:274)
    in App (at src/index.js:8)

weirder still I have a similar loop for other things, where key is not acting weird.

    const resources = this.state.resources.map(resourceData=>
      {
       console.log("unique resourceName is:", resourceData.name)

        return(

        <Resource
          name ={resourceData.name}
          max = {resourceData.max}
          isUnlocked = {resourceData.isUnlocked}
          changePerTick = {resourceData.changePerTick}
          amount={resourceData.amount}
          key={resourceData.name} //change out to a number - names are in fact unique.

        />)
    });

and that output is:

unique resourceName is: grey
App.js:240 unique resourceName is: red
App.js:240 unique resourceName is: green
App.js:240 unique resourceName is: blue
App.js:240 unique resourceName is: purple
App.js:240 unique resourceName is: teal
App.js:240 unique resourceName is: orange

so I don't understand why the above isn't working while in the same page the below is.

can anyone shed any light as to what may be happening?

edit: in case it is relevant, the building component

function Building(props)
    {
    if(props.isUnlocked)
        {
        const buyClass = props.isBuyable ? "afford": "cantAfford";
        const PriceList = props.buyPrice.map(price=>
            {
            return(

                    {price.name}: {price.cost}

            )
        })

        return(

 BUY FOR:

{PriceList}

                {props.isBuyable ?
                    <button name={props.name} onClick={props.handleBuildingBuy} className="buildingBuyBTN">{props.name}</button>
                    :
                    <button name={props.name} className="buildingNoBuyBTN">{props.name}</button>
                }

 COUNT:{props.count}

        )
    }
    else{return null}
}

Body:
As indicated by the error message, the problem is within your <Building> component:

Check the render method of Building.

It even tells you where:

in div (at Building.js:11)

Valiant debugging efforts though!

eta: If your buyPrice array isn't going to change, the fix is straightforward:

const PriceList = props.buyPrice.map((price,index)=>
            {
            return(
                <div key={index}>
                    {price.name}: {price.cost}
                </div>
            )
        })


问:
Python Script- failing to bypass logon page using beautifulSoup
I had a script that would bypass a logon page that looks like this

```<code>URL="http://mywebsite.com/logon.aspx"
headers = {"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36"}

username="username"
password="password"
s = Session()
s.verify = False

s.headers.update(headers)
r = s.get(URL)

soup=BeautifulSoup(r.content,"html.parser")

VIEWSTATE = soup.find(id="__VIEWSTATE")['value']
VIEWSTATEGENERATOR = soup.find(id="__VIEWSTATEGENERATOR")['value']
EVENTVALIDATION = soup.find(id="__EVENTVALIDATION")['value']

login_data={"__VIEWSTATE":VIEWSTATE,
"__VIEWSTATEGENERATOR":VIEWSTATEGENERATOR,
"__EVENTVALIDATION":EVENTVALIDATION,
"txtUsername":username,
"txtPassword":password,
"btnLogin":"Login"
}

#r = s.post(URL, data=login_data, verify=False)
r = s.post("http://mywebsite.com/logon.aspx", data=login_data)

r = s.get("http://mywebsite.com/SummaryReport/Index")
</code>```

that script was working fine before but then it started running into SSL errors so I changed it so that verify=false for the session

Now I don't get SSL errors but now it won't post the data to logon page, I'm not sure if it is related or not but any help is much appreciated

答:
If this is the SSL error you are seeing its a warning and can be ignored.

```<code>/usr/local/lib/python3.5/dist-packages/urllib3/connectionpool.py:1004: InsecureRequestWarning: Unverified HTTPS request is being made to host 'ownwebsite.com'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
 InsecureRequestWarning,
</code>```

What's failing is the following lines.

```<code>VIEWSTATE = soup.find(id="__VIEWSTATE")['value']
</code>```

The content received from the URL doesn't have the expected id __VIEWSTATE and is returning None  and trying to access based of key 'value' is causing the error.

```<code>TypeError: 'NoneType' object is not subscriptable
</code>```

Body:
I had a script that would bypass a logon page that looks like this

URL="http://mywebsite.com/logon.aspx"
headers = {"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36"}

username="username"
password="password"
s = Session()
s.verify = False

s.headers.update(headers)
r = s.get(URL)

soup=BeautifulSoup(r.content,"html.parser")

VIEWSTATE = soup.find(id="__VIEWSTATE")['value']
VIEWSTATEGENERATOR = soup.find(id="__VIEWSTATEGENERATOR")['value']
EVENTVALIDATION = soup.find(id="__EVENTVALIDATION")['value']

login_data={"__VIEWSTATE":VIEWSTATE,
"__VIEWSTATEGENERATOR":VIEWSTATEGENERATOR,
"__EVENTVALIDATION":EVENTVALIDATION,
"txtUsername":username,
"txtPassword":password,
"btnLogin":"Login"
}

#r = s.post(URL, data=login_data, verify=False)
r = s.post("http://mywebsite.com/logon.aspx", data=login_data)

r = s.get("http://mywebsite.com/SummaryReport/Index")

that script was working fine before but then it started running into SSL errors so I changed it so that verify=false for the session

Now I don't get SSL errors but now it won't post the data to logon page, I'm not sure if it is related or not but any help is much appreciated

Body:
If this is the SSL error you are seeing its a warning and can be ignored.

/usr/local/lib/python3.5/dist-packages/urllib3/connectionpool.py:1004: InsecureRequestWarning: Unverified HTTPS request is being made to host 'ownwebsite.com'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
 InsecureRequestWarning,

What's failing is the following lines.

VIEWSTATE = soup.find(id="__VIEWSTATE")['value']

The content received from the URL doesn't have the expected id __VIEWSTATE and is returning None  and trying to access based of key 'value' is causing the error.

TypeError: 'NoneType' object is not subscriptable


问:
How to send an image as a node HTTPS response with raw data
I'm writing a path in my node HTTPS server that returns an image. The problem is I'm getting this image from another external API call (the image data exists in res.body). This image grab is basically a proxy to another API that returns an image.

I've printed out the response to the external API and I see the image data. It also opens up the image in postman, but when I make the call with my Node server acting as a proxy, I either get failure responses or the picture does not show up. The most common error in my attempts is a 'parse error' in postman trying to display the image.

The logical flow is that I make a call to the API with the image. If the response is a 200 I grab that response information and set it as the response from my node server. The code is below:

```<code>function axisGetImage(command, webResponse){

  var commandURL = config.CameraIP;
  commandURL += '/GrabImage';

 //console.log(commandURL);
  const options = {
    'auth': {
      'user': username,
      'pass': password,
      'sendImmediately': false
    }
  }
  console.log(commandURL);

  request.get(commandURL, options, function(err, res, body){
    if(res.statusCode == 200){
      console.log(res.headers);
      //webResponse.setHeader('content-type', res.headers['content-type']);
      webResponse.setHeader('content-length', res.headers['content-length']);
      webResponse.setHeader('cache-control', res.headers['cache-control']);
      webResponse.setHeader('pragma', res.headers['pragma']);
      webResponse.setHeader('connection', res.headers['connection']);
      webResponse.writeHead(200,{"Content-Type":res.headers['content-type']});
      var base64data = Buffer.from(res.body).toString('base64');
      //body.write(res.body);
      console.log(webResponse.headers);
      //webResponse.write(base64data);
      webResponse.end(base64data);
    }else{
      webResponse.end('Image pull failed');
    }
    console.log(res.statusCode);
  });

}
</code>```

答:
Solved: When you set your options for the initial request to the external server, specify that there is no encoding in the request:

```<code>  const options = {
    'auth': {
      'user': username,
      'pass': password,
      'sendImmediately': false
    },
    encoding: null
  }
</code>```

Then you can simply write the body the request returns (the image data) directly to the response of your node server, thus proxying a request for an image.

```<code>request.get(commandURL, options, function(err, res, body){
    if(res.statusCode == 200){
      webResponse.setHeader('content-length', res.headers['content-length']);
      webResponse.setHeader('cache-control', res.headers['cache-control']);
      webResponse.setHeader('pragma', res.headers['pragma']);
      webResponse.setHeader('connection', res.headers['connection']);
      webResponse.writeHead(200,{"Content-Type":res.headers['content-type']});
      webResponse.end(body, 'binary');
    }else{
      webResponse.end('Image pull failed');
    }
    //console.log(res.statusCode);
  });
</code>```

Body:
I'm writing a path in my node HTTPS server that returns an image. The problem is I'm getting this image from another external API call (the image data exists in res.body). This image grab is basically a proxy to another API that returns an image.

I've printed out the response to the external API and I see the image data. It also opens up the image in postman, but when I make the call with my Node server acting as a proxy, I either get failure responses or the picture does not show up. The most common error in my attempts is a 'parse error' in postman trying to display the image.

The logical flow is that I make a call to the API with the image. If the response is a 200 I grab that response information and set it as the response from my node server. The code is below:

function axisGetImage(command, webResponse){

  var commandURL = config.CameraIP;
  commandURL += '/GrabImage';

 //console.log(commandURL);
  const options = {
    'auth': {
      'user': username,
      'pass': password,
      'sendImmediately': false
    }
  }
  console.log(commandURL);

  request.get(commandURL, options, function(err, res, body){
    if(res.statusCode == 200){
      console.log(res.headers);
      //webResponse.setHeader('content-type', res.headers['content-type']);
      webResponse.setHeader('content-length', res.headers['content-length']);
      webResponse.setHeader('cache-control', res.headers['cache-control']);
      webResponse.setHeader('pragma', res.headers['pragma']);
      webResponse.setHeader('connection', res.headers['connection']);
      webResponse.writeHead(200,{"Content-Type":res.headers['content-type']});
      var base64data = Buffer.from(res.body).toString('base64');
      //body.write(res.body);
      console.log(webResponse.headers);
      //webResponse.write(base64data);
      webResponse.end(base64data);
    }else{
      webResponse.end('Image pull failed');
    }
    console.log(res.statusCode);
  });

}

Body:
Solved: When you set your options for the initial request to the external server, specify that there is no encoding in the request:

  const options = {
    'auth': {
      'user': username,
      'pass': password,
      'sendImmediately': false
    },
    encoding: null
  }

Then you can simply write the body the request returns (the image data) directly to the response of your node server, thus proxying a request for an image.

request.get(commandURL, options, function(err, res, body){
    if(res.statusCode == 200){
      webResponse.setHeader('content-length', res.headers['content-length']);
      webResponse.setHeader('cache-control', res.headers['cache-control']);
      webResponse.setHeader('pragma', res.headers['pragma']);
      webResponse.setHeader('connection', res.headers['connection']);
      webResponse.writeHead(200,{"Content-Type":res.headers['content-type']});
      webResponse.end(body, 'binary');
    }else{
      webResponse.end('Image pull failed');
    }
    //console.log(res.statusCode);
  });


问:
Hiding the Material card on user selection not working
I am creating a launchpad kind of application where the material card will be loaded on user selection.
In order to handle this dynamically, I am trying to hide the element from TS class but change is not reflecting on the browser. redering of the Cards is happening based on rules to need to make it dynamic.  In order to make it work I am trying with a simpler scenario of one card:
Card code is like below:

```<code>    <mat-card class="launchpad-tiles"
  [class.mat-elevation-z8]="true"
  (click)="onCardClick($event)"
  matRipple
  [matRippleCentered]="true"
  [fxHide]="preg" #tiles>
      <mat-card-header>
        <div mat-card-avatar class="patient-image"></div>
        <mat-card-title>Patient Registration</mat-card-title>
        <mat-card-subtitle>Create new patient</mat-card-subtitle>
      </mat-card-header>
      <mat-card-content>
    </mat-card-content>
  </mat-card>
  <mat-card class="launchpad-tiles"
</code>```

I have used viewchild directive to get the reference and then setting the attribute in hook AfterViewInit. Change of attribute is not reflecting on the browser. Not sure if I am using the correct hook method.

```<code>@ViewChild(MatCard, { read: ElementRef, static: false }) lpadTiles: ElementRef;

ngAfterViewInit() {
this.lpadTiles.nativeElement.setAttribute('hidden', 'true');
}
</code>```

I have also tried to set Flex-Layout attribute FX-HIDE to True but that also didn't work.

I am working on angular for just one month so I might be missing something basic. Please let me know if there is a better way to handle this requirement.

答:
If you want to remove somthing from dom, you can use *ngIf structrual directive in angular Like.

```<code><ng-container *ngIf="condition">data</ng-container>
</code>```

when your condition will be true data will be visible and when it will be false it will not be shown. Other thing you can use like this

```<code><div [hidden]="true/false"> data</div>
</code>```

it will work same but will not remove element from dom.

Body:
I am creating a launchpad kind of application where the material card will be loaded on user selection.
In order to handle this dynamically, I am trying to hide the element from TS class but change is not reflecting on the browser. redering of the Cards is happening based on rules to need to make it dynamic.  In order to make it work I am trying with a simpler scenario of one card:
Card code is like below:

    <mat-card class="launchpad-tiles"
  [class.mat-elevation-z8]="true"
  (click)="onCardClick($event)"
  matRipple
  [matRippleCentered]="true"
  [fxHide]="preg" #tiles>
      <mat-card-header>

        <mat-card-title>Patient Registration</mat-card-title>
        <mat-card-subtitle>Create new patient</mat-card-subtitle>
      </mat-card-header>
      <mat-card-content>
    </mat-card-content>
  </mat-card>
  <mat-card class="launchpad-tiles"

I have used viewchild directive to get the reference and then setting the attribute in hook AfterViewInit. Change of attribute is not reflecting on the browser. Not sure if I am using the correct hook method.

@ViewChild(MatCard, { read: ElementRef, static: false }) lpadTiles: ElementRef;

ngAfterViewInit() {
this.lpadTiles.nativeElement.setAttribute('hidden', 'true');
}

I have also tried to set Flex-Layout attribute FX-HIDE to True but that also didn't work.

I am working on angular for just one month so I might be missing something basic. Please let me know if there is a better way to handle this requirement.

Body:
If you want to remove somthing from dom, you can use *ngIf structrual directive in angular Like.

<ng-container *ngIf="condition">data</ng-container>

when your condition will be true data will be visible and when it will be false it will not be shown. Other thing you can use like this

<div [hidden]="true/false"> data</div>

it will work same but will not remove element from dom.


问:
Calculate the total value of the Widgets sold each month for a particular year
If I have a Django Model that defines a Widget like this:

```<code>class Widget(models.Model):
    type = models.CharField()
    sold = models.DateTimeField()
    price = models.DecimalField()
    .
    .
</code>```

How would I go about getting the total value of the Widgets sold per month for a particular year?

I'd like to end up with a list of 12 monthly totals, for example:

```<code>[1225, 197, 131, 125, ...
</code>```

This would indicate the total value of the Widgets sold in January was $1225, February $197 etc.

I expect this can be done with a Django Query, but not quite sure how.

UPDATE

I'd prefer not to use anything database specific to make changing databases easier. I don't mind if it's not all done in a single query. Doing a query, then some manipulation using Python after is fine.

UPDATE

I think I can slightly change some code from an answer to another question I raised to get this:

```<code>queryset = Widget.objects.filter(sold__year=year)
totals = [0] * 12
for widget in queryset:
    totals[widget.sold.month - 1] += widget.price
return totals
</code>```

Please let me know if I've missed something or if there's a better way of doing it.

答:
Similar approach, but probably not very efficient either</p>

```<code>month_totals = []
for month in range(1, 13):
    month_total = Widget.objects. \
               filter(sold__gte=datetime.date(the_year, month, 1),
                      sold__lte=datetime.date(the_year, month, 31)). \
               aggregate(month_total=Sum('price')).month_total
    month_totals.append(month_total)
</code>```

Body:
If I have a Django Model that defines a Widget like this:

class Widget(models.Model):
    type = models.CharField()
    sold = models.DateTimeField()
    price = models.DecimalField()
    .
    .

How would I go about getting the total value of the Widgets sold per month for a particular year?

I'd like to end up with a list of 12 monthly totals, for example:

[1225, 197, 131, 125, ...

This would indicate the total value of the Widgets sold in January was $1225, February $197 etc.

I expect this can be done with a Django Query, but not quite sure how.

UPDATE

I'd prefer not to use anything database specific to make changing databases easier. I don't mind if it's not all done in a single query. Doing a query, then some manipulation using Python after is fine.

UPDATE

I think I can slightly change some code from an answer to another question I raised to get this:

queryset = Widget.objects.filter(sold__year=year)
totals = [0] * 12
for widget in queryset:
    totals[widget.sold.month - 1] += widget.price
return totals

Please let me know if I've missed something or if there's a better way of doing it.

Body:
Similar approach, but probably not very efficient either

month_totals = []
for month in range(1, 13):
    month_total = Widget.objects. \
               filter(sold__gte=datetime.date(the_year, month, 1),
                      sold__lte=datetime.date(the_year, month, 31)). \
               aggregate(month_total=Sum('price')).month_total
    month_totals.append(month_total)


问:
How do I align text for a single subitem in a ListView using C#?
I wasn't able to find an answer anywhere about this seemingly simple topic: is it possible to align text of a single subitem in a WinForms ListView control?

If so, how?

I would like to have text in the same column aligned differently.

答:
Building on the answer by @Fueled, here's what I did to use the column header alignment:</p>

```<code>    protected override void OnDrawSubItem( DrawListViewSubItemEventArgs e )
        {
        // Match the subitem alignment to the column header alignment
        TextFormatFlags flags = TextFormatFlags.Left;
        switch ( this.Columns[ e.ColumnIndex ].TextAlign )
            {
            case HorizontalAlignment.Right:
                flags = TextFormatFlags.Right;
                break;
            case HorizontalAlignment.Center:
                flags = TextFormatFlags.HorizontalCenter;
                break;
            }
        e.DrawText( flags );
        }
</code>```

OwnerDisplayName: Fueled

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Rich B

Body:
Building on the answer by @Fueled, here's what I did to use the column header alignment:

    protected override void OnDrawSubItem( DrawListViewSubItemEventArgs e )
        {
        // Match the subitem alignment to the column header alignment
        TextFormatFlags flags = TextFormatFlags.Left;
        switch ( this.Columns[ e.ColumnIndex ].TextAlign )
            {
            case HorizontalAlignment.Right:
                flags = TextFormatFlags.Right;
                break;
            case HorizontalAlignment.Center:
                flags = TextFormatFlags.HorizontalCenter;
                break;
            }
        e.DrawText( flags );
        }


问:
Error when running API call in R using comprador() package
I get this error when I try to run an API call using ct_search() from comtradr() package in R .

```<code>Error in curl::curl_fetch_memory(url, handle = handle) :
      SSL certificate problem: certificate has expired
</code>```

Any ideas?

答:
You haven't given enough details, but it could be related to this:
https://support.sectigo.com/articles/Knowledge/Sectigo-AddTrust-External-CA-Root-Expiring-May-30-2020

If you are on a Linux machine that you are running curl from, you can do the following:

```<code>$ sudo vi /etc/ca-certificates.conf
add an exclamation point in front of the line that says "mozilla/AddTrust_External_Root.crt" and save the file
$ sudo apt update
$ sudo apt install ca-certificates
$ sudo update-ca-certificates -f -v
</code>```

Body:
I get this error when I try to run an API call using ct_search() from comtradr() package in R .

Error in curl::curl_fetch_memory(url, handle = handle) :
      SSL certificate problem: certificate has expired

Any ideas?

Body:
You haven't given enough details, but it could be related to this:
https://support.sectigo.com/articles/Knowledge/Sectigo-AddTrust-External-CA-Root-Expiring-May-30-2020

If you are on a Linux machine that you are running curl from, you can do the following:

$ sudo vi /etc/ca-certificates.conf
add an exclamation point in front of the line that says "mozilla/AddTrust_External_Root.crt" and save the file
$ sudo apt update
$ sudo apt install ca-certificates
$ sudo update-ca-certificates -f -v


问:
How to use the npm replace command in windows instead of the windows replace.exe command
I can't use directly the npm's replace package in windows because replace command is using replace.exe of windows.

答: Use $APPDATA/npm/replace command instead of replacecommand. It will call the 'replace' of npm and not the one of windows


问:
Attempt to invoke virtual method 'android.view.View android.widget.ImageView.findViewById(int)' on a null object reference
I am trying to retrieve data from firebase but my app is keep crashing. i have tried many solution but nothing is working.
In my app i am trying to retrieve name,image,descriptions,price form my Firebase database.
I have written this flowing code to display data in Card view.

my code:-
Main Activity

```<code>public class MainActivity extends AppCompatActivity {
private DatabaseReference ProductsRef;
private RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ProductsRef = FirebaseDatabase.getInstance().getReference().child("Products");
    recyclerView = findViewById(R.id.recycler_menu);
    recyclerView.setHasFixedSize(true);
    layoutManager= new LinearLayoutManager(this);
    recyclerView.setLayoutManager(layoutManager);
    FirebaseRecyclerOptions<Products> options =
            new FirebaseRecyclerOptions.Builder<Products>()
                    .setQuery(ProductsRef, Products.class)
                    .build();
    FirebaseRecyclerAdapter<Products, ProductViewHolder> adapter =
            new FirebaseRecyclerAdapter<Products, ProductViewHolder>(options) {
                @Override
                protected void onBindViewHolder(@NonNull ProductViewHolder holder, int position, @NonNull Products model) {
                    holder.textProductName.setText(model.getName());
                    holder.textProductDescription.setText(model.getDescription());
                    holder.textProductPrice.setText("Price = ₹"+model.getPrice());
                    Picasso.get().load(model.getImage()).into(holder.imageView);
                }

                @NonNull
                @Override
                public ProductViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.product_items_layout, parent,false);
                    ProductViewHolder holder = new ProductViewHolder(view);
                    return holder;
                }
            };
    recyclerView.setAdapter(adapter);
    adapter.startListening();
}
</code>```

}

Products Activity

```<code>public class Products {
private String  description, image,name,price ;
public Products() {
}

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}

public String getImage() {
    return image;
}

public void setImage(String image) {
    this.image = image;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getPrice() {
    return price;
}

public void setPrice(String price) {
    this.price = price;
}
</code>```

}

ProductViewHolder Activity

```<code>              [enter image description here][1]public class ProductViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView textProductName, textProductDescription, textProductPrice;
public ImageView imageView;
public ProductViewHolder(@NonNull View itemView) {
    super(itemView);
    imageView= imageView.findViewById(R.id.product_image);
    textProductName = textProductName.findViewById(R.id.product_name);
    textProductDescription = textProductDescription.findViewById(R.id.product_description);
    textProductPrice = textProductPrice.findViewById(R.id.product_price);
}

@Override
public void onClick(View v) {

}
</code>```

}

答:
Attempt to invoke virtual method 'android.view.View
  android.widget.ImageView.findViewById(int)' on a null object reference

findViewById() is nullable, so it might return a null value.. make sure that the ImageView resource id product_name exists in your R.layout.product_items_layout layout and not in any other layouts in your project.

Body:
I am trying to retrieve data from firebase but my app is keep crashing. i have tried many solution but nothing is working.
In my app i am trying to retrieve name,image,descriptions,price form my Firebase database.
I have written this flowing code to display data in Card view.

my code:-
Main Activity

public class MainActivity extends AppCompatActivity {
private DatabaseReference ProductsRef;
private RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ProductsRef = FirebaseDatabase.getInstance().getReference().child("Products");
    recyclerView = findViewById(R.id.recycler_menu);
    recyclerView.setHasFixedSize(true);
    layoutManager= new LinearLayoutManager(this);
    recyclerView.setLayoutManager(layoutManager);
    FirebaseRecyclerOptions<Products> options =
            new FirebaseRecyclerOptions.Builder<Products>()
                    .setQuery(ProductsRef, Products.class)
                    .build();
    FirebaseRecyclerAdapter<Products, ProductViewHolder> adapter =
            new FirebaseRecyclerAdapter<Products, ProductViewHolder>(options) {
                @Override
                protected void onBindViewHolder(@NonNull ProductViewHolder holder, int position, @NonNull Products model) {
                    holder.textProductName.setText(model.getName());
                    holder.textProductDescription.setText(model.getDescription());
                    holder.textProductPrice.setText("Price = ₹"+model.getPrice());
                    Picasso.get().load(model.getImage()).into(holder.imageView);
                }

                @NonNull
                @Override
                public ProductViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.product_items_layout, parent,false);
                    ProductViewHolder holder = new ProductViewHolder(view);
                    return holder;
                }
            };
    recyclerView.setAdapter(adapter);
    adapter.startListening();
}

}

Products Activity

public class Products {
private String  description, image,name,price ;
public Products() {
}

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}

public String getImage() {
    return image;
}

public void setImage(String image) {
    this.image = image;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getPrice() {
    return price;
}

public void setPrice(String price) {
    this.price = price;
}

}

ProductViewHolder Activity

              [enter image description here][1]public class ProductViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView textProductName, textProductDescription, textProductPrice;
public ImageView imageView;
public ProductViewHolder(@NonNull View itemView) {
    super(itemView);
    imageView= imageView.findViewById(R.id.product_image);
    textProductName = textProductName.findViewById(R.id.product_name);
    textProductDescription = textProductDescription.findViewById(R.id.product_description);
    textProductPrice = textProductPrice.findViewById(R.id.product_price);
}

@Override
public void onClick(View v) {

}

}


问:
Static variable across multiple, different subclasses - corrected
I was wondering what happened if I define a base Activity object with all my activities as subclasses of that. Then I declare a static variable in the base class, will all the subclasses use the SAME static or will there be one per subclass.

For example. My base class:

```<code>public class MyBaseActivity extends Activity{

   static int myStatic;

   ...
   ....

}
</code>```

Then:

```<code>public class MyActivity1 extends MyBaseActivity {

   private void someMethod1(){
         myStatic = 1;
    }

   ...
   ....

}
</code>```

and

```<code>public class MyActivity1 extends MyBaseActivity {

   private void someMethod2(){
          if (myStatic == 1)
            doSomething();
    }

   ...
   ....

}
</code>```

If I now start MyActivity1 and it sets a value in "myStatic". It then exits and then I start MyActivity2 - should I still have the value set by the first activity?
In the example above, would the "if" statement be true or false?

I know that if I instantiate Activity1 more than once then obviously I would get the same static variable. However, here I am instantiating a different subclass each time.

I am getting the impression that that is what is happening to me but want to be sure.

答:
If I now start MyActivity1 and it sets
  a value in "myStatic". It then exits
  and then I start MyActivity2 - should
  I still have the value set by the
  first activity? In the example above,
  would the "if" statement be true or
  false?

All subclass will share the same static class instance. so the if statement is true

Body:
I was wondering what happened if I define a base Activity object with all my activities as subclasses of that. Then I declare a static variable in the base class, will all the subclasses use the SAME static or will there be one per subclass.

For example. My base class:

public class MyBaseActivity extends Activity{

   static int myStatic;

   ...
   ....

}

Then:

public class MyActivity1 extends MyBaseActivity {

   private void someMethod1(){
         myStatic = 1;
    }

   ...
   ....

}

and

public class MyActivity1 extends MyBaseActivity {

   private void someMethod2(){
          if (myStatic == 1)
            doSomething();
    }

   ...
   ....

}

If I now start MyActivity1 and it sets a value in "myStatic". It then exits and then I start MyActivity2 - should I still have the value set by the first activity?
In the example above, would the "if" statement be true or false?

I know that if I instantiate Activity1 more than once then obviously I would get the same static variable. However, here I am instantiating a different subclass each time.

I am getting the impression that that is what is happening to me but want to be sure.


问:
What is segmentation fault. How to deal with it
Problem:

A student signed up for workshops and wants to attend the maximum

number of workshops where no two workshops overlap. You must do the

following: Implement structures:

struct Workshop having the following members: The workshop's start time. The workshop's duration. The workshop's end time.

struct Available_Workshops having the following members: An integer, (the number of workshops the student signed up for). An

array of type Workshop array having size .  Implement functions:

Available_Workshops* initialize (int start_time[], int duration[], int n) Creates an Available_Workshops object and
initializes its    elements using the elements in the and parameters
(both are of size    ). Here, and are the respective start time and
duration for the    workshop. This function must return a pointer to
an    Available_Workshops object.

int CalculateMaxWorkshops(Available_Workshops* ptr) Returns the maximum number of workshops the student can attend—without overlap.

The next workshop cannot be attended until the previous workshop

ends. Note: An array of unkown size ( ) should be declared as

follows: DataType* arrayName = new DataType[n];

Your initialize function must return a pointer to    an
Available_Workshops object. Your CalculateMaxWorkshops function

must return maximum number of non-overlapping workshops the student

can attend.

Sample Input

6

1 3 0 5 5 8

1 1 6 2 4 1

Sample Output

4

Explanation  The first line denotes , the number of workshops. The next line contains    space-separated integers where the integer
   is the workshop's start    time. The next line contains
   space-separated integers where the    integer is the workshop's
   duration. The student can attend the    workshops and without
   overlap, so CalculateMaxWorkshops returns to    main (which then
   prints to stdout).

MY CODE:

```<code>#include <iostream>

using namespace std;

class Workshop{
    public:
    int start_time{},duration{},end_time{};};

class Available_Workshops
{
    public:
     int n{};
    struct Workshop*arr=new struct Workshop[n];
    ~Available_Workshops()
    {
        delete [] arr;

    }
    void arr_sort();
    void arr_delete(int i);

};
////////////////////////////////////////////////////////////////////////////////////////////
Available_Workshops * initialize(int start_time[],int duration[],int n)
{
    Available_Workshops * x=new Available_Workshops{};
    x->n=n;
    for(int i=0;i<n;i++)
    {
     x->arr[i].start_time=start_time[i];
     x->arr[i].duration=duration[i];
     x->arr[i].end_time=start_time[i]+duration[i];
    }

    return x;

}
///////////////////////////////////////////////////////////////////////////////////////////
void Available_Workshops:: arr_delete(int i)
{

    n-=1;

    for(int j=i;j<n;j++)
    {
     arr[j]=arr[j+1];
    }

}
///////////////////////////////////////////////////////////////////////////////////////////
void Available_Workshops:: arr_sort()
{
for(int i=0;i<n;i++)
{
    for(int j=i+1;j<n;j++)
    {
        if(arr[i].start_time>arr[j].start_time)
            {
                struct Workshop temp=arr[i];
                arr[i]=arr[j];
                arr[j]=temp;
            }
    }
}

}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int CalculateMaxWorkshops(Available_Workshops * x)
{
    x->arr_sort();
    for(int i=0;i<x->n-1;i++)
    {
       for(int j=i+1;j<x->n;j++)
       {
           if(x->arr[i].end_time>x->arr[j].start_time)
           {
               if(x->arr[i].duration>=x->arr[j].duration)
                x->arr_delete(i);
               else x->arr_delete(j);
               j--;
           }
       }
    }
    int y=x->n;
    delete x;
   return y;

}

int main(int argc, char *argv[]) {
    int n; // number of workshops
    cin >> n;
    // create arrays of unknown size n
    int* start_time = new int[n];
    int* duration = new int[n];

    for(int i=0; i < n; i++){
        cin >> start_time[i];
    }
    for(int i = 0; i < n; i++){
        cin >> duration[i];
    }

    Available_Workshops * ptr;
    ptr = initialize(start_time,duration, n);

    cout << CalculateMaxWorkshops(ptr) << endl;
    return 0;
}
</code>```

My code is not running. It has segmentation fault. Please help me find this error

答:
You bug can be seen from the class declaration:

```<code>class Available_Workshops
{
public:
    int n{};
    struct Workshop* arr = new struct Workshop[n];

    ~Available_Workshops()
    {
        delete[] arr;

    }
    void arr_sort();
    void arr_delete(int i);

};
</code>```

Member n gets explicitly initialized to 0.  Yet, your initialize function will happily fill in more elements into arr (an array of zero elements) and cause all kinds of undefined behavior.

You really, really want a proper constructor for your class instead of trying to inline initialize the members.

```<code>Available_Workshops(int size) :
n(size)
{
    arr = new Workshop[n];
}
</code>```

Another issue, although not related to your crash is inside your arr_delete function.

```<code>for (int j = i; j < n; j++)
{
    arr[j] = arr[j + 1];
}
</code>```

When j == n-1 on the last iteration of the loop, it will execute arr[n-1] = arr[n].  Accesing arr[n] is undefined behavior since the only valid indices in the array are from [0..n-1]

Body:
Problem:

A student signed up for workshops and wants to attend the maximum

number of workshops where no two workshops overlap. You must do the

following: Implement structures:

struct Workshop having the following members: The workshop's start time. The workshop's duration. The workshop's end time.

struct Available_Workshops having the following members: An integer, (the number of workshops the student signed up for). An

array of type Workshop array having size .  Implement functions:

Available_Workshops* initialize (int start_time[], int duration[], int n) Creates an Available_Workshops object and
initializes its    elements using the elements in the and parameters
(both are of size    ). Here, and are the respective start time and
duration for the    workshop. This function must return a pointer to
an    Available_Workshops object.

int CalculateMaxWorkshops(Available_Workshops* ptr) Returns the maximum number of workshops the student can attend—without overlap.

The next workshop cannot be attended until the previous workshop

ends. Note: An array of unkown size ( ) should be declared as

follows: DataType* arrayName = new DataType[n];

Your initialize function must return a pointer to    an
Available_Workshops object. Your CalculateMaxWorkshops function

must return maximum number of non-overlapping workshops the student

can attend.

Sample Input

6

1 3 0 5 5 8

1 1 6 2 4 1

Sample Output

4

Explanation  The first line denotes , the number of workshops. The next line contains    space-separated integers where the integer
   is the workshop's start    time. The next line contains
   space-separated integers where the    integer is the workshop's
   duration. The student can attend the    workshops and without
   overlap, so CalculateMaxWorkshops returns to    main (which then
   prints to stdout).

MY CODE:

#include <iostream>

using namespace std;

class Workshop{
    public:
    int start_time{},duration{},end_time{};};

class Available_Workshops
{
    public:
     int n{};
    struct Workshop*arr=new struct Workshop[n];
    ~Available_Workshops()
    {
        delete [] arr;

    }
    void arr_sort();
    void arr_delete(int i);

};
////////////////////////////////////////////////////////////////////////////////////////////
Available_Workshops * initialize(int start_time[],int duration[],int n)
{
    Available_Workshops * x=new Available_Workshops{};
    x->n=n;
    for(int i=0;i<n;i++)
    {
     x->arr[i].start_time=start_time[i];
     x->arr[i].duration=duration[i];
     x->arr[i].end_time=start_time[i]+duration[i];
    }

    return x;

}
///////////////////////////////////////////////////////////////////////////////////////////
void Available_Workshops:: arr_delete(int i)
{

    n-=1;

    for(int j=i;j<n;j++)
    {
     arr[j]=arr[j+1];
    }

}
///////////////////////////////////////////////////////////////////////////////////////////
void Available_Workshops:: arr_sort()
{
for(int i=0;i<n;i++)
{
    for(int j=i+1;j<n;j++)
    {
        if(arr[i].start_time>arr[j].start_time)
            {
                struct Workshop temp=arr[i];
                arr[i]=arr[j];
                arr[j]=temp;
            }
    }
}

}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int CalculateMaxWorkshops(Available_Workshops * x)
{
    x->arr_sort();
    for(int i=0;i<x->n-1;i++)
    {
       for(int j=i+1;j<x->n;j++)
       {
           if(x->arr[i].end_time>x->arr[j].start_time)
           {
               if(x->arr[i].duration>=x->arr[j].duration)
                x->arr_delete(i);
               else x->arr_delete(j);
               j--;
           }
       }
    }
    int y=x->n;
    delete x;
   return y;

}

int main(int argc, char *argv[]) {
    int n; // number of workshops
    cin >> n;
    // create arrays of unknown size n
    int* start_time = new int[n];
    int* duration = new int[n];

    for(int i=0; i < n; i++){
        cin >> start_time[i];
    }
    for(int i = 0; i < n; i++){
        cin >> duration[i];
    }

    Available_Workshops * ptr;
    ptr = initialize(start_time,duration, n);

    cout << CalculateMaxWorkshops(ptr) << endl;
    return 0;
}

My code is not running. It has segmentation fault. Please help me find this error

Body:
You bug can be seen from the class declaration:

class Available_Workshops
{
public:
    int n{};
    struct Workshop* arr = new struct Workshop[n];

    ~Available_Workshops()
    {
        delete[] arr;

    }
    void arr_sort();
    void arr_delete(int i);

};

Member n gets explicitly initialized to 0.  Yet, your initialize function will happily fill in more elements into arr (an array of zero elements) and cause all kinds of undefined behavior.

You really, really want a proper constructor for your class instead of trying to inline initialize the members.

Available_Workshops(int size) :
n(size)
{
    arr = new Workshop[n];
}

Another issue, although not related to your crash is inside your arr_delete function.

for (int j = i; j < n; j++)
{
    arr[j] = arr[j + 1];
}

When j == n-1 on the last iteration of the loop, it will execute arr[n-1] = arr[n].  Accesing arr[n] is undefined behavior since the only valid indices in the array are from [0..n-1]


问:
Is it possible to enable color support for a multiple inherited Docker container?
I have a container, which inherits from nvidia cuda 10.2 ubuntu 18.04:

```<code>FROM nvidia/cuda:10.2-base-ubuntu18.04

# Install some basic utilities
RUN apt-get update && apt-get install -y \
    curl \
    wget \
    ca-certificates \
    sudo \
    git \
    bzip2 \
    libx11-6 \
 && rm -rf /var/lib/apt/lists/*

# Create a working directory and set it as default
RUN mkdir /app
RUN chmod 777 /app
WORKDIR /app

# Create a non-root user and switch to it
RUN adduser --disabled-password --gecos '' --shell /bin/bash user
RUN echo "user ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/90-user
USER user

# All users can use /home/user as their home directory
ENV HOME=/home/user
RUN chmod 777 /home/user

 # Install Miniconda
RUN wget -O ~/miniconda.sh https://repo.continuum.io/miniconda/Miniconda3-py37_4.8.2-Linux-x86_64.sh \
 && chmod +x ~/miniconda.sh \
 && ~/miniconda.sh -b -p ~/miniconda \
 && rm ~/miniconda.sh
ENV PATH=/home/user/miniconda/bin:$PATH
ENV CONDA_AUTO_UPDATE_CONDA=false

# Update Conda
RUN conda update conda
</code>```

If I run this container with the environment variable env TERM=xterm-256color I get the expected colored output support.

Now I have another Docker container, which inherits from the container (tagged: mlflowcore/base:1.0.0) which I pasted above:

```<code>FROM mlflowcore/base:1.0.0

# Install the conda environment
COPY pytorch_environment.yml .
RUN conda env create -f pytorch_environment.yml && conda clean -a

# Activate the environment
RUN echo "source activate pytorch" > ~/.bashrc
ENV PATH /home/user/miniconda/envs/pytorch/bin:$PATH

# Dump the details of the installed packages to a file for posterity
RUN conda env export --name pytorch > pytorch.yml

# Currently required, since mlflow writes every file as root!
USER root
</code>```

However, when I run this container with the variable env TERM=xterm-256color or I set the ENV TERM xterm-256color variable from the Docker container I don't get color support.

How can I get color support for my container, which inherits from a Docker container, which is based on another container?

Thank you very much!

答:
The issue was that the line RUN echo "source activate pytorch" > ~/.bashrc was overwriting the default bashrc file.

Changing it to appending the command to the bashrc by adding a >: RUN echo "source activate pytorch" >> ~/.bashrc solved the problem.

Body:
I have a container, which inherits from nvidia cuda 10.2 ubuntu 18.04:

FROM nvidia/cuda:10.2-base-ubuntu18.04

# Install some basic utilities
RUN apt-get update && apt-get install -y \
    curl \
    wget \
    ca-certificates \
    sudo \
    git \
    bzip2 \
    libx11-6 \
 && rm -rf /var/lib/apt/lists/*

# Create a working directory and set it as default
RUN mkdir /app
RUN chmod 777 /app
WORKDIR /app

# Create a non-root user and switch to it
RUN adduser --disabled-password --gecos '' --shell /bin/bash user
RUN echo "user ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/90-user
USER user

# All users can use /home/user as their home directory
ENV HOME=/home/user
RUN chmod 777 /home/user

 # Install Miniconda
RUN wget -O ~/miniconda.sh https://repo.continuum.io/miniconda/Miniconda3-py37_4.8.2-Linux-x86_64.sh \
 && chmod +x ~/miniconda.sh \
 && ~/miniconda.sh -b -p ~/miniconda \
 && rm ~/miniconda.sh
ENV PATH=/home/user/miniconda/bin:$PATH
ENV CONDA_AUTO_UPDATE_CONDA=false

# Update Conda
RUN conda update conda

If I run this container with the environment variable env TERM=xterm-256color I get the expected colored output support.

Now I have another Docker container, which inherits from the container (tagged: mlflowcore/base:1.0.0) which I pasted above:

FROM mlflowcore/base:1.0.0

# Install the conda environment
COPY pytorch_environment.yml .
RUN conda env create -f pytorch_environment.yml && conda clean -a

# Activate the environment
RUN echo "source activate pytorch" > ~/.bashrc
ENV PATH /home/user/miniconda/envs/pytorch/bin:$PATH

# Dump the details of the installed packages to a file for posterity
RUN conda env export --name pytorch > pytorch.yml

# Currently required, since mlflow writes every file as root!
USER root

However, when I run this container with the variable env TERM=xterm-256color or I set the ENV TERM xterm-256color variable from the Docker container I don't get color support.

How can I get color support for my container, which inherits from a Docker container, which is based on another container?

Thank you very much!


问:
Why does adding a Swift protocol in some situations not require all the normally required methods?
For example, these are valid and will compile without (all) protocol stubs

```<code>public class ViewController: UIViewController, SFSpeechRecognizerDelegate {

}

class BLEController: CBCentralManager, CBCentralManagerDelegate {
    func centralManagerDidUpdateState(_ central: CBCentralManager) {

    }
}
</code>```

Edit:  Solved!  Creating a class without inheriting from UIViewController or CBCentralManager still does comply with the delegate protocols, but it does not comply with NSObjectProtocol.  It just seems to be that I'm attempting to use the frameworks in an unintended way.

答:
Why does my code compile without fulfilling all the protocol requirements?

What you are seeing here are optional protocol requirements. They are here because Swift code needs to interact with Objective-C, and Objective-C has them.

All methods except centralManagerDidUpdateState declared in CBCentralManagerDelegate are optional, from here:

The only required method is centralManagerDidUpdateState(_:); the central manager calls this when its state updates, thereby indicating the availability of the central manager.

And SFSpeechRecognizerDelegate, only contains one optional method, from here:

Use this protocol's optional method to track those changes and provide an appropriate response.

why does the code not compile if you remove the superclasses then?

This is because both of those protocols in your question also inherit from NSObjectProtocol, so they actually also have the additional requirements of NSObjectProtocol. UIViewController and CBCentralManager both inherits from NSObject, so they satisfy the NSObjectProtocol requirements, but your Swift class without a superclass doesn't.

Protocols with optional requirements don't have to inherit from NSObjectProtocol though. It's just that most of them are that way in the framework. You can for example do:

```<code>@objc protocol Foo {
    @objc optional func foo()
}

class FooClass : Foo {
    // compiles fine!
}
</code>```

Body:
For example, these are valid and will compile without (all) protocol stubs

public class ViewController: UIViewController, SFSpeechRecognizerDelegate {

}

class BLEController: CBCentralManager, CBCentralManagerDelegate {
    func centralManagerDidUpdateState(_ central: CBCentralManager) {

    }
}

Edit:  Solved!  Creating a class without inheriting from UIViewController or CBCentralManager still does comply with the delegate protocols, but it does not comply with NSObjectProtocol.  It just seems to be that I'm attempting to use the frameworks in an unintended way.

Body:
Why does my code compile without fulfilling all the protocol requirements?

What you are seeing here are optional protocol requirements. They are here because Swift code needs to interact with Objective-C, and Objective-C has them.

All methods except centralManagerDidUpdateState declared in CBCentralManagerDelegate are optional, from here:

The only required method is centralManagerDidUpdateState(_:); the central manager calls this when its state updates, thereby indicating the availability of the central manager.

And SFSpeechRecognizerDelegate, only contains one optional method, from here:

Use this protocol's optional method to track those changes and provide an appropriate response.

why does the code not compile if you remove the superclasses then?

This is because both of those protocols in your question also inherit from NSObjectProtocol, so they actually also have the additional requirements of NSObjectProtocol. UIViewController and CBCentralManager both inherits from NSObject, so they satisfy the NSObjectProtocol requirements, but your Swift class without a superclass doesn't.

Protocols with optional requirements don't have to inherit from NSObjectProtocol though. It's just that most of them are that way in the framework. You can for example do:

@objc protocol Foo {
    @objc optional func foo()
}

class FooClass : Foo {
    // compiles fine!
}


答:
Your error is indeed in building. You are not adding keys to the PriceList. This needs a key

```<code>      const PriceList = props.buyPrice.map(price=>
            {
            return(
                <div>
                    {price.name}: {price.cost}
                </div>
            )
        })
</code>```

The error it gave you was pointing you in the correct place

Title: unique keys are unique, are assigned to key prop, but still getting error... but only in one component

Body:
within my main App render function... I have this list generated.

    const buildings = this.state.buildings.map(buildingData=>
      {
       console.log("unique id is:", buildingData.id)
      return(
        <Building
          key={buildingData.id}
          name ={buildingData.name}
          handleBuildingBuy={this.handleBuildingBuy}
          buyPrice={buildingData.buyPrice}
          count = {buildingData.count}
          subjectsOfIncrease = {buildingData.subjectsOfIncrease}
          isBuyable = {buildingData.isBuyable}
          isUnlocked = {buildingData.isUnlocked}

        />)
    });

but I still get the console output error, even though each key is both defined and unique....

App.js:224 unique id is: 0
App.js:224 unique id is: 1
App.js:224 unique id is: 2
App.js:224 unique id is: 3
App.js:224 unique id is: 4
App.js:224 unique id is: 5
App.js:224 unique id is: 6
App.js:224 unique id is: 7
index.js:1 Warning: Each child in a list should have a unique "key" prop.

Check the render method of `Building`. See react-warning-keys for more information.
    in div (at Building.js:11)
    in Building (at App.js:226)
    in div (at App.js:275)
    in div (at App.js:274)
    in App (at src/index.js:8)

weirder still I have a similar loop for other things, where key is not acting weird.

    const resources = this.state.resources.map(resourceData=>
      {
       console.log("unique resourceName is:", resourceData.name)

        return(

        <Resource
          name ={resourceData.name}
          max = {resourceData.max}
          isUnlocked = {resourceData.isUnlocked}
          changePerTick = {resourceData.changePerTick}
          amount={resourceData.amount}
          key={resourceData.name} //change out to a number - names are in fact unique.

        />)
    });

and that output is:

unique resourceName is: grey
App.js:240 unique resourceName is: red
App.js:240 unique resourceName is: green
App.js:240 unique resourceName is: blue
App.js:240 unique resourceName is: purple
App.js:240 unique resourceName is: teal
App.js:240 unique resourceName is: orange

so I don't understand why the above isn't working while in the same page the below is.

can anyone shed any light as to what may be happening?

edit: in case it is relevant, the building component

function Building(props)
    {
    if(props.isUnlocked)
        {
        const buyClass = props.isBuyable ? "afford": "cantAfford";
        const PriceList = props.buyPrice.map(price=>
            {
            return(

                    {price.name}: {price.cost}

            )
        })

        return(

 BUY FOR:

{PriceList}

                {props.isBuyable ?
                    <button name={props.name} onClick={props.handleBuildingBuy} className="buildingBuyBTN">{props.name}</button>
                    :
                    <button name={props.name} className="buildingNoBuyBTN">{props.name}</button>
                }

 COUNT:{props.count}

        )
    }
    else{return null}
}

Body:
Your error is indeed in building. You are not adding keys to the PriceList. This needs a key

      const PriceList = props.buyPrice.map(price=>
            {
            return(
                <div>
                    {price.name}: {price.cost}
                </div>
            )
        })

The error it gave you was pointing you in the correct place


问:
Update SQL from React
I build a react app using nodejs and mysql. I want to update an entry from react but the following code doesn't working and I can't understan what is the problem. Any suggestions are much appreciated.

// from index.js

```<code>script.get('/updatepost/:id', (req, res) => {
    let sql = `UPDATE posts SET name = '${req.body.name}', school='${req.body.school}' WHERE id = ${req.params.id}`;
    let query = connection.query(sql, (err, result) => {
        if(err) throw err;
        console.log(result);
        res.send('Post updated...');
    })
});
</code>```

//from react component

```<code>axios(`http://localhost:4000/updatepost/${userId}`, {
method: 'PATCH',
data: qs.stringify(data);
})
</code>```

答:
Try removing the brackets (). The query should be as below

let sql = UPDATE posts SET name = '${newName}', school='${newSchool}' WHERE id = ${req.params.id};

Title: Update SQL from React

Body:
I build a react app using nodejs and mysql. I want to update an entry from react but the following code doesn't working and I can't understan what is the problem. Any suggestions are much appreciated.

// from index.js

script.get('/updatepost/:id', (req, res) => {
    let sql = `UPDATE posts SET name = '${req.body.name}', school='${req.body.school}' WHERE id = ${req.params.id}`;
    let query = connection.query(sql, (err, result) => {
        if(err) throw err;
        console.log(result);
        res.send('Post updated...');
    })
});

//from react component

axios(`http://localhost:4000/updatepost/${userId}`, {
method: 'PATCH',
data: qs.stringify(data);
})


问:
Flutter Keyboard makes textfield hide
I'm new to flutter. I've added a form with a text field and when I clicked the textfield and keyboard comes, the textfield goes up.

This is my code :

```<code>Widget build(BuildContext context) {

MediaQueryData mediaQuery = MediaQuery.of(context);
return new Scaffold(
  body:  new Container(
      color: Colors.purple,
      constraints: new BoxConstraints.expand(),
      padding: EdgeInsets.only(top: 10.0,left: 10.0,right: 10.0, bottom: mediaQuery.viewInsets.bottom, ),
      child: SingleChildScrollView(
        child: Container(
            child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  SizedBox(height: 12.0),
                  Text(
                    'What is your Business Name?',
                    style: TextStyle(fontSize: 24.0),
                  ),
                  AppForm(),
                ],
              ),
            padding: EdgeInsets.only(left: 10.0,right: 10.0, bottom: mediaQuery.viewInsets.bottom),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.all(Radius.circular(30.0)),
              color: Colors.white,
                ),
              )
          )
      ),
    );
  }
</code>```

This is the result without opening the keyboard:
Image without keyboard

This is the image after opening the keyboard:
Image after opening the keyboard

Here is my flutter doctor output.

```<code>Doctor summary (to see all details, run flutter doctor -v): [√] Flutter
(Channel beta, v0.5.1, on Microsoft Windows [Version 10.0.17134.165], locale
en-US) [√] Android toolchain - develop for Android devices (Android SDK
28.0.0) [√] Android Studio (version 3.1) [!] VS Code, 64-bit edition (version
1.25.1) [!] Connected devices ! No devices available ! Doctor found issues in
2 categories.
</code>```

any idea how to fix this?

答:
If you are using Scaffold than wrap the body with SingleChildScrollView

for Example like this:

```<code>...
return Scaffold(
body: SingleChildScrollView(
    child: Column(
      children: <Widget>[
        TextField(),
        TextField(),
        TextField(),
      ],
    ),
  ),
);
...
</code>```

this was really a lifesaver for me.
Now the scaffold will become scrollable.

Title: Flutter Keyboard makes textfield hide

Body:
I'm new to flutter. I've added a form with a text field and when I clicked the textfield and keyboard comes, the textfield goes up.

This is my code :

Widget build(BuildContext context) {

MediaQueryData mediaQuery = MediaQuery.of(context);
return new Scaffold(
  body:  new Container(
      color: Colors.purple,
      constraints: new BoxConstraints.expand(),
      padding: EdgeInsets.only(top: 10.0,left: 10.0,right: 10.0, bottom: mediaQuery.viewInsets.bottom, ),
      child: SingleChildScrollView(
        child: Container(
            child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  SizedBox(height: 12.0),
                  Text(
                    'What is your Business Name?',
                    style: TextStyle(fontSize: 24.0),
                  ),
                  AppForm(),
                ],
              ),
            padding: EdgeInsets.only(left: 10.0,right: 10.0, bottom: mediaQuery.viewInsets.bottom),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.all(Radius.circular(30.0)),
              color: Colors.white,
                ),
              )
          )
      ),
    );
  }

This is the result without opening the keyboard:
Image without keyboard

This is the image after opening the keyboard:
Image after opening the keyboard

Here is my flutter doctor output.

Doctor summary (to see all details, run flutter doctor -v): [√] Flutter
(Channel beta, v0.5.1, on Microsoft Windows [Version 10.0.17134.165], locale
en-US) [√] Android toolchain - develop for Android devices (Android SDK
28.0.0) [√] Android Studio (version 3.1) [!] VS Code, 64-bit edition (version
1.25.1) [!] Connected devices ! No devices available ! Doctor found issues in
2 categories.

any idea how to fix this?

Body:
If you are using Scaffold than wrap the body with SingleChildScrollView

for Example like this:

...
return Scaffold(
body: SingleChildScrollView(
    child: Column(
      children: <Widget>[
        TextField(),
        TextField(),
        TextField(),
      ],
    ),
  ),
);
...

this was really a lifesaver for me.
Now the scaffold will become scrollable.


问:
PowerMock throwing class not found exception in test class
I am using Play 2.6.13 and mockito-all 2.10.19 and using sbt for building.
While executing sbt test, i am getting the below exception in test calsses:

initializationError failed: org.powermock.reflect.exceptions.FieldNotFoundException: Field 'fTestClass' was not found in class org.junit.internal.runners.MethodValidator.,

I am using the mockito by configuring in sbt as below:
"org.mockito" % "mockito-all" % "1.10.19" % "test"

Any help.

Thanks

答:
Seems to be known issue: https://github.com/powermock/powermock/issues/551

According to link I provided, they renamed fTestClass to simply testClass in JUnit 4.12, so I suppose you have to use more recent PowerMock lib version.