问:
Unable to load the "PHP Email Form" Library
For some reason, my PHP Form doesn't work, when someone presses send message button this error pops out "Unable to load the "PHP Email Form" Library". I don't know what the problem is.

This is contact.php

```<code><?php

    $receiving_email_address = 'myemailadress';

      if( file_exists($php_email_form = '../assets/vendor/php-email-form/php-email-form.php' )) {
        include( $php_email_form );
      } else {
        die( 'Coming Soon!');
      }

      $contact = new PHP_Email_Form;
      $contact->ajax = true;

      $contact->to = $receiving_email_address;
      $contact->from_name = $_POST['name'];
      $contact->from_email = $_POST['email'];
      $contact->subject = $_POST['subject'];

      // Uncomment below code if you want to use SMTP to send emails. You need to enter your correct SMTP credentials
      /*
      $contact->smtp = array(
        'host' => 'example.com',
        'username' => 'example',
        'password' => 'pass',
        'port' => '587'
      );
      */

      $contact->add_message( $_POST['name'], 'From');
      $contact->add_message( $_POST['email'], 'Email');
      $contact->add_message( $_POST['message'], 'Message', 10);

      echo $contact->send();
    ?>
</code>```

This is index.html

```<code> <div class="form">
              <form action="forms/contact.php" method="post" role="form" class="php-email-form">
                <div class="row">
                  <div class="form-group col-md-6">
                    <input type="text" name="name" class="form-control" id="name" placeholder="Your Name" required>
                  </div>
                  <div class="form-group col-md-6 mt-3 mt-md-0">
                    <input type="email" class="form-control" name="email" id="email" placeholder="Your Email" required>
                  </div>
                </div>
                <div class="form-group mt-3">
                  <input type="text" class="form-control" name="subject" id="subject" placeholder="Subject" required>
                </div>
                <div class="form-group mt-3">
                  <textarea class="form-control" name="message" rows="5" placeholder="Message" required></textarea>
                </div>
                <div class="my-3">
                  <div class="loading">Loading</div>
                  <div class="error-message"></div>
                  <div class="sent-message">Your message has been sent. Thank you!</div>
                </div>
                <div class="text-center"><button type="submit">Send Message</button></div>
              </form>
            </div>
</code>```

Anf for some reason some kind of a error log file came up in the folder that says:

```<code>[19-Nov-2021 13:49:31 UTC] PHP Fatal error:  Uncaught Error: Class 'PHP_Email_Form' not found in /home/domain/public_html/forms/contact.php:16
Stack trace:
#0 {main}
  thrown in /home/domain/public_html/forms/contact.php on line 16
[19-Nov-2021 13:49:32 UTC] PHP Fatal error:  Uncaught Error: Class 'PHP_Email_Form' not found in /home/domain/public_html/forms/contact.php:16
Stack trace:
#0 {main}
  thrown in /home/domain/public_html/forms/contact.php on line 16
</code>```

I guess I should add this home/domain/public.html/froms/contact.php on line 16 but I don't know how to do that properly apparently.

答:
you are using the free template and the PHP Form
requires the "PHP Email Form" library and
the "PHP Email Form" library is available only in the pro version of the template.

you must to buy the pro version template

if you don't want to buy you must create your own php code

Body:
For some reason, my PHP Form doesn't work, when someone presses send message button this error pops out "Unable to load the "PHP Email Form" Library". I don't know what the problem is.

This is contact.php

<?php

    $receiving_email_address = 'myemailadress';

      if( file_exists($php_email_form = '../assets/vendor/php-email-form/php-email-form.php' )) {
        include( $php_email_form );
      } else {
        die( 'Coming Soon!');
      }

      $contact = new PHP_Email_Form;
      $contact->ajax = true;

      $contact->to = $receiving_email_address;
      $contact->from_name = $_POST['name'];
      $contact->from_email = $_POST['email'];
      $contact->subject = $_POST['subject'];

      // Uncomment below code if you want to use SMTP to send emails. You need to enter your correct SMTP credentials
      /*
      $contact->smtp = array(
        'host' => 'example.com',
        'username' => 'example',
        'password' => 'pass',
        'port' => '587'
      );
      */

      $contact->add_message( $_POST['name'], 'From');
      $contact->add_message( $_POST['email'], 'Email');
      $contact->add_message( $_POST['message'], 'Message', 10);

      echo $contact->send();
    ?>

This is index.html

              <form action="forms/contact.php" method="post" role="form" class="php-email-form">

                    <input type="text" name="name" class="form-control" id="name" placeholder="Your Name" required>

                    <input type="email" class="form-control" name="email" id="email" placeholder="Your Email" required>

                  <input type="text" class="form-control" name="subject" id="subject" placeholder="Subject" required>

                  <textarea class="form-control" name="message" rows="5" placeholder="Message" required></textarea>

Loading

Your message has been sent. Thank you!

<button type="submit">Send Message</button>

              </form>

Anf for some reason some kind of a error log file came up in the folder that says:

[19-Nov-2021 13:49:31 UTC] PHP Fatal error:  Uncaught Error: Class 'PHP_Email_Form' not found in /home/domain/public_html/forms/contact.php:16
Stack trace:
#0 {main}
  thrown in /home/domain/public_html/forms/contact.php on line 16
[19-Nov-2021 13:49:32 UTC] PHP Fatal error:  Uncaught Error: Class 'PHP_Email_Form' not found in /home/domain/public_html/forms/contact.php:16
Stack trace:
#0 {main}
  thrown in /home/domain/public_html/forms/contact.php on line 16

I guess I should add this home/domain/public.html/froms/contact.php on line 16 but I don't know how to do that properly apparently.


来源: stackexchange

问:
initializeApp when adding firebase to app and to server
I'm using firebase for auth and db, and AWS lambda for cloud functions.

To add firebase to my JS project, I initializeApp with the firebase config as parameter, as documented here : https://firebase.google.com/docs/web/setup.

As documented here : https://firebase.google.com/docs/admin/setup, I also need to initializeApp in my lambda function.

Something as follows here :

```<code>const admin = require('firebase-admin');
const serviceAccount = require('../path/to/service-account.json');

const firebaseAdmin = admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: "dB_URL"
});
</code>```

The credentials come from the firebase-admin library, so I cannot add this to my web firebase config. So, I need to initialize twice.

However, if I proceed like this, the server will throw an error :

The default Firebase app already exists. This means you called initializeApp() more than once without providing an app name as the second argument. In most cases you only need to call initializeApp() once.But if you do want to initialize multiple apps, pass a second argument to initializeApp() to give each app a unique name.

Am I missing something here ? What's the best practice ? I'm confused.

Someone faced the same issue before it seems : Use Firebase SDK with Netlify Lambda Functions

What worked for this user was to use the REST API as documented here : https://firebase.google.com/docs/projects/api/workflow_set-up-and-manage-project

The documentation says it's in beta though.

Thanks for your kind help

答:
Have similar problem. Based on answer from @Frank van Puffelen ( Thanks to him ), Now a days, Using ES6 ( Firebase admin V >= 9 )</p>
```<code>import { initializeApp, applicationDefault, getApps } from "firebase-admin/app";

...

        if ( !getApps().length ) {
            initializeApp({
                credential: applicationDefault(),
                databaseURL: 'https://XXXXXXX.firebaseio.com'
            });
        }
...
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm using firebase for auth and db, and AWS lambda for cloud functions.

To add firebase to my JS project, I initializeApp with the firebase config as parameter, as documented here : https://firebase.google.com/docs/web/setup.

As documented here : https://firebase.google.com/docs/admin/setup, I also need to initializeApp in my lambda function.

Something as follows here :

const admin = require('firebase-admin');
const serviceAccount = require('../path/to/service-account.json');

const firebaseAdmin = admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: "dB_URL"
});

The credentials come from the firebase-admin library, so I cannot add this to my web firebase config. So, I need to initialize twice.

However, if I proceed like this, the server will throw an error :

The default Firebase app already exists. This means you called initializeApp() more than once without providing an app name as the second argument. In most cases you only need to call initializeApp() once.But if you do want to initialize multiple apps, pass a second argument to initializeApp() to give each app a unique name.

Am I missing something here ? What's the best practice ? I'm confused.

Someone faced the same issue before it seems : Use Firebase SDK with Netlify Lambda Functions

What worked for this user was to use the REST API as documented here : https://firebase.google.com/docs/projects/api/workflow_set-up-and-manage-project

The documentation says it's in beta though.

Thanks for your kind help

Body:
Have similar problem. Based on answer from @Frank van Puffelen ( Thanks to him ), Now a days, Using ES6 ( Firebase admin V >= 9 )

import { initializeApp, applicationDefault, getApps } from "firebase-admin/app";

...

        if ( !getApps().length ) {
            initializeApp({
                credential: applicationDefault(),
                databaseURL: 'https://XXXXXXX.firebaseio.com'
            });
        }
...


问:
Groovy: MultiValueMap with Maps as keys
Heres's something I'm thinking about doing, and I want to know if you think it's a good idea or not.

I retrieve a bunch of rows from a database, which in groovy gives me a list of lists something like:

```<code>[
  [ 'Dog', 'M', 'Mutt', 'Sammy' ],
  [ 'Cat', 'F', 'Siamese', 'Pat' ],
  [ 'Dog', 'M', 'Husky', 'Taco' ],
  ...
]
</code>```

Not my real data set but you get the idea.

Since I will be pulling this data pretty frequently and doing some analysis to it before presenting it in the UI, I want to store it in a MultiValueMap keyed by groovy maps (i.e. LinkedHashMaps), so I can retrieve the bits and pieces of it that I need, without going to DB every time.  It's kind of a cache of a subset of data that comes from several tables (more complex than the animals data above).

I would be able to use it like this:

```<code>animals.get([species:'Dog', gender:'M'])
</code>```

returns:

```<code>[['Sammy', 'Mutt'], ['Taco', 'Husky'] ]
</code>```

I think I have some idea how to implement it, so I'm not really looking for that (though if you have a novel suggestion please share).  I'm mainly looking for somebody to tell me that either this won't work for some reason, or it sounds fine, or it won't scale, etc.  Or maybe there's some easier way to get a similar functionality.  One more consideration: the whole data set can sometimes be sorta large-ish, e.g. few 100k records.  If not this, what's a good way to deal with it, aside from hit the DB every time?

I realize there are lots of key/value caching solutions around, but I don't think I need anything so heavy duty for what I'm doing.  It is just a small webapp with pretty low usage, mostly internal to the company I'm building it for.

答: Using a mutable Map as a key is a really bad idea, because if the key changes then it will not be found.</p>

ContentLicense: CC BY-SA 3.0

Title: Groovy: MultiValueMap with Maps as keys

Body:
Heres's something I'm thinking about doing, and I want to know if you think it's a good idea or not.

I retrieve a bunch of rows from a database, which in groovy gives me a list of lists something like:

[
  [ 'Dog', 'M', 'Mutt', 'Sammy' ],
  [ 'Cat', 'F', 'Siamese', 'Pat' ],
  [ 'Dog', 'M', 'Husky', 'Taco' ],
  ...
]

Not my real data set but you get the idea.

Since I will be pulling this data pretty frequently and doing some analysis to it before presenting it in the UI, I want to store it in a MultiValueMap keyed by groovy maps (i.e. LinkedHashMaps), so I can retrieve the bits and pieces of it that I need, without going to DB every time.  It's kind of a cache of a subset of data that comes from several tables (more complex than the animals data above).

I would be able to use it like this:

animals.get([species:'Dog', gender:'M'])

returns:

[['Sammy', 'Mutt'], ['Taco', 'Husky'] ]

I think I have some idea how to implement it, so I'm not really looking for that (though if you have a novel suggestion please share).  I'm mainly looking for somebody to tell me that either this won't work for some reason, or it sounds fine, or it won't scale, etc.  Or maybe there's some easier way to get a similar functionality.  One more consideration: the whole data set can sometimes be sorta large-ish, e.g. few 100k records.  If not this, what's a good way to deal with it, aside from hit the DB every time?

I realize there are lots of key/value caching solutions around, but I don't think I need anything so heavy duty for what I'm doing.  It is just a small webapp with pretty low usage, mostly internal to the company I'm building it for.


问:
Flutter web easy printing
Due to flutter web exported javascript, we can't print the current web page information.
In the print preview we have blank page, this is not the case with all others website.

My question is simple, is there any way we can get current screen printed with a bluetooth printer or wired using flutter web?

The only thing i found was using a package named printing and i need to rebuild all my page into pdf.

https://pub.dev/packages/printing

答: I have tried this ai_blue_tooth_print - https://pub.dev/packages/ai_blue_tooth_print. It is able to print the flutter web screen straight to the printer. However, this package is not "null safe".</p>

Title: Flutter web easy printing


问:
Reduce brigthness in real time OpenCv Python
I am looking around how to reduce the brightness of the webcam image.
Can you tell me how to do it?

I couldn't find anything ...

To increase the value I use this function (I increase the brightness with a trackbar):

```<code>def change_brightness(frame, value):
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    h, s, v = cv2.split(hsv)

    lim = 255 - value
    v[v > lim] = 255
    v[v <= lim] += value

    final_hsv = cv2.merge((h, s, v))
    img = cv2.cvtColor(final_hsv, cv2.COLOR_HSV2BGR)
    return img
