问:
debugpy warning when running a flask app alongside a selenium webdriver instance
I get the following warning when running a flask app alongside selenium:
UserWarning: incompatible copy of pydevd already imported

```<code>C:\Users\Admin\AppData\Roaming\Python\Python39\site-packages\debugpy\_vendored\force_pydevd.py:18: UserWarning: incompatible copy of pydevd already imported:
</code>```

Then webdriver keeps retrying to open chrome over and over again, which raises the following exception:
Chrome failed to start: exited normally. DevToolsActivePort file doesn't exist

```<code>Exception has occurred: WebDriverException
Message: unknown error: Chrome failed to start: exited normally.
  (unknown error: DevToolsActivePort file doesn't exist)
  (The process started from chrome location C:\Program Files\Google\Chrome\Application\chrome.exe is no longer running, so ChromeDriver is assuming that Chrome has crashed.)
Stacktrace:
Backtrace:
    (No symbol) [0x0112F243]
    (No symbol) [0x010B7FD1]
    (No symbol) [0x00FAD04D]
    (No symbol) [0x00FCC24E]
    (No symbol) [0x00FC82E9]
    (No symbol) [0x00FFF056]
    (No symbol) [0x00FFEB2A]
    (No symbol) [0x00FF8386]
    (No symbol) [0x00FD163C]
    (No symbol) [0x00FD269D]
    GetHandleVerifier [0x013C9A22+2655074]
    GetHandleVerifier [0x013BCA24+2601828]
    GetHandleVerifier [0x011D8C0A+619850]
    GetHandleVerifier [0x011D7830+614768]
    (No symbol) [0x010C05FC]
    (No symbol) [0x010C5968]
    (No symbol) [0x010C5A55]
    (No symbol) [0x010D051B]
    BaseThreadInitThunk [0x7630FEF9+25]
    RtlGetAppContainerNamedObjectPath [0x77487BBE+286]
    RtlGetAppContainerNamedObjectPath [0x77487B8E+238]
  File "F:\Projects\Python\thinkLikePotato\new\new.py", line 40, in initBrowser
    chrome = webdriver.Chrome(options=options)
  File "F:\Projects\Python\thinkLikePotato\new\new.py", line 81, in <module>
    initBrowser()
selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: exited normally.
  (unknown error: DevToolsActivePort file doesn't exist)
  (The process started from chrome location C:\Program Files\Google\Chrome\Application\chrome.exe is no longer running, so ChromeDriver is assuming that Chrome has crashed.)
Stacktrace:
Backtrace:
    (No symbol) [0x0112F243]
    (No symbol) [0x010B7FD1]
    (No symbol) [0x00FAD04D]
    (No symbol) [0x00FCC24E]
    (No symbol) [0x00FC82E9]
    (No symbol) [0x00FFF056]
    (No symbol) [0x00FFEB2A]
    (No symbol) [0x00FF8386]
    (No symbol) [0x00FD163C]
    (No symbol) [0x00FD269D]
    GetHandleVerifier [0x013C9A22+2655074]
    GetHandleVerifier [0x013BCA24+2601828]
    GetHandleVerifier [0x011D8C0A+619850]
    GetHandleVerifier [0x011D7830+614768]
    (No symbol) [0x010C05FC]
    (No symbol) [0x010C5968]
    (No symbol) [0x010C5A55]
    (No symbol) [0x010D051B]
    BaseThreadInitThunk [0x7630FEF9+25]
    RtlGetAppContainerNamedObjectPath [0x77487BBE+286]
    RtlGetAppContainerNamedObjectPath [0x77487B8E+238]

</code>```

Here is my full code:

```<code>from time import sleep
from youtubesearchpython import VideosSearch
import threading

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

from flask import Flask, render_template
flaskapp = Flask(__name__)

songQueue = []

class song:
    def __init__(self, url, title):
        self.url = url
        self.title = title

#######################################################################

def searchSong(songRequest):
    searchResult = VideosSearch(songRequest, limit = 1).result()
    if len(searchResult["result"]) > 0:
        songName = (searchResult["result"][0]["title"])
        songLink = (searchResult["result"][0]["link"])
        songQueue.append(song(songLink,songName))
    else:
        print("Search results returned no videos. Please check that your song suggestion was spelt correctly.")

def initBrowser():
    global chrome
    #webbrowser.register("edge", None, webbrowser.GenericBrowser("C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe"))
    #edge = webbrowser.get("edge")
    options = Options()
    options.add_experimental_option("excludeSwitches", ['enable-automation'])
    options.add_argument(r"--user-data-dir=C:\Users\Admin\AppData\Local\Google\Chrome\User Data")
    options.add_argument("--autoplay-policy=no-user-gesture-required")
    chrome = webdriver.Chrome(options=options)

def nextSong():
    try:songQueue.pop(0)
    except:pass
    while len(songQueue) == 0:
        pass
    chrome.get(songQueue[0].url+"?autoplay=1")

    global elementCurrentPlaybackTime
    global videoLength
    elementCurrentPlaybackTime= chrome.find_element(By.CLASS_NAME,"ytp-time-current")
    videoLength = chrome.find_element(By.CLASS_NAME,"ytp-time-duration").text

def testSongs():
    songQueue.append(song("https://www.youtube.com/watch?v=ByAxrX4JhFU", "come in"))
    songQueue.append(song("https://www.youtube.com/watch?v=lzhgl_qrZGg", "older than before"))

#######################################################################
### THREADS ####
################

def playerLoop():
    while True:
        try:
            chrome.execute_script("""setTimeout(function(){let video = document.querySelector("#movie_player");setInterval(function(){video.dispatchEvent(new Event('mousemove'));},100);},1500)""")
            currentPlaybackTime = elementCurrentPlaybackTime.text
        except:pass

        if currentPlaybackTime == videoLength:
            nextSong()

def webLoop():
    pass

@flaskapp.route('/')
def mainIndex():
  return render_template('main.html')

#######################################################################

initBrowser()
testSongs()

chrome.get(songQueue[0].url+"?autoplay=1")

elementCurrentPlaybackTime= chrome.find_element(By.CLASS_NAME,"ytp-time-current")
videoLength = chrome.find_element(By.CLASS_NAME,"ytp-time-duration").text

if __name__ == "__main__":
    flaskapp.run(debug=True)

    playerThread = threading.Thread(target=playerLoop)
    webThread = threading.Thread(target=webLoop)
    playerThread.start()
    webThread.start()

</code>```

Any help is appreciated

I've tried these add_argument(): headless, debug port, no sandbox
I've also tried installing pywin32

Edit:
Fixed by adding use_reloader=False to flaskapp.run() and putting it into it's own thread (webLoop)

Body:
I get the following warning when running a flask app alongside selenium:
UserWarning: incompatible copy of pydevd already imported

C:\Users\Admin\AppData\Roaming\Python\Python39\site-packages\debugpy\_vendored\force_pydevd.py:18: UserWarning: incompatible copy of pydevd already imported:

Then webdriver keeps retrying to open chrome over and over again, which raises the following exception:
Chrome failed to start: exited normally. DevToolsActivePort file doesn't exist

