问:
fastest way of applying color to specified line of richtextbox?
I'm making text filter.
The source text file is loaded in richtextbox.
I coded to change color of the whole sentence which contains the key-string defined in filter.
In below code, it took very long time to complete due to this code "this.richTextBox1.Lines[lineCount].Length". It almost takes about tens seconds.
The total number of lines of richtextbox is about 15000.
When I fix any constant number instead of "this.richTextBox1.Lines[lineCount].Length", it finish within a few second. Is there any smartter way to apply color to certain line of richtextbox?</p>
```<code>foreach (string line in this.richTextBox1.Lines)
{
    if (filterKeyString != "")
    {
        if (line.Contains(filterKeyString)
        {
            this.lbFilterOut1.Items.Add(line);
            lineNum1.Add(lineCount);
            offset = this.richTextBox1.GetFirstCharIndexFromLine(lineCount);
            this.richTextBox1.Select(offset, this.richTextBox1.Lines[lineCount].Length);
            this.richTextBox1.SelectionColor = Color.FromName(filterSet[0].color);
        }
    }
    lineCount++;
}
</code>```

Body:
I'm making text filter.
The source text file is loaded in richtextbox.
I coded to change color of the whole sentence which contains the key-string defined in filter.
In below code, it took very long time to complete due to this code "this.richTextBox1.Lines[lineCount].Length". It almost takes about tens seconds.
The total number of lines of richtextbox is about 15000.
When I fix any constant number instead of "this.richTextBox1.Lines[lineCount].Length", it finish within a few second. Is there any smartter way to apply color to certain line of richtextbox?

foreach (string line in this.richTextBox1.Lines)
{
    if (filterKeyString != "")
    {
        if (line.Contains(filterKeyString)
        {
            this.lbFilterOut1.Items.Add(line);
            lineNum1.Add(lineCount);
            offset = this.richTextBox1.GetFirstCharIndexFromLine(lineCount);
            this.richTextBox1.Select(offset, this.richTextBox1.Lines[lineCount].Length);
            this.richTextBox1.SelectionColor = Color.FromName(filterSet[0].color);
        }
    }
    lineCount++;
}


来源: stackexchange

问:
How can I customize my mat paginator in angular 8 it includes round shaped buttons?
I want to Customize the mat paginator in Angular 8 to include round-shaped buttons., I am not able to make any changes in the default in-built mat paginator.

ContentLicense: CC BY-SA 4.0


问:
How to change App Center Secret key at runtime as I change environment in the react-native app
I change my environment from testing to staging in the react native app at runtime & I want the crash logs to be stored in different paths in app center based on the environment I'm into. How can I manage to change the app center secret key whenever I change the environment in the app?

I tried different links but nothing worked for me.


问:
How do I rerender a FlatList when a value of an object changes?
The idea is to have a toggle switch that switches from To Watch and Watched bookings. When I update a movie in the To Watch list, I want it to rerender the FlatList without that booking because it's now in the Watched list. And so when I press the toggle to see the Watched list I would now see the booking there. Same for reverse. This is the code I have:

```<code>const WatchList = () => {

  const uid = auth.currentUser.uid;
  const docRef = doc(db, 'users', uid);
  const [user, setUser] = useState({});
  const [watched, setWatched] = useState(true);
  const [text, setText] = useState('To watch');
  const [filteredBookings, setFilteredBookings] = useState(bookings);

  const bookingsRef = collection(db, "booking"); // imamo ref ka bazi

  const [bookings, setBookings] = useState({});
   useEffect(() => {
    getUser();
    getBookings();
  },[])

  const getUser = async () => {
    const snap = await getDoc(docRef)
    setUser({user, ...snap.data()})
  }

  const getBookings = async () =>{
    const q = query(bookingsRef, where("users","array-contains",auth.currentUser.uid));
      const unsubscribe = onSnapshot(q, (querySnapshot) => {
        const a = [];
        querySnapshot.forEach((doc) => {
        a.push(doc.data());
      });
      setBookings(querySnapshot.docs);
    });
  }

  const toggleSwitch = () =>{
    if(!watched){
      setFilteredBookings(bookings.filter(function(item){
        return item.data().watched == true;
      }))
      setText('Watched');
    } else {
      setText('To watch');
      setFilteredBookings(bookings.filter(function(item){
        return item.data().watched == false;
      }))
    }
    setWatched(previousState => !previousState);
  }

  const updateBooking = async(id) => {
    try {
      await setDoc(doc(db, 'booking', id), {
        watched: true
      }, {merge: true})
    }
    catch(e) {
      console.log(e)
    }
  }

  const updateBooking1 = async(id) => {
    try {
      await setDoc(doc(db, 'booking', id), {
        watched: false
      }, {merge: true})
    }
    catch(e) {
      console.log(e)
    }
  }

  const deleteBooking = async(id) => {
    try {
      await deleteDoc(doc(db, 'booking', id));
    }
    catch(e) {
      console.log(e)
    }
  }

  useEffect(() => {
    const resultOfFiltering = bookings
    setFilteredBookings(resultOfFiltering)
  }, [bookings])

  return (
    <View>
      <View>
        <Text>{text}</Text>
        <Switch
          value = {watched}
        />
      </View>

  <FlatList
    data = {filteredBookings}

    renderItem  = {({item}) => (
      <View>
      <View>
        <Text>{item.data().movie}</Text>
        <Text>{item.data().day} - {item.data().showtime}</Text>
      </View>
      <View>
        {item.data().watched == true ? (
            <TouchableOpacity style = {styles.delete} onPress = {() => {updateBookings(item.id); setFilteredBookings();}}>
            <Image source={require('../assets/watched.png')}/>
            </TouchableOpacity>
        ) : (
        <TouchableOpacity onPress = {() => {updateBookings1(item.id); setFilteredBookings();}}>
        <Image source={require('../assets/towatch.png')}/>
        </TouchableOpacity>)}

        <TouchableOpacity onPress = {() => {deleteBooking(item.id); setFilteredBookings();}}>
          <Image source={require('../assets/remove.png')}/>
        </TouchableOpacity>
      </View>
      </View>
    )}
  />
      </View>
  )
}

export default WatchList
</code>```

It's not really working properly at the moment and I'm not sure what I'm doing wrong so I'm kind of stuck. If I could get some help, I'd really appreciate it. Thank you!

Body:
The idea is to have a toggle switch that switches from To Watch and Watched bookings. When I update a movie in the To Watch list, I want it to rerender the FlatList without that booking because it's now in the Watched list. And so when I press the toggle to see the Watched list I would now see the booking there. Same for reverse. This is the code I have:

const WatchList = () => {

  const uid = auth.currentUser.uid;
  const docRef = doc(db, 'users', uid);
  const [user, setUser] = useState({});
  const [watched, setWatched] = useState(true);
  const [text, setText] = useState('To watch');
  const [filteredBookings, setFilteredBookings] = useState(bookings);

  const bookingsRef = collection(db, "booking"); // imamo ref ka bazi

  const [bookings, setBookings] = useState({});
   useEffect(() => {
    getUser();
    getBookings();
  },[])

  const getUser = async () => {
    const snap = await getDoc(docRef)
    setUser({user, ...snap.data()})
  }

  const getBookings = async () =>{
    const q = query(bookingsRef, where("users","array-contains",auth.currentUser.uid));
      const unsubscribe = onSnapshot(q, (querySnapshot) => {
        const a = [];
        querySnapshot.forEach((doc) => {
        a.push(doc.data());
      });
      setBookings(querySnapshot.docs);
    });
  }

  const toggleSwitch = () =>{
    if(!watched){
      setFilteredBookings(bookings.filter(function(item){
        return item.data().watched == true;
      }))
      setText('Watched');
    } else {
      setText('To watch');
      setFilteredBookings(bookings.filter(function(item){
        return item.data().watched == false;
      }))
    }
    setWatched(previousState => !previousState);
  }

  const updateBooking = async(id) => {
    try {
      await setDoc(doc(db, 'booking', id), {
        watched: true
      }, {merge: true})
    }
    catch(e) {
      console.log(e)
    }
  }

  const updateBooking1 = async(id) => {
    try {
      await setDoc(doc(db, 'booking', id), {
        watched: false
      }, {merge: true})
    }
    catch(e) {
      console.log(e)
    }
  }

  const deleteBooking = async(id) => {
    try {
      await deleteDoc(doc(db, 'booking', id));
    }
    catch(e) {
      console.log(e)
    }
  }

  useEffect(() => {
    const resultOfFiltering = bookings
    setFilteredBookings(resultOfFiltering)
  }, [bookings])

  return (
    <View>
      <View>
        <Text>{text}</Text>
        <Switch
          value = {watched}
        />
      </View>

  <FlatList
    data = {filteredBookings}

    renderItem  = {({item}) => (
      <View>
      <View>
        <Text>{item.data().movie}</Text>
        <Text>{item.data().day} - {item.data().showtime}</Text>
      </View>
      <View>
        {item.data().watched == true ? (
            <TouchableOpacity style = {styles.delete} onPress = {() => {updateBookings(item.id); setFilteredBookings();}}>
            <Image source={require('../assets/watched.png')}/>
            </TouchableOpacity>
        ) : (
        <TouchableOpacity onPress = {() => {updateBookings1(item.id); setFilteredBookings();}}>
        <Image source={require('../assets/towatch.png')}/>
        </TouchableOpacity>)}

        <TouchableOpacity onPress = {() => {deleteBooking(item.id); setFilteredBookings();}}>
          <Image source={require('../assets/remove.png')}/>
        </TouchableOpacity>
      </View>
      </View>
    )}
  />
      </View>
  )
}

export default WatchList

It's not really working properly at the moment and I'm not sure what I'm doing wrong so I'm kind of stuck. If I could get some help, I'd really appreciate it. Thank you!


问:
How to Add a signature form field visible on all pages using itext7
as showed on another post, using iText7 I can add a signature field on a pdf document so that it is visible on first and last page.
So, I need to add an empty signature field visible on all pages.

Is there any way to do my goal?

I tried to ad the dame field multiple times (but N field will be created):

```<code>Using reader As New PdfReader(sourceFile)
    Using writer As New PdfWriter(destFile)
        Dim document As PdfDocument = New PdfDocument(reader, writer, New StampingProperties)
        Dim r As New iText.Kernel.Geom.Rectangle(400, 380, 120, 60)
        Dim field As PdfFormField = PdfFormField.CreateSignature(document, r)
        field.SetFieldName(fieldName)
        Dim form As PdfAcroForm = PdfAcroForm.GetAcroForm(document, True)
        For i As Integer = document.GetNumberOfPages To 1 Step -1
            form.AddField(field, document.GetPage(i))
        Next
        field.UpdateDefaultAppearance()
        document.Close()
        writer.Close()
    End Using
End Using
</code>```

I tried also to add widget to the same signature (but it seems not correct):

```<code>Using reader As New PdfReader(sourceFile)
    Using writer As New PdfWriter(destFile)
        Dim document As PdfDocument = New PdfDocument(reader, writer, New StampingProperties)
        Dim r As New iText.Kernel.Geom.Rectangle(400, 380, 120, 60)
        Dim field As PdfFormField = PdfFormField.CreateSignature(document, r)
        field.SetFieldName(fieldName)
        Dim form As PdfAcroForm = PdfAcroForm.GetAcroForm(document, True)
        form.AddField(field, document.GetPage(1))
        For i As Integer = 2 To document.GetNumberOfPages
            Dim w As New PdfWidgetAnnotation(r)
            w.MakeIndirect(document)
            field.AddKid(w)
            w.SetPage(document.GetPage(i))
            field.SetPage(i)
        Next
        field.UpdateDefaultAppearance()
        document.Close()
        writer.Close()
    End Using
End Using
</code>```

Body:
as showed on another post, using iText7 I can add a signature field on a pdf document so that it is visible on first and last page.
So, I need to add an empty signature field visible on all pages.

Is there any way to do my goal?

I tried to ad the dame field multiple times (but N field will be created):

Using reader As New PdfReader(sourceFile)
    Using writer As New PdfWriter(destFile)
        Dim document As PdfDocument = New PdfDocument(reader, writer, New StampingProperties)
        Dim r As New iText.Kernel.Geom.Rectangle(400, 380, 120, 60)
        Dim field As PdfFormField = PdfFormField.CreateSignature(document, r)
        field.SetFieldName(fieldName)
        Dim form As PdfAcroForm = PdfAcroForm.GetAcroForm(document, True)
        For i As Integer = document.GetNumberOfPages To 1 Step -1
            form.AddField(field, document.GetPage(i))
        Next
        field.UpdateDefaultAppearance()
        document.Close()
        writer.Close()
    End Using
End Using

I tried also to add widget to the same signature (but it seems not correct):

Using reader As New PdfReader(sourceFile)
    Using writer As New PdfWriter(destFile)
        Dim document As PdfDocument = New PdfDocument(reader, writer, New StampingProperties)
        Dim r As New iText.Kernel.Geom.Rectangle(400, 380, 120, 60)
        Dim field As PdfFormField = PdfFormField.CreateSignature(document, r)
        field.SetFieldName(fieldName)
        Dim form As PdfAcroForm = PdfAcroForm.GetAcroForm(document, True)
        form.AddField(field, document.GetPage(1))
        For i As Integer = 2 To document.GetNumberOfPages
            Dim w As New PdfWidgetAnnotation(r)
            w.MakeIndirect(document)
            field.AddKid(w)
            w.SetPage(document.GetPage(i))
            field.SetPage(i)
        Next
        field.UpdateDefaultAppearance()
        document.Close()
        writer.Close()
    End Using
End Using


问:
How to make djangoq tests use the same test database as pytest
I was beginning to write some tests that involve async tasks, and I realised these tests (using pytest-django) were failing because the async job isnt pointed at the right database. How does one point django-q /qcluster to look at the test database that pytest uses.
I am mostly using the default settings from Django.
DATABASE related settings.py looks like this

```<code>    'default': { 'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
'TEST': { 'NAME': BASE_DIR / 'testdb.sqlite3'}
</code>```

I am running this to check what is the db being connected to.

```<code>from django.db import connection
db_name = connection.settings_dict['NAME']
</code>```

When the function is being run in non async mode - it rightly points to the testdb.sqlite3.
When run using async mode, it points to the db.sqlite3.
How do i make the async task to refer to the testdb.
Any pointers would be very helpful.

Body:
I was beginning to write some tests that involve async tasks, and I realised these tests (using pytest-django) were failing because the async job isnt pointed at the right database. How does one point django-q /qcluster to look at the test database that pytest uses.
I am mostly using the default settings from Django.
DATABASE related settings.py looks like this

    'default': { 'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
'TEST': { 'NAME': BASE_DIR / 'testdb.sqlite3'}

I am running this to check what is the db being connected to.

from django.db import connection
db_name = connection.settings_dict['NAME']

When the function is being run in non async mode - it rightly points to the testdb.sqlite3.
When run using async mode, it points to the db.sqlite3.
How do i make the async task to refer to the testdb.
Any pointers would be very helpful.


问:
Return Meta Ad Account Remaining balance (account limit)
I would like to return the "Remaining amount: xx" on Meta ad accounts by inputting the ad account ID. In Meta's documentation, there are multiple fields that could work for this, but none do fully. The fields that COULD work are spend_cap, balance and amount_spent. The error occurs when the spending limit is reset (e.g. account has a limit of 500, spends 100, then the limit is reset. The logic would show a remaining balance of 400, while it is actually 500, because the balance was reset).

Any help is appreciated :)


问:
I'm getting an error when trying to reach my Instagram followers in Selenium
My Code:

```<code>``
from instagramUserInfo import username,password
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import time

class Instagram:
    def init(self, username, password):
        self.browser = webdriver.Chrome()
        self.username = username
        self.password = password
    def signIn(self):
        self.browser.get("https://www.instagram.com/accounts/login/")
        time.sleep(2)
        usernameInput = self.browser.find_element(By.XPATH, "//*[@id='loginForm']/div/div[1]/div/label/input")
        passwordInput = self.browser.find_element(By.XPATH, "//*[@id='loginForm']/div/div[2]/div/label/input")

        usernameInput.send_keys(self.username)
        passwordInput.send_keys(self.password)
        passwordInput.send_keys(Keys.ENTER)
        time.sleep(2)

    def getFollowers(self):
        self.browser.get(f"https://www.instagram.com/{self.username}")
        time.sleep(3)
        followersLink = self.browser.find_element(By.XPATH, "//*[@id='mount_0_0_fu']/div/div/div/div[1]/div/div/div/div[1]/div[1]/div[2]/section/main/div/ul/li[2]/a/div")
        followersLink.click()

instgrm = Instagram(username, password)
instgrm.signIn()
instgrm.getFollowers() ``
</code>```

I want to reach my instagram followers.

Error from:

DevTools listening on ws://127.0.0.1:52748/devtools/browser/1961d49b-bcad-45f3-b51d-a56a906fb66e
[24984:19012:0111/144509.336:ERROR:device_event_log_impl.cc(215)] [14:45:09.337] Bluetooth: bluetooth_adapter_winrt.cc:1074 Getting Default Adapter failed.
Traceback (most recent call last):
File "C:\Users\oguzc\Desktop\Çalışmalarım\Yazılım\90-instagram.py", line 32, in <module>
instgrm.getFollowers()
File "C:\Users\oguzc\Desktop\Çalışmalarım\Yazılım\90-instagram.py", line 27, in getFollowers
followersLink = self.browser.find_element(By.XPATH, "//[@id='mount_0_0_vv']/div/div/div/div[1]/div/div/div/div[1]/div[1]/div[2]/section/main/div/ul/li[2]/a")
File "C:\Users\oguzc\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 861, in find_element
return self.execute(Command.FIND_ELEMENT, {"using": by, "value": value})["value"]
File "C:\Users\oguzc\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 444, in execute
self.error_handler.check_response(response)
File "C:\Users\oguzc\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 249, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//[@id='mount_0_0_vv']/div/div/div/div[1]/div/div/div/div[1]/div[1]/div[2]/section/main/div/ul/li[2]/a"}
(Session info: chrome=108.0.5359.125)
Stacktrace:
Backtrace:
(No symbol) [0x0035F243]
(No symbol) [0x002E7FD1]
(No symbol) [0x001DD04D]
(No symbol) [0x0020C0B0]
(No symbol) [0x0020C22B]
(No symbol) [0x0023E612]
(No symbol) [0x002285D4]
(No symbol) [0x0023C9EB]
(No symbol) [0x00228386]
(No symbol) [0x0020163C]
(No symbol) [0x0020269D]
GetHandleVerifier [0x005F9A22+2655074]
(No symbol) [0x002F5968]
(No symbol) [0x002F5A55]
(No symbol) [0x0030051B]
BaseThreadInitThunk [0x768C7D69+25]
RtlInitializeExceptionChain [0x7794BB9B+107]
RtlClearBits [0x7794BB1F+191]