</code>```

This is the full code:

```<code>cv2.namedWindow("VIDEO")
#cv2.createTrackbar("alpha", "VIDEO", 0, 4, nothing)
cv2.createTrackbar("gamma", "VIDEO", 50, 100, nothing)
while True:
        k = cv2.waitKey(1)
        _, frame = video.read()
        frame = cv2.resize(frame, FRAME_DIM)  # frame contiene l'immagine della webcam
        frame = cv2.flip(frame, 1) # giro orizzontalmente (parametro = 1) l'immagine

        #test = cv2.getTrackbarPos("alpha", "VIDEO")
        test = cv2.getTrackbarPos("gamma", "VIDEO")

        gamma = cv2.getTrackbarPos("gamma", "VIDEO")
        frame = change_brightness(frame, gamma)
        if (k % 256 == ord("q")):  # PATH, folder_name, full_path, IMG_LABELquando premo "q" si chiude la webcam e la relativa finestra
            cv2.destroyAllWindows()
            break
        camera = cv2.imshow("VIDEO", frame)
</code>```

答:
This seems to work; the essence is that the slider goes from 0 to 510, so you subtract an offset to get values to add or subtract to the 'v' value of HSV.   The original code used a neat trick to easily go through all elements of the image to add brightness; the trick is repeated for subtracting off values.  For example, if you subtract off -10 in brightness, anything lower than 10 is zero; otherwise, subtract off.

```<code>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Feb  6 18:06:51 2022

https://stackoverflow.com/questions/71011111/reduce-brigthness-in-real-time-opencv-python#comment125531455_71011111
"""
import cv2

def change_brightness(frame, value):
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    h, s, v = cv2.split(hsv)

    # increase brightness; input value is 1 to 255
    if(value>0):
        lim_upper = 255 - value
        # If v>lim, then set to 255
        v[v > lim_upper] = 255
        # if v<lim, then add
        v[v <= lim_upper] += value
    # decrease brightness; input value from 0 to -255
    else:
        lim_lower = -value
        v[v < lim_lower] = 0
        v[v >= lim_lower] -= -value

    final_hsv = cv2.merge((h, s, v))
    img = cv2.cvtColor(final_hsv, cv2.COLOR_HSV2BGR)
    return img

# Read from video camera
video_capture_device_index = 0
webcam = cv2.VideoCapture(video_capture_device_index)
cv2.namedWindow("VIDEO")
cv2.createTrackbar("gamma", "VIDEO", 255, 510,(lambda a: None))

while True:
        ret, frame = webcam.read()
        k = cv2.waitKey(1)
        # flip horizontally (mirror)
        frame = cv2.flip(frame, 1) # giro orizzontalmente (parametro = 1) l'immagine

        # varies from 0-510, so subtract so range is -255 to 255
        gamma = cv2.getTrackbarPos("gamma", "VIDEO")
        gamma = gamma - 255

        frame = change_brightness(frame, gamma)
        # Use q to quit
        if (k == ord("q")):  # PATH, folder_name, full_path, IMG_LABELquando premo "q" si chiude la webcam e la relativa finestra
            cv2.destroyAllWindows()
            break

        camera = cv2.imshow("VIDEO", frame)

webcam.release()
print("end video.")
</code>```

Body:
I am looking around how to reduce the brightness of the webcam image.
Can you tell me how to do it?

I couldn't find anything ...

To increase the value I use this function (I increase the brightness with a trackbar):

def change_brightness(frame, value):
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    h, s, v = cv2.split(hsv)

    lim = 255 - value
    v[v > lim] = 255
    v[v <= lim] += value

    final_hsv = cv2.merge((h, s, v))
    img = cv2.cvtColor(final_hsv, cv2.COLOR_HSV2BGR)
    return img

This is the full code:

cv2.namedWindow("VIDEO")
#cv2.createTrackbar("alpha", "VIDEO", 0, 4, nothing)
cv2.createTrackbar("gamma", "VIDEO", 50, 100, nothing)
while True:
        k = cv2.waitKey(1)
        _, frame = video.read()
        frame = cv2.resize(frame, FRAME_DIM)  # frame contiene l'immagine della webcam
        frame = cv2.flip(frame, 1) # giro orizzontalmente (parametro = 1) l'immagine

        #test = cv2.getTrackbarPos("alpha", "VIDEO")
        test = cv2.getTrackbarPos("gamma", "VIDEO")

        gamma = cv2.getTrackbarPos("gamma", "VIDEO")
        frame = change_brightness(frame, gamma)
        if (k % 256 == ord("q")):  # PATH, folder_name, full_path, IMG_LABELquando premo "q" si chiude la webcam e la relativa finestra
            cv2.destroyAllWindows()
            break
        camera = cv2.imshow("VIDEO", frame)

Body:
This seems to work; the essence is that the slider goes from 0 to 510, so you subtract an offset to get values to add or subtract to the 'v' value of HSV.   The original code used a neat trick to easily go through all elements of the image to add brightness; the trick is repeated for subtracting off values.  For example, if you subtract off -10 in brightness, anything lower than 10 is zero; otherwise, subtract off.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Feb  6 18:06:51 2022

https://stackoverflow.com/questions/71011111/reduce-brigthness-in-real-time-opencv-python#comment125531455_71011111
"""
import cv2

def change_brightness(frame, value):
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    h, s, v = cv2.split(hsv)

    # increase brightness; input value is 1 to 255
    if(value>0):
        lim_upper = 255 - value
        # If v>lim, then set to 255
        v[v > lim_upper] = 255
        # if v<lim, then add
        v[v <= lim_upper] += value
    # decrease brightness; input value from 0 to -255
    else:
        lim_lower = -value
        v[v < lim_lower] = 0
        v[v >= lim_lower] -= -value

    final_hsv = cv2.merge((h, s, v))
    img = cv2.cvtColor(final_hsv, cv2.COLOR_HSV2BGR)
    return img

# Read from video camera
video_capture_device_index = 0
webcam = cv2.VideoCapture(video_capture_device_index)
cv2.namedWindow("VIDEO")
cv2.createTrackbar("gamma", "VIDEO", 255, 510,(lambda a: None))

while True:
        ret, frame = webcam.read()
        k = cv2.waitKey(1)
        # flip horizontally (mirror)
        frame = cv2.flip(frame, 1) # giro orizzontalmente (parametro = 1) l'immagine

        # varies from 0-510, so subtract so range is -255 to 255
        gamma = cv2.getTrackbarPos("gamma", "VIDEO")
        gamma = gamma - 255

        frame = change_brightness(frame, gamma)
        # Use q to quit
        if (k == ord("q")):  # PATH, folder_name, full_path, IMG_LABELquando premo "q" si chiude la webcam e la relativa finestra
            cv2.destroyAllWindows()
            break

        camera = cv2.imshow("VIDEO", frame)

webcam.release()
print("end video.")


问:
Generate object from Typescript interface
I realize this is essentially the opposite intent of Typescript, but I would like to be able to programmatically generate an object FROM a typescript interface. Basically, I want something like this:

```<code>interface Foo {
    bar: string
}

const generateObjFromInterface = (Foo) => // { bar: 'string'}
</code>```

I -do not- mind how contrived the implementation is if it IS possible! If it is categorically impossible that would also be helpful information!

Thanks in advance!

答: I also was searching for something that could do it and I didn't find anything. So I build this lib https://www.npmjs.com/package/class-validator-mocker, which can generate random data for classes attributes annotated with class-validator's decorators. Worked pretty well for my purposes.</p>

Body:
I realize this is essentially the opposite intent of Typescript, but I would like to be able to programmatically generate an object FROM a typescript interface. Basically, I want something like this:

interface Foo {
    bar: string
}

const generateObjFromInterface = (Foo) => // { bar: 'string'}

I -do not- mind how contrived the implementation is if it IS possible! If it is categorically impossible that would also be helpful information!

Thanks in advance!


问:
How to add remote repository in git with SSH?
I just getting started using SSH keys due to managing multiple accounts in a single mac. It works very well when I tried to clone with SSH. However, when I tried to add a remote repository using SSH (git remote add origin git@github.com:jiwanjeon/26-django-practice.git) and push my files. It shows up this error message "git@github.com: Permission denied (publickey). fatal: Could not read from remote repository."

I googled so many times but I am not sure how to deal with it...

What I tried to
: I made a new SSH Key and add it in its' repository Deploy Key but it didn't work as well.

edit 1)
: I also tried to make a new SSH Keys and copy and paste it, also didn't work

edit 2)
When I tried to git add repository through HTTP not a SSH. It works as well but I am not sure why SSH didn't work even I add a SSH Keys...

I would appreciate your help!

