问:
Show/Hide elements/tags for different users in Enterprise Architect
I want to make an EA-Project where I and some other people can see all information but some others should only see selected information.

Is it possible to create an EA-Project and do some settings so some defined elements or tags or element information are shown or hidden to defined users?

Or do i have to create two seperate EA-Projects?

答:
No, that is not possible, if a user has access to an element, he has access to all its properties.

What you can do is hide parts of the model. There are two options:

Hide Project Root

You can use a group lock to hide a project root from users outside of that group. This is mainly a usability feature as it doesn't prevent users from accessing the contents of the hidden project root in other ways.

From the manual:

When you set a Group Lock on a Root Node, you can also select a checkbox to hide the Package in the Browser window from users who are not members of the locking group or Administrators. If you change the type of lock, or remove the lock altogether, the Package becomes visible to all users.

This feature hides the Root Package and its contents from initial view in the Browser window. It does not prevent the contents of the Package from being exposed in Model Searches. If you want to completely hide a Package from groups of users, consider Pro Cloud Server Visibility Levels.

Pro Cloud Server Visibility Levels

This is the real thing. It uses database row level security to prevent certain users from seeing the information stored in these rows. You'll need Pro Cloud Server to setup these visibility levels.

See the manual for more information


来源: stackexchange

问:
Don't Work gspreads when i try to edit google sheet
I'am have a problem with gspreads, i registered API for google sheets and include json to my code, i already open access to the file for robot email, but i also see one error: raise SpreadsheetNotFound
gspread.exceptions.SpreadsheetNotFound. What to do?

my code:

```<code>import gspread

sa = gspread.service_account("creds.json")
sh = sa.open("filename")

wks = sh.worksheet("Sheet1")

print(wks.row_count)
</code>```

Error:

```<code>Traceback (most recent call last):
  File "C:\Users\Руслан\AppData\Local\Programs\Python\Python37-32\lib\site-packages\gspread\client.py", line 121, in open
    self.list_spreadsheet_files(title, folder_id),
  File "C:\Users\Руслан\AppData\Local\Programs\Python\Python37-32\lib\site-packages\gspread\utils.py", line 88, in finditem
    return next(item for item in seq if func(item))
StopIteration

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Руслан\Downloads\google-sheets-video-1-sacc-reading\main.py", line 4, in <module>
    sh = sa.open("url")
  File "C:\Users\Руслан\AppData\Local\Programs\Python\Python37-32\lib\site-packages\gspread\client.py", line 129, in open
    raise SpreadsheetNotFound
gspread.exceptions.SpreadsheetNotFound
</code>```

Edit:
I fixed this error, but now there is another one
New code:

```<code>import gspread

sa = gspread.service_account("creds.json")
sh = sa.open("filename", "D")

wks = sh.worksheet("Sheet1")

print(wks.row_count)
</code>```

New error:

```<code>Traceback (most recent call last):
  File "C:\Users\Руслан\Downloads\google-sheets-video-1-sacc-reading\main.py", line 4, in <module>
    sh = sa.open('url', 'D')
  File "C:\Users\Руслан\AppData\Local\Programs\Python\Python37-32\lib\site-packages\gspread\client.py", line 121, in open
    self.list_spreadsheet_files(title, folder_id),
  File "C:\Users\Руслан\AppData\Local\Programs\Python\Python37-32\lib\site-packages\gspread\client.py", line 96, in list_spreadsheet_files
    res = self.request("get", url, params=params).json()
  File "C:\Users\Руслан\AppData\Local\Programs\Python\Python37-32\lib\site-packages\gspread\client.py", line 71, in request
    raise APIError(response)
gspread.exceptions.APIError: {'errors': [{'domain': 'global', 'reason': 'notFound', 'message': 'File not found: .', 'locationType': 'parameter', 'location': 'fileId'}], 'code': 404, 'message': 'File not found: .'}
</code>```

答:
From your script and SpreadsheetNotFound gspread.exceptions.SpreadsheetNotFound., I thought that in this case, the reason for your issue might be due to that the owner of the Spreadsheet of filename is not the service account or the Spreadsheet is not shared with the service account.

If your Spreadsheet of filename is in your Google Drive and the owner of it is you, how about the following methods?

Share the Spreadsheet with the email of the service account.

Delegating domain-wide authority to the service account

In this case, your account is required to be a Google Workspace account.

ContentLicense: CC BY-SA 4.0

Body:
I'am have a problem with gspreads, i registered API for google sheets and include json to my code, i already open access to the file for robot email, but i also see one error: raise SpreadsheetNotFound
gspread.exceptions.SpreadsheetNotFound. What to do?

my code:

import gspread

sa = gspread.service_account("creds.json")
sh = sa.open("filename")

wks = sh.worksheet("Sheet1")

print(wks.row_count)

Error:

Traceback (most recent call last):
  File "C:\Users\Руслан\AppData\Local\Programs\Python\Python37-32\lib\site-packages\gspread\client.py", line 121, in open
    self.list_spreadsheet_files(title, folder_id),
  File "C:\Users\Руслан\AppData\Local\Programs\Python\Python37-32\lib\site-packages\gspread\utils.py", line 88, in finditem
    return next(item for item in seq if func(item))
StopIteration

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Руслан\Downloads\google-sheets-video-1-sacc-reading\main.py", line 4, in <module>
    sh = sa.open("url")
  File "C:\Users\Руслан\AppData\Local\Programs\Python\Python37-32\lib\site-packages\gspread\client.py", line 129, in open
    raise SpreadsheetNotFound
gspread.exceptions.SpreadsheetNotFound

Edit:
I fixed this error, but now there is another one
New code:

import gspread

sa = gspread.service_account("creds.json")
sh = sa.open("filename", "D")

wks = sh.worksheet("Sheet1")

print(wks.row_count)

New error:

Traceback (most recent call last):
  File "C:\Users\Руслан\Downloads\google-sheets-video-1-sacc-reading\main.py", line 4, in <module>
    sh = sa.open('url', 'D')
  File "C:\Users\Руслан\AppData\Local\Programs\Python\Python37-32\lib\site-packages\gspread\client.py", line 121, in open
    self.list_spreadsheet_files(title, folder_id),
  File "C:\Users\Руслан\AppData\Local\Programs\Python\Python37-32\lib\site-packages\gspread\client.py", line 96, in list_spreadsheet_files
    res = self.request("get", url, params=params).json()
  File "C:\Users\Руслан\AppData\Local\Programs\Python\Python37-32\lib\site-packages\gspread\client.py", line 71, in request
    raise APIError(response)
gspread.exceptions.APIError: {'errors': [{'domain': 'global', 'reason': 'notFound', 'message': 'File not found: .', 'locationType': 'parameter', 'location': 'fileId'}], 'code': 404, 'message': 'File not found: .'}


问:
JavaScript - img caption to appear/disappear onclick event
I need to have image caption to appear on 1 mouse click and disappear on next click by using JS. I can't figure out why the image caption is not appearing when I click on the image with onclick event and function use on external JS. Sorry if I make any mistake on question as this is my first post on  the forum.

HTML

```<code><div id="section1" >
        <h1>Pictures from my vacation</h1>`enter code here`
        <figure style="float: left;" >
            <img src="Photos/p1.jpg" title="Beach" value="hide/show" onclick="showOrHide()">
            <figcaption id="showthis"  style="visibility: hidden;">Waterton Beach</figcaption>
        </figure>
    <p>Beautiful and Sunny day at Wateron last year. Taking Ferry to explore around the late and natural beauty surrounded there. It was a beatiful day and beach and small town with full of visitors. Hope to back to this beautiful small town on summer break.
    </p>
</div>
</code>```

JS

function showOrHide() {

```<code>if (show=="false") {

document.getElementById("showthis").style.visibility="visible";
show="true";

}
else {
//show is true
document.getElementById("showthis").style.visibility="hidden";
show="false";
}
</code>```

}

答:
I've changed some things.

The html code:

```<code><div id="section1" >
    <h1>Pictures from my vacation</h1>`enter code here`
    <figure style="float: left;" >
        <img id="myImage" src="https://logowik.com/content/uploads/images/526_liverpoolfc.jpg" title="Beach">
        <figcaption id="showthis"  style="visibility: hidden;">Waterton Beach</figcaption>
    </figure>
<p>Beautiful and Sunny day at Wateron last year. Taking Ferry to explore around the late and natural beauty surrounded there. It was a beatiful day and beach and small town with full of visitors. Hope to back to this beautiful small town on summer break.
</p>
</code>```

I removed the inline onclick property, because it's better to add event listener in the JS like in the code below.
With JS then we add the click listener and we check for the visibility value and we either show or hide it.

The JS code:

```<code>const myImage = document.getElementById("myImage")
const caption = document.getElementById("showthis")
myImage.addEventListener("click", () => {
 if(caption.style.visibility == "visible") {
  caption.style.visibility = "hidden"
 } else {
  caption.style.visibility = "visible"
 }
</code>```

})

This is doing the toggle functionality. If you want the caption to be over the image, this is a matter of CSS.

Body:
I need to have image caption to appear on 1 mouse click and disappear on next click by using JS. I can't figure out why the image caption is not appearing when I click on the image with onclick event and function use on external JS. Sorry if I make any mistake on question as this is my first post on  the forum.

HTML

Pictures from my vacation
`enter code here`

Waterton Beach

Beautiful and Sunny day at Wateron last year. Taking Ferry to explore around the late and natural beauty surrounded there. It was a beatiful day and beach and small town with full of visitors. Hope to back to this beautiful small town on summer break.

JS

function showOrHide() {

if (show=="false") {

document.getElementById("showthis").style.visibility="visible";
show="true";

}
else {
//show is true
document.getElementById("showthis").style.visibility="hidden";
show="false";
}

}

Body:
I've changed some things.

The html code:

<div id="section1" >
    <h1>Pictures from my vacation</h1>`enter code here`
    <figure style="float: left;" >
        <img id="myImage" src="https://logowik.com/content/uploads/images/526_liverpoolfc.jpg" title="Beach">
        <figcaption id="showthis"  style="visibility: hidden;">Waterton Beach</figcaption>
    </figure>
<p>Beautiful and Sunny day at Wateron last year. Taking Ferry to explore around the late and natural beauty surrounded there. It was a beatiful day and beach and small town with full of visitors. Hope to back to this beautiful small town on summer break.
</p>

I removed the inline onclick property, because it's better to add event listener in the JS like in the code below.
With JS then we add the click listener and we check for the visibility value and we either show or hide it.

The JS code:

const myImage = document.getElementById("myImage")
const caption = document.getElementById("showthis")
myImage.addEventListener("click", () => {
 if(caption.style.visibility == "visible") {
  caption.style.visibility = "hidden"
 } else {
  caption.style.visibility = "visible"
 }

})

This is doing the toggle functionality. If you want the caption to be over the image, this is a matter of CSS.