Body:
My Code:

``
from instagramUserInfo import username,password
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import time

class Instagram:
    def init(self, username, password):
        self.browser = webdriver.Chrome()
        self.username = username
        self.password = password
    def signIn(self):
        self.browser.get("https://www.instagram.com/accounts/login/")
        time.sleep(2)
        usernameInput = self.browser.find_element(By.XPATH, "//*[@id='loginForm']/div/div[1]/div/label/input")
        passwordInput = self.browser.find_element(By.XPATH, "//*[@id='loginForm']/div/div[2]/div/label/input")

        usernameInput.send_keys(self.username)
        passwordInput.send_keys(self.password)
        passwordInput.send_keys(Keys.ENTER)
        time.sleep(2)

    def getFollowers(self):
        self.browser.get(f"https://www.instagram.com/{self.username}")
        time.sleep(3)
        followersLink = self.browser.find_element(By.XPATH, "//*[@id='mount_0_0_fu']/div/div/div/div[1]/div/div/div/div[1]/div[1]/div[2]/section/main/div/ul/li[2]/a/div")
        followersLink.click()

instgrm = Instagram(username, password)
instgrm.signIn()
instgrm.getFollowers() ``

I want to reach my instagram followers.

Error from:

DevTools listening on ws://127.0.0.1:52748/devtools/browser/1961d49b-bcad-45f3-b51d-a56a906fb66e
[24984:19012:0111/144509.336:ERROR:device_event_log_impl.cc(215)] [14:45:09.337] Bluetooth: bluetooth_adapter_winrt.cc:1074 Getting Default Adapter failed.
Traceback (most recent call last):
File "C:\Users\oguzc\Desktop\Çalışmalarım\Yazılım\90-instagram.py", line 32, in <module>
instgrm.getFollowers()
File "C:\Users\oguzc\Desktop\Çalışmalarım\Yazılım\90-instagram.py", line 27, in getFollowers
followersLink = self.browser.find_element(By.XPATH, "//[@id='mount_0_0_vv']/div/div/div/div[1]/div/div/div/div[1]/div[1]/div[2]/section/main/div/ul/li[2]/a")
File "C:\Users\oguzc\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 861, in find_element
return self.execute(Command.FIND_ELEMENT, {"using": by, "value": value})["value"]
File "C:\Users\oguzc\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 444, in execute
self.error_handler.check_response(response)
File "C:\Users\oguzc\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 249, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//[@id='mount_0_0_vv']/div/div/div/div[1]/div/div/div/div[1]/div[1]/div[2]/section/main/div/ul/li[2]/a"}
(Session info: chrome=108.0.5359.125)
Stacktrace:
Backtrace:
(No symbol) [0x0035F243]
(No symbol) [0x002E7FD1]
(No symbol) [0x001DD04D]
(No symbol) [0x0020C0B0]
(No symbol) [0x0020C22B]
(No symbol) [0x0023E612]
(No symbol) [0x002285D4]
(No symbol) [0x0023C9EB]
(No symbol) [0x00228386]
(No symbol) [0x0020163C]
(No symbol) [0x0020269D]
GetHandleVerifier [0x005F9A22+2655074]
(No symbol) [0x002F5968]
(No symbol) [0x002F5A55]
(No symbol) [0x0030051B]
BaseThreadInitThunk [0x768C7D69+25]
RtlInitializeExceptionChain [0x7794BB9B+107]
RtlClearBits [0x7794BB1F+191]