答:
To use a remote repository, you must only make sure that you have SSH access to your server. Once there, you can follow these steps to create your remote repository in the link below.
https://www.inmotionhosting.com/support/website/git/setting-up-your-remote-repository-with-git/</p>


问:
NOT EXISTS vs NOT attribute= ANY vs NOT IN
After I read this post, I found a third way to achieve the query with NOT ANY. Does it really makes a difference?

Which of these queries run the faster?

NOT EXISTS

```<code>SELECT DISTINCT U.no FROM U
INNER JOIN PUF ON PUF.noU = U.no
WHERE NOT EXISTS (
    SELECT DISTINCT PUF.noU FROM F
    INNER JOIN PUF AS PUF2 ON PUF2.noF = F.no
    WHERE VILLE <> 'Lausanne' AND PUF.noU = PUF2.noU
)

</code>```

NOT attribute = ANY

```<code>SELECT DISTINCT U.no FROM U
INNER JOIN PUF ON PUF.noU = U.no
WHERE NOT PUF.noU = ANY (
    SELECT DISTINCT PUF.noU FROM F
    INNER JOIN PUF ON PUF.noF = F.no
    WHERE VILLE <> 'Lausanne'
)

</code>```

NOT IN (The initial one)

```<code>SELECT DISTINCT U.no FROM U
INNER JOIN PUF ON PUF.noU = U.no
WHERE PUF.noU NOT IN (
    SELECT DISTINCT PUF.noU FROM F
    INNER JOIN PUF ON PUF.noF = F.no
    WHERE VILLE <> 'Lausanne'
)
</code>```

If they're equivalent, should I use NOT EXISTS instead of NOT attribute = ANY () ?

答:
The one construct to avoid in most cases is NOT IN, especially NOT IN (subquery).

NOT attribute = ANY (subquery) is equally inferior.

Those yield "surprising" results when involving NULL values, and there is almost always a superior (correct, faster, less deceiving) formulation with NOT EXISTS or LEFT JOIN / IS NULL. See:

Select rows which are not present in other table

Either way, DISTINCT is useless noise inside an EXISTS expression. Postgres stops evaluation after the first find anyway.

You can probably simplify to this:

SELECT DISTINCT U.no
FROM   U
JOIN   PUF ON PUF.noU = U.no
WHERE  NOT EXISTS (
   SELECT FROM F
   WHERE  F.no = PUF.noF
   AND    F.VILLE <> 'Lausanne'
   );
```

Maybe you can simplify further. The JOIN may not be needed, either.
I would have to know exact table definitions and the exact intention of the query to be sure.

That said, the proof of the pudding is in the eating. After verifying that all variants are indeed equivalent (NULL values?), test performance for each (properly) and compare. See:

Get execution time of PostgreSQL query

Body:
After I read this post, I found a third way to achieve the query with NOT ANY. Does it really makes a difference?

Which of these queries run the faster?

NOT EXISTS

SELECT DISTINCT U.no FROM U
INNER JOIN PUF ON PUF.noU = U.no
WHERE NOT EXISTS (
    SELECT DISTINCT PUF.noU FROM F
    INNER JOIN PUF AS PUF2 ON PUF2.noF = F.no
    WHERE VILLE <> 'Lausanne' AND PUF.noU = PUF2.noU
)

NOT attribute = ANY

SELECT DISTINCT U.no FROM U
INNER JOIN PUF ON PUF.noU = U.no
WHERE NOT PUF.noU = ANY (
    SELECT DISTINCT PUF.noU FROM F
    INNER JOIN PUF ON PUF.noF = F.no
    WHERE VILLE <> 'Lausanne'
)

NOT IN (The initial one)

SELECT DISTINCT U.no FROM U
INNER JOIN PUF ON PUF.noU = U.no
WHERE PUF.noU NOT IN (
    SELECT DISTINCT PUF.noU FROM F
    INNER JOIN PUF ON PUF.noF = F.no
    WHERE VILLE <> 'Lausanne'
)

If they're equivalent, should I use NOT EXISTS instead of NOT attribute = ANY () ?

Body:
The one construct to avoid in most cases is NOT IN, especially NOT IN (subquery).

NOT attribute = ANY (subquery) is equally inferior.

Those yield "surprising" results when involving NULL values, and there is almost always a superior (correct, faster, less deceiving) formulation with NOT EXISTS or LEFT JOIN / IS NULL. See:

Select rows which are not present in other table

Either way, DISTINCT is useless noise inside an EXISTS expression. Postgres stops evaluation after the first find anyway.

You can probably simplify to this:

SELECT DISTINCT U.no
FROM   U
JOIN   PUF ON PUF.noU = U.no
WHERE  NOT EXISTS (
   SELECT FROM F
   WHERE  F.no = PUF.noF
   AND    F.VILLE <> 'Lausanne'
   );

Maybe you can simplify further. The JOIN may not be needed, either.
I would have to know exact table definitions and the exact intention of the query to be sure.

That said, the proof of the pudding is in the eating. After verifying that all variants are indeed equivalent (NULL values?), test performance for each (properly) and compare. See:

Get execution time of PostgreSQL query


问:
Auto formatting a 100mb+ C++ file
I have a 100mb auto generated C++ file with broken formatting that I want to autoformat (indentation primarily).

All editors I have tried either crash or do not allow autoformatting more than a few megabytes of text.

By auto formatting I mean indentation.

Beyond writing some custom code to do this how can I auto format 100mb C/c++ files?

I have tried:
VSCode
Visual Studio
Notepad++

Why do I need this?

We need to search the code for meta data (it is decompiled from assembly) and it makes it a lot easier to read if its indented properly.

We don't know ahead of time which parts of the code we need.. until we need it. It needs to be a single file to make it simpler to search for names/functions without constantly searching 1000s of individual files (if we did it per function).

The original C code would be millions of lines long which is why its so large

答:
My first three recommendations are text editors, but I don't know if they'll work for you: 1) JEdit has a CLangBeauty plugin for reformatting source. 2) I assume Netbeans has a similar plugin, and can handle large files.  3) Then, there is QtCreator, which is available in a Windows version.  If you let it install Qt, it will be a large install, but I think you can do a custom install and just get the IDE; but it is very good at large files and can reformat them.  Just choose the Open Source Edition at the download.

Here's a page with a list of text editors than can open files gigabytes in size: "How to open Gigabyte-sized text files on Windows".  I've used glogg to view huge text files successfully; although it's features are minimalistic.

In order to reformat "C" and "C++" code, there is a handy utility "UniversalIndentGUI" that can call a number of code beautifiers/formatters.  It was lasted updated in 2012, though.  One of the command-line tools it can call is "Uncrustify".

Uncrustify is a command-line utility for reformatting code, and should be more memory efficient than the editor-based methods, as will be command-line code formatters in general. It is probably the most powerful at customizing the format it puts things in than the others.  It has recently been updated as of this writing. clang-format will probably also do it too.  These are command line utilities, so it's best to run them from a command prompt, call them in a pipe, or from an external GUI like UniversalIndentGUI; at least on Windows.  Uncrustify has a LOT of configuration options you can make.  I was also able to contact the author, and get him to add a feature for code formatting that I felt to be important.  Uncrustify should do it if none of the others will do.

Title: Auto formatting a 100mb+ C++ file


问:
How to set a list into DB with sqlite (or achive something similar)
I have a movie that can have any number of genres. I would like to have that list inside a database, but it seems databases cant hold a list in a cell.

Is there any other way to achieve this, so I can have any number of genres connected to a specific movie?

```<code>class Film:
    def __init__(self, title, genres):
        self.title = title
        self.genres = genres

    def accept_genre(self, genre):
        self.genres.append(genre)

Movie1 = Film("Taxi Driver", ["Drama"])

print(Movie1.genres) #prints ["Drama"]

Movie1.accept_genre("Crime")

print(Movie1.genres) #prints ["Drama", "Crime"]

...
#im thinking something like this but it doesnt work with lists:
def addToDB(title):
    with conn:
        c.execute("""UPDATE film SET genres = :genre WHERE title = :title""",
        {'title': title, 'genres': list,})  addToDB("Taxi Driver")
</code>```

答:
Have you considered storing as a semicolon delimited string?

```<code>genres_list = ['Comedy','Horror']
# Pass this dictionary into cur.execute:
{'title': title, 'genres': ';'.join(genres_list),}
</code>```

To convert a semicolon delimited string to a list, use the .split method:

```<code>'Comedy;Horror'.split(';')
# the result is ['Comedy','Horror']
</code>```

Body:
I have a movie that can have any number of genres. I would like to have that list inside a database, but it seems databases cant hold a list in a cell.

Is there any other way to achieve this, so I can have any number of genres connected to a specific movie?

class Film:
    def __init__(self, title, genres):
        self.title = title
        self.genres = genres

    def accept_genre(self, genre):
        self.genres.append(genre)

Movie1 = Film("Taxi Driver", ["Drama"])

print(Movie1.genres) #prints ["Drama"]

Movie1.accept_genre("Crime")

print(Movie1.genres) #prints ["Drama", "Crime"]

...
#im thinking something like this but it doesnt work with lists:
def addToDB(title):
    with conn:
        c.execute("""UPDATE film SET genres = :genre WHERE title = :title""",
        {'title': title, 'genres': list,})  addToDB("Taxi Driver")

Body:
Have you considered storing as a semicolon delimited string?

genres_list = ['Comedy','Horror']
# Pass this dictionary into cur.execute:
{'title': title, 'genres': ';'.join(genres_list),}

To convert a semicolon delimited string to a list, use the .split method:

'Comedy;Horror'.split(';')
# the result is ['Comedy','Horror']


问:
Get error ```gaierror(-2, 'Name or service not known'))``` from certbot
i try to get SSL cert for my site and i am using certbot certonly -a webroot --webroot-path=/var/www/html -d example.com -d www.example.com but get such error  raise ConnectionError(err, request=request) ConnectionError: ('Connection aborted.', gaierror(-2, 'Name or service not known')), my OS is Debian 8 and i am using nginx and node js on my server, tnks

答:
I ran into this error today. Seems to have fixed itself.

This makes me think it was a transient name resolution issue.

The solution seems to be to wait and try again later.


问:
Angular: Click button to redirect to another page not working
In the Market > Value page, I have a button named add, when the user clicks on this button, the user goes to another page. This page is named ajout.

Here is the structure

value.component.html

```<code><div class="text-center">
    <button type="submit" class="btn btn-primary" (click)="btnAjout">Add</button>
</div>
</code>```

value.component.ts

btnAjout(): void {
   this.router.navigateByUrl('/ajout');
}
```
<p>market-routing.module.ts</p>
```{
  path: 'value',
  component: ValueComponent,
},
{
  path: 'ajout',
  component: AjoutComponent
},
```
<p>ajout.component.html</p>
```
ajout works!

```

The ajout page is not working, did I make a mistake?

Code Stackblitz

答:
Issue 1: Unable fire btnAjout method

btnAjout is a function. Hence with (click)="btnAjout", it never trigger the btnAjout function.

