问:
Creating error bar that extends from data point to an exact curve
I have the following plot that I generated with matplotlib.

I would like to draw error bars from the data points to the red curve. I have experimented with matplotlib.pyplot.errorbars() function, but I could not find a decent way to do this.
Here is the code for the plot:

```<code># imports
import numpy as np
import matplotlib.pyplot as plt

# data for scatter plot
target_time = np.array([0., 1.001001, 2.002002, 3.003003, 4.004004, 5.00500501, 6.00600601, 7.00700701, 8.00800801, 9.00900901])
results = np.array([0.9073288221126276, 0.16595939901364837, 0.37664869824521163, 0.7899988530794816, 0.03750430095194403, 0.5939901364835417, 0.6294299805023512, 0.031081546048858814, 0.7823144856061475, 0.4050923271017319])

# exact curve
time = np.arange(0, 1000, 0.01)
y = np.cos(2*time)**2

# plot data
plt.scatter(target_time, results, label='Simulation Result')

# plot exact curve
plt.plot(time, y, color='red', label='Exact Curve')
plt.xlim(0, 10)
plt.xlabel('Time')
plt.ylabel('Probability Density')
plt.title('Noisy Simulation: Time Dependent Probability Density')
plt.legend()
plt.show()

</code>```

答:
You can do this using matplotlib.pyplot.errorbars by specifiying the error. Here the error is given by the distance between the blue point and the red curve. In the code, I've done it for you assuming the error is in the y-direction. This can be similarily done for error in the x-direction.

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

# data for scatter plot
target_time = np.array([0., 1.001001, 2.002002, 3.003003, 4.004004, 5.00500501, 6.00600601, 7.00700701, 8.00800801, 9.00900901])
results = np.array([0.9073288221126276, 0.16595939901364837, 0.37664869824521163, 0.7899988530794816, 0.03750430095194403, 0.5939901364835417, 0.6294299805023512, 0.031081546048858814, 0.7823144856061475, 0.4050923271017319])

# exact curve
time = np.arange(0, 1000, 0.01)
y = np.cos(2*time)**2

# plot data

yerr = abs(results -  np.cos(2*target_time)**2) #calcuating the y-error
plt.errorbar(target_time, results,yerr=yerr, marker='o', ls ='none', label='Simulation Result') #This plots both the points AND the error bars. I replaced plt.scatter with this.

# plot exact curve
plt.plot(time, y, color='red', label='Exact Curve')
plt.xlim(0, 10)
plt.xlabel('Time')
plt.ylabel('Probability Density')
plt.title('Noisy Simulation: Time Dependent Probability Density')
plt.legend()
plt.show()
</code>```

Additonally, you can also add fancy styles e.g., errorbar caps, color, etc. Please refer to the wiki page: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.errorbar.html

Body:
I have the following plot that I generated with matplotlib.

I would like to draw error bars from the data points to the red curve. I have experimented with matplotlib.pyplot.errorbars() function, but I could not find a decent way to do this.
Here is the code for the plot:

# imports
import numpy as np
import matplotlib.pyplot as plt

# data for scatter plot
target_time = np.array([0., 1.001001, 2.002002, 3.003003, 4.004004, 5.00500501, 6.00600601, 7.00700701, 8.00800801, 9.00900901])
results = np.array([0.9073288221126276, 0.16595939901364837, 0.37664869824521163, 0.7899988530794816, 0.03750430095194403, 0.5939901364835417, 0.6294299805023512, 0.031081546048858814, 0.7823144856061475, 0.4050923271017319])

# exact curve
time = np.arange(0, 1000, 0.01)
y = np.cos(2*time)**2

# plot data
plt.scatter(target_time, results, label='Simulation Result')

# plot exact curve
plt.plot(time, y, color='red', label='Exact Curve')
plt.xlim(0, 10)
plt.xlabel('Time')
plt.ylabel('Probability Density')
plt.title('Noisy Simulation: Time Dependent Probability Density')
plt.legend()
plt.show()

Body:
You can do this using matplotlib.pyplot.errorbars by specifiying the error. Here the error is given by the distance between the blue point and the red curve. In the code, I've done it for you assuming the error is in the y-direction. This can be similarily done for error in the x-direction.

import numpy as np
import matplotlib.pyplot as plt

# data for scatter plot
target_time = np.array([0., 1.001001, 2.002002, 3.003003, 4.004004, 5.00500501, 6.00600601, 7.00700701, 8.00800801, 9.00900901])
results = np.array([0.9073288221126276, 0.16595939901364837, 0.37664869824521163, 0.7899988530794816, 0.03750430095194403, 0.5939901364835417, 0.6294299805023512, 0.031081546048858814, 0.7823144856061475, 0.4050923271017319])

# exact curve
time = np.arange(0, 1000, 0.01)
y = np.cos(2*time)**2

# plot data

yerr = abs(results -  np.cos(2*target_time)**2) #calcuating the y-error
plt.errorbar(target_time, results,yerr=yerr, marker='o', ls ='none', label='Simulation Result') #This plots both the points AND the error bars. I replaced plt.scatter with this.

# plot exact curve
plt.plot(time, y, color='red', label='Exact Curve')
plt.xlim(0, 10)
plt.xlabel('Time')
plt.ylabel('Probability Density')
plt.title('Noisy Simulation: Time Dependent Probability Density')
plt.legend()
plt.show()

Additonally, you can also add fancy styles e.g., errorbar caps, color, etc. Please refer to the wiki page: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.errorbar.html


来源: stackexchange

问:
Unusual way of using java constructor
At some part of the code that I've been working on I am tempted to use the constructor in an unusual way. The goal is to have minimal to none sensitive values inside string pool.

public class MyClass{
    private String mySafeString;

    public MyClass(char[] aCharArray, String salt) {
         this.mySafeString = Encrypt.encrypt(new String(aCharArray), salt);
    }

    public String getMySafeString(){
         return this.mySafeString;
    }
}

...
public static void main(String[] args){
    String salt = getSaltFromSomewhere();
    char[] someKey = new char[]{'c', 'x'};
    var myObject = new MyClass(someKey, salt);
    var encryptedSafeString = myObject.getMySafeString();
}
```

By creating the String object like that I am avoiding the value's presence inside the string pool. Thereby, intending to leave it to GC to perish the object.

However, I fail to find any resource that forbids the usage of constructor like the way I used it. I am keen to know if it is a bad practice in any way?

Could you please be so kind and advise me on my approach?

答:
I think you mean safe means that the string won't be modified outside of the class.  As a result, you are making a copy.

You don't need to do this for String because strings are immutable.  There's no way to modify the string outside of the class even if there's a reference to the string outside of the class.

ContentLicense: CC BY-SA 4.0

Title: Unusual way of using java constructor

Body:
At some part of the code that I've been working on I am tempted to use the constructor in an unusual way. The goal is to have minimal to none sensitive values inside string pool.

public class MyClass{
    private String mySafeString;

    public MyClass(char[] aCharArray, String salt) {
         this.mySafeString = Encrypt.encrypt(new String(aCharArray), salt);
    }

    public String getMySafeString(){
         return this.mySafeString;
    }
}

...
public static void main(String[] args){
    String salt = getSaltFromSomewhere();
    char[] someKey = new char[]{'c', 'x'};
    var myObject = new MyClass(someKey, salt);
    var encryptedSafeString = myObject.getMySafeString();
}

By creating the String object like that I am avoiding the value's presence inside the string pool. Thereby, intending to leave it to GC to perish the object.

However, I fail to find any resource that forbids the usage of constructor like the way I used it. I am keen to know if it is a bad practice in any way?

Could you please be so kind and advise me on my approach?


问:
Install Shield doesn't create new folder
I am new to installshield. However, I'm trying to apply the simplest of commands, but ran into an issue.
I have an installation that needs to be installed in c:\program files(x86) (Tried other locations as well). We want to make it automated, so we applied the following command to record the installation.

```<code>    (Location of the setup)\Setup.exe -r -f1(Full path)\SetupAnswer.iss
</code>```

and run the setup smoothly.
which installed in c:\program files(x86)(Program name) and created an answerfile
Next when I try to run (Location of the setup)\Setup.exe -S -f(Full path)\SetupAnswer.iss On a new PC it doesn't work.
After some testing. I found that if I create the folder name in c:\program files(x86)(Folder name) before I run the command above, it works like a charm.

I can create a short script to create a folder before running the setup command. But it doesn't look "clean". Checking the .ISS file reveals that at the location it wants to create the folder it looks like this -

```<code>    szDir=(installation path)\(Folder name)
    Result = 1
</code>```

Not sure if this szDir means create or just use the following path.
Let me know if I'm missing something.

Regards,

Nik

答:
There was an issue with the installation sequence, found it after following yossiz74 advice. There was a missing line due to the folder already existing in c:

Reinstalled it on a clean PC with the record method - Problem solved.

Body:
I am new to installshield. However, I'm trying to apply the simplest of commands, but ran into an issue.
I have an installation that needs to be installed in c:\program files(x86) (Tried other locations as well). We want to make it automated, so we applied the following command to record the installation.

    (Location of the setup)\Setup.exe -r -f1(Full path)\SetupAnswer.iss

and run the setup smoothly.
which installed in c:\program files(x86)(Program name) and created an answerfile
Next when I try to run (Location of the setup)\Setup.exe -S -f(Full path)\SetupAnswer.iss On a new PC it doesn't work.
After some testing. I found that if I create the folder name in c:\program files(x86)(Folder name) before I run the command above, it works like a charm.

I can create a short script to create a folder before running the setup command. But it doesn't look "clean". Checking the .ISS file reveals that at the location it wants to create the folder it looks like this -

    szDir=(installation path)\(Folder name)
    Result = 1

Not sure if this szDir means create or just use the following path.
Let me know if I'm missing something.

Regards,

Nik


问:
Added code and now it's not print correctly to CSV file
I have the first code that is working and printing to csv, however it included a lot of data I didn't need.  A paragraph of code was then added to only include the data I wanted.  The problem is it prints to the screen correctly but still includes all the data in the CSV file.  I've tried everything I could think of in this line but it won't either won't print or still prints everything.

data = pd.DataFrame(stock_info)

Could someone show me where I'm going wrong so it will print only the portion I want it to?

Old Working Code