Exception has occurred: WebDriverException
Message: unknown error: Chrome failed to start: exited normally.
  (unknown error: DevToolsActivePort file doesn't exist)
  (The process started from chrome location C:\Program Files\Google\Chrome\Application\chrome.exe is no longer running, so ChromeDriver is assuming that Chrome has crashed.)
Stacktrace:
Backtrace:
    (No symbol) [0x0112F243]
    (No symbol) [0x010B7FD1]
    (No symbol) [0x00FAD04D]
    (No symbol) [0x00FCC24E]
    (No symbol) [0x00FC82E9]
    (No symbol) [0x00FFF056]
    (No symbol) [0x00FFEB2A]
    (No symbol) [0x00FF8386]
    (No symbol) [0x00FD163C]
    (No symbol) [0x00FD269D]
    GetHandleVerifier [0x013C9A22+2655074]
    GetHandleVerifier [0x013BCA24+2601828]
    GetHandleVerifier [0x011D8C0A+619850]
    GetHandleVerifier [0x011D7830+614768]
    (No symbol) [0x010C05FC]
    (No symbol) [0x010C5968]
    (No symbol) [0x010C5A55]
    (No symbol) [0x010D051B]
    BaseThreadInitThunk [0x7630FEF9+25]
    RtlGetAppContainerNamedObjectPath [0x77487BBE+286]
    RtlGetAppContainerNamedObjectPath [0x77487B8E+238]
  File "F:\Projects\Python\thinkLikePotato\new\new.py", line 40, in initBrowser
    chrome = webdriver.Chrome(options=options)
  File "F:\Projects\Python\thinkLikePotato\new\new.py", line 81, in <module>
    initBrowser()
selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: exited normally.
  (unknown error: DevToolsActivePort file doesn't exist)
  (The process started from chrome location C:\Program Files\Google\Chrome\Application\chrome.exe is no longer running, so ChromeDriver is assuming that Chrome has crashed.)
Stacktrace:
Backtrace:
    (No symbol) [0x0112F243]
    (No symbol) [0x010B7FD1]
    (No symbol) [0x00FAD04D]
    (No symbol) [0x00FCC24E]
    (No symbol) [0x00FC82E9]
    (No symbol) [0x00FFF056]
    (No symbol) [0x00FFEB2A]
    (No symbol) [0x00FF8386]
    (No symbol) [0x00FD163C]
    (No symbol) [0x00FD269D]
    GetHandleVerifier [0x013C9A22+2655074]
    GetHandleVerifier [0x013BCA24+2601828]
    GetHandleVerifier [0x011D8C0A+619850]
    GetHandleVerifier [0x011D7830+614768]
    (No symbol) [0x010C05FC]
    (No symbol) [0x010C5968]
    (No symbol) [0x010C5A55]
    (No symbol) [0x010D051B]
    BaseThreadInitThunk [0x7630FEF9+25]
    RtlGetAppContainerNamedObjectPath [0x77487BBE+286]
    RtlGetAppContainerNamedObjectPath [0x77487B8E+238]

Here is my full code:

from time import sleep
from youtubesearchpython import VideosSearch
import threading

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

from flask import Flask, render_template
flaskapp = Flask(__name__)

songQueue = []

class song:
    def __init__(self, url, title):
        self.url = url
        self.title = title

#######################################################################

def searchSong(songRequest):
    searchResult = VideosSearch(songRequest, limit = 1).result()
    if len(searchResult["result"]) > 0:
        songName = (searchResult["result"][0]["title"])
        songLink = (searchResult["result"][0]["link"])
        songQueue.append(song(songLink,songName))
    else:
        print("Search results returned no videos. Please check that your song suggestion was spelt correctly.")

def initBrowser():
    global chrome
    #webbrowser.register("edge", None, webbrowser.GenericBrowser("C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe"))
    #edge = webbrowser.get("edge")
    options = Options()
    options.add_experimental_option("excludeSwitches", ['enable-automation'])
    options.add_argument(r"--user-data-dir=C:\Users\Admin\AppData\Local\Google\Chrome\User Data")
    options.add_argument("--autoplay-policy=no-user-gesture-required")
    chrome = webdriver.Chrome(options=options)

def nextSong():
    try:songQueue.pop(0)
    except:pass
    while len(songQueue) == 0:
        pass
    chrome.get(songQueue[0].url+"?autoplay=1")

    global elementCurrentPlaybackTime
    global videoLength
    elementCurrentPlaybackTime= chrome.find_element(By.CLASS_NAME,"ytp-time-current")
    videoLength = chrome.find_element(By.CLASS_NAME,"ytp-time-duration").text

def testSongs():
    songQueue.append(song("https://www.youtube.com/watch?v=ByAxrX4JhFU", "come in"))
    songQueue.append(song("https://www.youtube.com/watch?v=lzhgl_qrZGg", "older than before"))

#######################################################################
### THREADS ####
################

def playerLoop():
    while True:
        try:
            chrome.execute_script("""setTimeout(function(){let video = document.querySelector("#movie_player");setInterval(function(){video.dispatchEvent(new Event('mousemove'));},100);},1500)""")
            currentPlaybackTime = elementCurrentPlaybackTime.text
        except:pass

        if currentPlaybackTime == videoLength:
            nextSong()

def webLoop():
    pass

@flaskapp.route('/')
def mainIndex():
  return render_template('main.html')

#######################################################################

initBrowser()
testSongs()

chrome.get(songQueue[0].url+"?autoplay=1")

elementCurrentPlaybackTime= chrome.find_element(By.CLASS_NAME,"ytp-time-current")
videoLength = chrome.find_element(By.CLASS_NAME,"ytp-time-duration").text

if __name__ == "__main__":
    flaskapp.run(debug=True)

    playerThread = threading.Thread(target=playerLoop)
    webThread = threading.Thread(target=webLoop)
    playerThread.start()
    webThread.start()

Any help is appreciated

I've tried these add_argument(): headless, debug port, no sandbox
I've also tried installing pywin32

Edit:
Fixed by adding use_reloader=False to flaskapp.run() and putting it into it's own thread (webLoop)


来源: stackexchange

问:
Wordpress - Installing plugin error - "Missing a temporary folder"
I have an error when installing the plugin on Wordpress

Upload plugin

Missing a temporary folder error

I tried add this code

```<code>define('WP_TEMP_DIR', dirname(__FILE__) . '/wp-content/temp/');
</code>```

into the wp-config.php and set the permission to **755 **already but it's not work

File Manager

Change permission

wp-config.php

I have stuck on this problem about 1 week, anyone figured out this problem?

ContentLicense: CC BY-SA 4.0

Body:
I have an error when installing the plugin on Wordpress

Upload plugin

Missing a temporary folder error

I tried add this code

define('WP_TEMP_DIR', dirname(__FILE__) . '/wp-content/temp/');

into the wp-config.php and set the permission to **755 **already but it's not work

File Manager

Change permission

wp-config.php

I have stuck on this problem about 1 week, anyone figured out this problem?


问:
Why does my customisation of settings.json in VS Code not work?
I customized the VS Code's settings.json to customize the highlightning color of functions. It worked for the built-in function "print" but not for imported functions as "matplotlib.pyplot.scatter".

My settings.json

My py-file


问:
Cloud Function can't deploy with argument --gen2?
I was trying everything possible, but the CLI (Terminal Mac) will not accept the argument --gen2 to create a generation2 Function.

```<code>sudo gcloud functions deploy func_name --gen2  --runtime=python39  --region=us-central1 --trigger-http
</code>```

According to the docs : https://cloud.google.com/functions/docs/deploy this need to be added. (also not clear why they write [--gen2] inside [] and on different docs they write --gen2 (https://cloud.google.com/functions/docs/create-deploy-gcloud#functions-deploy-command-python)

Emitting this will create a gen1 Function, but if you create the gen2 Function on the web platform first, then you will not be able to redeploy it from cli ( because it see it as a duplicate and ask to delete the Function that is already exist).
I am so surprised by the unclarity and bugs by such a large company's new product.

Bottom line - I can't create gen 2 Function no matter what direction I choose.

Body:
I was trying everything possible, but the CLI (Terminal Mac) will not accept the argument --gen2 to create a generation2 Function.

sudo gcloud functions deploy func_name --gen2  --runtime=python39  --region=us-central1 --trigger-http

According to the docs : https://cloud.google.com/functions/docs/deploy this need to be added. (also not clear why they write [--gen2] inside [] and on different docs they write --gen2 (https://cloud.google.com/functions/docs/create-deploy-gcloud#functions-deploy-command-python)

Emitting this will create a gen1 Function, but if you create the gen2 Function on the web platform first, then you will not be able to redeploy it from cli ( because it see it as a duplicate and ask to delete the Function that is already exist).
I am so surprised by the unclarity and bugs by such a large company's new product.

Bottom line - I can't create gen 2 Function no matter what direction I choose.


问:
How to make SwiftUI ViewBuilder accept only Views of certain protocol as input blocks?
I am trying to use a SwiftUI @ViewBuilder to allow users of my package to dynamically specify a view's body content. However, I am trying to restrict the possible views that can be used as an input to just a few default views I implemented (for streamlining purposes).

This is an example:

public protocol PopupBodyView: View { } // every one of my default views conforms to this protocol

func generateChildView(@ViewBuilder items: () -> PopupBodyView)
-> some PopupBodyView {
    return menuItems()
}
```
<p>If I now call <code>generateChildView</code>, I can correctly specify <strong>one</strong> view of protocol type <code>PopupBodyView</code> - however, if I specify more than one view in the result builder body, I get the following error:</p>
<p><code>Instance method 'contextMenu(items:)' requires that 'TupleView<(Text, Text)>' conform to 'PopupBodyView'</code></p>
<pre class="lang-swift prettyprint-override"><code>extension Text: PopupBodyView { } // add protocol conformance

contextMenu {
    Text("Test")
    Text("Test") // Instance method 'contextMenu(items:)' requires that 'TupleView<(Text, Text)>' conform to 'PopupBodyView'
}
</code>```

How can I now adapt the default @ViewBuilder to accept only Views that conform to my custom PopupBodyContent type? I basically only want to limit the set of possible inputs the view builder accepts.

Body:
I am trying to use a SwiftUI @ViewBuilder to allow users of my package to dynamically specify a view's body content. However, I am trying to restrict the possible views that can be used as an input to just a few default views I implemented (for streamlining purposes).

This is an example:

public protocol PopupBodyView: View { } // every one of my default views conforms to this protocol

func generateChildView(@ViewBuilder items: () -> PopupBodyView)
-> some PopupBodyView {
    return menuItems()
}

If I now call generateChildView, I can correctly specify one view of protocol type PopupBodyView - however, if I specify more than one view in the result builder body, I get the following error:

Instance method 'contextMenu(items:)' requires that 'TupleView<(Text, Text)>' conform to 'PopupBodyView'

extension Text: PopupBodyView { } // add protocol conformance

contextMenu {
    Text("Test")
    Text("Test") // Instance method 'contextMenu(items:)' requires that 'TupleView<(Text, Text)>' conform to 'PopupBodyView'
}

How can I now adapt the default @ViewBuilder to accept only Views that conform to my custom PopupBodyContent type? I basically only want to limit the set of possible inputs the view builder accepts.


问:
Python selenium proxy authentication in incognito AND headless AND extensions disabled chromedriver
This question was asked many times, but I didnt found a solution for a headless + icognito + extensions disabled browser.

Seleniumwire does not work properly with https. There is these install certificate thingy but I want to use like 20 Browser instances in parrallel and dont want to install any certificates manually.

I try to stay under the radar, so I use these options.
my Config is following:

from src.models import Proxy, Useragent
from selenium.webdriver.chrome.options import Options
from selenium import webdriver

def configure_driver(proxy: Proxy, useragent: Useragent):
    options = Options()

    options.add_argument("--ignore-certificate-errors")
    options.add_argument("--incognito")
    options.add_argument("--headless")
    options.add_argument("--no-sandbox")
    options.add_argument("--disable-dev-shm-usage")
    options.add_argument('--disable-blink-features=AutomationControlled')
    options.add_argument("--disable-notifications")
    options.add_argument("--disable-extensions")
    options.add_argument('--window-size=1920,1080')
    options.add_argument("--disable-gpu")

    options.add_argument(f'user-agent={useragent}')
    options.add_experimental_option("excludeSwitches", ["enable-automation"])
    options.add_experimental_option('useAutomationExtension', False)

    driver = webdriver.Chrome(
        options=options)
    driver.set_page_load_timeout(10)

    return driver
```

How to do proxy authentication with that config?

No satisfactory answers are:

Seleniumwire with manually uploading a certificate to work properly with https

Using extensions

Not using headless

Not using icognito

Whitelisting my own IP at the proxy provider

Body:
This question was asked many times, but I didnt found a solution for a headless + icognito + extensions disabled browser.

Seleniumwire does not work properly with https. There is these install certificate thingy but I want to use like 20 Browser instances in parrallel and dont want to install any certificates manually.

I try to stay under the radar, so I use these options.
my Config is following:

from src.models import Proxy, Useragent
from selenium.webdriver.chrome.options import Options
from selenium import webdriver

def configure_driver(proxy: Proxy, useragent: Useragent):
    options = Options()

    options.add_argument("--ignore-certificate-errors")
    options.add_argument("--incognito")
    options.add_argument("--headless")
    options.add_argument("--no-sandbox")
    options.add_argument("--disable-dev-shm-usage")
    options.add_argument('--disable-blink-features=AutomationControlled')
    options.add_argument("--disable-notifications")
    options.add_argument("--disable-extensions")
    options.add_argument('--window-size=1920,1080')
    options.add_argument("--disable-gpu")

    options.add_argument(f'user-agent={useragent}')
    options.add_experimental_option("excludeSwitches", ["enable-automation"])
    options.add_experimental_option('useAutomationExtension', False)

    driver = webdriver.Chrome(
        options=options)
    driver.set_page_load_timeout(10)

    return driver

How to do proxy authentication with that config?

No satisfactory answers are:

Seleniumwire with manually uploading a certificate to work properly with https

Using extensions

Not using headless

Not using icognito

Whitelisting my own IP at the proxy provider


问:
How to get access to global DOM variables (window, localStorage) in a package in a Turborepo?
Context:
Using Turborepo to create a host app and a bunch of microfrontend packages. Problem is in those packages I dont have access to any of the global variables. The monorepo is Open Source.

Problem:
Inside a package named store where I want to have access to localStorage.

Story:
The user can select a custom language for the web app.

The default is (string) en with other option for de, as example.
User selecting a language calls change_language(lang: string) which:

sets the language for i18next

updates the state in React Context API.

Also, I want to persist the language by saving in the localStorage, but in this this package I don't have access to DOM global variables.

Question

What is another way I can use global variables in Turborepo monorepo packages, without passing it as props as I did?

What library / package do I need to import inside store to have access to the global scope?

My current solution:
The only way I got this to work is by passing window through props. from main.tsx (main file from the react host app) to AppContext.tsx (in store package). through the ContextProvider:

main.tsx:

```<code>ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
  <React.StrictMode>
    <ContextProvider window={window}>
      <App />
    </ContextProvider>
  </React.StrictMode>
);
</code>```

AppContext.tsx:

```<code>export function ContextProvider({ window, children }: {
  window: **any**;
  children: React.ReactNode;
}) { ... }
</code>```

Notice any because I dont have access to Window & typeof globalThis

Now, I have access to global variables like so:

window.localStorage( ... )

I dislike this implementation, because of the dependency created.

Body:
Context:
Using Turborepo to create a host app and a bunch of microfrontend packages. Problem is in those packages I dont have access to any of the global variables. The monorepo is Open Source.

Problem:
Inside a package named store where I want to have access to localStorage.

Story:
The user can select a custom language for the web app.

The default is (string) en with other option for de, as example.
User selecting a language calls change_language(lang: string) which:

sets the language for i18next

updates the state in React Context API.

Also, I want to persist the language by saving in the localStorage, but in this this package I don't have access to DOM global variables.

Question

What is another way I can use global variables in Turborepo monorepo packages, without passing it as props as I did?

What library / package do I need to import inside store to have access to the global scope?

My current solution:
The only way I got this to work is by passing window through props. from main.tsx (main file from the react host app) to AppContext.tsx (in store package). through the ContextProvider:

main.tsx:

ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
  <React.StrictMode>
    <ContextProvider window={window}>
      <App />
    </ContextProvider>
  </React.StrictMode>
);

AppContext.tsx:

export function ContextProvider({ window, children }: {
  window: **any**;
  children: React.ReactNode;
}) { ... }

Notice any because I dont have access to Window & typeof globalThis

Now, I have access to global variables like so:

window.localStorage( ... )

I dislike this implementation, because of the dependency created.


问:
Import GoogleWebRTC with pod but no header files
```<code>use_frameworks!

install! 'cocoapods',
         :preserve_pod_file_structure => true

platform :ios, '11.0'

source 'https://github.com/CocoaPods/Specs.git'

target 'WebRTCDemo' do
    inherit! :search_paths

  pod 'GoogleWebRTC'

end
</code>```

Only static libraries have no header files

I have also downloaded the header file in the source code, but there are still other errors

Body:
use_frameworks!

install! 'cocoapods',
         :preserve_pod_file_structure => true

platform :ios, '11.0'

source 'https://github.com/CocoaPods/Specs.git'

target 'WebRTCDemo' do
    inherit! :search_paths

  pod 'GoogleWebRTC'

end

Only static libraries have no header files

I have also downloaded the header file in the source code, but there are still other errors


问:
(SAC) Change the cell color based on specific text value
I'm new to SAP Analytics Cloud.
I have a table with a column named "Status", if a cell has a value of "Done" then the background color will change. Is this possible with SAP Analytics Cloud?

I tried conditional formatting but it only works with numbers.


问:
Use SMTPHandler using SSL
I'm using Flask. When an error occurs, I want be notified by email.
If a use TLS, it works, but if I use SSL, it doesn't.
What am I doing wrong?

```<code>import logging
import ssl
from logging.handlers import SMTPHandler

if not app.debug:
        mail_handler = SMTPHandler(
            mailhost=('mail.example.com', 587),
            fromaddr='no-reply@example.com',
            toaddrs=[example@gmail.com],
            subject='Microblog Failure',
            credentials=('no-reply@example.com', 'password'),
            secure=()
        )

        mail_handler.setLevel(logging.ERROR)
        app.logger.addHandler(mail_handler)
from app import routes, models, errors
</code>```

SSL code, which doesn't work:

```<code>        context = ssl.create_default_context()
        mail_handler = SMTPHandler(
            mailhost=('mail.example.com', 465),
            fromaddr='no-reply@example.com',
            toaddrs=[example@gmail.com],
            subject='Microblog Failure',
            credentials=('no-reply@example.com', 'password'),
            secure=(context,)
        )
</code>```

The error:

```<code>Traceback (most recent call last):
  File "C:\Python\Python310\lib\smtplib.py", line 398, in getreply
    line = self.file.readline(_MAXLINE + 1)
  File "C:\Python\Python310\lib\socket.py", line 705, in readinto
    return self._sock.recv_into(b)
TimeoutError: timed out

During handling of the above exception, another exception occurred:

File "C:\Users\user\programacion\flask_mega_tutorial\lib\site-packages\flask\app.py", line 1741, in log_exception
    self.logger.error(
</code>```

I try too:
secure=context and timeout=60

Title: Use SMTPHandler using SSL

Body:
I'm using Flask. When an error occurs, I want be notified by email.
If a use TLS, it works, but if I use SSL, it doesn't.
What am I doing wrong?

import logging
import ssl
from logging.handlers import SMTPHandler

if not app.debug:
        mail_handler = SMTPHandler(
            mailhost=('mail.example.com', 587),
            fromaddr='no-reply@example.com',
            toaddrs=[example@gmail.com],
            subject='Microblog Failure',
            credentials=('no-reply@example.com', 'password'),
            secure=()
        )

        mail_handler.setLevel(logging.ERROR)
        app.logger.addHandler(mail_handler)
from app import routes, models, errors

SSL code, which doesn't work:

        context = ssl.create_default_context()
        mail_handler = SMTPHandler(
            mailhost=('mail.example.com', 465),
            fromaddr='no-reply@example.com',
            toaddrs=[example@gmail.com],
            subject='Microblog Failure',
            credentials=('no-reply@example.com', 'password'),
            secure=(context,)
        )

The error:

Traceback (most recent call last):
  File "C:\Python\Python310\lib\smtplib.py", line 398, in getreply
    line = self.file.readline(_MAXLINE + 1)
  File "C:\Python\Python310\lib\socket.py", line 705, in readinto
    return self._sock.recv_into(b)
TimeoutError: timed out

During handling of the above exception, another exception occurred:

File "C:\Users\user\programacion\flask_mega_tutorial\lib\site-packages\flask\app.py", line 1741, in log_exception
    self.logger.error(

I try too:
secure=context and timeout=60


问:
Yarn start returns error when executed in a service (Linux Server)
I need to run in the background a web app programmed in react and node which is hosted on a linux server. To do this I have created a service in

/etc/systemd/system

that does the following:

```<code>Description=Load React-Node Service.
[Service]
ExecStart=/usr/bin/yarn startLinux
WorkingDirectory=/home/developer/projectFolder/
[Install]
WantedBy=multi-user.target
</code>```

But when I run it with systemctl start webapp.service I get the following error:

On the other hand if I run it with yarn start directly from ssh it works, but I need to run it through a service so I don't have to have the terminal open. The yarn start and yarn startLinux commands do the following:

```<code>"start": "cross-env NODE_ENV=development concurrently --kill-others-on-fail \"yarn server\" \"yarn client\"",
"startLinux": "cross-env NODE_ENV=development concurrently --kill-others-on-fail \"yarn server\" \"yarn clientLinux\"",
"client": "cd frontend && yarn start",
"clientLinux": "cd frontend && yarn startLinux",
"server": "nodemon --exec babel-node src/server.js"
</code>```

Do you know what could be the problem?

Thanks!

Body:
I need to run in the background a web app programmed in react and node which is hosted on a linux server. To do this I have created a service in

/etc/systemd/system

that does the following:

Description=Load React-Node Service.
[Service]
ExecStart=/usr/bin/yarn startLinux
WorkingDirectory=/home/developer/projectFolder/
[Install]
WantedBy=multi-user.target

But when I run it with systemctl start webapp.service I get the following error:

On the other hand if I run it with yarn start directly from ssh it works, but I need to run it through a service so I don't have to have the terminal open. The yarn start and yarn startLinux commands do the following:

"start": "cross-env NODE_ENV=development concurrently --kill-others-on-fail \"yarn server\" \"yarn client\"",
"startLinux": "cross-env NODE_ENV=development concurrently --kill-others-on-fail \"yarn server\" \"yarn clientLinux\"",
"client": "cd frontend && yarn start",
"clientLinux": "cd frontend && yarn startLinux",
"server": "nodemon --exec babel-node src/server.js"

Do you know what could be the problem?

Thanks!


问:
The error handler of Future.catchError must return a value of the future's type
I'm stuck with a problem that app registration via friebase doesn't work, app can't write data to mysql, I get error

"invalid argument(s) (onError): The error handler of Future.catchError must return a value of the future's type"

Register

```<code>class DriverRegisterScreen extends StatefulWidget {
  bool socialLogin;
  String? userName;
  bool isOtp;
  String? countryCode;

  DriverRegisterScreen({this.socialLogin = false, this.userName, this.isOtp = false, this.countryCode});

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

class DriverRegisterScreenState extends State<DriverRegisterScreen> {
  AuthServices authService = AuthServices();

  List<GlobalKey<FormState>> formKeys = [
    GlobalKey<FormState>(),
    GlobalKey<FormState>(),
    GlobalKey<FormState>(),
    GlobalKey<FormState>(),
    GlobalKey<FormState>(),
    GlobalKey<FormState>(),
    GlobalKey<FormState>(),
    GlobalKey<FormState>(),
  ];
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();

  TextEditingController firstController = TextEditingController();
  TextEditingController lastNameController = TextEditingController();
  TextEditingController emailController = TextEditingController();
  TextEditingController userNameController = TextEditingController();
  TextEditingController phoneController = TextEditingController();
  TextEditingController passController = TextEditingController();
  TextEditingController carModelController = TextEditingController();
  TextEditingController carProductionController = TextEditingController();
  TextEditingController carPlateController = TextEditingController();
  TextEditingController carColorController = TextEditingController();

  FocusNode firstNameFocus = FocusNode();
  FocusNode lastNameFocus = FocusNode();
  FocusNode userNameFocus = FocusNode();
  FocusNode emailFocus = FocusNode();
  FocusNode phoneFocus = FocusNode();
  FocusNode passFocus = FocusNode();

  bool mIsCheck = false;
  String countryCode = '+66';

  int currentIndex = 0;

  List<ServiceList> listServices = [];

  List<String> gender = [MALE, FEMALE, OTHER];
  String selectGender = MALE;

  int vehicleTypeIndex = 0;

  XFile? imageProfile;
  int radioValue = -1;

  @override
  void initState() {
    super.initState();
    init();
  }

  void init() async {
    await getServices().then((value) {
      listServices.addAll(value.data!);
      vehicleTypeIndex = listServices[0].id!;
      setState(() {});
    }).catchError((error) {
      log(error.toString());
    });
  }

  Future<void> register() async {
    hideKeyboard(context);
    if (formKey.currentState!.validate()) {
      formKey.currentState!.save();
      appStore.setLoading(true);

      authService
          .signUpWithEmailPassword(
        context,
        name: firstController.text.trim(),
        mobileNumber: widget.socialLogin ? '$countryCode ${widget.userName}' : '$countryCode ${phoneController.text.trim()}',
        email: emailController.text.trim(),
        fName: firstController.text.trim(),
        lName: lastNameController.text.trim(),
        userName: widget.socialLogin ? widget.userName : userNameController.text.trim(),
        password: widget.socialLogin ? widget.userName : passController.text.trim(),
        userType: 'driver',
        socialLoginName: widget.socialLogin,
        isOtp: widget.isOtp,
        serviceId: listServices[vehicleTypeIndex].id,
        gender: selectGender,
        userDetail: UserDetail(
          car_model: carModelController.text.trim(),
          car_color: carColorController.text.trim(),
          car_plate_number: carPlateController.text.trim(),
          car_production_year: carProductionController.text.trim(),
        ),
      )
          .then((res) async {
        appStore.setLoading(false);

        //
      }).catchError((a) {
        appStore.setLoading(false);
        toast(a.toString());
      });
    }
  }

  @override
  void setState(fn) {
    if (mounted) super.setState(fn);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(language.signUp, style: boldTextStyle(color: Colors.white)),
      ),
      body: Stack(
        children: [
          Form(
            key: formKey,
            child: Stepper(
              currentStep: currentIndex,
              onStepCancel: () {
                if (currentIndex > 0) {
                  currentIndex--;
                  setState(() {});
                }
              },
              onStepContinue: () {
                if (formKeys[currentIndex].currentState!.validate()) {
                  if (currentIndex == 1 && listServices.isEmpty) {
                    return toast(language.pleaseSelectService);
                  } else if (currentIndex <= 5) {
                    currentIndex++;
                    setState(() {});
                  } else {
                    register();
                  }
                }
              },
              onStepTapped: (int index) {
                currentIndex = index;
                setState(() {});
              },
              steps: [
                Step(
                  isActive: currentIndex <= 0,
                  state: currentIndex <= 0 ? StepState.disabled : StepState.complete,
                  title: Text(language.userDetail, style: boldTextStyle()),
                  content: Form(
                    key: formKeys[0],
                    child: Column(
                      children: [
                        SizedBox(height: 8),
                        Row(
                          children: [
                            Expanded(
                              child: AppTextField(
                                textFieldType: TextFieldType.NAME,
                                controller: firstController,
                                focus: firstNameFocus,
                                nextFocus: lastNameFocus,
                                errorThisFieldRequired: language.thisFieldRequired,
                                decoration: inputDecoration(context, label: language.firstName),
                              ),
                            ),
                            SizedBox(width: 16),
                            Expanded(
                              child: AppTextField(
                                textFieldType: TextFieldType.NAME,
                                controller: lastNameController,
                                focus: lastNameFocus,
                                nextFocus: emailFocus,
                                errorThisFieldRequired: language.thisFieldRequired,
                                decoration: inputDecoration(context, label: language.lastName),
                              ),
                            ),
                          ],
                        ),
                        SizedBox(height: 16),
                        Row(
                          children: [
                            Expanded(
                              child: AppTextField(
                                textFieldType: TextFieldType.EMAIL,
                                focus: emailFocus,
                                controller: emailController,
                                nextFocus: userNameFocus,
                                errorThisFieldRequired: language.thisFieldRequired,
                                decoration: inputDecoration(context, label: language.email),
                              ),
                            ),
                            SizedBox(width: 16),
                            if (widget.socialLogin != true)
                              Expanded(
                                child: AppTextField(
                                  textFieldType: TextFieldType.USERNAME,
                                  focus: userNameFocus,
                                  controller: userNameController,
                                  nextFocus: phoneFocus,
                                  errorThisFieldRequired: language.thisFieldRequired,
                                  decoration: inputDecoration(context, label: language.userName),
                                ),
                              ),
                          ],
                        ),
                        if (widget.socialLogin != true) SizedBox(height: 16),
                        if (widget.socialLogin != true)
                          AppTextField(
                            controller: phoneController,
                            textFieldType: TextFieldType.PHONE,
                            focus: phoneFocus,
                            nextFocus: passFocus,
                            decoration: inputDecoration(
                              context,
                              label: language.phoneNumber,
                              prefixIcon: IntrinsicHeight(
                                child: Row(
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    CountryCodePicker(
                                      padding: EdgeInsets.zero,
                                      initialSelection: countryCode,
                                      showCountryOnly: false,
                                      dialogSize: Size(MediaQuery.of(context).size.width - 60, MediaQuery.of(context).size.height * 0.6),
                                      showFlag: true,
                                      showFlagDialog: true,
                                      showOnlyCountryWhenClosed: false,
                                      alignLeft: false,
                                      enabled: false,
                                      textStyle: primaryTextStyle(),
                                      dialogBackgroundColor: Theme.of(context).cardColor,
                                      barrierColor: Colors.black12,
                                      dialogTextStyle: primaryTextStyle(),
                                      searchDecoration: InputDecoration(
                                        iconColor: Theme.of(context).dividerColor,
                                        enabledBorder: UnderlineInputBorder(borderSide: BorderSide(color: Theme.of(context).dividerColor)),
                                        focusedBorder: UnderlineInputBorder(borderSide: BorderSide(color: primaryColor)),
                                      ),
                                      searchStyle: primaryTextStyle(),
                                      onInit: (c) {
                                        countryCode = c!.dialCode!;
                                      },
                                      onChanged: (c) {
                                        countryCode = c.dialCode!;
                                      },
                                    ),
                                    VerticalDivider(color: Colors.grey.withOpacity(0.5)),
                                  ],
                                ),
                              ),
                            ),
                            validator: (value) {
                              if (value!.trim().isEmpty) return language.thisFieldRequired;
                              if (value.trim().length < 10 || value.trim().length > 14) return language.contactLength;
                              return null;
                            },
                          ),
                        if (widget.socialLogin != true) SizedBox(height: 16),
                        if (widget.socialLogin != true)
                          AppTextField(
                            controller: passController,
                            focus: passFocus,
                            autoFocus: false,
                            textFieldType: TextFieldType.PASSWORD,
                            errorThisFieldRequired: language.thisFieldRequired,
                            decoration: inputDecoration(context, label: language.password),
                          ),
                      ],
                    ),
                  ),
                ),
                Step(
                  isActive: currentIndex <= 1,
                  state: currentIndex <= 1 ? StepState.disabled : StepState.complete,
                  title: Text(language.selectService, style: boldTextStyle()),
                  content: Form(
                    key: formKeys[1],
                    child: listServices.isNotEmpty
                        ? Column(
                            children: listServices.map((e) {
                              return inkWellWidget(
                                onTap: () {
                                  vehicleTypeIndex = listServices.indexOf(e);
                                  setState(() {});
                                  print(listServices[vehicleTypeIndex].id);
                                },
                                child: Container(
                                  margin: EdgeInsets.only(
                                    bottom: 8,
                                  ),
                                  padding: EdgeInsets.only(left: 16, right: 8, top: 4, bottom: 4),
                                  decoration: BoxDecoration(
                                    border: Border.all(color: vehicleTypeIndex == listServices.indexOf(e) ? Colors.green : primaryColor.withOpacity(0.5)),
                                    borderRadius: BorderRadius.circular(defaultRadius),
                                  ),
                                  child: Row(
                                    children: [
                                      commonCachedNetworkImage(e.serviceImage, fit: BoxFit.contain, height: 50, width: 50),
                                      SizedBox(width: 16),
                                      Expanded(
                                        child: Text(e.name.validate(), style: boldTextStyle()),
                                      ),
                                      Visibility(
                                        visible: vehicleTypeIndex == listServices.indexOf(e),
                                        child: Icon(Icons.check_circle_outline, color: Colors.green),
                                      )
                                    ],
                                  ),
                                ),
                              );
                            }).toList(),
                          )
                        : emptyWidget(),
                  ),
                ),
                Step(
                  isActive: currentIndex <= 2,
                  state: currentIndex <= 2 ? StepState.disabled : StepState.complete,
                  title: Text(language.carModel, style: boldTextStyle()),
                  content: Form(
                    key: formKeys[2],
                    child: AppTextField(textFieldType: TextFieldType.NAME, controller: carModelController),
                  ),
                ),
                Step(
                  isActive: currentIndex <= 3,
                  state: currentIndex <= 3 ? StepState.indexed : StepState.complete,
                  title: Text(language.carProductionYear, style: boldTextStyle()),
                  content: Form(
                    key: formKeys[3],
                    child: AppTextField(textFieldType: TextFieldType.PHONE, controller: carProductionController),
                  ),
                ),
                Step(
                  isActive: currentIndex <= 4,
                  state: currentIndex <= 4 ? StepState.disabled : StepState.complete,
                  title: Text(language.carPlateNumber, style: boldTextStyle()),
                  content: Form(
                    key: formKeys[4],
                    child: AppTextField(textFieldType: TextFieldType.NAME, controller: carPlateController),
                  ),
                ),
                Step(
                  isActive: currentIndex <= 5,
                  state: currentIndex <= 5 ? StepState.disabled : StepState.complete,
                  title: Text(language.carColor, style: boldTextStyle()),
                  content: Form(
                    key: formKeys[5],
                    child: AppTextField(textFieldType: TextFieldType.NAME, controller: carColorController),
                  ),
                ),
                Step(
                  isActive: currentIndex <= 6,
                  state: currentIndex <= 6 ? StepState.disabled : StepState.complete,
                  title: Text(language.selectGender, style: boldTextStyle()),
                  content: Form(
                    key: formKeys[6],
                    child: Row(
                      children: gender.map((e) {
                        return Row(
                          children: [
                            Radio(
                              activeColor: primaryColor,
                              value: e,
                              groupValue: selectGender,
                              onChanged: (String? val) {
                                selectGender = val!;
                                setState(() {});
                              },
                            ),
                            Text(changeGender(e), style: primaryTextStyle())
                          ],
                        );
                      }).toList(),
                    ),
                  ),
                ),
              ],
            ),
          ),
          Observer(builder: (context) {
            return Visibility(
              visible: appStore.isLoading,
              child: loaderWidget(),
            );
          })
        ],
      ),
    );
  }
}
</code>```

AuthServic

```<code>final FirebaseAuth _auth = FirebaseAuth.instance;