```<code><button type="submit" class="btn btn-primary" (click)="btnAjout">Add</button>
</code>```

btnAjout(): void {
  ...
}
```
<p><strong>Solution for Issue 1</strong></p>
<p>Correct the click event.</p>
```<button type="submit" class="btn btn-primary" (click)="btnAjout()">Add</button>
```
<hr />
<p><strong>Issue 2: Incorrect routing to 'market/ajout'</strong></p>
<p>From reviewing <code>DashboardRoutingModule</code> to <code>MarketingRoutingModule</code>, (to redirect) <code>adjout</code> component's URL should be:</p>
<blockquote>
<p>/market/adjout</p>
</blockquote>
<p>Instead of:</p>
<pre class="lang-js prettyprint-override"><code>this.router.navigateByUrl('/ajout');
</code>```

Solution for Issue 2

Correct the url path.

this.router.navigateByUrl('/market/ajout');
```

Sample Solution on StackBlitz

Body:
In the Market > Value page, I have a button named add, when the user clicks on this button, the user goes to another page. This page is named ajout.

Here is the structure

value.component.html

    <button type="submit" class="btn btn-primary" (click)="btnAjout">Add</button>

value.component.ts

btnAjout(): void {
   this.router.navigateByUrl('/ajout');
}

market-routing.module.ts

{
  path: 'value',
  component: ValueComponent,
},
{
  path: 'ajout',
  component: AjoutComponent
},

ajout.component.html

ajout works!

The ajout page is not working, did I make a mistake?

Code Stackblitz

Body:
Issue 1: Unable fire btnAjout method

btnAjout is a function. Hence with (click)="btnAjout", it never trigger the btnAjout function.

<button type="submit" class="btn btn-primary" (click)="btnAjout">Add</button>

btnAjout(): void {
  ...
}

Solution for Issue 1

Correct the click event.

<button type="submit" class="btn btn-primary" (click)="btnAjout()">Add</button>

Issue 2: Incorrect routing to 'market/ajout'

From reviewing DashboardRoutingModule to MarketingRoutingModule, (to redirect) adjout component's URL should be:

/market/adjout

Instead of:

this.router.navigateByUrl('/ajout');

Solution for Issue 2

Correct the url path.

this.router.navigateByUrl('/market/ajout');

Sample Solution on StackBlitz


问:
Synchronous calls using RemoteObject
Is there a way to make synchronous calls using RemoteObject in Flex?</p>

答:
All IO in Flex is asynchronous. The typical pattern to deal with this is to use an AsyncResponder.  For instance:

```<code>var t:AsyncToken = remoteObject.methodCall();
t.addResponder(new AsyncResponder(resultEvent, faultEvent));
</code>```

OwnerDisplayName: Sandy

ContentLicense: CC BY-SA 2.5

Title: Synchronous calls using RemoteObject

LastEditorDisplayName: Sandy

Body:
All IO in Flex is asynchronous. The typical pattern to deal with this is to use an AsyncResponder.  For instance:

var t:AsyncToken = remoteObject.methodCall();
t.addResponder(new AsyncResponder(resultEvent, faultEvent));

OwnerDisplayName: James Ward


问:
I am facing Loop issue in DOM Manipulation, Can anyone look at it please?
I am trying to make rainbow text but I am unable to loop over, can anyone help?

This is the HTML

```<code><body>
    <h1>
        <span>R</span>
        <span>A</span>
        <span>I</span>
        <span>N</span>
        <span>B</span>
        <span>O</span>
        <span>W</span>
    </h1>
</body>```
```
<p>And this is the javascript</p>
```const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']
```

I want to loop colors over the span using document.querySelectorAll

答:
I'm not entirely sure what you're hoping to accomplish here. I think you want to color the individual letters with the elements in your colors array sequentially.

You can do that in several different ways. One of the more straightforward solutions would be to execute a callback function on an (array-like) nodelist using the forEach method.

Something like this...

Gather your spans into a nodelist (using querySelectorAll)

Iterate over the members of that nodelist (passing in the member variable and the index property)

Assign an inline style (the color corresponding to the index in the colors array) in your callback function.

Or, you could add a class instead and probably others things as well.

Good luck.

const letters = document.querySelectorAll('.letters span');
const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];

letters.forEach((letter, index) => {
  letter.style.color = colors[index]
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <h1 class="letters">
    <span>R</span>
    <span>A</span>
    <span>I</span>
    <span>N</span>
    <span>B</span>
    <span>O</span>
    <span>W</span>
  </h1>
</body></code>```

Body:
I am trying to make rainbow text but I am unable to loop over, can anyone help?

This is the HTML

        R
        A
        I
        N
        B
        O
        W

```

And this is the javascript

const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']

I want to loop colors over the span using document.querySelectorAll

Body:
I'm not entirely sure what you're hoping to accomplish here. I think you want to color the individual letters with the elements in your colors array sequentially.

You can do that in several different ways. One of the more straightforward solutions would be to execute a callback function on an (array-like) nodelist using the forEach method.

Something like this...

Gather your spans into a nodelist (using querySelectorAll)

Iterate over the members of that nodelist (passing in the member variable and the index property)

Assign an inline style (the color corresponding to the index in the colors array) in your callback function.

Or, you could add a class instead and probably others things as well.

Good luck.

const letters = document.querySelectorAll('.letters span');
const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];

letters.forEach((letter, index) => {
  letter.style.color = colors[index]
})

<body>
  <h1 class="letters">
    <span>R</span>
    <span>A</span>
    <span>I</span>
    <span>N</span>
    <span>B</span>
    <span>O</span>
    <span>W</span>
  </h1>
</body>


问:
When using Pinia and TypeScript how do you use an Action to set the State?
I have a Pinia + TypeScript store named user.ts that looks like this:

```<code>import { User } from 'firebase/auth';
import { defineStore } from 'pinia';
export const useUserStore = defineStore('user', {
  state: () =>
    ({
      displayName: null,
      email: null,
      emailVerified: null,
      isAnonymous: null,
      metadata: null,
      multiFactor: null,
      phoneNumber: null,
      photoURL: null,
      providerData: null,
      providerId: null,
      refreshToken: null,
      tenantId: null,
      uid: null,
    } as unknown as User),
  actions: {
    setPhotoURL(photoURLData: string | null) {
      this.photoURL = photoURLData; //<-- ERROR HERE
    },
  },
});
</code>```

The state is a FireBase User object.

And I want to update photoURL using the setPhotoURL() action.

But photoURL has this TypeScript error:

```<code>Cannot assign to 'photoURL' because it is a read-only property. ts(2540)
</code>```

What am I doing wrong?

Is this the correct way to update state?

答:
'firebase/auth' declares User interface as having readonly props. When you forcefully apply that interface to your state object, TS trusts you.

Spreading it should remove the readonly from its props, while still inferring the types:

```<code>export const useUserStore = defineStore('user', {
  state: () => ({ ...({
    displayName: null,
    email: null,
    emailVerified: null,
    isAnonymous: null,
    metadata: null,
    multiFactor: null,
    phoneNumber: null,
    photoURL: null,
    providerData: null,
    providerId: null,
    refreshToken: null,
    tenantId: null,
    uid: null,
  } as unknown as User) }),
  actions: {
    //...
  }
})
</code>```

Body:
I have a Pinia + TypeScript store named user.ts that looks like this:

import { User } from 'firebase/auth';
import { defineStore } from 'pinia';
export const useUserStore = defineStore('user', {
  state: () =>
    ({
      displayName: null,
      email: null,
      emailVerified: null,
      isAnonymous: null,
      metadata: null,
      multiFactor: null,
      phoneNumber: null,
      photoURL: null,
      providerData: null,
      providerId: null,
      refreshToken: null,
      tenantId: null,
      uid: null,
    } as unknown as User),
  actions: {
    setPhotoURL(photoURLData: string | null) {
      this.photoURL = photoURLData; //<-- ERROR HERE
    },
  },
});

The state is a FireBase User object.

And I want to update photoURL using the setPhotoURL() action.

But photoURL has this TypeScript error:

Cannot assign to 'photoURL' because it is a read-only property. ts(2540)

What am I doing wrong?

Is this the correct way to update state?

Body:
'firebase/auth' declares User interface as having readonly props. When you forcefully apply that interface to your state object, TS trusts you.

Spreading it should remove the readonly from its props, while still inferring the types:

export const useUserStore = defineStore('user', {
  state: () => ({ ...({
    displayName: null,
    email: null,
    emailVerified: null,
    isAnonymous: null,
    metadata: null,
    multiFactor: null,
    phoneNumber: null,
    photoURL: null,
    providerData: null,
    providerId: null,
    refreshToken: null,
    tenantId: null,
    uid: null,
  } as unknown as User) }),
  actions: {
    //...
  }
})


问:
how to resolve unpack error in python function
I was wondering why I'm getting an unpack error for entry[1] when the value will always be some tuple like so Tuple[str, int] for this function:

```<code>def add_to_index(index, keyword, url):
    for entry in index:
        if entry[0] == keyword:
              for curr_url, count in entry[1]:
                    if curr_url == url:
                        url_exists = True
              if not url_exists:
                    entry[1].append((url,0))
              return
(('http://www.example.com/index.html', 0), 'has error')
                curr_url, count = entry[1]
                print(count) # prints 0
    index.append([keyword, (url,0)])
index = []
add_to_index(index, 'foo', 'http://example.com/index.html')
add_to_index(index, 'foo', 'http://example.com/index.html')
</code>```

The exception is as follows:

```<code>Traceback (most recent call last):  File "/Users/user/foo.py", line 58, in add_to_index
    for curr_url, count in entry[1]:
ValueError: too many values to unpack (expected 2)
</code>```

Thank you.

答:
entry[1] is a two-tuple ('http://example.com/index.html', 0). The problem is that you try to iterate that tuple. The first thing iterated is the string 'http://example.com/index.html', which has more that two values, giving the unpack error. Instead of iterating, just assign

```<code>curr_url, count = entry[1]
</code>```

To demonstrate

```<code>>>> entry = ['foo', ('http://example.com/index.html', 0)]
>>> for curr_url, count in entry[1]:
...     print("success")
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 2)
</code>```

Breaking the unpacking into a separate step shows the problem

```<code>>>> for value in entry[1]:
...     print(value)
...     curr_rul, count = value
...
http://example.com/index.html
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
ValueError: too many values to unpack (expected 2)
</code>```

Body:
I was wondering why I'm getting an unpack error for entry[1] when the value will always be some tuple like so Tuple[str, int] for this function:

def add_to_index(index, keyword, url):
    for entry in index:
        if entry[0] == keyword:
              for curr_url, count in entry[1]:
                    if curr_url == url:
                        url_exists = True
              if not url_exists:
                    entry[1].append((url,0))
              return
(('http://www.example.com/index.html', 0), 'has error')
                curr_url, count = entry[1]
                print(count) # prints 0
    index.append([keyword, (url,0)])
index = []
add_to_index(index, 'foo', 'http://example.com/index.html')
add_to_index(index, 'foo', 'http://example.com/index.html')

The exception is as follows:

Traceback (most recent call last):  File "/Users/user/foo.py", line 58, in add_to_index
    for curr_url, count in entry[1]:
ValueError: too many values to unpack (expected 2)

Thank you.

Body:
entry[1] is a two-tuple ('http://example.com/index.html', 0). The problem is that you try to iterate that tuple. The first thing iterated is the string 'http://example.com/index.html', which has more that two values, giving the unpack error. Instead of iterating, just assign

curr_url, count = entry[1]

To demonstrate

>>> entry = ['foo', ('http://example.com/index.html', 0)]
>>> for curr_url, count in entry[1]:
...     print("success")
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 2)