```<code>import requests
import pandas as pd

url = "https://www.stockrover.com/stock_infos/grid?_dc=1644769629231"

def stock_data(stock_info):
    data = pd.DataFrame(stock_info)
    data.to_csv("data.csv", index=False)

payload = "state=%7B%22sortInfo%22%3A%7B%7D%2C%22columns%22%3A%5B77%2C32%2C498%2C500%2C31%2C27%2C499%2C30%2C578%2C28%2C29%2C544%2C181%2C185%2C186%5D%2C%22view%22%3A281%2C%22priorPrimaryColumn%22%3A170%2C%22filterData%22%3A%5B%5D%2C%22name%22%3A%22New%201%22%2C%22cType%22%3A%22Screener%22%2C%22cNode%22%3A%22s_39%22%2C%22cIsFolder%22%3Afalse%2C%22gridSelection%22%3A%22BTU%22%2C%22lastActive%22%3A1396898415%2C%22primaryColumn%22%3A76%2C%22folderDisabledParams%22%3A%7B%22filterData%22%3A%5B%5D%7D%2C%22mainGridDateRange%22%3A%22ytd%22%2C%22groupState%22%3Anull%2C%22moversGridDateRange%22%3A%221_day%22%2C%22peersGridDateRange%22%3A%221_day%22%2C%22lastGridSelections%22%3A%5B%22BTU%22%5D%2C%22lastQuantNode%22%3A%5B%5D%2C%22includeQuotesInTable%22%3Afalse%2C%22includeAllQuotesLastValue%22%3Afalse%2C%22markets%22%3A%7B%22panel%22%3A%22summary%22%7D%2C%22researchPanel%22%3A%22tablePanel%22%2C%22recentSearchTickers%22%3A%5B%22SPY%22%2C%22AMZN%22%2C%22AAPL%22%2C%22s_32%22%2C%22%5ENDX%22%2C%22AXP%22%2C%22XOM%22%2C%22AFL%22%2C%22%5EDJX%22%2C%22AIT%22%2C%22ADVC%22%5D%2C%22quotesBoxTickers%22%3A%5B%22AMZN%22%2C%22AAPL%22%2C%22SPY%22%5D%2C%22checkedQuotesBoxTickers%22%3A%5B%22AMZN%22%2C%22AAPL%22%2C%22SPY%22%5D%2C%22dashboard%22%3A%7B%22buttonRef%22%3A%22272%22%7D%2C%22tickerSelectedFeeds%22%3A%5B%22Benzinga%20News%22%2C%22Yahoo%20News%22%5D%2C%22marketSelectedFeeds%22%3A%5B%22Google%20News%22%2C%22Stock%20Market%20News%20-%20Investing.com%22%5D%2C%22bondsSelectedFeeds%22%3A%5B%22Bonds%20Strategy%20-%20Investing.com%22%5D%2C%22commoditiesSelectedFeeds%22%3A%5B%22Commodities%20%26%20Futures%20News%20-%20Investing.com%22%2C%22Commodities%20Fundamental%20Analysis%20-%20Investing.com%22%2C%22Commodities%20Strategy%20Analysis%20-%20Investing.com%22%5D%2C%22stocksSelectedFeeds%22%3A%5B%22CNNMoney%20News%22%2C%22Google%20News%22%2C%22Seeking%20Alpha%20Top%20Stories%22%5D%2C%22etfsSelectedFeeds%22%3A%5B%22Economy%20News%20-%20Investing.com%22%2C%22ETF%20Analysis%20-%20Investing.com%22%2C%22Investing%20Ideas%20-%20Investing.com%22%5D%2C%22topPanel%22%3A%22researchPanel%22%2C%22maxRecordsNode%22%3Afalse%2C%22version%22%3A7%2C%22lastGridSelectionsRaw%22%3A%5B%22BTU%22%5D%2C%22lastSelectionScreeners%22%3A%22s_39%22%2C%22quotesDisabled%22%3Atrue%2C%22lastSelectionPortfolios%22%3A%22p_2%22%2C%22comparisonPanels%22%3A%7B%22Portfolio%22%3A%22p_2%22%2C%22Index%22%3A%22%5EDJX%22%2C%22Watchlist%22%3A%22Watchlists%22%2C%22Screener%22%3A%22s_39%22%7D%2C%22lastSelectionWatchlists%22%3A%22w_26%22%2C%22indicesSelectedFeeds%22%3A%5B%22Google%20News%22%2C%22Yahoo%20News%22%5D%2C%22newsActive%22%3A%22tickerNews%22%2C%22recentSearchMetrics%22%3A%5B%22Price%22%2C%22EPS%22%2C%22Sales%22%5D%2C%22editPanel%22%3A%22positionsPanel%22%2C%22newsType%22%3A%22marketNews%22%2C%22tableColumns%22%3A%5B%22ticker%22%2C%22rank%22%2C%22score_rank%22%2C%22filter_score%22%2C%22company%22%2C%22cash%22%2C%22currentassets%22%2C%22netppe%22%2C%22intangibles%22%2C%22totalassets%22%2C%22currentliabilities%22%2C%22longtermdebt%22%2C%22totaldebt%22%2C%22totalliabilities%22%2C%22equity%22%2C%22tangiblebookvalue%22%2C%22cash_short_term_p%22%2C%22net_ppe_p%22%2C%22intangibles_p%22%5D%2C%22last_save%22%3A1644769379%2C%22panels%22%3A%7B%22collapsed%22%3A%7B%22chp%22%3Atrue%2C%22ip%22%3Atrue%2C%22mp%22%3Afalse%2C%22qp%22%3Afalse%2C%22conp%22%3Atrue%2C%22fsp%22%3Afalse%7D%2C%22viewportWidth%22%3A%221920%22%2C%22viewportHeight%22%3A%221069%22%2C%22chartPanelHeight%22%3A483%2C%22controlPanelWidth%22%3A296%2C%22insightPanelWidth%22%3A%22485%22%2C%22quoteBoxHeight%22%3A200%2C%22navigationPanelWidth%22%3A277%7D%7D&updateMarket=true&page=1&start=0&limit=250"
headers = {
    'authority': 'www.stockrover.com',
    'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="98", "Google Chrome";v="98"',
    'x-csrf-token': '7yR4pfI0kAArtjJak535+NJrpB0L212PAbXCg0kbyE4SyjFaQ73sMHJLiqAkPb5nGzfC8KvAa3kTADLAEQXyOQ==',
    'sec-ch-ua-mobile': '?0',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.82 Safari/537.36',
    'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'accept': 'application/json',
    'x-requested-with': 'XMLHttpRequest',
    'sec-ch-ua-platform': '"Windows"',
    'origin': 'https://www.stockrover.com',
    'sec-fetch-site': 'same-origin',
    'sec-fetch-mode': 'cors',
    'sec-fetch-dest': 'empty',
    'referer': 'https://www.stockrover.com/research/table/281/s_39/BTU',
    'accept-language': 'en-US,en;q=0.9',
    'cookie': 'remember_me_pref=0; user_name=test11964; plan=3; premiumBraintreeKey=MIIBCgKCAQEAzM4LJfrNnBOgRFB1dDJkmqTFCWT2Y%2BksOydD8xDH4R033WUzxbffMZb%2B3dqEyQvOVjLcwFIHByDc4Xwej7enas2E%2FVRyh7Cvyadn7M5zQeRyLcI9Ys5KCozMwxJPc0x76FlXPwiAo1Qlz3RcLb9wGHBag2R51FuTie%2BhVDCgzWajqDCREzRhi%2Fqlt3D%2FxXNo%2FiwJlpOUr%2Fx1QnkkILxgKlq1dD7KJ767O5ojYKXsO%2BV2Bfu7sSD3djsOxQJ1%2FRbaDm2E96EDkWhhOeOpPndQ6IuSl4NmnJg%2Fcq6f8csW8M3Ys%2BMZPFkdxPC4%2FfRM1XC9o76PjpVNBIO%2ByJEELKZedwIDAQAB; lr=1644769628; _Ruby2_session=Q1drcmlhazYvUFZLd0NydnRXUGpoUzArZDlxYWRCcW9sRUx5VDBydWVWRHdGWDZlMnlESURzbldwbFV1L0drbUlKaWt5MXRtaS9iR0ZYZEpPVHQ1N25qRnR1d3FrY0tzQW1qQm9CdTZ3MSs0d2c3MlpuMjRiQWhCOHI1cGNWekZ4cUdJd0ZFcGtpeng3MFlqZjFDUW9RYmpFMU9DeGdGMVZKR1EwMjVhSE9yVHl4VXFtQm9aYVBtNHF5d0pwMjJ1aVlNMUVRUzdnVFZWZ1AxQkY5Q0p6a2RKay9QL05tOWk4cHZiSERtaGRxeTlxTWZnV3Q0cjdwR3RndUtmeUp3QThhMnJaV2dGZjlPUUtjcGRidDhiajRxK2g0RUZTMWNZUDBaeGNCcUVxSDJ1QnZVRlRkWk9tUExJNWN3TDN5T1BQcmhVVGsycStVTzJRaUwvSkk2TnNVZldTOGU3Tm5wQ3RUMy9nazFqbzdrUWtvYzRwQWRpV3dnTVB3YzhodFV2U0FRR3VKdllMY01NZmdOdGtmOEJ4UT09LS1nTXBrYldhQ0pEeWJ3ak9qQjcrTGV3PT0%3D--1439f36a7f9362aee4b5b666747a2d63d72e81bd'
}

response = requests.request("POST", url, headers=headers, data=payload)
stock_info = response.json()['stock_infos']
stock_data(stock_info)
</code>```

New Non-Working Code

```<code>import requests
import pandas as pd

url = "https://www.stockrover.com/stock_infos/grid?_dc=1644769629231"

def stock_data(stock_info):
    data = pd.DataFrame(stock_info)
    data.to_csv("data.csv", index=False)

payload = "state=%7B%22sortInfo%22%3A%7B%7D%2C%22columns%22%3A%5B77%2C32%2C498%2C500%2C31%2C27%2C499%2C30%2C578%2C28%2C29%2C544%2C181%2C185%2C186%5D%2C%22view%22%3A281%2C%22priorPrimaryColumn%22%3A170%2C%22filterData%22%3A%5B%5D%2C%22name%22%3A%22New%201%22%2C%22cType%22%3A%22Screener%22%2C%22cNode%22%3A%22s_39%22%2C%22cIsFolder%22%3Afalse%2C%22gridSelection%22%3A%22BTU%22%2C%22lastActive%22%3A1396898415%2C%22primaryColumn%22%3A76%2C%22folderDisabledParams%22%3A%7B%22filterData%22%3A%5B%5D%7D%2C%22mainGridDateRange%22%3A%22ytd%22%2C%22groupState%22%3Anull%2C%22moversGridDateRange%22%3A%221_day%22%2C%22peersGridDateRange%22%3A%221_day%22%2C%22lastGridSelections%22%3A%5B%22BTU%22%5D%2C%22lastQuantNode%22%3A%5B%5D%2C%22includeQuotesInTable%22%3Afalse%2C%22includeAllQuotesLastValue%22%3Afalse%2C%22markets%22%3A%7B%22panel%22%3A%22summary%22%7D%2C%22researchPanel%22%3A%22tablePanel%22%2C%22recentSearchTickers%22%3A%5B%22SPY%22%2C%22AMZN%22%2C%22AAPL%22%2C%22s_32%22%2C%22%5ENDX%22%2C%22AXP%22%2C%22XOM%22%2C%22AFL%22%2C%22%5EDJX%22%2C%22AIT%22%2C%22ADVC%22%5D%2C%22quotesBoxTickers%22%3A%5B%22AMZN%22%2C%22AAPL%22%2C%22SPY%22%5D%2C%22checkedQuotesBoxTickers%22%3A%5B%22AMZN%22%2C%22AAPL%22%2C%22SPY%22%5D%2C%22dashboard%22%3A%7B%22buttonRef%22%3A%22272%22%7D%2C%22tickerSelectedFeeds%22%3A%5B%22Benzinga%20News%22%2C%22Yahoo%20News%22%5D%2C%22marketSelectedFeeds%22%3A%5B%22Google%20News%22%2C%22Stock%20Market%20News%20-%20Investing.com%22%5D%2C%22bondsSelectedFeeds%22%3A%5B%22Bonds%20Strategy%20-%20Investing.com%22%5D%2C%22commoditiesSelectedFeeds%22%3A%5B%22Commodities%20%26%20Futures%20News%20-%20Investing.com%22%2C%22Commodities%20Fundamental%20Analysis%20-%20Investing.com%22%2C%22Commodities%20Strategy%20Analysis%20-%20Investing.com%22%5D%2C%22stocksSelectedFeeds%22%3A%5B%22CNNMoney%20News%22%2C%22Google%20News%22%2C%22Seeking%20Alpha%20Top%20Stories%22%5D%2C%22etfsSelectedFeeds%22%3A%5B%22Economy%20News%20-%20Investing.com%22%2C%22ETF%20Analysis%20-%20Investing.com%22%2C%22Investing%20Ideas%20-%20Investing.com%22%5D%2C%22topPanel%22%3A%22researchPanel%22%2C%22maxRecordsNode%22%3Afalse%2C%22version%22%3A7%2C%22lastGridSelectionsRaw%22%3A%5B%22BTU%22%5D%2C%22lastSelectionScreeners%22%3A%22s_39%22%2C%22quotesDisabled%22%3Atrue%2C%22lastSelectionPortfolios%22%3A%22p_2%22%2C%22comparisonPanels%22%3A%7B%22Portfolio%22%3A%22p_2%22%2C%22Index%22%3A%22%5EDJX%22%2C%22Watchlist%22%3A%22Watchlists%22%2C%22Screener%22%3A%22s_39%22%7D%2C%22lastSelectionWatchlists%22%3A%22w_26%22%2C%22indicesSelectedFeeds%22%3A%5B%22Google%20News%22%2C%22Yahoo%20News%22%5D%2C%22newsActive%22%3A%22tickerNews%22%2C%22recentSearchMetrics%22%3A%5B%22Price%22%2C%22EPS%22%2C%22Sales%22%5D%2C%22editPanel%22%3A%22positionsPanel%22%2C%22newsType%22%3A%22marketNews%22%2C%22tableColumns%22%3A%5B%22ticker%22%2C%22rank%22%2C%22score_rank%22%2C%22filter_score%22%2C%22company%22%2C%22cash%22%2C%22currentassets%22%2C%22netppe%22%2C%22intangibles%22%2C%22totalassets%22%2C%22currentliabilities%22%2C%22longtermdebt%22%2C%22totaldebt%22%2C%22totalliabilities%22%2C%22equity%22%2C%22tangiblebookvalue%22%2C%22cash_short_term_p%22%2C%22net_ppe_p%22%2C%22intangibles_p%22%5D%2C%22last_save%22%3A1644769379%2C%22panels%22%3A%7B%22collapsed%22%3A%7B%22chp%22%3Atrue%2C%22ip%22%3Atrue%2C%22mp%22%3Afalse%2C%22qp%22%3Afalse%2C%22conp%22%3Atrue%2C%22fsp%22%3Afalse%7D%2C%22viewportWidth%22%3A%221920%22%2C%22viewportHeight%22%3A%221069%22%2C%22chartPanelHeight%22%3A483%2C%22controlPanelWidth%22%3A296%2C%22insightPanelWidth%22%3A%22485%22%2C%22quoteBoxHeight%22%3A200%2C%22navigationPanelWidth%22%3A277%7D%7D&updateMarket=true&page=1&start=0&limit=250"
headers = {
    'authority': 'www.stockrover.com',
    'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="98", "Google Chrome";v="98"',
    'x-csrf-token': '7yR4pfI0kAArtjJak535+NJrpB0L212PAbXCg0kbyE4SyjFaQ73sMHJLiqAkPb5nGzfC8KvAa3kTADLAEQXyOQ==',
    'sec-ch-ua-mobile': '?0',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.82 Safari/537.36',
    'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'accept': 'application/json',
    'x-requested-with': 'XMLHttpRequest',
    'sec-ch-ua-platform': '"Windows"',
    'origin': 'https://www.stockrover.com',
    'sec-fetch-site': 'same-origin',
    'sec-fetch-mode': 'cors',
    'sec-fetch-dest': 'empty',
    'referer': 'https://www.stockrover.com/research/table/281/s_39/BTU',
    'accept-language': 'en-US,en;q=0.9',
    'cookie': 'remember_me_pref=0; user_name=test11964; plan=3; premiumBraintreeKey=MIIBCgKCAQEAzM4LJfrNnBOgRFB1dDJkmqTFCWT2Y%2BksOydD8xDH4R033WUzxbffMZb%2B3dqEyQvOVjLcwFIHByDc4Xwej7enas2E%2FVRyh7Cvyadn7M5zQeRyLcI9Ys5KCozMwxJPc0x76FlXPwiAo1Qlz3RcLb9wGHBag2R51FuTie%2BhVDCgzWajqDCREzRhi%2Fqlt3D%2FxXNo%2FiwJlpOUr%2Fx1QnkkILxgKlq1dD7KJ767O5ojYKXsO%2BV2Bfu7sSD3djsOxQJ1%2FRbaDm2E96EDkWhhOeOpPndQ6IuSl4NmnJg%2Fcq6f8csW8M3Ys%2BMZPFkdxPC4%2FfRM1XC9o76PjpVNBIO%2ByJEELKZedwIDAQAB; lr=1644769628; _Ruby2_session=Q1drcmlhazYvUFZLd0NydnRXUGpoUzArZDlxYWRCcW9sRUx5VDBydWVWRHdGWDZlMnlESURzbldwbFV1L0drbUlKaWt5MXRtaS9iR0ZYZEpPVHQ1N25qRnR1d3FrY0tzQW1qQm9CdTZ3MSs0d2c3MlpuMjRiQWhCOHI1cGNWekZ4cUdJd0ZFcGtpeng3MFlqZjFDUW9RYmpFMU9DeGdGMVZKR1EwMjVhSE9yVHl4VXFtQm9aYVBtNHF5d0pwMjJ1aVlNMUVRUzdnVFZWZ1AxQkY5Q0p6a2RKay9QL05tOWk4cHZiSERtaGRxeTlxTWZnV3Q0cjdwR3RndUtmeUp3QThhMnJaV2dGZjlPUUtjcGRidDhiajRxK2g0RUZTMWNZUDBaeGNCcUVxSDJ1QnZVRlRkWk9tUExJNWN3TDN5T1BQcmhVVGsycStVTzJRaUwvSkk2TnNVZldTOGU3Tm5wQ3RUMy9nazFqbzdrUWtvYzRwQWRpV3dnTVB3YzhodFV2U0FRR3VKdllMY01NZmdOdGtmOEJ4UT09LS1nTXBrYldhQ0pEeWJ3ak9qQjcrTGV3PT0%3D--1439f36a7f9362aee4b5b666747a2d63d72e81bd'
}

response = requests.request("POST", url, headers=headers, data=payload)
stock_info = response.json()['stock_infos']
stock_data(stock_info)

for info in stock_info:
    key = info[0]
    for i, sub in enumerate(info[1:], 1):
        if sub == key:
            print(info[i:])
            break
</code>```