问:
"THREE.WebGLRenderer: A WebGL context could not be created. Reason: Failed to create a WebGL2 context" error in Angular Studio
I'm new to Angular-Ionic and I created my first App with THREE js, now. When I run it in Firefox or Chrome, I don't get any erros at all. But when I run it with Android Studio I get a lot of errors.

Examples:
Could not create a WebGL context, VENDOR = 0xffff, DEVICE = 0xffff, GL_VENDOR = Google (NVIDIA Corporation), GL_RENDERER = Android Emulator OpenGL ES Translator (NVIDIA GeForce MX350/PCIe/SSE2), GL_VERSION = 526.98, Sandboxed = no, Optimus = no, AMD switchable = no, Reset notification strategy = 0x8252, ErrorMessage = bindToCurrentThread failed:

glDrawElements: framebuffer incomplete (check)

Shader Error 1280 - VALIDATE_STATUS false

Failed to create a WebGL2 context.

in Angular Studio
in Firefox

my home.page.ts (and I know, it's not a clean code):

```<code>import { Component, ElementRef, HostListener, ViewChild } from '@angular/core';
import * as THREE from 'three';

import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
import { Water } from 'three/examples/jsm/objects/Water';
import { Sky } from 'three/examples/jsm/objects/Sky';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})

export class HomePage {
  steps = 1000
  target = 10000
  progress = this.steps / this.target

  @ViewChild('canvas') container!: ElementRef;

  protected scene
  protected camera
  protected renderer
  protected controls
  protected pmremGenerator

  constructor() {
    this.scene = new THREE.Scene()
    this.camera = new THREE.PerspectiveCamera(55, window.innerWidth / window.innerHeight, 1, 20000);
    this.renderer = new THREE.WebGLRenderer({antialias: true})
    this.controls = new OrbitControls(this.camera, this.renderer.domElement);
    this.pmremGenerator = new THREE.PMREMGenerator(this.renderer)
  }

  ngAfterViewInit() {
    this.renderer.setPixelRatio(window.devicePixelRatio);
    this.renderer.setSize(window.innerWidth, window.innerHeight);
    this.renderer.toneMapping = THREE.ACESFilmicToneMapping;
    this.container.nativeElement.appendChild(this.renderer.domElement);

    this.camera.position.set(0, 0, -1000);

    this.renderer.shadowMap.enabled = true;

    this.controls.maxPolarAngle = Math.PI * 0.46;
    this.controls.minDistance = 10.0;
    this.controls.maxDistance = 200.0;
    this.controls.update();
    this.controls.update();
    let sun = new THREE.Vector3();

    const waterGeometry = new THREE.PlaneGeometry(10000, 10000);

    let water = new Water(
      waterGeometry,
      {
        textureWidth: 1024,
        textureHeight: 1024,
        waterNormals: new THREE.TextureLoader().load('../../assets/textures/waternormals.jpg', function (texture) {

          texture.wrapS = texture.wrapT = THREE.RepeatWrapping;

        }),
        sunDirection: new THREE.Vector3(),
        sunColor: 0xffffff,
        waterColor: 0x001e0f,
        distortionScale: 3.7,
        fog: true
      }
    );

    water.rotation.x = - Math.PI / 2;

    this.scene.add(water);

    const sky = new Sky();
    sky.scale.setScalar(10000);
    this.scene.add(sky);

    const skyUniforms = sky.material.uniforms;

    skyUniforms['turbidity'].value = 5;
    skyUniforms['rayleigh'].value = 0.1;
    skyUniforms['mieCoefficient'].value = 0.006;
    skyUniforms['mieDirectionalG'].value = 0.55;

    let renderTarget;

    let cylinderGeo = new THREE.CylinderGeometry(50, 50, 10, 100)
    let cylinderMat = new THREE.MeshStandardMaterial({
      metalness: 0,
      roughness: 1
    })
    let cylinder = new THREE.Mesh(cylinderGeo, cylinderMat)
    this.scene.add(cylinder)
    cylinder.position.set(0, -3, 0)
    cylinder.receiveShadow = true

    const loader = new GLTFLoader;
    loader.load(
      'assets/Wohnhaus.glb',
      (object) => {
        this.scene.add(object.scene);
        object.scene.position.set(0, 2, 0)
        object.scene.scale.set(10,10,10)
      }
    )

    this.updateSun(sky, water, sun, renderTarget);
    this.animate(water)
  }

  animate(water: Water) {
    requestAnimationFrame(() => { this.animate(water) })
    this.controls.update()

    water.material.uniforms['time'].value += 1.0 / 60.0;
    this.renderer.render(this.scene, this.camera)
  }

  @HostListener('window:resize', ['$event'])
  onResize() {
    this.renderer.setSize(window.innerWidth, window.innerHeight);
    this.camera.aspect = window.innerWidth / window.innerHeight;
    this.camera.updateProjectionMatrix();
    this.renderer.render(this.scene, this.camera);
  }

  updateSun(sky: Sky, water: Water, sun: THREE.Vector3, renderTarget: any) {

    const parameters = {
      elevation: 10,
      azimuth: 90
    };

    const phi = THREE.MathUtils.degToRad(90 - parameters.elevation);
    const theta = THREE.MathUtils.degToRad(parameters.azimuth);

    sun.setFromSphericalCoords(1, phi, theta);

    sky.material.uniforms['sunPosition'].value.copy(sun);
    water.material.uniforms['sunDirection'].value.copy(sun).normalize();
    sky.castShadow = true
    water.castShadow = true

    if (renderTarget !== undefined) renderTarget.dispose();

    renderTarget = this.pmremGenerator.fromScene(this.scene);

    this.scene.environment = renderTarget.texture;

  }
}

</code>```

I already tried different Android Versions and Phones and I always have the same problems.

Update
I have changed WEBGLRenderer to WEBGL1Renderer. In my Code I removed the commented code. Now I don't get any Errors at all. I can see the cylinder now, but not the GLTFModel.

```<code>let cylinderGeo = new THREE.CylinderGeometry(50, 50, 10, 100)
    /*let cylinderMat = new THREE.MeshStandardMaterial({
      metalness: 0,
      roughness: 1
    })*/
    let cylinder = new THREE.Mesh(cylinderGeo)
    this.scene.add(cylinder)
    cylinder.position.set(0, -3, 0)

    const loader = new GLTFLoader;
    loader.load(
      'assets/Wohnhaus.glb',
      (object) => {
        this.scene.add(object.scene);
        object.scene.position.set(0, 2, 0)
        object.scene.scale.set(10, 10, 10)
      }
    )
</code>```

Body:
I'm new to Angular-Ionic and I created my first App with THREE js, now. When I run it in Firefox or Chrome, I don't get any erros at all. But when I run it with Android Studio I get a lot of errors.

Examples:
Could not create a WebGL context, VENDOR = 0xffff, DEVICE = 0xffff, GL_VENDOR = Google (NVIDIA Corporation), GL_RENDERER = Android Emulator OpenGL ES Translator (NVIDIA GeForce MX350/PCIe/SSE2), GL_VERSION = 526.98, Sandboxed = no, Optimus = no, AMD switchable = no, Reset notification strategy = 0x8252, ErrorMessage = bindToCurrentThread failed:

glDrawElements: framebuffer incomplete (check)

Shader Error 1280 - VALIDATE_STATUS false

Failed to create a WebGL2 context.

in Angular Studio
in Firefox

my home.page.ts (and I know, it's not a clean code):

import { Component, ElementRef, HostListener, ViewChild } from '@angular/core';
import * as THREE from 'three';

import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
import { Water } from 'three/examples/jsm/objects/Water';
import { Sky } from 'three/examples/jsm/objects/Sky';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})

export class HomePage {
  steps = 1000
  target = 10000
  progress = this.steps / this.target

  @ViewChild('canvas') container!: ElementRef;

  protected scene
  protected camera
  protected renderer
  protected controls
  protected pmremGenerator

  constructor() {
    this.scene = new THREE.Scene()
    this.camera = new THREE.PerspectiveCamera(55, window.innerWidth / window.innerHeight, 1, 20000);
    this.renderer = new THREE.WebGLRenderer({antialias: true})
    this.controls = new OrbitControls(this.camera, this.renderer.domElement);
    this.pmremGenerator = new THREE.PMREMGenerator(this.renderer)
  }

  ngAfterViewInit() {
    this.renderer.setPixelRatio(window.devicePixelRatio);
    this.renderer.setSize(window.innerWidth, window.innerHeight);
    this.renderer.toneMapping = THREE.ACESFilmicToneMapping;
    this.container.nativeElement.appendChild(this.renderer.domElement);

    this.camera.position.set(0, 0, -1000);

    this.renderer.shadowMap.enabled = true;

    this.controls.maxPolarAngle = Math.PI * 0.46;
    this.controls.minDistance = 10.0;
    this.controls.maxDistance = 200.0;
    this.controls.update();
    this.controls.update();
    let sun = new THREE.Vector3();

    const waterGeometry = new THREE.PlaneGeometry(10000, 10000);

    let water = new Water(
      waterGeometry,
      {
        textureWidth: 1024,
        textureHeight: 1024,
        waterNormals: new THREE.TextureLoader().load('../../assets/textures/waternormals.jpg', function (texture) {

          texture.wrapS = texture.wrapT = THREE.RepeatWrapping;

        }),
        sunDirection: new THREE.Vector3(),
        sunColor: 0xffffff,
        waterColor: 0x001e0f,
        distortionScale: 3.7,
        fog: true
      }
    );

    water.rotation.x = - Math.PI / 2;

    this.scene.add(water);

    const sky = new Sky();
    sky.scale.setScalar(10000);
    this.scene.add(sky);

    const skyUniforms = sky.material.uniforms;

    skyUniforms['turbidity'].value = 5;
    skyUniforms['rayleigh'].value = 0.1;
    skyUniforms['mieCoefficient'].value = 0.006;
    skyUniforms['mieDirectionalG'].value = 0.55;

    let renderTarget;

    let cylinderGeo = new THREE.CylinderGeometry(50, 50, 10, 100)
    let cylinderMat = new THREE.MeshStandardMaterial({
      metalness: 0,
      roughness: 1
    })
    let cylinder = new THREE.Mesh(cylinderGeo, cylinderMat)
    this.scene.add(cylinder)
    cylinder.position.set(0, -3, 0)
    cylinder.receiveShadow = true

    const loader = new GLTFLoader;
    loader.load(
      'assets/Wohnhaus.glb',
      (object) => {
        this.scene.add(object.scene);
        object.scene.position.set(0, 2, 0)
        object.scene.scale.set(10,10,10)
      }
    )

    this.updateSun(sky, water, sun, renderTarget);
    this.animate(water)
  }

  animate(water: Water) {
    requestAnimationFrame(() => { this.animate(water) })
    this.controls.update()

    water.material.uniforms['time'].value += 1.0 / 60.0;
    this.renderer.render(this.scene, this.camera)
  }