Breaking the unpacking into a separate step shows the problem

>>> for value in entry[1]:
...     print(value)
...     curr_rul, count = value
...
http://example.com/index.html
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
ValueError: too many values to unpack (expected 2)


问:
onClick function is possibly null
I have a props function that is giving me an error that says object is possibly null.

```<code>import {Dropdown} from "react-bootstrap";
interface GenreButtonProps {
    key: number;
    id: number | null;
    genre: string;
    filterByGenre(id: string | null): void;
}
export default function GenreButton(props: GenreButtonProps) {
    return (
        <Dropdown.Item as={'button'} onClick={() => props.filterByGenre(props.id.toString())}>{props.genre}</Dropdown.Item>
    )
}
</code>```

The function is filterByGenre. The argument I'm passing in is giving me an error which is props.id.toString().

答:
ok thanks I figured it out.</p>
```<code>onclick{() => {
   if(props.id !== null) {
     props.filterByGenre(props.id.toString());
   }
}
</code>```

Title: onClick function is possibly null

Body:
I have a props function that is giving me an error that says object is possibly null.

import {Dropdown} from "react-bootstrap";
interface GenreButtonProps {
    key: number;
    id: number | null;
    genre: string;
    filterByGenre(id: string | null): void;
}
export default function GenreButton(props: GenreButtonProps) {
    return (
        <Dropdown.Item as={'button'} onClick={() => props.filterByGenre(props.id.toString())}>{props.genre}</Dropdown.Item>
    )
}

The function is filterByGenre. The argument I'm passing in is giving me an error which is props.id.toString().

Body:
ok thanks I figured it out.

onclick{() => {
   if(props.id !== null) {
     props.filterByGenre(props.id.toString());
   }
}


问:
Is it possible to use only lookaround to match characters that are not repeated immediately before and after?
For example, to match the first slash after the domain name in the URL.

Intent: Only match '/' in '.com/...' but not any '/' in 'https://'.

url = 'https://example.com/...';
[
url.match(       /(?<!\/)(?<slash>\/)(?!\k<slash>).../), // [A]
url.match(/(?<!\k<slash>)(?<slash>\/)(?!\k<slash>).../)  // [B]
]
```

The above [A] returns the correct match, but [B] is the kind of expression I want (although it did not match any characters), that is, to use the / character only 1 time in the body of regex literals.

Is there a generalized form of expression similar to [B] (using capturing groups or the like) and using only regular expression literals (instead of using the constructor (RegExp))?

答:
If all your inputs are URLs, this will do what you want:

```<code>/\/\/.+?(\/)/
</code>```

And then capture the first group:

url = 'https://example.com/...';
const matches = url.match(/\/\/.+?(\/)/);
console.log(matches[1]);```

Body:
For example, to match the first slash after the domain name in the URL.

Intent: Only match '/' in '.com/...' but not any '/' in 'https://'.

url = 'https://example.com/...';
[
url.match(       /(?<!\/)(?<slash>\/)(?!\k<slash>).../), // [A]
url.match(/(?<!\k<slash>)(?<slash>\/)(?!\k<slash>).../)  // [B]
]

The above [A] returns the correct match, but [B] is the kind of expression I want (although it did not match any characters), that is, to use the / character only 1 time in the body of regex literals.

Is there a generalized form of expression similar to [B] (using capturing groups or the like) and using only regular expression literals (instead of using the constructor (RegExp))?

Body:
If all your inputs are URLs, this will do what you want:

/\/\/.+?(\/)/

And then capture the first group:

url = 'https://example.com/...';
const matches = url.match(/\/\/.+?(\/)/);
console.log(matches[1]);


问:
Retrieve value of a column after update?
I update a counter (no autoincrement ... not my database ...) with this FDQuery SQL:

```<code>UPDATE CountersTables
SET Cnter = Cnter + 1
OUTPUT Inserted.Cnter
WHERE TableName = 'TableName'
</code>```

I execute FDQuery.ExecSQL and it works: 'Cnter' is incremented.

I need to retrieve the new 'Counter' value but the subsequent command

```<code>newvalue := FDQuery.FieldByName('Cnter').AsInteger
</code>```

Fails with error:

... EDatabaseError ... 'CountersTables: Field 'Cnter' not found.

What is the way to get that value?

答:
TFDQuery.ExecSQL() is meant for queries that don't return records. But you are asking your query to return a record. So use TFDQuery.Open() instead, eg:

FDQuery.SQL.Text :=
  'UPDATE CountersTables' +
  ' SET Cnter = Cnter + 1' +
  ' OUTPUT Inserted.Cnter' +
  ' WHERE TableName = :TableName';
FDQuery.ParamByName('TableName').AsString := 'TableName';
FDQuery.Open;
try
  NewValue := FDQuery.FieldByName('Cnter').AsInteger;
finally
  FDQuery.Close;
end;
```

If the database you are connected to does not support OUTPUT, UPDATE OUTPUT into a variable shows some alternative ways you can save the updated counter into a local SQL variable/table that you can then SELECT from.

Body:
I update a counter (no autoincrement ... not my database ...) with this FDQuery SQL:

UPDATE CountersTables
SET Cnter = Cnter + 1
OUTPUT Inserted.Cnter
WHERE TableName = 'TableName'

I execute FDQuery.ExecSQL and it works: 'Cnter' is incremented.

I need to retrieve the new 'Counter' value but the subsequent command

newvalue := FDQuery.FieldByName('Cnter').AsInteger

Fails with error:

... EDatabaseError ... 'CountersTables: Field 'Cnter' not found.

What is the way to get that value?

Body:
TFDQuery.ExecSQL() is meant for queries that don't return records. But you are asking your query to return a record. So use TFDQuery.Open() instead, eg:

FDQuery.SQL.Text :=
  'UPDATE CountersTables' +
  ' SET Cnter = Cnter + 1' +
  ' OUTPUT Inserted.Cnter' +
  ' WHERE TableName = :TableName';
FDQuery.ParamByName('TableName').AsString := 'TableName';
FDQuery.Open;
try
  NewValue := FDQuery.FieldByName('Cnter').AsInteger;
finally
  FDQuery.Close;
end;

If the database you are connected to does not support OUTPUT, UPDATE OUTPUT into a variable shows some alternative ways you can save the updated counter into a local SQL variable/table that you can then SELECT from.


问:
Wear Engine how to cancel/abort file sending on wearable (Java)?
I use Wear Engine to send files from watch (HarmonyOS) to phone (Android).
I can't find any method to cancel/abort file transfer. I imagine a file can weigh many megabytes and there is no option to stop the bytes transfer.

P2pClient object doesn't expose any method to cancel file sending.
P2pClient send() method returns Task result but I was unable to find here any way to stop this Task returned by P2pClient.

Wear Engine API Java

答:
Call the unregisterReceiver method to cancel the reception of messages or files from your wearable app. The principle behind this is to unregister a listener for Wear Engine.

```<code>// Step 6: Your phone app cancels receiving the messages or files sent by the wearable app.
HiWear.getP2pClient(this).unregisterReceiver(receiver)
    .addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void successVoid) {
            // Your phone app cancels the reception of messages or files.
        }
    })
    .addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(Exception e) {
            // Your phone app fails to cancel the reception of messages or files.
        }
    });
</code>```

For more info, pls refer to this docs.

Body:
Call the unregisterReceiver method to cancel the reception of messages or files from your wearable app. The principle behind this is to unregister a listener for Wear Engine.

// Step 6: Your phone app cancels receiving the messages or files sent by the wearable app.
HiWear.getP2pClient(this).unregisterReceiver(receiver)
    .addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void successVoid) {
            // Your phone app cancels the reception of messages or files.
        }
    })
    .addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(Exception e) {
            // Your phone app fails to cancel the reception of messages or files.
        }
    });

For more info, pls refer to this docs.


问:
Prometheus-- context deadline exceeded for a responsive target in prometheus UI
When I open the prometheus target in a browser it is responding, but in prometheus UI it is showing the error -- Get endpoint context line exceeded

答:
I do have the same problem, and the problem is the Network.
I installed my machine on Virtualbox and activate the NAT to supply the Internet inside my master node. I turn off my NAT and use a bridge connection instead.
I do change the scrape but it's not working on my side.

NB: I don't have docker and my memory is only 4GB.


问:
Access function in class A from non related class B using object of class A

Possible Duplicate:

  Call function of class ONE from class TWO without extend?

why this does not work?

```<code>    class A {
        function one() {
            echo "Class A";
        }
    }

    class B {
        function two() {
            echo "Class B";
            $a->one();
        }
    }

    $a = new A;
    $b = new B;

    $b->two();
</code>```

答:
As mentioned, this is a variable scope problem. The scope of B::two() does not include the variable $a which has been declared in the global namespace.

The best thing to do is pass $a to B as a dependency. There would be several ways to do this...

For single use in B::two()

```<code>public function two(A $a)
{
    echo 'Class B';
    $a->one();
}
</code>```

Then

```<code>$b->two($a);
</code>```

As a property of B

```<code>class B
{
    private $a;

    public function __construct(A $a)
    {
        $this->a = $a;
    }

    public function two()
    {
        echo 'Class B';
        $this->a->one();
    }
}
</code>```

then

```<code>$b = new B($a);
$b->two();
</code>```

Body:
Possible Duplicate:

  Call function of class ONE from class TWO without extend?

why this does not work?

    class A {
        function one() {
            echo "Class A";
        }
    }

    class B {
        function two() {
            echo "Class B";
            $a->one();
        }
    }

    $a = new A;
    $b = new B;

    $b->two();

Body:
As mentioned, this is a variable scope problem. The scope of B::two() does not include the variable $a which has been declared in the global namespace.

The best thing to do is pass $a to B as a dependency. There would be several ways to do this...

For single use in B::two()

public function two(A $a)
{
    echo 'Class B';
    $a->one();
}

Then

$b->two($a);

As a property of B

class B
{
    private $a;

    public function __construct(A $a)
    {
        $this->a = $a;
    }

    public function two()
    {
        echo 'Class B';
        $this->a->one();
    }
}

then

$b = new B($a);
$b->two();


问:
Efficiency in extracting data from webscraping in R
This is no doubt very simple so apologies but I am new to webscraping and am trying to extract multiple datapoints in one call using rvest. Let's take for example the following code (NB I have not used the actual website which I have replaced in this code snippet with xxxxxx.com):

```<code>univsalaries <- lapply(paste0('https://xxxxxx.com/job/p', 1:20,'/key=%F9%80%76&final=1&jump=1&PGTID=0d3408-0000-24gf-ac2b-810&ClickID=2'),
                   function(url_base){
                     url_base %>% read_html() %>%
                       html_nodes('.salary') %>%
                       html_text()
                   })