答:
The added block of code is added after the csv file has already been written.

You have other problems as well but that is the most obvious at the moment.

it should be closer to...

```<code>...

for info in stock_info:
    key = info[0]
    for i, sub in enumerate(info[1:], 1):
        if sub == key:
            print(info[i:])
            break

stock_data(stock_info)
</code>```

Also the added block of code doesn't actually make any changes to the data, it only changes what ends up getting printed. Whatever changes you want made to the file need to be made to stock_info.

Body:
I have the first code that is working and printing to csv, however it included a lot of data I didn't need.  A paragraph of code was then added to only include the data I wanted.  The problem is it prints to the screen correctly but still includes all the data in the CSV file.  I've tried everything I could think of in this line but it won't either won't print or still prints everything.

data = pd.DataFrame(stock_info)

Could someone show me where I'm going wrong so it will print only the portion I want it to?

Old Working Code

import requests
import pandas as pd

url = "https://www.stockrover.com/stock_infos/grid?_dc=1644769629231"

def stock_data(stock_info):
    data = pd.DataFrame(stock_info)
    data.to_csv("data.csv", index=False)

payload = "state=%7B%22sortInfo%22%3A%7B%7D%2C%22columns%22%3A%5B77%2C32%2C498%2C500%2C31%2C27%2C499%2C30%2C578%2C28%2C29%2C544%2C181%2C185%2C186%5D%2C%22view%22%3A281%2C%22priorPrimaryColumn%22%3A170%2C%22filterData%22%3A%5B%5D%2C%22name%22%3A%22New%201%22%2C%22cType%22%3A%22Screener%22%2C%22cNode%22%3A%22s_39%22%2C%22cIsFolder%22%3Afalse%2C%22gridSelection%22%3A%22BTU%22%2C%22lastActive%22%3A1396898415%2C%22primaryColumn%22%3A76%2C%22folderDisabledParams%22%3A%7B%22filterData%22%3A%5B%5D%7D%2C%22mainGridDateRange%22%3A%22ytd%22%2C%22groupState%22%3Anull%2C%22moversGridDateRange%22%3A%221_day%22%2C%22peersGridDateRange%22%3A%221_day%22%2C%22lastGridSelections%22%3A%5B%22BTU%22%5D%2C%22lastQuantNode%22%3A%5B%5D%2C%22includeQuotesInTable%22%3Afalse%2C%22includeAllQuotesLastValue%22%3Afalse%2C%22markets%22%3A%7B%22panel%22%3A%22summary%22%7D%2C%22researchPanel%22%3A%22tablePanel%22%2C%22recentSearchTickers%22%3A%5B%22SPY%22%2C%22AMZN%22%2C%22AAPL%22%2C%22s_32%22%2C%22%5ENDX%22%2C%22AXP%22%2C%22XOM%22%2C%22AFL%22%2C%22%5EDJX%22%2C%22AIT%22%2C%22ADVC%22%5D%2C%22quotesBoxTickers%22%3A%5B%22AMZN%22%2C%22AAPL%22%2C%22SPY%22%5D%2C%22checkedQuotesBoxTickers%22%3A%5B%22AMZN%22%2C%22AAPL%22%2C%22SPY%22%5D%2C%22dashboard%22%3A%7B%22buttonRef%22%3A%22272%22%7D%2C%22tickerSelectedFeeds%22%3A%5B%22Benzinga%20News%22%2C%22Yahoo%20News%22%5D%2C%22marketSelectedFeeds%22%3A%5B%22Google%20News%22%2C%22Stock%20Market%20News%20-%20Investing.com%22%5D%2C%22bondsSelectedFeeds%22%3A%5B%22Bonds%20Strategy%20-%20Investing.com%22%5D%2C%22commoditiesSelectedFeeds%22%3A%5B%22Commodities%20%26%20Futures%20News%20-%20Investing.com%22%2C%22Commodities%20Fundamental%20Analysis%20-%20Investing.com%22%2C%22Commodities%20Strategy%20Analysis%20-%20Investing.com%22%5D%2C%22stocksSelectedFeeds%22%3A%5B%22CNNMoney%20News%22%2C%22Google%20News%22%2C%22Seeking%20Alpha%20Top%20Stories%22%5D%2C%22etfsSelectedFeeds%22%3A%5B%22Economy%20News%20-%20Investing.com%22%2C%22ETF%20Analysis%20-%20Investing.com%22%2C%22Investing%20Ideas%20-%20Investing.com%22%5D%2C%22topPanel%22%3A%22researchPanel%22%2C%22maxRecordsNode%22%3Afalse%2C%22version%22%3A7%2C%22lastGridSelectionsRaw%22%3A%5B%22BTU%22%5D%2C%22lastSelectionScreeners%22%3A%22s_39%22%2C%22quotesDisabled%22%3Atrue%2C%22lastSelectionPortfolios%22%3A%22p_2%22%2C%22comparisonPanels%22%3A%7B%22Portfolio%22%3A%22p_2%22%2C%22Index%22%3A%22%5EDJX%22%2C%22Watchlist%22%3A%22Watchlists%22%2C%22Screener%22%3A%22s_39%22%7D%2C%22lastSelectionWatchlists%22%3A%22w_26%22%2C%22indicesSelectedFeeds%22%3A%5B%22Google%20News%22%2C%22Yahoo%20News%22%5D%2C%22newsActive%22%3A%22tickerNews%22%2C%22recentSearchMetrics%22%3A%5B%22Price%22%2C%22EPS%22%2C%22Sales%22%5D%2C%22editPanel%22%3A%22positionsPanel%22%2C%22newsType%22%3A%22marketNews%22%2C%22tableColumns%22%3A%5B%22ticker%22%2C%22rank%22%2C%22score_rank%22%2C%22filter_score%22%2C%22company%22%2C%22cash%22%2C%22currentassets%22%2C%22netppe%22%2C%22intangibles%22%2C%22totalassets%22%2C%22currentliabilities%22%2C%22longtermdebt%22%2C%22totaldebt%22%2C%22totalliabilities%22%2C%22equity%22%2C%22tangiblebookvalue%22%2C%22cash_short_term_p%22%2C%22net_ppe_p%22%2C%22intangibles_p%22%5D%2C%22last_save%22%3A1644769379%2C%22panels%22%3A%7B%22collapsed%22%3A%7B%22chp%22%3Atrue%2C%22ip%22%3Atrue%2C%22mp%22%3Afalse%2C%22qp%22%3Afalse%2C%22conp%22%3Atrue%2C%22fsp%22%3Afalse%7D%2C%22viewportWidth%22%3A%221920%22%2C%22viewportHeight%22%3A%221069%22%2C%22chartPanelHeight%22%3A483%2C%22controlPanelWidth%22%3A296%2C%22insightPanelWidth%22%3A%22485%22%2C%22quoteBoxHeight%22%3A200%2C%22navigationPanelWidth%22%3A277%7D%7D&updateMarket=true&page=1&start=0&limit=250"
headers = {
    'authority': 'www.stockrover.com',
    'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="98", "Google Chrome";v="98"',
    'x-csrf-token': '7yR4pfI0kAArtjJak535+NJrpB0L212PAbXCg0kbyE4SyjFaQ73sMHJLiqAkPb5nGzfC8KvAa3kTADLAEQXyOQ==',
    'sec-ch-ua-mobile': '?0',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.82 Safari/537.36',
    'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'accept': 'application/json',
    'x-requested-with': 'XMLHttpRequest',
    'sec-ch-ua-platform': '"Windows"',
    'origin': 'https://www.stockrover.com',
    'sec-fetch-site': 'same-origin',
    'sec-fetch-mode': 'cors',
    'sec-fetch-dest': 'empty',
    'referer': 'https://www.stockrover.com/research/table/281/s_39/BTU',
    'accept-language': 'en-US,en;q=0.9',
    'cookie': 'remember_me_pref=0; user_name=test11964; plan=3; premiumBraintreeKey=MIIBCgKCAQEAzM4LJfrNnBOgRFB1dDJkmqTFCWT2Y%2BksOydD8xDH4R033WUzxbffMZb%2B3dqEyQvOVjLcwFIHByDc4Xwej7enas2E%2FVRyh7Cvyadn7M5zQeRyLcI9Ys5KCozMwxJPc0x76FlXPwiAo1Qlz3RcLb9wGHBag2R51FuTie%2BhVDCgzWajqDCREzRhi%2Fqlt3D%2FxXNo%2FiwJlpOUr%2Fx1QnkkILxgKlq1dD7KJ767O5ojYKXsO%2BV2Bfu7sSD3djsOxQJ1%2FRbaDm2E96EDkWhhOeOpPndQ6IuSl4NmnJg%2Fcq6f8csW8M3Ys%2BMZPFkdxPC4%2FfRM1XC9o76PjpVNBIO%2ByJEELKZedwIDAQAB; lr=1644769628; _Ruby2_session=Q1drcmlhazYvUFZLd0NydnRXUGpoUzArZDlxYWRCcW9sRUx5VDBydWVWRHdGWDZlMnlESURzbldwbFV1L0drbUlKaWt5MXRtaS9iR0ZYZEpPVHQ1N25qRnR1d3FrY0tzQW1qQm9CdTZ3MSs0d2c3MlpuMjRiQWhCOHI1cGNWekZ4cUdJd0ZFcGtpeng3MFlqZjFDUW9RYmpFMU9DeGdGMVZKR1EwMjVhSE9yVHl4VXFtQm9aYVBtNHF5d0pwMjJ1aVlNMUVRUzdnVFZWZ1AxQkY5Q0p6a2RKay9QL05tOWk4cHZiSERtaGRxeTlxTWZnV3Q0cjdwR3RndUtmeUp3QThhMnJaV2dGZjlPUUtjcGRidDhiajRxK2g0RUZTMWNZUDBaeGNCcUVxSDJ1QnZVRlRkWk9tUExJNWN3TDN5T1BQcmhVVGsycStVTzJRaUwvSkk2TnNVZldTOGU3Tm5wQ3RUMy9nazFqbzdrUWtvYzRwQWRpV3dnTVB3YzhodFV2U0FRR3VKdllMY01NZmdOdGtmOEJ4UT09LS1nTXBrYldhQ0pEeWJ3ak9qQjcrTGV3PT0%3D--1439f36a7f9362aee4b5b666747a2d63d72e81bd'
}