class AuthServices {
  Future<void> updateUserData(UserData user) async {
    userService.updateDocument({
      'player_id': sharedPref.getString(PLAYER_ID),
      'updatedAt': Timestamp.now(),
    }, user.uid);
  }

  Future<void> signUpWithEmailPassword(
    context, {
    String? name,
    String? email,
    String? password,
    String? mobileNumber,
    String? fName,
    String? lName,
    String? userName,
    bool socialLoginName = false,
    String? userType,
    String? uID,
    bool isOtp = false,
    UserDetail? userDetail,
    int? serviceId,
    String? gender,
  }) async {
    UserCredential? userCredential = await _auth.createUserWithEmailAndPassword(email: email!, password: password!);
    if (userCredential.user != null) {
      User currentUser = userCredential.user!;

      UserData userModel = UserData();

      /// Create user
      userModel.uid = currentUser.uid;
      userModel.email = currentUser.email;
      userModel.contact_number = mobileNumber;
      userModel.username = userName;
      userModel.user_type = userType;
      userModel.display_name = fName! + " " + lName!;
      userModel.first_name = fName;
      userModel.last_name = lName;
      userModel.created_at = Timestamp.now().toDate().toString();
      userModel.updated_at = Timestamp.now().toDate().toString();
      userModel.player_id = sharedPref.getString(PLAYER_ID);

      await userService.addDocumentWithCustomId(currentUser.uid, userModel.toJson()).then((value) async {
        Map req = {
          'first_name': fName,
          'last_name': lName,
          'username': userName,
          'email': email,
          "user_type": "driver",
          "contact_number": mobileNumber,
          'password': password,
          "player_id": sharedPref.getString(PLAYER_ID).validate(),
          "uid": userModel.uid,
          "gender": gender,
          if (socialLoginName) 'login_type': isOtp ? 'mobile' : 'google',
          "user_detail": {
            'car_model': userDetail!.car_model,
            'car_color': userDetail.car_color,
            'car_plate_number': userDetail.car_plate_number,
            'car_production_year': userDetail.car_production_year,
          },
          'service_id': serviceId,
        };

        log(req);
        await signUpApi(req).then((value) {
          if (sharedPref.getInt(IS_Verified_Driver) == 1) {
            launchScreen(context, DriverDashboardScreen());
          } else {
            launchScreen(context, VerifyDeliveryPersonScreen(isShow: true), pageRouteAnimation: PageRouteAnimation.Slide, isNewTask: true);
          }
        }).catchError((error) {
          toast(error.toString());
          log(error.toString());
        });
        appStore.setLoading(false);
      }).catchError((a) {
        appStore.setLoading(false);
        toast(a.toString());
      });
    } else {
      throw "errorSomethingWentWrong";
    }
  }