问:
Why shared ptr in vector not delete with reserve
```<code>class A{
    public:
        A(){cout<<"constructor"<<endl;}
        ~A(){cout<<"destructor"<<endl;}
};

int main()
{
    {
        //case 1
        vector<std::shared_ptr<A>> vec;
        vec.reserve(1);
        vec[0] = std::make_shared<A>();
    }
    // Not destructor
    {
        //case 2
        vector<std::shared_ptr<A>> vec;
        vec.emplace_back(std::make_shared<A>());
    }
    // Called destructor
  return 0;
}

</code>```

Why vec at end of life, the element within it not be deleted in case1.result

If we not reserve vector, but emplace back element to vec, it works.

答:
TL;DR: I guess this is a typo and you meant to call resize(1) instead of reserve(1), but I'd like to explain a bit, because I see how one could easily confuse the two functions.

std::vector has a capactiy (the total slots that can be used) and a size (the number of slots actually used).

reserve() will increase the capacity, i.e. make room for more elements, but it will not increase the size. That's the job of resize():

```<code>vec.reserve(1); // capacity >= 1, size = 0!
</code>```

Access to a vector is out of bounds if the index is >= the vector's size, irrespective of it's capacity, thus

```<code>vec[0] = std::make_shared<A>();
</code>```

is out of bounds and leads to undefined behaviour. (index 0 >= size 0)

Body:
class A{
    public:
        A(){cout<<"constructor"<<endl;}
        ~A(){cout<<"destructor"<<endl;}
};

int main()
{
    {
        //case 1
        vector<std::shared_ptr> vec;
        vec.reserve(1);
        vec[0] = std::make_shared();
    }
    // Not destructor
    {
        //case 2
        vector<std::shared_ptr> vec;
        vec.emplace_back(std::make_shared());
    }
    // Called destructor
  return 0;
}

Why vec at end of life, the element within it not be deleted in case1.result

If we not reserve vector, but emplace back element to vec, it works.

Body:
TL;DR: I guess this is a typo and you meant to call resize(1) instead of reserve(1), but I'd like to explain a bit, because I see how one could easily confuse the two functions.

std::vector has a capactiy (the total slots that can be used) and a size (the number of slots actually used).

reserve() will increase the capacity, i.e. make room for more elements, but it will not increase the size. That's the job of resize():

vec.reserve(1); // capacity >= 1, size = 0!

Access to a vector is out of bounds if the index is >= the vector's size, irrespective of it's capacity, thus

vec[0] = std::make_shared<A>();

is out of bounds and leads to undefined behaviour. (index 0 >= size 0)


问:
Type mismatch: cannot convert from Agent to Fellow
In my model, various practitioners go to see patients multiple times in one visit. I am trying to ensure the same fellow is used to see a patient over multiple visits after being seized and released multiple times. I continue to receive this Type mismatch. Type Patient is the agent being pushed through the model and type Fellow belongs to a resource pool of 3 fellows.

答:
A few notes

Your screenshot is of the resource pool named Fellows - yet you market the Unit type as Patient - it should be Fellow if you want the resource pool to contain agents of type Fellow and have patients flow through the process flow and seize Fellows

In the on seize code you have two local variables you can use

Unit  - is the Fellow, the resource unit from this pool
agent - the agent that seized the unit (can be literally anything) so you need to cast it to what you think it is going to be.. AnyLogic cant do it or you as it has no idea what agent type will seize it

Your custom resource choice will then also change

We again need to cast the agent to a Patient again

NB - remember that this logic will throw a cast class exception error if any other agent than a Patient seizes a fellow.


问:
Can a Perl script modify itself?
I would like to have my scripts keep track of thier last date of revision internally as a comment.  Is this possible?  It seems to me that it would need to grab the date and then open its script file for an append, write the data and save the file.

Thanks Everone, great answsers one and all.  Based on the code snippet left by GreenMatt I threw this together...

```<code>#!/usr/bin/perl -w

my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime time;
$year += 1900;
$mon +=1;

open SELF, ">> letterhome.pl" or die "Unable to open self";
#print SELF "# ran/modified at " . join(' ', localtime(time)) . "\n";
print SELF "# ran/modified at $hour:$min:$sec on $mon/$mday/$year.\n";
close(SELF);

# ran/modified at 31 48 23 24 7 110 2 235 1
# unformated result of using localtime(time)

#Results using formated time/date
# ran/modified at 0:1:43 on 8/25/2010.
# ran/modified at 0:2:40 on 8/25/2010.
# ran/modified at 0:4:35 on 8/25/2010.
</code>```

答:
Very old question, and this is the worst practice.
If you want to know when script has been run, implement any logging system for that script.

If you want to know about modifications, do it as others wrote to you, with any control version system, subversion or git (the most popular, free for any use). Of course, on that way, you can write manually change log with bigger changes, or ..... do that log separately with different filename extention, for example <your_script>.changelog

ContentLicense: CC BY-SA 2.5

Title: Can a Perl script modify itself?

Body:
I would like to have my scripts keep track of thier last date of revision internally as a comment.  Is this possible?  It seems to me that it would need to grab the date and then open its script file for an append, write the data and save the file.

Thanks Everone, great answsers one and all.  Based on the code snippet left by GreenMatt I threw this together...

#!/usr/bin/perl -w

my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime time;
$year += 1900;
$mon +=1;

open SELF, ">> letterhome.pl" or die "Unable to open self";
#print SELF "# ran/modified at " . join(' ', localtime(time)) . "\n";
print SELF "# ran/modified at $hour:$min:$sec on $mon/$mday/$year.\n";
close(SELF);

# ran/modified at 31 48 23 24 7 110 2 235 1
# unformated result of using localtime(time)

#Results using formated time/date
# ran/modified at 0:1:43 on 8/25/2010.
# ran/modified at 0:2:40 on 8/25/2010.
# ran/modified at 0:4:35 on 8/25/2010.


问:
How to use Regedit utility to see Virtual Registry for a win32 uwp app
Is it possible to see the Virtual Registry of my win32 UWP App (desktop-bridge converted)? I know that all programmatic access goes to the virtual registry and that works. But I want to view it with RegEdit. Any solutions?

I remember viewing it about a year back but don't remember the details.

答: Yes, you can. We built a free tool called Hover that allows you to launch an external process in the context of your MSIX/APPX container. Using this tool you can launch Regedit, cmd.exe, PowerShell, or other processes inside your container, and thus have access to the same resources your app does.</p>


问:
Find difference between two time for verification token in Django
I am creating an app in Django where I have to send a token to a user but I want to make it expire
after 5 minutes, now the issue I am getting time from django field in this format

```<code>token_time = Token.objects.filter(user_id=user_id).last().user_token_timestamp
current time = datetime.now().time()
</code>```

is there any way to find the time difference in minutes in pythonic way, although I have done by converting the time into string and then striping it  but it just feels like not a good way.

答:
Just subtract the current time from token time</p>
```<code> td = current_time - token_time
 mins = td.seconds / 60
</code>```

Body:
I am creating an app in Django where I have to send a token to a user but I want to make it expire
after 5 minutes, now the issue I am getting time from django field in this format

token_time = Token.objects.filter(user_id=user_id).last().user_token_timestamp
current time = datetime.now().time()

is there any way to find the time difference in minutes in pythonic way, although I have done by converting the time into string and then striping it  but it just feels like not a good way.

Body:
Just subtract the current time from token time

 td = current_time - token_time
 mins = td.seconds / 60


问:
why powermail form don't send emails?
I'm using Typo3 powermail mail forms, after send the form is stored in backend but never send a copy to the recepient or user adress. how can i troubleshoot this issue ?
btw, Test emails from installtool works good.</p>

答:
Have you set a subject? I've been fooled more than once because I didn't set the subject.

There are different ways to do this:

in the Plugin/CE,

in TypoScript,

in the overrides in TypoScript.

The value must not be empty after applying this cascade.

(Applies to sender and receiver settings in the same way)

Title: why powermail form don't send emails?


问:
cv2.resize() unable to use with (y, x) matrix
I'm trying to calibrate HD Camera, resolution 1280x720.

I need it to be resized after applying undistort function to size 640x480.
So it's changing aspect ratio from 16:9 to 4:3.

In my opencv application anything works flawless besides saving (y, x) positions of calibrated camera. I need it because, binary output file is working with flashplayer application that reads this changed camera (y, x) positions and applyies it to original camera view that is being grabbed by flashplayer.

Binary file with cv2.resize():

```<code>def generate_grid(rows, cols):
    """Generate grid filed with y,x values at desired size"""
    cc, rr = np.meshgrid(np.arange(cols, dtype=np.uint16), np.arange(rows, dtype=np.uint16))
    return np.dstack([rr, cc])

camera_size = (1280, 720)
binary_size = (320, 240)
raw_grid = generate_grid(camera_size[1], camera_size[0])
undist_grid = cv2.undistort(raw_grid, camera_matrix, dist_coeffs)
resized_grid = cv2.resize(undist_grid, (320, 240))
transformed_grid = cv2.warpPerspective(resized_grid, transformed_matrix, binary_size)

with open(path_to_binary_file, "wb") as binary_file:
    num_bytes_written = binary_file.write(transformed_grid)
    print(transformed_grid.shape)
    print("Wrote %d bytes." % num_bytes_written)
</code>```

Output image read by flashplayer apllication:

Binary file with naive algorithm:

```<code>def generate_grid(rows, cols):
    """Generate grid filed with y,x values at desired size"""
    cc, rr = np.meshgrid(np.arange(cols, dtype=np.uint16), np.arange(rows, dtype=np.uint16))
    return np.dstack([rr, cc])

camera_size = (1280, 720)
binary_size = (320, 240)
raw_grid = generate_grid(camera_size[1], camera_size[0])
undist_grid = cv2.undistort(raw_grid, camera_matrix, dist_coeffs)
resized_grid = generate_grid(480, 640)
_resized_grid = generate_grid(binary_size[1], binary_size[0])

for y in range(undist_grid.shape[0]):
    for x in range(undist_grid.shape[1]):
        if y % 2 != 0 and x % 2 != 0:
            yy = int(y / 2)
            xx = int(x / 2)
            resized_grid[yy, xx, :] = undist_grid[y, x] / 2

for y in range(resized_grid.shape[0]):
    for x in range(resized_grid.shape[1]):
        if y % 2 != 0 and x % 2 != 0:
            yy = int(y / 2)
            xx = int(x / 2)
            _resized_grid[yy, xx, :] = resized_grid[y, x] / 2

transformed_grid = cv2.warpPerspective(_resized_grid, transformed_matrix, binary_size)

with open(path_to_binary_file, "wb") as binary_file:
    num_bytes_written = binary_file.write(transformed_grid)
    print(transformed_grid.shape)
    print("Wrote %d bytes." % num_bytes_written)
</code>```

Output image read by flashplayer application:

So in the naive case, I can see that this transformation from 1280x720 to 640x480 is wrong because normally it would be 640x360.

My questions are:

Am I using the cv2.resize() function in the wrong way?