response = requests.request("POST", url, headers=headers, data=payload)
stock_info = response.json()['stock_infos']
stock_data(stock_info)

New Non-Working Code

import requests
import pandas as pd

url = "https://www.stockrover.com/stock_infos/grid?_dc=1644769629231"

def stock_data(stock_info):
    data = pd.DataFrame(stock_info)
    data.to_csv("data.csv", index=False)

payload = "state=%7B%22sortInfo%22%3A%7B%7D%2C%22columns%22%3A%5B77%2C32%2C498%2C500%2C31%2C27%2C499%2C30%2C578%2C28%2C29%2C544%2C181%2C185%2C186%5D%2C%22view%22%3A281%2C%22priorPrimaryColumn%22%3A170%2C%22filterData%22%3A%5B%5D%2C%22name%22%3A%22New%201%22%2C%22cType%22%3A%22Screener%22%2C%22cNode%22%3A%22s_39%22%2C%22cIsFolder%22%3Afalse%2C%22gridSelection%22%3A%22BTU%22%2C%22lastActive%22%3A1396898415%2C%22primaryColumn%22%3A76%2C%22folderDisabledParams%22%3A%7B%22filterData%22%3A%5B%5D%7D%2C%22mainGridDateRange%22%3A%22ytd%22%2C%22groupState%22%3Anull%2C%22moversGridDateRange%22%3A%221_day%22%2C%22peersGridDateRange%22%3A%221_day%22%2C%22lastGridSelections%22%3A%5B%22BTU%22%5D%2C%22lastQuantNode%22%3A%5B%5D%2C%22includeQuotesInTable%22%3Afalse%2C%22includeAllQuotesLastValue%22%3Afalse%2C%22markets%22%3A%7B%22panel%22%3A%22summary%22%7D%2C%22researchPanel%22%3A%22tablePanel%22%2C%22recentSearchTickers%22%3A%5B%22SPY%22%2C%22AMZN%22%2C%22AAPL%22%2C%22s_32%22%2C%22%5ENDX%22%2C%22AXP%22%2C%22XOM%22%2C%22AFL%22%2C%22%5EDJX%22%2C%22AIT%22%2C%22ADVC%22%5D%2C%22quotesBoxTickers%22%3A%5B%22AMZN%22%2C%22AAPL%22%2C%22SPY%22%5D%2C%22checkedQuotesBoxTickers%22%3A%5B%22AMZN%22%2C%22AAPL%22%2C%22SPY%22%5D%2C%22dashboard%22%3A%7B%22buttonRef%22%3A%22272%22%7D%2C%22tickerSelectedFeeds%22%3A%5B%22Benzinga%20News%22%2C%22Yahoo%20News%22%5D%2C%22marketSelectedFeeds%22%3A%5B%22Google%20News%22%2C%22Stock%20Market%20News%20-%20Investing.com%22%5D%2C%22bondsSelectedFeeds%22%3A%5B%22Bonds%20Strategy%20-%20Investing.com%22%5D%2C%22commoditiesSelectedFeeds%22%3A%5B%22Commodities%20%26%20Futures%20News%20-%20Investing.com%22%2C%22Commodities%20Fundamental%20Analysis%20-%20Investing.com%22%2C%22Commodities%20Strategy%20Analysis%20-%20Investing.com%22%5D%2C%22stocksSelectedFeeds%22%3A%5B%22CNNMoney%20News%22%2C%22Google%20News%22%2C%22Seeking%20Alpha%20Top%20Stories%22%5D%2C%22etfsSelectedFeeds%22%3A%5B%22Economy%20News%20-%20Investing.com%22%2C%22ETF%20Analysis%20-%20Investing.com%22%2C%22Investing%20Ideas%20-%20Investing.com%22%5D%2C%22topPanel%22%3A%22researchPanel%22%2C%22maxRecordsNode%22%3Afalse%2C%22version%22%3A7%2C%22lastGridSelectionsRaw%22%3A%5B%22BTU%22%5D%2C%22lastSelectionScreeners%22%3A%22s_39%22%2C%22quotesDisabled%22%3Atrue%2C%22lastSelectionPortfolios%22%3A%22p_2%22%2C%22comparisonPanels%22%3A%7B%22Portfolio%22%3A%22p_2%22%2C%22Index%22%3A%22%5EDJX%22%2C%22Watchlist%22%3A%22Watchlists%22%2C%22Screener%22%3A%22s_39%22%7D%2C%22lastSelectionWatchlists%22%3A%22w_26%22%2C%22indicesSelectedFeeds%22%3A%5B%22Google%20News%22%2C%22Yahoo%20News%22%5D%2C%22newsActive%22%3A%22tickerNews%22%2C%22recentSearchMetrics%22%3A%5B%22Price%22%2C%22EPS%22%2C%22Sales%22%5D%2C%22editPanel%22%3A%22positionsPanel%22%2C%22newsType%22%3A%22marketNews%22%2C%22tableColumns%22%3A%5B%22ticker%22%2C%22rank%22%2C%22score_rank%22%2C%22filter_score%22%2C%22company%22%2C%22cash%22%2C%22currentassets%22%2C%22netppe%22%2C%22intangibles%22%2C%22totalassets%22%2C%22currentliabilities%22%2C%22longtermdebt%22%2C%22totaldebt%22%2C%22totalliabilities%22%2C%22equity%22%2C%22tangiblebookvalue%22%2C%22cash_short_term_p%22%2C%22net_ppe_p%22%2C%22intangibles_p%22%5D%2C%22last_save%22%3A1644769379%2C%22panels%22%3A%7B%22collapsed%22%3A%7B%22chp%22%3Atrue%2C%22ip%22%3Atrue%2C%22mp%22%3Afalse%2C%22qp%22%3Afalse%2C%22conp%22%3Atrue%2C%22fsp%22%3Afalse%7D%2C%22viewportWidth%22%3A%221920%22%2C%22viewportHeight%22%3A%221069%22%2C%22chartPanelHeight%22%3A483%2C%22controlPanelWidth%22%3A296%2C%22insightPanelWidth%22%3A%22485%22%2C%22quoteBoxHeight%22%3A200%2C%22navigationPanelWidth%22%3A277%7D%7D&updateMarket=true&page=1&start=0&limit=250"
headers = {
    'authority': 'www.stockrover.com',
    'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="98", "Google Chrome";v="98"',
    'x-csrf-token': '7yR4pfI0kAArtjJak535+NJrpB0L212PAbXCg0kbyE4SyjFaQ73sMHJLiqAkPb5nGzfC8KvAa3kTADLAEQXyOQ==',
    'sec-ch-ua-mobile': '?0',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.82 Safari/537.36',
    'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'accept': 'application/json',
    'x-requested-with': 'XMLHttpRequest',
    'sec-ch-ua-platform': '"Windows"',
    'origin': 'https://www.stockrover.com',
    'sec-fetch-site': 'same-origin',
    'sec-fetch-mode': 'cors',
    'sec-fetch-dest': 'empty',
    'referer': 'https://www.stockrover.com/research/table/281/s_39/BTU',
    'accept-language': 'en-US,en;q=0.9',
    'cookie': 'remember_me_pref=0; user_name=test11964; plan=3; premiumBraintreeKey=MIIBCgKCAQEAzM4LJfrNnBOgRFB1dDJkmqTFCWT2Y%2BksOydD8xDH4R033WUzxbffMZb%2B3dqEyQvOVjLcwFIHByDc4Xwej7enas2E%2FVRyh7Cvyadn7M5zQeRyLcI9Ys5KCozMwxJPc0x76FlXPwiAo1Qlz3RcLb9wGHBag2R51FuTie%2BhVDCgzWajqDCREzRhi%2Fqlt3D%2FxXNo%2FiwJlpOUr%2Fx1QnkkILxgKlq1dD7KJ767O5ojYKXsO%2BV2Bfu7sSD3djsOxQJ1%2FRbaDm2E96EDkWhhOeOpPndQ6IuSl4NmnJg%2Fcq6f8csW8M3Ys%2BMZPFkdxPC4%2FfRM1XC9o76PjpVNBIO%2ByJEELKZedwIDAQAB; lr=1644769628; _Ruby2_session=Q1drcmlhazYvUFZLd0NydnRXUGpoUzArZDlxYWRCcW9sRUx5VDBydWVWRHdGWDZlMnlESURzbldwbFV1L0drbUlKaWt5MXRtaS9iR0ZYZEpPVHQ1N25qRnR1d3FrY0tzQW1qQm9CdTZ3MSs0d2c3MlpuMjRiQWhCOHI1cGNWekZ4cUdJd0ZFcGtpeng3MFlqZjFDUW9RYmpFMU9DeGdGMVZKR1EwMjVhSE9yVHl4VXFtQm9aYVBtNHF5d0pwMjJ1aVlNMUVRUzdnVFZWZ1AxQkY5Q0p6a2RKay9QL05tOWk4cHZiSERtaGRxeTlxTWZnV3Q0cjdwR3RndUtmeUp3QThhMnJaV2dGZjlPUUtjcGRidDhiajRxK2g0RUZTMWNZUDBaeGNCcUVxSDJ1QnZVRlRkWk9tUExJNWN3TDN5T1BQcmhVVGsycStVTzJRaUwvSkk2TnNVZldTOGU3Tm5wQ3RUMy9nazFqbzdrUWtvYzRwQWRpV3dnTVB3YzhodFV2U0FRR3VKdllMY01NZmdOdGtmOEJ4UT09LS1nTXBrYldhQ0pEeWJ3ak9qQjcrTGV3PT0%3D--1439f36a7f9362aee4b5b666747a2d63d72e81bd'
}

response = requests.request("POST", url, headers=headers, data=payload)
stock_info = response.json()['stock_infos']
stock_data(stock_info)

for info in stock_info:
    key = info[0]
    for i, sub in enumerate(info[1:], 1):
        if sub == key:
            print(info[i:])
            break

Body:
The added block of code is added after the csv file has already been written.

You have other problems as well but that is the most obvious at the moment.

it should be closer to...

...

for info in stock_info:
    key = info[0]
    for i, sub in enumerate(info[1:], 1):
        if sub == key:
            print(info[i:])
            break

stock_data(stock_info)

Also the added block of code doesn't actually make any changes to the data, it only changes what ends up getting printed. Whatever changes you want made to the file need to be made to stock_info.


问:
Cannot list contents of db file in Xamarin
I want to create an easy quiz application that gets values from a .db file.

In my MainPage.xaml.cs I want to list all my questions (with just one answer option for testing,  from a database that is embedded and is implemented correctly for both platforms) in a list form just for now, but I get a white empty stuff without any error msg.

DataModels/Questions.cs

```<code>namespace quiztest.DataModels
{
    public class Questions
    {
        [PrimaryKey]
        public int ID { get; set; }
        public string Field{ get; set; }
        public string Question{ get; set; }
        public string Answer1 { get; set; }
        public string Answer2 { get; set; }
        public string Answer3 { get; set; }
        public string Answer4 { get; set; }
        public string CorrectAnswer { get; set; }
    }
}
</code>```

MainPage.xaml.cs

```<code>using quiztest.DataModels;

...

protected override void OnAppearing()
            {
                base.OnAppearing();
                using (SQLiteConnection conn = new SQLiteConnection(App.FilePath))
                {
                    var questions = conn.Table<Question>().ToList();
                    quizListView.ItemsSource = questions;

                }

            }
</code>```

MainPage.Xaml

```<code>        <StackLayout>
        <Label Text="Contents:"/>
        <Label x:Name="labelrandom"/>
        <ScrollView>
            <ListView x:Name="quizListView">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <TextCell Text="{Binding Question}" Detail="{Binding Answer1}" TextColor="Aquamarine"/>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </ScrollView>
    </StackLayout>
</code>```

I feel that the issue is related to getting the correct columns to show up on the textcell but I am just started learning and I am not an expert.

答:
I suggest you to create the connection in App.cs with code like:
static NoteDatabase database;

```<code>// Create the database connection as a singleton.
public static MyDatabase Database
{
    get
    {
        if (database == null)
        {
            database = new MyDatabase(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "dbfile.db3"));
        }
        return database;
    }
}
</code>```

and set the itemssource in onappearing.

You can refer to this sample to understand better:https://learn.microsoft.com/en-us/samples/xamarin/xamarin-forms-samples/getstarted-notes-database/

Body:
I want to create an easy quiz application that gets values from a .db file.

In my MainPage.xaml.cs I want to list all my questions (with just one answer option for testing,  from a database that is embedded and is implemented correctly for both platforms) in a list form just for now, but I get a white empty stuff without any error msg.

DataModels/Questions.cs