</code>```

Let's say there is another html node I want to scrape (.company). Obviously I can make a separate call and fetch that data, but I want to understand the syntax of how I could extract the information in the same call.

I tried to put it in the following structure, but the code sent me to the debugger

```<code> ....     function(url_base){
                                  url_base %>% read_html() %>%
                                    Salary <- univsalaries %>%
                                    html_nodes('.salary') %>% html_text()
                                    Company <- univsalaries %>%
                                      html_nodes('.company') %>% html_text()
                                    dt<-tibble(Salary,Company)
                                })
</code>```

答:
Read the webpage once and then you can extract multiple values from the same page.

```<code>library(purrr)
library(rvest)

univsalaries <- map(paste0('https://xxxxxx.com/job/p', 1:20,'/key=%F9%80%76&final=1&jump=1&PGTID=0d3408-0000-24gf-ac2b-810&ClickID=2'),
                       function(url_base){
                         webpage <- url_base %>% read_html()
                         data.frame(Salary = webpage %>% html_nodes('.salary') %>% html_text(),
                                    Company = webpage %>% html_nodes('.company') %>% html_text())
                       })
</code>```

This would give you a list of dataframes (one for every link), if you need one combined dataframe then use map_df instead of map.

Body:
This is no doubt very simple so apologies but I am new to webscraping and am trying to extract multiple datapoints in one call using rvest. Let's take for example the following code (NB I have not used the actual website which I have replaced in this code snippet with xxxxxx.com):

univsalaries <- lapply(paste0('https://xxxxxx.com/job/p', 1:20,'/key=%F9%80%76&final=1&jump=1&PGTID=0d3408-0000-24gf-ac2b-810&ClickID=2'),
                   function(url_base){
                     url_base %>% read_html() %>%
                       html_nodes('.salary') %>%
                       html_text()
                   })

Let's say there is another html node I want to scrape (.company). Obviously I can make a separate call and fetch that data, but I want to understand the syntax of how I could extract the information in the same call.

I tried to put it in the following structure, but the code sent me to the debugger

 ....     function(url_base){
                                  url_base %>% read_html() %>%
                                    Salary <- univsalaries %>%
                                    html_nodes('.salary') %>% html_text()
                                    Company <- univsalaries %>%
                                      html_nodes('.company') %>% html_text()
                                    dt<-tibble(Salary,Company)
                                })

Body:
Read the webpage once and then you can extract multiple values from the same page.

library(purrr)
library(rvest)

univsalaries <- map(paste0('https://xxxxxx.com/job/p', 1:20,'/key=%F9%80%76&final=1&jump=1&PGTID=0d3408-0000-24gf-ac2b-810&ClickID=2'),
                       function(url_base){
                         webpage <- url_base %>% read_html()
                         data.frame(Salary = webpage %>% html_nodes('.salary') %>% html_text(),
                                    Company = webpage %>% html_nodes('.company') %>% html_text())
                       })

This would give you a list of dataframes (one for every link), if you need one combined dataframe then use map_df instead of map.


问:
EJB is not abstract and does not override abstract method fix solution?
I get this error in the EJB class I tried to see in the other questions but I couldn't solve it, can anyone help me? Thanks

"CanzoneEJB is not abstract and does not override abstract method cercaPerSerataEsibizione(Integer) in CanzoneEJBRemote"

CanzoneEJB

Method CanzoneEJB

CanzoneEJBRemote

答:
The method cercaPerSerataEsibizione in the CanzoneEJBRemote interface takes an Integer, but the corresponding method in CanzoneEJB class takes a String. Since the abstract method and the overriding method have different types for the serataesibizione parameter, the method is not overridden and Java gives an error.

Either change the aforementioned method in CanzoneEJBRemote to take a String, or change the method in CanzoneEJB to take an Integer.


问:
My kirby website wasn't hosted(I'm totally new to this)
I watched a tutorial about hosting a website using Kirby
and read the documentation on Kirby official website.

As far as I followed,
What I had to do is downloading starter-kit and go to domain and register that.

(I have my license key- Kirby 3 License and the licenses page shows my domain)

After I registered my license in my panel from my kirby template.(now the register button is gone).

When I visit my website url shown on my license page "soonkpaik.com".
It wasn't published on the web yet.

What am I missing now?
Really Can't find any documentation nor tutorial about it.
I assume there is an extreme basic thing for publishing my page on the web that Kirby and youtubers assume that I already know.

Thank you.

答:
Kirby doesn't help at all with deployment or publishing as far as I know. That's considered a separate concern. You'll have to find a PHP-enabled host on which you can manually launch a Kirby instance, similarly to how you launched it on your local machine.

Some (rare) web hosts offer some helpers to get started with Kirby. The only one I've found is A2hosting (which I don't recommend), which provides you with a relatively standard (and horribly broken) cPanel environment along with the Softaculous software installer. Once in Softwaculous, you can find the Kirby installer by clicking on the Wordpress installer (ironically enough) and searching for Kirby.


问:
Setting the table name in telegraf mqtt_consumer plugin
I am using telegraf to write mqtt messages to questdb. Currently, all my mqtt messages are written into the table "mqtt_consumer" by default. How can I change the name, where the mqtt_consumer is writing the data into the db?

```<code>[inputs.mqtt_consumer.tags]
destinationdb = "mqtt_data"
</code>```

That doesn't work. I cant find an option for that. It could be that the table name needs to be set in the output plugin but I can't find any option for that. This is my output plugin:

```<code>[[outputs.socket_writer]]
adress = "tcp://localhost:9000"
</code>```

答:
I believe questdb uses the metric name to determine what table it writes to. The metric name is determined by the input name in most cases.

You can rename a metric via:

```<code>[[processors.rename]]
  [[processors.rename.replace]]
    measurement = "mqtt_consumer"
    dest = "mqtt_data"
</code>```

Edit:

I forgot about the name_override option. You can use that to change the name of the measurement directly. See it listed in the configuration options docs. You could set this for every mqtt_consumer input plugin to get distinct measurement names.

Body:
I am using telegraf to write mqtt messages to questdb. Currently, all my mqtt messages are written into the table "mqtt_consumer" by default. How can I change the name, where the mqtt_consumer is writing the data into the db?

[inputs.mqtt_consumer.tags]
destinationdb = "mqtt_data"

That doesn't work. I cant find an option for that. It could be that the table name needs to be set in the output plugin but I can't find any option for that. This is my output plugin:

[[outputs.socket_writer]]
adress = "tcp://localhost:9000"

Body:
I believe questdb uses the metric name to determine what table it writes to. The metric name is determined by the input name in most cases.

You can rename a metric via:

[[processors.rename]]
  [[processors.rename.replace]]
    measurement = "mqtt_consumer"
    dest = "mqtt_data"

Edit:

I forgot about the name_override option. You can use that to change the name of the measurement directly. See it listed in the configuration options docs. You could set this for every mqtt_consumer input plugin to get distinct measurement names.


问:
What is the correct way to include one js file in another?
The following JavaScript code works:

let Color = require('color');

class Example {
    its_not_easy_being_green() {
        return Color('green');
    }
}

test('It is not easy being green', () => {
    expect(new Example().its_not_easy_being_green()).toBeDefined();
})
```
<p>and <code>npx jest</code> gets me a greenbar.</p>
```$ npx jest
 PASS  test/example.spec.js
  ✓ It is not easy being green (2 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        0.351 s, estimated 1 s
Ran all test suites.
```
<p>However, any time I try to separate the class from the test I get various errors:</p>
<p>The most common is one about not being permitted to use import outside a module.</p>
<p>Or that <code>Example</code> is not a constructor.</p>
<p>What I am trying to do is move everything that isn't the three line test <em>out</em> of the JavaScript file that I've posted above.</p>
<p>If this were Java, I'd move that stuff into a separate <code>.java</code> file and then <code>import</code> that file in my test.</p>
<p>If this were C there would be a linker and <code>#include</code> involved.</p>
<p>What I've tried is to create an <code>Example.js</code> file:</p>
<pre class="lang-js prettyprint-override"><code>let Color = require('color');

class Example {
    its_not_easy_being_green() {
        return Color('green');
    }
}
</code>```

and then require it in the test:

```<code>let Example = require('Example.js')

test('It is not easy being green', () => {
    expect(new Example().its_not_easy_being_green()).toBeDefined();
})
</code>```

But that gets me a complaint about Example not being a constructor, which, I suppose is true. It is a class, which presumably has a pretty inert default constructor of some kind.

I've also tried replacing the require with an import:

```<code>import('Example.js')

test('It is not easy being green', () => {
    expect(new Example().its_not_easy_being_green()).toBeDefined();
})
</code>```

But that gets complaints about not being permitted to use import outside a module.

Is it possible to separate the jest test from the code being tested in JavaScript?

答:
There is no #include in Javascript - it uses a module system instead where you export things you want to share.

It is best to learn the tools the language offers rather than trying to force it to do something the way a different language does things.

Also, note there are two types of modules in nodejs, CommonJS modules that use require() and module.exports and ESM modules that use import and export. Your project appears to be set up for CommonJS so that's what you would use unless you want to configure the project to be an ESM module project and then use the ESM rules for importing and exporting.

For a CommonJS project:

```<code>const Color = require('color');

class Example {
    its_not_easy_being_green() {
        return Color('green');
    }
}

module.exports.Example = Example;
</code>```

Then, in your main file:

```<code>const { Example } = require('./Example.js')

test('It is not easy being green', () => {
    expect(new Example().its_not_easy_being_green()).toBeDefined();
});
</code>```

FYI, require(someModule) gets you whatever module.exports was.  If you assign something directly to module.exports such as:

```<code>// in color.js

module.exports = function Color() {
     // do something here
}
</code>```

Then, you would use that like this:

```<code>const Color = require('color');
</code>```

But, if you just add a property to the module.exports object such as this:

```<code>// in Example.js
const Color = require('color');

class Example {
    its_not_easy_being_green() {
        return Color('green');
    }
}

module.exports.Example = Example;
</code>```

Then you must get the .Example property off the exported object in any of these ways:

```<code>const { Example } = require('./Example.js');

const Example = require('./Example.js').Example;

const exampleExports = require('./Example.js');
const Example = exampleExports.Example;
</code>```

Note, the brackets in the syntax:

```<code>const { Example } = require('./Example.js');
</code>```

is called "object destructuring" and is a shortcut syntax.

The color.js method above is done when there's only one main export from the module so rather than exporting an object, you export the function directly.

The example.js method above is done when you have more than one main export from the module (or you want to retain the flexibility to have more than one top-level export in the future) like this:

```<code>// in Example.js
const Color = require('color');

