问:
Using additional domain fields in WHMCS with python
I'm trying to register a domain for customers using WHMCS apis with python.

The issue I'm having is with the additional domain fields, in this case for the .eu domain:

```<code>additional_domainfields = base64.b64encode(phpserialize.dumps({'Entity Type':'INDIVIDUAL', 'EU Country of Citizenship':'IT'}))

    post_data = {
        'identifier':'xxx',
        'secret':'xxx',
        'action':'AddOrder',
        'clientid':client_id,
        'domain':domain,
        'domaintype':"register",
        'billingcycle':"annually",
        'regperiod':1,
        'noinvoice':True,
        'noinvoiceemail':True,
        'noemail':True,
        'paymentmethod':"stripe",
        'domainpriceoverride':0,
        'domainrenewoverride':0,
        'domainfields':additional_domainfields,
        'responsetype':'json'
        }
    postfields = urlencode(post_data)
    c.setopt(c.POSTFIELDS, postfields)  # type: ignore
    c.perform()
    c.reset
</code>```

I can't find what to use for the array of serialized data, so far all of my tests were for nothing.

I tried any combination of fields on the line:

additional_domainfields = base64.b64encode(phpserialize.dumps({'Entity Type':'INDIVIDUAL', 'EU Country of Citizenship':'IT'})).

Also, tried cheching for the php overrides for field names, so far without success.

Any help would be immensely appreciated

Body:
I'm trying to register a domain for customers using WHMCS apis with python.

The issue I'm having is with the additional domain fields, in this case for the .eu domain:

additional_domainfields = base64.b64encode(phpserialize.dumps({'Entity Type':'INDIVIDUAL', 'EU Country of Citizenship':'IT'}))

    post_data = {
        'identifier':'xxx',
        'secret':'xxx',
        'action':'AddOrder',
        'clientid':client_id,
        'domain':domain,
        'domaintype':"register",
        'billingcycle':"annually",
        'regperiod':1,
        'noinvoice':True,
        'noinvoiceemail':True,
        'noemail':True,
        'paymentmethod':"stripe",
        'domainpriceoverride':0,
        'domainrenewoverride':0,
        'domainfields':additional_domainfields,
        'responsetype':'json'
        }
    postfields = urlencode(post_data)
    c.setopt(c.POSTFIELDS, postfields)  # type: ignore
    c.perform()
    c.reset

I can't find what to use for the array of serialized data, so far all of my tests were for nothing.

I tried any combination of fields on the line:

additional_domainfields = base64.b64encode(phpserialize.dumps({'Entity Type':'INDIVIDUAL', 'EU Country of Citizenship':'IT'})).

Also, tried cheching for the php overrides for field names, so far without success.

Any help would be immensely appreciated


来源: stackexchange

问:
dlib correlation tracker tracks object after object is out of frame
dlib correlation tracker detects object/person but when object/person is out of frame it still detects a object. If the object/person out of the frame When the camera stream starts, it detects nothing,  after object/person enters the frame it detects the object/person correctly, so The tracker updates itself. However, it didn't update itself, once the object/person out of frame.

the code below run on Raspberry Pi 3A+ with Rasbian Buster, opencv 4.1.0, dlib 19.24.99, with arguments:

```<code>python3 object-tracker.py --prototxt MobileNetSSD_deploy.prototxt --model MobileNetSSD_deploy.caffemodel --label person
</code>```

The below code is from pyimagesearch. The input video argument removed since the video stream from camera used. The code is work as expected if the input video file used as shown in the source. However, the  tracker do not stop tracking once object is out of frame when camera stream used. prototxt and model files can be found here.

```<code>from imutils.video import VideoStream
from imutils.video import FPS
import numpy as np
import argparse
import imutils
import dlib
import cv2
import time

ap = argparse.ArgumentParser()
ap.add_argument("-p", "--prototxt", required=True, help="path o Caffe 'deploy' prototxt file")
ap.add_argument("-m", "--model", required=True, help="path to the Caffe pre-trained model")
ap.add_argument("-l", "--label", required=True, help="class label we are interested in")
ap.add_argument("-o", "--output", type=str, help="path to optional output video file")
ap.add_argument("-c", "--confidence", type=float, default=0.2, help="minimum probability to filter weak detections")
args = vars(ap.parse_args())

CLASSES = ["background", "areoplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow",
    "diningtable", "dog", "horse", "motorbile", "person", "pottedplant", "sheep", "sofa", "train", "tvmonitor"]

print("[INFO] loading model...")
net = cv2.dnn.readNetFromCaffe(args["prototxt"], args["model"])

print("[INFO] starting video stream...")
vs = VideoStream(src=0).start()
tracker = None
writer = None
label = ""

fps = FPS().start()

while True:
    frame = vs.read()

    if frame is None:
        break

    frame = imutils.resize(frame, width=300)
    frame = imutils.rotate(frame, angle=180)
    rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

    if args["output"] is not None and writer is None:
        fourcc = cv2.VideoWriter_fourcc(*"MJPG")
        writer = cv2.VideoWriter(args["output"], fourcc, 30, (frame.shape[1], frame.shape[0]), True)

    if tracker is None:
        (h, w) = frame.shape[:2]
        blob = cv2.dnn.blobFromImage(frame, 0.007843, (w, h), 127.5)

        net.setInput(blob)
        detections = net.forward()

        if len(detections) > 0:
            i = np.argmax(detections[0, 0, :, 2])

            conf = detections[0, 0, i, 2]
            label = CLASSES[int(detections[0, 0, i, 1])]

            if conf > args["confidence"] and label == args["label"]:
                box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
                (startX, startY, endX, endY) = box.astype("int")

                tracker = dlib.correlation_tracker()
                rect = dlib.rectangle(startX, startY, endX, endY)
                tracker.start_track(rgb, rect)

                cv2.rectangle(frame, (startX, startY), (endX, endY), (0, 255, 0), 2)
                cv2.putText(frame, label, (startX, startY - 15), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 255, 0), 2)

    else:
        tracker.update(rgb)
        pos = tracker.get_position()

        startX = int(pos.left())
        startY = int(pos.top())
        endX = int(pos.right())
        endY = int(pos.bottom())

        cv2.rectangle(frame, (startX, startY), (endX, endY), (0, 255, 0), 2)
        cv2.putText(frame, label, (startX, startY - 15), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 255, 0), 2)

    if writer is not None:
        writer.write(frame)

    cv2.imshow("Frame",frame)
    key = cv2.waitKey(1) & 0xFF

    if key == ord("q"):
        break

    fps.update()

fps.stop()
print("[INFO] elapsed time: {:.2f}".format(fps.elapsed()))
print("[INFO] approx. FPS: {:.2f}".format(fps.fps()))

if writer is not None:
    writer.release()

cv2.destroyAllWindows()
vs.stop()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
dlib correlation tracker detects object/person but when object/person is out of frame it still detects a object. If the object/person out of the frame When the camera stream starts, it detects nothing,  after object/person enters the frame it detects the object/person correctly, so The tracker updates itself. However, it didn't update itself, once the object/person out of frame.

the code below run on Raspberry Pi 3A+ with Rasbian Buster, opencv 4.1.0, dlib 19.24.99, with arguments:

python3 object-tracker.py --prototxt MobileNetSSD_deploy.prototxt --model MobileNetSSD_deploy.caffemodel --label person

The below code is from pyimagesearch. The input video argument removed since the video stream from camera used. The code is work as expected if the input video file used as shown in the source. However, the  tracker do not stop tracking once object is out of frame when camera stream used. prototxt and model files can be found here.

from imutils.video import VideoStream
from imutils.video import FPS
import numpy as np
import argparse
import imutils
import dlib
import cv2
import time

ap = argparse.ArgumentParser()
ap.add_argument("-p", "--prototxt", required=True, help="path o Caffe 'deploy' prototxt file")
ap.add_argument("-m", "--model", required=True, help="path to the Caffe pre-trained model")
ap.add_argument("-l", "--label", required=True, help="class label we are interested in")
ap.add_argument("-o", "--output", type=str, help="path to optional output video file")
ap.add_argument("-c", "--confidence", type=float, default=0.2, help="minimum probability to filter weak detections")
args = vars(ap.parse_args())

CLASSES = ["background", "areoplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow",
    "diningtable", "dog", "horse", "motorbile", "person", "pottedplant", "sheep", "sofa", "train", "tvmonitor"]

print("[INFO] loading model...")
net = cv2.dnn.readNetFromCaffe(args["prototxt"], args["model"])

print("[INFO] starting video stream...")
vs = VideoStream(src=0).start()
tracker = None
writer = None
label = ""

fps = FPS().start()

while True:
    frame = vs.read()

    if frame is None:
        break

    frame = imutils.resize(frame, width=300)
    frame = imutils.rotate(frame, angle=180)
    rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

    if args["output"] is not None and writer is None:
        fourcc = cv2.VideoWriter_fourcc(*"MJPG")
        writer = cv2.VideoWriter(args["output"], fourcc, 30, (frame.shape[1], frame.shape[0]), True)

    if tracker is None:
        (h, w) = frame.shape[:2]
        blob = cv2.dnn.blobFromImage(frame, 0.007843, (w, h), 127.5)

        net.setInput(blob)
        detections = net.forward()

        if len(detections) > 0:
            i = np.argmax(detections[0, 0, :, 2])

            conf = detections[0, 0, i, 2]
            label = CLASSES[int(detections[0, 0, i, 1])]

            if conf > args["confidence"] and label == args["label"]:
                box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
                (startX, startY, endX, endY) = box.astype("int")

                tracker = dlib.correlation_tracker()
                rect = dlib.rectangle(startX, startY, endX, endY)
                tracker.start_track(rgb, rect)

                cv2.rectangle(frame, (startX, startY), (endX, endY), (0, 255, 0), 2)
                cv2.putText(frame, label, (startX, startY - 15), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 255, 0), 2)

    else:
        tracker.update(rgb)
        pos = tracker.get_position()

        startX = int(pos.left())
        startY = int(pos.top())
        endX = int(pos.right())
        endY = int(pos.bottom())

        cv2.rectangle(frame, (startX, startY), (endX, endY), (0, 255, 0), 2)
        cv2.putText(frame, label, (startX, startY - 15), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 255, 0), 2)

    if writer is not None:
        writer.write(frame)

    cv2.imshow("Frame",frame)
    key = cv2.waitKey(1) & 0xFF

    if key == ord("q"):
        break

    fps.update()

fps.stop()
print("[INFO] elapsed time: {:.2f}".format(fps.elapsed()))
print("[INFO] approx. FPS: {:.2f}".format(fps.fps()))

if writer is not None:
    writer.release()

cv2.destroyAllWindows()
vs.stop()


问:
ExtJS 7.5 - Model hasMany triggers http error 404
I have a grid with a row widget :

```<code>            {
                xtype: 'gridpanel',
                margin: '10 0 0 0',
                reserveScrollbar: true,
                enableColumnHide: false,
                shallowGrouping: true,
                flex: 1,
                emptyText: 'No data available',
                plugins: [
                    {
                        ptype: 'columnsmanager'
                    },
                    {
                        ptype: 'gridfilters'
                    },
                    {
                        ptype: 'gridexporter'
                    },
                    {
                        ptype: 'rowwidget',
                        widget: {
                            xtype: 'grid',
                            bind: {
                                store: '{record.allocations}'
                            },
                            plugins: [
                                {
                                    ptype: 'gridfilters'
                                }
                            ],
                            viewConfig: {
                                stripeRows: true,
                                isRowWidget: true
                            },
                            columns:
                            [
                                {
                                    xtype: 'datecolumn',
                                    text: 'Date',
                                    dataIndex: 'creationDate',
                                    format: 'Y-m-d H:i',
                                    filter: 'date',
                                    width: 120
                                },
                                {
                                    xtype: 'gridcolumn',
                                    text: 'Portfolio',
                                    dataIndex: 'portfolioShortName',
                                    filter: 'string',
                                    width: 250
                                }
                                {
                                    ...
                                }
                            ]
                        }
                    }
                ],
                selModel: {
                    selType: 'rowmodel',
                    mode: 'SINGLE',
                },
                listeners: {
                    afterrender: 'onGridAfterRender',
                    selectionchange: 'onGridSelectionChange'
                },
                bind: {
                    store: '{Orders}'
                },
                rowViewModel: true,
                columns: [ ... ]
            }