namespace quiztest.DataModels
{
    public class Questions
    {
        [PrimaryKey]
        public int ID { get; set; }
        public string Field{ get; set; }
        public string Question{ get; set; }
        public string Answer1 { get; set; }
        public string Answer2 { get; set; }
        public string Answer3 { get; set; }
        public string Answer4 { get; set; }
        public string CorrectAnswer { get; set; }
    }
}

MainPage.xaml.cs

using quiztest.DataModels;

...

protected override void OnAppearing()
            {
                base.OnAppearing();
                using (SQLiteConnection conn = new SQLiteConnection(App.FilePath))
                {
                    var questions = conn.Table<Question>().ToList();
                    quizListView.ItemsSource = questions;

                }

            }

MainPage.Xaml

        <StackLayout>

        <ScrollView>
            <ListView x:Name="quizListView">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <TextCell Text="{Binding Question}" Detail="{Binding Answer1}" TextColor="Aquamarine"/>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </ScrollView>
    </StackLayout>

I feel that the issue is related to getting the correct columns to show up on the textcell but I am just started learning and I am not an expert.

Body:
I suggest you to create the connection in App.cs with code like:
static NoteDatabase database;

// Create the database connection as a singleton.
public static MyDatabase Database
{
    get
    {
        if (database == null)
        {
            database = new MyDatabase(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "dbfile.db3"));
        }
        return database;
    }
}

and set the itemssource in onappearing.

You can refer to this sample to understand better:https://learn.microsoft.com/en-us/samples/xamarin/xamarin-forms-samples/getstarted-notes-database/


问:
Why do I see duplicate javascript async responses?
I'm trying to understand why I'm seeing the following:

I fire off several async requests inside a for loop and then simply print out the responses. Here's a very simplified version of what I'm doing:

```<code>function getStuff(){
   var singers = ['marley','matthews','johnson','buffett'];
   for(lastname in singers){
       var lastName = singers[lastname];
       log("Making request for "+ singers[lastname]);
       makeAsyncRequest(singers[lastname], function(response){
               //this is the callback when the async request returns
               log("RESPONSE - "+lastName+": "+response);
       });
   }
}
</code>```

If I run the code with syncronously (async: false), I get the following results as expected every time:

```<code>Making request for marley
Making request for matthews
Making request for johnson
Making request for buffett
RESPONSE - marley: bob
RESPONSE - johnson: jack
RESPONSE - matthews: dave
RESPONSE - buffett: jimmy
</code>```

When I run asyncronously, I see results like the following. I understand that the responses might come back out of order. But what I don't understand is when they come back out of order, why do I see duplicate values? For example, I might see:

```<code>Making request for marley
Making request for matthews
Making request for johnson
Making request for buffett
RESPONSE - marley: bob
RESPONSE - johnson: dave
RESPONSE - matthews: dave
RESPONSE - buffett: jimmy
</code>```

Notice 'dave' seems to be returned twice? I would understand if the values 'jack' and 'dave' were switched, like so:

```<code>Making request for marley
Making request for matthews
Making request for johnson
Making request for buffett
RESPONSE - marley: bob
RESPONSE - johnson: dave
RESPONSE - matthews: jack
RESPONSE - buffett: jimmy
</code>```

But I don't understand why the "response" param in the callback appears to be getting set to the same value twice? Am I overlooking something basic here?

Thanks for any help!

答: You've got a race condition. The singer[name] value inside your response handler depends entirely on the state the for() loop is in. Once you're doing async requests, it's entirely possible to get out of sync if any of the requests get delayed (net.burp, slow server, etc...). </p>

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to understand why I'm seeing the following:

I fire off several async requests inside a for loop and then simply print out the responses. Here's a very simplified version of what I'm doing:

function getStuff(){
   var singers = ['marley','matthews','johnson','buffett'];
   for(lastname in singers){
       var lastName = singers[lastname];
       log("Making request for "+ singers[lastname]);
       makeAsyncRequest(singers[lastname], function(response){
               //this is the callback when the async request returns
               log("RESPONSE - "+lastName+": "+response);
       });
   }
}

If I run the code with syncronously (async: false), I get the following results as expected every time:

Making request for marley
Making request for matthews
Making request for johnson
Making request for buffett
RESPONSE - marley: bob
RESPONSE - johnson: jack
RESPONSE - matthews: dave
RESPONSE - buffett: jimmy

When I run asyncronously, I see results like the following. I understand that the responses might come back out of order. But what I don't understand is when they come back out of order, why do I see duplicate values? For example, I might see:

Making request for marley
Making request for matthews
Making request for johnson
Making request for buffett
RESPONSE - marley: bob
RESPONSE - johnson: dave
RESPONSE - matthews: dave
RESPONSE - buffett: jimmy

Notice 'dave' seems to be returned twice? I would understand if the values 'jack' and 'dave' were switched, like so:

Making request for marley
Making request for matthews
Making request for johnson
Making request for buffett
RESPONSE - marley: bob
RESPONSE - johnson: dave
RESPONSE - matthews: jack
RESPONSE - buffett: jimmy

But I don't understand why the "response" param in the callback appears to be getting set to the same value twice? Am I overlooking something basic here?

Thanks for any help!


问:
Arranging vector x as an anti-diagonal matrix
I am trying to input a vector x onto a matrix where values of x are located on the anti-diagonal of the matrix

```<code>x = c(1,2,3,4,5)
ID = function(x){
  n = length(x)
  A = matrix(0, nrow = n, ncol = n)
  for ( i in 1:n){
    A[i, n-i+1] = x[i]
  }
  print(A)  # Why did my code not work when I did not include this
}

Z = ID(x)
</code>```

I was wondering why does my code not work when I do not include the print(A) within the function. When I don't include Print(A), my z turns out to be NULL.

Thank you in advance.

答:
If a return statement is not encountered before the end of the function body, then the function returns the value of the last "top level" expression. When you exclude print(A), the last top level expression is the for call, which returns NULL invisibly, as documented in ?`for`.

I would modify your function in three ways:

Replace matrix(0, n, n) with matrix(vector(typeof(x), n * n), n, n) so that the type of the matrix result matches the type of the vector argument.

Replace the for loop with a vectorized subassignment.

Replace print(A) with A so that print(ID(x)) doesn't print the matrix twice.

Hence my version of your function would look something like this:

antidiag <- function(x) {
    n <- length(x)
    A <- matrix(vector(typeof(x), n * n), n, n)
    if (n > 0L) {
        A[cbind(n:1, 1:n)] <- x
    }
    A
}

antidiag(1:4)
##      [,1] [,2] [,3] [,4]
## [1,]    0    0    0    4
## [2,]    0    0    3    0
## [3,]    0    2    0    0
## [4,]    1    0    0    0

antidiag(1:4 > 0L)
##       [,1]  [,2]  [,3]  [,4]
## [1,] FALSE FALSE FALSE  TRUE
## [2,] FALSE FALSE  TRUE FALSE
## [3,] FALSE  TRUE FALSE FALSE
## [4,]  TRUE FALSE FALSE FALSE

antidiag(letters[1:4])
##      [,1] [,2] [,3] [,4]
## [1,] ""   ""   ""   "d"
## [2,] ""   ""   "c"  ""
## [3,] ""   "b"  ""   ""
## [4,] "a"  ""   ""   ""
```

Body:
I am trying to input a vector x onto a matrix where values of x are located on the anti-diagonal of the matrix

x = c(1,2,3,4,5)
ID = function(x){
  n = length(x)
  A = matrix(0, nrow = n, ncol = n)
  for ( i in 1:n){
    A[i, n-i+1] = x[i]
  }
  print(A)  # Why did my code not work when I did not include this
}

Z = ID(x)

I was wondering why does my code not work when I do not include the print(A) within the function. When I don't include Print(A), my z turns out to be NULL.

Thank you in advance.


问:
Trying to add heartbeat for my console application
A discussion on github mentions that heartbeat is automatically sent when Microsoft.ApplicationInsights.Extensibility.Implementation.Tracing.DiagnosticsTelemetryModule& is added to the applicationinsights.config file. I want to create an alert in case the app hangs or crashes. Where can I track the heart beat on the AI instance? Also, currently its not sending anything . I am using .net framework 4.7.2. Am I configuring it wrong? I am not able to track the heartbeat on application insights instance. Where can I track it? Can someone provide a snippet for config file?</p>

答:
Currently, there is an issue involving this telemetry module AppServicesHeartbeatTelemetryModule .

Can someone provide a snippet for config file?

There is given a temporary workaround for WorkerServices.

Add application insights to worker service using services.AddApplicationInsightsTelemetryWorkerService().

Not only this DiagnosticsTelemetryModule adding to DI and also we need to configure it's heartbeat interval/module using the below snippet:

```<code>services.TryAddSingleton<ITelemetryModule, DiagnosticsTelemetryModule>();
                    services.ConfigureTelemetryModule<DiagnosticsTelemetryModule>((mod,opt) => mod.HeartbeatInterval = TimeSpan.FromSeconds(30));
                    services.AddApplicationInsightsTelemetryWorkerService();
</code>```

The TelemetryConfiguration.Active is not recommended because Worker service is new SDK, its not touching .active or any other static singletons.

Where can I track it?

After Deploying, Look for "HeartbeatState" in customMetrics.

Note:

Disabling DiagnosticsTelemetryModule will cause the following settings to be ignored: EnableHeartbeat, EnableAzureInstanceMetadataTelemetryModule, EnableAppServicesHeartbeatTelemetryModule.

Enable Azure Monitor from the Portal.

References:

Configuring or removing default TelemetryModules (HeartBeat Telemetry Issue)

Enabling Hearbeat in App Services for .NET and .NET Core

Body:
Currently, there is an issue involving this telemetry module AppServicesHeartbeatTelemetryModule .

Can someone provide a snippet for config file?

There is given a temporary workaround for WorkerServices.

Add application insights to worker service using services.AddApplicationInsightsTelemetryWorkerService().

Not only this DiagnosticsTelemetryModule adding to DI and also we need to configure it's heartbeat interval/module using the below snippet:

services.TryAddSingleton<ITelemetryModule, DiagnosticsTelemetryModule>();
                    services.ConfigureTelemetryModule<DiagnosticsTelemetryModule>((mod,opt) => mod.HeartbeatInterval = TimeSpan.FromSeconds(30));
                    services.AddApplicationInsightsTelemetryWorkerService();

The TelemetryConfiguration.Active is not recommended because Worker service is new SDK, its not touching .active or any other static singletons.

Where can I track it?

After Deploying, Look for "HeartbeatState" in customMetrics.

Note:

Disabling DiagnosticsTelemetryModule will cause the following settings to be ignored: EnableHeartbeat, EnableAzureInstanceMetadataTelemetryModule, EnableAppServicesHeartbeatTelemetryModule.

Enable Azure Monitor from the Portal.

References:

Configuring or removing default TelemetryModules (HeartBeat Telemetry Issue)

Enabling Hearbeat in App Services for .NET and .NET Core


问:
Multi-threading in image processing - video python opencv
Im working on object detection from a live stream video using opencv python. The program I have is running on a single thread because of that the resulting video shown on the screen doesnt even look like a video, since there is a delay in detection process. So, Im trying to re-implement it using multiple threads. I am using one thread for reading frames and another for showing the detection result and about 5 threads to run the detection algorithm on multiple frames at once. I have written the following code but the result is not different from the single thread program. Im new to python. So, any help is appreciated.</p>
```<code>import threading, time
import cv2
import queue

def detect_object():
    while True:
        print("get")
        frame = input_buffer.get()
        if frame is not None:
            time.sleep(1)
            detection_buffer.put(frame)
        else:
            break
    return

def show():
    while True:
        print("show")
        frame = detection_buffer.get()
        if frame is not None:
            cv2.imshow("Video", frame)
        else:
            break
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    return

if __name__ == "__main__":

    input_buffer = queue.Queue()
    detection_buffer = queue.Queue()

    cap = cv2.VideoCapture(0)

    for i in range(5):
        t = threading.Thread(target=detect_object)
        t.start()

    t1 = threading.Thread(target=show)
    t1.start()

    while True:
        ret, frame = cap.read()
        if ret:
            input_buffer.put(frame)
            time.sleep(0.025)
        else:
            break

    print("program ended")

</code>```

答:
for me what I've done is building 2 threads for 2 funtions and use one queue:

to get the frame and process it

to dispaly

the cap variable was inside my process function.

```<code>def process:
     cap = cv2.VideoCapture(filename)
     ret, frame = cap.read()

      while ret:
          ret, frame = cap.read()
#detection part in my case I use tensorflow then
     # end of detection part
          q.put(result_of_detection)