  @HostListener('window:resize', ['$event'])
  onResize() {
    this.renderer.setSize(window.innerWidth, window.innerHeight);
    this.camera.aspect = window.innerWidth / window.innerHeight;
    this.camera.updateProjectionMatrix();
    this.renderer.render(this.scene, this.camera);
  }

  updateSun(sky: Sky, water: Water, sun: THREE.Vector3, renderTarget: any) {

    const parameters = {
      elevation: 10,
      azimuth: 90
    };

    const phi = THREE.MathUtils.degToRad(90 - parameters.elevation);
    const theta = THREE.MathUtils.degToRad(parameters.azimuth);

    sun.setFromSphericalCoords(1, phi, theta);

    sky.material.uniforms['sunPosition'].value.copy(sun);
    water.material.uniforms['sunDirection'].value.copy(sun).normalize();
    sky.castShadow = true
    water.castShadow = true

    if (renderTarget !== undefined) renderTarget.dispose();

    renderTarget = this.pmremGenerator.fromScene(this.scene);

    this.scene.environment = renderTarget.texture;

  }
}

I already tried different Android Versions and Phones and I always have the same problems.

Update
I have changed WEBGLRenderer to WEBGL1Renderer. In my Code I removed the commented code. Now I don't get any Errors at all. I can see the cylinder now, but not the GLTFModel.

let cylinderGeo = new THREE.CylinderGeometry(50, 50, 10, 100)
    /*let cylinderMat = new THREE.MeshStandardMaterial({
      metalness: 0,
      roughness: 1
    })*/
    let cylinder = new THREE.Mesh(cylinderGeo)
    this.scene.add(cylinder)
    cylinder.position.set(0, -3, 0)

    const loader = new GLTFLoader;
    loader.load(
      'assets/Wohnhaus.glb',
      (object) => {
        this.scene.add(object.scene);
        object.scene.position.set(0, 2, 0)
        object.scene.scale.set(10, 10, 10)
      }
    )


问:
Deserializing /Serializing immutable fields and the fields within the fields which are immutable and not changeable with Jackson
I m using Java 17 and the latest Jackson for  deserializing  the new ObjectMapper.convertValue(objectA, A.class); . The class A looks like ->

```<code>public class A  {
  private final B objectB;
  private final String id;
  private final C objectC;

  @JsonCreator
  public A(
  @JsonProperty("id") String  id,
  @JsonProperty("objectB") B objectB,
  @JsonProperty("objectC") C objectC){

    this.id = id;
    this.objectB= objectB;
    this.objectC= objectC;
}
}
public class B  {

  private final String idB;
  private final D objectD;

  public B(String  idB, D objectD){
    this.idB = idB;
    this.objectD= objectD;}}

public class D  {

  private final String idD;

  public D(String  idD){
    this.idD = idD;}}
</code>```

With the set up above i m getting the following error when trying to deserialize ->

```<code>   Cannot construct instance of `com.note.in.my.project.B` (no Creators, like default constructor, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
 at [Source: UNKNOWN; byte offset: #UNKNOWN] (through reference chain: com.in.my.project.A["objectB"])
</code>```

Is there a way to deserialize the fields from B, C , D classes without creating my own classes which look the same to the one which I cant change and without using @JsonIgnore. Is it possible to change something in the ObjectMapper's configuration or ?

Body:
I m using Java 17 and the latest Jackson for  deserializing  the new ObjectMapper.convertValue(objectA, A.class); . The class A looks like ->

public class A  {
  private final B objectB;
  private final String id;
  private final C objectC;

  @JsonCreator
  public A(
  @JsonProperty("id") String  id,
  @JsonProperty("objectB") B objectB,
  @JsonProperty("objectC") C objectC){

    this.id = id;
    this.objectB= objectB;
    this.objectC= objectC;
}
}
public class B  {

  private final String idB;
  private final D objectD;

  public B(String  idB, D objectD){
    this.idB = idB;
    this.objectD= objectD;}}

public class D  {

  private final String idD;

  public D(String  idD){
    this.idD = idD;}}

With the set up above i m getting the following error when trying to deserialize ->

   Cannot construct instance of `com.note.in.my.project.B` (no Creators, like default constructor, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
 at [Source: UNKNOWN; byte offset: #UNKNOWN] (through reference chain: com.in.my.project.A["objectB"])

Is there a way to deserialize the fields from B, C , D classes without creating my own classes which look the same to the one which I cant change and without using @JsonIgnore. Is it possible to change something in the ObjectMapper's configuration or ?


问:
Moshi adapter to trip trailing 0 in BigDecimal
I am trying to make custom MoshiAdapter to trim trailing 0's after decimal, but its not working

```<code>object BigDecimalAdapter : JsonAdapter<BigDecimal>() {

override fun fromJson(reader: JsonReader): BigDecimal {
    return BigDecimal(reader.readJsonValue().toString()).stripTrailingZeros()
}

override fun toJson(writer: JsonWriter, value: BigDecimal?) {
    TODO("Not yet implemented")
}
</code>```

}

And this is how i am calling my moshi

```<code>Moshi.Builder()
        .add(BigDecimalAdapter())
        .addLast(KotlinJsonAdapterFactory())
        .build()
</code>```

Body:
I am trying to make custom MoshiAdapter to trim trailing 0's after decimal, but its not working

object BigDecimalAdapter : JsonAdapter<BigDecimal>() {

override fun fromJson(reader: JsonReader): BigDecimal {
    return BigDecimal(reader.readJsonValue().toString()).stripTrailingZeros()
}

override fun toJson(writer: JsonWriter, value: BigDecimal?) {
    TODO("Not yet implemented")
}

}

And this is how i am calling my moshi

Moshi.Builder()
        .add(BigDecimalAdapter())
        .addLast(KotlinJsonAdapterFactory())
        .build()


问:
Errors with installation of firebase npm i firebase
I am trying to install fire base into my react app but i keep getting an error in the terminal

I tried installing it outside of the app directory and it seemed to install but not in the app's directory


问:
HttpClient hanging in long-running service
We have a service deployed in AKS that makes HTTP requests to an external API outside of the cluster. The path of the request is AKS -> API Management -> ExpressRoute -> API.

We have been encountering an issue where all requests from an instance of the service will hang when calling the external API. The requests never reach the API. Due to the timeouts that we have configured, the requests will be cancelled after 10 seconds. We most recently saw this on an instance of the service that had been running for over 30 days without any issues. Restarting the instance resolves the issue.

We use Microsoft.Extensions.Http (6.0.0) to register the API client class with the following code:

```<code>serviceCollection.AddHttpClient<IMyApiClient, MyApiClient>();
</code>```

Our API client looks like this:

```<code>public class MyApiClient : IMyApiClient
{
    private readonly HttpClient _httpClient;

    public MyApiClient(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    public async Task CallApi(CancellationToken ctx)
    {
        await _httpClient.GetAsync("api-uri", ctx);
    }
}
</code>```

Obviously there is complexity in the hops between AKS and the API, however, I first want to understand if we are doing anything wrong with HttpClient. As far as I can tell, we are following the reccommended usage.

We are unable to reproduce this issue locally and we have no additional logs as the requests are simply taking a long time and then being cancelled, there are no actual errors.

Body:
We have a service deployed in AKS that makes HTTP requests to an external API outside of the cluster. The path of the request is AKS -> API Management -> ExpressRoute -> API.

We have been encountering an issue where all requests from an instance of the service will hang when calling the external API. The requests never reach the API. Due to the timeouts that we have configured, the requests will be cancelled after 10 seconds. We most recently saw this on an instance of the service that had been running for over 30 days without any issues. Restarting the instance resolves the issue.

We use Microsoft.Extensions.Http (6.0.0) to register the API client class with the following code:

serviceCollection.AddHttpClient<IMyApiClient, MyApiClient>();

Our API client looks like this:

public class MyApiClient : IMyApiClient
{
    private readonly HttpClient _httpClient;

    public MyApiClient(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    public async Task CallApi(CancellationToken ctx)
    {
        await _httpClient.GetAsync("api-uri", ctx);
    }
}

Obviously there is complexity in the hops between AKS and the API, however, I first want to understand if we are doing anything wrong with HttpClient. As far as I can tell, we are following the reccommended usage.

We are unable to reproduce this issue locally and we have no additional logs as the requests are simply taking a long time and then being cancelled, there are no actual errors.


问:
getting different file size when reading pdf from disc to varbinary(max) column and subsequently bcp-ing it back to disc
So in setting the test environment for SQL Agent job I'm working on I populated a varbinary(max) field from a pdf file on disc using OPENROWSET like so

```<code>DECLARE @File varbinary(max)
SELECT @File=BulkColumn
FROM OPENROWSET
    (BULK 'v:\DIMA.pdf', SINGLE_BLOB) pdf

UPDATe Invoice_FileList SET Fajl=@File WHERE ID=4
</code>```

Afterwards I write the file back to disc like so

```<code>DECLARE @bcpCommand nvarchar(1000), @ID bigint, @UID bigint
DECLARE @FileName nvarchar(256), @FileDir nvarchar(128) = 'v:\'

SELECT @ID=ID, @UID=UID, @FileName =@FileDir + ImeFajla FROM ABImport_ImmoF.dbo.Invoice_FileList WHERE ID=4

SET @bcpCommand = 'bcp "SELECT Fajl FROM ABImport_ImmoF.dbo.Invoice_FileList WHERE ID = ' + CAST(@ID AS VARCHAR(20)) + ' AND UID = ' + CAST(@UID AS VARCHAR(20))  + '" queryout "' + @FileName + '" -T -N -S ' + @@SERVERNAME
print @bcpCommand
EXEC master..xp_cmdshell @bcpCommand

</code>```

Everything seemingly works fine, but the original pdf file and the file bcp saves to disk differ in size by few bytes and while looking identical when opened in pdf reader, comparing their respective hex shows that they are very much different.

Can someone explain to me why is that so (and since they are looking the same when opened in pdf reader do I need to worry about it at all)

Body:
So in setting the test environment for SQL Agent job I'm working on I populated a varbinary(max) field from a pdf file on disc using OPENROWSET like so

DECLARE @File varbinary(max)
SELECT @File=BulkColumn
FROM OPENROWSET
    (BULK 'v:\DIMA.pdf', SINGLE_BLOB) pdf

UPDATe Invoice_FileList SET Fajl=@File WHERE ID=4

Afterwards I write the file back to disc like so

DECLARE @bcpCommand nvarchar(1000), @ID bigint, @UID bigint
DECLARE @FileName nvarchar(256), @FileDir nvarchar(128) = 'v:\'

SELECT @ID=ID, @UID=UID, @FileName =@FileDir + ImeFajla FROM ABImport_ImmoF.dbo.Invoice_FileList WHERE ID=4

SET @bcpCommand = 'bcp "SELECT Fajl FROM ABImport_ImmoF.dbo.Invoice_FileList WHERE ID = ' + CAST(@ID AS VARCHAR(20)) + ' AND UID = ' + CAST(@UID AS VARCHAR(20))  + '" queryout "' + @FileName + '" -T -N -S ' + @@SERVERNAME
print @bcpCommand
EXEC master..xp_cmdshell @bcpCommand

Everything seemingly works fine, but the original pdf file and the file bcp saves to disk differ in size by few bytes and while looking identical when opened in pdf reader, comparing their respective hex shows that they are very much different.

Can someone explain to me why is that so (and since they are looking the same when opened in pdf reader do I need to worry about it at all)


问:
Run ffmpeg on all files of a folder
I have folder with many videos: ABOUT_00001.mp4, ABOUT_00002.mp4, ABOUT_00003.mp4, ...
I want to decompose those videos into frames, so for doing that, I execute: ffmpeg.exe -i ABOUT_00001.mp4 ABOUT_00001-%d.jpg
But I would like to take automatically all the videos in the folder and execute that command.
Something like:

ffmpeg.exe -i ABOUT_00001.mp4 ABOUT_00001-%d.jpg

ffmpeg.exe -i ABOUT_00002.mp4 ABOUT_00002-%d.jpg

...

ffmpeg.exe -i ABOUT_0000X.mp4 ABOUT_0000X-%d.jpg

And so on. Does anyone know how can I do that?
Thanks in advace

Title: Run ffmpeg on all files of a folder


问:
Read Grayscale raster in opencv
I have a raster image which contains only one band. I am trying to apply histogram equalization on this raster. The problem i cannot read it as grayscale. if i read it as unchanged it show the shape and the values.

```<code>import cv2
import numpy as np
img = cv2.imread('blur3.tif',cv2.IMREAD_UNCHANGED)
print(img.shape)
</code>```

shape
(1678, 1064)

But when i change the code to read grayscale it shows empty.

```<code>import cv2
import numpy as np
img = cv2.imread('blur3.tif',cv2.IMREAD_GRAYSCALE)
</code>```

Title: Read Grayscale raster in opencv

Body:
I have a raster image which contains only one band. I am trying to apply histogram equalization on this raster. The problem i cannot read it as grayscale. if i read it as unchanged it show the shape and the values.

import cv2
import numpy as np
img = cv2.imread('blur3.tif',cv2.IMREAD_UNCHANGED)
print(img.shape)

shape
(1678, 1064)

But when i change the code to read grayscale it shows empty.

import cv2
import numpy as np
img = cv2.imread('blur3.tif',cv2.IMREAD_GRAYSCALE)


问:
How to change label color with Chart.js?
I would like to change the color of my labels with Chart.s

I tried setting it in th option like

```<code>options: {
        plugins: {
            legend: {
                labels: {
                    // This more specific font property overrides the global property
                    font: {
                        color: "#fff"
                    }
                }
            }
        }
    }
</code>```

I found on an other post that I was supposed to use scaleFontColor in a function Line but it doesn't work or at least I'm not sure how to use it.

```<code>c = new Chart('canvas1',
                {
                  type: 'bar',
                  data: {
                    labels: fullname,
                    datasets: [{
                      label: "taux d'attaque",
                      data: attack,
                      backgroundColor: '#ceade0',
                      borderWidth: 1,
                      borderColor: '#9444CC',

                    }]
                  }
                })
            }
          }).Line(lineChartData, {
            scaleFontColor: "red"
          });
</code>```

Body:
I would like to change the color of my labels with Chart.s

I tried setting it in th option like

options: {
        plugins: {
            legend: {
                labels: {
                    // This more specific font property overrides the global property
                    font: {
                        color: "#fff"
                    }
                }
            }
        }
    }

I found on an other post that I was supposed to use scaleFontColor in a function Line but it doesn't work or at least I'm not sure how to use it.

c = new Chart('canvas1',
                {
                  type: 'bar',
                  data: {
                    labels: fullname,
                    datasets: [{
                      label: "taux d'attaque",
                      data: attack,
                      backgroundColor: '#ceade0',
                      borderWidth: 1,
                      borderColor: '#9444CC',

                    }]
                  }
                })
            }
          }).Line(lineChartData, {
            scaleFontColor: "red"
          });