</code>```

The property 'portfolioShortName' is defined in a model

```<code>    {
        name: 'portfolioShortName',
        mapping: 'portfolio.shortName'
    }
</code>```

Which is a nested object of another object

```<code>hasMany: {model: 'Xxx.model.oms.Order', name: 'allocations', associationKey:'allocations'}
</code>```

The problem is when I click on the row expander ExtJs make a http call to get the file and triggers a http error 404, the error is triggered but the fields are visible.

I tried without 'hasMany' in the parent object and using 'tpl' or 'renderer' in the grid but this does not work. The issue is only for nested object, properties are displayed properly.

Body:
I have a grid with a row widget :

            {
                xtype: 'gridpanel',
                margin: '10 0 0 0',
                reserveScrollbar: true,
                enableColumnHide: false,
                shallowGrouping: true,
                flex: 1,
                emptyText: 'No data available',
                plugins: [
                    {
                        ptype: 'columnsmanager'
                    },
                    {
                        ptype: 'gridfilters'
                    },
                    {
                        ptype: 'gridexporter'
                    },
                    {
                        ptype: 'rowwidget',
                        widget: {
                            xtype: 'grid',
                            bind: {
                                store: '{record.allocations}'
                            },
                            plugins: [
                                {
                                    ptype: 'gridfilters'
                                }
                            ],
                            viewConfig: {
                                stripeRows: true,
                                isRowWidget: true
                            },
                            columns:
                            [
                                {
                                    xtype: 'datecolumn',
                                    text: 'Date',
                                    dataIndex: 'creationDate',
                                    format: 'Y-m-d H:i',
                                    filter: 'date',
                                    width: 120
                                },
                                {
                                    xtype: 'gridcolumn',
                                    text: 'Portfolio',
                                    dataIndex: 'portfolioShortName',
                                    filter: 'string',
                                    width: 250
                                }
                                {
                                    ...
                                }
                            ]
                        }
                    }
                ],
                selModel: {
                    selType: 'rowmodel',
                    mode: 'SINGLE',
                },
                listeners: {
                    afterrender: 'onGridAfterRender',
                    selectionchange: 'onGridSelectionChange'
                },
                bind: {
                    store: '{Orders}'
                },
                rowViewModel: true,
                columns: [ ... ]
            }

The property 'portfolioShortName' is defined in a model

    {
        name: 'portfolioShortName',
        mapping: 'portfolio.shortName'
    }

Which is a nested object of another object

hasMany: {model: 'Xxx.model.oms.Order', name: 'allocations', associationKey:'allocations'}

The problem is when I click on the row expander ExtJs make a http call to get the file and triggers a http error 404, the error is triggered but the fields are visible.

I tried without 'hasMany' in the parent object and using 'tpl' or 'renderer' in the grid but this does not work. The issue is only for nested object, properties are displayed properly.


问:
Wordpress React JS based template website not working after upgrading to PHP 8.1
After switching from PHP 7.4.30 to PHP 8.1, my WordPress website, which was built by the original developer using React JS, started acting strangely. The menus stopped working and the home page became frozen and immovable.

Enable the debug and below are some of them.

Deprecated: Optional parameter $menu declared before required parameter $location is implicitly treated as a required parameter in \app\public\wp-content\themes**\functions\classes\Settings\Menu.php on line 22
**

```<code>   <?php

  namespace ThemeClasses\Settings;

  class Menu
  {
    public function __construct()
    {
      add_action('after_setup_theme', [$this, 'registerNavMenus']);
      add_filter('getMenuTree', [$this, 'getMenuTree'], 10, 2);
    }

    public function registerNavMenus()
    {
      register_nav_menus([
        'header_menu' => __('Header Menu', 'siri'),
        'footer_menu' => __('Footer Menu', 'siri'),
        'footer_columns' => __('Footer Columns', 'siri'),
      ]);
    }

    public function getMenuTree($menu = [], $location)
    {
      $flatMenu = $menu;
      $flatMenu = $this->getMenuItems($menu, $location);

      $treeMenu = [];
      $itemsRefs = [];

      foreach ($flatMenu as $menuItemObj) {
        $itemId = $menuItemObj->ID;
        $parentId = $menuItemObj->menu_item_parent;

        $itemsRefs[$itemId] = [
          'name' => $menuItemObj->title,
          'url' => $menuItemObj->url,
          'target' => $menuItemObj->target,
          'active' => $menuItemObj->active,
          'ID' => $itemId,
          'parentId' => $parentId,
          'children' => [],
        ];;

        if ($parentId == 0) {
          $treeMenu[] = &$itemsRefs[$itemId];
        } elseif (isset($itemsRefs[$parentId])) {
          $itemsRefs[$parentId]['children'][] = &$itemsRefs[$itemId];
        }
      }

      return $treeMenu;
    }

    private function getMenuItems($menu, $location)
    {
      // Get all locations
      $locations = get_nav_menu_locations();

      // Get object id by location
      $menuObject = wp_get_nav_menu_object($locations[$location]);

      // Check menu exists
      if (!is_object($menuObject)) return [];

      // Get menu items by menu slug
      $menu = wp_get_nav_menu_items($menuObject->slug);

      // Return menu post objects
      return $menu;
    }
  }

</code>```

**Deprecated: parse_str(): Passing null to parameter #1 ($string) of type string is deprecated in public\wp-content\themes**r\functions\classes\WordPressSecurity.php on line 364

```<code>      // add the filter
      add_filter('wp_admin_css', function($url, $file) {
        errol_log($url);
        // make filter magic happen here...
        return $url;
      }, 10, 2 );
    }

    public function removeWPVersion($src)
    {
      global $wp_version;
      parse_str(parse_url($src, PHP_URL_QUERY), $query);

      if (!empty($query['ver']) && $query['ver'] === $wp_version) {
        $src = remove_query_arg('ver', $src);
      }

      return $src;
    }

</code>```

Body:
After switching from PHP 7.4.30 to PHP 8.1, my WordPress website, which was built by the original developer using React JS, started acting strangely. The menus stopped working and the home page became frozen and immovable.

Enable the debug and below are some of them.

Deprecated: Optional parameter $menu declared before required parameter $location is implicitly treated as a required parameter in \app\public\wp-content\themes**\functions\classes\Settings\Menu.php on line 22
**

   <?php

  namespace ThemeClasses\Settings;

  class Menu
  {
    public function __construct()
    {
      add_action('after_setup_theme', [$this, 'registerNavMenus']);
      add_filter('getMenuTree', [$this, 'getMenuTree'], 10, 2);
    }

    public function registerNavMenus()
    {
      register_nav_menus([
        'header_menu' => __('Header Menu', 'siri'),
        'footer_menu' => __('Footer Menu', 'siri'),
        'footer_columns' => __('Footer Columns', 'siri'),
      ]);
    }

    public function getMenuTree($menu = [], $location)
    {
      $flatMenu = $menu;
      $flatMenu = $this->getMenuItems($menu, $location);

      $treeMenu = [];
      $itemsRefs = [];

      foreach ($flatMenu as $menuItemObj) {
        $itemId = $menuItemObj->ID;
        $parentId = $menuItemObj->menu_item_parent;

        $itemsRefs[$itemId] = [
          'name' => $menuItemObj->title,
          'url' => $menuItemObj->url,
          'target' => $menuItemObj->target,
          'active' => $menuItemObj->active,
          'ID' => $itemId,
          'parentId' => $parentId,
          'children' => [],
        ];;

        if ($parentId == 0) {
          $treeMenu[] = &$itemsRefs[$itemId];
        } elseif (isset($itemsRefs[$parentId])) {
          $itemsRefs[$parentId]['children'][] = &$itemsRefs[$itemId];
        }
      }

      return $treeMenu;
    }

    private function getMenuItems($menu, $location)
    {
      // Get all locations
      $locations = get_nav_menu_locations();

      // Get object id by location
      $menuObject = wp_get_nav_menu_object($locations[$location]);

      // Check menu exists
      if (!is_object($menuObject)) return [];

      // Get menu items by menu slug
      $menu = wp_get_nav_menu_items($menuObject->slug);

      // Return menu post objects
      return $menu;
    }
  }

**Deprecated: parse_str(): Passing null to parameter #1 ($string) of type string is deprecated in public\wp-content\themes**r\functions\classes\WordPressSecurity.php on line 364

      // add the filter
      add_filter('wp_admin_css', function($url, $file) {
        errol_log($url);
        // make filter magic happen here...
        return $url;
      }, 10, 2 );
    }

    public function removeWPVersion($src)
    {
      global $wp_version;
      parse_str(parse_url($src, PHP_URL_QUERY), $query);

      if (!empty($query['ver']) && $query['ver'] === $wp_version) {
        $src = remove_query_arg('ver', $src);
      }

      return $src;
    }


问:
Open SwiftUI View using custom URL
I am trying to open a new view be tapping on custom hyperlink in an AttribiutedString.
There you can find a preview of this view.
I am using SwiftUI to create this view so I can not rely on UITextView function:

func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) ... which I regret because there would have been no problem at all.

I have tried using .onOpenURL modifier but it seems not to be called at all.
I was expecting that when user clicks certain link I could override the default behaviour if clicked URL would match with the one created by me...

```<code>private var hyperlinkText: some View {
        let firstURL = URL(string: "firstSCREEN=1")!
        let secondURL = URL(string: "secondSCREEN=2")!

        return TextLabelWithHyperlink(completeString: "After clicking %@ first screen should be displayed and when you click %@ the second one should be presented.",
                               urlStringArray: [ firstURL, secondURL ],
                               stringArray: ["this link", "this next text with my custom link "],
                               fontSize: Constants.BottomDescription.fontSize)
        .onOpenURL { url in
            if url == firstURL {
                // open first screen
            }
            if url == secondURL {
                // open second screen
            }
            else {
                // open url in browser
            }
        }
    }