def Display():
  while True:
    if q.empty() != True:
        frame = q.get()
        cv2.imshow("frame1", frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

if __name__ == '__main__':
#  start threads
p1 = threading.Thread(target=process)
p2 = threading.Thread(target=Display)
p1.start()
p2.start()
</code>```

it works just fine for me

hope I helped :D

Also, I think this page could may help:
https://pyimagesearch.com/2015/12/21/increasing-webcam-fps-with-python-and-opencv/

Body:
Im working on object detection from a live stream video using opencv python. The program I have is running on a single thread because of that the resulting video shown on the screen doesnt even look like a video, since there is a delay in detection process. So, Im trying to re-implement it using multiple threads. I am using one thread for reading frames and another for showing the detection result and about 5 threads to run the detection algorithm on multiple frames at once. I have written the following code but the result is not different from the single thread program. Im new to python. So, any help is appreciated.

import threading, time
import cv2
import queue

def detect_object():
    while True:
        print("get")
        frame = input_buffer.get()
        if frame is not None:
            time.sleep(1)
            detection_buffer.put(frame)
        else:
            break
    return

def show():
    while True:
        print("show")
        frame = detection_buffer.get()
        if frame is not None:
            cv2.imshow("Video", frame)
        else:
            break
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    return

if __name__ == "__main__":

    input_buffer = queue.Queue()
    detection_buffer = queue.Queue()

    cap = cv2.VideoCapture(0)

    for i in range(5):
        t = threading.Thread(target=detect_object)
        t.start()

    t1 = threading.Thread(target=show)
    t1.start()

    while True:
        ret, frame = cap.read()
        if ret:
            input_buffer.put(frame)
            time.sleep(0.025)
        else:
            break

    print("program ended")

Body:
for me what I've done is building 2 threads for 2 funtions and use one queue:

to get the frame and process it

to dispaly

the cap variable was inside my process function.

def process:
     cap = cv2.VideoCapture(filename)
     ret, frame = cap.read()

      while ret:
          ret, frame = cap.read()
#detection part in my case I use tensorflow then
     # end of detection part
          q.put(result_of_detection)

def Display():
  while True:
    if q.empty() != True:
        frame = q.get()
        cv2.imshow("frame1", frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

if __name__ == '__main__':
#  start threads
p1 = threading.Thread(target=process)
p2 = threading.Thread(target=Display)
p1.start()
p2.start()

it works just fine for me

hope I helped :D

Also, I think this page could may help:
https://pyimagesearch.com/2015/12/21/increasing-webcam-fps-with-python-and-opencv/


问:
Generate and display random message – JavaScript
For the website that I am creating, I am looking to have a random welcome message be generated using a JavaScript array and be displayed on the screen using the innerHTML property. So far, I've created the array with the messages, but I'm stuck on how to select a random one, then insert it using the innerHTML property. Any help would be awesome.</p>

答:
From MDN:</p>
```<code>const getRandomArbitrary = (min, max) => {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
};
</code>```

Body:
From MDN:

const getRandomArbitrary = (min, max) => {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
};


Title: Arranging vector x as an anti-diagonal matrix

Body:
I would do this without a loop -

x = c(1,2,3,4,5)

ID = function(x){
  n = length(x)
  A = matrix(0, nrow = n, ncol = n)
  diag(A[nrow(A):1, ]) <- x
  A
}
ID(x)

#     [,1] [,2] [,3] [,4] [,5]
#[1,]    0    0    0    0    5
#[2,]    0    0    0    4    0
#[3,]    0    0    3    0    0
#[4,]    0    2    0    0    0
#[5,]    1    0    0    0    0


答:
try to keep a copy of the lastname in the for loop :</p>

```<code>function getStuff()
{
   var singers = ['marley','matthews','johnson','buffett'];
   for(lastname in singers)
   {
       var currentName = lastname;
       log("Making request for "+ singers[currentName]);
       makeAsyncRequest(singers[lastname], function(response)
       {

           //this is the callback when the async request returns
           log("RESPONSE - "+singers[currentName ]+": "+response);
       });
   }
}
</code>```

Title: Why do I see duplicate javascript async responses?

Body:
try to keep a copy of the lastname in the for loop :

function getStuff()
{
   var singers = ['marley','matthews','johnson','buffett'];
   for(lastname in singers)
   {
       var currentName = lastname;
       log("Making request for "+ singers[currentName]);
       makeAsyncRequest(singers[lastname], function(response)
       {

           //this is the callback when the async request returns
           log("RESPONSE - "+singers[currentName ]+": "+response);
       });
   }
}


问:
Oracle SQL statement returns no rows when executed from C# application
Following SQL statement returns data when executed in Oracle SQL Developer:

```<code>SELECT TC_GUID FROM TBLBUF WHERE TC_DEST = 'aaaaaaa' AND TC_STATE <= 20
</code>```

but when it is executed in a following C# code, reader returns no rows.

```<code>using Oracle.ManagedDataAccess.Client;
using System;
using System.Data;
using System.Data.Common;
using System.Threading;
using System.Threading.Tasks;

namespace OracleQuery
{
    public class Program
    {
        public static DbDataReader QueryReader()
        {
            OracleConnection connection = new OracleConnection(".........");
            connection.Open();
            using (OracleCommand command = connection.CreateCommand())
            {
                command.InitialLOBFetchSize = -1;
                command.InitialLONGFetchSize = -1;
                ((IDbCommand)command).Transaction = null;
                command.CommandText = "SELECT TC_GUID FROM TBLBUF WHERE TC_DEST = 'aaaaaaa' AND TC_STATE <= 20";
                command.CommandType = CommandType.Text;
                return command.ExecuteReader(CommandBehavior.Default | CommandBehavior.CloseConnection);
            }
        }

        public static void Main(string[] args)
        {
            DbDataReader reader = QueryReader();
            while (reader.Read())
            {
                string s = (string)reader["TC_GUID"];
                Console.WriteLine(s);
            }
        }
    }
}
</code>```

When I leave only one part of WHERE clause, either TC_DEST = 'aaaaaaa' or TC_STATE <= 20, it returns rows.

What could be a reason for such behaviour?

答:
What could be a reason for such behaviour?

Rows which have been INSERTed but not COMMITted are only visible inside the session in which they were created. Therefore, if you have created some new rows but have not issued a COMMIT command in the SQL Developer session, you will not be able to see that uncommitted data from any other session (even if you connect as the same user, as it will create a different session).

If this is the the case, the solution would be to COMMIT the data in the SQL Developer session and it would then be visible to other sessions.

Body:
Following SQL statement returns data when executed in Oracle SQL Developer:

SELECT TC_GUID FROM TBLBUF WHERE TC_DEST = 'aaaaaaa' AND TC_STATE <= 20

but when it is executed in a following C# code, reader returns no rows.

using Oracle.ManagedDataAccess.Client;
using System;
using System.Data;
using System.Data.Common;
using System.Threading;
using System.Threading.Tasks;

namespace OracleQuery
{
    public class Program
    {
        public static DbDataReader QueryReader()
        {
            OracleConnection connection = new OracleConnection(".........");
            connection.Open();
            using (OracleCommand command = connection.CreateCommand())
            {
                command.InitialLOBFetchSize = -1;
                command.InitialLONGFetchSize = -1;
                ((IDbCommand)command).Transaction = null;
                command.CommandText = "SELECT TC_GUID FROM TBLBUF WHERE TC_DEST = 'aaaaaaa' AND TC_STATE <= 20";
                command.CommandType = CommandType.Text;
                return command.ExecuteReader(CommandBehavior.Default | CommandBehavior.CloseConnection);
            }
        }

        public static void Main(string[] args)
        {
            DbDataReader reader = QueryReader();
            while (reader.Read())
            {
                string s = (string)reader["TC_GUID"];
                Console.WriteLine(s);
            }
        }
    }
}

When I leave only one part of WHERE clause, either TC_DEST = 'aaaaaaa' or TC_STATE <= 20, it returns rows.

What could be a reason for such behaviour?


问:
Javafx 12 with vscode-java
I followed the process described in Javafx 11 with vscode-java, to set vscode with javafx. It worked for once and i was able to run that sample code OpenJFX sample code. But after that it is giving me error
 Error occured during initialization of VM
java.nio.charset.IllegalCharsetNameException: UTF-8 -cp C:\Users\... ;.. ;
In the end is all jar files. How do i make it work?

答: The repo has dedicated samples for VS Code now: https://github.com/openjfx/samples/tree/master/IDE/VSCode. Maybe you can take a look at it.</p>

Title: Javafx 12 with vscode-java


问:
Expecting string, bytes, or os.PathLike or integer, not StringVar
I'm working on a project that monitors two selected folders and automatically moves files created or edited within the last twenty-four hours from Folder_A to Folder_B. It also will check the two folders manually when the user clicks the scan button. So far it will select the two folders, but when I click the scan button I get this error. How would I go about fixing the error?

My code is below the error. Please be understanding that I am still really new to python, so there might be quite a few really stupid mistakes in here.

```<code>import tkinter as tk
from tkinter import *
from tkinter import filedialog
import os,time
import datetime
import shutil
import datetime as dt

def browse_button():
  # Allow user to select a directory and store it in global var
  # called origin_path
  global origin_path
  filename = filedialog.askdirectory()
  origin_path.set(filename)
  print(filename)

def browse_button2():
  # Allow user to select a directory and store it in global var
  # called receiving_path
  global receiving_path
  filename = filedialog.askdirectory()
  receiving_path.set(filename)
  print(filename)

def submitFunction() :
  for root, dirs,files in os.walk(origin_path.get()):
      for fname in files:
          path = os.path.join(fname, root)
          st = os.stat(path)
          mtime = dt.datetime.fromtimestamp(st.st_mtime)
          shutil.move(path, receiving_path)
  print('Submit button is clicked.')

root = Tk()
origin_path = StringVar()
receiving_path = StringVar()

#First Browse Button Label
lbl1 = Label(master=root,textvariable=origin_path)
lbl1.grid(row=0, column=1)
#Second Browse Button Label
lbl1_2 = Label(master=root,textvariable=receiving_path)
lbl1_2.grid(row=1, column=1)

lbl1_3 = Label(master=root)
lbl1_3.grid(row=2, column=1)

button = Button(text="Browse", command=browse_button)
button.grid(row=0, column=3)

button2 = Button(text="Browse", command=browse_button2)
button2.grid(row=1, column=3)

scan_btn=Button(text="Scan", command = lambda:submitFunction())
scan_btn.grid(row=2, column=7)

mainloop()

now = dt.datetime.now()
ago = now-dt.timedelta(hours=24)
strftime = "%H:%M %m/%d/%Y"
created = 'origin_path'
dest = 'receiving_path'
file_path = 'file:///'+os.getcwd()+'/' + ''

print("Last modified: %s" % time.ctime(os.path.getmtime(file_path)))
print("Created: %s" % time.ctime(os.path.getctime(file_path)))

for root, dirs,files in os.walk(origin_path.get()):
  for fname in files:
      path = os.path.join(root, fname)
      st = os.stat(path)
      mtime = dt.datetime.fromtimestamp(st.st_mtime)
      if mtime > ago:
          print("True:  ", fname, " at ", mtime.strftime("%H:%M %m/%d/%Y"))
          shutil.move(path, dest)

def find_info(): #this first func. works fine.for root, dirs, files in os.walk(created):
  for root, dirs, files in os,walk(origin_path.get()):
      for fname in files:
          path = os.path.join(root, fname)
          st = os.stat(path)
          mtime = dt.datetime.fromtimestamp(st.st_mtime)
  if mtime > ago:
      print(True)
  else:
      print(False)

print (find_info())
print (move())

print (os.listdir(dest))
print (os.listdir(created))

Here's the error:

C:/Users/quirk/PycharmProjects/Trial_2
C:/Users/quirk/PycharmProjects/Trial_2/.idea
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\quirk\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 1921, in __call__
  return self.func(*args)
File "C:\Users\quirk\AppData\Local\Programs\Python\Python310\Projects\File_transfer.py", line 63, in <lambda>
  scan_btn=Button(text="Scan", command = lambda:submitFunction())
File "C:\Users\quirk\AppData\Local\Programs\Python\Python310\Projects\File_transfer.py", line 39, in submitFunction
  shutil.move(path, receiving_path)
File "C:\Users\quirk\AppData\Local\Programs\Python\Python310\lib\shutil.py", line 791, in move
  if os.path.isdir(dst):
File "C:\Users\quirk\AppData\Local\Programs\Python\Python310\lib\genericpath.py", line 42, in isdir
  st = os.stat(s)
TypeError: stat: path should be string, bytes, os.PathLike or integer, not StringVar

</code>```

答:
As the message says, receiving_path is a StringVar object, not a string.  To fetch the string value, you need to use .get():

```<code>          shutil.move(path, receiving_path.get())
</code>```

Body:
I'm working on a project that monitors two selected folders and automatically moves files created or edited within the last twenty-four hours from Folder_A to Folder_B. It also will check the two folders manually when the user clicks the scan button. So far it will select the two folders, but when I click the scan button I get this error. How would I go about fixing the error?

My code is below the error. Please be understanding that I am still really new to python, so there might be quite a few really stupid mistakes in here.

import tkinter as tk
from tkinter import *
from tkinter import filedialog
import os,time
import datetime
import shutil
import datetime as dt

def browse_button():
  # Allow user to select a directory and store it in global var
  # called origin_path
  global origin_path
  filename = filedialog.askdirectory()
  origin_path.set(filename)
  print(filename)

def browse_button2():
  # Allow user to select a directory and store it in global var
  # called receiving_path
  global receiving_path
  filename = filedialog.askdirectory()
  receiving_path.set(filename)
  print(filename)

def submitFunction() :
  for root, dirs,files in os.walk(origin_path.get()):
      for fname in files:
          path = os.path.join(fname, root)
          st = os.stat(path)
          mtime = dt.datetime.fromtimestamp(st.st_mtime)
          shutil.move(path, receiving_path)
  print('Submit button is clicked.')

root = Tk()
origin_path = StringVar()
receiving_path = StringVar()

#First Browse Button Label
lbl1 = Label(master=root,textvariable=origin_path)
lbl1.grid(row=0, column=1)
#Second Browse Button Label
lbl1_2 = Label(master=root,textvariable=receiving_path)
lbl1_2.grid(row=1, column=1)

lbl1_3 = Label(master=root)
lbl1_3.grid(row=2, column=1)

button = Button(text="Browse", command=browse_button)
button.grid(row=0, column=3)

button2 = Button(text="Browse", command=browse_button2)
button2.grid(row=1, column=3)

scan_btn=Button(text="Scan", command = lambda:submitFunction())
scan_btn.grid(row=2, column=7)

mainloop()

now = dt.datetime.now()
ago = now-dt.timedelta(hours=24)
strftime = "%H:%M %m/%d/%Y"
created = 'origin_path'
dest = 'receiving_path'
file_path = 'file:///'+os.getcwd()+'/' + ''

print("Last modified: %s" % time.ctime(os.path.getmtime(file_path)))
print("Created: %s" % time.ctime(os.path.getctime(file_path)))

for root, dirs,files in os.walk(origin_path.get()):
  for fname in files:
      path = os.path.join(root, fname)
      st = os.stat(path)
      mtime = dt.datetime.fromtimestamp(st.st_mtime)
      if mtime > ago:
          print("True:  ", fname, " at ", mtime.strftime("%H:%M %m/%d/%Y"))
          shutil.move(path, dest)

def find_info(): #this first func. works fine.for root, dirs, files in os.walk(created):
  for root, dirs, files in os,walk(origin_path.get()):
      for fname in files:
          path = os.path.join(root, fname)
          st = os.stat(path)
          mtime = dt.datetime.fromtimestamp(st.st_mtime)
  if mtime > ago:
      print(True)
  else:
      print(False)

print (find_info())
print (move())

print (os.listdir(dest))
print (os.listdir(created))

Here's the error:

C:/Users/quirk/PycharmProjects/Trial_2
C:/Users/quirk/PycharmProjects/Trial_2/.idea
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\quirk\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 1921, in __call__
  return self.func(*args)
File "C:\Users\quirk\AppData\Local\Programs\Python\Python310\Projects\File_transfer.py", line 63, in <lambda>
  scan_btn=Button(text="Scan", command = lambda:submitFunction())
File "C:\Users\quirk\AppData\Local\Programs\Python\Python310\Projects\File_transfer.py", line 39, in submitFunction
  shutil.move(path, receiving_path)
File "C:\Users\quirk\AppData\Local\Programs\Python\Python310\lib\shutil.py", line 791, in move
  if os.path.isdir(dst):
File "C:\Users\quirk\AppData\Local\Programs\Python\Python310\lib\genericpath.py", line 42, in isdir
  st = os.stat(s)
TypeError: stat: path should be string, bytes, os.PathLike or integer, not StringVar

Body:
As the message says, receiving_path is a StringVar object, not a string.  To fetch the string value, you need to use .get():

          shutil.move(path, receiving_path.get())


问:
What is Sqlite used for?
I don't know how authoritative this is but I found this:

http://www.sqlite.org/cvstrac/wiki?p=PerformanceConsiderations

and it doesn't seem good to have a lot of connections to sqlite.  This seems to be bad for the web and most applications that have more than a few users.  I'm having a hard time thinking of what sqlite would be used for when you don't need that many connections.  Every program I can think of needs users, lots of them sometimes, so what would I use a database for that doesn't allow that many connections?  I thought about prototypes but why would I use that when I can just connect to a larger database?  Embedded apps maybe?

Thank you.

EDIT:  Thanks everyone.  I look at the page recommended below but an confused about something:

Under appropriate uses for sqlite it has:

Situations Where SQLite Works Well

•Websites

SQLite usually will work great as the database engine for low to medium traffic websites (which is to say, 99.9% of all websites). The amount of web traffic that SQLite can handle depends, of course, on how heavily the website uses its database. Generally speaking, any site that gets fewer than 100K hits/day should work fine with SQLite. The 100K hits/day figure is a conservative estimate, not a hard upper bound. SQLite has been demonstrated to work with 10 times that amount of traffic.

Situations Where Another RDBMS May Work Better

•Client/Server Applications

If you have many client programs accessing a common database over a network, you should consider using a client/server database engine instead of SQLite. SQLite will work over a network filesystem, but because of the latency associated with most network filesystems, performance will not be great. Also, the file locking logic of many network filesystems implementation contains bugs (on both Unix and Windows). If file locking does not work like it should, it might be possible for two or more client programs to modify the same part of the same database at the same time, resulting in database corruption. Because this problem results from bugs in the underlying filesystem implementation, there is nothing SQLite can do to prevent it.

A good rule of thumb is that you should avoid using SQLite in situations where the same database will be accessed simultaneously from many computers over a network filesystem.

The Question:

I'm going to show my ignorance here but what is the difference between these two?

答: What the above two answers say. Expanding slightly on Chad Birch's answer, its teh calls to the SQLite db, and a rather poor implementation of sync() that causes FF3 to be so slow in linux.</p>

OwnerDisplayName: johnny

ContentLicense: CC BY-SA 2.5

Title: What is Sqlite used for?

LastEditorDisplayName: johnny

OwnerDisplayName: tpdi


问:
How to add screen sharing to my app
Are there any off the shelf components for adding a screen sharing feature to my app?

I've built real time text chat for a group chat room - now I'd like to have a button where a user can share their screen with the other members of the chat.

Basically, I'm looking for a way to add this feature as easily as possible, hopefully using a service provider to help:

Client:
The client can be Flash or Java applet based (whatever works)
- I'm currently investigating this: http://code.google.com/p/red5-screenshare/
but would love any others options you may know of

Server:
Are there any hosted live Red5/Adode FMS providers out there, that I could point a client to?

I've also seen Adobe LiveCycle Collab - but I have no Flash/Flex experience.  Are there any providers that I can point a client to and they'll take care of the streaming bit.

For example, Opentok works well for video sharing, but they only support sharing a webcam and not a user's desktop.

Any thoughts on this would be most appreciated.

Thanks.

答: I've recently started using Bloomfire and they have the most seemless screencapture experience. I suggest you investigate how they do it, maybe it's even licensable. </p>

Title: How to add screen sharing to my app


答:
We can set_index to address any columns which do not have a set pattern of prefix_suffix. We can then use str.rsplit with expand=True and n=1 to create MultiIndex columns. rsplit with n=1 ensures we only split one time on the rightmost underscore. Then stack to convert the new column index level to a row index level and transpose to get to the correct general shape:

```<code>df = df.set_index('Year')
df.columns = df.columns.str.rsplit('_', expand=True, n=1)
df = df.stack(level=1).transpose()
</code>```
```<code>Year   2017          2018          2019
          a      b      a      b      a      b
col1    1.4  123.0    1.5  456.0    0.6  789.0
col2  555.0   55.5  444.0   56.5  333.0   57.5
col3    5.0   80.0    6.0   90.0    8.0  100.0
</code>```

We can further clean the data with a swaplevel and sort_index to get the headers to match the expected order. Also rename_axis to remove any unneeded column names:

```<code>df = df.set_index('Year')
df.columns = df.columns.str.rsplit('_', expand=True, n=1)
df = (
    df.stack(level=1)
        .transpose()
        .sort_index(axis=1, level=1)
        .swaplevel(axis=1)
        .rename_axis(columns=[None, None])
)
</code>```
```<code>          a                    b
       2017   2018   2019   2017   2018   2019
col1    1.4    1.5    0.6  123.0  456.0  789.0
col2  555.0  444.0  333.0   55.5   56.5   57.5
col3    5.0    6.0    8.0   80.0   90.0  100.0
</code>```

Setup used:

```<code>import pandas as pd

df = pd.DataFrame({
    'Year': [2017, 2018, 2019], 'col1_a': [1.4, 1.5, 0.6],
    'col2_a': [555, 444, 333], 'col3_a': [5, 6, 8], 'col1_b': [123, 456, 789],
    'col2_b': [55.5, 56.5, 57.5], 'col3_b': [80, 90, 100]
})
</code>```

Title: pandas convert columns with same name but different suffixes to indices and index to columns

Body:
I have a problem in which I am trying to change the shape of data, but trying to have column names on row level without having suffixes attached to them.

e.g.

My original df looks like this

+------+--------+--------+--------+--------+--------+--------+
| Year | col1_a | col2_a | col3_a | col1_b | col2_b | col3_b |
+------+--------+--------+--------+--------+--------+--------+
| 2017 |    1.4 |    555 |      5 |    123 |   55.5 |     80 |
| 2018 |    1.5 |    444 |      6 |    456 |   56.5 |     90 |
| 2019 |    0.6 |    333 |      8 |    789 |   57.5 |    100 |
+------+--------+--------+--------+--------+--------+--------+

and I am trying to reshape it as

+------+------+------+------+------+------+------+
|      |  a   |  a   |   a  |  b   |   b  |   b  |
+------+------+------+------+------+------+------+
|        2017 | 2018 | 2019 | 2017 | 2018 | 2019 |
| col1 |  1.4 |  1.5 |  0.6 |  123 |  456 |  789 |
| col2 |  555 |  444 |  333 | 55.5 | 56.5 | 57.5 |
| col3 |    5 |    6 |    8 |   80 |   90 |  100 |
+------+------+------+------+------+------+------+

I can use pivot_table but the thing is I am not able to get unique column names at index level. Any idea which method can be used to reshape this?

Body:
We can set_index to address any columns which do not have a set pattern of prefix_suffix. We can then use str.rsplit with expand=True and n=1 to create MultiIndex columns. rsplit with n=1 ensures we only split one time on the rightmost underscore. Then stack to convert the new column index level to a row index level and transpose to get to the correct general shape:

df = df.set_index('Year')
df.columns = df.columns.str.rsplit('_', expand=True, n=1)
df = df.stack(level=1).transpose()

Year   2017          2018          2019
          a      b      a      b      a      b
col1    1.4  123.0    1.5  456.0    0.6  789.0
col2  555.0   55.5  444.0   56.5  333.0   57.5
col3    5.0   80.0    6.0   90.0    8.0  100.0

We can further clean the data with a swaplevel and sort_index to get the headers to match the expected order. Also rename_axis to remove any unneeded column names:

df = df.set_index('Year')
df.columns = df.columns.str.rsplit('_', expand=True, n=1)
df = (
    df.stack(level=1)
        .transpose()
        .sort_index(axis=1, level=1)
        .swaplevel(axis=1)
        .rename_axis(columns=[None, None])
)

          a                    b
       2017   2018   2019   2017   2018   2019
col1    1.4    1.5    0.6  123.0  456.0  789.0
col2  555.0  444.0  333.0   55.5   56.5   57.5
col3    5.0    6.0    8.0   80.0   90.0  100.0

Setup used:

import pandas as pd

df = pd.DataFrame({
    'Year': [2017, 2018, 2019], 'col1_a': [1.4, 1.5, 0.6],
    'col2_a': [555, 444, 333], 'col3_a': [5, 6, 8], 'col1_b': [123, 456, 789],
    'col2_b': [55.5, 56.5, 57.5], 'col3_b': [80, 90, 100]
})


问:
Is there a way that Azure Data Factory Pipeline step to execute automatic retry if the step failed?
By the step, I mean each copy, each filter, each columns, or each sink. I have a hard time figuring it out because I only know how to re-run the whole pipeline but not the individual steps inside pipeline. The re-run of each step is to determine th intermittent errors.</p>

答:
You can use Activity Policies available only for execution activities (data movement and data transformation activities)

This property includes a timeout and retry behavior.

For more information, see official MS doc on Activity policy


问:
How to make blinking text in python with termcolor?
Whenever I try to use termcolor to make blinking text, using the following code:

```<code>from termcolor import colored, cprint
cprint('\nJames Everleigh', 'red', attrs=['blink'])
</code>```

It prints the text red, but it doesn't blink. Is there some function that I need to use to turn the blinking on/something like that?

I use replit.com which is using python 3.8.2. I've also tried Visual Studio but it still doesn't blink.

答:
You can use the curses library to do some cool stuff inside a terminal (only for Linux).

Here is the documentation : https://docs.python.org/3.7/howto/curses.html

Body:
Whenever I try to use termcolor to make blinking text, using the following code:

from termcolor import colored, cprint
cprint('\nJames Everleigh', 'red', attrs=['blink'])

It prints the text red, but it doesn't blink. Is there some function that I need to use to turn the blinking on/something like that?

I use replit.com which is using python 3.8.2. I've also tried Visual Studio but it still doesn't blink.


问:
Flutter For Web Cookie/Token Sessions and Authentcation
I am working on a full stack app using NodeJS and Flutter For Web, at the moment i don't understand how to make safe cookie/token sessions.

The answer i need is how to make an authentication system with Flutter For Web like other Social Networks or Stackoverflow itself.

答:
You can encrypt it as you want then use getStorage to store it & it supports all platforms, example:

```<code>GetStorage box = GetStorage();
</code>```

write it:

```<code>box.write('jwt', 'value');
</code>```

read it:

```<code>if (box.hasData('jwt')) {
  box.read('jwt');
}
</code>```

Body:
You can encrypt it as you want then use getStorage to store it & it supports all platforms, example:

GetStorage box = GetStorage();

write it:

box.write('jwt', 'value');

read it:

if (box.hasData('jwt')) {
  box.read('jwt');
}


问:
Do I need a menu item with alias for all sef urls in Joomla?
I'm new to Joomla so my comprehension of how it all works is a bit incomplete. I'd just like to know whether or not I need to add new menu items with an alias for all short urls used in the application (e.g. http://mysite/shorturl). What bothers me is that:

Why would I need to make a menu item for an alias if I don't use the item in a menu (why such a relationship between urls and menus).

If I had 50 articles using short urls (aliases), would I have to make a menu item for every single short url? There's some dependencies I don't like about that.

I thought it made sense to set the alias on an article level.

I read something about having to purchase an extension sh404-something for this - really?

If someone could help me out it would be much appriciated.

Thanks and regards,
Kjetil

答: Each article has its own unique url, even it's own unique SEF url. The only reason for have the menu item there is because there has to be a way to locally group and link things. Try this, create a category called "Things Starting with A" then create 3 articles and put them in that category. Create a menu item with a blog layout assigned to the category "Things Starting with A". When you click the menu item you should see your 3 articles, when you click their title you should see them on a single page with their own URL.</p>


问:
passing key and value from a list of values to a function in a loop
I have a dictionary:

```<code>my_dict = {
           "port1":["red","chevy"],
           "port2":["orange","ford"],
           "port3":["black","thunderbird"]}
</code>```

I want to iterate through it and call a function for each combination

```<code>my_func(port, color, model):
     do cool stuff

for key, values in my_dict.items():
    for value in values:
      # Here I want to call the function and pass "port1","red","chevy" for the first iteration then "port2","orange","ford" for the 2nd iteration etc..
        my_func("port1", "red", "chevy")
</code>```

Can't figure out how to do this.

答:
If you know which element in the list you want to pass as each argument to the function then you could do this:</p>
```<code>my_func(port, color, model):
 do cool stuff

for key, values in my_dict.items():
    my_func(key, values[0], values[1])
</code>```

Body:
I have a dictionary:

my_dict = {
           "port1":["red","chevy"],
           "port2":["orange","ford"],
           "port3":["black","thunderbird"]}

I want to iterate through it and call a function for each combination

my_func(port, color, model):
     do cool stuff

for key, values in my_dict.items():
    for value in values:
      # Here I want to call the function and pass "port1","red","chevy" for the first iteration then "port2","orange","ford" for the 2nd iteration etc..
        my_func("port1", "red", "chevy")

Can't figure out how to do this.

Body:
If you know which element in the list you want to pass as each argument to the function then you could do this:

my_func(port, color, model):
 do cool stuff

for key, values in my_dict.items():
    my_func(key, values[0], values[1])


问:
React Component doesn't rerender when the state is changed
I am working on a small React project to get to learn more about it.

The project can make and view groups and in the groups you can store images, videos...

So the problem is when I open one of those groups and while I'm in it if I try to change to another group the component doesn't rerender and I have the same information.

Here's some of the code:

App:

```<code>function App() {
  const [chosenGroup, setChosenGroup] = useState({});

return (
    <Router>
      <Header setChosenGroup={setChosenGroup}/>
      <Routes>
        <Route
          path="/Group/:group_name"
          element={<Group group={chosenGroup} />}
        />
      </Routes>
    </Router>
  );

}
</code>```

Header (Where I choose the group):

```<code>function Header(props) {
  const setChosenGroup = props.setChosenGroup;

  return (
    <>
      <Top>
        <Image src={SiteLogo} />
        <GroupsBtn>
          MY GROUPS
        </GroupsBtn>
        <AllGroupsCont>
          <AllGroups>
            {myGroupDB.map((group, index) => {
              return (
                <StyledLink to={`/Group/${group.group_name}`} key={index}>
                  <Group onClick={() => {
                      setChosenGroup(group);
                    }}>
                    {group.group_name}
                  </Group>
                </StyledLink>
              );
            })}
          </AllGroups>
        </AllGroupsCont>
      </Top>
    </>
  )
}
</code>```

Group:

```<code>function Group(props) {
  const param = useParams();

  return (
    <Main>
      <Top>
        <GroupTitle defaultValue={param.group_name} />
        <SaveButton className="saveButtonGroup" src={SaveIcon} />
        <DateCreated>Date created: {creationDate}</DateCreated>
      </Top>
      <Center>
        <GridContainer>
          {group.photos.map((photo) => {
            <Image src={photo.url} />;
          })}
        </GridContainer>
      </Center>
      <Bottom>
        <GoBackBtn onClick={() => navigate(-1)}>GO BACK</GoBackBtn>
        <SaveBtn>SAVE</SaveBtn>
      </Bottom>
    </Main>
  )
}
</code>```

I checked the components in the browser and the state does indeed update so the problem is something else.

答:
This might solve it

  <Group onClick={() => {
                      setChosenGroup({...group});
 }}>```

Body:
I am working on a small React project to get to learn more about it.

The project can make and view groups and in the groups you can store images, videos...

So the problem is when I open one of those groups and while I'm in it if I try to change to another group the component doesn't rerender and I have the same information.

Here's some of the code:

App:

function App() {
  const [chosenGroup, setChosenGroup] = useState({});

return (
    <Router>

      <Routes>
        <Route
          path="/Group/:group_name"
          element={<Group group={chosenGroup} />}
        />
      </Routes>
    </Router>
  );

}

Header (Where I choose the group):

function Header(props) {
  const setChosenGroup = props.setChosenGroup;

  return (
    <>
      <Top>
        <Image src={SiteLogo} />
        <GroupsBtn>
          MY GROUPS
        </GroupsBtn>
        <AllGroupsCont>
          <AllGroups>
            {myGroupDB.map((group, index) => {
              return (

              );
            })}
          </AllGroups>
        </AllGroupsCont>
      </Top>
    </>
  )
}

Group:

function Group(props) {
  const param = useParams();

  return (

      <Top>
        <GroupTitle defaultValue={param.group_name} />
        <SaveButton className="saveButtonGroup" src={SaveIcon} />
        <DateCreated>Date created: {creationDate}</DateCreated>
      </Top>

        <GridContainer>
          {group.photos.map((photo) => {
            <Image src={photo.url} />;
          })}
        </GridContainer>

      <Bottom>
        <GoBackBtn onClick={() => navigate(-1)}>GO BACK</GoBackBtn>
        <SaveBtn>SAVE</SaveBtn>
      </Bottom>

  )
}

I checked the components in the browser and the state does indeed update so the problem is something else.


问:
what is wrong with python my python code in while loop?
I don't know what is the error of my code can anyone help  me to fix this code.</p>
```<code>age = ""
while int(len(age)) == 0:
    age = int(input("Enter your age: "))
print("Your age is " + age)
</code>```

答:
You cast age to be an int inside of your while loop, while using the len(age) as the comparison.

int does not have a length.

You want to wait to cast age until you are outside of the loop, or in this situation, don't cast it at all.

```<code>age = ""
while len(age) == 0:
    age = input("Enter your age: ")
print("Your age is " + age)
</code>```

Body:
I don't know what is the error of my code can anyone help  me to fix this code.

age = ""
while int(len(age)) == 0:
    age = int(input("Enter your age: "))
print("Your age is " + age)

Body:
You cast age to be an int inside of your while loop, while using the len(age) as the comparison.

int does not have a length.

You want to wait to cast age until you are outside of the loop, or in this situation, don't cast it at all.

age = ""
while len(age) == 0:
    age = input("Enter your age: ")
print("Your age is " + age)


答:
You wanted a string for age but you transformed this age into an integer inside your loop :)