  Future<void> signInWithEmailPassword(context, {required String email, required String password}) async {
    await _auth.signInWithEmailAndPassword(email: email, password: password).then((value) async {
      appStore.setLoading(true);
      final User user = value.user!;
      UserData userModel = await userService.getUser(email: user.email);
      await updateUserData(userModel);

      appStore.setLoading(true);
      //Login Details to SharedPreferences
      sharedPref.setString(UID, userModel.uid.validate());
      sharedPref.setString(USER_EMAIL, userModel.email.validate());
      sharedPref.setBool(IS_LOGGED_IN, true);

      //Login Details to AppStore
      appStore.setUserEmail(userModel.email.validate());
      appStore.setUId(userModel.uid.validate());

      //
    }).catchError((a) {
      toast(a.toString());
      log(a.toString());
    });
  }

  Future<void> loginFromFirebaseUser(User currentUser, {LoginResponse? loginDetail, String? fullName, String? fName, String? lName}) async {
    UserData userModel = UserData();

    if (await userService.isUserExist(loginDetail!.data!.email)) {
      ///Return user data
      await userService.userByEmail(loginDetail.data!.email).then((user) async {
        userModel = user;
        appStore.setUserEmail(userModel.email.validate());
        appStore.setUId(userModel.uid.validate());

        await updateUserData(user);
      }).catchError((a) {
        log(a);
        throw a;
      });
    } else {
      /// Create user
      userModel.uid = currentUser.uid.validate();
      userModel.id = loginDetail.data!.id;
      userModel.email = loginDetail.data!.email.validate();
      userModel.username = loginDetail.data!.username.validate();
      userModel.contact_number = loginDetail.data!.contact_number.validate();
      userModel.username = loginDetail.data!.username.validate();
      userModel.email = loginDetail.data!.email.validate();

      if (Platform.isIOS) {
        userModel.username = fullName;
      } else {
        userModel.username = loginDetail.data!.username.validate();
      }

      userModel.contact_number = loginDetail.data!.contact_number.validate();
      userModel.profile_image = loginDetail.data!.profile_image.validate();
      userModel.player_id = sharedPref.getString(PLAYER_ID);

      sharedPref.setString(UID, currentUser.uid.validate());
      log(sharedPref.getString(UID)!);
      sharedPref.setString(USER_EMAIL, userModel.email.validate());
      sharedPref.setBool(IS_LOGGED_IN, true);

      log(userModel.toJson());

      await userService.addDocumentWithCustomId(currentUser.uid, userModel.toJson()).then((value) {
        //
      }).catchError((a) {
        throw a;
      });
    }
  }