问:
Angular/Ionic. Error: Cannot match any routes
Here is an example of my routes in the app-routing.module.ts file:

```<code>const routes: Routes = [
  {
    path: "onboarding-intro",
    loadChildren: () =>
      import("./pages/onboarding-intro/onboarding-intro.module").then(
        (m) => m.OnboardingIntroPageModule
      )
  },
  {
    path: "main",
    loadChildren: () =>
      import("./main/main.module").then((m) => m.MainPageModule)
  },
  // other
  {
    path: "",
    redirectTo: "onboarding-intro",
    pathMatch: "full",
  },
]
</code>```

The issue occurs in the main module, where we use the <ion-tabs> component and the following structure:

```<code>const routes: Routes = [
  {
    path: "",
    component: MainPage,
    children: [
      {
        path: "dashboard",
        loadChildren: () =>
          import("./pages/dashboard/dashboard.module").then(
            (m) => m.DashboardPageModule
          ),
      },
      {
        path: "profile",
        loadChildren: () =>
          import("./pages/profile/profile.module").then(
            (m) => m.ProfilePageModule
          ),
      },
      // other
      {
        path: "",
        redirectTo: "dashboard",
        pathMatch: "full",
      },
    ],
  },
  // other
];
</code>```

Here is an example of the main.page.html:

```<code><ion-tabs>
  <ion-tab-bar slot="bottom">
    <ion-tab-button tab="dashboard">
      <ion-icon name="home-outline"></ion-icon>
      <ion-label>{{ 'MAIN_TABS.DASHBOARD' | translate}}</ion-label>
    </ion-tab-button>

    <ion-tab-button tab="profile">
      <ion-icon name="person-circle-outline"></ion-icon>
      <ion-label>{{ 'MAIN_TABS.PROFILE' | translate}}</ion-label>
    </ion-tab-button>
  </ion-tab-bar>

  // other
</ion-tabs>
</code>```

Initially, everything is fine. However, if your current path will be for example main/dashboard and you reload the page a couple of times and then try to navigate to the profile, I get the following error: Error: Cannot match any routes. URL Segment: 'main/dashboard/profile'.

I do not understand why it puts dashboard into the path, instead of navigation to the main/profile. Could you please help?

Body:
Here is an example of my routes in the app-routing.module.ts file:

const routes: Routes = [
  {
    path: "onboarding-intro",
    loadChildren: () =>
      import("./pages/onboarding-intro/onboarding-intro.module").then(
        (m) => m.OnboardingIntroPageModule
      )
  },
  {
    path: "main",
    loadChildren: () =>
      import("./main/main.module").then((m) => m.MainPageModule)
  },
  // other
  {
    path: "",
    redirectTo: "onboarding-intro",
    pathMatch: "full",
  },
]

The issue occurs in the main module, where we use the <ion-tabs> component and the following structure:

const routes: Routes = [
  {
    path: "",
    component: MainPage,
    children: [
      {
        path: "dashboard",
        loadChildren: () =>
          import("./pages/dashboard/dashboard.module").then(
            (m) => m.DashboardPageModule
          ),
      },
      {
        path: "profile",
        loadChildren: () =>
          import("./pages/profile/profile.module").then(
            (m) => m.ProfilePageModule
          ),
      },
      // other
      {
        path: "",
        redirectTo: "dashboard",
        pathMatch: "full",
      },
    ],
  },
  // other
];

Here is an example of the main.page.html:

<ion-tabs>
  <ion-tab-bar slot="bottom">
    <ion-tab-button tab="dashboard">
      <ion-icon name="home-outline"></ion-icon>
      <ion-label>{{ 'MAIN_TABS.DASHBOARD' | translate}}</ion-label>
    </ion-tab-button>

    <ion-tab-button tab="profile">
      <ion-icon name="person-circle-outline"></ion-icon>
      <ion-label>{{ 'MAIN_TABS.PROFILE' | translate}}</ion-label>
    </ion-tab-button>
  </ion-tab-bar>

  // other
</ion-tabs>

Initially, everything is fine. However, if your current path will be for example main/dashboard and you reload the page a couple of times and then try to navigate to the profile, I get the following error: Error: Cannot match any routes. URL Segment: 'main/dashboard/profile'.

I do not understand why it puts dashboard into the path, instead of navigation to the main/profile. Could you please help?


问:
next-pwa bad-precaching-response: bad-precaching-response - Getting a 404 in console
I have seen similar issues posted on stackoverflow , however the issue i have seems to be the inverse of whats going on in most github issues and stackoverflow questions posted. The files are generated fine i.e. sw.js, fallback.js, workbox.js. However i get the following error in the console when i load my UI , on localhost:5050 :-

```<code>workbox-588899ac.js:1 Uncaught (in promise) bad-precaching-response: bad-precaching-response :: [{"url":"http://localhost:5050/static/HwVMKKqHt-mx6OcvUVKh-/_buildManifest.js","status":404}]
</code>```

The thing is if i change the path in the url to http://localhost:5050/_next/static/HwVMKKqHt-mx6OcvUVKh-/_buildManifest.js (i.e. Add the _next), the file loads fine. Also most of the issue i came across on git and stackoverflow seem to have the _next sub directory path in the url. Why do i not have the _next path appended in my url ?

Some of the issues i came across :-

ISSUE 1

ISSUE 2

However in my case the next-pwa package seems to be doing its job, i just don't understand why the /_next path is not being appended.

Additional info, my package versions are as below :-

```<code>    "next-pwa": "5.5.5",
    "next": "10.1.2",
</code>```

Also i have a custom server and my next.config.js looks like below :-

```<code>...
pwa: {
  dest: 'public',
  register: true,
  skipWaiting: true,
  runtimeCaching,
  buildExcludes: [/middleware-manifest\.json$/],
},
...
</code>```

Body:
I have seen similar issues posted on stackoverflow , however the issue i have seems to be the inverse of whats going on in most github issues and stackoverflow questions posted. The files are generated fine i.e. sw.js, fallback.js, workbox.js. However i get the following error in the console when i load my UI , on localhost:5050 :-

workbox-588899ac.js:1 Uncaught (in promise) bad-precaching-response: bad-precaching-response :: [{"url":"http://localhost:5050/static/HwVMKKqHt-mx6OcvUVKh-/_buildManifest.js","status":404}]

The thing is if i change the path in the url to http://localhost:5050/_next/static/HwVMKKqHt-mx6OcvUVKh-/_buildManifest.js (i.e. Add the _next), the file loads fine. Also most of the issue i came across on git and stackoverflow seem to have the _next sub directory path in the url. Why do i not have the _next path appended in my url ?

Some of the issues i came across :-

ISSUE 1

ISSUE 2

However in my case the next-pwa package seems to be doing its job, i just don't understand why the /_next path is not being appended.

Additional info, my package versions are as below :-

    "next-pwa": "5.5.5",
    "next": "10.1.2",

Also i have a custom server and my next.config.js looks like below :-

...
pwa: {
  dest: 'public',
  register: true,
  skipWaiting: true,
  runtimeCaching,
  buildExcludes: [/middleware-manifest\.json$/],
},
...


问:
Encrypting System Disk in Alibaba ECS through Terraform
does anyone know how I can Encrypt System Disk in Alibaba ECS through Terraform? Support says it is possible but I can't find any source for that. Thank you in advance!