You can write :

age = ""
while age == "":
    age = input("Enter your age: ")
print("Your age is " + age)
```

Title: what is wrong with python my python code in while loop?


问:
How to get value from json using restassured
I have json and there is array of 'products'.

```<code>{
  "data": [
    {
      "contact_id": "...",
      "email": "...",
      "first_name": "...",
      "hash_campaign": "",
      "hash_campaign_valid_to_date": null,
      "hash_password": "",
      "last_name": "...",
      "loans": [

      ],
      "max_available_loan_amount": 2000.00,
      "middle_name": "P",
      "mobile": "...",
      "personal_id": "...",
      "product_code": 2,
      "products": [
        {
          "available_loan_terms": [
            15,
            21,
            30,
            7,
            45
          ],
          "default_amount": 0,
          "default_term": 15,
          "document_required": 0,
          "max_available_loan_amount": 2000.00,
          "max_loan_amount": 0,
          "max_monthly_payment": 0.00,
          "product_code": 2
        },
        {
          "available_loan_terms": [
            3,
            6,
            4,
            5
          ],
          "default_amount": 0,
          "default_term": 0,
          "document_required": 0,
          "max_available_loan_amount": 4000.00,
          "max_loan_amount": 0,
          "max_monthly_payment": 1300.00,
          "product_code": 101
        },
        {
          "available_loan_terms": [
            3,
            6,
            4,
            5
          ],
          "default_amount": 0,
          "default_term": 0,
          "document_required": 0,
          "max_available_loan_amount": 3000.00,
          "max_loan_amount": 0,
          "max_monthly_payment": 1510.00,
          "product_code": 100
        }
      ],
      "scoring_through_zoral": "0"
    }
  ],
  "description": "...",
  "requestId": "...",
  "status": 8888
}
</code>```

I would like to get values of fields 'default_term' and 'max_available_loan_amount' only for product with code 2.
I use restassured
I've tried

```<code> List<List> lists = response.body().jsonPath().getList("data.products");
</code>```

but this code returns list with only one item, I mean all products in one item...
how can I get information for first item in products array from this json ???

答:
Step 1: Create POJO to mapping

```<code>import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;

