问:
Spawning multiple instances of the same object concurrently in python
I'm a beginner programmer who is starting with python and I'm starting out by making a game in pygame.
The game basically spawns circles at random positions and when clicked, it gives you points.

Recently I've hit a roadblock when I want to spawn multiple instances of the same object (in this case circles) at the same time.
I've tried stuff like sleep() and some other code related to counters, but it always results in the next circle spawned overriding the previous one (i.e the program spawns circle 1, but when circle 2 comes in, circle 1 disappears).

Does anyone know a solution to this? I would really appreciate your help!

import pygame
import random
import time

pygame.init()

window = pygame.display.set_mode((800,600))

class circle():
    def __init__(self, color, x, y, radius, width,):
        self.color = color
        self.x = x
        self.y = y
        self.radius = radius
        self.width = width

    def draw(self, win, outline=None):
        pygame.draw.circle(win, self.color, (self.x, self.y, self.radius, self.width), 0)

run=True
while run:
    window.fill((0, 0, 0))
    pygame.draw.circle(window, (255, 255, 255), (random.randint(0, 800),random.randint(0, 600)), 20, 20)
    time.sleep(1)
    pygame.display.update()

    for event in pygame.event.get():

        if event.type == pygame.QUIT:
            run=False
            pygame.quit()
            quit()
```

答:
It does not work that way. time.sleep, pygame.time.wait() or pygame.time.delay is not the right way to control time and gameplay within an application loop. The game does not respond while you wait. The application loop runs continuously. You have to measure the time in the loop and spawn the objects according to the elapsed time.

pygame.Surface.fill clears the entire screen. Add the newly created objects to a list. Redraw all of the objects and the entire scene in each frame.

See also Time, timer event and clock

You have 2 options. Use pygame.time.get_ticks() to measure the time. Define a time interval after which a new object should appear. Create an object when the point in time is reached and calculate the point in time for the next object:

object_list = []
time_interval = 500 # 500 milliseconds == 0.1 seconds
next_object_time = 0

while run:
    # [...]

    current_time = pygame.time.get_ticks()
    if current_time > next_object_time:
        next_object_time += time_interval
        object_list.append(Object())
```
<p>Minimal example:</p>
<p><kbd><img src="https://i.stack.imgur.com/5jD0C.png" alt="" /> repl.it/@Rabbid76/PyGame-TimerSpawnObjects</kbd></p>
<p><img src="https://i.stack.imgur.com/cVQze.gif" alt="" /></p>
<pre class="lang-py prettyprint-override"><code>import pygame, random
pygame.init()
window = pygame.display.set_mode((300, 300))

class Object:
    def __init__(self):
        self.radius = 50
        self.x = random.randrange(self.radius, window.get_width()-self.radius)
        self.y = random.randrange(self.radius, window.get_height()-self.radius)
        self.color = pygame.Color(0)
        self.color.hsla = (random.randrange(0, 360), 100, 50, 100)

object_list = []
time_interval = 200 # 200 milliseconds == 0.2 seconds
next_object_time = 0

run = True
clock = pygame.time.Clock()
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    current_time = pygame.time.get_ticks()
    if current_time > next_object_time:
        next_object_time += time_interval
        object_list.append(Object())

    window.fill(0)
    for object in object_list[:]:
        pygame.draw.circle(window, object.color, (object.x, object.y), round(object.radius))
        object.radius -= 0.2
        if object.radius < 1:
            object_list.remove(object)
    pygame.display.flip()

pygame.quit()
exit()
</code>```

The other option is to use the pygame.event module. Use pygame.time.set_timer() to repeatedly create a USEREVENT in the event queue. The time has to be set in milliseconds. e.g.:

object_list = []
time_interval = 500 # 500 milliseconds == 0.1 seconds
timer_event = pygame.USEREVENT+1
pygame.time.set_timer(timer_event, time_interval)
```
<p>Note, in pygame customer events can be defined. Each event needs a unique id. The ids for the user events have to be between <code>pygame.USEREVENT</code> (24) and <code>pygame.NUMEVENTS</code> (32). In this case <code>pygame.USEREVENT+1</code> is the event id for the timer event.</p>
<p>Receive the event in the event loop:</p>
<pre class="lang-py prettyprint-override"><code>while run:
    for event in pygame.event.get():
        if event.type == timer_event:
            object_list.append(Object())
</code>```

The timer event can be stopped by passing 0 to the time argument of pygame.time.set_timer.

Minimal example:

 repl.it/@Rabbid76/PyGame-TimerEventSpawn

import pygame, random
pygame.init()
window = pygame.display.set_mode((300, 300))

class Object:
    def __init__(self):
        self.radius = 50
        self.x = random.randrange(self.radius, window.get_width()-self.radius)
        self.y = random.randrange(self.radius, window.get_height()-self.radius)
        self.color = pygame.Color(0)
        self.color.hsla = (random.randrange(0, 360), 100, 50, 100)

object_list = []
time_interval = 200 # 200 milliseconds == 0.2 seconds
timer_event = pygame.USEREVENT+1
pygame.time.set_timer(timer_event, time_interval)

run = True
clock = pygame.time.Clock()
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        elif event.type == timer_event:
            object_list.append(Object())

    window.fill(0)
    for object in object_list[:]:
        pygame.draw.circle(window, object.color, (object.x, object.y), round(object.radius))
        object.radius -= 0.2
        if object.radius < 1:
            object_list.remove(object)
    pygame.display.flip()

pygame.quit()
exit()
```

Body:
It does not work that way. time.sleep, pygame.time.wait() or pygame.time.delay is not the right way to control time and gameplay within an application loop. The game does not respond while you wait. The application loop runs continuously. You have to measure the time in the loop and spawn the objects according to the elapsed time.

pygame.Surface.fill clears the entire screen. Add the newly created objects to a list. Redraw all of the objects and the entire scene in each frame.

See also Time, timer event and clock

You have 2 options. Use pygame.time.get_ticks() to measure the time. Define a time interval after which a new object should appear. Create an object when the point in time is reached and calculate the point in time for the next object:

object_list = []
time_interval = 500 # 500 milliseconds == 0.1 seconds
next_object_time = 0

while run:
    # [...]

    current_time = pygame.time.get_ticks()
    if current_time > next_object_time:
        next_object_time += time_interval
        object_list.append(Object())

Minimal example:

 repl.it/@Rabbid76/PyGame-TimerSpawnObjects

import pygame, random
pygame.init()
window = pygame.display.set_mode((300, 300))

class Object:
    def __init__(self):
        self.radius = 50
        self.x = random.randrange(self.radius, window.get_width()-self.radius)
        self.y = random.randrange(self.radius, window.get_height()-self.radius)
        self.color = pygame.Color(0)
        self.color.hsla = (random.randrange(0, 360), 100, 50, 100)

object_list = []
time_interval = 200 # 200 milliseconds == 0.2 seconds
next_object_time = 0

run = True
clock = pygame.time.Clock()
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    current_time = pygame.time.get_ticks()
    if current_time > next_object_time:
        next_object_time += time_interval
        object_list.append(Object())

    window.fill(0)
    for object in object_list[:]:
        pygame.draw.circle(window, object.color, (object.x, object.y), round(object.radius))
        object.radius -= 0.2
        if object.radius < 1:
            object_list.remove(object)
    pygame.display.flip()

pygame.quit()
exit()

The other option is to use the pygame.event module. Use pygame.time.set_timer() to repeatedly create a USEREVENT in the event queue. The time has to be set in milliseconds. e.g.:

object_list = []
time_interval = 500 # 500 milliseconds == 0.1 seconds
timer_event = pygame.USEREVENT+1
pygame.time.set_timer(timer_event, time_interval)

Note, in pygame customer events can be defined. Each event needs a unique id. The ids for the user events have to be between pygame.USEREVENT (24) and pygame.NUMEVENTS (32). In this case pygame.USEREVENT+1 is the event id for the timer event.

Receive the event in the event loop:

while run:
    for event in pygame.event.get():
        if event.type == timer_event:
            object_list.append(Object())

The timer event can be stopped by passing 0 to the time argument of pygame.time.set_timer.

Minimal example:

 repl.it/@Rabbid76/PyGame-TimerEventSpawn

import pygame, random
pygame.init()
window = pygame.display.set_mode((300, 300))

class Object:
    def __init__(self):
        self.radius = 50
        self.x = random.randrange(self.radius, window.get_width()-self.radius)
        self.y = random.randrange(self.radius, window.get_height()-self.radius)
        self.color = pygame.Color(0)
        self.color.hsla = (random.randrange(0, 360), 100, 50, 100)

object_list = []
time_interval = 200 # 200 milliseconds == 0.2 seconds
timer_event = pygame.USEREVENT+1
pygame.time.set_timer(timer_event, time_interval)

run = True
clock = pygame.time.Clock()
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        elif event.type == timer_event:
            object_list.append(Object())

    window.fill(0)
    for object in object_list[:]:
        pygame.draw.circle(window, object.color, (object.x, object.y), round(object.radius))
        object.radius -= 0.2
        if object.radius < 1:
            object_list.remove(object)
    pygame.display.flip()

pygame.quit()
exit()


来源: stackexchange

问:
EntityFramework Core Group By with Sum
Haven't written any code in a while and I'm trying to shake the rust off by writing a small app for my kids to track the books they've read over the summer.  The DB is simple, only 3 tables. 1 for books (title, author, pages etc), 1 for reader names and 1 is the actual reading log (1 row for each book they read, foreign key relationship to book table and reader table).

Trying to use EntityFramework core to write a query that will return the total pages read by reader.  I can run this in SSMS and it works fine

```<code>select r.Name, sum(b.Pages) as PagesRead
from ReadingLog rl
inner join Readers r on rl.ReaderId = r.Id
inner join Books b on rl.BookId = b.Id
where rl.IsActive = 1
group by r.Name
</code>```

I tried writing it in EF as this:

```<code>var pagesByReader = _context.ReadingLog
                            .Where(m => m.IsActive)
                            .GroupBy(m => m.Reader.Name)
                            .Select(m => new GraphViewModel()
                                   {
                                      Reader = m.Key,
                                      PagesRead = m.Sum(b => b.Book.Pages)
                                   })
                            .ToList();
</code>```

but I get this error at runtime: ).Book.Pages' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync()

I think I'm just writing the EF query wrong but I can't figure out why.  Any help is appreciated

答:
Looks like you have m.Key in the select.  When using GroupBy, all values in a select that are not defined in the group by must be in an aggregate function.

Try changing m.Key to m.Key.First()

ContentLicense: CC BY-SA 4.0

Title: EntityFramework Core Group By with Sum

Body:
Haven't written any code in a while and I'm trying to shake the rust off by writing a small app for my kids to track the books they've read over the summer.  The DB is simple, only 3 tables. 1 for books (title, author, pages etc), 1 for reader names and 1 is the actual reading log (1 row for each book they read, foreign key relationship to book table and reader table).