it seems only possible for data disk
https://registry.terraform.io/providers/aliyun/alicloud/latest/docs/resources/ess_scaling_configuration


问:
Nodejs Socketio Client inside Docker not connecting
I've developed a socketio client which connects to a site using something like:

```<code>console.log("Start")
let socket = io("https://SITETOCONNECT.net", { transports: ["websocket"]})
socket.on("connect_error", (err) => {
    console.log(`connect_error due to ${err.message} - ${err}`);
});
socket.on("connect_error", (err) => {
    console.log(`connect_error due to ${err.message}`);
  });
socket.on('error', () => console.log("errore"));
socket.on('message', (message) => console.log("message", message));
socket.on("connect", () => {//bla bla bla})
socket.on("message",()=>{//blablabla})
</code>```

If I run this script locally on my Mac (both debugging and not_debugging) it works perfectly, but if i run it inside a docker container I just see "Start" printed and then nothing. No errors, no log, nothing!
Just to add info:

the site is a "normal" site, located outside my network.

I've done executed curl ifconfig.me  inside the container and i can see my ip, so the container is not isolated.

I've run the container both with --network=host and without it, same behaviour.

Body:
I've developed a socketio client which connects to a site using something like:

console.log("Start")
let socket = io("https://SITETOCONNECT.net", { transports: ["websocket"]})
socket.on("connect_error", (err) => {
    console.log(`connect_error due to ${err.message} - ${err}`);
});
socket.on("connect_error", (err) => {
    console.log(`connect_error due to ${err.message}`);
  });