@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public static class Product {
    @JsonProperty("default_term")
    private int default_term;
    @JsonProperty("max_available_loan_amount")
    private double max_available_loan_amount;
}
</code>```

Step 2: Extract response and deserialize to object.

```<code>Product product = ...jsonPath().getObject("data[0].products.find {it.product_code == 2}", Product.class);
System.out.println(product);
//Product(default_term=15, max_available_loan_amount=2000.0)
</code>```

Body:
I have json and there is array of 'products'.

{
  "data": [
    {
      "contact_id": "...",
      "email": "...",
      "first_name": "...",
      "hash_campaign": "",
      "hash_campaign_valid_to_date": null,
      "hash_password": "",
      "last_name": "...",
      "loans": [

      ],
      "max_available_loan_amount": 2000.00,
      "middle_name": "P",
      "mobile": "...",
      "personal_id": "...",
      "product_code": 2,
      "products": [
        {
          "available_loan_terms": [
            15,
            21,
            30,
            7,
            45
          ],
          "default_amount": 0,
          "default_term": 15,
          "document_required": 0,
          "max_available_loan_amount": 2000.00,
          "max_loan_amount": 0,
          "max_monthly_payment": 0.00,
          "product_code": 2
        },
        {
          "available_loan_terms": [
            3,
            6,
            4,
            5
          ],
          "default_amount": 0,
          "default_term": 0,
          "document_required": 0,
          "max_available_loan_amount": 4000.00,
          "max_loan_amount": 0,
          "max_monthly_payment": 1300.00,
          "product_code": 101
        },
        {
          "available_loan_terms": [
            3,
            6,
            4,
            5
          ],
          "default_amount": 0,
          "default_term": 0,
          "document_required": 0,
          "max_available_loan_amount": 3000.00,
          "max_loan_amount": 0,
          "max_monthly_payment": 1510.00,
          "product_code": 100
        }
      ],
      "scoring_through_zoral": "0"
    }
  ],
  "description": "...",
  "requestId": "...",
  "status": 8888
}

I would like to get values of fields 'default_term' and 'max_available_loan_amount' only for product with code 2.
I use restassured
I've tried

 List<List> lists = response.body().jsonPath().getList("data.products");

but this code returns list with only one item, I mean all products in one item...
how can I get information for first item in products array from this json ???

Body:
Step 1: Create POJO to mapping

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;

@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public static class Product {
    @JsonProperty("default_term")
    private int default_term;
    @JsonProperty("max_available_loan_amount")
    private double max_available_loan_amount;
}

Step 2: Extract response and deserialize to object.

Product product = ...jsonPath().getObject("data[0].products.find {it.product_code == 2}", Product.class);
System.out.println(product);
//Product(default_term=15, max_available_loan_amount=2000.0)