Trying to use EntityFramework core to write a query that will return the total pages read by reader.  I can run this in SSMS and it works fine

select r.Name, sum(b.Pages) as PagesRead
from ReadingLog rl
inner join Readers r on rl.ReaderId = r.Id
inner join Books b on rl.BookId = b.Id
where rl.IsActive = 1
group by r.Name

I tried writing it in EF as this:

var pagesByReader = _context.ReadingLog
                            .Where(m => m.IsActive)
                            .GroupBy(m => m.Reader.Name)
                            .Select(m => new GraphViewModel()
                                   {
                                      Reader = m.Key,
                                      PagesRead = m.Sum(b => b.Book.Pages)
                                   })
                            .ToList();

but I get this error at runtime: ).Book.Pages' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync()

I think I'm just writing the EF query wrong but I can't figure out why.  Any help is appreciated


问:
cent os is reinstalling during installation in virtual box
I am trying to install cent os on virtual box and when it shows "cent os is successfully installed and ready for you to use Go ahead and reboot to start using it"  and when i press  reboot, it again start for reinstalling all over again from start.
I tried almost 7-8 times and same thing is happening.</p>

答:
When you show "cent os is successfully installed and ready for you to use Go ahead and reboot to start using it" before reboot you need to do some steps...

go to 'devices' on virtual box.

tab called 'cd/dvd devices'

uncheck the option said 'cent_os.iso'.

pop up comes click 'force
mount'
Then click reboot.
Once you see black screen,

go to 'machine' and click
'reset'.

Now you can enjoy using cent os on virtual box.


问:
Encryption of contents in compiled iOS app ( IPA )
As IPA structure is just a zipped file containing compiled codes & media contents like images & audio, how can I protect the contents from being extracted and stolen by others? Is there any encryption I can add into the IPA?</p>

答:
This answer mentions that the application is already encrypted by the time it gets onto your users' devices: Does Apple modify iOS application executables on apps submitted to the App Store?

Sorry, that's only the application binary. The other media are not encrypted, and no, there's no way to encrypt the .ipa. You could try encrypting your images and other media on your system, providing a bunch of application code to decrypt those resources when the app runs, and then your decryption code will become a part of the encrypted application binary. You can't submit an encrypted IPA though, it needs to be the file directly output from Xcode.

In response to your comment, the one I've used in the past is CommonCrypto. You can use this crypto library as a starting point.

Simple usage example of the above:

```<code>NSError *error;
NSMutableData *encryptedData = [NSMutableData dataWithContentsOfFile:pathToEncryptedFile];
NSData *decryptedData = [RNDecryptor decryptData:encryptedData
                                withPassword:@"SuperSecretDecryptionKey"
                                       error:&error];
UIImage *decryptedImage = [UIImage imageWithData:decryptedData];
</code>```

IMPORTANT NOTE HERE: IF someone was to run the strings utility on your .app on a jailbroken iphone, or even on an iPhone they have filesystem access to via USB, they will get a list of all strings declared in your app. This includes "SuperSecretDecryptionKey". So you may want to use an integer, floating-point or other constant to do on-the-fly generation of a string decryption key, or make sure that the string you use to decrypt things is exactly the same as a normal system string so no-one suspects it as the true key. Security through obscurity, in this case, is advantageous.

To encrypt/decrypt *.strings files, you should encrypt the key and value strings in some manner (maybe one which gives you hexadecimal back, or any alphanumeric characters), and when you want to access a given value, say LicenceNumber, do this:

```<code>NSError *error;
NSData *unencryptedKey = [@"LicenceNumber"
                               dataUsingEncoding:NSUTF8StringEncoding];
NSData *encryptedKey = [RNEncryptor encryptData:unencryptedKey
                                withSettings:kRNCryptorAES256Settings
                                      password:@"SuperSecretEncryptionKey"
                                         error:&error]
NSData *encryptedValue = [[NSBundle mainBundle]
                                 localizedStringForKey:[NSString
                                  stringWithUTF8String:[encryptedKey bytes]]
                                 value:@"No licence"
                                 table:@"EncryptedStringsFile"];
NSData *decryptedValue = [RNDecryptor decryptData:encryptedValue
                                withPassword:@"SuperSecretDecryptionKey"
                                       error:&error];
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This answer mentions that the application is already encrypted by the time it gets onto your users' devices: Does Apple modify iOS application executables on apps submitted to the App Store?

Sorry, that's only the application binary. The other media are not encrypted, and no, there's no way to encrypt the .ipa. You could try encrypting your images and other media on your system, providing a bunch of application code to decrypt those resources when the app runs, and then your decryption code will become a part of the encrypted application binary. You can't submit an encrypted IPA though, it needs to be the file directly output from Xcode.

In response to your comment, the one I've used in the past is CommonCrypto. You can use this crypto library as a starting point.

Simple usage example of the above:

NSError *error;
NSMutableData *encryptedData = [NSMutableData dataWithContentsOfFile:pathToEncryptedFile];
NSData *decryptedData = [RNDecryptor decryptData:encryptedData
                                withPassword:@"SuperSecretDecryptionKey"
                                       error:&error];
UIImage *decryptedImage = [UIImage imageWithData:decryptedData];

IMPORTANT NOTE HERE: IF someone was to run the strings utility on your .app on a jailbroken iphone, or even on an iPhone they have filesystem access to via USB, they will get a list of all strings declared in your app. This includes "SuperSecretDecryptionKey". So you may want to use an integer, floating-point or other constant to do on-the-fly generation of a string decryption key, or make sure that the string you use to decrypt things is exactly the same as a normal system string so no-one suspects it as the true key. Security through obscurity, in this case, is advantageous.

To encrypt/decrypt *.strings files, you should encrypt the key and value strings in some manner (maybe one which gives you hexadecimal back, or any alphanumeric characters), and when you want to access a given value, say LicenceNumber, do this:

NSError *error;
NSData *unencryptedKey = [@"LicenceNumber"
                               dataUsingEncoding:NSUTF8StringEncoding];
NSData *encryptedKey = [RNEncryptor encryptData:unencryptedKey
                                withSettings:kRNCryptorAES256Settings
                                      password:@"SuperSecretEncryptionKey"
                                         error:&error]
NSData *encryptedValue = [[NSBundle mainBundle]
                                 localizedStringForKey:[NSString
                                  stringWithUTF8String:[encryptedKey bytes]]
                                 value:@"No licence"
                                 table:@"EncryptedStringsFile"];
NSData *decryptedValue = [RNDecryptor decryptData:encryptedValue
                                withPassword:@"SuperSecretDecryptionKey"
                                       error:&error];


问:
node: command not found - in wsl bash
I install docker on my windows 10. after that I get a message that I need to download and install wsl2.

Now, when I run bash command I get wsl bash.

When I try to run node I get an error (node.exe is installed in my windows10):

```<code>DESKTOP-BVRDS:/tmp/docker-desktop-root/mnt/host/c/Users/myuser# node
bash: node: command not found
</code>```

when I run echo $PATH I get output of:

```<code>/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
</code>```

and not the windows path's. (where the node and other software installed).

How to solve this error? maybe change the default bash? to git bash? (which I don't know how)

答:
Please try below:

Open a regular command prompt (win+r then cmd)

Right-click the title bar and select Properties

Deselect "Use legacy console (requires restart)"

Now it should work either by launching the standalone app, or typing bash into a regular cmd window after restarting Command Prompt.

Title: node: command not found - in wsl bash

Body:
I install docker on my windows 10. after that I get a message that I need to download and install wsl2.

Now, when I run bash command I get wsl bash.

When I try to run node I get an error (node.exe is installed in my windows10):

DESKTOP-BVRDS:/tmp/docker-desktop-root/mnt/host/c/Users/myuser# node
bash: node: command not found

when I run echo $PATH I get output of:

/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

and not the windows path's. (where the node and other software installed).

How to solve this error? maybe change the default bash? to git bash? (which I don't know how)


问:
Error while indexing an array in google sheet
Formula1 ArrayFormula(regexextract(ArrayFormula(address(1,sequence(150,1,1,1),4)),"\D+"))

Formula2 if(and(5>=column(indirect(B2)),5<=columns(indirect(B2))+column(indirect(B2))-1),5,-1)

B2 contains range E1:G4

Formula1 & 2 are working perfectly fine but when we combine both as mentioned below there is an error: "Function INDEX parameter 2 value is -1. Valid values are between 0 and 150 inclusive."

```<code>index(ArrayFormula(regexextract(ArrayFormula(address(1,sequence(150,1,1,1),4)),"\D+")),if(and(5>=column(indirect(B2)),5<=columns(indirect(B2))+column(indirect(B2))-1),5,-1))
</code>```

I have deliberately used -1 which is not a valued value for index parameter 2 so that it gives error when "If" condition is unfulfilled and I can omit whole result with iferror function, but when condition is fulfilled then it shouldn't give any error. Any work around will not help me because I need to use this formula component in another complex formula.

Google Sheet with function

Thanks in advance.

答:
try:</p>

```<code>=ARRAYFORMULA(INDEX(REGEXEXTRACT(ADDRESS(1, SEQUENCE(150, 1, 1, 1), 4), "\D+"),
 IF((5>=COLUMN(INDIRECT(B2)))*(5<=COLUMNS(INDIRECT(B2))+COLUMN(INDIRECT(B2))-1), 5, -1)))