  Future<void> loginWithOTP(BuildContext context, String phoneNumber) async {
    return await _auth.verifyPhoneNumber(
      phoneNumber: phoneNumber,
      verificationCompleted: (PhoneAuthCredential credential) async {},
      verificationFailed: (FirebaseAuthException a) {
        if (a.code == 'invalid-phone-number') {
          toast('The provided phone number is not valid.');
          throw 'The provided phone number is not valid.';
        } else {
          toast(a.toString());
          throw a.toString();
        }
      },
      codeSent: (String verificationId, int? resendToken) async {
        Navigator.pop(context);
        appStore.setLoading(false);
        await showDialog(
          context: context,
          builder: (context) => AlertDialog(content: OTPDialog(verificationId: verificationId, isCodeSent: true, phoneNumber: phoneNumber)),
          barrierDismissible: false,
        );
      },
      codeAutoRetrievalTimeout: (String verificationId) {
        //
      },
    );
  }

  Future deleteUserFirebase() async {
    if (FirebaseAuth.instance.currentUser != null) {
      FirebaseAuth.instance.currentUser!.delete();
      await FirebaseAuth.instance.signOut();
    }
  }
}
</code>```

Cloud Firestore

```<code>rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
 match /{document=**} {
  allow read, write: if request.auth != null;
  }
 }
}
</code>```

The other side of the app uses the same structure but does not register through it.

"invalid argument(s) (onError): The error handler of Future.catchError must return a value of the future's type"

please guide me

Body:
I'm stuck with a problem that app registration via friebase doesn't work, app can't write data to mysql, I get error

"invalid argument(s) (onError): The error handler of Future.catchError must return a value of the future's type"

Register

class DriverRegisterScreen extends StatefulWidget {
  bool socialLogin;
  String? userName;
  bool isOtp;
  String? countryCode;

  DriverRegisterScreen({this.socialLogin = false, this.userName, this.isOtp = false, this.countryCode});

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

class DriverRegisterScreenState extends State<DriverRegisterScreen> {
  AuthServices authService = AuthServices();

  List<GlobalKey<FormState>> formKeys = [
    GlobalKey<FormState>(),
    GlobalKey<FormState>(),
    GlobalKey<FormState>(),
    GlobalKey<FormState>(),
    GlobalKey<FormState>(),
    GlobalKey<FormState>(),
    GlobalKey<FormState>(),
    GlobalKey<FormState>(),
  ];
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();

  TextEditingController firstController = TextEditingController();
  TextEditingController lastNameController = TextEditingController();
  TextEditingController emailController = TextEditingController();
  TextEditingController userNameController = TextEditingController();
  TextEditingController phoneController = TextEditingController();
  TextEditingController passController = TextEditingController();
  TextEditingController carModelController = TextEditingController();
  TextEditingController carProductionController = TextEditingController();
  TextEditingController carPlateController = TextEditingController();
  TextEditingController carColorController = TextEditingController();

  FocusNode firstNameFocus = FocusNode();
  FocusNode lastNameFocus = FocusNode();
  FocusNode userNameFocus = FocusNode();
  FocusNode emailFocus = FocusNode();
  FocusNode phoneFocus = FocusNode();
  FocusNode passFocus = FocusNode();

  bool mIsCheck = false;
  String countryCode = '+66';

  int currentIndex = 0;

  List<ServiceList> listServices = [];

  List<String> gender = [MALE, FEMALE, OTHER];
  String selectGender = MALE;

  int vehicleTypeIndex = 0;

  XFile? imageProfile;
  int radioValue = -1;

  @override
  void initState() {
    super.initState();
    init();
  }

  void init() async {
    await getServices().then((value) {
      listServices.addAll(value.data!);
      vehicleTypeIndex = listServices[0].id!;
      setState(() {});
    }).catchError((error) {
      log(error.toString());
    });
  }

  Future<void> register() async {
    hideKeyboard(context);
    if (formKey.currentState!.validate()) {
      formKey.currentState!.save();
      appStore.setLoading(true);

      authService
          .signUpWithEmailPassword(
        context,
        name: firstController.text.trim(),
        mobileNumber: widget.socialLogin ? '$countryCode ${widget.userName}' : '$countryCode ${phoneController.text.trim()}',
        email: emailController.text.trim(),
        fName: firstController.text.trim(),
        lName: lastNameController.text.trim(),
        userName: widget.socialLogin ? widget.userName : userNameController.text.trim(),
        password: widget.socialLogin ? widget.userName : passController.text.trim(),
        userType: 'driver',
        socialLoginName: widget.socialLogin,
        isOtp: widget.isOtp,
        serviceId: listServices[vehicleTypeIndex].id,
        gender: selectGender,
        userDetail: UserDetail(
          car_model: carModelController.text.trim(),
          car_color: carColorController.text.trim(),
          car_plate_number: carPlateController.text.trim(),
          car_production_year: carProductionController.text.trim(),
        ),
      )
          .then((res) async {
        appStore.setLoading(false);

        //
      }).catchError((a) {
        appStore.setLoading(false);
        toast(a.toString());
      });
    }
  }

  @override
  void setState(fn) {
    if (mounted) super.setState(fn);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(language.signUp, style: boldTextStyle(color: Colors.white)),
      ),
      body: Stack(
        children: [
          Form(
            key: formKey,
            child: Stepper(
              currentStep: currentIndex,
              onStepCancel: () {
                if (currentIndex > 0) {
                  currentIndex--;
                  setState(() {});
                }
              },
              onStepContinue: () {
                if (formKeys[currentIndex].currentState!.validate()) {
                  if (currentIndex == 1 && listServices.isEmpty) {
                    return toast(language.pleaseSelectService);
                  } else if (currentIndex <= 5) {
                    currentIndex++;
                    setState(() {});
                  } else {
                    register();
                  }
                }
              },
              onStepTapped: (int index) {
                currentIndex = index;
                setState(() {});
              },
              steps: [
                Step(
                  isActive: currentIndex <= 0,
                  state: currentIndex <= 0 ? StepState.disabled : StepState.complete,
                  title: Text(language.userDetail, style: boldTextStyle()),
                  content: Form(
                    key: formKeys[0],
                    child: Column(
                      children: [
                        SizedBox(height: 8),
                        Row(
                          children: [
                            Expanded(
                              child: AppTextField(
                                textFieldType: TextFieldType.NAME,
                                controller: firstController,
                                focus: firstNameFocus,
                                nextFocus: lastNameFocus,
                                errorThisFieldRequired: language.thisFieldRequired,
                                decoration: inputDecoration(context, label: language.firstName),
                              ),
                            ),
                            SizedBox(width: 16),
                            Expanded(
                              child: AppTextField(
                                textFieldType: TextFieldType.NAME,
                                controller: lastNameController,
                                focus: lastNameFocus,
                                nextFocus: emailFocus,
                                errorThisFieldRequired: language.thisFieldRequired,
                                decoration: inputDecoration(context, label: language.lastName),
                              ),
                            ),
                          ],
                        ),
                        SizedBox(height: 16),
                        Row(
                          children: [
                            Expanded(
                              child: AppTextField(
                                textFieldType: TextFieldType.EMAIL,
                                focus: emailFocus,
                                controller: emailController,
                                nextFocus: userNameFocus,
                                errorThisFieldRequired: language.thisFieldRequired,
                                decoration: inputDecoration(context, label: language.email),
                              ),
                            ),
                            SizedBox(width: 16),
                            if (widget.socialLogin != true)
                              Expanded(
                                child: AppTextField(
                                  textFieldType: TextFieldType.USERNAME,
                                  focus: userNameFocus,
                                  controller: userNameController,
                                  nextFocus: phoneFocus,
                                  errorThisFieldRequired: language.thisFieldRequired,
                                  decoration: inputDecoration(context, label: language.userName),
                                ),
                              ),
                          ],
                        ),
                        if (widget.socialLogin != true) SizedBox(height: 16),
                        if (widget.socialLogin != true)
                          AppTextField(
                            controller: phoneController,
                            textFieldType: TextFieldType.PHONE,
                            focus: phoneFocus,
                            nextFocus: passFocus,
                            decoration: inputDecoration(
                              context,
                              label: language.phoneNumber,
                              prefixIcon: IntrinsicHeight(
                                child: Row(
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    CountryCodePicker(
                                      padding: EdgeInsets.zero,
                                      initialSelection: countryCode,
                                      showCountryOnly: false,
                                      dialogSize: Size(MediaQuery.of(context).size.width - 60, MediaQuery.of(context).size.height * 0.6),
                                      showFlag: true,
                                      showFlagDialog: true,
                                      showOnlyCountryWhenClosed: false,
                                      alignLeft: false,
                                      enabled: false,
                                      textStyle: primaryTextStyle(),
                                      dialogBackgroundColor: Theme.of(context).cardColor,
                                      barrierColor: Colors.black12,
                                      dialogTextStyle: primaryTextStyle(),
                                      searchDecoration: InputDecoration(
                                        iconColor: Theme.of(context).dividerColor,
                                        enabledBorder: UnderlineInputBorder(borderSide: BorderSide(color: Theme.of(context).dividerColor)),
                                        focusedBorder: UnderlineInputBorder(borderSide: BorderSide(color: primaryColor)),
                                      ),
                                      searchStyle: primaryTextStyle(),
                                      onInit: (c) {
                                        countryCode = c!.dialCode!;
                                      },
                                      onChanged: (c) {
                                        countryCode = c.dialCode!;
                                      },
                                    ),
                                    VerticalDivider(color: Colors.grey.withOpacity(0.5)),
                                  ],
                                ),
                              ),
                            ),
                            validator: (value) {
                              if (value!.trim().isEmpty) return language.thisFieldRequired;
                              if (value.trim().length < 10 || value.trim().length > 14) return language.contactLength;
                              return null;
                            },
                          ),
                        if (widget.socialLogin != true) SizedBox(height: 16),
                        if (widget.socialLogin != true)
                          AppTextField(
                            controller: passController,
                            focus: passFocus,
                            autoFocus: false,
                            textFieldType: TextFieldType.PASSWORD,
                            errorThisFieldRequired: language.thisFieldRequired,
                            decoration: inputDecoration(context, label: language.password),
                          ),
                      ],
                    ),
                  ),
                ),
                Step(
                  isActive: currentIndex <= 1,
                  state: currentIndex <= 1 ? StepState.disabled : StepState.complete,
                  title: Text(language.selectService, style: boldTextStyle()),
                  content: Form(
                    key: formKeys[1],
                    child: listServices.isNotEmpty
                        ? Column(
                            children: listServices.map((e) {
                              return inkWellWidget(
                                onTap: () {
                                  vehicleTypeIndex = listServices.indexOf(e);
                                  setState(() {});
                                  print(listServices[vehicleTypeIndex].id);
                                },
                                child: Container(
                                  margin: EdgeInsets.only(
                                    bottom: 8,
                                  ),
                                  padding: EdgeInsets.only(left: 16, right: 8, top: 4, bottom: 4),
                                  decoration: BoxDecoration(
                                    border: Border.all(color: vehicleTypeIndex == listServices.indexOf(e) ? Colors.green : primaryColor.withOpacity(0.5)),
                                    borderRadius: BorderRadius.circular(defaultRadius),
                                  ),
                                  child: Row(
                                    children: [
                                      commonCachedNetworkImage(e.serviceImage, fit: BoxFit.contain, height: 50, width: 50),
                                      SizedBox(width: 16),
                                      Expanded(
                                        child: Text(e.name.validate(), style: boldTextStyle()),
                                      ),
                                      Visibility(
                                        visible: vehicleTypeIndex == listServices.indexOf(e),
                                        child: Icon(Icons.check_circle_outline, color: Colors.green),
                                      )
                                    ],
                                  ),
                                ),
                              );
                            }).toList(),
                          )
                        : emptyWidget(),
                  ),
                ),
                Step(
                  isActive: currentIndex <= 2,
                  state: currentIndex <= 2 ? StepState.disabled : StepState.complete,
                  title: Text(language.carModel, style: boldTextStyle()),
                  content: Form(
                    key: formKeys[2],
                    child: AppTextField(textFieldType: TextFieldType.NAME, controller: carModelController),
                  ),
                ),
                Step(
                  isActive: currentIndex <= 3,
                  state: currentIndex <= 3 ? StepState.indexed : StepState.complete,
                  title: Text(language.carProductionYear, style: boldTextStyle()),
                  content: Form(
                    key: formKeys[3],
                    child: AppTextField(textFieldType: TextFieldType.PHONE, controller: carProductionController),
                  ),
                ),
                Step(
                  isActive: currentIndex <= 4,
                  state: currentIndex <= 4 ? StepState.disabled : StepState.complete,
                  title: Text(language.carPlateNumber, style: boldTextStyle()),
                  content: Form(
                    key: formKeys[4],
                    child: AppTextField(textFieldType: TextFieldType.NAME, controller: carPlateController),
                  ),
                ),
                Step(
                  isActive: currentIndex <= 5,
                  state: currentIndex <= 5 ? StepState.disabled : StepState.complete,
                  title: Text(language.carColor, style: boldTextStyle()),
                  content: Form(
                    key: formKeys[5],
                    child: AppTextField(textFieldType: TextFieldType.NAME, controller: carColorController),
                  ),
                ),
                Step(
                  isActive: currentIndex <= 6,
                  state: currentIndex <= 6 ? StepState.disabled : StepState.complete,
                  title: Text(language.selectGender, style: boldTextStyle()),
                  content: Form(
                    key: formKeys[6],
                    child: Row(
                      children: gender.map((e) {
                        return Row(
                          children: [
                            Radio(
                              activeColor: primaryColor,
                              value: e,
                              groupValue: selectGender,
                              onChanged: (String? val) {
                                selectGender = val!;
                                setState(() {});
                              },
                            ),
                            Text(changeGender(e), style: primaryTextStyle())
                          ],
                        );
                      }).toList(),
                    ),
                  ),
                ),
              ],
            ),
          ),
          Observer(builder: (context) {
            return Visibility(
              visible: appStore.isLoading,
              child: loaderWidget(),
            );
          })
        ],
      ),
    );
  }
}

AuthServic

final FirebaseAuth _auth = FirebaseAuth.instance;

class AuthServices {
  Future<void> updateUserData(UserData user) async {
    userService.updateDocument({
      'player_id': sharedPref.getString(PLAYER_ID),
      'updatedAt': Timestamp.now(),
    }, user.uid);
  }

  Future<void> signUpWithEmailPassword(
    context, {
    String? name,
    String? email,
    String? password,
    String? mobileNumber,
    String? fName,
    String? lName,
    String? userName,
    bool socialLoginName = false,
    String? userType,
    String? uID,
    bool isOtp = false,
    UserDetail? userDetail,
    int? serviceId,
    String? gender,
  }) async {
    UserCredential? userCredential = await _auth.createUserWithEmailAndPassword(email: email!, password: password!);
    if (userCredential.user != null) {
      User currentUser = userCredential.user!;

      UserData userModel = UserData();

      /// Create user
      userModel.uid = currentUser.uid;
      userModel.email = currentUser.email;
      userModel.contact_number = mobileNumber;
      userModel.username = userName;
      userModel.user_type = userType;
      userModel.display_name = fName! + " " + lName!;
      userModel.first_name = fName;
      userModel.last_name = lName;
      userModel.created_at = Timestamp.now().toDate().toString();
      userModel.updated_at = Timestamp.now().toDate().toString();
      userModel.player_id = sharedPref.getString(PLAYER_ID);

      await userService.addDocumentWithCustomId(currentUser.uid, userModel.toJson()).then((value) async {
        Map req = {
          'first_name': fName,
          'last_name': lName,
          'username': userName,
          'email': email,
          "user_type": "driver",
          "contact_number": mobileNumber,
          'password': password,
          "player_id": sharedPref.getString(PLAYER_ID).validate(),
          "uid": userModel.uid,
          "gender": gender,
          if (socialLoginName) 'login_type': isOtp ? 'mobile' : 'google',
          "user_detail": {
            'car_model': userDetail!.car_model,
            'car_color': userDetail.car_color,
            'car_plate_number': userDetail.car_plate_number,
            'car_production_year': userDetail.car_production_year,
          },
          'service_id': serviceId,
        };

        log(req);
        await signUpApi(req).then((value) {
          if (sharedPref.getInt(IS_Verified_Driver) == 1) {
            launchScreen(context, DriverDashboardScreen());
          } else {
            launchScreen(context, VerifyDeliveryPersonScreen(isShow: true), pageRouteAnimation: PageRouteAnimation.Slide, isNewTask: true);
          }
        }).catchError((error) {
          toast(error.toString());
          log(error.toString());
        });
        appStore.setLoading(false);
      }).catchError((a) {
        appStore.setLoading(false);
        toast(a.toString());
      });
    } else {
      throw "errorSomethingWentWrong";
    }
  }

  Future<void> signInWithEmailPassword(context, {required String email, required String password}) async {
    await _auth.signInWithEmailAndPassword(email: email, password: password).then((value) async {
      appStore.setLoading(true);
      final User user = value.user!;
      UserData userModel = await userService.getUser(email: user.email);
      await updateUserData(userModel);

      appStore.setLoading(true);
      //Login Details to SharedPreferences
      sharedPref.setString(UID, userModel.uid.validate());
      sharedPref.setString(USER_EMAIL, userModel.email.validate());
      sharedPref.setBool(IS_LOGGED_IN, true);

      //Login Details to AppStore
      appStore.setUserEmail(userModel.email.validate());
      appStore.setUId(userModel.uid.validate());

      //
    }).catchError((a) {
      toast(a.toString());
      log(a.toString());
    });
  }

  Future<void> loginFromFirebaseUser(User currentUser, {LoginResponse? loginDetail, String? fullName, String? fName, String? lName}) async {
    UserData userModel = UserData();

    if (await userService.isUserExist(loginDetail!.data!.email)) {
      ///Return user data
      await userService.userByEmail(loginDetail.data!.email).then((user) async {
        userModel = user;
        appStore.setUserEmail(userModel.email.validate());
        appStore.setUId(userModel.uid.validate());

        await updateUserData(user);
      }).catchError((a) {
        log(a);
        throw a;
      });
    } else {
      /// Create user
      userModel.uid = currentUser.uid.validate();
      userModel.id = loginDetail.data!.id;
      userModel.email = loginDetail.data!.email.validate();
      userModel.username = loginDetail.data!.username.validate();
      userModel.contact_number = loginDetail.data!.contact_number.validate();
      userModel.username = loginDetail.data!.username.validate();
      userModel.email = loginDetail.data!.email.validate();

      if (Platform.isIOS) {
        userModel.username = fullName;
      } else {
        userModel.username = loginDetail.data!.username.validate();
      }

      userModel.contact_number = loginDetail.data!.contact_number.validate();
      userModel.profile_image = loginDetail.data!.profile_image.validate();
      userModel.player_id = sharedPref.getString(PLAYER_ID);

      sharedPref.setString(UID, currentUser.uid.validate());
      log(sharedPref.getString(UID)!);
      sharedPref.setString(USER_EMAIL, userModel.email.validate());
      sharedPref.setBool(IS_LOGGED_IN, true);

      log(userModel.toJson());

      await userService.addDocumentWithCustomId(currentUser.uid, userModel.toJson()).then((value) {
        //
      }).catchError((a) {
        throw a;
      });
    }
  }

  Future<void> loginWithOTP(BuildContext context, String phoneNumber) async {
    return await _auth.verifyPhoneNumber(
      phoneNumber: phoneNumber,
      verificationCompleted: (PhoneAuthCredential credential) async {},
      verificationFailed: (FirebaseAuthException a) {
        if (a.code == 'invalid-phone-number') {
          toast('The provided phone number is not valid.');
          throw 'The provided phone number is not valid.';
        } else {
          toast(a.toString());
          throw a.toString();
        }
      },
      codeSent: (String verificationId, int? resendToken) async {
        Navigator.pop(context);
        appStore.setLoading(false);
        await showDialog(
          context: context,
          builder: (context) => AlertDialog(content: OTPDialog(verificationId: verificationId, isCodeSent: true, phoneNumber: phoneNumber)),
          barrierDismissible: false,
        );
      },
      codeAutoRetrievalTimeout: (String verificationId) {
        //
      },
    );
  }

  Future deleteUserFirebase() async {
    if (FirebaseAuth.instance.currentUser != null) {
      FirebaseAuth.instance.currentUser!.delete();
      await FirebaseAuth.instance.signOut();
    }
  }
}

Cloud Firestore

rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
 match /{document=**} {
  allow read, write: if request.auth != null;
  }
 }
}

The other side of the app uses the same structure but does not register through it.

"invalid argument(s) (onError): The error handler of Future.catchError must return a value of the future's type"

please guide me


问:
Content not updating when changed through socket io request
I'm trying to change the content of the page through a socket io request, but the variable is changing, but the content of the page is staying the same

```<code><script>
  import { io } from "../src/lib/socketClient";

  var screen = "this";
  io.on("screenChange",(msg)=>{
    screen = msg.screen;
  });