Is there a better way to generate (y, x) points from undistorted camera view?

How can I implement resize 1280x720 to 640x480 in naive algorithm?

@Edit

My application is working okay.

I'm stuck on transferring, changed camera data to binary file.

答:
I could not get to work numpy 2d array with cv2.resize()

but finally I could get (y, x) 720,1280 array to be "scaled" to 480x640

```<code>for y in range(undist_grid.shape[0]):
    for x in range(undist_grid.shape[1]):
        if y % 3 != 0 and x % 2 != 0:
            yy = int((2*y) / 3)
            xx = int(x / 2)
            resized_grid[yy, xx, :] = (2 * undist_grid[y, x]) / 3
</code>```

Body:
I'm trying to calibrate HD Camera, resolution 1280x720.

I need it to be resized after applying undistort function to size 640x480.
So it's changing aspect ratio from 16:9 to 4:3.

In my opencv application anything works flawless besides saving (y, x) positions of calibrated camera. I need it because, binary output file is working with flashplayer application that reads this changed camera (y, x) positions and applyies it to original camera view that is being grabbed by flashplayer.

Binary file with cv2.resize():

def generate_grid(rows, cols):
    """Generate grid filed with y,x values at desired size"""
    cc, rr = np.meshgrid(np.arange(cols, dtype=np.uint16), np.arange(rows, dtype=np.uint16))
    return np.dstack([rr, cc])

camera_size = (1280, 720)
binary_size = (320, 240)
raw_grid = generate_grid(camera_size[1], camera_size[0])
undist_grid = cv2.undistort(raw_grid, camera_matrix, dist_coeffs)
resized_grid = cv2.resize(undist_grid, (320, 240))
transformed_grid = cv2.warpPerspective(resized_grid, transformed_matrix, binary_size)

with open(path_to_binary_file, "wb") as binary_file:
    num_bytes_written = binary_file.write(transformed_grid)
    print(transformed_grid.shape)
    print("Wrote %d bytes." % num_bytes_written)

Output image read by flashplayer apllication:

Binary file with naive algorithm:

def generate_grid(rows, cols):
    """Generate grid filed with y,x values at desired size"""
    cc, rr = np.meshgrid(np.arange(cols, dtype=np.uint16), np.arange(rows, dtype=np.uint16))
    return np.dstack([rr, cc])

camera_size = (1280, 720)
binary_size = (320, 240)
raw_grid = generate_grid(camera_size[1], camera_size[0])
undist_grid = cv2.undistort(raw_grid, camera_matrix, dist_coeffs)
resized_grid = generate_grid(480, 640)
_resized_grid = generate_grid(binary_size[1], binary_size[0])

for y in range(undist_grid.shape[0]):
    for x in range(undist_grid.shape[1]):
        if y % 2 != 0 and x % 2 != 0:
            yy = int(y / 2)
            xx = int(x / 2)
            resized_grid[yy, xx, :] = undist_grid[y, x] / 2

for y in range(resized_grid.shape[0]):
    for x in range(resized_grid.shape[1]):
        if y % 2 != 0 and x % 2 != 0:
            yy = int(y / 2)
            xx = int(x / 2)
            _resized_grid[yy, xx, :] = resized_grid[y, x] / 2

transformed_grid = cv2.warpPerspective(_resized_grid, transformed_matrix, binary_size)

with open(path_to_binary_file, "wb") as binary_file:
    num_bytes_written = binary_file.write(transformed_grid)
    print(transformed_grid.shape)
    print("Wrote %d bytes." % num_bytes_written)

Output image read by flashplayer application:

So in the naive case, I can see that this transformation from 1280x720 to 640x480 is wrong because normally it would be 640x360.

My questions are:

Am I using the cv2.resize() function in the wrong way?

Is there a better way to generate (y, x) points from undistorted camera view?

How can I implement resize 1280x720 to 640x480 in naive algorithm?

@Edit

My application is working okay.

I'm stuck on transferring, changed camera data to binary file.

Body:
I could not get to work numpy 2d array with cv2.resize()

but finally I could get (y, x) 720,1280 array to be "scaled" to 480x640

for y in range(undist_grid.shape[0]):
    for x in range(undist_grid.shape[1]):
        if y % 3 != 0 and x % 2 != 0:
            yy = int((2*y) / 3)
            xx = int(x / 2)
            resized_grid[yy, xx, :] = (2 * undist_grid[y, x]) / 3


问:
Airflow wrong execution_date for timezone aware DAGs
We're using Airflow v2.2.3 on Kubernetes (KubernetesExecutor),
our environment requires a DAG pre-customer, and each customer can be in a different timezone.

Each DAG should be scheduled in its own timezone at midnight,
and I saw that it can be achieved using Airflow's timezone aware DAGs

so configuring timezone aware start_date for each DAG worked and made each DAG to execute in its own timezone midnight:

```<code>start_date_utc = (datetime.now() - timedelta(days=2)).replace(
        hour=0, minute=0, second=0, microsecond=0)

timezone = pendulum.timezone(get_customer_timezone(customer))
START_DATE = start_date_utc.replace(tzinfo=timezone)

default_args = {
        "owner": "owner",
        "depends_on_past": False,
        "start_date": START_DATE,
}

dag = DAG(
    dag_id,
    schedule_interval="0 0 * * *",
    default_args=default_args,
    tags=[cusotmer_name]
)

date = '{{ execution_date | ds }}'

operator_args = {
    "customer_date": date,
}
</code>```

My problem is that both the jinja template and dag_run the execution_date (dag_run.logical_date) is still in UTC, and was not adjusted based on the DAGs timezone.

That causes unexpected behavior when running DAGs in different timezones tho execution_date of DAGs with timezone offset earlier than UTC is wrong (2 days before and not 1)

I need some advice please on how can we change the execution_date based on the DAGs timezone

thanks

答:
The value of execution_date is in UTC.
To convert to different time zone you can do:

```<code>{{ execution_date.in_timezone('Europe/Amsterdam') }}
</code>```

If you set timezone in your DAG you can access it from dag.timezone and use it Jinja.

```<code>{{ dag_run.execution_date.astimezone(dag.timezone) }}
</code>```

You already noticed that execution_date is deprecated macro so you should use logical_date as:

```<code>{{ dag_run.logical_date.astimezone(dag.timezone) }}
</code>```

Body:
We're using Airflow v2.2.3 on Kubernetes (KubernetesExecutor),
our environment requires a DAG pre-customer, and each customer can be in a different timezone.

Each DAG should be scheduled in its own timezone at midnight,
and I saw that it can be achieved using Airflow's timezone aware DAGs

so configuring timezone aware start_date for each DAG worked and made each DAG to execute in its own timezone midnight:

start_date_utc = (datetime.now() - timedelta(days=2)).replace(
        hour=0, minute=0, second=0, microsecond=0)

timezone = pendulum.timezone(get_customer_timezone(customer))
START_DATE = start_date_utc.replace(tzinfo=timezone)

default_args = {
        "owner": "owner",
        "depends_on_past": False,
        "start_date": START_DATE,
}

dag = DAG(
    dag_id,
    schedule_interval="0 0 * * *",
    default_args=default_args,
    tags=[cusotmer_name]
)

date = '{{ execution_date | ds }}'

operator_args = {
    "customer_date": date,
}

My problem is that both the jinja template and dag_run the execution_date (dag_run.logical_date) is still in UTC, and was not adjusted based on the DAGs timezone.

That causes unexpected behavior when running DAGs in different timezones tho execution_date of DAGs with timezone offset earlier than UTC is wrong (2 days before and not 1)

I need some advice please on how can we change the execution_date based on the DAGs timezone

thanks

Body:
The value of execution_date is in UTC.
To convert to different time zone you can do:

{{ execution_date.in_timezone('Europe/Amsterdam') }}

If you set timezone in your DAG you can access it from dag.timezone and use it Jinja.

{{ dag_run.execution_date.astimezone(dag.timezone) }}

You already noticed that execution_date is deprecated macro so you should use logical_date as:

{{ dag_run.logical_date.astimezone(dag.timezone) }}


问:
How can an ES6 module be run as a script in Node?
How can an ES6 module be run as a script in Node?

When I try this shebang I get an error:

```<code>#!/usr/bin/env node --experimental-modules
</code>```

/usr/bin/env: ‘node --experimental-modules’: No such file or directory

If I use this shebang it has syntax errors (of course):

```<code>#!/usr/bin/env node
</code>```

SyntaxError: Unexpected token import

The work around I'm using is to use a shell script to call the module:

```<code>#!/usr/bin/env sh

BASEDIR=$( dirname "$0" )
node --experimental-modules $BASEDIR/script.mjs "$@"
</code>```

Is it possible to get this working without a second file?

答:
I'm not sure exactly when it changed, but in recent Node versions no special care is needed, if the script is part of a package (ie, there is a package.json file in the folder or any parent folder). Just ensure these steps are followed:

In package.json, set "type": "module"

Give the file a .js extension

Use the shebang #!/usr/bin/env node

ContentLicense: CC BY-SA 3.0

Body:
How can an ES6 module be run as a script in Node?

When I try this shebang I get an error:

#!/usr/bin/env node --experimental-modules

/usr/bin/env: ‘node --experimental-modules’: No such file or directory

If I use this shebang it has syntax errors (of course):

#!/usr/bin/env node

SyntaxError: Unexpected token import

The work around I'm using is to use a shell script to call the module:

#!/usr/bin/env sh

BASEDIR=$( dirname "$0" )
node --experimental-modules $BASEDIR/script.mjs "$@"

Is it possible to get this working without a second file?


问:
WTForms equivalent to <input type="datetime-local">

I would like to know if it's possible to create a dropdown datetime field for the DateTimeField in WTForms, the way  renders in HTML.

A dropdown menu is much more user friendly than the default in WTForms where a user has to type in the date and time in the exact correct format.

And if it's not possible using only WTForms then how would I be able to implement the raw HTML into a WTForm as I would still like to use the security CSRF token that is provided by WTForms.

Thanks in advance!

答:
Ok after being forced to read the WTForms documentation because nobody immediately answered my question I now understand that it can be manipulated to do anything HTML can do by passing in HTML keyword arguments like so:

{{ form.when.label }}

{{ form.when(type='datetime-local') }}

Body:
Ok after being forced to read the WTForms documentation because nobody immediately answered my question I now understand that it can be manipulated to do anything HTML can do by passing in HTML keyword arguments like so:

{{ form.when.label }}<br>

{{ form.when(type='datetime-local') }}


问:
Systemd service with multiple execStart and watchdog for each execStart
I would know if it's possible to create service with multiple execStart where I can monitor each execStart with a watchdog such as:

```<code>[Unit]
Description="test service"

[Service]
Type=oneshot
ExecStart=/home/program1
ExecStart=/home/program2
WatchdogSec= 2
Restart=on-failure
RestartSec= 1

[Install]
WantedBy=default.target

</code>```