</code>```

Body:
Formula1 ArrayFormula(regexextract(ArrayFormula(address(1,sequence(150,1,1,1),4)),"\D+"))

Formula2 if(and(5>=column(indirect(B2)),5<=columns(indirect(B2))+column(indirect(B2))-1),5,-1)

B2 contains range E1:G4

Formula1 & 2 are working perfectly fine but when we combine both as mentioned below there is an error: "Function INDEX parameter 2 value is -1. Valid values are between 0 and 150 inclusive."

index(ArrayFormula(regexextract(ArrayFormula(address(1,sequence(150,1,1,1),4)),"\D+")),if(and(5>=column(indirect(B2)),5<=columns(indirect(B2))+column(indirect(B2))-1),5,-1))

I have deliberately used -1 which is not a valued value for index parameter 2 so that it gives error when "If" condition is unfulfilled and I can omit whole result with iferror function, but when condition is fulfilled then it shouldn't give any error. Any work around will not help me because I need to use this formula component in another complex formula.

Google Sheet with function

Thanks in advance.

Body:
try:

=ARRAYFORMULA(INDEX(REGEXEXTRACT(ADDRESS(1, SEQUENCE(150, 1, 1, 1), 4), "\D+"),
 IF((5>=COLUMN(INDIRECT(B2)))*(5<=COLUMNS(INDIRECT(B2))+COLUMN(INDIRECT(B2))-1), 5, -1)))


问:
MongoEngine - how to make sure document has been saved?
After defining a document, creating an instance and calling the save method on that instance, what is the best way to make sure the saving of the document succeeds?

Should I implement the post_save method, use try/except block, or is there a better way?

答:
save() is a synchronous call:

```<code>Save the :class:`~mongoengine.Document` to the database. If the
document already exists, it will be updated, otherwise it will be
created. Returns the saved object instance.
</code>```

Use try/except block to deal with errors.

Body:
save() is a synchronous call:

Save the :class:`~mongoengine.Document` to the database. If the
document already exists, it will be updated, otherwise it will be
created. Returns the saved object instance.

Use try/except block to deal with errors.


问:
Writing large amounts of streamed data frequently with writestream
I'm trying to write a live websocket feed line-by-line to a file - I think for this I should be using a writeable stream.

My problem here is that the data received is in the region of 10 lines per second, which quickly fills the buffer.

I understand when using streams from sources you control, you would normally add some sort of backpressure logic here, but what should I do if I do not control the source? Should I be batching up the writes and writing, say 500 lines at a time, instead of per line, or should I be using some other way to save this data?

答:
I'm wondering how big are the lines? 10 lines per second sounds trivial to stream to a disk unless the lines are gigantic or the disk really slow. Ultimately, if you have no ability to apply backpressure logic, the source can overwhelm you if they go fast or your storage goes slow and you'd have to decide how much you can reasonably buffer and eventually just drop some of the data if you get behind.

But, you should be able to write a lot of data.  On a my regular hard disk (using the generic stream code below with no additional buffering) I can do sequential writes of 100,000,000 bytes at a speed of 55 MBytes/sec:

So, if you have 10 lines per second coming in, as long as the lines were below 10,000,000 bytes each, my hard drive could keep up.

Here's the code I used to test it:

```<code>const fs = require('fs');
const { Bench } = require('../../Github/measure');
const { addCommas } = require("../../Github/str-utils");

const lineData = Buffer.from("012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678\n", 'utf-8');

let stream = fs.createWriteStream("D:\\Temp\\temp.txt");
stream.on('open', function() {
    let linesRemaining = 1_000_000;

    let b = new Bench();
    let bytes = 0;

    function write() {
        do {
            linesRemaining--;
            let readyMore;
            bytes += lineData.length;
            if (linesRemaining === 0) {
                readyForMore = stream.write(lineData, done);
            } else {
                readyForMore = stream.write(lineData);
            }
        } while (linesRemaining > 0 && readyForMore);
        if (linesRemaining > 0) {
            stream.once('drain', write);
        }
    }

    function done() {
        b.markEnd();
        console.log(`Time to write ${addCommas(bytes)} bytes: ${b.formatSec(3)}`);
        console.log(`bytes/sec = ${addCommas((bytes/b.sec).toFixed(0))}`);
        console.log(`MB/sec = ${addCommas(((bytes/(1024 * 1024))/b.sec).toFixed(1))}`);
        stream.end();
    }

    b.markBegin();
    write();
});
</code>```

Theoretically, it is more efficient for your disk to do fewer writes that are larger, than tons of small writes.  In practice, because of the way the writeStream works, as soon as an inefficient write gets slow, the next write will get buffered and it kind of self corrects.  If you were really trying to minimize the load on the disk, you would buffer writes until you had at least something like 4k to write.  The issue is that each write has potentially allocate some bytes to the file (which involves writing to a table on the disk), then seek to where the bytes should be written on the disk, then write the bytes.  Fewer and larger writes that are larger (up to some limit that depends upon internal implementation) will reduce the number of times it has to do the file allocation overhead.

So, I ran a test.  I modified the above code (shown below) to buffer into 4k chunks and write them out in 4k chunks.  The write through increased from 55 MBytes/sec to 284.2 MBytes/sec.

So, the theory holds true that you will write faster if you buffer into larger chunks.

But, even the simpler, non-buffered version may be plenty fast.

Here's the test code for the buffered version:

```<code>const fs = require('fs');
const { Bench } = require('../../Github/measure');
const { addCommas } = require("../../Github/str-utils");

const lineData = Buffer.from("012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678\n", 'utf-8');

let stream = fs.createWriteStream("D:\\Temp\\temp.txt");
stream.on('open', function() {
    let linesRemaining = 1_000_000;

    let b = new Bench();
    let bytes = 0;

    let cache = [];
    let cacheTotal = 0;
    const maxBuffered = 4 * 1024;

    stream.myWrite = function(data, callback) {
        if (callback) {
            cache.push(data);
            return stream.write(Buffer.concat(cache), callback);
        } else {
            cache.push(data);
            cacheTotal += data.length;
            if (cacheTotal >= maxBuffered) {
                let ready = stream.write(Buffer.concat(cache));
                cache.length = 0;
                cacheTotal = 0;
                return ready;
            } else {
                return true;
            }
        }
    }

    function write() {
        do {
            linesRemaining--;
            let readyMore;
            bytes += lineData.length;
            if (linesRemaining === 0) {
                readyForMore = stream.myWrite(lineData, done);
            } else {
                readyForMore = stream.myWrite(lineData);
            }
        } while (linesRemaining > 0 && readyForMore);
        if (linesRemaining > 0) {
            stream.once('drain', write);
        }
    }

    function done() {
        b.markEnd();
        console.log(`Time to write ${addCommas(bytes)} bytes: ${b.formatSec(3)}`);
        console.log(`bytes/sec = ${addCommas((bytes/b.sec).toFixed(0))}`);
        console.log(`MB/sec = ${addCommas(((bytes/(1024 * 1024))/b.sec).toFixed(1))}`);
        stream.end();
    }

    b.markBegin();
    write();
});
</code>```

This code uses a couple of my local libraries for measuring the time and formatting the output.  If you want to run this yourself, you can substitute your own logic for those.

Body:
I'm wondering how big are the lines? 10 lines per second sounds trivial to stream to a disk unless the lines are gigantic or the disk really slow. Ultimately, if you have no ability to apply backpressure logic, the source can overwhelm you if they go fast or your storage goes slow and you'd have to decide how much you can reasonably buffer and eventually just drop some of the data if you get behind.

But, you should be able to write a lot of data.  On a my regular hard disk (using the generic stream code below with no additional buffering) I can do sequential writes of 100,000,000 bytes at a speed of 55 MBytes/sec:

So, if you have 10 lines per second coming in, as long as the lines were below 10,000,000 bytes each, my hard drive could keep up.

Here's the code I used to test it:

const fs = require('fs');
const { Bench } = require('../../Github/measure');
const { addCommas } = require("../../Github/str-utils");

const lineData = Buffer.from("012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678\n", 'utf-8');

let stream = fs.createWriteStream("D:\\Temp\\temp.txt");
stream.on('open', function() {
    let linesRemaining = 1_000_000;

    let b = new Bench();
    let bytes = 0;

    function write() {
        do {
            linesRemaining--;
            let readyMore;
            bytes += lineData.length;
            if (linesRemaining === 0) {
                readyForMore = stream.write(lineData, done);
            } else {
                readyForMore = stream.write(lineData);
            }
        } while (linesRemaining > 0 && readyForMore);
        if (linesRemaining > 0) {
            stream.once('drain', write);
        }
    }

    function done() {
        b.markEnd();
        console.log(`Time to write ${addCommas(bytes)} bytes: ${b.formatSec(3)}`);
        console.log(`bytes/sec = ${addCommas((bytes/b.sec).toFixed(0))}`);
        console.log(`MB/sec = ${addCommas(((bytes/(1024 * 1024))/b.sec).toFixed(1))}`);
        stream.end();
    }

    b.markBegin();
    write();
});

Theoretically, it is more efficient for your disk to do fewer writes that are larger, than tons of small writes.  In practice, because of the way the writeStream works, as soon as an inefficient write gets slow, the next write will get buffered and it kind of self corrects.  If you were really trying to minimize the load on the disk, you would buffer writes until you had at least something like 4k to write.  The issue is that each write has potentially allocate some bytes to the file (which involves writing to a table on the disk), then seek to where the bytes should be written on the disk, then write the bytes.  Fewer and larger writes that are larger (up to some limit that depends upon internal implementation) will reduce the number of times it has to do the file allocation overhead.

So, I ran a test.  I modified the above code (shown below) to buffer into 4k chunks and write them out in 4k chunks.  The write through increased from 55 MBytes/sec to 284.2 MBytes/sec.

So, the theory holds true that you will write faster if you buffer into larger chunks.

But, even the simpler, non-buffered version may be plenty fast.

Here's the test code for the buffered version:

const fs = require('fs');
const { Bench } = require('../../Github/measure');
const { addCommas } = require("../../Github/str-utils");

const lineData = Buffer.from("012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678\n", 'utf-8');

let stream = fs.createWriteStream("D:\\Temp\\temp.txt");
stream.on('open', function() {
    let linesRemaining = 1_000_000;

    let b = new Bench();
    let bytes = 0;

    let cache = [];
    let cacheTotal = 0;
    const maxBuffered = 4 * 1024;

    stream.myWrite = function(data, callback) {
        if (callback) {
            cache.push(data);
            return stream.write(Buffer.concat(cache), callback);
        } else {
            cache.push(data);
            cacheTotal += data.length;
            if (cacheTotal >= maxBuffered) {
                let ready = stream.write(Buffer.concat(cache));
                cache.length = 0;
                cacheTotal = 0;
                return ready;
            } else {
                return true;
            }
        }
    }

    function write() {
        do {
            linesRemaining--;
            let readyMore;
            bytes += lineData.length;
            if (linesRemaining === 0) {
                readyForMore = stream.myWrite(lineData, done);
            } else {
                readyForMore = stream.myWrite(lineData);
            }
        } while (linesRemaining > 0 && readyForMore);
        if (linesRemaining > 0) {
            stream.once('drain', write);
        }
    }

    function done() {
        b.markEnd();
        console.log(`Time to write ${addCommas(bytes)} bytes: ${b.formatSec(3)}`);
        console.log(`bytes/sec = ${addCommas((bytes/b.sec).toFixed(0))}`);
        console.log(`MB/sec = ${addCommas(((bytes/(1024 * 1024))/b.sec).toFixed(1))}`);
        stream.end();
    }

    b.markBegin();
    write();
});

This code uses a couple of my local libraries for measuring the time and formatting the output.  If you want to run this yourself, you can substitute your own logic for those.


问:
Laravel SQLSTATE[01000]: Warning: 1265 Data truncated for column for urdu or arabic character which are RTL mean right to left
I am stuck in an error for many days, I want to insert data in database in urdu or arabic language , the problem I am facing is strange the insert query changes the position of variables which throws data truncated error , I have used the same work in register Quer which works fine , I have set character set etc every thing perfect but the problem is during inserting values. I am sending the error query which larave throws.

#

```<code>Illuminate\Database\QueryException
SQLSTATE[01000]: Warning: 1265 Data truncated for column 'calor_bane' at row 1 (SQL: insert into `service_attributes` (`calor_bane`, `user_id`, `service_id`) values (کالر, 1, 1))
This is the query elequent
enter code here
ServiceAttribute::create([
'calor_bane' =>$data['name'],
'user_id' => 1,
'service_id' => 1
]);
</code>```

#

The same field is inserted in using User Model, it insert the urdu or arabic text correctly both char set are same but problem occurs in the insert query which moves the places you can see the above query.I have tried query builder and other types but didn't work.

```<code>insert into `users` (`name`, `email`, `password`, `updated_at`, `created_at`) values (کالر, mutahir12@gmail.pk, $2y$10$Y5fOtbpy..mgExbTotb1sO6irLlhNePKCfMvHv1JSmgtpOhUC2XLO, 2020-05-19 18:13:16, 2020-05-19 18:13:16)
User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
</code>```

答:
Actually by changing the ENUM data type solved my problem.
Thanks all.</p>

Body:
I am stuck in an error for many days, I want to insert data in database in urdu or arabic language , the problem I am facing is strange the insert query changes the position of variables which throws data truncated error , I have used the same work in register Quer which works fine , I have set character set etc every thing perfect but the problem is during inserting values. I am sending the error query which larave throws.

#

Illuminate\Database\QueryException
SQLSTATE[01000]: Warning: 1265 Data truncated for column 'calor_bane' at row 1 (SQL: insert into `service_attributes` (`calor_bane`, `user_id`, `service_id`) values (کالر, 1, 1))
This is the query elequent
enter code here
ServiceAttribute::create([
'calor_bane' =>$data['name'],
'user_id' => 1,
'service_id' => 1
]);

#

The same field is inserted in using User Model, it insert the urdu or arabic text correctly both char set are same but problem occurs in the insert query which moves the places you can see the above query.I have tried query builder and other types but didn't work.

insert into `users` (`name`, `email`, `password`, `updated_at`, `created_at`) values (کالر, mutahir12@gmail.pk, $2y$10$Y5fOtbpy..mgExbTotb1sO6irLlhNePKCfMvHv1JSmgtpOhUC2XLO, 2020-05-19 18:13:16, 2020-05-19 18:13:16)
User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);


问:
How is an int data stored on the memory in terms of bits? Is it not right-aligned?
I got really confused while I was trying some things out with fwrite function in C.

I read through the manual of fwrite here http://www.cplusplus.com/reference/cstdio/fwrite/

It says the functions writes the array byte by byte, so I tried to write an array of integers, expecting each integer in the array be split up to 4 characters.

I thought that a bit representation of a value is right-aligned on memory. That is, 98(ascii of 'b') would be stored as

00000000 00000000 00000000 01100010

on the memory. So I expected the fwrite function to write ' ', ' ', ' ', 'b' in the txt file. Instead, it wrote 'b', ' ', ' ', ' '.

I got confused so I tested it again with pointer, hoping my knowledge about memory storage was not wrong and it was only about fwrite function. I made an integer array arr, and put (1<<8)+2, 98 in it.

I used char pointer to split each integer into four bytes. Here's the code.

```<code>#include <stdio.h>