</script>

<div>
  {#if screen == "this"}
    <h1>this</h1>
  {:else if screen == "that"}
    <h1>that</h1>
  {/if}
</div>
</code>```

I already checked the socket io server and the connection, the variable is changing but the content is still staying the same

Body:
I'm trying to change the content of the page through a socket io request, but the variable is changing, but the content of the page is staying the same

  {#if screen == "this"}

this

  {:else if screen == "that"}

that

  {/if}

I already checked the socket io server and the connection, the variable is changing but the content is still staying the same


问:
dotnet-core-uninstall doesn't see some versions
As I began to pickup a legacy project at work, I ran into some version collision issues with .net sdks and decided to uninstall all my .net sdks(start from scratch). Upon doing this I had 3 versions:

6.0.302

6.0.308

7.0.100

I used <Control Panel\All Control Panel Items\Programs and Features> to remove dotnet 6 and dotnet 7. But I still saw the 6.9.302 was still being listed. I checked my files and it is still there:

After searching through the microsoft docs, it was suggested to download the uninstall commandline tool. I did that and am having the following experience where the tool does not see the installed version:

I would prefer to use a proper uninstaller instead of just deleting the folders in my program files and removing it from my environment variables, as the uninstaller should also remove lingering services, registry edit files, and other lingering files throughout the system (remember I want a clean start).

Any ideas?


问:
Getting a different answer for complexity of a nested loop from the answer given and all the other posts
I am working a hw problem and keep getting it wrong.  I need to find the complexity for:

```<code>for (i = 2; i < n; i = i*2)
   for (j = 2; j < i; j = j+2)
     ;
</code>```

Complexity Summation Analysis Description

But the answer is Theta(n)

I looked at post Time complexity of nested loop dependent on the outer loop but that says the complexity is Theta(n^2) which is not what the professor is telling us.

Can someone tell me what I'm doing wrong? I looked through all the many other questions about complexity of nested loops when the inner one is dependent on the other one and they all say the answer is Theta(n^2) so I'm really confused.

Body:
I am working a hw problem and keep getting it wrong.  I need to find the complexity for:

for (i = 2; i < n; i = i*2)
   for (j = 2; j < i; j = j+2)
     ;

Complexity Summation Analysis Description

But the answer is Theta(n)

I looked at post Time complexity of nested loop dependent on the outer loop but that says the complexity is Theta(n^2) which is not what the professor is telling us.

Can someone tell me what I'm doing wrong? I looked through all the many other questions about complexity of nested loops when the inner one is dependent on the other one and they all say the answer is Theta(n^2) so I'm really confused.


问:
how to count Quicksort comparisons accurately
I'm trying to make a program where I count the amount of comparisons quicksort makes but its not 100% accurate. how would I make this comparison counter accurate?

The quicksort takes in an array of n random integers.

Code I have so far:

```<code>public int QuickSort(int[] list, int from, int to) {
    int icount = 0;
    if (from >= to) {
        return icount;
    }
    int p = from;
    int i = from;
    int j = to;
    while (i <= j) {
        if (list[i] <= list[p]) {
            i++;
            icount++;
        } else if (list[j] >= list[p]) {
            j--;
            icount++;
        } else {
            swap(list, i, j);
            i++;
            j--;
            icount++;
        }
    }
    if (p < j) {   // place the pivot in its correct position
        swap(list, j, p);
        p = j;
        icount++;
    } else if (p > i) {
        swap(list, i, p);
        p = i;
        icount++;
    }
    icount += QuickSort(list, from, p - 1);
    icount += QuickSort(list, p + 1, to);
    return icount;
}
</code>```

Is there anything wrong with the current code? or is it not possible to be completely accurate with random integers?

Body:
I'm trying to make a program where I count the amount of comparisons quicksort makes but its not 100% accurate. how would I make this comparison counter accurate?

The quicksort takes in an array of n random integers.

Code I have so far:

public int QuickSort(int[] list, int from, int to) {
    int icount = 0;
    if (from >= to) {
        return icount;
    }
    int p = from;
    int i = from;
    int j = to;
    while (i <= j) {
        if (list[i] <= list[p]) {
            i++;
            icount++;
        } else if (list[j] >= list[p]) {
            j--;
            icount++;
        } else {
            swap(list, i, j);
            i++;
            j--;
            icount++;
        }
    }
    if (p < j) {   // place the pivot in its correct position
        swap(list, j, p);
        p = j;
        icount++;
    } else if (p > i) {
        swap(list, i, p);
        p = i;
        icount++;
    }
    icount += QuickSort(list, from, p - 1);
    icount += QuickSort(list, p + 1, to);
    return icount;
}

Is there anything wrong with the current code? or is it not possible to be completely accurate with random integers?


问:
Abp Dapper parsing ExtraProperties
I received this error when using Dapper. My code: "(dbConnection.QueryAsync("select * from AbpUsers", transaction: await GetDbTransactionAsync())).ToList()"
=> Error:

System.Data.DataException: 'Error parsing column 2 (ExtraProperties={} - String)'

InvalidCastException: Invalid cast from 'System.String' to 'Volo.Abp.Data.ExtraPropertyDictionary'.

When I select only column "ExtraProperties" from table "IdentityUser" is work fine. My code: "(dbConnection.QueryAsync("select ExtraProperties from AbpUsers", transaction: await GetDbTransactionAsync())).ToList()"

Title: Abp Dapper parsing ExtraProperties


问:
Iteration to recursion
I need some help with a homework. I need to write the following code recursive, but I dont`t know how to do it. Any solution or tip is welcome.

```<code>def differences(values):
    result = []
    for i in range(len(values) - 1):
        result.append(values[i + 1] - values[i])
        print(result)
    return result

differences([4, 3, 6, 8])
</code>```

The parameter is list of any length with integers.

I tried sth like that, but the output it way too false

```<code>def differences(values):
    result = []
    if len(values) == 0:
        return
    result.extend(values[len(values) - 1] - len(values) + 1)
    print(result)
    return differences(values[:-1])

differences([4, 3, 6, 8])
</code>```

Title: Iteration to recursion

Body:
I need some help with a homework. I need to write the following code recursive, but I dont`t know how to do it. Any solution or tip is welcome.

def differences(values):
    result = []
    for i in range(len(values) - 1):
        result.append(values[i + 1] - values[i])
        print(result)
    return result

differences([4, 3, 6, 8])

The parameter is list of any length with integers.

I tried sth like that, but the output it way too false

def differences(values):
    result = []
    if len(values) == 0:
        return
    result.extend(values[len(values) - 1] - len(values) + 1)
    print(result)
    return differences(values[:-1])

differences([4, 3, 6, 8])


问:
Is it possible to use DbContext with Autofac in Program.cs while using AddDbContext in .EF6?
Hi everyone I am learning .EF6 and I got the compiler error CS0310 in my project. I figured that it is caused by my DbContext object as it had no default constructor. I used a constructor with DbContextOptions object in my DbContext to access my database using AddDbContext function in Program.cs. Here is the code:

```<code>using Autofac;
using FullStackBootcampSetTube.Business.Abstracts;
using FullStackBootcampSetTube.Business.Concretes;
using FullStackBootcampSetTube.DataAccess.Abstracts;
using FullStackBootcampSetTube.DataAccess.Concretes;
using FullStackBootcampSetTube.DataAccess.Concretes.EntityFramework;

namespace FullStackBootcampSetTube.Business.DependencyResolvers.AutoFac
{
    public class AutofacBusinessModule : Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType<CategoryManager>().As<ICategoryService>().SingleInstance();
            builder.RegisterType<CategoryDao>().As<ICategoryDao>().SingleInstance();

            builder.RegisterType<ChannelManager>().As<IChannelService>().SingleInstance();
            builder.RegisterType<ChannelDao>().As<IChannelDao>().SingleInstance();

            builder.RegisterType<CommentManager>().As<ICommentService>().SingleInstance();
            builder.RegisterType<CommentDao>().As<ICommentDao>().SingleInstance();

            builder.RegisterType<UserManager>().As<IUserService>().SingleInstance();
            builder.RegisterType<UserDao>().As<IUserDao>().SingleInstance();

            builder.RegisterType<VideoManager>().As<IVideoService>().SingleInstance();
            builder.RegisterType<VideoDao>().As<IVideoDao>().SingleInstance();
        }
    }
}
</code>```

This part was for Autofac DI.

```<code>using FullStackBootcampSetTube.Entities.Concretes;
using Microsoft.EntityFrameworkCore;