class Example {
    its_not_easy_being_green() {
        return Color('green');
    }
}

class SubExample extends Example {
    its_not_easy_being_red() {
        return Color('red');
    }
}

// multiple exports
module.exports.Example = Example;
module.exports.SubExample = SubExample;
</code>```

Body:
The following JavaScript code works:

let Color = require('color');

class Example {
    its_not_easy_being_green() {
        return Color('green');
    }
}

test('It is not easy being green', () => {
    expect(new Example().its_not_easy_being_green()).toBeDefined();
})

and npx jest gets me a greenbar.

$ npx jest
 PASS  test/example.spec.js
  ✓ It is not easy being green (2 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        0.351 s, estimated 1 s
Ran all test suites.

However, any time I try to separate the class from the test I get various errors:

The most common is one about not being permitted to use import outside a module.

Or that Example is not a constructor.

What I am trying to do is move everything that isn't the three line test out of the JavaScript file that I've posted above.

If this were Java, I'd move that stuff into a separate .java file and then import that file in my test.

If this were C there would be a linker and #include involved.

What I've tried is to create an Example.js file:

let Color = require('color');

class Example {
    its_not_easy_being_green() {
        return Color('green');
    }
}

and then require it in the test:

let Example = require('Example.js')

test('It is not easy being green', () => {
    expect(new Example().its_not_easy_being_green()).toBeDefined();
})

But that gets me a complaint about Example not being a constructor, which, I suppose is true. It is a class, which presumably has a pretty inert default constructor of some kind.

I've also tried replacing the require with an import:

import('Example.js')

test('It is not easy being green', () => {
    expect(new Example().its_not_easy_being_green()).toBeDefined();
})

But that gets complaints about not being permitted to use import outside a module.

Is it possible to separate the jest test from the code being tested in JavaScript?

Body:
There is no #include in Javascript - it uses a module system instead where you export things you want to share.

It is best to learn the tools the language offers rather than trying to force it to do something the way a different language does things.

Also, note there are two types of modules in nodejs, CommonJS modules that use require() and module.exports and ESM modules that use import and export. Your project appears to be set up for CommonJS so that's what you would use unless you want to configure the project to be an ESM module project and then use the ESM rules for importing and exporting.

For a CommonJS project:

const Color = require('color');

class Example {
    its_not_easy_being_green() {
        return Color('green');
    }
}

module.exports.Example = Example;

Then, in your main file:

const { Example } = require('./Example.js')

test('It is not easy being green', () => {
    expect(new Example().its_not_easy_being_green()).toBeDefined();
});

FYI, require(someModule) gets you whatever module.exports was.  If you assign something directly to module.exports such as:

// in color.js

module.exports = function Color() {
     // do something here
}

Then, you would use that like this:

const Color = require('color');

But, if you just add a property to the module.exports object such as this:

// in Example.js
const Color = require('color');

class Example {
    its_not_easy_being_green() {
        return Color('green');
    }
}

module.exports.Example = Example;

Then you must get the .Example property off the exported object in any of these ways:

const { Example } = require('./Example.js');

const Example = require('./Example.js').Example;

const exampleExports = require('./Example.js');
const Example = exampleExports.Example;

Note, the brackets in the syntax:

const { Example } = require('./Example.js');

is called "object destructuring" and is a shortcut syntax.

The color.js method above is done when there's only one main export from the module so rather than exporting an object, you export the function directly.

The example.js method above is done when you have more than one main export from the module (or you want to retain the flexibility to have more than one top-level export in the future) like this:

// in Example.js
const Color = require('color');

class Example {
    its_not_easy_being_green() {
        return Color('green');
    }
}

class SubExample extends Example {
    its_not_easy_being_red() {
        return Color('red');
    }
}

// multiple exports
module.exports.Example = Example;
module.exports.SubExample = SubExample;


问:
My ListView is not appearing when I transition to the next page
I am currently using the default layout on in my program. The first page is good, it goes to the next page with no issues. The second page where I have the listview, it doesnt show

.java file

```<code>package com.example.alimkutchhi_comp304_001_assign2;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.ArrayList;

public class SelectPhoneBrandActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_phone_brand);

        ListView listview = findViewById(R.id.lstvPhones);

        ArrayList<String> phones = new ArrayList<>();
        phones.add("iPhone");
        phones.add("Samsung");
        phones.add("Google Pixel");
        phones.add("Huawei");

        ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_2, phones);

    }
}
</code>```

I followed a tutorial so I know this should be the correct format
This is what I wrote in my .xml file

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".SelectPhoneBrandActivity">

    <ListView
        android:id="@+id/lstvPhones"
        android:layout_width="379dp"
        android:layout_height="699dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Again, this should be correct, so maybe it has something to do with Android Studio? Hopefully I can get an answer to this issue.

答:
I was able to figure this one out thankfully. What I forgot to do was add  listview.setAdapter(adapter); to it

The bottom line of the java file is now this

```<code> ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, phones);
        listview.setAdapter(adapter);
</code>```

I also made the mistake of my layout being wrong, its simple list item 1 that should be used

Thank you for the help. I will use this place better next time

Body:
I am currently using the default layout on in my program. The first page is good, it goes to the next page with no issues. The second page where I have the listview, it doesnt show

.java file

package com.example.alimkutchhi_comp304_001_assign2;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.ArrayList;

public class SelectPhoneBrandActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_phone_brand);

        ListView listview = findViewById(R.id.lstvPhones);

        ArrayList<String> phones = new ArrayList<>();
        phones.add("iPhone");
        phones.add("Samsung");
        phones.add("Google Pixel");
        phones.add("Huawei");

        ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_2, phones);

    }
}

I followed a tutorial so I know this should be the correct format
This is what I wrote in my .xml file

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".SelectPhoneBrandActivity">

    <ListView
        android:id="@+id/lstvPhones"
        android:layout_width="379dp"
        android:layout_height="699dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Again, this should be correct, so maybe it has something to do with Android Studio? Hopefully I can get an answer to this issue.

Body:
I was able to figure this one out thankfully. What I forgot to do was add  listview.setAdapter(adapter); to it

The bottom line of the java file is now this

 ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, phones);
        listview.setAdapter(adapter);

I also made the mistake of my layout being wrong, its simple list item 1 that should be used

Thank you for the help. I will use this place better next time


问:
Extract specific list elements from a nested list in R?
I have a nested list that looks like this:

```<code>x <- list(list(a = c(1,10), b=c(2,10)), list(c=c(3,10), d=c(6,10)), list(e= c(3,10)))
> x
[[1]]
[[1]]$a
[1]  1 10

[[1]]$b
[1]  2 10

[[2]]
[[2]]$c
[1]  3 10

[[2]]$d
[1]  6 10

[[3]]
[[3]]$e
[1]  3 10
</code>```

I'm trying to extract just the first value from each list element. However, if the length of a list is greater than 1, then I want to add the extracted values together.

For example, in my list x above, we can see that the first list (i.e., x[[1]]) contains a and b... so I want to extract the 1st values from this list (in this case, 1 and 2) and since they belong to the same list, they get added together.

At the end, Im just trying to return a vector of the extracted (and where necessary, added) values. So in my example, I would expect a vector like: [1] 3 9 3.

答:
Using nested sapply -

```<code>sapply(x, function(y) sum(sapply(y, head, 1)))
#[1] 3 9 3
</code>```

Or combine each list into a matrix and take sum of first column/row.

```<code>sapply(x, function(y) sum(do.call(rbind, y)[, 1]))
#sapply(x, function(y) sum(do.call(cbind, y)[1, ]))
</code>```

Body:
I have a nested list that looks like this:

x <- list(list(a = c(1,10), b=c(2,10)), list(c=c(3,10), d=c(6,10)), list(e= c(3,10)))
> x
[[1]]
[[1]]$a
[1]  1 10

[[1]]$b
[1]  2 10

[[2]]
[[2]]$c
[1]  3 10

[[2]]$d
[1]  6 10

[[3]]
[[3]]$e
[1]  3 10

I'm trying to extract just the first value from each list element. However, if the length of a list is greater than 1, then I want to add the extracted values together.

For example, in my list x above, we can see that the first list (i.e., x[[1]]) contains a and b... so I want to extract the 1st values from this list (in this case, 1 and 2) and since they belong to the same list, they get added together.

At the end, Im just trying to return a vector of the extracted (and where necessary, added) values. So in my example, I would expect a vector like: [1] 3 9 3.

Body:
Using nested sapply -

sapply(x, function(y) sum(sapply(y, head, 1)))
#[1] 3 9 3

Or combine each list into a matrix and take sum of first column/row.

sapply(x, function(y) sum(do.call(rbind, y)[, 1]))
#sapply(x, function(y) sum(do.call(cbind, y)[1, ]))


问:
How to implement a Fibonacci sequence in JavaScript?
I need to implement a Fibonacci sequence Оthrough a function for my homework. And I need to implement a function so that each subsequent call will output the next number in the sequence. It seems simple if you pass an argument to the function, but I'm not allowed to do that by the assignment. I have implemented this function with an argument, the code is shown below:

function helperFibonacci(n) {
  let number1 = 0;
  let number2 = 1;

  for (i = 0; i < n; i++) {
    let current = number1 + number2;
    number1 = number2;
    number2 = current;
    console.log(current);
  }
}

helperFibonacci(2);```

Please help me implement this function without passing an argument. thanks!

答:
OPTION 1 USING GENERATOR FUNCTIONS

I think the proper way to do this is to use a Generator function.
Theese are functions meant to return sequences, they are built for this kinds of situations where you have a sequence that you can calculate based on a formula and want to get the next value at will.

So lets say you have a simple formula to calculate the nth fibonacci number

```<code>function fibonacci(n = 0) {
    if (n < 0){ throw 'Fibonacci not defined for negative numbers'}
    if (n < 2) { return n};
    return fibonacci(n - 1) + fibonacci(n - 2);
}
</code>```

so then you just wrap it in a generator function (using the function* syntax, note the *)

```<code>function* fibonacciGenerator() {
  var index = 0;
  while (true){
        // yields the next fibonacci
        yield fibonacci(index++);
    }
}
</code>```

Then you can use it creating a new generator and calling the next function to retrieve the next element in the sequence. Note the while true here represents that the sequence is infinite, that is that it never ends and I can keep getting more and more elements. This does not become an infinite loop because of the yield keyword

```<code>let fibonacciSequence = fibonacciGenerator();
fibonacciSequence.next().value; // 0
fibonacciSequence.next().value; // 1
fibonacciSequence.next().value; // 1
fibonacciSequence.next().value; // 2
</code>```

You can read more about generator functions here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*

NOT USING GENERATOR FUNCTIONS

If you are not familiar with generator functions or cannot use them, you can do it with a regular function and save the "state". I dont recommend at all saving it in a global variable because its a considered bad practice. But you can create a closure.

Closures are like functions with their own scope, or environment where they can have variables.

```<code>function fibonacciGenerator() {
    var index = 0;
    return function () {
        return fibonacci(index++);
    }
}
</code>```