int main()
{
    int arr[5]={(1<<8)+2, 98, 'c', 'd', 'e'};
    char *p = (char*)&(arr[0]);

    printf("%d %d %d %d %d %d", arr[0], (int)(*p), (int)(*(p+1)), (int)(*(p+2)), (int)(*(p+3)), (int)(*(p+4)));

    FILE *fp;

    fp = fopen("TestFile2.txt", "a");
    fwrite(arr, sizeof(char), 5, fp);
    fclose(fp);
}
</code>```

The program printed "258 2 1 0 0 98" on the console, and "  b" was written in TestFile2 (exlcluding "s).

In my knowledge, (1<<8)+2 representation in terms of bits is

00000000 00000000 00000001 00000010 so the program should've printed 258 0 0 1 2 0.

The weird thing is that the result is not even left-aligned bit representation of the value either.

How is a value store on the memory bitwise? Is it not like what I thought it is? Or, am I missing something else here?

Any helps would be really appreciated.

答:
Issue is how you (as human) look at memory, you are caught in trap that memory is displayed in a way 0x0000 0x0001 0x002 for example as memory address(less significant on left), and for you to understand how 4 byte integer is stored in your system do next:

```<code>int a=0x01020408;
char* c=(char*)(void*)&a;
</code>```

And see how it is stored per bytes; most likely it will be c[0]=0x8; c[1]=0x04; c[2]=0x02;
Also you can think a bit how processor will load this 4 bytes of memory into register; least significant memory address is loaded into least significant register bits

Body:
I got really confused while I was trying some things out with fwrite function in C.

I read through the manual of fwrite here http://www.cplusplus.com/reference/cstdio/fwrite/

It says the functions writes the array byte by byte, so I tried to write an array of integers, expecting each integer in the array be split up to 4 characters.

I thought that a bit representation of a value is right-aligned on memory. That is, 98(ascii of 'b') would be stored as

00000000 00000000 00000000 01100010

on the memory. So I expected the fwrite function to write ' ', ' ', ' ', 'b' in the txt file. Instead, it wrote 'b', ' ', ' ', ' '.

I got confused so I tested it again with pointer, hoping my knowledge about memory storage was not wrong and it was only about fwrite function. I made an integer array arr, and put (1<<8)+2, 98 in it.

I used char pointer to split each integer into four bytes. Here's the code.

#include <stdio.h>

int main()
{
    int arr[5]={(1<<8)+2, 98, 'c', 'd', 'e'};
    char *p = (char*)&(arr[0]);

    printf("%d %d %d %d %d %d", arr[0], (int)(*p), (int)(*(p+1)), (int)(*(p+2)), (int)(*(p+3)), (int)(*(p+4)));

    FILE *fp;

    fp = fopen("TestFile2.txt", "a");
    fwrite(arr, sizeof(char), 5, fp);
    fclose(fp);
}

The program printed "258 2 1 0 0 98" on the console, and "  b" was written in TestFile2 (exlcluding "s).

In my knowledge, (1<<8)+2 representation in terms of bits is

00000000 00000000 00000001 00000010 so the program should've printed 258 0 0 1 2 0.

The weird thing is that the result is not even left-aligned bit representation of the value either.

How is a value store on the memory bitwise? Is it not like what I thought it is? Or, am I missing something else here?

Any helps would be really appreciated.

Body:
Issue is how you (as human) look at memory, you are caught in trap that memory is displayed in a way 0x0000 0x0001 0x002 for example as memory address(less significant on left), and for you to understand how 4 byte integer is stored in your system do next:

int a=0x01020408;
char* c=(char*)(void*)&a;

And see how it is stored per bytes; most likely it will be c[0]=0x8; c[1]=0x04; c[2]=0x02;
Also you can think a bit how processor will load this 4 bytes of memory into register; least significant memory address is loaded into least significant register bits


问:
How to define an optional entry point into custom Mac OS X framework / dynamic library?
In Windows there is a DllMain and DLL_PROCESS_ATTACH / DLL_PROCESS_DETACH flags, which allow to initialize / free resources after DLL is attached to a process... So how can I specify an entry point in case of OS X? As always, I can't find anything useful in Apple documentation :(

答:
The Dynamic Library Programming Topics document on Apple’s Web site shows the use of

```<code>__attribute__((constructor))
</code>```

and

```<code>__attribute__((destructor))
</code>```

to implement initialisers and finalizers in dynamic libraries.

Body:
The Dynamic Library Programming Topics document on Apple’s Web site shows the use of

__attribute__((constructor))

and

__attribute__((destructor))

to implement initialisers and finalizers in dynamic libraries.


问:
What are the implications of "Do you want to allow your PC to be discoverable by other PCs and devices on this network?" on AWS EC2?
When a Windows Server EC2 is started, it immediately prompts

Do you want to allow your pc to be discoverable by other pcs and
  devices on this network?

I can also see how to turn it on/off here

My question is, are there implications (security or otherwise) for Windows Server EC2 instances? In layman's terms, what does it mean I can/cannot do?

答:
By enabling this you will be discover-able to all Windows instances in your current subnet assuming security group permissions are there.

For your security group it is important that you keep the scope as limited as you can do, for example allowing 0.0.0.0/0 (which allows inbound access for anyone) is considered bad practice.

Instead create a dedicated security group of Network Discovery and for each port you add to it, add the source as the Network Discovery security group. By referencing a logical resource instead of specifying a CIDR range you can limit the scope of discoverable instances to a specific subset of your instances.

Ultimately I would suggest that you leave this off unless you specifically want to use certain features like Windows Folder Sharing.

You can still perform a standard Windows folder share which is accessible outside of the subnet, but this will require your other machine to be able to connect to your Windows server with valid credentials for that server witht the correct permissions.

By selecting No the only functionality disabled is that other hosts on the same subnet as you cannot automatically discover your Windows host.


问:
Scraping page with requests doesn't return all html tags
I am trying to scrape this page in order to extract the details of each [li] tag inside the [ol id="prices"]. The problem is that the returned .html code has some blank tags. Specifically, in each [li], the content of the tag [div class="shop cf"] is not returned. I have used requests and BeautifulSoup for this as follows:

```<code>import requests
import time
from bs4 import BeautifulSoup

headers = {
    "Connection": "keep-alive",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36"
}

url = "https://www.skroutz.gr/s/11706397/Guy-Laroche-Linda-Red.html"
page = requests.get(url, headers=headers )

# i also tried the following two commands in order to wait for the page to load
#seconds = 10
#page = requests.get(url, time.sleep(seconds), headers=headers)

soup = BeautifulSoup(page.content, 'html.parser')

eshops_grid = soup.find("ol", id="prices")
eshops_product = eshops_grid.findAll("li", class_='cf card js-product-card')
for eshop in eshops_product[0:]:
    eshop_name = eshop.find("div", class_="shop-name").text
    print(eshop_name) # I need to print the eshop_name for each eshop
</code>```

Although I need to do this by using requests library, I have also used selenium for this reason but the same problem occurs.

```<code>from selenium import webdriver
from pyvirtualdisplay import Display
from bs4 import BeautifulSoup

# We are opening a browser but not visible
print('- Open a browser but not visible ')
display = Display(visible=0, size=(1920, 1080))
display.start()

driver = webdriver.Chrome("/usr/lib/chromium-browser/chromedriver")

url = 'https://www.skroutz.gr/s/11706397/Guy-Laroche-Linda-Red.html?o=%CE%9C%CF%80%CE%BF%CF%85%CF%81%CE%BD%CE%BF%CF%8D%CE%B6%CE%B9%20Guy%20Laroche%20Linda%20Red'
#print('- Get the initial url of brandwatch')
driver.get(url)

page = driver.page_source
soup = BeautifulSoup(page, 'html.parser')