Or it's better if I use template service for example test@.service with this syntax:

```<code>[Unit]
Description="test service %i"

[Service]
ExecStart=/home/%i
WatchdogSec= 2
Restart=on-failure
RestartSec= 1

[Install]
WantedBy=default.target

</code>```

Thanks in advance.

答: I found that using the template service is the better solution and covers what I need. Thanks to you all.</p>

Body:
I would know if it's possible to create service with multiple execStart where I can monitor each execStart with a watchdog such as:

[Unit]
Description="test service"

[Service]
Type=oneshot
ExecStart=/home/program1
ExecStart=/home/program2
WatchdogSec= 2
Restart=on-failure
RestartSec= 1

[Install]
WantedBy=default.target

Or it's better if I use template service for example test@.service with this syntax:

[Unit]
Description="test service %i"

[Service]
ExecStart=/home/%i
WatchdogSec= 2
Restart=on-failure
RestartSec= 1

[Install]
WantedBy=default.target

Thanks in advance.


问:
Connection timed out when I try to connect posgrest sql server on digitalocen and azure function
I have a postgres database running on a digital ocean server. The database is protected by a firewall and ssl root certificate, I add the Outbound addresses provided by the Azure Function App to the database firewall and I am passing the certificate through the connection string.

```<code>pg_conn = psycopg2.connect(host= os.environ.get("PG_HOST"),database= os.environ.get("PG_DB"), user=os.environ.get("PG_USER"), password=os.environ.get("PG_PASSWORD"), port=os.environ.get("PG_PORT"), sslmode='require', sslrootcert = r'my-proyect/certificate.crt' )
</code>```

But when I upload my function to the cloud the connection sends a timeout

```<code>Connection timed out Is the server running on that host and accepting TCP/IP connections?
</code>```

答:
As per my knowledge, A connection time-out error is typically due to connectivity issues or networking issues.

Firewall if not allowing the access to the port number which application has.

Here is the tool for troubleshooting these sort of issues is portgry

portqry -n [hostname] -e [port number]

you can even add applications to Trusted Resources in Postgry SQL

Here is the document which has complete information about connection time out error.

Body:
I have a postgres database running on a digital ocean server. The database is protected by a firewall and ssl root certificate, I add the Outbound addresses provided by the Azure Function App to the database firewall and I am passing the certificate through the connection string.

pg_conn = psycopg2.connect(host= os.environ.get("PG_HOST"),database= os.environ.get("PG_DB"), user=os.environ.get("PG_USER"), password=os.environ.get("PG_PASSWORD"), port=os.environ.get("PG_PORT"), sslmode='require', sslrootcert = r'my-proyect/certificate.crt' )

But when I upload my function to the cloud the connection sends a timeout

Connection timed out Is the server running on that host and accepting TCP/IP connections?


问:
React router nested routing is not working
I am using react router v6 and trying to nest routers to switch only a particular div of the page.

I tried doing this

```<code><div className="user-profile-page">
    <div className="user-profile-page-background">
        <img className="full-img" src = {user.profile_picture_url} />
    </div>
    <div className = "user-profile-contents-container">
        <h1 className="user-profile-name ellipsis">{user.full_name} ({user.age})</h1>
        <div className = "user-profile-nav">
            <NavLink to = "" className={(state)=>!state.isActive?"user-profile-nav-item":"user-profile-nav-item user-profile-nav-item-active"}>
                About
            </NavLink>
            <NavLink to = "pictures" className={(state)=>!state.isActive?"user-profile-nav-item":"user-profile-nav-item user-profile-nav-item-active"}>
                Pictures
            </NavLink>
        </div>
        <div className = "user-profile-contents-main">
            <Routes>
                <Route index={true} element = {<UserProfileAbout />} />
                <Route path = "pictures" element =  {<UserProfilePictures />} />
            </Routes>
        </div>
    </div>
</div>
</code>```

but when I go to "/user/pictures" instead of just changing the contents inside "user-profile-contents-main" div. It changes the whole page.

Here is my main router

```<code><Routes>
    <Route path = "/" element = {<HomePage /> } />
    <Route path = "/message/:uid" element = {<ChatPage />} />
    <Route path = "/user/:uid" element = {<UserProfilePage />} />
</Routes>
</code>```

EDIT

all i had to do was

```<code><Routes>
    <Route path = "/" element = {<HomePage /> } />
    <Route path = "/message/:uid" element = {<ChatPage />} />
    <Route path = "/user/:uid/*" element = {<UserProfilePage />} />
</Routes>
</code>```