namespace FullStackBootcampSetTube.DataAccess.Concretes.EntityFramework
{
    public class FullStackBootcampSetTubeDBContext : DbContext
    {
        public FullStackBootcampSetTubeDBContext(DbContextOptions<FullStackBootcampSetTubeDBContext> options) : base(options) { }

        public DbSet<Category> Categories { get; set; }
        public DbSet<Channel> Channels { get; set; }
        public DbSet<Comment> Comments { get; set; }
        public DbSet<User> Users { get; set; }
        public DbSet<Video> Videos { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            //FluentAPI stuff to create tables in my database
        }
    }
}
</code>```

This part is my DbContext class.

```<code>using Autofac.Extensions.DependencyInjection;
using Autofac;
using FullStackBootcampSetTube.Business.DependencyResolvers.AutoFac;
using FullStackBootcampSetTube.DataAccess.Concretes.EntityFramework;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Services.AddDbContext<FullStackBootcampSetTubeDBContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("SqlConnectionString"))
);

builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory())
                .ConfigureContainer<ContainerBuilder>(builder =>
                {
                    builder.RegisterModule(new AutofacBusinessModule());
                });

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseAuthorization();

app.MapControllers();

app.Run();
</code>```

And this is my Program.cs file. So my question is can I do anything to resolve this issue without changing AddDbContext part with OnConfiguring function to access my database in my DbContext?

I tried adding a default constructor to my DbContext class but that disabled my connection to my database. I tried changing AddDbContext part to OnConfiguring function in my DbContext class and it solved the problem but I want to explore other options without OnConfiguring function if available.

Body:
Hi everyone I am learning .EF6 and I got the compiler error CS0310 in my project. I figured that it is caused by my DbContext object as it had no default constructor. I used a constructor with DbContextOptions object in my DbContext to access my database using AddDbContext function in Program.cs. Here is the code:

using Autofac;
using FullStackBootcampSetTube.Business.Abstracts;
using FullStackBootcampSetTube.Business.Concretes;
using FullStackBootcampSetTube.DataAccess.Abstracts;
using FullStackBootcampSetTube.DataAccess.Concretes;
using FullStackBootcampSetTube.DataAccess.Concretes.EntityFramework;

namespace FullStackBootcampSetTube.Business.DependencyResolvers.AutoFac
{
    public class AutofacBusinessModule : Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType<CategoryManager>().As<ICategoryService>().SingleInstance();
            builder.RegisterType<CategoryDao>().As<ICategoryDao>().SingleInstance();

            builder.RegisterType<ChannelManager>().As<IChannelService>().SingleInstance();
            builder.RegisterType<ChannelDao>().As<IChannelDao>().SingleInstance();

            builder.RegisterType<CommentManager>().As<ICommentService>().SingleInstance();
            builder.RegisterType<CommentDao>().As<ICommentDao>().SingleInstance();

            builder.RegisterType<UserManager>().As<IUserService>().SingleInstance();
            builder.RegisterType<UserDao>().As<IUserDao>().SingleInstance();

            builder.RegisterType<VideoManager>().As<IVideoService>().SingleInstance();
            builder.RegisterType<VideoDao>().As<IVideoDao>().SingleInstance();
        }
    }
}

This part was for Autofac DI.

using FullStackBootcampSetTube.Entities.Concretes;
using Microsoft.EntityFrameworkCore;

namespace FullStackBootcampSetTube.DataAccess.Concretes.EntityFramework
{
    public class FullStackBootcampSetTubeDBContext : DbContext
    {
        public FullStackBootcampSetTubeDBContext(DbContextOptions<FullStackBootcampSetTubeDBContext> options) : base(options) { }

        public DbSet<Category> Categories { get; set; }
        public DbSet<Channel> Channels { get; set; }
        public DbSet<Comment> Comments { get; set; }
        public DbSet<User> Users { get; set; }
        public DbSet<Video> Videos { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            //FluentAPI stuff to create tables in my database
        }
    }
}

This part is my DbContext class.

using Autofac.Extensions.DependencyInjection;
using Autofac;
using FullStackBootcampSetTube.Business.DependencyResolvers.AutoFac;
using FullStackBootcampSetTube.DataAccess.Concretes.EntityFramework;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Services.AddDbContext<FullStackBootcampSetTubeDBContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("SqlConnectionString"))
);

builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory())
                .ConfigureContainer<ContainerBuilder>(builder =>
                {
                    builder.RegisterModule(new AutofacBusinessModule());
                });

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseAuthorization();

app.MapControllers();

app.Run();

And this is my Program.cs file. So my question is can I do anything to resolve this issue without changing AddDbContext part with OnConfiguring function to access my database in my DbContext?

I tried adding a default constructor to my DbContext class but that disabled my connection to my database. I tried changing AddDbContext part to OnConfiguring function in my DbContext class and it solved the problem but I want to explore other options without OnConfiguring function if available.