eshops_grid = soup.find("ol", id="prices")
eshops_product = eshops_grid.findAll("li", class_='cf card js-product-card')
for eshop in eshops_product[0:]:
    eshop_name = eshop.find("div", class_="shop-name").text
    print(eshop_name) # I need to print the eshop_name for each eshop
</code>```

Is there a way to get all the content of each ["li"] in order to extract and print the 'eshop_name'?

答:
Here is what you wanted.

```<code>import requests
import demjson
from bs4 import BeautifulSoup as bs

headers = {
    'authority': 'www.skroutz.gr',
    'cache-control': 'max-age=0',
    'sec-ch-ua': '"Google Chrome"; v="83"',
    'sec-ch-ua-mobile': '?0',
    'upgrade-insecure-requests': '1',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36',
    'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
    'sec-fetch-site': 'none',
    'sec-fetch-mode': 'navigate',
    'sec-fetch-user': '?1',
    'sec-fetch-dest': 'document',
    'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8',
    'cookie': '_helmet_couch=eyJzZXNzaW9uX2lkIjoiNjgzNzhmMmNmNjI5OTcxNjI5NzU2ZWNmMTM5MzE5MmIiLCJidWNrZXRfaWQiOiJmNTk1ZGRhYy00ZmVhLTQ5NmYtODNkNS00OWQzODgzMWFhYTAiLCJsYXN0X3NlZW4iOjE1OTEyNjgwNTUsInZvbCI6MSwiX2NzcmZfdG9rZW4iOiI1a3Yxb3FKTmhXTCs1YUxzdjYzRFk3TlNXeGs5TlhXYmZhM0UzSmtEL0NBPSJ9--22dfbfe582c0f3a7485e20d9d3932b32fbfb721b',
    'if-none-match': 'W/"e6fb8187391e99a90270c2351f9d17cd"',
}

params = (
    ('o', '\u039C\u03C0\u03BF\u03C5\u03C1\u03BD\u03BF\u03CD\u03B6\u03B9 Guy Laroche Linda Red'),
)

response = requests.get('https://www.skroutz.gr/s/11706397/Guy-Laroche-Linda-Red.html', headers=headers, params=params)