add /* in the route path

答:
```<code> <Routes>
    <Route index={true} element = {<UserProfileAbout />} />
    <Route path = "pictures" element =  {<UserProfilePictures />} />
 </Routes>
</code>```

no need to declare a new navigation inside the component in which it should be called, if you want to isolate some screens it is better to create a separate stack for them

Body:
I am using react router v6 and trying to nest routers to switch only a particular div of the page.

I tried doing this

{user.full_name} ({user.age})

            <NavLink to = "" className={(state)=>!state.isActive?"user-profile-nav-item":"user-profile-nav-item user-profile-nav-item-active"}>
                About
            </NavLink>
            <NavLink to = "pictures" className={(state)=>!state.isActive?"user-profile-nav-item":"user-profile-nav-item user-profile-nav-item-active"}>
                Pictures
            </NavLink>

            <Routes>
                <Route index={true} element = {<UserProfileAbout />} />
                <Route path = "pictures" element =  {<UserProfilePictures />} />
            </Routes>

but when I go to "/user/pictures" instead of just changing the contents inside "user-profile-contents-main" div. It changes the whole page.

Here is my main router

<Routes>
    <Route path = "/" element = {<HomePage /> } />
    <Route path = "/message/:uid" element = {<ChatPage />} />
    <Route path = "/user/:uid" element = {<UserProfilePage />} />
</Routes>

EDIT

all i had to do was

<Routes>
    <Route path = "/" element = {<HomePage /> } />
    <Route path = "/message/:uid" element = {<ChatPage />} />
    <Route path = "/user/:uid/*" element = {<UserProfilePage />} />
</Routes>

add /* in the route path

Body:
 <Routes>
    <Route index={true} element = {<UserProfileAbout />} />
    <Route path = "pictures" element =  {<UserProfilePictures />} />
 </Routes>

no need to declare a new navigation inside the component in which it should be called, if you want to isolate some screens it is better to create a separate stack for them


问:
Pandas: Check each row for condition and insert row below if condition is met
this is my first question here as I really couldn't figure it out with related answers:
I have a list of dataframes "df_list", for each user I have a dataframe which basically looks like:

```<code>-   |User |Timestamp                |Timestamp2         |check            |in_out
0   |0001 |2022-01-07 07:40:44  |2022-01-07 17:32:18    |0 days 09:51:34  |in
1   |0001 |2022-01-07 17:32:18  |2022-01-10 17:31:50    |2 days 23:59:32  |out
2   |0001 |2022-01-10 17:31:50  |2022-01-11 07:43:48    |0 days 14:11:58  |in
</code>```

Data:

```<code>data = {'User': [1, 1, 1],
 'Timestamp': ['2022-01-07 07:40:44',
  '2022-01-07 17:32:18',
  '2022-01-10 17:31:50'],
 'Timestamp2': ['2022-01-07 17:32:18',
  '2022-01-10 17:31:50',
  '2022-01-11 07:43:48'],
 'check': ['0 days 09:51:34', '2 days 23:59:32', '0 days 14:11:58'],
 'in_out': ['in', 'out', 'in']}
</code>```

I would like to go through all the dataframes in my df_list and inside each df I would like to add 1 row (below) where the 'check' value is > 15 hours.

Desired Output

```<code>-   |User |Timestamp                |Timestamp2         |check            |in_out
0   |0001 |2022-01-07 07:40:44  |2022-01-07 17:32:18    |0 days 09:51:34  |in
1   |0001 |2022-01-07 17:32:18  |2022-01-10 17:31:50    |2 days 23:59:32  |out
2   |0001
3   |0001 |2022-01-10 17:31:50  |2022-01-11 07:43:48    |0 days 14:11:58  |in
</code>```

Attempt:

So what I tried is to go with a for-loop into the list and there with another loop through all my rows in each dataframe. Then I checked via if-clause for my condition...
I create a new blank line with the required index and then concat the dataframe so i can include the empty line.

```<code>for dfx in df_list:
    for i in dfx.index.values.tolist():
        if (pd.Timedelta(dfx["check"].loc[i]) > pd.Timedelta("15 hours")) == True:
            line = pd.DataFrame({'ID': '', 'Timestamp': None,'Timestamp2': '','check': None}, index=[i+1])
            dfx = pd.concat([dfx.iloc[:i+1], line, dfx.iloc[i:]]).reset_index(drop=True)
</code>```

I also found this here Add empty row if a condition is met Pandas but I can't get this running as well...

```<code>for i in dfy.index.values.tolist():
    indices = dfy.loc[pd.Timedelta(((dfy["check"].loc[i]) > pd.Timedelta("15 hours"))== True)].index.tolist()
    ERROR: Value must be Timedelta, string, integer, float, timedelta or convertible, not bool
</code>```

In the next step I want to add the 'Timestamp' value from previous line + or - 10 hours, depending on the 'value' of the in/out column...but I thought I should figure out one problem at a time...

答:
You can create a boolean mask using "check" column and add a row using Index.repeat and reindexing. Then sort_index and delete duplicate values:

```<code>msk = df['check'].astype('timedelta64[h]') > 15
df = df.reindex(df[msk].index.repeat(2)).append(df[~msk]).sort_index()
df.loc[df.duplicated(['Timestamp','check']), df.columns.drop('User')] = np.nan
</code>```

Note that this assumes "check" is dtype timedelta object.

Output:

```<code>   User           Timestamp          Timestamp2           check in_out
0     1 2022-01-07 07:40:44 2022-01-07 17:32:18 0 days 09:51:34     in
1     1 2022-01-07 17:32:18 2022-01-10 17:31:50 2 days 23:59:32    out
1     1                 NaT                 NaT             NaT    NaN
2     1 2022-01-10 17:31:50 2022-01-11 07:43:48 0 days 14:11:58     in
</code>```

Body:
this is my first question here as I really couldn't figure it out with related answers:
I have a list of dataframes "df_list", for each user I have a dataframe which basically looks like:

-   |User |Timestamp                |Timestamp2         |check            |in_out
0   |0001 |2022-01-07 07:40:44  |2022-01-07 17:32:18    |0 days 09:51:34  |in
1   |0001 |2022-01-07 17:32:18  |2022-01-10 17:31:50    |2 days 23:59:32  |out
2   |0001 |2022-01-10 17:31:50  |2022-01-11 07:43:48    |0 days 14:11:58  |in

Data:

data = {'User': [1, 1, 1],
 'Timestamp': ['2022-01-07 07:40:44',
  '2022-01-07 17:32:18',
  '2022-01-10 17:31:50'],
 'Timestamp2': ['2022-01-07 17:32:18',
  '2022-01-10 17:31:50',
  '2022-01-11 07:43:48'],
 'check': ['0 days 09:51:34', '2 days 23:59:32', '0 days 14:11:58'],
 'in_out': ['in', 'out', 'in']}

I would like to go through all the dataframes in my df_list and inside each df I would like to add 1 row (below) where the 'check' value is > 15 hours.

Desired Output

-   |User |Timestamp                |Timestamp2         |check            |in_out
0   |0001 |2022-01-07 07:40:44  |2022-01-07 17:32:18    |0 days 09:51:34  |in
1   |0001 |2022-01-07 17:32:18  |2022-01-10 17:31:50    |2 days 23:59:32  |out
2   |0001
3   |0001 |2022-01-10 17:31:50  |2022-01-11 07:43:48    |0 days 14:11:58  |in

Attempt:

So what I tried is to go with a for-loop into the list and there with another loop through all my rows in each dataframe. Then I checked via if-clause for my condition...
I create a new blank line with the required index and then concat the dataframe so i can include the empty line.

for dfx in df_list:
    for i in dfx.index.values.tolist():
        if (pd.Timedelta(dfx["check"].loc[i]) > pd.Timedelta("15 hours")) == True:
            line = pd.DataFrame({'ID': '', 'Timestamp': None,'Timestamp2': '','check': None}, index=[i+1])
            dfx = pd.concat([dfx.iloc[:i+1], line, dfx.iloc[i:]]).reset_index(drop=True)

I also found this here Add empty row if a condition is met Pandas but I can't get this running as well...

for i in dfy.index.values.tolist():
    indices = dfy.loc[pd.Timedelta(((dfy["check"].loc[i]) > pd.Timedelta("15 hours"))== True)].index.tolist()
    ERROR: Value must be Timedelta, string, integer, float, timedelta or convertible, not bool

In the next step I want to add the 'Timestamp' value from previous line + or - 10 hours, depending on the 'value' of the in/out column...but I thought I should figure out one problem at a time...

Body:
You can create a boolean mask using "check" column and add a row using Index.repeat and reindexing. Then sort_index and delete duplicate values:

msk = df['check'].astype('timedelta64[h]') > 15
df = df.reindex(df[msk].index.repeat(2)).append(df[~msk]).sort_index()
df.loc[df.duplicated(['Timestamp','check']), df.columns.drop('User')] = np.nan

Note that this assumes "check" is dtype timedelta object.

Output:

   User           Timestamp          Timestamp2           check in_out
0     1 2022-01-07 07:40:44 2022-01-07 17:32:18 0 days 09:51:34     in
1     1 2022-01-07 17:32:18 2022-01-10 17:31:50 2 days 23:59:32    out
1     1                 NaT                 NaT             NaT    NaN
2     1 2022-01-10 17:31:50 2022-01-11 07:43:48 0 days 14:11:58     in


问:
How to wait for a python script to complete run and then download the resulting file with PHP?
I have a python script (on Windows Server) that requests information through an API, downloads data into several csv and at the end it 'zips' them all into 1 single .zip file. The idea is to access that zip file through an URL, using PHP.

But the main issue here is PHP making the zip available, even before the file is not yet completely compressed.

Using the 'sleep' function, I believe will halt the execution of PHP, even the Python script, am I right?

My current setting is using a Task, on Windows Task Scheduler, to trigger the Python script, download the necessary files and only then, making the zip file available with PHP.

Is there any way of doing all the process within PHP script, without using Windows Task Scheduler?

```<code><?php
include_once $_SERVER['DOCUMENT_ROOT'] . "/#classes/simple_html_dom.php";

#header("Content-type: text/html");
header("Content-Disposition: attachment; filename=api-week-values.zip");

unlink("api-week-values.zip");
$command = escapeshellcmd('python api_weekly.py');
$output = shell_exec($command);

sleep(15);
?>
</code>```

You can see the code I am using for the whole process.

To clarify the process:

An application needs to access the file I am downloading with the python script

I feed the application with the URL from Apache server

the application goes to the link (through index.php) and triggers the python script (which downloads the zip file)

php should pop-up a save file WHEN the zip file has been completely downloaded

答:
May be you can do something like that :

The python script put at the begining a file somewhere with informations like start time and end time when it endded

The PHP script loop on read the file while the end time is not set. And after delete the file. And then, it takes the zip.

Body:
I have a python script (on Windows Server) that requests information through an API, downloads data into several csv and at the end it 'zips' them all into 1 single .zip file. The idea is to access that zip file through an URL, using PHP.

But the main issue here is PHP making the zip available, even before the file is not yet completely compressed.

Using the 'sleep' function, I believe will halt the execution of PHP, even the Python script, am I right?

My current setting is using a Task, on Windows Task Scheduler, to trigger the Python script, download the necessary files and only then, making the zip file available with PHP.

Is there any way of doing all the process within PHP script, without using Windows Task Scheduler?

<?php
include_once $_SERVER['DOCUMENT_ROOT'] . "/#classes/simple_html_dom.php";

#header("Content-type: text/html");
header("Content-Disposition: attachment; filename=api-week-values.zip");

unlink("api-week-values.zip");
$command = escapeshellcmd('python api_weekly.py');
$output = shell_exec($command);

sleep(15);
?>

You can see the code I am using for the whole process.

To clarify the process:

An application needs to access the file I am downloading with the python script

I feed the application with the URL from Apache server

the application goes to the link (through index.php) and triggers the python script (which downloads the zip file)

php should pop-up a save file WHEN the zip file has been completely downloaded


问:
how to know if the request is ajax in asp.net mvc?
anybody how can I know if the request is ajax ? (I'm using jquery for ajax)</p>

答:
It works for me in ASP.NET MVC 3</p>

```<code>if (Request.IsAjaxRequest())
{
     // ajax request handled
}
</code>```

Body:
It works for me in ASP.NET MVC 3

if (Request.IsAjaxRequest())
{
     // ajax request handled
}


问:
Empty Textbox values inside a GridView in asp.net c#
I have this GridView and and on a button click want to send the whole gridview data in an email body (using SMTP)

```<code><asp:GridView ID="GridView2" runat="server" ShowFooter="true" AutoGenerateColumns="false">
<Columns>
    <asp:TemplateField HeaderText="Heading 1">
        <ItemTemplate>
            <asp:TextBox ID="tbxHeading1" runat="server"></asp:TextBox>
        </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Heading 2">
        <ItemTemplate>
            <asp:TextBox ID="tbxHeading2" runat="server"></asp:TextBox>
        </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Heading 3">
        <ItemTemplate>
            <asp:DropDownList runat="server" ID="ddlHeading3" Height="26">
                <asp:ListItem Text=" " Selected="True" />
                <asp:ListItem Text="list-1" />
                <asp:ListItem Text="list-2" />
                <asp:ListItem Text="list-3" />
            </asp:DropDownList>
        </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Heading 4">
        <ItemTemplate>
            <asp:TextBox ID="tbxHeading4" runat="server"></asp:TextBox>
        </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Heading 5">
        <ItemTemplate>
            <asp:TextBox ID="tbxHeading5" runat="server"></asp:TextBox>
        </ItemTemplate>
    </asp:TemplateField>
</Columns></asp:GridView>

<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click"></asp:Button>
</code>```

Button click:

```<code>protected void btnSubmit_Click(object sender, EventArgs e)
{
   StringBuilder strBuilder = new StringBuilder();
   StringWriter strWriter = new StringWriter(strBuilder);
   HtmlTextWriter htw = new HtmlTextWriter(strWriter);
   GridView2.RenderControl(htw);

   message.Body += strBuilder.ToString();
}
</code>```

On button click I am getting the data in the email body but if the textbox value is empty I am getting an empty array. Like this Image

Is there anyway to hide the empty array "[   ]" if the textbox is empty?

NOTE: When I debug the code I am seeing no value attribute to the textbox. If I passed default value to texbox, no use.
Debug code:

```<code><td><input name="defaultcontent_0$GridView2$ctl02$tbxHeading1" type="text" id="defaultcontent_0_GridView2_tbxHeading1_0" /></td>
</code>```

Thanks in advance!

答:
Try to replace it with empty string before passing it to the message body like this

strBuilder = strBuilder.replace("[]","");

Body:
I have this GridView and and on a button click want to send the whole gridview data in an email body (using SMTP)

<asp:GridView ID="GridView2" runat="server" ShowFooter="true" AutoGenerateColumns="false">
<Columns>
    <asp:TemplateField HeaderText="Heading 1">
        <ItemTemplate>
            <asp:TextBox ID="tbxHeading1" runat="server"></asp:TextBox>
        </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Heading 2">
        <ItemTemplate>
            <asp:TextBox ID="tbxHeading2" runat="server"></asp:TextBox>
        </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Heading 3">
        <ItemTemplate>
            <asp:DropDownList runat="server" ID="ddlHeading3" Height="26">
                <asp:ListItem Text=" " Selected="True" />
                <asp:ListItem Text="list-1" />
                <asp:ListItem Text="list-2" />
                <asp:ListItem Text="list-3" />
            </asp:DropDownList>
        </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Heading 4">
        <ItemTemplate>
            <asp:TextBox ID="tbxHeading4" runat="server"></asp:TextBox>
        </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Heading 5">
        <ItemTemplate>
            <asp:TextBox ID="tbxHeading5" runat="server"></asp:TextBox>
        </ItemTemplate>
    </asp:TemplateField>
</Columns></asp:GridView>

<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click"></asp:Button>

Button click:

protected void btnSubmit_Click(object sender, EventArgs e)
{
   StringBuilder strBuilder = new StringBuilder();
   StringWriter strWriter = new StringWriter(strBuilder);
   HtmlTextWriter htw = new HtmlTextWriter(strWriter);
   GridView2.RenderControl(htw);

   message.Body += strBuilder.ToString();
}

On button click I am getting the data in the email body but if the textbox value is empty I am getting an empty array. Like this Image

Is there anyway to hide the empty array "[   ]" if the textbox is empty?

NOTE: When I debug the code I am seeing no value attribute to the textbox. If I passed default value to texbox, no use.
Debug code:

<input name="defaultcontent_0$GridView2$ctl02$tbxHeading1" type="text" id="defaultcontent_0_GridView2_tbxHeading1_0" />

Thanks in advance!


问:
How to delete item from Swift UI List in UI Test

Is it possible to delete a Swift UI List item from a UI test?

For the user they can press the edit button which puts the list into edit mode (screenshot 1), then press the red circle with the white line, then press Delete.

Alternatively the user can swipe delete the list item.

Even with the accessibility inspector on I can't see what the icon is (the red circle with the white line). It doesn't show anything when I hover over it. Also the recorder doesn't record anything if I try using that tool.

If I try with .swipeLeft() to try to delete using the swipe gesture instead, it actually "taps" on the list button instead of swiping and just opens the detail view.

Any ideas? What am I missing here? Or is this not actually possible?

答:
Ok I found a way to make it work with the swipe method. It's pretty simple. Just need to let the test know to swipe a bit slower.

```<code>app.staticTexts["Test"].swipeLeft(velocity: XCUIGestureVelocity.slow)
</code>```

Using that I'm able to then tap on the delete button and assert that the item is gone.

I'm not super fussed right now about the other method, as long as there's a way to test deleting (and as long as I'm allowing swipe delete). However would be good to know if someone has the answer.

Body:
Ok I found a way to make it work with the swipe method. It's pretty simple. Just need to let the test know to swipe a bit slower.

app.staticTexts["Test"].swipeLeft(velocity: XCUIGestureVelocity.slow)

Using that I'm able to then tap on the delete button and assert that the item is gone.

I'm not super fussed right now about the other method, as long as there's a way to test deleting (and as long as I'm allowing swipe delete). However would be good to know if someone has the answer.


问:
What is lazy loading in Hibernate?
What is lazy loading in Java? I don't understand the process. Can anybody help me to understand the process of lazy loading?</p>

答: Lazy setting decides whether to load child objects while loading the Parent Object.You need to do this setting respective hibernate mapping file of the parent class.Lazy = true (means not to load child)By default the lazy loading of the child objects is true.</p>

Title: What is lazy loading in Hibernate?


问:
Validate path param in AWS API Gateway through OpenAPI spec
I created a POST API with path parameter and request body through openAPI spec.

```<code>"/v2/{lang}/subject": {
  "post": {
    "parameters": [
        {
          "name": "lang",
          "in": "path",
          "required": true,
          "type": "string"
        },
        {
          "in": "body",
          "name": "subject",
          "required": true,
          "schema": {
            "$ref": "#/definitions/subject"
          }
        }
      ],
    "requestBody": {
      "content": {
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/subject"
          }
        }
      },
      "required": true
    },
    "x-amazon-apigateway-request-validator" : "all",
    .....
   }
</code>```

I want to validate path param and request body at APIGW. Unfortunately, 1 test case is failing.

If I try accessing API with missing lang, ex: https://apigwsampleurl.com/v2/subject, AWS APIGW is throwing Missing Authentication Token error.

How this case should be handled in the configuration?

答:
If the path is incorrect, there won't be an API Gateway resource on the back end to hit so any validation on that path would need to happen client-side.
Path parameters are validated only when they exist.</p>

Body:
I created a POST API with path parameter and request body through openAPI spec.

"/v2/{lang}/subject": {
  "post": {
    "parameters": [
        {
          "name": "lang",
          "in": "path",
          "required": true,
          "type": "string"
        },
        {
          "in": "body",
          "name": "subject",
          "required": true,
          "schema": {
            "$ref": "#/definitions/subject"
          }
        }
      ],
    "requestBody": {
      "content": {
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/subject"
          }
        }
      },
      "required": true
    },
    "x-amazon-apigateway-request-validator" : "all",
    .....
   }

I want to validate path param and request body at APIGW. Unfortunately, 1 test case is failing.

If I try accessing API with missing lang, ex: https://apigwsampleurl.com/v2/subject, AWS APIGW is throwing Missing Authentication Token error.

How this case should be handled in the configuration?


问:
How to upload files with graphql-java?
I can't find out how to upload files if i use graphql-java, can someone show me a demo? I will be appreciated!

reference :  https://github.com/graphql-java-kickstart/graphql-java-tools/issues/240

I tried it in springboot by using graphql-java-kickstart graphql-java-tools, but it didn't work

```<code>@Component
public class FilesUpload implements GraphQLMutationResolver {

    public Boolean testMultiFilesUpload(List<Part> parts, DataFetchingEnvironment env) {
        // get file parts from DataFetchingEnvironment, the parts parameter is not used
        List<Part> attchmentParts = env.getArgument("files");
        System.out.println(attchmentParts);
        return true;
    }
}
</code>```

this is my schema

```<code>type Mutation {
    testSingleFileUpload(file: Upload): UploadResult
}
</code>```

I expect this resolver can print attchmentParts,so i can get the file part.

答:
Since there is no data type for bytes I decided to use the String type sending the data in base64. I explain, schema first:

```<code>type Mutation{
  uploadCSV(filedatabase64: String!): Boolean
}
</code>```

spring boot:

```<code>public DataFetcher<Boolean> uploadCSV() {
    return dataFetchingEnvironment -> {
        String input= dataFetchingEnvironment.getArgument("filedatabase64");
        byte[] bytes = Base64.getDecoder().decode(input);
        //in my case is textfile:
        String strCSV = new String(bytes);
        //....
        return true;
    };
}
</code>```

Http Client sender, for example in python3:

```<code>import requests
import base64
import json

with open('myfile.csv', 'r',encoding='utf-8') as file:
    content = file.read().rstrip()
file.close()

base64data = base64.b64encode(content.encode()).decode()
url = 'https://www.misite/graphql/'
query = "mutation{uploadCSV(filedatabase64:\""+base64data+"\")}"
r = requests.post(url, json={'query': query})
print("response " + r.status_code + " " + r.text)

</code>```

about base64 encoding/decoding in java this article is helpful: https://www.baeldung.com/java-base64-encode-and-decode

Title: How to upload files with graphql-java?

Body:
I can't find out how to upload files if i use graphql-java, can someone show me a demo? I will be appreciated!

reference :  https://github.com/graphql-java-kickstart/graphql-java-tools/issues/240

I tried it in springboot by using graphql-java-kickstart graphql-java-tools, but it didn't work

@Component
public class FilesUpload implements GraphQLMutationResolver {

    public Boolean testMultiFilesUpload(List<Part> parts, DataFetchingEnvironment env) {
        // get file parts from DataFetchingEnvironment, the parts parameter is not used
        List<Part> attchmentParts = env.getArgument("files");
        System.out.println(attchmentParts);
        return true;
    }
}

this is my schema

type Mutation {
    testSingleFileUpload(file: Upload): UploadResult
}

I expect this resolver can print attchmentParts,so i can get the file part.

Body:
Since there is no data type for bytes I decided to use the String type sending the data in base64. I explain, schema first:

type Mutation{
  uploadCSV(filedatabase64: String!): Boolean
}

spring boot:

public DataFetcher<Boolean> uploadCSV() {
    return dataFetchingEnvironment -> {
        String input= dataFetchingEnvironment.getArgument("filedatabase64");
        byte[] bytes = Base64.getDecoder().decode(input);
        //in my case is textfile:
        String strCSV = new String(bytes);
        //....
        return true;
    };
}

Http Client sender, for example in python3:

import requests
import base64
import json

with open('myfile.csv', 'r',encoding='utf-8') as file:
    content = file.read().rstrip()
file.close()

base64data = base64.b64encode(content.encode()).decode()
url = 'https://www.misite/graphql/'
query = "mutation{uploadCSV(filedatabase64:\""+base64data+"\")}"
r = requests.post(url, json={'query': query})
print("response " + r.status_code + " " + r.text)

about base64 encoding/decoding in java this article is helpful: https://www.baeldung.com/java-base64-encode-and-decode


问:
how to fetch reset password api in front-end Node js
I'm student in web development. Currently, I'm trying to build a basic project, where I'm stack in implementing reset password feature, I really need help in how fetching reset password API in front-end using Axios. In short, the reset password API that I implemented works fine on Postman, but whenever I tried to pass in front-end and fetch the API in order to enable users to enter their new password and passwordValidation I kinda lost, below I share my code snippets:

backend code reset password

resetPassword = async(req, res) => {
  try {
    // Step 1: Get user based on the token
    const validateHashedToken = crypto
                              .createHash('sha256')
                              .update(req.params.token)
                              .digest('hex');

    const user = await User.findOne(
                {
                  passwordResetToken: validateHashedToken,
                  passwordResetExpires: { $gt: Date.now() }
                });

    user.password = req.body.password;
    user.passwordValidation = req.body.passwordValidation;
    user.passwordResetToken = undefined;
    user.passwordResetExpires = undefined;
    await user.save();

    // Step 3: Update the "passwordChangedAt" date
    // Step 4: Log the user in and send a JWT
    genResJWT(user, 200, res);

  } catch (error) {
    console.log('error', error)
  }
};
```
<p>Routes:</p>
<pre class="lang-js prettyprint-override"><code>router
  .route('/api/v1/users/resetpassword/:token')
  .get(viewsController.getResetPasswordUrl)
  .patch(viewsController.resetpassword);
</code>```

controllers

exports.getResetPasswordUrl = async(req, res) => {
  try {
    const { token } = req.params.token;
    const validToken = await User.findOne(
      {
        passwordResetToken: token
      }
    );

    res.status(200).render('resetPassword',
      {
    title: 'resetpassword',
    token: validToken
      });
  } catch (error) {
    console.log(error);
  }
};

exports.resetpassword = (req, res) => {
  // I'm stack here and I really need help
  res.status(200).render('profile', {
    title: 'reset password successfuly'
  });
};
```
<p>front-end fetching api code:</p>
<pre class="lang-js prettyprint-override"><code>import axios from 'axios';

export const resetPassword = async (password, passwordValidation) => {
  try {
    const res = await axios({
      method: 'PATCH',
      url:
        `http://127.0.0.1:3000/api/v1/users/resetpassword/:token`,
      data: {
        password,
        passwordValidation
      }
    });

    if (res.data.status === 'success') {
      window.setTimeout(() => {
    location.replace('/me');
      }, 500);
    }
  } catch (error) {
    console.log('error', error.response.data.message);
  }
};
</code>```

答:
I fixed my issue with the following steps:

1- Use only GET request in my '/resetpassword/:token' route and submit the PATCH request with Axios.

2- Pass the 'token' along with the 'password' and the 'passwordValidation' as input data in the PATCH request.

3- create a hidden input within the 'resetPassword' form in order to submit the 'token' with the password and the 'passwordValidation' whenever users confirm their updated password.

Below is my code snippet in order to explain how goes the solution:

Routes:

router.get(
  '/resetpassword/:token',
  viewsController.resetPassword
  )
```
<p>controllers</p>
<pre class="lang-js prettyprint-override"><code>exports.resetPassword = (req, res) => {
  const token = req.params.token;
  res.status(200).render('/login', {
    title: 'reset password successfuly', { token }
  });
};
</code>```

front-end fetching API code:

import axios from 'axios';

export const resetPassword = async (password, passwordValidation, token) => {
  try {
    const res = await axios({
      method: 'PATCH',
      url:
        `/api/v1/users/resetpassword/${token}`,
      data: {
        password,
        passwordValidation
      }
    });

    if (res.data.status === 'success') {
      window.setTimeout(() => {
        location.assign('/login');
      }, 1000);
    }
  } catch (error) {
    console.log('error', error.response.data.message);
  }
};
```
<p>the resetPassword form:</p>
<pre class="lang-js prettyprint-override"><code>extends goaheadtravel

block content
  main.main
    .resetpassword-form
      h2.heading-secondary.ma-bt-lg Please enter a new password and validate it
      form.form.resetpassword--form
        .form__group.ma-bt-md
          label.form__label(for='password') Password
          input#password.form__input(type='password' placeholder='••••••••' required='' minlength='8')
        .form__group.ma-bt-md
          label.form__label(for='passwordValidation') Confirm password
          input#passwordValidation.form__input(type='password' placeholder='••••••••' required='' minlength='8')
          input#resetToken(type='hidden' value=`${token}`)
        .form__group.right
          button.btn.btn--green Confirm new password
</code>```

Hope that my solution will help other developers!

Body:
I'm student in web development. Currently, I'm trying to build a basic project, where I'm stack in implementing reset password feature, I really need help in how fetching reset password API in front-end using Axios. In short, the reset password API that I implemented works fine on Postman, but whenever I tried to pass in front-end and fetch the API in order to enable users to enter their new password and passwordValidation I kinda lost, below I share my code snippets:

backend code reset password

resetPassword = async(req, res) => {
  try {
    // Step 1: Get user based on the token
    const validateHashedToken = crypto
                              .createHash('sha256')
                              .update(req.params.token)
                              .digest('hex');

    const user = await User.findOne(
                {
                  passwordResetToken: validateHashedToken,
                  passwordResetExpires: { $gt: Date.now() }
                });

    user.password = req.body.password;
    user.passwordValidation = req.body.passwordValidation;
    user.passwordResetToken = undefined;
    user.passwordResetExpires = undefined;
    await user.save();

    // Step 3: Update the "passwordChangedAt" date
    // Step 4: Log the user in and send a JWT
    genResJWT(user, 200, res);

  } catch (error) {
    console.log('error', error)
  }
};

Routes:

router
  .route('/api/v1/users/resetpassword/:token')
  .get(viewsController.getResetPasswordUrl)
  .patch(viewsController.resetpassword);

controllers

exports.getResetPasswordUrl = async(req, res) => {
  try {
    const { token } = req.params.token;
    const validToken = await User.findOne(
      {
        passwordResetToken: token
      }
    );

    res.status(200).render('resetPassword',
      {
    title: 'resetpassword',
    token: validToken
      });
  } catch (error) {
    console.log(error);
  }
};

exports.resetpassword = (req, res) => {
  // I'm stack here and I really need help
  res.status(200).render('profile', {
    title: 'reset password successfuly'
  });
};

front-end fetching api code:

import axios from 'axios';

export const resetPassword = async (password, passwordValidation) => {
  try {
    const res = await axios({
      method: 'PATCH',
      url:
        `http://127.0.0.1:3000/api/v1/users/resetpassword/:token`,
      data: {
        password,
        passwordValidation
      }
    });

    if (res.data.status === 'success') {
      window.setTimeout(() => {
    location.replace('/me');
      }, 500);
    }
  } catch (error) {
    console.log('error', error.response.data.message);
  }
};

Body:
I fixed my issue with the following steps:

1- Use only GET request in my '/resetpassword/:token' route and submit the PATCH request with Axios.

2- Pass the 'token' along with the 'password' and the 'passwordValidation' as input data in the PATCH request.

3- create a hidden input within the 'resetPassword' form in order to submit the 'token' with the password and the 'passwordValidation' whenever users confirm their updated password.

Below is my code snippet in order to explain how goes the solution:

Routes:

router.get(
  '/resetpassword/:token',
  viewsController.resetPassword
  )

controllers

exports.resetPassword = (req, res) => {
  const token = req.params.token;
  res.status(200).render('/login', {
    title: 'reset password successfuly', { token }
  });
};

front-end fetching API code:

import axios from 'axios';

export const resetPassword = async (password, passwordValidation, token) => {
  try {
    const res = await axios({
      method: 'PATCH',
      url:
        `/api/v1/users/resetpassword/${token}`,
      data: {
        password,
        passwordValidation
      }
    });

    if (res.data.status === 'success') {
      window.setTimeout(() => {
        location.assign('/login');
      }, 1000);
    }
  } catch (error) {
    console.log('error', error.response.data.message);
  }
};

the resetPassword form:

extends goaheadtravel

block content
  main.main
    .resetpassword-form
      h2.heading-secondary.ma-bt-lg Please enter a new password and validate it
      form.form.resetpassword--form
        .form__group.ma-bt-md
          label.form__label(for='password') Password
          input#password.form__input(type='password' placeholder='••••••••' required='' minlength='8')
        .form__group.ma-bt-md
          label.form__label(for='passwordValidation') Confirm password
          input#passwordValidation.form__input(type='password' placeholder='••••••••' required='' minlength='8')
          input#resetToken(type='hidden' value=`${token}`)
        .form__group.right
          button.btn.btn--green Confirm new password

Hope that my solution will help other developers!


问:
Add css style to django ckeditor
I'm using django ckeditor

I can add and edit HTML tags, but can't add CSS styles

Is there any way to add CSS style to the content?

答:
You can add 'allowedContent': True to your CKEDITOR_CONFIGS, in the settings.py file:

CKEDITOR_CONFIGS = {
    'default': {
        # ... your default config...
        'allowedContent': True
    }
}
```

You can see a full config example in the docs: https://django-ckeditor.readthedocs.io/en/latest/#example-ckeditor-configuration

Title: Add css style to django ckeditor

Body:
You can add 'allowedContent': True to your CKEDITOR_CONFIGS, in the settings.py file:

CKEDITOR_CONFIGS = {
    'default': {
        # ... your default config...
        'allowedContent': True
    }
}

You can see a full config example in the docs: https://django-ckeditor.readthedocs.io/en/latest/#example-ckeditor-configuration


问:
CUDA(GPU) as OpenCV backend
Am trying to use CUDA as backend for dnn module provided in opencv-4.1.1 , I have build opencv with CUDA enabled, nvidia drivers and CUDA is properly placed on system, here am using manjaro as development platform.

am trying to load pre-trained YOLOv3 weights using cv2.dnn module,

```<code>net = cv2.dnn.readNetFromDarknet('yolov3.cfg', 'yolov3.weights')
</code>```

But it uses CPU as defualt inference engine, but am trying to use GPU as backend IE, from offecial opencv doc, i found following

```<code>DNN_TARGET_CPU
DNN_TARGET_OPENCL
DNN_TARGET_OPENCL_FP16
DNN_TARGET_MYRIAD
DNN_TARGET_FPGA
</code>```

as target backend, but no support for direct GPU inference, so what's point of compiling opencv with CUDA if it doen't make use of GPU as underlying inferencing engine,

in order to make sure processes are runing on GPU I posted output of
  nvidia-smi ,

```<code>+-----------------------------------------------------------------------------+
| NVIDIA-SMI 430.26       Driver Version: 430.26       CUDA Version: 10.2     |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  GeForce GT 710      Off  | 00000000:01:00.0 N/A |                  N/A |
| 40%   40C    P0    N/A /  N/A |    598MiB /  1998MiB |     N/A      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID   Type   Process name                             Usage      |
|=============================================================================|
|    0                    Not Supported                                       |
+-----------------------------------------------------------------------------+
</code>```

the process id for GPU utilization is 0, clearly means that no process utilizing GPU, any guidance will be appreciated.

答:
You can use CUDA backend on OpenCV as follows.</p>
```<code># Loading trained YOLO v3 Objects Detector
network = cv2.dnn.readNetFromDarknet('yolo-coco-data/yolov3.cfg',
                                 'yolo-coco-data/yolov3.weights')

# CUDA Backend
network.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)
network.setPreferableTarget(cv2.dnn. DNN_TARGET_CUDA)

# Also you can use following code for 16 FPS(if your system supports).
#network.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA_FP16)
</code>```

Title: CUDA(GPU) as OpenCV backend

Body:
Am trying to use CUDA as backend for dnn module provided in opencv-4.1.1 , I have build opencv with CUDA enabled, nvidia drivers and CUDA is properly placed on system, here am using manjaro as development platform.

am trying to load pre-trained YOLOv3 weights using cv2.dnn module,

net = cv2.dnn.readNetFromDarknet('yolov3.cfg', 'yolov3.weights')

But it uses CPU as defualt inference engine, but am trying to use GPU as backend IE, from offecial opencv doc, i found following

DNN_TARGET_CPU
DNN_TARGET_OPENCL
DNN_TARGET_OPENCL_FP16
DNN_TARGET_MYRIAD
DNN_TARGET_FPGA

as target backend, but no support for direct GPU inference, so what's point of compiling opencv with CUDA if it doen't make use of GPU as underlying inferencing engine,

in order to make sure processes are runing on GPU I posted output of
  nvidia-smi ,

+-----------------------------------------------------------------------------+
| NVIDIA-SMI 430.26       Driver Version: 430.26       CUDA Version: 10.2     |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  GeForce GT 710      Off  | 00000000:01:00.0 N/A |                  N/A |
| 40%   40C    P0    N/A /  N/A |    598MiB /  1998MiB |     N/A      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID   Type   Process name                             Usage      |
|=============================================================================|
|    0                    Not Supported                                       |
+-----------------------------------------------------------------------------+

the process id for GPU utilization is 0, clearly means that no process utilizing GPU, any guidance will be appreciated.

Body:
You can use CUDA backend on OpenCV as follows.

# Loading trained YOLO v3 Objects Detector
network = cv2.dnn.readNetFromDarknet('yolo-coco-data/yolov3.cfg',
                                 'yolo-coco-data/yolov3.weights')

# CUDA Backend
network.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)
network.setPreferableTarget(cv2.dnn. DNN_TARGET_CUDA)

# Also you can use following code for 16 FPS(if your system supports).
#network.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA_FP16)


问:
Parsing frame-by-frame from .mov using ffmpeg
I'm trying to parse H.264 frames from a .mov file. I think I've come to the conclusion that mov.c from AVFormat-part of FFMPEG is the way to go. But mov.c is ~2600 lines of next to uncommented code. I'm looking for examples of usage of FFMPEG, especially parsing the structure of any file type. doesn't matter if it is MPEG4 or Quicktime Movie since they are quite similar in structure.

if there are no existing examples (I can't find any) maybe someone has used it and can give me a couple of lines of code, or explain how to get started?

What I'm trying to do:
i use AVCaptureSession to capture samples from the video camera, these samples are then encoded in H264 and written to file with the help of AVAssetsWriter, AVAssetsWriterInput and AVAssetsWriterInputPixelBufferAdaptor. The reason for which is that I can't access the hardware H264 encoding directly since apple won't allow this. What I now need to do (I think not sure) is parse out:

The "mdat"-atom (Movie data, there might be more than one i think) from the .mov file.
then the "vide"-atom and then within the vide-atom (Video data sample, there might be more than one). I think there will be several atoms which i belive is the frames. these will be of type "avc1" (that's the type for H264). Please correct me in this because i'm quite sure that i havn't gotten all of this correctly yet.

my question then is, how will i go about parsing out the single frames. I've been reading the documentation and looked at iFrameExtractor (which is not very helpful since it decodes the frames). I think I've understood it correctly when I'm supposed to use mov.c from FFMPEG-AVFormat but I'm not sure.

Edit:
I'm now trying like this:

I run the slightly reduced init function i iFrameExtractor which finds the videostream in the .mov-file.

I get the data for the frame like this:

```<code>AVPacket packet;
av_read_frame(pFormatCtx, &packet);
NSData *frame;
if(packet.stream_index == videoStream){
    frame = [NSData dataWithBytes:packet.data length:packet.size];
}
videoStream++;
av_free_packet(&packet);
return frame;
</code>```

i then pass it to a subclass of NSOperation where it is retained in wait for upload.
but i receive a EXC_BAD_ACC, am I doing something wrong when copying the data from the frame? any ideas. i get the EXC_... when I try to set the class variable NSData* frame using its (nonatomic,retain)-property. (it says EXC_BAD_ACC on the synthesize row)

答:
i use the following to parse each frame from the mov file.

```<code>-(NSData *)nextFrame {
    AVPacket packet;
    NSData *frame = nil;

    while(!frame && av_read_frame(pFormatCtx, &packet)>=0) {

        if(packet.stream_index == streamNo) {
            frame = [[[NSData alloc] initWithBytes:packet.data length:packet.size] autorelease];
        }
        av_free_packet(&packet);
    }
    return frame;
}
</code>```

although watch out since av_read_frame does not verify the frames, that is done in the decoding step. this means that the "frames" returned might contain extra information which are not part of the actual frame.

to init the AVFormatContext *pFormatCtx and AVCodecContext *pCodecCtx I use this code (which I believe is derived from Martin Böhme's example code):

```<code>    AVCodec *pCodec;

    // Register all formats and codecs
    av_register_all();

    // Open video file
    if(avformat_open_input(&pFormatCtx, [moviePath cStringUsingEncoding:NSASCIIStringEncoding], NULL, NULL)!=0)
        goto initError; // Couldn't open file

    // Retrieve stream information
    if(avformat_find_stream_info(pFormatCtx,NULL)<0)
        goto initError; // Couldn't find stream information

    // Find the video stream
    streamNo = -1;
    for(int i=0; i<pFormatCtx->nb_streams; i++){
        if(pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO)
        {
            streamNo = i;
            break;
        }
    }
    if(streamNo == -1)
        goto initError; // Didn't find a video stream

    // Get a pointer to the codec context for the video stream
    pCodecCtx=pFormatCtx->streams[streamNo]->codec;

    // Find the decoder for the video stream
    pCodec=avcodec_find_decoder(pCodecCtx->codec_id);
    if(pCodec==NULL)
        goto initError; // Codec not found

    // Open codec
    if(avcodec_open2(pCodecCtx, pCodec, NULL)<0)
        goto initError; // Could not open codec

    return self;

initError:
    NSLog(@"initError in VideoFrameExtractor");
    [self release];
    return nil;
</code>```

hope this helps someone in the future.

Body:
I'm trying to parse H.264 frames from a .mov file. I think I've come to the conclusion that mov.c from AVFormat-part of FFMPEG is the way to go. But mov.c is ~2600 lines of next to uncommented code. I'm looking for examples of usage of FFMPEG, especially parsing the structure of any file type. doesn't matter if it is MPEG4 or Quicktime Movie since they are quite similar in structure.

if there are no existing examples (I can't find any) maybe someone has used it and can give me a couple of lines of code, or explain how to get started?

What I'm trying to do:
i use AVCaptureSession to capture samples from the video camera, these samples are then encoded in H264 and written to file with the help of AVAssetsWriter, AVAssetsWriterInput and AVAssetsWriterInputPixelBufferAdaptor. The reason for which is that I can't access the hardware H264 encoding directly since apple won't allow this. What I now need to do (I think not sure) is parse out:

The "mdat"-atom (Movie data, there might be more than one i think) from the .mov file.
then the "vide"-atom and then within the vide-atom (Video data sample, there might be more than one). I think there will be several atoms which i belive is the frames. these will be of type "avc1" (that's the type for H264). Please correct me in this because i'm quite sure that i havn't gotten all of this correctly yet.

my question then is, how will i go about parsing out the single frames. I've been reading the documentation and looked at iFrameExtractor (which is not very helpful since it decodes the frames). I think I've understood it correctly when I'm supposed to use mov.c from FFMPEG-AVFormat but I'm not sure.

Edit:
I'm now trying like this:

I run the slightly reduced init function i iFrameExtractor which finds the videostream in the .mov-file.

I get the data for the frame like this:

AVPacket packet;
av_read_frame(pFormatCtx, &packet);
NSData *frame;
if(packet.stream_index == videoStream){
    frame = [NSData dataWithBytes:packet.data length:packet.size];
}
videoStream++;
av_free_packet(&packet);
return frame;

i then pass it to a subclass of NSOperation where it is retained in wait for upload.
but i receive a EXC_BAD_ACC, am I doing something wrong when copying the data from the frame? any ideas. i get the EXC_... when I try to set the class variable NSData* frame using its (nonatomic,retain)-property. (it says EXC_BAD_ACC on the synthesize row)

Body:
i use the following to parse each frame from the mov file.

-(NSData *)nextFrame {
    AVPacket packet;
    NSData *frame = nil;

    while(!frame && av_read_frame(pFormatCtx, &packet)>=0) {

        if(packet.stream_index == streamNo) {
            frame = [[[NSData alloc] initWithBytes:packet.data length:packet.size] autorelease];
        }
        av_free_packet(&packet);
    }
    return frame;
}

although watch out since av_read_frame does not verify the frames, that is done in the decoding step. this means that the "frames" returned might contain extra information which are not part of the actual frame.

to init the AVFormatContext *pFormatCtx and AVCodecContext *pCodecCtx I use this code (which I believe is derived from Martin Böhme's example code):

    AVCodec *pCodec;

    // Register all formats and codecs
    av_register_all();

    // Open video file
    if(avformat_open_input(&pFormatCtx, [moviePath cStringUsingEncoding:NSASCIIStringEncoding], NULL, NULL)!=0)
        goto initError; // Couldn't open file

    // Retrieve stream information
    if(avformat_find_stream_info(pFormatCtx,NULL)<0)
        goto initError; // Couldn't find stream information

    // Find the video stream
    streamNo = -1;
    for(int i=0; i<pFormatCtx->nb_streams; i++){
        if(pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO)
        {
            streamNo = i;
            break;
        }
    }
    if(streamNo == -1)
        goto initError; // Didn't find a video stream

    // Get a pointer to the codec context for the video stream
    pCodecCtx=pFormatCtx->streams[streamNo]->codec;

    // Find the decoder for the video stream
    pCodec=avcodec_find_decoder(pCodecCtx->codec_id);
    if(pCodec==NULL)
        goto initError; // Codec not found

    // Open codec
    if(avcodec_open2(pCodecCtx, pCodec, NULL)<0)
        goto initError; // Could not open codec

    return self;

initError:
    NSLog(@"initError in VideoFrameExtractor");
    [self release];
    return nil;

hope this helps someone in the future.


问:
every time loop is finished return something C#
hi I Want to loop over a data and each time it's iterating return something. I know if if use return inside loop the loop will be finished is there any other way. Thanks for helping.

some thing like this

reply to kevinSpaceyIsKeyserSöze
no it's like a list of data when user clicks post it should remove the ones which are finished from list or send a msg like remove data where id == id and i could remove it from list in angular front-end

let me show you the real code what i want

```<code> foreach (var item in data)
        {
            var FileName = Guid.NewGuid().ToString() + "_" + item.CustomerName + ".pdf";
            var filePath = root + FileName;
            using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
            {
                // create pdf file
                var doc = new iTextSharp.text.Document(PageSize.A4.Rotate());
                PdfWriter.GetInstance(doc, new FileStream(filePath, FileMode.Create));
                doc.Open();
                doc.Add(new iTextSharp.text.Paragraph(item.Data));
                doc.Close();
                // create pdf file ended

                // send email
                sendEmail(item.CustomerName, filePath);
                // in here i want to send back a response that the file with id item.id is created so remove it from table
            }
        }
</code>```

答:
if you want to remove multiply rows from table make an array of succesfuly created files

and then return this array

elements of array will be item.id

Body:
hi I Want to loop over a data and each time it's iterating return something. I know if if use return inside loop the loop will be finished is there any other way. Thanks for helping.

some thing like this

reply to kevinSpaceyIsKeyserSöze
no it's like a list of data when user clicks post it should remove the ones which are finished from list or send a msg like remove data where id == id and i could remove it from list in angular front-end

let me show you the real code what i want

 foreach (var item in data)
        {
            var FileName = Guid.NewGuid().ToString() + "_" + item.CustomerName + ".pdf";
            var filePath = root + FileName;
            using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
            {
                // create pdf file
                var doc = new iTextSharp.text.Document(PageSize.A4.Rotate());
                PdfWriter.GetInstance(doc, new FileStream(filePath, FileMode.Create));
                doc.Open();
                doc.Add(new iTextSharp.text.Paragraph(item.Data));
                doc.Close();
                // create pdf file ended

                // send email
                sendEmail(item.CustomerName, filePath);
                // in here i want to send back a response that the file with id item.id is created so remove it from table
            }
        }


问:
Export a MySQL Database to SQLite Database
Please help me with exporting a MySQL database into a SQLite database.</p>

答:
The following Website has an online tool to convert
Convert MySQL to SQLite online
https://www.rebasedata.com/convert-mysql-to-sqlite-online</p>


问:
How to remove sensitive data from a file in github history
I am using a shared github repository to collaborate on a project. Because i am an idiot, I committed and pushed a script file containing a password which I don't want to share (Yes, i can change the password, but I would like to remove it anyway!).

Is there any way to revert the commits from github's history, remove the password locally and then recommit and push the updated files? I do not want to remove the file completely, and I would rather not lose the commit history on github.

(This question
How can I completely remove a file from a git repository?
shows how to remove a sensitive file, but not how to edit sensitive data from a file, so this is not a duplicate)

答:
If your content had already been pushed to GitHub, after scrubbing the repository with git filter-repo or bfg and force-pushing the cleaned up repository, reach out to GitHub Support. They will then make sure all references to the commit and it's files are deleted from issue references, pull requests and the cached data GitHub keeps. Only then the password will really be gone from your repositories.

If anyone forked your repository and synced in the sensitive commit, then there is no way to force GitHub to clean up their repositories too. You'll need to ask each owner of the forks to go through the same process.

Consider your password burned. Since your password is out there and since it will take some time to be fully removed, there is ample time for a bad actor to scrape your current repo state and store the password for later use. Always reset the password. Do not fall for the trap of thinking you may still be safe.

Make sure any other contributors on your project clone a fresh copy or rebase there local changes on the fixed repository. Removing data from history will cause the commit-ids of all subsequent commits to change.