socket.on('error', () => console.log("errore"));
socket.on('message', (message) => console.log("message", message));
socket.on("connect", () => {//bla bla bla})
socket.on("message",()=>{//blablabla})

If I run this script locally on my Mac (both debugging and not_debugging) it works perfectly, but if i run it inside a docker container I just see "Start" printed and then nothing. No errors, no log, nothing!
Just to add info:

the site is a "normal" site, located outside my network.

I've done executed curl ifconfig.me  inside the container and i can see my ip, so the container is not isolated.

I've run the container both with --network=host and without it, same behaviour.


问:
Use amazon-textract-response-parser in Lambda
How can I use https://github.com/aws-samples/amazon-textract-response-parser in Lambda?
From what I understand it's the recommended way to parse the textract response.

I tried importing the module but it couldn't find it.


问:
Localhost skipping a portion of an AnimeJS animation
I am currently learning AnimeJS but I am having a problem with the animation.
Basically, what is happening is that when I run a simple html that contains css styles and a javascript script on my localhost, the website is skipping a portion of the `

Here is my entire code:

<!DOCTYPE html>

        <title>AnimeJS</title>

```

Here is the localhost version:

And here is the version when I just open the index.html normally (locally) without localhost

Any suggestions as to what I am doing wrong and/or what I need to change in order for my localhost to work properly?

Body:
I am currently learning AnimeJS but I am having a problem with the animation.
Basically, what is happening is that when I run a simple html that contains css styles and a javascript script on my localhost, the website is skipping a portion of the `

Here is my entire code:

<!DOCTYPE html>

        <title>AnimeJS</title>

Here is the localhost version:

And here is the version when I just open the index.html normally (locally) without localhost

Any suggestions as to what I am doing wrong and/or what I need to change in order for my localhost to work properly?


问:
How can I define a custom loss function with three inputs in tensorflow?
I want make a model consists of two modules, a cluster-level prediction module and a global-level prediction module. All city regions are partitioned into several clusters, and the cluster-level prediction module employs independent recurrent neural networks for the demand prediction of each cluster. The global-level prediction module uses a single recurrent neural network to simultaneously predict the taxi demand of all regions.
My mixed loss function is designed to train model, consisting of three parts:

```<code>Loss = WMSE(Dc, D) + WMSE(Dg, D) + WMSE(Dc, Dg)

WMSE = weighted mean square error
Dc: Dc is the predicted taxi demand by cluster-level prediction module.
Dg: Dg is the predicted value from the global-level prediction module.
D: D is regarded as the final prediction.
</code>```

How can I define a custom loss function with three inputs in tensorflow?

Body:
I want make a model consists of two modules, a cluster-level prediction module and a global-level prediction module. All city regions are partitioned into several clusters, and the cluster-level prediction module employs independent recurrent neural networks for the demand prediction of each cluster. The global-level prediction module uses a single recurrent neural network to simultaneously predict the taxi demand of all regions.
My mixed loss function is designed to train model, consisting of three parts:

Loss = WMSE(Dc, D) + WMSE(Dg, D) + WMSE(Dc, Dg)

WMSE = weighted mean square error
Dc: Dc is the predicted taxi demand by cluster-level prediction module.
Dg: Dg is the predicted value from the global-level prediction module.
D: D is regarded as the final prediction.

How can I define a custom loss function with three inputs in tensorflow?


问:
Sphinx - Intersphinx - Refering to other project in one documentation
I'm trying to combine two sphinx's projects documentation into one. I try to use intersphinx.

This is the repo structure:

```<code>Projects
├── project_1
│   └── docs
│      └── source
│          └── ...
│          └── index.rst
│      └── build
│   └── lib
│      └── subfolder
│         └── python_files
├── project_2
│   └── docs
│      └── source
│          └── ...
│          └── index.rst
│              └── testing_sphinx_modules.rst
│      └── build
│   └── lib
│      └── subfolder
│         └── python_files
</code>```

Is it possible somehow in sphinx index.rst to refer to modules from other documentation / in other directory? In other words to be able to pass a path to "testing_sphinx_modules.rst" which comes from the second project?

```<code>.. toctree::
   :maxdepth: 3
   :caption: Second

   testing_sphinx_modules
</code>```

Or maybe there's some other way to combine multiple docs into one for sphinx?

Body:
I'm trying to combine two sphinx's projects documentation into one. I try to use intersphinx.

This is the repo structure:

Projects
├── project_1
│   └── docs
│      └── source
│          └── ...
│          └── index.rst
│      └── build
│   └── lib
│      └── subfolder
│         └── python_files
├── project_2
│   └── docs
│      └── source
│          └── ...
│          └── index.rst
│              └── testing_sphinx_modules.rst
│      └── build
│   └── lib
│      └── subfolder
│         └── python_files

Is it possible somehow in sphinx index.rst to refer to modules from other documentation / in other directory? In other words to be able to pass a path to "testing_sphinx_modules.rst" which comes from the second project?

.. toctree::
   :maxdepth: 3
   :caption: Second

   testing_sphinx_modules

Or maybe there's some other way to combine multiple docs into one for sphinx?


问:
R markdown word export create template
I would like to create a template using knitr for word export. I plan to use word_document2 from bookdown package.

I've seen references, tutorials for changing styles from a docx. But none of them answer my questions.

For instance, let's say my title page is as below. I'd like that all the text in black do not change. And that text in green will be updated depending on the YAML entries in the RMD file. Is it possible? Secondly in this example I would have new YAML metadata. Here project number. How to define it?

Then, if I want my template to have a second fixed page, e.g.

Same as beofre, black text is always there, and then I have the green text which change. Is it possible to do?

Title: R markdown word export create template


问:
Unable to send a jpeg attachment to mail with C#
I am trying to send a jpeg attachment to some email templates through a MailSenderService I have connected to my C# web application. I am using a .NET 6.0 version for my application.

The weird and bizarre thing is that I can send all types of documents and files such as .docx,.doc, .png, .pdf as attachments through my emails but whenever I am loading jpeg files they are not attached to the email.

My C# code for converting the full path of my files to a base64 string which is saved in my database is this:

```<code> string base64DNI = String.Empty;

 if (newEsp.rutadni != null && newEsp.rutadni != old.rutadni){
   // Lst is the text that goes together with the attachment in the email if the condition above is true
   Lst += $"<p style='font-size: 14px;font-weight: bold; font-family: 'Montserrat','Arial',sans-serif; color: #6668ae;'>" + "Se ha subido un nuevo documento de DNI." + "</p>";
   using (StreamReader strm = new StreamReader(newEsp.rutadni, System.Text.Encoding.UTF8))
   {
          Stream s = strm.BaseStream;
          BinaryReader r = new BinaryReader(s);
          docBytes = r.ReadBytes(Convert.ToInt32(r.BaseStream.Length));
          base64DNI = Convert.ToBase64String(docBytes);
          r.Close();
          s.Close();
         strm.Close();
    }
  }
</code>```

After converting my file to a base64 string, I am using a try catch block to send all my attachments through the email:

```<code>  try {
      base64DNI = base64DNI.Replace('+', '-').Replace('/', '_');
      await mailSenderService.EmailEditUser(Lst, base64DNI);
      response.status = "OK";
      response.message = "Su solicitud se ha enviado con éxito.";
  }catch (Exception ex){
       response.status = "KO";
       response.message = "Se ha producido un error. Por favor, intentelo de nuevo.";
    }
</code>```

Furthemore, I am calling an asynchronous function from my mailSenderService which is this one, it takes the Lst string which is the text of the email plus the generated base64 string from the conversion in the try catch block in the above explanation.

Finally, I am putting everything together in another try catch block which receives various properties for the request such as the sender, password, receiver, a mail template id and an email data model.

```<code>public async Task EmailEditUser(string old, string base64DNI){
        var Attachmentsls = new List<AttachmentData>();
        string ext;
        string nameDoc;

        if (base64DNI != "")
        {
            if (!string.IsNullOrEmpty(GetFileExtension(base64DNI)))
            {
                ext = GetFileExtension(base64DNI);
                nameDoc = "DNI." + ext;
                Attachmentsls.Add(new AttachmentData { Id = 1067, MailDataId = 1008, FileName = nameDoc, Data = base64DNI });
            }
        }

        try
        {
            var reqForMail = new MailSenderRequest()
            {
                From = null,
                Pass = null,
                To = mailSenderConfiguration.GetDepartmentEmails(),
                MailTemplateId = 1008,
                EmailDataModel = new MailData()
                {
                    Id = 1038,
                    MailTemplateId = 1008,
                    Properties = new List<PropertyData>
                    {
                        new PropertyData{ Id = 1067, MailDataId= 1008, ReplaceId = "Lst", Value = old},
                    },
                    Attachments = Attachmentsls
                }
            };
            ExecuteUsingMSS(mailSenderConfiguration.MSS_endpoint, reqForMail);
        }
        catch (Exception e)
        {

            Console.WriteLine($"Error al intentar enviar Email emailregisteredeventReports: {e.Message}");
        }
 }
</code>```

Any help or guidance would be kindly appreciated.

Thanks you

Body:
I am trying to send a jpeg attachment to some email templates through a MailSenderService I have connected to my C# web application. I am using a .NET 6.0 version for my application.

The weird and bizarre thing is that I can send all types of documents and files such as .docx,.doc, .png, .pdf as attachments through my emails but whenever I am loading jpeg files they are not attached to the email.

My C# code for converting the full path of my files to a base64 string which is saved in my database is this:

 string base64DNI = String.Empty;

 if (newEsp.rutadni != null && newEsp.rutadni != old.rutadni){
   // Lst is the text that goes together with the attachment in the email if the condition above is true
   Lst += $"
" + "Se ha subido un nuevo documento de DNI." + "
";
   using (StreamReader strm = new StreamReader(newEsp.rutadni, System.Text.Encoding.UTF8))
   {
          Stream s = strm.BaseStream;
          BinaryReader r = new BinaryReader(s);
          docBytes = r.ReadBytes(Convert.ToInt32(r.BaseStream.Length));
          base64DNI = Convert.ToBase64String(docBytes);
          r.Close();
          s.Close();
         strm.Close();
    }
  }

After converting my file to a base64 string, I am using a try catch block to send all my attachments through the email:

  try {
      base64DNI = base64DNI.Replace('+', '-').Replace('/', '_');
      await mailSenderService.EmailEditUser(Lst, base64DNI);
      response.status = "OK";
      response.message = "Su solicitud se ha enviado con éxito.";
  }catch (Exception ex){
       response.status = "KO";
       response.message = "Se ha producido un error. Por favor, intentelo de nuevo.";
    }

Furthemore, I am calling an asynchronous function from my mailSenderService which is this one, it takes the Lst string which is the text of the email plus the generated base64 string from the conversion in the try catch block in the above explanation.

Finally, I am putting everything together in another try catch block which receives various properties for the request such as the sender, password, receiver, a mail template id and an email data model.

public async Task EmailEditUser(string old, string base64DNI){
        var Attachmentsls = new List<AttachmentData>();
        string ext;
        string nameDoc;

        if (base64DNI != "")
        {
            if (!string.IsNullOrEmpty(GetFileExtension(base64DNI)))
            {
                ext = GetFileExtension(base64DNI);
                nameDoc = "DNI." + ext;
                Attachmentsls.Add(new AttachmentData { Id = 1067, MailDataId = 1008, FileName = nameDoc, Data = base64DNI });
            }
        }

        try
        {
            var reqForMail = new MailSenderRequest()
            {
                From = null,
                Pass = null,
                To = mailSenderConfiguration.GetDepartmentEmails(),
                MailTemplateId = 1008,
                EmailDataModel = new MailData()
                {
                    Id = 1038,
                    MailTemplateId = 1008,
                    Properties = new List<PropertyData>
                    {
                        new PropertyData{ Id = 1067, MailDataId= 1008, ReplaceId = "Lst", Value = old},
                    },
                    Attachments = Attachmentsls
                }
            };
            ExecuteUsingMSS(mailSenderConfiguration.MSS_endpoint, reqForMail);
        }
        catch (Exception e)
        {

            Console.WriteLine($"Error al intentar enviar Email emailregisteredeventReports: {e.Message}");
        }
 }

Any help or guidance would be kindly appreciated.

Thanks you


问:
How to make Multiple dependent dropdown in CRUD Django?
Fields are such as;
Phone Name(Field1)
Samsung
Redmi

Phone Model(Field2)
M30
Note10

Note : Dependency between Phone Name and Phone Model(if select samsung from the dropdown then M30 should comes and if select Redmi from the dropdown then Note10 should come.

State(Field3)
Karnataka
Andhra

City(Field4)
Bangalore
Tirupathi

Note : Dependency between State and City(if i select "Karnataka" from the dropdown then "Bangalore" should come and if i select "Andhra" from the dropdown then "Tirupathi" should come.

Data & Time(Field5)
Company Name(Field6)

I need form design Horizontally(col-6) in Separate page

Phone Name(Field1)          Phone Model(Field2)
State(Field3)               City(Field4)

Data & Time(Field5)         Company Name(Field6)

I need Retrieving Data from database in Separate page

Example:                                                                                Phone name Phone Model State City Company Name                                                                ---------- ----------- ----- ---- -------------


问:
React Native context returning empty array
In my react native application I am using context to save in the state a list of production plants The list is fetch via an API call.

Here is my redux configuration:

plant_context folder

actions.ts

```<code>
import Plant from '../../interfaces/plant.interface';
import types from './plants-types';

function loadPlants(plants: Plant[]) {
    return {
        type: types.PLANTS_LOAD_PLANTS,
        plants: plants,
    };
}

const actions = {
    loadPlants,
};

export default actions;
</code>```

plants-context.ts

```<code>import React from 'react';
import PlantsReducer, { defaultState } from './plants-reducer';
import actions from './actions';
import Plant from '../../interfaces/plant.interface';

type PlantsProviderProps = { children: React.ReactNode }

export interface PlantsContextData {
    plants: Plant[],
    loadPlants: (plants: Plant[]) => void,
}

const PlantsContext = React.createContext<PlantsContextData | undefined>(undefined);

function usePlantContextValue() {

    const [state, dispatch] = React.useReducer(PlantsReducer, defaultState);
    const { plants } = state;

    const loadPlants: (plants: Plant[]) => void = React.useCallback((plants: Plant[]) => dispatch(actions.loadPlants(plants)), []);

    return React.useMemo(() => {
        return {
            plants, loadPlants,
        };
    }, [
        plants, loadPlants,
    ]);
}

function PlantsProvider({ children }: PlantsProviderProps) {
    const value = usePlantContextValue();
    return <PlantsContext.Provider value={value}>{children}</PlantsContext.Provider>;
}

function usePlants(): PlantsContextData {
    const context = React.useContext(PlantsContext);
    if (!context) {
        throw new Error('usePlants must be used within a PlantsProvider');
    }
    return context;
}

export {
    PlantsProvider,
    usePlants,
};
</code>```

plants-reducer.ts

```<code>import types from './plants-types';

export const defaultState = {
    plants: [],
};

function PlantsReducer(state: any, action: any) {
    switch (action.type) {
        case types.PLANTS_LOAD_PLANTS:
            return {
                ...state,
                plants: action.plants
            };
        default:
            throw new Error('Unhandled action type: ' + action.type);
    }
}

export default PlantsReducer;
</code>```

plants-types

```<code>type State = {
    plants: [],
}

type Dispatch = (action: string) => void;

const PLANTS_LOAD_PLANTS = 'PLANTS_LOAD_PLANTS';

const PLANTS = {
    PLANTS_LOAD_PLANTS,
};

const types = {
    ...PLANTS,
};

export default types;
</code>```

Above is my reducer structure. Now below I will show my implementation in react functional component.

PlantsList.jsx

```<code>import React, { useEffect, useState } from 'react';
import { usePlants } from '../../utils/plant_context/plants-context';
import { doGetPlants } from '../../logic/plants';
import Plant from '../../interfaces/plant.interface';
import { useNavigation } from '@react-navigation/native';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { useApp } from '../../utils/app_context/app-context';
import useApi from '../../utils/custom_hooks/api-hook';

const PlantsList = () => {

    const { language } = useApp();
    const { t } = useTranslation();
    const navigation = useNavigation<NativeStackNavigationProp<any>>();
    const { makeCall, loading } = useApi();
    const { plants, loadPlants } = usePlants();
    const [lastUpdate, setLastUpdate] = useState<Date | null>(null);

    const renderItem = ({ item }: { item: Plant }) => (
        <PlantItem plant={item} />
    );

    const handleRefresh = async () => {
        await reloadPlants();
    };

    const reloadPlants = async () => {
        await makeCall(
            () => doGetPlants(),
            (_plants) => {
                loadPlants(_plants.plants);
            }
        );
    };

    const returnEmpty = () => {
        return <Text className='text-gray-500 text-center text-xs'>{t('No plants')}</Text>;
    };

    useEffect(() => {
        const load = async () => {
            await reloadPlants();
        };
        load();
    }, []);

    console.log('plants', plants);

    return (
        <View className="flex-1 pt-2">
           etc etc
        </View>
    );
};

export default PlantsList;
</code>```

doGetPlants.js

```<code>import API, { APIResponse } from './api';

async function doGetPlants(): Promise<APIResponse | undefined> {

    try {
        const response = await API.get('/users/whoami');
        console.log(response?.data?.data?.devicess);
        console.log('typeof-plants', typeof response?.data?.data?.devicess);

        if (response.data)
            return response.data.data.devices;
        else
            throw new Error('GET Error');

    } catch (e) {
        console.error('ERROR');
        console.error(e);
    }
}

export { doGetPlants };
</code>```

api.ts

```<code>import axios from 'axios';
import { API_URL } from 'react-native-dotenv';
import storage, { STORAGE_VARIABLES } from 'src/utils/storage';
import qs from 'query-string';

const ENDPOINT = API_URL;

export interface APIResponse {
    data: any,
    status: string,
    status_code: number,
    error: any,
    locale: string,
}

async function get(url: string, params?: any) {

    const token = await storage.getData(STORAGE_VARIABLES.token);

    try {
        const instance = await getInstance();
        if (params) {
            return await instance.get(ENDPOINT + url,
                { headers: { 'x-auth-token': token } }
                ,
                { params: { ...params } }
            );
        }
        return await instance.get(ENDPOINT + url, { headers: { 'x-auth-token': token } });

    }
    catch (error) {
        console.log(error);
        return null;
    }
}
</code>```

Bear with me, I know its a lot of code to read and understand. The function doGetPlants receive data from an API call, which is returned properly as an array of objects. But in PlantsList.jsx when i console.log "plants" i get an empty array

Body:
In my react native application I am using context to save in the state a list of production plants The list is fetch via an API call.

Here is my redux configuration:

plant_context folder

actions.ts

import Plant from '../../interfaces/plant.interface';
import types from './plants-types';

function loadPlants(plants: Plant[]) {
    return {
        type: types.PLANTS_LOAD_PLANTS,
        plants: plants,
    };
}

const actions = {
    loadPlants,
};

export default actions;

plants-context.ts

import React from 'react';
import PlantsReducer, { defaultState } from './plants-reducer';
import actions from './actions';
import Plant from '../../interfaces/plant.interface';

type PlantsProviderProps = { children: React.ReactNode }

export interface PlantsContextData {
    plants: Plant[],
    loadPlants: (plants: Plant[]) => void,
}

const PlantsContext = React.createContext<PlantsContextData | undefined>(undefined);

function usePlantContextValue() {

    const [state, dispatch] = React.useReducer(PlantsReducer, defaultState);
    const { plants } = state;

    const loadPlants: (plants: Plant[]) => void = React.useCallback((plants: Plant[]) => dispatch(actions.loadPlants(plants)), []);

    return React.useMemo(() => {
        return {
            plants, loadPlants,
        };
    }, [
        plants, loadPlants,
    ]);
}

function PlantsProvider({ children }: PlantsProviderProps) {
    const value = usePlantContextValue();
    return <PlantsContext.Provider value={value}>{children}</PlantsContext.Provider>;
}

function usePlants(): PlantsContextData {
    const context = React.useContext(PlantsContext);
    if (!context) {
        throw new Error('usePlants must be used within a PlantsProvider');
    }
    return context;
}

export {
    PlantsProvider,
    usePlants,
};

plants-reducer.ts

import types from './plants-types';

export const defaultState = {
    plants: [],
};

function PlantsReducer(state: any, action: any) {
    switch (action.type) {
        case types.PLANTS_LOAD_PLANTS:
            return {
                ...state,
                plants: action.plants
            };
        default:
            throw new Error('Unhandled action type: ' + action.type);
    }
}

export default PlantsReducer;

plants-types

type State = {
    plants: [],
}

type Dispatch = (action: string) => void;

const PLANTS_LOAD_PLANTS = 'PLANTS_LOAD_PLANTS';

const PLANTS = {
    PLANTS_LOAD_PLANTS,
};

const types = {
    ...PLANTS,
};

export default types;

Above is my reducer structure. Now below I will show my implementation in react functional component.

PlantsList.jsx

import React, { useEffect, useState } from 'react';
import { usePlants } from '../../utils/plant_context/plants-context';
import { doGetPlants } from '../../logic/plants';
import Plant from '../../interfaces/plant.interface';
import { useNavigation } from '@react-navigation/native';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { useApp } from '../../utils/app_context/app-context';
import useApi from '../../utils/custom_hooks/api-hook';

const PlantsList = () => {

    const { language } = useApp();
    const { t } = useTranslation();
    const navigation = useNavigation<NativeStackNavigationProp<any>>();
    const { makeCall, loading } = useApi();
    const { plants, loadPlants } = usePlants();
    const [lastUpdate, setLastUpdate] = useState<Date | null>(null);

    const renderItem = ({ item }: { item: Plant }) => (
        <PlantItem plant={item} />
    );

    const handleRefresh = async () => {
        await reloadPlants();
    };

    const reloadPlants = async () => {
        await makeCall(
            () => doGetPlants(),
            (_plants) => {
                loadPlants(_plants.plants);
            }
        );
    };

    const returnEmpty = () => {
        return <Text className='text-gray-500 text-center text-xs'>{t('No plants')}</Text>;
    };

    useEffect(() => {
        const load = async () => {
            await reloadPlants();
        };
        load();
    }, []);

    console.log('plants', plants);

    return (
        <View className="flex-1 pt-2">
           etc etc
        </View>
    );
};

export default PlantsList;

doGetPlants.js

import API, { APIResponse } from './api';

async function doGetPlants(): Promise<APIResponse | undefined> {

    try {
        const response = await API.get('/users/whoami');
        console.log(response?.data?.data?.devicess);
        console.log('typeof-plants', typeof response?.data?.data?.devicess);

        if (response.data)
            return response.data.data.devices;
        else
            throw new Error('GET Error');

    } catch (e) {
        console.error('ERROR');
        console.error(e);
    }
}

export { doGetPlants };

api.ts

import axios from 'axios';
import { API_URL } from 'react-native-dotenv';
import storage, { STORAGE_VARIABLES } from 'src/utils/storage';
import qs from 'query-string';

const ENDPOINT = API_URL;

export interface APIResponse {
    data: any,
    status: string,
    status_code: number,
    error: any,
    locale: string,
}

async function get(url: string, params?: any) {

    const token = await storage.getData(STORAGE_VARIABLES.token);

    try {
        const instance = await getInstance();
        if (params) {
            return await instance.get(ENDPOINT + url,
                { headers: { 'x-auth-token': token } }
                ,
                { params: { ...params } }
            );
        }
        return await instance.get(ENDPOINT + url, { headers: { 'x-auth-token': token } });

    }
    catch (error) {
        console.log(error);
        return null;
    }
}

Bear with me, I know its a lot of code to read and understand. The function doGetPlants receive data from an API call, which is returned properly as an array of objects. But in PlantsList.jsx when i console.log "plants" i get an empty array


问:
OpenSSL RSA_padding_check_PKCS1_type_2:pkcs decoding error
I'm working my way through reversing a toy challenge, and I find myself stuck. The app is pretty simple, it spits out a blob of text (e.g. "3b880a90e476d66569d9d5dfb5cd755af3f...") by building an RSA public key by directly specifying n and e:

```<code>myRsa->n=v4;
myRsa->e=v5;
</code>```

Then it encrypts it's payload and prints it out:

```<code>encodedLength = RSA_public_encrypt(flen, from, to, myRsa, 1);
...
printf("%s",to);
</code>```

My goal: "steal" the payload. Debugging tells me flen is 240, encodedLength is 256. I dumped the e for the public key as bytes, and wrote some code to generate my own RSA public/private key, patching e to be mine (n is the same for both, so left unpatched).

```<code>unsigned long bytes_read = fread(in, sizeof(unsigned char), size, file);
fclose(file);

for (size_t i = 0; i < bytes_read; i++) {
    if (memcmp(nCharOrig, in + i, 258) == 0) {
        memcpy(in + i, nCharNew, 258);
        printf("Found and patched at %d\n", i);
    };
}
</code>```

Patch works, I get a different blob of text, which in theory is the same payload, encrypted with my public key. So I try to decrypt it:

```<code>unsigned char output[8000];
RSA *rsa = RSA_new();
EVP_PKEY *privkey;
FILE *fp;

privkey = EVP_PKEY_new();
fp = fopen ("private.pem", "r");
PEM_read_PrivateKey( fp, &privkey, NULL, NULL);
fclose(fp);

rsa = EVP_PKEY_get1_RSA(privkey);
int decryptLength = RSA_private_decrypt(256, input, output, rsa, 1);
</code>```

Weirdly I get back:

```<code>decryptLength = -1, and an error: error:0407109F:rsa routines:RSA_padding_check_PKCS1_type_2:pkcs decoding error
</code>```

I thought maybe the printf("%s", to) call was doing weird char/unsigned char conversion, but it doesn't seem to, so I'm at a loss.. what am I missing here?

Body:
I'm working my way through reversing a toy challenge, and I find myself stuck. The app is pretty simple, it spits out a blob of text (e.g. "3b880a90e476d66569d9d5dfb5cd755af3f...") by building an RSA public key by directly specifying n and e:

myRsa->n=v4;
myRsa->e=v5;

Then it encrypts it's payload and prints it out:

encodedLength = RSA_public_encrypt(flen, from, to, myRsa, 1);
...
printf("%s",to);

My goal: "steal" the payload. Debugging tells me flen is 240, encodedLength is 256. I dumped the e for the public key as bytes, and wrote some code to generate my own RSA public/private key, patching e to be mine (n is the same for both, so left unpatched).

unsigned long bytes_read = fread(in, sizeof(unsigned char), size, file);
fclose(file);

for (size_t i = 0; i < bytes_read; i++) {
    if (memcmp(nCharOrig, in + i, 258) == 0) {
        memcpy(in + i, nCharNew, 258);
        printf("Found and patched at %d\n", i);
    };
}

Patch works, I get a different blob of text, which in theory is the same payload, encrypted with my public key. So I try to decrypt it:

unsigned char output[8000];
RSA *rsa = RSA_new();
EVP_PKEY *privkey;
FILE *fp;

privkey = EVP_PKEY_new();
fp = fopen ("private.pem", "r");
PEM_read_PrivateKey( fp, &privkey, NULL, NULL);
fclose(fp);

rsa = EVP_PKEY_get1_RSA(privkey);
int decryptLength = RSA_private_decrypt(256, input, output, rsa, 1);

Weirdly I get back:

decryptLength = -1, and an error: error:0407109F:rsa routines:RSA_padding_check_PKCS1_type_2:pkcs decoding error

I thought maybe the printf("%s", to) call was doing weird char/unsigned char conversion, but it doesn't seem to, so I'm at a loss.. what am I missing here?


问:
Pyautogui locate on screen doesnt find the object
I'm trying to detect image on screen and thanks to this click on it. I'm doing this with pyautogui.locateteCenterOnScreen. I am watching tutorials and read the documentation. But even with that after rewriting code from documentation and copying the graphics from from the documentation it doesn't found this image. I'm trying to move my mouse over the calculator but it doesn't work like in the documentation. File kalk.png is the file on calculator picture. Even after opening paint with only photos of this calculator pyautogui doesn't find it. I have opencv so the confidence should work. What is the cause of that and how to make it work? I am working on macos. The same code works fine on windows. What is wrong with that code? kalk.png is the picture of calculator from the https://pyautogui.readthedocs.io/en/latest/screenshot.html
On windows my mouse goes to this calculator but on mac I got the error
cannot unpack nontype object. It means that program didn't find the image

```<code>    time.sleep(3)
    x,y = pyautogui.locateCenterOnScreen("kalk.png", grayscale=True, confidence=.5)
    pyautogui.moveTo(x,y,1)
    pyautogui.click()
</code>```

Body:
I'm trying to detect image on screen and thanks to this click on it. I'm doing this with pyautogui.locateteCenterOnScreen. I am watching tutorials and read the documentation. But even with that after rewriting code from documentation and copying the graphics from from the documentation it doesn't found this image. I'm trying to move my mouse over the calculator but it doesn't work like in the documentation. File kalk.png is the file on calculator picture. Even after opening paint with only photos of this calculator pyautogui doesn't find it. I have opencv so the confidence should work. What is the cause of that and how to make it work? I am working on macos. The same code works fine on windows. What is wrong with that code? kalk.png is the picture of calculator from the https://pyautogui.readthedocs.io/en/latest/screenshot.html
On windows my mouse goes to this calculator but on mac I got the error
cannot unpack nontype object. It means that program didn't find the image

    time.sleep(3)
    x,y = pyautogui.locateCenterOnScreen("kalk.png", grayscale=True, confidence=.5)
    pyautogui.moveTo(x,y,1)
    pyautogui.click()


问:
Only one checked checkbox in android studio(kotlin)
I need only one checked checkbox, but with that code I can choose both checkbox in application. Any solutions?</p>
```<code>if(checkboxMale.isChecked){
            checkboxFemale.isChecked = false
        }else if(checkboxFemale.isChecked){
            checkboxMale.isChecked = false
        }
</code>```

Body:
I need only one checked checkbox, but with that code I can choose both checkbox in application. Any solutions?

if(checkboxMale.isChecked){
            checkboxFemale.isChecked = false
        }else if(checkboxFemale.isChecked){
            checkboxMale.isChecked = false
        }


问:
Excel365 Cascading Data Validation between multiple worksheets (within same workbook) - no VBA
I'm developing a workbook for Risk Analysis.
Currently we have a single list/array with several thousand lines.
We want to make it more managable, by splitting it according the different departments.

But the Risk Theme and specific Risks are identical for all departments.

I've created a 'Background' sheet where there's a Table with the Risk Themes and the specific Risks that are linked.

The specific Risks are a casade of the Risk Theme:
e.g.: High Risk jobs (= theme) has 4 specific risks, Chemical reagents (=theme) has 10 specific risks, etc

So far so good, when I create a cascading List on the Background sheet.
When I select a Theme (purple cell I1 = dropdown box = based on unique List from column C), I get the Range in columns E and F.
Based on selected value in I1 and with Data Validation, I'm able to fill the Dropdown box in I2 with the data from column F.

But now I want to make the formula dynamic by referencing the Theme from a any worksheet.
So referencing in e.g. LabQC-Sheet must deliver the same cascading effect, but the Dropdown boxes will be located on the LaboQC-sheet, while the arrays are still on the Background-sheet.
Extra attention is that the Dropdown boxes will be located in Named Tables.

Basicly: the reference to "I1" in the formula in the screenshot above, needs to be a Named Table reference of column D, on a worksheet that is not the Background worksheet.