data = bs(response.text,'lxml')
s = data.find_all('script')[5].text.split('SKR.page.first_shop_name = ')[1].split(';')[0].replace('"','')
print(s)
</code>```

The Output is:

```<code>Spitishop
</code>```

Body:
I am trying to scrape this page in order to extract the details of each [li] tag inside the [ol id="prices"]. The problem is that the returned .html code has some blank tags. Specifically, in each [li], the content of the tag [div class="shop cf"] is not returned. I have used requests and BeautifulSoup for this as follows:

import requests
import time
from bs4 import BeautifulSoup

headers = {
    "Connection": "keep-alive",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36"
}

url = "https://www.skroutz.gr/s/11706397/Guy-Laroche-Linda-Red.html"
page = requests.get(url, headers=headers )

# i also tried the following two commands in order to wait for the page to load
#seconds = 10
#page = requests.get(url, time.sleep(seconds), headers=headers)

soup = BeautifulSoup(page.content, 'html.parser')

eshops_grid = soup.find("ol", id="prices")
eshops_product = eshops_grid.findAll("li", class_='cf card js-product-card')
for eshop in eshops_product[0:]:
    eshop_name = eshop.find("div", class_="shop-name").text
    print(eshop_name) # I need to print the eshop_name for each eshop

Although I need to do this by using requests library, I have also used selenium for this reason but the same problem occurs.

from selenium import webdriver
from pyvirtualdisplay import Display
from bs4 import BeautifulSoup

# We are opening a browser but not visible
print('- Open a browser but not visible ')
display = Display(visible=0, size=(1920, 1080))
display.start()

driver = webdriver.Chrome("/usr/lib/chromium-browser/chromedriver")

url = 'https://www.skroutz.gr/s/11706397/Guy-Laroche-Linda-Red.html?o=%CE%9C%CF%80%CE%BF%CF%85%CF%81%CE%BD%CE%BF%CF%8D%CE%B6%CE%B9%20Guy%20Laroche%20Linda%20Red'
#print('- Get the initial url of brandwatch')
driver.get(url)

page = driver.page_source
soup = BeautifulSoup(page, 'html.parser')

eshops_grid = soup.find("ol", id="prices")
eshops_product = eshops_grid.findAll("li", class_='cf card js-product-card')
for eshop in eshops_product[0:]:
    eshop_name = eshop.find("div", class_="shop-name").text
    print(eshop_name) # I need to print the eshop_name for each eshop

Is there a way to get all the content of each ["li"] in order to extract and print the 'eshop_name'?

Body:
Here is what you wanted.

import requests
import demjson
from bs4 import BeautifulSoup as bs

headers = {
    'authority': 'www.skroutz.gr',
    'cache-control': 'max-age=0',
    'sec-ch-ua': '"Google Chrome"; v="83"',
    'sec-ch-ua-mobile': '?0',
    'upgrade-insecure-requests': '1',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36',
    'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
    'sec-fetch-site': 'none',
    'sec-fetch-mode': 'navigate',
    'sec-fetch-user': '?1',
    'sec-fetch-dest': 'document',
    'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8',
    'cookie': '_helmet_couch=eyJzZXNzaW9uX2lkIjoiNjgzNzhmMmNmNjI5OTcxNjI5NzU2ZWNmMTM5MzE5MmIiLCJidWNrZXRfaWQiOiJmNTk1ZGRhYy00ZmVhLTQ5NmYtODNkNS00OWQzODgzMWFhYTAiLCJsYXN0X3NlZW4iOjE1OTEyNjgwNTUsInZvbCI6MSwiX2NzcmZfdG9rZW4iOiI1a3Yxb3FKTmhXTCs1YUxzdjYzRFk3TlNXeGs5TlhXYmZhM0UzSmtEL0NBPSJ9--22dfbfe582c0f3a7485e20d9d3932b32fbfb721b',
    'if-none-match': 'W/"e6fb8187391e99a90270c2351f9d17cd"',
}

params = (
    ('o', '\u039C\u03C0\u03BF\u03C5\u03C1\u03BD\u03BF\u03CD\u03B6\u03B9 Guy Laroche Linda Red'),
)

response = requests.get('https://www.skroutz.gr/s/11706397/Guy-Laroche-Linda-Red.html', headers=headers, params=params)

data = bs(response.text,'lxml')
s = data.find_all('script')[5].text.split('SKR.page.first_shop_name = ')[1].split(';')[0].replace('"','')
print(s)

The Output is:

Spitishop


问:
Navigator.push() shows a Black Screen
I am trying to make a fruithero flutter app but while changing my main page to another page, It shows only a black screen on my android emulator in laptop and on my phone, but in https://flutlab.io/ it shows perfectly, What is the problem that the app is not working on local emulator or in my phone but working on online IDE

Showing an Eror like this: -

There are multiple heroes that share the same tag within a subtree.

main.dart

```<code>import 'package:flutter/material.dart';
import './detailsPage.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
      debugShowCheckedModeBanner: false,
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xFF21BFBD),
      body: ListView(
        children: <Widget>[
          Padding(
            padding: EdgeInsets.only(top: 15.0, left: 10.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                IconButton(
                  icon: Icon(Icons.arrow_back_ios),
                  color: Colors.white,
                  onPressed: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => DetailsPage(),
                      ),
                    );
                  },
                ),
                Container(
                  width: 125.0,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      IconButton(
                        icon: Icon(Icons.filter_list),
                        color: Colors.white,
                        onPressed: () {},
                      ),
                      IconButton(
                        icon: Icon(Icons.menu),
                        color: Colors.white,
                        onPressed: () {},
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          SizedBox(
            height: 25.0,
          ),
          Padding(
            padding: EdgeInsets.only(left: 40.0),
            child: Row(
              children: <Widget>[
                Text(
                  'Healthy',
                  style: TextStyle(
                      fontFamily: 'Mont',
                      color: Colors.white,
                      fontSize: 25.0,
                      fontWeight: FontWeight.bold),
                ),
                SizedBox(width: 10.0),
                Text(
                  'Food',
                  style: TextStyle(
                      fontFamily: 'Mont', color: Colors.white, fontSize: 25.0),
                ),
              ],
            ),
          ),
          SizedBox(
            height: 40.0,
          ),
          Container(
            height: MediaQuery.of(context).size.height - 185.0,
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius:
                    BorderRadius.only(topLeft: Radius.circular(75.0))),
            child: ListView(
              primary: false,
              padding: EdgeInsets.only(left: 25.0, right: 20.0),
              children: <Widget>[
                Padding(
                  padding: EdgeInsets.only(top: 45.0),
                  child: Container(
                    height: MediaQuery.of(context).size.height / 1.68,
                    child: ListView(
                      children: <Widget>[
                        _buildFoodItem('images/one.png', 'Salmon', '\$24.0'),
                        _buildFoodItem('images/two.png', 'Spring', '\$22.0'),
                        _buildFoodItem('images/three.png', 'Sprite', '\$34.0'),
                        _buildFoodItem('images/one.png', 'Mut', '\$12.0')
                      ],
                    ),
                  ),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Container(
                      height: 65.0,
                      width: MediaQuery.of(context).size.width / 6,
                      decoration: BoxDecoration(
                          border: Border.all(
                            color: Colors.grey,
                            style: BorderStyle.solid,
                            width: 1.0,
                          ),
                          borderRadius: BorderRadius.circular(20)),
                      child: Center(
                        child: Icon(
                          Icons.search,
                          color: Colors.black,
                        ),
                      ),
                    ),
                    Container(
                      height: 65.0,
                      width: MediaQuery.of(context).size.width / 6,
                      decoration: BoxDecoration(
                          border: Border.all(
                            color: Colors.grey,
                            style: BorderStyle.solid,
                            width: 1.0,
                          ),
                          borderRadius: BorderRadius.circular(20)),
                      child: Center(
                        child: Icon(
                          Icons.shopping_cart,
                          color: Colors.black,
                        ),
                      ),
                    ),
                    Container(
                      height: 65.0,
                      width: MediaQuery.of(context).size.width / 2,
                      decoration: BoxDecoration(
                          color: Color(0xff170F1F),
                          border: Border.all(
                            color: Colors.grey,
                            style: BorderStyle.solid,
                            width: 1.0,
                          ),
                          borderRadius: BorderRadius.circular(20)),
                      child: Center(
                          child: Text(
                        'Checkout',
                        style: TextStyle(
                          fontSize: 18.0,
                          color: Colors.white,
                          fontFamily: 'Mont',
                        ),
                      )),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildFoodItem(String imgPath, String foodName, String price) {
    return Padding(
      padding: EdgeInsets.only(left: 10.0, right: 10.0, top: 10.0),
      child: InkWell(
        onTap: () {
          Navigator.push(                                               //Here is the Navigator.push()
            context,
            MaterialPageRoute(builder: (BuildContext context) {
              return DetailsPage();
            }),
          );
        },
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Container(
              child: Row(
                children: [
                  Hero(
                    tag: imgPath,
                    child: Image(
                      image: AssetImage(imgPath),
                      fit: BoxFit.cover,
                      height: 75.0,
                      width: 75.0,
                    ),
                  ),
                  SizedBox(width: 10.0),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        foodName,
                        style: TextStyle(
                            fontFamily: 'Mont',
                            fontSize: 17.0,
                            fontWeight: FontWeight.bold),
                      ),
                      Text(
                        price,
                        style: TextStyle(
                            fontFamily: 'Mont',
                            fontSize: 15.0,
                            color: Colors.grey),
                      )
                    ],
                  ),
                ],
              ),
            ),
            IconButton(
              icon: Icon(Icons.add),
              color: Colors.black,
              onPressed: () {},
            ),
          ],
        ),
      ),
    );
  }
}

</code>```

Navigator.push code is like this:

Navigator.push(
              context,
              MaterialPageRoute(builder: (BuildContext context) {
                return DetailsPage();
              }),
            );

detailsPage.dart

```<code>import 'package:flutter/material.dart';

class DetailsPage extends StatefulWidget {
  @override
  _DetailsPageState createState() => _DetailsPageState();
}

class _DetailsPageState extends State<DetailsPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xFF7A9BEE),
      appBar: AppBar(
        leading: IconButton(
          onPressed: () {
            Navigator.of(context).pop();
          },
          icon: Icon(Icons.arrow_back_ios),
          color: Colors.white,
        ),
        backgroundColor: Colors.transparent,
        elevation: 0.0,
        title: Text(
          'Details',
          style: TextStyle(
            fontFamily: 'Mont',
            fontSize: 18.0,
            color: Colors.white,
          ),
        ),
        centerTitle: true,
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.more_horiz),
            onPressed: () {},
            color: Colors.white,
          ),
        ],
      ),
    );
  }
}
</code>```

Here is git Repository link: 1

答:
i dont see the hero widget in the detailsPage.dart, when you set up a Hero widget in main and Navigate to detailsPage, you have to set up a hero widget to receive a hero transition from the main page, and because you have a listView in main you have to give a dynamic tag to each list item because each hero must have a tag associated with it so when it transfer to different layout it knows which hero to transit to it,
you already set up a hero tag in main page and you already give it a tag as  tag: imgPath
tag is like an id for that hero, now you need to set the same tag (id) in the detailsPage,
please watch this to understand the logic Hero Flutter Widget </p>

Title: Navigator.push() shows a Black Screen

Body:
I am trying to make a fruithero flutter app but while changing my main page to another page, It shows only a black screen on my android emulator in laptop and on my phone, but in https://flutlab.io/ it shows perfectly, What is the problem that the app is not working on local emulator or in my phone but working on online IDE

Showing an Eror like this: -

There are multiple heroes that share the same tag within a subtree.

main.dart

import 'package:flutter/material.dart';
import './detailsPage.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
      debugShowCheckedModeBanner: false,
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xFF21BFBD),
      body: ListView(
        children: <Widget>[
          Padding(
            padding: EdgeInsets.only(top: 15.0, left: 10.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                IconButton(
                  icon: Icon(Icons.arrow_back_ios),
                  color: Colors.white,
                  onPressed: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => DetailsPage(),
                      ),
                    );
                  },
                ),
                Container(
                  width: 125.0,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      IconButton(
                        icon: Icon(Icons.filter_list),
                        color: Colors.white,
                        onPressed: () {},
                      ),
                      IconButton(
                        icon: Icon(Icons.menu),
                        color: Colors.white,
                        onPressed: () {},
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          SizedBox(
            height: 25.0,
          ),
          Padding(
            padding: EdgeInsets.only(left: 40.0),
            child: Row(
              children: <Widget>[
                Text(
                  'Healthy',
                  style: TextStyle(
                      fontFamily: 'Mont',
                      color: Colors.white,
                      fontSize: 25.0,
                      fontWeight: FontWeight.bold),
                ),
                SizedBox(width: 10.0),
                Text(
                  'Food',
                  style: TextStyle(
                      fontFamily: 'Mont', color: Colors.white, fontSize: 25.0),
                ),
              ],
            ),
          ),
          SizedBox(
            height: 40.0,
          ),
          Container(
            height: MediaQuery.of(context).size.height - 185.0,
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius:
                    BorderRadius.only(topLeft: Radius.circular(75.0))),
            child: ListView(
              primary: false,
              padding: EdgeInsets.only(left: 25.0, right: 20.0),
              children: <Widget>[
                Padding(
                  padding: EdgeInsets.only(top: 45.0),
                  child: Container(
                    height: MediaQuery.of(context).size.height / 1.68,
                    child: ListView(
                      children: <Widget>[
                        _buildFoodItem('images/one.png', 'Salmon', '\$24.0'),
                        _buildFoodItem('images/two.png', 'Spring', '\$22.0'),
                        _buildFoodItem('images/three.png', 'Sprite', '\$34.0'),
                        _buildFoodItem('images/one.png', 'Mut', '\$12.0')
                      ],
                    ),
                  ),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Container(
                      height: 65.0,
                      width: MediaQuery.of(context).size.width / 6,
                      decoration: BoxDecoration(
                          border: Border.all(
                            color: Colors.grey,
                            style: BorderStyle.solid,
                            width: 1.0,
                          ),
                          borderRadius: BorderRadius.circular(20)),
                      child: Center(
                        child: Icon(
                          Icons.search,
                          color: Colors.black,
                        ),
                      ),
                    ),
                    Container(
                      height: 65.0,
                      width: MediaQuery.of(context).size.width / 6,
                      decoration: BoxDecoration(
                          border: Border.all(
                            color: Colors.grey,
                            style: BorderStyle.solid,
                            width: 1.0,
                          ),
                          borderRadius: BorderRadius.circular(20)),
                      child: Center(
                        child: Icon(
                          Icons.shopping_cart,
                          color: Colors.black,
                        ),
                      ),
                    ),
                    Container(
                      height: 65.0,
                      width: MediaQuery.of(context).size.width / 2,
                      decoration: BoxDecoration(
                          color: Color(0xff170F1F),
                          border: Border.all(
                            color: Colors.grey,
                            style: BorderStyle.solid,
                            width: 1.0,
                          ),
                          borderRadius: BorderRadius.circular(20)),
                      child: Center(
                          child: Text(
                        'Checkout',
                        style: TextStyle(
                          fontSize: 18.0,
                          color: Colors.white,
                          fontFamily: 'Mont',
                        ),
                      )),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildFoodItem(String imgPath, String foodName, String price) {
    return Padding(
      padding: EdgeInsets.only(left: 10.0, right: 10.0, top: 10.0),
      child: InkWell(
        onTap: () {
          Navigator.push(                                               //Here is the Navigator.push()
            context,
            MaterialPageRoute(builder: (BuildContext context) {
              return DetailsPage();
            }),
          );
        },
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Container(
              child: Row(
                children: [
                  Hero(
                    tag: imgPath,
                    child: Image(
                      image: AssetImage(imgPath),
                      fit: BoxFit.cover,
                      height: 75.0,
                      width: 75.0,
                    ),
                  ),
                  SizedBox(width: 10.0),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        foodName,
                        style: TextStyle(
                            fontFamily: 'Mont',
                            fontSize: 17.0,
                            fontWeight: FontWeight.bold),
                      ),
                      Text(
                        price,
                        style: TextStyle(
                            fontFamily: 'Mont',
                            fontSize: 15.0,
                            color: Colors.grey),
                      )
                    ],
                  ),
                ],
              ),
            ),
            IconButton(
              icon: Icon(Icons.add),
              color: Colors.black,
              onPressed: () {},
            ),
          ],
        ),
      ),
    );
  }
}

Navigator.push code is like this:

Navigator.push(
              context,
              MaterialPageRoute(builder: (BuildContext context) {
                return DetailsPage();
              }),
            );

detailsPage.dart

import 'package:flutter/material.dart';

class DetailsPage extends StatefulWidget {
  @override
  _DetailsPageState createState() => _DetailsPageState();
}

class _DetailsPageState extends State<DetailsPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xFF7A9BEE),
      appBar: AppBar(
        leading: IconButton(
          onPressed: () {
            Navigator.of(context).pop();
          },
          icon: Icon(Icons.arrow_back_ios),
          color: Colors.white,
        ),
        backgroundColor: Colors.transparent,
        elevation: 0.0,
        title: Text(
          'Details',
          style: TextStyle(
            fontFamily: 'Mont',
            fontSize: 18.0,
            color: Colors.white,
          ),
        ),
        centerTitle: true,
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.more_horiz),
            onPressed: () {},
            color: Colors.white,
          ),
        ],
      ),
    );
  }
}

Here is git Repository link: 1


问:
What is a Hybrid App for mobile?
What is a hybrid app for mobiles? What is basic architecture to follow while developing? What are the components? What will be the back end and what will be the UI? Is it for only iPhone or can be for any mobile device?</p>

答:
With iOS, you can create an application that combines features of native applications and webpages.

A hybrid application is a native iPhone application that provides most of its structure and functionality through a web viewing area, but also tends to contain standard iOS user interface elements.
A hybrid application gives users access to web content with an element called a web view (described in “Web Views”).
Precisely how you use a web view in your application is up to you, but it’s important to avoid giving users the impression that your application is merely a mini web browser.
A hybrid application should behave and appear like a native iPhone application; it should not draw attention to the fact that it depends upon web sources.

You can create Phonegap app and still using native controls of cocoa for powerful features like Mapkit api, UIWebview (Childbrowser plugin) etc

Title: What is a Hybrid App for mobile?


问:
how to give padding=6 in tensorflow 2.0?
```<code>self.conv6 = tf.keras.layers.Conv2D(1024, kernel_size=3, padding=6,dilation_rate=6) # atrous convolution
</code>```

this gives error in tensorflow 2.0

I see the padding='same' option

but what if I want to give padding=6

File
  "/home/jake/venv/lib/python3.7/site-packages/tensorflow_core/python/keras/utils/conv_utils.py",
  line 202, in normalize_padding
      padding = value.lower() AttributeError: 'int' object has no attribute 'lower'

答:
According to the tf.keras.layers.Conv2D documentation, padding can only be either 'same' or 'valid'.

'same' ensures that the spatial dimensions are preserved and 'valid' adds the minimum amount of padding required to ensure that the filter "fits" your spatial dimensions (which can be an issue if stride is anything other than one).

You shouldn't need to specify an custom padding size as in most cases it would be unnecessary upsampling. But if you must, you can have a padding layer before the conv layer.

tf.keras.layers.ZeroPadding2D(padding=(6, 6)) # put this before your conv layer
```