</code>```

I know that there is a way to do it with .environment modifier but it does not support iOS 14 which I need for this project.

Title: Open SwiftUI View using custom URL

Body:
I am trying to open a new view be tapping on custom hyperlink in an AttribiutedString.
There you can find a preview of this view.
I am using SwiftUI to create this view so I can not rely on UITextView function:

func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) ... which I regret because there would have been no problem at all.

I have tried using .onOpenURL modifier but it seems not to be called at all.
I was expecting that when user clicks certain link I could override the default behaviour if clicked URL would match with the one created by me...

private var hyperlinkText: some View {
        let firstURL = URL(string: "firstSCREEN=1")!
        let secondURL = URL(string: "secondSCREEN=2")!

        return TextLabelWithHyperlink(completeString: "After clicking %@ first screen should be displayed and when you click %@ the second one should be presented.",
                               urlStringArray: [ firstURL, secondURL ],
                               stringArray: ["this link", "this next text with my custom link "],
                               fontSize: Constants.BottomDescription.fontSize)
        .onOpenURL { url in
            if url == firstURL {
                // open first screen
            }
            if url == secondURL {
                // open second screen
            }
            else {
                // open url in browser
            }
        }
    }

I know that there is a way to do it with .environment modifier but it does not support iOS 14 which I need for this project.


问:
See tkinter Label on screen
I wanted to do my first tkinter code with python3, but when I used the code below a window opens up without any text. If somebody nows how to fix this please let me now.
I already have the latest version of tkinter and I am using the mac terminal

P.S. When I try to open the window with tkinter, this error message always pops up:

DEPRECATION WARNING: The system version of Tk is deprecated and may be removed in a future release. Please don't rely on it. Set TK_SILENCE_DEPRECATION=1 to suppress this warning.

This is my code.

```<code>from tkinter import *

root = Tk()

myLabel1 = Label (root, text="Hello World!")
myLabel2 = Label (root, text="My name is Bugs Bunny.")

myLabel1.grid(row=0, column=0)
myLabel2.grid(row=1,column=0)

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

Title: See tkinter Label on screen

Body:
I wanted to do my first tkinter code with python3, but when I used the code below a window opens up without any text. If somebody nows how to fix this please let me now.
I already have the latest version of tkinter and I am using the mac terminal

P.S. When I try to open the window with tkinter, this error message always pops up:

DEPRECATION WARNING: The system version of Tk is deprecated and may be removed in a future release. Please don't rely on it. Set TK_SILENCE_DEPRECATION=1 to suppress this warning.

This is my code.

from tkinter import *

root = Tk()

myLabel1 = Label (root, text="Hello World!")
myLabel2 = Label (root, text="My name is Bugs Bunny.")

myLabel1.grid(row=0, column=0)
myLabel2.grid(row=1,column=0)

root.mainloop()


问:
Why does this .indexOn: 'g' no longer work as it should?
I can no longer place activeDrivers in the correct position to make it work. "acriveDrivers" is a direct branch of the root, so the way I placed it is as if it were a child of drivers, which seems wrong to me, but I can't find the solution.

The rules at the beginning were like this (practically no security):

```<code>{
      "rules": {
        ".read":true,
        ".write": true,
          "activeDrivers": {
          ".indexOn": ["g"]
        }
      }
}
</code>```

New rules are:

```<code> "rules": {
         "drivers": {
            "$uid": {
              ".read": "auth !== null && auth.uid === $uid",
              ".write": "auth !== null && auth.uid === $uid",
                   "activeDrivers": {
                        ".indexOn": ["g"]
                    }
            }

         }
}
</code>```

This is the JSON of the Database:

```<code>{
  "ALL Ride Requests": {
    "-NJlIOrp49pNBSuuEawT": {
      "destination": {
        "latitude": "41.929612",
        "longitude": "12.4858561"
      },
      "destinationAddress": "Duke's",
      "driverId": "waiting",
      "origin": {
        "latitude": "41.919225",
        "longitude": "12.5266267"
      },
      "originAddress": "Circonvallazione Nomentana, 270, 00162 Roma RM, Italy",
      "time": "2022-12-20 21:50:48.437521",
      "userName": "Peter Parker",
      "userPhone": "090012321354"
    },
  },
  "activeDrivers": {
    "31uMBJKvl6PF7BVKQnqHORTrWRP2": {
      ".priority": "sr2yt23wk8",
      "g": "sr2yt23wl8",
      "l": [
        41.926275,
        12.5376567
      ]
    },
    "G3OJ79KiLeMmxqoUpJ1NggIKbiF2": {
      ".priority": "sr2yt23wk8",
      "g": "sr2yt23rk8",
      "l": [
        41.926275,
        12.5376567
      ]
    },
    "filTJu3xjiQYTzehD71kzY1Oybz1": {
      ".priority": "sr2yt23wk8",
      "g": "sr2yy23wk8",
      "l": [
        41.926275,
        12.5376567
      ]
    }
  },
  "drivers": {
    "G3OJ79KiLeMmxqoUpJ1NggIKbiF2": {
      "earnings": "0.0",
      "email": "simo@hotmail.it",
      "id": "G3OJ79KiLeMmxqoUpJ1NggIKbiF2",
      "name": "Simone Demichele Test",
      "newRideStatus": "idle",
      "password": "testpassword",
      "phone": "3452362585",
      "token": "fFIwv1IHRv2ylXyW-qRVGQ:APA91bH7IfcNBBi7Y53wRjQKN12-nBUgFHHpf7F0LeWCstG_MIqt-mkobRN6nvUZxqbMnMlXU2yMHdE-efYykUdtcXl-91wW5rGyQcpMl6Dij6bxC8snQRkAMGBhQUmyqYW6sBhY6Ul3"
    },
    "Gzs0qxNiE6VZrwNGPYpFPRB7J8p1": {
      "email": "giacomo@gmail.com",
      "id": "Gzs0qxNiE6VZrwNGPYpFPRB7J8p1",
      "name": "giacomo",
      "newRideStatus": "idle",
      "phone": "134634564352",
      "token": "cdG8W0lFRZ2F0jAeG2WbnO:APA91bHTtbtSg18sPNxcH92TIdM3UuX-qcim2-h0I_1YPcBgucIGO0I3ACIQEGVpmsg-EKcRZXFIMIXlxGk1iBw-V0hmDZBVWDyFh44yH2iM8fZgrhRsQzyVBdXdLxGMI0Vz67hQFUQU"
    },
    "OLhsoowb9FXTBtWQmGysGLLBgNz2": {
      "email": "gino@gmail.com",
      "id": "OLhsoowb9FXTBtWQmGysGLLBgNz2",
      "name": "Gino",
      "phone": "4568965432",
      "token": "ewktnxHKRSCBWwilm_SDfd:APA91bFchfCs_33zZNGNtbUHPf6TBC3Vrua7U4QT0bX_e4cr6Z62XSPr5TwZyL-BQ12fmDa3XKnAqeLDQy7NMUKp9m8bq676jS_i5n1vjNMFYJ4tHfIYjntEwYKvOcsTp0yh4ZSvjuxb"
    },
    "ZYqM7SbG3IhRBAGCfXRZHHs7XdG3": {
      "email": "laura@gmail.com",
      "id": "ZYqM7SbG3IhRBAGCfXRZHHs7XdG3",
      "name": "Laura",
      "newRideStatus": "idle",
      "phone": "1212432554325",
      "token": "cdG8W0lFRZ2F0jAeG2WbnO:APA91bHTtbtSg18sPNxcH92TIdM3UuX-qcim2-h0I_1YPcBgucIGO0I3ACIQEGVpmsg-EKcRZXFIMIXlxGk1iBw-V0hmDZBVWDyFh44yH2iM8fZgrhRsQzyVBdXdLxGMI0Vz67hQFUQU"
    },
    "filTJu3xjiQYTzehD71kzY1Oybz1": {
      "email": "maria@gmail.com",
      "id": "filTJu3xjiQYTzehD71kzY1Oybz1",
      "name": "Maria",
      "newRideStatus": "idle",
      "phone": "3726761919",
      "token": "fFIwv1IHRv2ylXyW-qRVGQ:APA91bH7IfcNBBi7Y53wRjQKN12-nBUgFHHpf7F0LeWCstG_MIqt-mkobRN6nvUZxqbMnMlXU2yMHdE-efYykUdtcXl-91wW5rGyQcpMl6Dij6bxC8snQRkAMGBhQUmyqYW6sBhY6Ul3"
    }
  },
  "users": {
    "yHc7xseCT0QePnpolGHZvdr8ARV2": {
      "email": "peter@gmail.com",
      "id": "yHc7xseCT0QePnpolGHZvdr8ARV2",
      "name": "Peter Parker",
      "phone": "090012321354"
    }
  }
}
</code>```

This is the query

```<code>Position pos = await Geolocator.getCurrentPosition(
      desiredAccuracy: LocationAccuracy.high,
    );
    driverCurrentPosition = pos;

    Geofire.initialize("activeDrivers");

    Geofire.setLocation(
        currentFirebaseUser!.uid,
        driverCurrentPosition!.latitude,
        driverCurrentPosition!.longitude
    );
</code>```

Body:
I can no longer place activeDrivers in the correct position to make it work. "acriveDrivers" is a direct branch of the root, so the way I placed it is as if it were a child of drivers, which seems wrong to me, but I can't find the solution.

The rules at the beginning were like this (practically no security):

{
      "rules": {
        ".read":true,
        ".write": true,
          "activeDrivers": {
          ".indexOn": ["g"]
        }
      }
}

New rules are:

 "rules": {
         "drivers": {
            "$uid": {
              ".read": "auth !== null && auth.uid === $uid",
              ".write": "auth !== null && auth.uid === $uid",
                   "activeDrivers": {
                        ".indexOn": ["g"]
                    }
            }

         }
}

This is the JSON of the Database:

{
  "ALL Ride Requests": {
    "-NJlIOrp49pNBSuuEawT": {
      "destination": {
        "latitude": "41.929612",
        "longitude": "12.4858561"
      },
      "destinationAddress": "Duke's",
      "driverId": "waiting",
      "origin": {
        "latitude": "41.919225",
        "longitude": "12.5266267"
      },
      "originAddress": "Circonvallazione Nomentana, 270, 00162 Roma RM, Italy",
      "time": "2022-12-20 21:50:48.437521",
      "userName": "Peter Parker",
      "userPhone": "090012321354"
    },
  },
  "activeDrivers": {
    "31uMBJKvl6PF7BVKQnqHORTrWRP2": {
      ".priority": "sr2yt23wk8",
      "g": "sr2yt23wl8",
      "l": [
        41.926275,
        12.5376567
      ]
    },
    "G3OJ79KiLeMmxqoUpJ1NggIKbiF2": {
      ".priority": "sr2yt23wk8",
      "g": "sr2yt23rk8",
      "l": [
        41.926275,
        12.5376567
      ]
    },
    "filTJu3xjiQYTzehD71kzY1Oybz1": {
      ".priority": "sr2yt23wk8",
      "g": "sr2yy23wk8",
      "l": [
        41.926275,
        12.5376567
      ]
    }
  },
  "drivers": {
    "G3OJ79KiLeMmxqoUpJ1NggIKbiF2": {
      "earnings": "0.0",
      "email": "simo@hotmail.it",
      "id": "G3OJ79KiLeMmxqoUpJ1NggIKbiF2",
      "name": "Simone Demichele Test",
      "newRideStatus": "idle",
      "password": "testpassword",
      "phone": "3452362585",
      "token": "fFIwv1IHRv2ylXyW-qRVGQ:APA91bH7IfcNBBi7Y53wRjQKN12-nBUgFHHpf7F0LeWCstG_MIqt-mkobRN6nvUZxqbMnMlXU2yMHdE-efYykUdtcXl-91wW5rGyQcpMl6Dij6bxC8snQRkAMGBhQUmyqYW6sBhY6Ul3"
    },
    "Gzs0qxNiE6VZrwNGPYpFPRB7J8p1": {
      "email": "giacomo@gmail.com",
      "id": "Gzs0qxNiE6VZrwNGPYpFPRB7J8p1",
      "name": "giacomo",
      "newRideStatus": "idle",
      "phone": "134634564352",
      "token": "cdG8W0lFRZ2F0jAeG2WbnO:APA91bHTtbtSg18sPNxcH92TIdM3UuX-qcim2-h0I_1YPcBgucIGO0I3ACIQEGVpmsg-EKcRZXFIMIXlxGk1iBw-V0hmDZBVWDyFh44yH2iM8fZgrhRsQzyVBdXdLxGMI0Vz67hQFUQU"
    },
    "OLhsoowb9FXTBtWQmGysGLLBgNz2": {
      "email": "gino@gmail.com",
      "id": "OLhsoowb9FXTBtWQmGysGLLBgNz2",
      "name": "Gino",
      "phone": "4568965432",
      "token": "ewktnxHKRSCBWwilm_SDfd:APA91bFchfCs_33zZNGNtbUHPf6TBC3Vrua7U4QT0bX_e4cr6Z62XSPr5TwZyL-BQ12fmDa3XKnAqeLDQy7NMUKp9m8bq676jS_i5n1vjNMFYJ4tHfIYjntEwYKvOcsTp0yh4ZSvjuxb"
    },
    "ZYqM7SbG3IhRBAGCfXRZHHs7XdG3": {
      "email": "laura@gmail.com",
      "id": "ZYqM7SbG3IhRBAGCfXRZHHs7XdG3",
      "name": "Laura",
      "newRideStatus": "idle",
      "phone": "1212432554325",
      "token": "cdG8W0lFRZ2F0jAeG2WbnO:APA91bHTtbtSg18sPNxcH92TIdM3UuX-qcim2-h0I_1YPcBgucIGO0I3ACIQEGVpmsg-EKcRZXFIMIXlxGk1iBw-V0hmDZBVWDyFh44yH2iM8fZgrhRsQzyVBdXdLxGMI0Vz67hQFUQU"
    },
    "filTJu3xjiQYTzehD71kzY1Oybz1": {
      "email": "maria@gmail.com",
      "id": "filTJu3xjiQYTzehD71kzY1Oybz1",
      "name": "Maria",
      "newRideStatus": "idle",
      "phone": "3726761919",
      "token": "fFIwv1IHRv2ylXyW-qRVGQ:APA91bH7IfcNBBi7Y53wRjQKN12-nBUgFHHpf7F0LeWCstG_MIqt-mkobRN6nvUZxqbMnMlXU2yMHdE-efYykUdtcXl-91wW5rGyQcpMl6Dij6bxC8snQRkAMGBhQUmyqYW6sBhY6Ul3"
    }
  },
  "users": {
    "yHc7xseCT0QePnpolGHZvdr8ARV2": {
      "email": "peter@gmail.com",
      "id": "yHc7xseCT0QePnpolGHZvdr8ARV2",
      "name": "Peter Parker",
      "phone": "090012321354"
    }
  }
}

This is the query

Position pos = await Geolocator.getCurrentPosition(
      desiredAccuracy: LocationAccuracy.high,
    );
    driverCurrentPosition = pos;

    Geofire.initialize("activeDrivers");

    Geofire.setLocation(
        currentFirebaseUser!.uid,
        driverCurrentPosition!.latitude,
        driverCurrentPosition!.longitude
    );


问:
Scala - Invoking a class by string (with class name)
I have those classes like this:

```<code>object Class1 extends parent {
   def execute() {
        print("Class1")
   }
}
object Class2 extends parent {
   def execute {
        print("Class2")
   }
}
</code>```

Then I have a Runner like this:

```<code>object Runner extends runParent {
    def manageRun(className: String) = {
        def ClassInstance = className match {
             case Some("Class1") => Some(Class1)
             case Some("Class2") => Some(Class2)
        }
       ClassInstance.execute()
    }
}
</code>```

There is any way to change this managerRun code and when I create a Class3 I don't need to add a new case in the match?

Thanks!

Body:
I have those classes like this:

object Class1 extends parent {
   def execute() {
        print("Class1")
   }
}
object Class2 extends parent {
   def execute {
        print("Class2")
   }
}

Then I have a Runner like this:

object Runner extends runParent {
    def manageRun(className: String) = {
        def ClassInstance = className match {
             case Some("Class1") => Some(Class1)
             case Some("Class2") => Some(Class2)
        }
       ClassInstance.execute()
    }
}

There is any way to change this managerRun code and when I create a Class3 I don't need to add a new case in the match?

Thanks!


Title: Can't pull image after successful login in ECR

Body:
I have already made many sucessfull push/pull to ECRs in different accounts using the ECR policy with no problems.

Now I'm using Podman/WSL in Windows and faced with an unusual situation. Docker/ECR Login works, the Resource policy is OK, pull doesn't work.

[root@GFT-79QHVP3-NB .aws]# aws ecr get-login-password --region us-east-1 | podman login --username AWS --password-stdin
 123456.dkr.ecr.us-east-1.amazonaws.com
Login Succeeded!
[root@GFT-79QHVP3-NB .aws]# podman pull 123456.dkr.ecr.us-east-1.amazonaws.com/amundsen:pantalla
Trying to pull 123456.dkr.ecr.us-east-1.amazonaws.com/amundsen:pantalla...
Getting image source signatures
Copying blob 326f452ade5c [--------------------------------------] 0.0b / 4.9MiB
Copying blob 15132af73342 [--------------------------------------] 0.0b / 6.0MiB
Copying blob 8ffa7aaef404 [--------------------------------------] 0.0b / 187.7MiB
Copying blob a42821cd14fb [--------------------------------------] 0.0b / 10.4MiB
Copying blob 8471b75885ef [--------------------------------------] 0.0b / 52.1MiB
Copying blob 23858da423a6 [--------------------------------------] 0.0b / 52.5MiB
Copying blob a81a13cb42bc [--------------------------------------] 0.0b / 14.8MiB
Copying blob 39baa166dda6 [--------------------------------------] 0.0b / 233.0b
Copying blob 28d172f530ba [--------------------------------------] 0.0b / 2.8MiB
Copying blob 675c578c2119 [--------------------------------------] 0.0b / 166.0b
Copying blob b1d5411ecaa3 [--------------------------------------] 0.0b / 583.0b
Copying blob c295868a77a0 [--------------------------------------] 0.0b / 6.5MiB
Copying blob 520ddae1a49a [--------------------------------------] 0.0b / 99.4MiB
Copying blob 1c076a62ab4f [--------------------------------------] 0.0b / 208.9MiB
Error: reading blob sha256:23858da423a6737f0467fab0014e5b53009ea7405d575636af0c3f100bbb2f10: unable to retrieve auth token: invalid username/password: unauthorized: authentication required

The resource policy:

{
  "Version": "2008-10-17",
  "Statement": [
    {
      "Sid": "AllowPushPull",
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::78910:root"
      },
      "Action": [
        "ecr:BatchCheckLayerAvailability",
        "ecr:BatchGetImage",
        "ecr:CompleteLayerUpload",
        "ecr:GetDownloadUrlForLayer",
        "ecr:InitiateLayerUpload",
        "ecr:PutImage",
        "ecr:UploadLayerPart"
      ]
    }
  ]
}

I wasn't able to find the Docker credentials anywhere. And from this podman env I was able to connect to other ECRs and do push/pulls. I'm lost here.

I have tried a little more verbosity and forcing the pull command to use the authfile. Still no game.

[root@GFT-79QHVP3-NB containers]# aws ecr get-login-password --region us-east-1 | podman login --username AWS --password-stdin xxxx.dkr.ecr.us-east-1.amazonaws.com --verbose
Used:  /run/user/0/containers/auth.json
Login Succeeded!

[root@GFT-79QHVP3-NB containers]# podman pull xxxx.dkr.ecr.us-east-1.amazonaws.com/amundsen:pantalla --authfile=/run/user/0/containers/auth.json
<same error as above>


问:
How to search in multiple child in FirebaseRecyclerOptions
I have this code that get the value from an edit text and search it in firebase real time database, the problem is that I want to search the string in multiple child in the data base

```<code>private void searchProcess(String s) {
        FirebaseRecyclerOptions<Product> options =
                new FirebaseRecyclerOptions.Builder<Product>()
                        .setQuery(FirebaseDatabase.getInstance().getReference().child("Products").orderByChild("name").startAt(s).endAt(s+"\uf8ff"), Product.class)
                        .build();
        productAdapter =new imageAdapter(options);
        productAdapter.startListening();
        recyclerView.setAdapter(productAdapter);
    }
</code>```

as you can see it only search by name, is there anyway so I can make it search in three Childs of the product class

```<code>public Product(String name, String type, String description, String owner, float price, String date, String downloadURL) {
        this.name = name;
        this.type = type;
        this.description = description;
        this.owner = owner;
        this.price = price;
        this.date = date;
        this.downloadURL = downloadURL;
        this.status = "Pending";
    }
</code>```

Body:
I have this code that get the value from an edit text and search it in firebase real time database, the problem is that I want to search the string in multiple child in the data base

private void searchProcess(String s) {
        FirebaseRecyclerOptions<Product> options =
                new FirebaseRecyclerOptions.Builder<Product>()
                        .setQuery(FirebaseDatabase.getInstance().getReference().child("Products").orderByChild("name").startAt(s).endAt(s+"\uf8ff"), Product.class)
                        .build();
        productAdapter =new imageAdapter(options);
        productAdapter.startListening();
        recyclerView.setAdapter(productAdapter);
    }

as you can see it only search by name, is there anyway so I can make it search in three Childs of the product class

public Product(String name, String type, String description, String owner, float price, String date, String downloadURL) {
        this.name = name;
        this.type = type;
        this.description = description;
        this.owner = owner;
        this.price = price;
        this.date = date;
        this.downloadURL = downloadURL;
        this.status = "Pending";
    }


问:
Nuxt 3 throw createError not reaching the custom error page
I am settting up an auth middleware which runs just fine, however when I am creating the error I just get to the default error page. I need to reach the custom ~/error.vue to insert a button to click clearError()

Docs says I can just add an error component in the source, which I did.
If ~/error.vue is not reachable from ~/server/middleware then how can I call clearError() in the default error page?

in ~/server/midddleware/auth/auth.ts