then use it

```<code>let fibonacciSequence = fibonacciGenerator();
fibonacciSequence(); // 0
fibonacciSequence(); // 1
fibonacciSequence(); // 1
fibonacciSequence(); // 2
</code>```

note that the structure is similar than that of generators, but we have normal functions instead.

You can read more about closures here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures

Body:
I need to implement a Fibonacci sequence Оthrough a function for my homework. And I need to implement a function so that each subsequent call will output the next number in the sequence. It seems simple if you pass an argument to the function, but I'm not allowed to do that by the assignment. I have implemented this function with an argument, the code is shown below:

function helperFibonacci(n) {
  let number1 = 0;
  let number2 = 1;

  for (i = 0; i < n; i++) {
    let current = number1 + number2;
    number1 = number2;
    number2 = current;
    console.log(current);
  }
}

helperFibonacci(2);

Please help me implement this function without passing an argument. thanks!

Body:
OPTION 1 USING GENERATOR FUNCTIONS

I think the proper way to do this is to use a Generator function.
Theese are functions meant to return sequences, they are built for this kinds of situations where you have a sequence that you can calculate based on a formula and want to get the next value at will.

So lets say you have a simple formula to calculate the nth fibonacci number

function fibonacci(n = 0) {
    if (n < 0){ throw 'Fibonacci not defined for negative numbers'}
    if (n < 2) { return n};
    return fibonacci(n - 1) + fibonacci(n - 2);
}

so then you just wrap it in a generator function (using the function* syntax, note the *)

function* fibonacciGenerator() {
  var index = 0;
  while (true){
        // yields the next fibonacci
        yield fibonacci(index++);
    }
}

Then you can use it creating a new generator and calling the next function to retrieve the next element in the sequence. Note the while true here represents that the sequence is infinite, that is that it never ends and I can keep getting more and more elements. This does not become an infinite loop because of the yield keyword

let fibonacciSequence = fibonacciGenerator();
fibonacciSequence.next().value; // 0
fibonacciSequence.next().value; // 1
fibonacciSequence.next().value; // 1
fibonacciSequence.next().value; // 2

You can read more about generator functions here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*

NOT USING GENERATOR FUNCTIONS

If you are not familiar with generator functions or cannot use them, you can do it with a regular function and save the "state". I dont recommend at all saving it in a global variable because its a considered bad practice. But you can create a closure.

Closures are like functions with their own scope, or environment where they can have variables.

function fibonacciGenerator() {
    var index = 0;
    return function () {
        return fibonacci(index++);
    }
}

then use it

let fibonacciSequence = fibonacciGenerator();
fibonacciSequence(); // 0
fibonacciSequence(); // 1
fibonacciSequence(); // 1
fibonacciSequence(); // 2

note that the structure is similar than that of generators, but we have normal functions instead.

You can read more about closures here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures


问:
Python: append not adding to an empty list
Hi sorry if this is an obvious one, looked around online and I can't seem to find what I'm doing wrong.

I am trying to compare the contents of two lists, in two separate csv files (file A and file B). Both csv files are of x rows, but only 1 column each. File A consists of rows with sentences in each, file B consists of single words. My goal is to search the rows in file B, and if any of these rows appear in file A, append the relevant rows from file A to a separate, empty list to be exported. The code I am running is as follows:

```<code>import pandas as pd
#Importing csv files

##File A is 2 rows of sentences in 1 column, e.g. "This list should be picked up for the word DISHWASHER" and "This sentence should not appear in list_AB"
file_A = pd.read_csv(r"C:\Users\User\Desktop\File\file_A.csv")

##File B is 2 rows of singular words that should appear in file A e.g. "DISHWASHER", "QWERTYXYZ123"
file_B = pd.read_csv(r"C:\Users\User\Desktop\File\file_B.csv", converters={i: str for i in range(10)})

#Convert csv files to lists
file_A2 = file_A.values.tolist()
file_B2 = file_B.values.tolist()

#Empty list
list_AB = []

#for loop supposed to filter file_A based on file_B
for x in file_A2:
    words = x[0].split(" ")
    #print(words)
    for y in file_B2:
        #print(y)
        if y in words:
            list_AB.append(x)

print(list_AB)
</code>```

The problem is that print(list_AB) only returns an empty list ([]), not a filtered version of file_A. The reason I want to do it this way is because the actual csv files I want to read consist of 21600 (file A) and 50400 (file B) rows. Apologies in advance if this is a really basic question.

Edit: Added images of csv file examples, couldn't see how to upload files.

答:
The problem is in the if-statement y in words.

Here y is a list. You're searching for a list inside a list of strings (not a list of lists).

Using y[0] in words solve your problem.

Body:
Hi sorry if this is an obvious one, looked around online and I can't seem to find what I'm doing wrong.

I am trying to compare the contents of two lists, in two separate csv files (file A and file B). Both csv files are of x rows, but only 1 column each. File A consists of rows with sentences in each, file B consists of single words. My goal is to search the rows in file B, and if any of these rows appear in file A, append the relevant rows from file A to a separate, empty list to be exported. The code I am running is as follows:

import pandas as pd
#Importing csv files

##File A is 2 rows of sentences in 1 column, e.g. "This list should be picked up for the word DISHWASHER" and "This sentence should not appear in list_AB"
file_A = pd.read_csv(r"C:\Users\User\Desktop\File\file_A.csv")

##File B is 2 rows of singular words that should appear in file A e.g. "DISHWASHER", "QWERTYXYZ123"
file_B = pd.read_csv(r"C:\Users\User\Desktop\File\file_B.csv", converters={i: str for i in range(10)})

#Convert csv files to lists
file_A2 = file_A.values.tolist()
file_B2 = file_B.values.tolist()

#Empty list
list_AB = []

#for loop supposed to filter file_A based on file_B
for x in file_A2:
    words = x[0].split(" ")
    #print(words)
    for y in file_B2:
        #print(y)
        if y in words:
            list_AB.append(x)

print(list_AB)

The problem is that print(list_AB) only returns an empty list ([]), not a filtered version of file_A. The reason I want to do it this way is because the actual csv files I want to read consist of 21600 (file A) and 50400 (file B) rows. Apologies in advance if this is a really basic question.

Edit: Added images of csv file examples, couldn't see how to upload files.


问:
Why is ".map" slower then "while/for loop" in Dart(Flutter)
I saw this article:
https://itnext.io/comparing-darts-loops-which-is-the-fastest-731a03ad42a2

It says that ".map" is slow with benchmark result

But I don't understand why slower than while/for loop

How does it work in low level?

I think it's because .map is called an unnamed method like this (_){ }

Can you explain that in detail?

答:
Its because mapping an array will create a copy of each value than modify the original array.

Since a while/for loop does not copy the values but rather just accesses them using their index, it is a lot faster.


问:
UNION works with CTE, but not without?
I'm using PostgreSQL 11.12.

I have this query:

```<code>select first_name, length(first_name)
from db_employee
where length(first_name) =
(select max(length(first_name)) from db_employee)
order by 1
limit 1
union
select first_name, length(first_name)
from db_employee
where length(first_name) =
(select min(length(first_name)) from db_employee)
order by 1
limit 1
</code>```

and when I run it I get this error:

```<code>syntax error at or near "union"
</code>```

If I use CTE it works:

```<code>with cte1 as
(select first_name, length(first_name)
from db_employee
where length(first_name) =
(select max(length(first_name)) from db_employee)
order by 1
limit 1),

cte2 as
(select first_name, length(first_name)
from db_employee
where length(first_name) =
(select min(length(first_name)) from db_employee)
order by 1
limit 1)

select * from cte1
union
select * from cte2;
</code>```

Why does the first query result in syntax error?  Is it possible to get it to work without using CTE?

答:
To include a LIMIT clause per SELECT in a UNION query, you must add parentheses. Like:

(  -- !
SELECT first_name, length(first_name)
FROM   db_employee
WHERE  length(first_name) = (SELECT max(length(first_name)) FROM db_employee)
ORDER  BY 1
LIMIT  1
) -- !
UNION
( -- !
SELECT first_name, length(first_name)
FROM   db_employee
WHERE  length(first_name) = (SELECT min(length(first_name)) FROM db_employee)
ORDER  BY 1
LIMIT  1
) -- !
```
<p>Related:</p>
<ul>
<li>Calculate difference of multiple highest and lowest column values</li>
</ul>
<p>That said, your query can be optimized. Use instead:</p>
<pre class="lang-sql prettyprint-override"><code>(
SELECT first_name, length(first_name)
FROM   db_employee
ORDER  BY length(first_name) DESC NULLS LAST, first_name
LIMIT  1
)
UNION ALL  -- my guess
(
SELECT first_name, length(first_name)
FROM   db_employee
ORDER  BY length(first_name), first_name
LIMIT  1
);
</code>```

Subtle difference: this does not completely exclude rows with first_name IS NULL, but that only shows if all rows have first_name IS NULL.

About NULLS LAST:

Sort by column ASC, but NULL values first?

Title: UNION works with CTE, but not without?

Body:
I'm using PostgreSQL 11.12.

I have this query:

select first_name, length(first_name)
from db_employee
where length(first_name) =
(select max(length(first_name)) from db_employee)
order by 1
limit 1
union
select first_name, length(first_name)
from db_employee
where length(first_name) =
(select min(length(first_name)) from db_employee)
order by 1
limit 1

and when I run it I get this error:

syntax error at or near "union"

If I use CTE it works:

with cte1 as
(select first_name, length(first_name)
from db_employee
where length(first_name) =
(select max(length(first_name)) from db_employee)
order by 1
limit 1),

cte2 as
(select first_name, length(first_name)
from db_employee
where length(first_name) =
(select min(length(first_name)) from db_employee)
order by 1
limit 1)

select * from cte1
union
select * from cte2;

Why does the first query result in syntax error?  Is it possible to get it to work without using CTE?

Body:
To include a LIMIT clause per SELECT in a UNION query, you must add parentheses. Like:

(  -- !
SELECT first_name, length(first_name)
FROM   db_employee
WHERE  length(first_name) = (SELECT max(length(first_name)) FROM db_employee)
ORDER  BY 1
LIMIT  1
) -- !
UNION
( -- !
SELECT first_name, length(first_name)
FROM   db_employee
WHERE  length(first_name) = (SELECT min(length(first_name)) FROM db_employee)
ORDER  BY 1
LIMIT  1
) -- !

Related:

Calculate difference of multiple highest and lowest column values

That said, your query can be optimized. Use instead:

(
SELECT first_name, length(first_name)
FROM   db_employee
ORDER  BY length(first_name) DESC NULLS LAST, first_name
LIMIT  1
)
UNION ALL  -- my guess
(
SELECT first_name, length(first_name)
FROM   db_employee
ORDER  BY length(first_name), first_name
LIMIT  1
);

Subtle difference: this does not completely exclude rows with first_name IS NULL, but that only shows if all rows have first_name IS NULL.

About NULLS LAST:

Sort by column ASC, but NULL values first?