Body:
self.conv6 = tf.keras.layers.Conv2D(1024, kernel_size=3, padding=6,dilation_rate=6) # atrous convolution

this gives error in tensorflow 2.0

I see the padding='same' option

but what if I want to give padding=6

File
  "/home/jake/venv/lib/python3.7/site-packages/tensorflow_core/python/keras/utils/conv_utils.py",
  line 202, in normalize_padding
      padding = value.lower() AttributeError: 'int' object has no attribute 'lower'


问:
Pass arguments inside pushNamedandRemoveUntil in flutter
I pass the argument through a Navigator.pushNamedAndRemoveUntil but it shows text widget must not be null when I try to access the passed parameter.

```<code>CustomButton(
  buttonText: 'Go',
  buttonClick: () {
    Navigator.pushNamedAndRemoveUntil(
      context,
      Next.id,
      (route) => false,
      arguments: "123456789",
    );
  },
);
</code>```
```<code>class Next extends StatefulWidget {
  const Next({this.number});

  static const id = "next";
  final String number;

  @override
  _NextState createState() => _NextState();
}

class _NextState extends State<Next> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: Center(
          child: Text(
            widget.number,
          ),
        ),
      ),
    );
  }
}
</code>```

Error is
Failed assertion: line 298 pos 10: 'data != null'

答:
To pass arguments you need to do the following:

```<code> Navigator.pushAndRemoveUntil(context,  MaterialPageRoute(builder: (context) => SecondPage(title : "Hello World")), (route) => false);
</code>```

Here you navigate to SecondPage widget and pass the argument title to the widget.

Body:
I pass the argument through a Navigator.pushNamedAndRemoveUntil but it shows text widget must not be null when I try to access the passed parameter.

CustomButton(
  buttonText: 'Go',
  buttonClick: () {
    Navigator.pushNamedAndRemoveUntil(
      context,
      Next.id,
      (route) => false,
      arguments: "123456789",
    );
  },
);

class Next extends StatefulWidget {
  const Next({this.number});

  static const id = "next";
  final String number;

  @override
  _NextState createState() => _NextState();
}

class _NextState extends State<Next> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: Center(
          child: Text(
            widget.number,
          ),
        ),
      ),
    );
  }
}

Error is
Failed assertion: line 298 pos 10: 'data != null'

Body:
To pass arguments you need to do the following:

 Navigator.pushAndRemoveUntil(context,  MaterialPageRoute(builder: (context) => SecondPage(title : "Hello World")), (route) => false);

Here you navigate to SecondPage widget and pass the argument title to the widget.


问:
SwiftUI macOS - Create clickable hyperlink
I would like to display a url that the user can click on in my macos app. What I have so far is this:

```<code>Text(url)
.onTapGesture {
    if let url = URL(string: self.url) {
        NSWorkspace.shared.open(url)
    }
}
</code>```

However, this provides no visual indication to the user that the url is clickable. I want the text to be underlined and I want the cursor to change to a hand when the user hovers over it. How do I do that?

EDIT:

I found a custom extension for conditionally applying a modifier to a view from the swift forums:

extension View {

    func `if`<Content: View>(_ conditional: Bool, content: (Self) -> Content) -> some View {
        if conditional {
            return AnyView(content(self))
        } else {
            return AnyView(self)
        }
    }

}
```

<p>after combining it with @Asperi's answer, I now have this:</p>

<pre class="lang-swift prettyprint-override"><code>
@State private var isHoveringOverURL = false

Button(action: {
    if let url = URL(string: self.url) {
        NSWorkspace.shared.open(url)
    }

}) {
    Text(self.url)
        .font(.caption)
        .foregroundColor(Color.blue)
        .if(isHoveringOverURL) {
            $0.underline()
        }

}
.buttonStyle(PlainButtonStyle())
.onHover { inside in
    if inside {
        self.isHoveringOverURL = true
        NSCursor.pointingHand.push()
    } else {
        self.isHoveringOverURL = false
        NSCursor.pop()
    }
}
</code>```

答:
Here is possible solution. Tested with Xcode 11.4 / macOS 10.15.4

```<code>Button(action: {
   // link action here
}) {
    Text("www.stackoverflow.com").underline()
        .foregroundColor(Color.blue)
}.buttonStyle(PlainButtonStyle())
.onHover { inside in
    if inside {
        NSCursor.pointingHand.push()
    } else {
        NSCursor.pop()
    }
}
</code>```

Body:
I would like to display a url that the user can click on in my macos app. What I have so far is this:

Text(url)
.onTapGesture {
    if let url = URL(string: self.url) {
        NSWorkspace.shared.open(url)
    }
}

However, this provides no visual indication to the user that the url is clickable. I want the text to be underlined and I want the cursor to change to a hand when the user hovers over it. How do I do that?

EDIT:

I found a custom extension for conditionally applying a modifier to a view from the swift forums:

extension View {

    func `if`<Content: View>(_ conditional: Bool, content: (Self) -> Content) -> some View {
        if conditional {
            return AnyView(content(self))
        } else {
            return AnyView(self)
        }
    }

}

after combining it with @Asperi's answer, I now have this:

@State private var isHoveringOverURL = false

Button(action: {
    if let url = URL(string: self.url) {
        NSWorkspace.shared.open(url)
    }

}) {
    Text(self.url)
        .font(.caption)
        .foregroundColor(Color.blue)
        .if(isHoveringOverURL) {
            $0.underline()
        }

}
.buttonStyle(PlainButtonStyle())
.onHover { inside in
    if inside {
        self.isHoveringOverURL = true
        NSCursor.pointingHand.push()
    } else {
        self.isHoveringOverURL = false
        NSCursor.pop()
    }
}

Body:
Here is possible solution. Tested with Xcode 11.4 / macOS 10.15.4

Button(action: {
   // link action here
}) {
    Text("www.stackoverflow.com").underline()
        .foregroundColor(Color.blue)
}.buttonStyle(PlainButtonStyle())
.onHover { inside in
    if inside {
        NSCursor.pointingHand.push()
    } else {
        NSCursor.pop()
    }
}


问:
What react-native library available for encrypting/decrypting data by public/private keys
Can someone suggest a react-native lib for encrypting/decrypting data using public/private keypair? I'm currently using ethers.js for generating keypair and wanting to encrypt files using generated public key. I've tried 'crypto-js', 'react-native-crypto-js' but none of them work. The error is below:

"this package itself specifies a main module field that could not be resolved..."

答: I ended up with tweetnacl-js which seems OK</p>


问:
javascript using object keys as variable names
I'm trying to use the object keys p1, p2, p3 as variable names, but my knowledge of javascript seems insufficient to get it right. How can I do this, so in the end console.log(p1) is value1 etc.

```<code>var p = {
    "p1": "value1",
    "p2": "value2",
    "p3": "value3"
};

for (var key in p) {
    if (p.hasOwnProperty(key)) {
        console.log(key + " -> " + p[key]);
      var key = p[key]
    }
}

console.log(p1,p2,p3) //value1, value2, value3
</code>```

答: In fact, you are not allowed to overwrite an object property key. I assume that's your goal by reading the var key = p[key] line.

Body:
I'm trying to use the object keys p1, p2, p3 as variable names, but my knowledge of javascript seems insufficient to get it right. How can I do this, so in the end console.log(p1) is value1 etc.

var p = {
    "p1": "value1",
    "p2": "value2",
    "p3": "value3"
};

for (var key in p) {
    if (p.hasOwnProperty(key)) {
        console.log(key + " -> " + p[key]);
      var key = p[key]
    }
}

console.log(p1,p2,p3) //value1, value2, value3


问:
How to change Entry height in tkinter while using grid system and add text wraping?
I'm making an email sending gui application. I want to add an entry (messageEntry in my code) for entering the message. I want to change it's height so the message doesn't have to be entered in one line (I want to have text wraping). I tried using ipady, it does resize the entry but the message can still only be entered in one line (in the middle of the entry). Here is my code:</p>

```<code>def sendMail(senderEmail, senderPassword):

    global server

    sendMailFont = ['Consolas', 10]

    sendMailWindow = Tk()

    sendMailWindow.title("Sendmail")

    sendMailWindow.resizable(False, False)
    sendMailWindow.focus_force()

    # sendMailWindow.iconbitmap('info icon.ico')
    sendMailWindow.config(bg = "#DCDCDC")

    loggedInLabel = Label(sendMailWindow, font = (sendMailFont), text = "Logged in as {}".format(senderEmail), bg = "#DCDCDC")
    loggedInLabel.grid(row = 0, column = 0)

    subjectLabel = Label(sendMailWindow, font = (sendMailFont), text = "Subject", bg = "#DCDCDC")
    subjectLabel.grid(row = 2, column = 0, sticky = "w")

    subjectEntry = Entry(sendMailWindow, font = (sendMailFont), bg = "#FFFFFF", width = 37)
    subjectEntry.grid(row = 3, column = 0, sticky = "w", ipady = 2)

    messageLabel = Label(sendMailWindow, font = (sendMailFont), text = "Message", bg = "#DCDCDC")
    messageLabel.grid(row = 5, column = 0, sticky = "w")

    messageEntry = Entry(sendMailWindow, font = (sendMailFont), bg = "#FFFFFF", width = 37)
    messageEntry.grid(row = 6, column = 0, sticky = "w")

    hiddenLabel = Label(sendMailWindow, font = ('Consolas', 1), text = "", bg = "#DCDCDC")
    hiddenLabel.grid(row = 1, column = 0, sticky = "we")
    hiddenLabel = Label(sendMailWindow, font = ('Consolas', 10), text = "", bg = "#DCDCDC")
    hiddenLabel.grid(row = 4, column = 0, sticky = "we")

    sendMailWindow.mainloop()
</code>```

答:
You can use the tkinter.scrolledtext module like this:

```<code>from tkinter import *
from tkinter.scrolledtext import *

def sendMail(senderEmail, senderPassword):

    global server

    sendMailFont = ['Consolas', 10]

    sendMailWindow = Tk()

    sendMailWindow.title("Sendmail")

    sendMailWindow.resizable(False, False)
    sendMailWindow.focus_force()

    # sendMailWindow.iconbitmap('info icon.ico')
    sendMailWindow.config(bg = "#DCDCDC")

    loggedInLabel = Label(sendMailWindow, font = (sendMailFont), text = "Logged in as {}".format(senderEmail), bg = "#DCDCDC")
    loggedInLabel.grid(row = 0, column = 0)

    subjectLabel = Label(sendMailWindow, font = (sendMailFont), text = "Subject", bg = "#DCDCDC")
    subjectLabel.grid(row = 2, column = 0, sticky = "w")

    subjectEntry = Entry(sendMailWindow, font = (sendMailFont), bg = "#FFFFFF", width = 37)
    subjectEntry.grid(row = 3, column = 0, sticky = "w", ipady = 2)

    messageLabel = Label(sendMailWindow, font = (sendMailFont), text = "Message", bg = "#DCDCDC")
    messageLabel.grid(row = 5, column = 0, sticky = "w")

    ##########
    messageEntry = ScrolledText(sendMailWindow, font = (sendMailFont), bg = "#FFFFFF", width = 37, height = 5)
    messageEntry.grid(row = 6, column = 0, sticky = "w")
    ##########

    sendMailWindow.mainloop()
</code>```