export default defineEventHandler(async (event) => {
 if(conditionNotMet){
  throw createError({
    statusCode: 404,
    name: 'NotFoundError',
    message: 'Todo not found',
    statusMessage: "Not Found",
  })
 }
}
```
<p><em>~/error.vue</em></p>
<pre class="lang-js prettyprint-override"><code><template>
  <div>{{ props.error }}</div>
</template>
<script setup>
  const props = defineProps(['error'])
</script>
</code>```

This is what I see instead

https://nuxt.com/docs/getting-started/error-handling

Body:
I am settting up an auth middleware which runs just fine, however when I am creating the error I just get to the default error page. I need to reach the custom ~/error.vue to insert a button to click clearError()

Docs says I can just add an error component in the source, which I did.
If ~/error.vue is not reachable from ~/server/middleware then how can I call clearError() in the default error page?

in ~/server/midddleware/auth/auth.ts

export default defineEventHandler(async (event) => {
 if(conditionNotMet){
  throw createError({
    statusCode: 404,
    name: 'NotFoundError',
    message: 'Todo not found',
    statusMessage: "Not Found",
  })
 }
}

~/error.vue

<template>

{{ props.error }}

</template>

This is what I see instead

https://nuxt.com/docs/getting-started/error-handling


问:
Local IMAP server on docker
I want to setup a local IMAP server within my home network for archiving emails. The server does not need to be accessable via the internet. Therefore I can pass on a secured access via SSL (If this makes it easier). I want to integrate the server in my current docker setup. So the server has to run within a docker container.

I already tried the following containers:

https://hub.docker.com/r/blackflysolutions/dovecot

https://hub.docker.com/r/dovecot/dovecot

https://hub.docker.com/r/mailu/dovecot

https://hub.docker.com/r/mailcow/dovecot

https://hub.docker.com/r/eilandert/dovecot

But i could not get any of them to run. At the same time none of them have a forum or anything where I can put a question. Two of them (mailu/dovecot and mailcow/dovecot) are part of a bigger mailserver package. Which I do not need, I only want a IMAP server to put some email locally. But I tried them anyway.

Does anyone know how to get any of those to run? Or suggest me another stable docker container solution.

Title: Local IMAP server on docker


问:
Show 2 shiny apps one after another
I have 2 different shiny apps, and I would like to show them one after ther other (the first should be a survey and the second a memory game).
I tried to find a solution, but I never found exacly what I am looking for. Maybe a third app that combines them?

The only thing I found is :
Switch between two shiny apps in one
But:

You have to click on which app do you want to start, and I want it to be automatically (so that the users won't play the game before the survey)

When I upload it to shinyapps it raises an error

Thanks!

Title: Show 2 shiny apps one after another


问:
WWDC ResearchKit + CareKit - Thread 1: Fatal error: Failed to extract answers from check in survey
Good morning everyone - hope everyone is doing well!

I am learning to use ResearchKit and CareKit from the WWDC code-along. The pre-completed code-along file works great. The way they have it set up is there is a survey with a couple of sliding scale questions that when completed are stored in the CareKit Store and are extracted to complete the rings at the top of the app to show the person has completed the surveys for the day.

Now, I am trying to add a ORKTextChoice survey (multiple choice) to the code-along scale questions. So far I have been able to add in the ORKTextChoice survey to the existing scale questions. I can open the survey and select the answer choice; however when I click Done, I think the app tries to extract the answers from the ORKTextChoice to fill the ring I am getting an error.

```<code>  else {
                assertionFailure("Failed to extract answers from check in survey!")
                return nil
            }
</code>```
```<code>
> Thread 1: Fatal error: Failed to extract answers from check in survey!

</code>```

Additionally, what I am trying to do here is to have multiple choice questions that store into CareKit as a number (where it says (in bold): ORKTextChoice(text: "Home oxygen use", value: 0 as NSNumber)) value so that later I can create a chart of the numbers based on the answer responses.

This is where I am getting the error (towards the very bottom of the full code below):

```<code>static let checkInIdentifier = "checkin"
static let checkInFormIdentifier = "checkin.form"
static let checkInPainItemIdentifier = "checkin.form.pain"
static let checkInSleepItemIdentifier = "checkin.form.sleep"
static let checkInSleepItemIdentifier2 = "checkin.form.sleep2"
static let TextChoiceQuestionStep = "checkin.form.sleep3"

static func checkInSurvey() -> ORKTask {

    let painAnswerFormat = ORKAnswerFormat.scale(
        withMaximumValue: 10,
        minimumValue: 1,
        defaultValue: 0,
        step: 1,
        vertical: false,
        maximumValueDescription: "Very painful",
        minimumValueDescription: "No pain"
    )

    let sleepAnswerFormat = ORKAnswerFormat.scale(
        withMaximumValue: 12,
        minimumValue: 0,
        defaultValue: 0,
        step: 1,
        vertical: false,
        maximumValueDescription: nil,
        minimumValueDescription: nil
    )

    let sleepAnswerFormat2 = ORKAnswerFormat.scale(
        withMaximumValue: 12,
        minimumValue: 0,
        defaultValue: 0,
        step: 1,
        vertical: false,
        maximumValueDescription: nil,
        minimumValueDescription: nil
    )

    let breathingChoices = [
        ORKTextChoice(text: "Home oxygen use", value: 0 as NSNumber),
        ORKTextChoice(text: "Cystic fibrosis", value: 1 as NSNumber),
        ORKTextChoice(text: "Chronic lung disease", value: 2 as NSNumber),
    ]
    let breathingAnswerFormat =  ORKAnswerFormat.choiceAnswerFormat(
        with: .singleChoice,    //<-- .multipleChoice can allow for multiple options selected
        textChoices: breathingChoices
    )

    let painItem = ORKFormItem(
        identifier: checkInPainItemIdentifier,
        text: "How would you rate your pain?",
        answerFormat: painAnswerFormat
    )
    painItem.isOptional = false

    let sleepItem = ORKFormItem(
        identifier: checkInSleepItemIdentifier,
        text: "How many hours of sleep did you get last night?",
        answerFormat: sleepAnswerFormat
    )
    sleepItem.isOptional = false

    let sleepItem2 = ORKFormItem(
        identifier: checkInSleepItemIdentifier2,
        text: "How many hours of sleep did you get last night2?",
        answerFormat: sleepAnswerFormat2
    )
    sleepItem2.isOptional = false

    let breathingStep = ORKFormItem(
        identifier: TextChoiceQuestionStep,
        text: "What of the following apply to your child's current breathing condition? (check all that apply)",
        answerFormat: breathingAnswerFormat
    )
    breathingStep.isOptional = false

    let formStep = ORKFormStep(
        identifier: checkInFormIdentifier,
        title: "Check In",
        text: "Please answer the following questions."
    )
    formStep.formItems = [painItem, sleepItem, sleepItem2, breathingStep]
    formStep.isOptional = false

    let surveyTask = ORKOrderedTask(
        identifier: checkInIdentifier,
        steps: [formStep]
    )

    return surveyTask
}

static func extractAnswersFromCheckInSurvey(
    _ result: ORKTaskResult) -> [OCKOutcomeValue]? {

        guard
            let response = result.results?
                .compactMap({ $0 as? ORKStepResult })
                .first(where: { $0.identifier == checkInFormIdentifier }),

                let scaleResults = response
                .results?.compactMap({ $0 as? ORKScaleQuestionResult }),

                let painAnswer = scaleResults
                .first(where: { $0.identifier == checkInPainItemIdentifier })?
                .scaleAnswer,

                let sleepAnswer = scaleResults
                .first(where: { $0.identifier == checkInSleepItemIdentifier })?
                .scaleAnswer,

                let breathAnswer = scaleResults
                .first(where: { $0.identifier == TextChoiceQuestionStep })?
                .scaleAnswer

        else {
            assertionFailure("Failed to extract answers from check in survey!")
            return nil
        }

        var painValue = OCKOutcomeValue(Double(truncating: painAnswer))
        painValue.kind = checkInPainItemIdentifier

        var sleepValue = OCKOutcomeValue(Double(truncating: sleepAnswer))
        sleepValue.kind = checkInSleepItemIdentifier

        var breathValue = OCKOutcomeValue(Double(truncating: breathAnswer))
        sleepValue.kind = checkInSleepItemIdentifier

        return [painValue, sleepValue, breathValue]
    }
</code>```

For reference, here is the code-along:
https://developer.apple.com/videos/play/wwdc2021/10068/

Here is the Git with the code-along code:
https://github.com/carekit-apple/WWDC21-RecoverApp

The ORKTextChoice survey questions (ie. Home oxygen use, etc.) came from here:
https://github.com/ResearchKit/ResearchKit/issues/919

I appreciate any help and guidance any of you can provide - Thank you!

Body:
Good morning everyone - hope everyone is doing well!

I am learning to use ResearchKit and CareKit from the WWDC code-along. The pre-completed code-along file works great. The way they have it set up is there is a survey with a couple of sliding scale questions that when completed are stored in the CareKit Store and are extracted to complete the rings at the top of the app to show the person has completed the surveys for the day.

Now, I am trying to add a ORKTextChoice survey (multiple choice) to the code-along scale questions. So far I have been able to add in the ORKTextChoice survey to the existing scale questions. I can open the survey and select the answer choice; however when I click Done, I think the app tries to extract the answers from the ORKTextChoice to fill the ring I am getting an error.

  else {
                assertionFailure("Failed to extract answers from check in survey!")
                return nil
            }

> Thread 1: Fatal error: Failed to extract answers from check in survey!

Additionally, what I am trying to do here is to have multiple choice questions that store into CareKit as a number (where it says (in bold): ORKTextChoice(text: "Home oxygen use", value: 0 as NSNumber)) value so that later I can create a chart of the numbers based on the answer responses.

This is where I am getting the error (towards the very bottom of the full code below):

static let checkInIdentifier = "checkin"
static let checkInFormIdentifier = "checkin.form"
static let checkInPainItemIdentifier = "checkin.form.pain"
static let checkInSleepItemIdentifier = "checkin.form.sleep"
static let checkInSleepItemIdentifier2 = "checkin.form.sleep2"
static let TextChoiceQuestionStep = "checkin.form.sleep3"

static func checkInSurvey() -> ORKTask {

    let painAnswerFormat = ORKAnswerFormat.scale(
        withMaximumValue: 10,
        minimumValue: 1,
        defaultValue: 0,
        step: 1,
        vertical: false,
        maximumValueDescription: "Very painful",
        minimumValueDescription: "No pain"
    )

    let sleepAnswerFormat = ORKAnswerFormat.scale(
        withMaximumValue: 12,
        minimumValue: 0,
        defaultValue: 0,
        step: 1,
        vertical: false,
        maximumValueDescription: nil,
        minimumValueDescription: nil
    )

    let sleepAnswerFormat2 = ORKAnswerFormat.scale(
        withMaximumValue: 12,
        minimumValue: 0,
        defaultValue: 0,
        step: 1,
        vertical: false,
        maximumValueDescription: nil,
        minimumValueDescription: nil
    )

    let breathingChoices = [
        ORKTextChoice(text: "Home oxygen use", value: 0 as NSNumber),
        ORKTextChoice(text: "Cystic fibrosis", value: 1 as NSNumber),
        ORKTextChoice(text: "Chronic lung disease", value: 2 as NSNumber),
    ]
    let breathingAnswerFormat =  ORKAnswerFormat.choiceAnswerFormat(
        with: .singleChoice,    //<-- .multipleChoice can allow for multiple options selected
        textChoices: breathingChoices
    )

    let painItem = ORKFormItem(
        identifier: checkInPainItemIdentifier,
        text: "How would you rate your pain?",
        answerFormat: painAnswerFormat
    )
    painItem.isOptional = false

    let sleepItem = ORKFormItem(
        identifier: checkInSleepItemIdentifier,
        text: "How many hours of sleep did you get last night?",
        answerFormat: sleepAnswerFormat
    )
    sleepItem.isOptional = false

    let sleepItem2 = ORKFormItem(
        identifier: checkInSleepItemIdentifier2,
        text: "How many hours of sleep did you get last night2?",
        answerFormat: sleepAnswerFormat2
    )
    sleepItem2.isOptional = false

    let breathingStep = ORKFormItem(
        identifier: TextChoiceQuestionStep,
        text: "What of the following apply to your child's current breathing condition? (check all that apply)",
        answerFormat: breathingAnswerFormat
    )
    breathingStep.isOptional = false

    let formStep = ORKFormStep(
        identifier: checkInFormIdentifier,
        title: "Check In",
        text: "Please answer the following questions."
    )
    formStep.formItems = [painItem, sleepItem, sleepItem2, breathingStep]
    formStep.isOptional = false

    let surveyTask = ORKOrderedTask(
        identifier: checkInIdentifier,
        steps: [formStep]
    )

    return surveyTask
}

static func extractAnswersFromCheckInSurvey(
    _ result: ORKTaskResult) -> [OCKOutcomeValue]? {

        guard
            let response = result.results?
                .compactMap({ $0 as? ORKStepResult })
                .first(where: { $0.identifier == checkInFormIdentifier }),

                let scaleResults = response
                .results?.compactMap({ $0 as? ORKScaleQuestionResult }),

                let painAnswer = scaleResults
                .first(where: { $0.identifier == checkInPainItemIdentifier })?
                .scaleAnswer,

                let sleepAnswer = scaleResults
                .first(where: { $0.identifier == checkInSleepItemIdentifier })?
                .scaleAnswer,

                let breathAnswer = scaleResults
                .first(where: { $0.identifier == TextChoiceQuestionStep })?
                .scaleAnswer

        else {
            assertionFailure("Failed to extract answers from check in survey!")
            return nil
        }

        var painValue = OCKOutcomeValue(Double(truncating: painAnswer))
        painValue.kind = checkInPainItemIdentifier

        var sleepValue = OCKOutcomeValue(Double(truncating: sleepAnswer))
        sleepValue.kind = checkInSleepItemIdentifier

        var breathValue = OCKOutcomeValue(Double(truncating: breathAnswer))
        sleepValue.kind = checkInSleepItemIdentifier

        return [painValue, sleepValue, breathValue]
    }

For reference, here is the code-along:
https://developer.apple.com/videos/play/wwdc2021/10068/

Here is the Git with the code-along code:
https://github.com/carekit-apple/WWDC21-RecoverApp

The ORKTextChoice survey questions (ie. Home oxygen use, etc.) came from here:
https://github.com/ResearchKit/ResearchKit/issues/919

I appreciate any help and guidance any of you can provide - Thank you!


问:
Extract data from excel
I want to extract all the cells from the A column which have the word 'coding' ( L column ) . Any ideas on how to do it?

I have no idea how to do it , I'm a beginner in programming

Title: Extract data from excel


问:
'error TS2300: Duplicate identifier 'DocumentQuery' from ts-mongoose and and mongoose
I am trying to run a local copy of a server I am working on with the following packages.

```<code>"dependencies": {
"@types/mongodb": "^4.0.7",
"cors": "^2.8.5",
"express": "^4.18.2",
"mongoose": "^5.10.19",
"nodemon": "^2.0.20",
"ts-mongoose": "0.0.24",
"typescript": "3.9.5"
</code>```

}

However, when I try to run this very basic app I get the following error message.

```<code>node_modules/mongoose/index.d.ts:3033:8 - error TS2300: Duplicate identifier 'DocumentQuery'.
</code>```

After a bit of googling, I /think/ the issue is that both mongoose and mongoose TS are declaring the same identifier. But I'm unsure how to fix it. I'm also unsure of what info needs to be included as well. The code for the app doesn't actually include DocumentQuery, so I find that confusing as well. What should be my next steps in terms of identify and solving the issue?

Here is a full copy of the error.

```<code>node_modules/mongoose/index.d.ts:3033:8 - error TS2300: Duplicate identifier 'DocumentQuery'.

3033   type DocumentQuery<ResultType, DocType extends Document, THelpers = {}> = Query<ResultType, DocType, THelpers>;
            ~~~~~~~~~~~~~

  node_modules/ts-mongoose/plugin.d.ts:4:15
    4     interface DocumentQuery<T, DocType extends Document, QueryHelpers = {}> extends mquery {
                    ~~~~~~~~~~~~~
    'DocumentQuery' was also declared here.

node_modules/ts-mongoose/plugin.d.ts:4:15 - error TS2300: Duplicate identifier 'DocumentQuery'.

4     interface DocumentQuery<T, DocType extends Document, QueryHelpers = {}> extends mquery {
                ~~~~~~~~~~~~~

  node_modules/mongoose/index.d.ts:3033:8
    3033   type DocumentQuery<ResultType, DocType extends Document, THelpers = {}> = Query<ResultType, DocType, THelpers>;
                ~~~~~~~~~~~~~
    'DocumentQuery' was also declared here.

node_modules/ts-mongoose/plugin.d.ts:5:103 - error TS2344: Type 'T & Document<any, any, any>' does not satisfy the constraint 'Document<any, any, any>'.
  The types of 'replaceOne(...).$where(...).and' are incompatible between these types.
    Type '(array: _FilterQuery<T & Document<any, any, any>>[]) => Query<(T & Document<any, any, any>)[], T & Document<any, any, any>, {}, T & Document<...>>' is not assignable to type '(array: _FilterQuery<Document<any, any, any>>[]) => Query<Document<any, any, any>[], Document<any, any, any>, {}, Document<any, any, any>>'.
      Types of parameters 'array' and 'array' are incompatible.
        Type '_FilterQuery<Document<any, any, any>>[]' is not assignable to type '_FilterQuery<T & Document<any, any, any>>[]'.
          Type '_FilterQuery<Document<any, any, any>>' is not assignable to type '_FilterQuery<T & Document<any, any, any>>'.
            Type '_FilterQuery<Document<any, any, any>>' is not assignable to type '{ [P in keyof (T & Document<any, any, any>)]?: Condition<[Extract<(T & Document<any, any, any>)[P], ObjectId>] extends [never] ? (T & Document<any, any, any>)[P] : string | (T & Document<...>)[P]>; }'.

5         populateTs<P extends keyof MaybeItem<NonNullable<T>>>(prop: P): DocumentQuery<Populate<T, P>, T & Document> & QueryHelpers;
                                                                                ~~~~~~~~~~~~

node_modules/ts-mongoose/types/extract.d.ts:10:136 - error TS2344: Type 'R & SubDocument' does not satisfy the constraint 'SubDocument'.
  Types of property 'overwrite' are incompatible.
    Type '(obj: DocumentDefinition<R & SubDocument>) => R & SubDocument' is not assignable to type '(obj: DocumentDefinition<SubDocument>) => SubDocument'.
      Types of parameters 'obj' and 'obj' are incompatible.
        Type 'DocumentDefinition<SubDocument>' is not assignable to type 'DocumentDefinition<R & SubDocument>'.

10 declare type DeepExtractProps<T> = T extends ((infer R & SubDocument) | (infer R & SubDocumentNoId)) ? R : T extends (SubDocumentArray<infer R & SubDocument> | SubDocumentArrayNoId<infer R & SubDocumentNoId>) ? Array<{
                                                                                ~~~~~~~~~~~~~~~~~~~~~

node_modules/ts-mongoose/types/singleType.d.ts:21:173 - error TS2344: Type 'Extract<T> & SubDocument' does not satisfy the constraint 'SubDocument'.
  Types of property 'overwrite' are incompatible.
    Type '(obj: DocumentDefinition<Extract<T> & SubDocument>) => Extract<T> & SubDocument' is not assignable to type '(obj: DocumentDefinition<SubDocument>) => SubDocument'.
      Types of parameters 'obj' and 'obj' are incompatible.
        Type 'DocumentDefinition<SubDocument>' is not assignable to type 'DocumentDefinition<Extract<T> & SubDocument>'.

21 export declare type ArrayOfElements<T> = IsSchemaType<T, ExtractOptions<T> extends OptionIdDisabled ? SubDocumentArrayNoId<Extract<T> & SubDocumentNoId> : SubDocumentArray<Extract<T> & SubDocument>, Array<T>>;
</code>```

Body:
I am trying to run a local copy of a server I am working on with the following packages.

"dependencies": {
"@types/mongodb": "^4.0.7",
"cors": "^2.8.5",
"express": "^4.18.2",
"mongoose": "^5.10.19",
"nodemon": "^2.0.20",
"ts-mongoose": "0.0.24",
"typescript": "3.9.5"

}

However, when I try to run this very basic app I get the following error message.

node_modules/mongoose/index.d.ts:3033:8 - error TS2300: Duplicate identifier 'DocumentQuery'.

After a bit of googling, I /think/ the issue is that both mongoose and mongoose TS are declaring the same identifier. But I'm unsure how to fix it. I'm also unsure of what info needs to be included as well. The code for the app doesn't actually include DocumentQuery, so I find that confusing as well. What should be my next steps in terms of identify and solving the issue?

Here is a full copy of the error.

node_modules/mongoose/index.d.ts:3033:8 - error TS2300: Duplicate identifier 'DocumentQuery'.

3033   type DocumentQuery<ResultType, DocType extends Document, THelpers = {}> = Query<ResultType, DocType, THelpers>;
            ~~~~~~~~~~~~~

  node_modules/ts-mongoose/plugin.d.ts:4:15
    4     interface DocumentQuery<T, DocType extends Document, QueryHelpers = {}> extends mquery {
                    ~~~~~~~~~~~~~
    'DocumentQuery' was also declared here.

node_modules/ts-mongoose/plugin.d.ts:4:15 - error TS2300: Duplicate identifier 'DocumentQuery'.

4     interface DocumentQuery<T, DocType extends Document, QueryHelpers = {}> extends mquery {
                ~~~~~~~~~~~~~

  node_modules/mongoose/index.d.ts:3033:8
    3033   type DocumentQuery<ResultType, DocType extends Document, THelpers = {}> = Query<ResultType, DocType, THelpers>;
                ~~~~~~~~~~~~~
    'DocumentQuery' was also declared here.

node_modules/ts-mongoose/plugin.d.ts:5:103 - error TS2344: Type 'T & Document<any, any, any>' does not satisfy the constraint 'Document<any, any, any>'.
  The types of 'replaceOne(...).$where(...).and' are incompatible between these types.
    Type '(array: _FilterQuery<T & Document<any, any, any>>[]) => Query<(T & Document<any, any, any>)[], T & Document<any, any, any>, {}, T & Document<...>>' is not assignable to type '(array: _FilterQuery<Document<any, any, any>>[]) => Query<Document<any, any, any>[], Document<any, any, any>, {}, Document<any, any, any>>'.
      Types of parameters 'array' and 'array' are incompatible.
        Type '_FilterQuery<Document<any, any, any>>[]' is not assignable to type '_FilterQuery<T & Document<any, any, any>>[]'.
          Type '_FilterQuery<Document<any, any, any>>' is not assignable to type '_FilterQuery<T & Document<any, any, any>>'.
            Type '_FilterQuery<Document<any, any, any>>' is not assignable to type '{ [P in keyof (T & Document<any, any, any>)]?: Condition<[Extract<(T & Document<any, any, any>)[P], ObjectId>] extends [never] ? (T & Document<any, any, any>)[P] : string | (T & Document<...>)[P]>; }'.

5         populateTs<P extends keyof MaybeItem<NonNullable<T>>>(prop: P): DocumentQuery<Populate<T, P>, T & Document> & QueryHelpers;
                                                                                ~~~~~~~~~~~~

node_modules/ts-mongoose/types/extract.d.ts:10:136 - error TS2344: Type 'R & SubDocument' does not satisfy the constraint 'SubDocument'.
  Types of property 'overwrite' are incompatible.
    Type '(obj: DocumentDefinition<R & SubDocument>) => R & SubDocument' is not assignable to type '(obj: DocumentDefinition<SubDocument>) => SubDocument'.
      Types of parameters 'obj' and 'obj' are incompatible.
        Type 'DocumentDefinition<SubDocument>' is not assignable to type 'DocumentDefinition<R & SubDocument>'.

10 declare type DeepExtractProps<T> = T extends ((infer R & SubDocument) | (infer R & SubDocumentNoId)) ? R : T extends (SubDocumentArray<infer R & SubDocument> | SubDocumentArrayNoId<infer R & SubDocumentNoId>) ? Array<{
                                                                                ~~~~~~~~~~~~~~~~~~~~~

node_modules/ts-mongoose/types/singleType.d.ts:21:173 - error TS2344: Type 'Extract<T> & SubDocument' does not satisfy the constraint 'SubDocument'.
  Types of property 'overwrite' are incompatible.
    Type '(obj: DocumentDefinition<Extract<T> & SubDocument>) => Extract<T> & SubDocument' is not assignable to type '(obj: DocumentDefinition<SubDocument>) => SubDocument'.
      Types of parameters 'obj' and 'obj' are incompatible.
        Type 'DocumentDefinition<SubDocument>' is not assignable to type 'DocumentDefinition<Extract<T> & SubDocument>'.

21 export declare type ArrayOfElements<T> = IsSchemaType<T, ExtractOptions<T> extends OptionIdDisabled ? SubDocumentArrayNoId<Extract<T> & SubDocumentNoId> : SubDocumentArray<Extract<T> & SubDocument>, Array<T>>;


问:
How to make App run useQuery without having to refresh the page
I am making a React Application with a GraphQL backend. My code is as follows:

App.js

```<code>import { UserContext } from "./UserContext"
function App() {
    const userQuery = useQuery(USER)
    ...
    return {
        <UserContext.Provider value={userQuery.data}>

</code>```

LoginForm.js

```<code>import { UserContext } from "./UserContext"
function LoginForm() {
  ...
  useEffect(() => {
    if (result.data) {
      const token = result.data.login.value
      localStorage.setItem("user-token", token)
      navigate("/")
    }
  }, [result.data])

</code>```

index.js

```<code>const authLink = setContext((_, { headers }) => {
  const token = localStorage.getItem("mouldy-peppers-user-token")
  return {
    headers: {
      ...headers,
      authorization: token ? `bearer ${token}` : null,
    },
  }
})
</code>```

But when the LoginForm navigates back to "/", the app component re-renders and user is null. Until I refresh the page, then it gets the logged-in user. The authorisation data sent with every graphQL query uses the local storage token. I would like to know how to get the query to use the new auth data without having to refresh the page.

Body:
I am making a React Application with a GraphQL backend. My code is as follows:

App.js

import { UserContext } from "./UserContext"
function App() {
    const userQuery = useQuery(USER)
    ...
    return {
        <UserContext.Provider value={userQuery.data}>

LoginForm.js

import { UserContext } from "./UserContext"
function LoginForm() {
  ...
  useEffect(() => {
    if (result.data) {
      const token = result.data.login.value
      localStorage.setItem("user-token", token)
      navigate("/")
    }
  }, [result.data])

index.js

const authLink = setContext((_, { headers }) => {
  const token = localStorage.getItem("mouldy-peppers-user-token")
  return {
    headers: {
      ...headers,
      authorization: token ? `bearer ${token}` : null,
    },
  }
})

But when the LoginForm navigates back to "/", the app component re-renders and user is null. Until I refresh the page, then it gets the logged-in user. The authorisation data sent with every graphQL query uses the local storage token. I would like to know how to get the query to use the new auth data without having to refresh the page.


问:
Type file (PNG or JPEG)
```<code>function upload(&$model){
    if($_SERVER['REQUEST_METHOD'] === 'POST'){
        $file = $_FILES['file'];
        $file_name = $file['name'];
        $file_ext2 = explode('.', $file_name);
        $file_extenstion = strtolower(end($file_ext2));
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        echo(finfo_file($finfo, $file['tmp_name']));
        echo($file['type']);
       }
    return "superliga_view";
}
</code>```

Why

```<code>echo(finfo_file($finfo, $file['tmp_name']));
</code>```

prints image/jpeg, but

```<code>echo($file['type']);
</code>```

prints "image/png"?

I try make watemark, but

```<code>$image = imagecreatefrompng($target);
</code>```

sometimes throws errors due to wrong file type. With small files php always reads them as png, but with large files it reads them as jpeg.

Title: Type file (PNG or JPEG)

Body:
function upload(&$model){
    if($_SERVER['REQUEST_METHOD'] === 'POST'){
        $file = $_FILES['file'];
        $file_name = $file['name'];
        $file_ext2 = explode('.', $file_name);
        $file_extenstion = strtolower(end($file_ext2));
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        echo(finfo_file($finfo, $file['tmp_name']));
        echo($file['type']);
       }
    return "superliga_view";
}

Why

echo(finfo_file($finfo, $file['tmp_name']));

prints image/jpeg, but

echo($file['type']);

prints "image/png"?

I try make watemark, but

$image = imagecreatefrompng($target);

sometimes throws errors due to wrong file type. With small files php always reads them as png, but with large files it reads them as jpeg.


问:
Why is publishAt in YouTube API not working?
I'm trying to schedule a video to be published via the YouTube API using the video.update method and the status.publishAt parameter.
But I get an error - 400.

The request metadata specifies an invalid scheduled publishing time.

I'm giving the time in the correct format but still getting the error. What can be wrong?
I also used the datetime library. And there I formatted the time in ISO format. But the error still occurs.

Has anyone encountered such a problem?

```<code>import google_auth_oauthlib.flow
import googleapiclient.discovery
import googleapiclient.errors

scopes = ["https://www.googleapis.com/auth/youtube.readonly",
          "https://www.googleapis.com/auth/youtube",
          "https://www.googleapis.com/auth/youtube.force-ssl"]

api_service_name = "youtube"
api_version = "v3"
client_secrets_file = 'client_secret.json'
flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(client_secrets_file, scopes)
credentials = flow.run_local_server(port=0)

youtube = googleapiclient.discovery.build(api_service_name, api_version, credentials=credentials)

# get upload playlist id
request = youtube.channels().list(
    part="contentDetails",
    mine=True
)
response = request.execute()
uploads = response["items"][0]["contentDetails"]["relatedPlaylists"]["uploads"]

# get all uploaded videos
request = youtube.playlistItems().list(
    part="snippet,contentDetails,status",
    playlistId=uploads,
    maxResults=50,
)
response = request.execute()
allvids = response["items"]

while "nextPageToken" in response.keys():
    request = youtube.playlistItems().list(
        part="snippet,contentDetails,status",
        playlistId=uploads,
        maxResults=50,
        pageToken=response["nextPageToken"]
    )
    response = request.execute()
    allvids += response["items"]

# identify only private videos
privvids = [vid for vid in allvids if vid["status"]["privacyStatus"] == "private"]

# let's publish the oldest uploaded draft
vid = privvids[-1]

snippet = vid["snippet"]
# modify snippet as needed

# note that you must set a categoryId if updating the snippet
snippet["categoryId"] = 27  # this is education

# change status to public
status = vid["status"]
status["privacyStatus"] = "private"
status["selfDeclaredMadeForKids"] = False
status["publishAt"] = '2022-12-29T02:00:00.000Z'
# apply changes
response = youtube.videos().update(
    part='snippet,status',
    body=dict(
        snippet=snippet,
        status=status,
        id=snippet["resourceId"]["videoId"]
    )).execute()
</code>```

Body:
I'm trying to schedule a video to be published via the YouTube API using the video.update method and the status.publishAt parameter.
But I get an error - 400.

The request metadata specifies an invalid scheduled publishing time.

I'm giving the time in the correct format but still getting the error. What can be wrong?
I also used the datetime library. And there I formatted the time in ISO format. But the error still occurs.

Has anyone encountered such a problem?

import google_auth_oauthlib.flow
import googleapiclient.discovery
import googleapiclient.errors

scopes = ["https://www.googleapis.com/auth/youtube.readonly",
          "https://www.googleapis.com/auth/youtube",
          "https://www.googleapis.com/auth/youtube.force-ssl"]

api_service_name = "youtube"
api_version = "v3"
client_secrets_file = 'client_secret.json'
flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(client_secrets_file, scopes)
credentials = flow.run_local_server(port=0)

youtube = googleapiclient.discovery.build(api_service_name, api_version, credentials=credentials)

# get upload playlist id
request = youtube.channels().list(
    part="contentDetails",
    mine=True
)
response = request.execute()
uploads = response["items"][0]["contentDetails"]["relatedPlaylists"]["uploads"]

# get all uploaded videos
request = youtube.playlistItems().list(
    part="snippet,contentDetails,status",
    playlistId=uploads,
    maxResults=50,
)
response = request.execute()
allvids = response["items"]

while "nextPageToken" in response.keys():
    request = youtube.playlistItems().list(
        part="snippet,contentDetails,status",
        playlistId=uploads,
        maxResults=50,
        pageToken=response["nextPageToken"]
    )
    response = request.execute()
    allvids += response["items"]

# identify only private videos
privvids = [vid for vid in allvids if vid["status"]["privacyStatus"] == "private"]

# let's publish the oldest uploaded draft
vid = privvids[-1]

snippet = vid["snippet"]
# modify snippet as needed

# note that you must set a categoryId if updating the snippet
snippet["categoryId"] = 27  # this is education

# change status to public
status = vid["status"]
status["privacyStatus"] = "private"
status["selfDeclaredMadeForKids"] = False
status["publishAt"] = '2022-12-29T02:00:00.000Z'
# apply changes
response = youtube.videos().update(
    part='snippet,status',
    body=dict(
        snippet=snippet,
        status=status,
        id=snippet["resourceId"]["videoId"]
    )).execute()


问:
Xml script: How do we point our own working directory?
```<code><?xml version="1.0" encoding="UTF-8"?>
    <attributes>
    <attribute name="priority" type="string"/>
        <attribute name="hierarchy" type="script"path="$WORK_DIR/pvim2vmgr/python_script/hierarchy.py">
            <scriptParam name="subject"/>
            <scriptParam name="test_plan"/>
    </attribute>
</code>```

I'm expecting when I set environment cmd in xterm.

setenv WORK_DIR <my_path>

In xml script, it'll recognize my directory ($WORK_DIR).However, it doesn't, is there any cmd for me to implement it?

Purpose of using xml script

I'm using it to obtain information from certain website and generate a csv file. This xml script is running with command line argument.

Reason I want to replace Working directory

When I'm using other person working_dir to generate this xml script, it automatically replace the $WORK_DIR to other person instead of mine.


问:
Phone Number Hint enable phone number sharing
Phone Number Hint API allows to pick phone number.
According to docs user can disable phone number sharing. How to re-enable it?
Where I can find an autofill screen?

Here is the code I use to call a "Choose phone number" dialog. When user has disable "Phone number sharing" it doesn't work anymore.

```<code>private val phoneNumberHintIntentResultLauncher: ActivityResultLauncher<IntentSenderRequest> =
    registerForActivityResult(ActivityResultContracts.StartIntentSenderForResult()) { result ->
        try {
            val phoneNumber = Identity.getSignInClient(requireActivity()).getPhoneNumberFromIntent(result.data)
            binding?.frgSetupAccountEtPhone?.setText(phoneNumber)
        } catch (e: Exception) {
            log(e)
        }
    }

private fun requestHint() {
    val request: GetPhoneNumberHintIntentRequest = GetPhoneNumberHintIntentRequest.builder().build()
    Identity.getSignInClient(requireActivity())
        .getPhoneNumberHintIntent(request)
        .addOnSuccessListener { result ->
            val phoneRequest = IntentSenderRequest.Builder(result.intentSender).build()
            phoneNumberHintIntentResultLauncher.launch(phoneRequest)
        }
        .addOnFailureListener {
            log(it)
        }
}
</code>```

Body:
Phone Number Hint API allows to pick phone number.
According to docs user can disable phone number sharing. How to re-enable it?
Where I can find an autofill screen?

Here is the code I use to call a "Choose phone number" dialog. When user has disable "Phone number sharing" it doesn't work anymore.

private val phoneNumberHintIntentResultLauncher: ActivityResultLauncher<IntentSenderRequest> =
    registerForActivityResult(ActivityResultContracts.StartIntentSenderForResult()) { result ->
        try {
            val phoneNumber = Identity.getSignInClient(requireActivity()).getPhoneNumberFromIntent(result.data)
            binding?.frgSetupAccountEtPhone?.setText(phoneNumber)
        } catch (e: Exception) {
            log(e)
        }
    }

private fun requestHint() {
    val request: GetPhoneNumberHintIntentRequest = GetPhoneNumberHintIntentRequest.builder().build()
    Identity.getSignInClient(requireActivity())
        .getPhoneNumberHintIntent(request)
        .addOnSuccessListener { result ->
            val phoneRequest = IntentSenderRequest.Builder(result.intentSender).build()
            phoneNumberHintIntentResultLauncher.launch(phoneRequest)
        }
        .addOnFailureListener {
            log(it)
        }
}


问:
gate descriptor is not valid sys seg
i use Bochs to emulate my kernel. I wrote IDT struct, load_idt function and keyboard handler procedure. Print handler, called by keyboard handler, just read 0x60 port and put char on screen.
When Bochs work and i press any key it restarts. And in log file:

```<code>00080068800e[CPU0  ] interrupt(): gate descriptor is not valid sys seg (vector=0x21)
00080068800e[CPU0  ] interrupt(): gate descriptor is not valid sys seg (vector=0x0d)
00080068800e[CPU0  ] interrupt(): gate descriptor is not valid sys seg (vector=0x08)
</code>```

my code:

```<code>struct IDT
{
    unsigned short offset_lowerbits;
    unsigned short offset_higherbits;
    unsigned short selector;
    unsigned char zero;
    unsigned char type_attributes;
};

struct IDT IDT_deskriptors[IDT_SIZE];

extern "C" void IDT_init()
{
    unsigned long idt_ptr[2];
    unsigned long idt_address = (unsigned long)IDT_deskriptors;
    idt_ptr[0] = (sizeof(struct IDT) * IDT_SIZE) + ((idt_address & 0xffff) << 16);
    idt_ptr[1] = idt_address >> 16;

    unsigned long kbd_address = (unsigned long)kbd_handler;
    IDT_deskriptors[0x21].offset_lowerbits = (kbd_address & 0xffff);
    IDT_deskriptors[0x21].offset_higherbits = (kbd_address & 0xffff0000) >> 16;
    IDT_deskriptors[0x21].zero = 0;
    IDT_deskriptors[0x21].selector = 0x08;
    IDT_deskriptors[0x21].type_attributes = 0x8e;

    outb(0x20, 0x11);
    outb(0xA0, 0x11);

    outb(0x21, 0x20);
    outb(0xA1, 0x28);

    outb(0x21, 0x04);
    outb(0xA1, 0x02);

    outb(0x21, 0x01);
    outb(0xA1, 0x01);

    outb(0x21, 0x0);
    outb(0xA1, 0x0);

    load_idt(idt_ptr);
}

extern "C" void kmain(void)
{
    IDT_init();
    kbd_init();
    while (1)
    {
        asm("hlt");
    };
}
</code>```

Asm functions

```<code>load_idt:
    mov edx, [esp + 4]
    lidt [edx]
    sti
    iretd

kbd_handler:
    call print_handler
    iretd
</code>```

I think, my problem in IDT filling and i used memset function to set 0 unused deskriptors. But Bochs gives:

```<code>00185622638e[CPU0  ] interrupt(): vector must be within IDT table limits, IDT.limit = 0x0
00185622638e[CPU0  ] interrupt(): vector must be within IDT table limits, IDT.limit = 0x0
00185622638e[CPU0  ] interrupt(): vector must be within IDT table limits, IDT.limit = 0x0
</code>```

Title: gate descriptor is not valid sys seg

Body:
i use Bochs to emulate my kernel. I wrote IDT struct, load_idt function and keyboard handler procedure. Print handler, called by keyboard handler, just read 0x60 port and put char on screen.
When Bochs work and i press any key it restarts. And in log file:

00080068800e[CPU0  ] interrupt(): gate descriptor is not valid sys seg (vector=0x21)
00080068800e[CPU0  ] interrupt(): gate descriptor is not valid sys seg (vector=0x0d)
00080068800e[CPU0  ] interrupt(): gate descriptor is not valid sys seg (vector=0x08)

my code:

struct IDT
{
    unsigned short offset_lowerbits;
    unsigned short offset_higherbits;
    unsigned short selector;
    unsigned char zero;
    unsigned char type_attributes;
};

struct IDT IDT_deskriptors[IDT_SIZE];

extern "C" void IDT_init()
{
    unsigned long idt_ptr[2];
    unsigned long idt_address = (unsigned long)IDT_deskriptors;
    idt_ptr[0] = (sizeof(struct IDT) * IDT_SIZE) + ((idt_address & 0xffff) << 16);
    idt_ptr[1] = idt_address >> 16;

    unsigned long kbd_address = (unsigned long)kbd_handler;
    IDT_deskriptors[0x21].offset_lowerbits = (kbd_address & 0xffff);
    IDT_deskriptors[0x21].offset_higherbits = (kbd_address & 0xffff0000) >> 16;
    IDT_deskriptors[0x21].zero = 0;
    IDT_deskriptors[0x21].selector = 0x08;
    IDT_deskriptors[0x21].type_attributes = 0x8e;

    outb(0x20, 0x11);
    outb(0xA0, 0x11);

    outb(0x21, 0x20);
    outb(0xA1, 0x28);

    outb(0x21, 0x04);
    outb(0xA1, 0x02);

    outb(0x21, 0x01);
    outb(0xA1, 0x01);

    outb(0x21, 0x0);
    outb(0xA1, 0x0);

    load_idt(idt_ptr);
}

extern "C" void kmain(void)
{
    IDT_init();
    kbd_init();
    while (1)
    {
        asm("hlt");
    };
}

Asm functions

load_idt:
    mov edx, [esp + 4]
    lidt [edx]
    sti
    iretd

kbd_handler:
    call print_handler
    iretd

I think, my problem in IDT filling and i used memset function to set 0 unused deskriptors. But Bochs gives:

00185622638e[CPU0  ] interrupt(): vector must be within IDT table limits, IDT.limit = 0x0
00185622638e[CPU0  ] interrupt(): vector must be within IDT table limits, IDT.limit = 0x0
00185622638e[CPU0  ] interrupt(): vector must be within IDT table limits, IDT.limit = 0x0


问:
How to install LSPServer for Vue+Pug in NeoVim editor?
I have a question for advanced Wimers/Neowimers on setting up Syntax, tabs and LSP for Pug inside a Vue component.

Recently moved from PhpStorm and Vscode to Nvim with AstroNvim config.
But there are some difficulties in customizing this editor for my technology stack that I use in my work.

For JavaScript I use LSP tsserver, I love it!
For Vue, I tried to use Volar, but it only works if we use the usual markup in the vue file, I couldn’t make friends with Pug,

My project has an index.vue file

```<code><template lang="pug">
    section.cabinet
        .container
            h2 lorem ipsum
</code>```

In this case, Volar will show that it was expecting a different token.

```<code><template lang="pug">
    section.cabinet__agency_info [VOLAR]=> Undefined Syntax Token
</code>```

That is, he expected to see such markup

```<code><template lang="pug">
    <section class="cabinet__agency_info">
</code>```

The question is how to make him friends with Pug so that he does not show that there is an error

There is also a nuance with Sass/Scss
Couldn't find language-parser for Sass, but found for Scss, installed it and installed language-parser for Css
Syntax highlighting works for Sass but only in sass files inside vue it doesn't work
For example, if we have such markup in the file

```<code><style lang="sass" scoped>
    .dropdown.phones
        button, label
            span[data-image]
</code>```

What is inside the Style tag, it does not highlight in any way!

In general, Nvim is configured for Backend.
The global question is how to configure Nvim for Frontend,

Body:
I have a question for advanced Wimers/Neowimers on setting up Syntax, tabs and LSP for Pug inside a Vue component.

Recently moved from PhpStorm and Vscode to Nvim with AstroNvim config.
But there are some difficulties in customizing this editor for my technology stack that I use in my work.

For JavaScript I use LSP tsserver, I love it!
For Vue, I tried to use Volar, but it only works if we use the usual markup in the vue file, I couldn’t make friends with Pug,

My project has an index.vue file

<template lang="pug">
    section.cabinet
        .container
            h2 lorem ipsum

In this case, Volar will show that it was expecting a different token.

<template lang="pug">
    section.cabinet__agency_info [VOLAR]=> Undefined Syntax Token

That is, he expected to see such markup

<template lang="pug">

The question is how to make him friends with Pug so that he does not show that there is an error

There is also a nuance with Sass/Scss
Couldn't find language-parser for Sass, but found for Scss, installed it and installed language-parser for Css
Syntax highlighting works for Sass but only in sass files inside vue it doesn't work
For example, if we have such markup in the file