This module is the tkinter.text module with a scroll bar. You can adjust his height.

Body:
I'm making an email sending gui application. I want to add an entry (messageEntry in my code) for entering the message. I want to change it's height so the message doesn't have to be entered in one line (I want to have text wraping). I tried using ipady, it does resize the entry but the message can still only be entered in one line (in the middle of the entry). Here is my code:

def sendMail(senderEmail, senderPassword):

    global server

    sendMailFont = ['Consolas', 10]

    sendMailWindow = Tk()

    sendMailWindow.title("Sendmail")

    sendMailWindow.resizable(False, False)
    sendMailWindow.focus_force()

    # sendMailWindow.iconbitmap('info icon.ico')
    sendMailWindow.config(bg = "#DCDCDC")

    loggedInLabel = Label(sendMailWindow, font = (sendMailFont), text = "Logged in as {}".format(senderEmail), bg = "#DCDCDC")
    loggedInLabel.grid(row = 0, column = 0)

    subjectLabel = Label(sendMailWindow, font = (sendMailFont), text = "Subject", bg = "#DCDCDC")
    subjectLabel.grid(row = 2, column = 0, sticky = "w")

    subjectEntry = Entry(sendMailWindow, font = (sendMailFont), bg = "#FFFFFF", width = 37)
    subjectEntry.grid(row = 3, column = 0, sticky = "w", ipady = 2)

    messageLabel = Label(sendMailWindow, font = (sendMailFont), text = "Message", bg = "#DCDCDC")
    messageLabel.grid(row = 5, column = 0, sticky = "w")

    messageEntry = Entry(sendMailWindow, font = (sendMailFont), bg = "#FFFFFF", width = 37)
    messageEntry.grid(row = 6, column = 0, sticky = "w")

    hiddenLabel = Label(sendMailWindow, font = ('Consolas', 1), text = "", bg = "#DCDCDC")
    hiddenLabel.grid(row = 1, column = 0, sticky = "we")
    hiddenLabel = Label(sendMailWindow, font = ('Consolas', 10), text = "", bg = "#DCDCDC")
    hiddenLabel.grid(row = 4, column = 0, sticky = "we")

    sendMailWindow.mainloop()

Body:
You can use the tkinter.scrolledtext module like this:

from tkinter import *
from tkinter.scrolledtext import *

def sendMail(senderEmail, senderPassword):

    global server

    sendMailFont = ['Consolas', 10]

    sendMailWindow = Tk()

    sendMailWindow.title("Sendmail")

    sendMailWindow.resizable(False, False)
    sendMailWindow.focus_force()

    # sendMailWindow.iconbitmap('info icon.ico')
    sendMailWindow.config(bg = "#DCDCDC")

    loggedInLabel = Label(sendMailWindow, font = (sendMailFont), text = "Logged in as {}".format(senderEmail), bg = "#DCDCDC")
    loggedInLabel.grid(row = 0, column = 0)

    subjectLabel = Label(sendMailWindow, font = (sendMailFont), text = "Subject", bg = "#DCDCDC")
    subjectLabel.grid(row = 2, column = 0, sticky = "w")

    subjectEntry = Entry(sendMailWindow, font = (sendMailFont), bg = "#FFFFFF", width = 37)
    subjectEntry.grid(row = 3, column = 0, sticky = "w", ipady = 2)

    messageLabel = Label(sendMailWindow, font = (sendMailFont), text = "Message", bg = "#DCDCDC")
    messageLabel.grid(row = 5, column = 0, sticky = "w")

    ##########
    messageEntry = ScrolledText(sendMailWindow, font = (sendMailFont), bg = "#FFFFFF", width = 37, height = 5)
    messageEntry.grid(row = 6, column = 0, sticky = "w")
    ##########

    sendMailWindow.mainloop()

This module is the tkinter.text module with a scroll bar. You can adjust his height.


问:
File empty check
I make a function to check if the text file is empty or not . I use fseek and ftell to check , but the problem is if the first line is a '\n' and next line is EOF then ftell will return 2 but not 0 . I want to check if the file actually empty or not but i cant think if there is a way to check the situation above . Please help . Here is my code </p>

```<code>void fileReader(FILE *file,char filePath[]){
char output[100];
file = fopen(filePath,"r");
printf("Content of file : ");
fseek(file, 0, SEEK_END);
printf("%d",ftell(file));
if(ftell(file)==0){
    printf("\nthere is nothing here");
}
else{
    do{
        printf("%s", output);
    }while (fscanf(file, "%s", output) != EOF);
}
fclose(file);
}
</code>```

答:
but the problem is if the first line is a '\n' and next line is EOF then ftell will return 2 but not 0

you do not want to know if a file is empty meaning its size is 0, but if the file contain something else that space, tab, newline etc, in that case the size is not enough. One way to do that can be :

```<code>#include <stdio.h>

int main(int argc, char ** argv)
{
  FILE * fp;

  if (argc != 2)
    fprintf(stderr, "Usage %s <file>\n", *argv);
  else if ((fp = fopen(argv[1], "r")) == NULL)
    perror("cannot read file");
  else {
    char c;

    switch (fscanf(fp, " %c", &c)) { /* note the space before % */
    case EOF:
      puts("empty or only spaces");
      break;
    case 1:
      puts("non empty");
      break;
    default:
      perror("cannot read file");
      break;
    }
    fclose(fp);
  }

  return 0;
}
</code>```

In fscanf(fp, " %c", &c) the space before % ask to bypass whitespaces (space, tab, newline ...)

Compilation and executions:

```<code>pi@raspberrypi:/tmp $ gcc -Wall c.c
pi@raspberrypi:/tmp $ ./a.out /dev/null
empty or only spaces
pi@raspberrypi:/tmp $ echo > e
pi@raspberrypi:/tmp $ wc -c e
1 e
pi@raspberrypi:/tmp $ ./a.out e
empty or only spaces
pi@raspberrypi:/tmp $ echo "   " > e
pi@raspberrypi:/tmp $ echo "   " >> e
pi@raspberrypi:/tmp $ wc -c e
8 e
pi@raspberrypi:/tmp $ ./a.out e
empty or only spaces
pi@raspberrypi:/tmp $ echo "a" >> e
pi@raspberrypi:/tmp $ cat e

a
pi@raspberrypi:/tmp $ ./a.out e
non empty
pi@raspberrypi:/tmp $
pi@raspberrypi:/tmp $ chmod -r e
pi@raspberrypi:/tmp $ ./a.out e
cannot read file: Permission denied
pi@raspberrypi:/tmp $ ./a.out
Usage ./a.out <file>
pi@raspberrypi:/tmp $
</code>```

Title: File empty check

Body:
I make a function to check if the text file is empty or not . I use fseek and ftell to check , but the problem is if the first line is a '\n' and next line is EOF then ftell will return 2 but not 0 . I want to check if the file actually empty or not but i cant think if there is a way to check the situation above . Please help . Here is my code

void fileReader(FILE *file,char filePath[]){
char output[100];
file = fopen(filePath,"r");
printf("Content of file : ");
fseek(file, 0, SEEK_END);
printf("%d",ftell(file));
if(ftell(file)==0){
    printf("\nthere is nothing here");
}
else{
    do{
        printf("%s", output);
    }while (fscanf(file, "%s", output) != EOF);
}
fclose(file);
}

Body:
but the problem is if the first line is a '\n' and next line is EOF then ftell will return 2 but not 0

you do not want to know if a file is empty meaning its size is 0, but if the file contain something else that space, tab, newline etc, in that case the size is not enough. One way to do that can be :

#include <stdio.h>

int main(int argc, char ** argv)
{
  FILE * fp;

  if (argc != 2)
    fprintf(stderr, "Usage %s <file>\n", *argv);
  else if ((fp = fopen(argv[1], "r")) == NULL)
    perror("cannot read file");
  else {
    char c;

    switch (fscanf(fp, " %c", &c)) { /* note the space before % */
    case EOF:
      puts("empty or only spaces");
      break;
    case 1:
      puts("non empty");
      break;
    default:
      perror("cannot read file");
      break;
    }
    fclose(fp);
  }

  return 0;
}

In fscanf(fp, " %c", &c) the space before % ask to bypass whitespaces (space, tab, newline ...)

Compilation and executions:

pi@raspberrypi:/tmp $ gcc -Wall c.c
pi@raspberrypi:/tmp $ ./a.out /dev/null
empty or only spaces
pi@raspberrypi:/tmp $ echo > e
pi@raspberrypi:/tmp $ wc -c e
1 e
pi@raspberrypi:/tmp $ ./a.out e
empty or only spaces
pi@raspberrypi:/tmp $ echo "   " > e
pi@raspberrypi:/tmp $ echo "   " >> e
pi@raspberrypi:/tmp $ wc -c e
8 e
pi@raspberrypi:/tmp $ ./a.out e
empty or only spaces
pi@raspberrypi:/tmp $ echo "a" >> e
pi@raspberrypi:/tmp $ cat e

a
pi@raspberrypi:/tmp $ ./a.out e
non empty
pi@raspberrypi:/tmp $
pi@raspberrypi:/tmp $ chmod -r e
pi@raspberrypi:/tmp $ ./a.out e
cannot read file: Permission denied
pi@raspberrypi:/tmp $ ./a.out
Usage ./a.out <file>
pi@raspberrypi:/tmp $


问:
Module 'Firebase' has no member named 'functions'
I can't get Firebase Functions to load in xcode.

```<code>import Firebase
lazy var functions = Firebase.functions()
</code>```

Installed just like the firebase docs said to.

Pod shows up under pods/pods/FirebaseFunctions.

No idea what to do here.

Firebase 6.25.0
Firebase Functions (2.5.1) (it shows up in brackets in my pod install idk why).

答:
According to Firebase documentation, you should call

```<code>lazy var functions = Functions.functions()
</code>```

https://firebase.google.com/docs/functions/callable

Body:
I can't get Firebase Functions to load in xcode.

import Firebase
lazy var functions = Firebase.functions()

Installed just like the firebase docs said to.

Pod shows up under pods/pods/FirebaseFunctions.

No idea what to do here.

Firebase 6.25.0
Firebase Functions (2.5.1) (it shows up in brackets in my pod install idk why).

Body:
According to Firebase documentation, you should call

lazy var functions = Functions.functions()

https://firebase.google.com/docs/functions/callable