问:
request.get() extremely slow
Situation- I have 144 kmls with +-1000 image urls per kml and I need all of those photos

Goal- To create a application that reads kml files, extracts url for any photos that are associated with a point an then to download the image.

problem- The requests.get() function is taking extremely long, a few minutes per request. The program used to work for a few tests and then at some point all the request slowed down completely. I think I'm being rate limited, but I'm not sure

code:

Interface.ui

```<code><?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="windowModality">
   <enum>Qt::ApplicationModal</enum>
  </property>
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>291</width>
    <height>513</height>
   </rect>
  </property>
  <property name="minimumSize">
   <size>
    <width>291</width>
    <height>513</height>
   </size>
  </property>
  <property name="maximumSize">
   <size>
    <width>291</width>
    <height>513</height>
   </size>
  </property>
  <property name="windowTitle">
   <string>KML Photo downloader</string>
  </property>
  <property name="tabShape">
   <enum>QTabWidget::Triangular</enum>
  </property>
  <widget class="QWidget" name="centralwidget">
   <widget class="QListWidget" name="list_selection">
    <property name="geometry">
     <rect>
      <x>20</x>
      <y>20</y>
      <width>251</width>
      <height>192</height>
     </rect>
    </property>
   </widget>
   <widget class="QProgressBar" name="progress_current">
    <property name="geometry">
     <rect>
      <x>10</x>
      <y>390</y>
      <width>271</width>
      <height>23</height>
     </rect>
    </property>
    <property name="value">
     <number>0</number>
    </property>
    <property name="textVisible">
     <bool>false</bool>
    </property>
    <property name="invertedAppearance">
     <bool>false</bool>
    </property>
    <property name="textDirection">
     <enum>QProgressBar::BottomToTop</enum>
    </property>
   </widget>
   <widget class="QPushButton" name="button_browse">
    <property name="geometry">
     <rect>
      <x>200</x>
      <y>220</y>
      <width>71</width>
      <height>23</height>
     </rect>
    </property>
    <property name="text">
     <string>Browse</string>
    </property>
   </widget>
   <widget class="QPushButton" name="button_remove">
    <property name="geometry">
     <rect>
      <x>120</x>
      <y>220</y>
      <width>71</width>
      <height>23</height>
     </rect>
    </property>
    <property name="text">
     <string>Remove</string>
    </property>
   </widget>
   <widget class="QProgressBar" name="progress_overall">
    <property name="geometry">
     <rect>
      <x>10</x>
      <y>440</y>
      <width>271</width>
      <height>23</height>
     </rect>
    </property>
    <property name="value">
     <number>0</number>
    </property>
    <property name="textVisible">
     <bool>false</bool>
    </property>
   </widget>
   <widget class="QLabel" name="label">
    <property name="geometry">
     <rect>
      <x>10</x>
      <y>370</y>
      <width>81</width>
      <height>16</height>
     </rect>
    </property>
    <property name="text">
     <string>Current Project</string>
    </property>
   </widget>
   <widget class="QLabel" name="label_2">
    <property name="geometry">
     <rect>
      <x>10</x>
      <y>420</y>
      <width>91</width>
      <height>16</height>
     </rect>
    </property>
    <property name="text">
     <string>Overall Progress</string>
    </property>
   </widget>
   <widget class="QPushButton" name="button_start">
    <property name="geometry">
     <rect>
      <x>210</x>
      <y>470</y>
      <width>71</width>
      <height>23</height>
     </rect>
    </property>
    <property name="text">
     <string>Start</string>
    </property>
   </widget>
   <widget class="QPushButton" name="button_close">
    <property name="geometry">
     <rect>
      <x>130</x>
      <y>470</y>
      <width>71</width>
      <height>23</height>
     </rect>
    </property>
    <property name="text">
     <string>Close</string>
    </property>
   </widget>
   <widget class="QListWidget" name="list_log">
    <property name="geometry">
     <rect>
      <x>20</x>
      <y>270</y>
      <width>251</width>
      <height>91</height>
     </rect>
    </property>
   </widget>
   <widget class="QGroupBox" name="groupBox">
    <property name="geometry">
     <rect>
      <x>10</x>
      <y>0</y>
      <width>271</width>
      <height>251</height>
     </rect>
    </property>
    <property name="title">
     <string>Select Files to download:</string>
    </property>
   </widget>
   <widget class="QGroupBox" name="groupBox_2">
    <property name="geometry">
     <rect>
      <x>10</x>
      <y>250</y>
      <width>271</width>
      <height>121</height>
     </rect>
    </property>
    <property name="title">
     <string>Log</string>
    </property>
   </widget>
   <zorder>groupBox_2</zorder>
   <zorder>groupBox</zorder>
   <zorder>list_selection</zorder>
   <zorder>progress_current</zorder>
   <zorder>button_browse</zorder>
   <zorder>button_remove</zorder>
   <zorder>progress_overall</zorder>
   <zorder>label</zorder>
   <zorder>label_2</zorder>
   <zorder>button_start</zorder>
   <zorder>button_close</zorder>
   <zorder>list_log</zorder>
  </widget>
  <widget class="QStatusBar" name="statusbar"/>
 </widget>
 <resources/>
 <connections/>
</ui>

</code>```

Main.py

```<code>from PyQt6.QtWidgets import QMainWindow, QApplication, QLabel, QListWidget, QProgressBar, QPushButton
from PyQt6 import uic
import sys
import functions
from tkinter import filedialog
from PyQt6.QtCore import pyqtSlot, QThreadPool, QTimer
from test import download_class

class window_ui(QMainWindow):
    def __init__(self):
        super(window_ui, self).__init__()

        #load the UI files:
        uic.loadUi("interface.ui", self)

        #New Thread
        self.thread_manager = QThreadPool()

        #Define widegets:
        self.button_browse = self.findChild(QPushButton, "button_browse")
        self.button_remove = self.findChild(QPushButton, "button_remove")
        self.button_start = self.findChild(QPushButton, "button_start")
        self.button_close = self.findChild(QPushButton, "button_close")
        self.list_selection = self.findChild(QListWidget, "list_selection")
        self.list_log = self.findChild(QListWidget, "list_log")
        self.progress_current = self.findChild(QProgressBar, "progress_current")
        self.progress_overall = self.findChild(QProgressBar, "progress_overall")

        #Running commands:
        self.button_browse.clicked.connect(self.browseFiles)

        self.button_close.clicked.connect(self.close)
        self.button_start.clicked.connect(self.downloadfiles_thread)

        #Display the app:
        self.show()

    # Function for opening the
    # file explorer window
    def browseFiles(self):
        filenames = filedialog.askopenfilename(multiple=True,
                                          initialdir = "/",
                                          title = "Select a File",
                                          filetypes = (("KML files",
                                                        "*.kml*"),
                                                       ("all files",
                                                        "*.*")))
        # Change label contents
        for index, filename in enumerate(filenames):
            #list_file_explorer.insert(index, filename)
            self.list_selection.insertItem(index, filename)

    #function to run the conversion
    @pyqtSlot()
    def downloadfiles(self):
        filenames = [self.list_selection.item(i).text() for i in range(self.list_selection.count())]
        self.progress_overall.setMaximum(len(filenames))

        for index, filename in enumerate(filenames):
            functions.download(self, filename)
            self.progress_overall.setValue(index + 1)

    #Start the download thread
    @pyqtSlot()
    def downloadfiles_thread(self):
        self.thread_manager.start(self.downloadfiles)

#Initialize App
app = QApplication(sys.argv)
UIWindow = window_ui()
app.exec()
</code>```

Functions.py

```<code>import shutil
import urllib
import re
import requests
from bs4 import BeautifulSoup as BSHTML
from pykml import parser
from pykml.factory import nsmap
import threading
from time import sleep
from requests.exceptions import Timeout
from requests.exceptions import ConnectTimeout
import random
import concurrent.futures
import urllib.request
import os
from PyQt6 import QtCore
import random

def download(window, filename):
    #folder name
    folder_name = os.path.basename(filename)
    folder_name = os.path.splitext(folder_name)
    folder_name = folder_name[0]
    #setup file directory
    rel_directory = os.path.join(os.path.dirname(__file__),'Photos', folder_name)
    if not os.path.exists(rel_directory):
        os.makedirs(rel_directory)

    namespace = {"ns": nsmap[None]}
    url_tuple = ()
    with open(filename) as f:
        root = parser.parse(f).getroot()
        pms = root.findall(".//ns:Placemark", namespaces=namespace)
    for pm in pms:
        name = pm.name
        if isinstance(name.text, str):
            name = name.text + '.png'
            directory_list = dir(pm)
            if 'description' in directory_list:
                description = pm.description
                source_text = description.text
                soup = BSHTML(source_text, 'html.parser')
                images = soup.findAll('img')
                for image in images:
                    url = image['src']
                    #create file name
                    point = pm.Point
                    coordinate = point.coordinates
                    coordinate = coordinate.text
                    coordinate = re.findall(r'\d+', coordinate)
                    coordinate = ','.join(coordinate) + '.png'
                    #list creation
                    url_dict = {'url' : url, 'name' : coordinate}
                    url_tuple = list(url_tuple)
                    url_tuple.append(url_dict)
                    url_tuple = tuple(url_tuple)

    #Update the current progressbar maximum
    window.progress_current.setMaximum(len(url_tuple))

    print(f'Total numbers: {len(url_tuple)}')

    #Create a thread pool to try and limit the amount of requests
    with concurrent.futures.ThreadPoolExecutor(max_workers = 10) as executor:
        future_to_url = {executor.submit(saveimage, window, url['url'], url['name'], rel_directory): url for url in url_tuple}
        for future in concurrent.futures.as_completed(future_to_url):
            url = future_to_url[future]
        try:
            data = future.result()
        except Exception as exc:
            print('%r generated an exception: %s' % (url, exc))

def saveimage(window, url, coordinate, rel_directory):
    try:
        response = requests.get(url, stream=True)
    except ConnectTimeout:
        print(url)
    except Timeout:
        print(url)
    file_name = os.path.join(rel_directory, coordinate)
    with open(file_name, 'wb') as out_file:
        shutil.copyfileobj(response.raw, out_file)
        num = window.progress_current.value()
        window.progress_current.setValue(num + 1)
        print (f'Proccesses Completed {num + 1}')
        num = num + 1
    del response
</code>```

Do you guys have any idea what the cause could be?

I tried setting up a thread pool to ensure I'm not sending through too many request, I expected the files to download at a reasonable rate and the result was incredibly slow

Title: request.get() extremely slow

Body:
Situation- I have 144 kmls with +-1000 image urls per kml and I need all of those photos

Goal- To create a application that reads kml files, extracts url for any photos that are associated with a point an then to download the image.

problem- The requests.get() function is taking extremely long, a few minutes per request. The program used to work for a few tests and then at some point all the request slowed down completely. I think I'm being rate limited, but I'm not sure

code:

Interface.ui

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="windowModality">
   <enum>Qt::ApplicationModal</enum>
  </property>
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>291</width>
    <height>513</height>
   </rect>
  </property>
  <property name="minimumSize">
   <size>
    <width>291</width>
    <height>513</height>
   </size>
  </property>
  <property name="maximumSize">
   <size>
    <width>291</width>
    <height>513</height>
   </size>
  </property>
  <property name="windowTitle">
   <string>KML Photo downloader</string>
  </property>
  <property name="tabShape">
   <enum>QTabWidget::Triangular</enum>
  </property>
  <widget class="QWidget" name="centralwidget">
   <widget class="QListWidget" name="list_selection">
    <property name="geometry">
     <rect>
      <x>20</x>
      <y>20</y>
      <width>251</width>
      <height>192</height>
     </rect>
    </property>
   </widget>
   <widget class="QProgressBar" name="progress_current">
    <property name="geometry">
     <rect>
      <x>10</x>
      <y>390</y>
      <width>271</width>
      <height>23</height>
     </rect>
    </property>
    <property name="value">
     <number>0</number>
    </property>
    <property name="textVisible">
     <bool>false</bool>
    </property>
    <property name="invertedAppearance">
     <bool>false</bool>
    </property>
    <property name="textDirection">
     <enum>QProgressBar::BottomToTop</enum>
    </property>
   </widget>
   <widget class="QPushButton" name="button_browse">
    <property name="geometry">
     <rect>
      <x>200</x>
      <y>220</y>
      <width>71</width>
      <height>23</height>
     </rect>
    </property>
    <property name="text">
     <string>Browse</string>
    </property>
   </widget>
   <widget class="QPushButton" name="button_remove">
    <property name="geometry">
     <rect>
      <x>120</x>
      <y>220</y>
      <width>71</width>
      <height>23</height>
     </rect>
    </property>
    <property name="text">
     <string>Remove</string>
    </property>
   </widget>
   <widget class="QProgressBar" name="progress_overall">
    <property name="geometry">
     <rect>
      <x>10</x>
      <y>440</y>
      <width>271</width>
      <height>23</height>
     </rect>
    </property>
    <property name="value">
     <number>0</number>
    </property>
    <property name="textVisible">
     <bool>false</bool>
    </property>
   </widget>
   <widget class="QLabel" name="label">
    <property name="geometry">
     <rect>
      <x>10</x>
      <y>370</y>
      <width>81</width>
      <height>16</height>
     </rect>
    </property>
    <property name="text">
     <string>Current Project</string>
    </property>
   </widget>
   <widget class="QLabel" name="label_2">
    <property name="geometry">
     <rect>
      <x>10</x>
      <y>420</y>
      <width>91</width>
      <height>16</height>
     </rect>
    </property>
    <property name="text">
     <string>Overall Progress</string>
    </property>
   </widget>
   <widget class="QPushButton" name="button_start">
    <property name="geometry">
     <rect>
      <x>210</x>
      <y>470</y>
      <width>71</width>
      <height>23</height>
     </rect>
    </property>
    <property name="text">
     <string>Start</string>
    </property>
   </widget>
   <widget class="QPushButton" name="button_close">
    <property name="geometry">
     <rect>
      <x>130</x>
      <y>470</y>
      <width>71</width>
      <height>23</height>
     </rect>
    </property>
    <property name="text">
     <string>Close</string>
    </property>
   </widget>
   <widget class="QListWidget" name="list_log">
    <property name="geometry">
     <rect>
      <x>20</x>
      <y>270</y>
      <width>251</width>
      <height>91</height>
     </rect>
    </property>
   </widget>
   <widget class="QGroupBox" name="groupBox">
    <property name="geometry">
     <rect>
      <x>10</x>
      <y>0</y>
      <width>271</width>
      <height>251</height>
     </rect>
    </property>
    <property name="title">
     <string>Select Files to download:</string>
    </property>
   </widget>
   <widget class="QGroupBox" name="groupBox_2">
    <property name="geometry">
     <rect>
      <x>10</x>
      <y>250</y>
      <width>271</width>
      <height>121</height>
     </rect>
    </property>
    <property name="title">
     <string>Log</string>
    </property>
   </widget>
   <zorder>groupBox_2</zorder>
   <zorder>groupBox</zorder>
   <zorder>list_selection</zorder>
   <zorder>progress_current</zorder>
   <zorder>button_browse</zorder>
   <zorder>button_remove</zorder>
   <zorder>progress_overall</zorder>
   <zorder>label</zorder>
   <zorder>label_2</zorder>
   <zorder>button_start</zorder>
   <zorder>button_close</zorder>
   <zorder>list_log</zorder>
  </widget>
  <widget class="QStatusBar" name="statusbar"/>
 </widget>
 <resources/>
 <connections/>
</ui>

Main.py

from PyQt6.QtWidgets import QMainWindow, QApplication, QLabel, QListWidget, QProgressBar, QPushButton
from PyQt6 import uic
import sys
import functions
from tkinter import filedialog
from PyQt6.QtCore import pyqtSlot, QThreadPool, QTimer
from test import download_class

class window_ui(QMainWindow):
    def __init__(self):
        super(window_ui, self).__init__()

        #load the UI files:
        uic.loadUi("interface.ui", self)

        #New Thread
        self.thread_manager = QThreadPool()

        #Define widegets:
        self.button_browse = self.findChild(QPushButton, "button_browse")
        self.button_remove = self.findChild(QPushButton, "button_remove")
        self.button_start = self.findChild(QPushButton, "button_start")
        self.button_close = self.findChild(QPushButton, "button_close")
        self.list_selection = self.findChild(QListWidget, "list_selection")
        self.list_log = self.findChild(QListWidget, "list_log")
        self.progress_current = self.findChild(QProgressBar, "progress_current")
        self.progress_overall = self.findChild(QProgressBar, "progress_overall")

        #Running commands:
        self.button_browse.clicked.connect(self.browseFiles)

        self.button_close.clicked.connect(self.close)
        self.button_start.clicked.connect(self.downloadfiles_thread)

        #Display the app:
        self.show()

    # Function for opening the
    # file explorer window
    def browseFiles(self):
        filenames = filedialog.askopenfilename(multiple=True,
                                          initialdir = "/",
                                          title = "Select a File",
                                          filetypes = (("KML files",
                                                        "*.kml*"),
                                                       ("all files",
                                                        "*.*")))
        # Change label contents
        for index, filename in enumerate(filenames):
            #list_file_explorer.insert(index, filename)
            self.list_selection.insertItem(index, filename)

    #function to run the conversion
    @pyqtSlot()
    def downloadfiles(self):
        filenames = [self.list_selection.item(i).text() for i in range(self.list_selection.count())]
        self.progress_overall.setMaximum(len(filenames))

        for index, filename in enumerate(filenames):
            functions.download(self, filename)
            self.progress_overall.setValue(index + 1)

    #Start the download thread
    @pyqtSlot()
    def downloadfiles_thread(self):
        self.thread_manager.start(self.downloadfiles)

#Initialize App
app = QApplication(sys.argv)
UIWindow = window_ui()
app.exec()

Functions.py

import shutil
import urllib
import re
import requests
from bs4 import BeautifulSoup as BSHTML
from pykml import parser
from pykml.factory import nsmap
import threading
from time import sleep
from requests.exceptions import Timeout
from requests.exceptions import ConnectTimeout
import random
import concurrent.futures
import urllib.request
import os
from PyQt6 import QtCore
import random

def download(window, filename):
    #folder name
    folder_name = os.path.basename(filename)
    folder_name = os.path.splitext(folder_name)
    folder_name = folder_name[0]
    #setup file directory
    rel_directory = os.path.join(os.path.dirname(__file__),'Photos', folder_name)
    if not os.path.exists(rel_directory):
        os.makedirs(rel_directory)

    namespace = {"ns": nsmap[None]}
    url_tuple = ()
    with open(filename) as f:
        root = parser.parse(f).getroot()
        pms = root.findall(".//ns:Placemark", namespaces=namespace)
    for pm in pms:
        name = pm.name
        if isinstance(name.text, str):
            name = name.text + '.png'
            directory_list = dir(pm)
            if 'description' in directory_list:
                description = pm.description
                source_text = description.text
                soup = BSHTML(source_text, 'html.parser')
                images = soup.findAll('img')
                for image in images:
                    url = image['src']
                    #create file name
                    point = pm.Point
                    coordinate = point.coordinates
                    coordinate = coordinate.text
                    coordinate = re.findall(r'\d+', coordinate)
                    coordinate = ','.join(coordinate) + '.png'
                    #list creation
                    url_dict = {'url' : url, 'name' : coordinate}
                    url_tuple = list(url_tuple)
                    url_tuple.append(url_dict)
                    url_tuple = tuple(url_tuple)

    #Update the current progressbar maximum
    window.progress_current.setMaximum(len(url_tuple))

    print(f'Total numbers: {len(url_tuple)}')

    #Create a thread pool to try and limit the amount of requests
    with concurrent.futures.ThreadPoolExecutor(max_workers = 10) as executor:
        future_to_url = {executor.submit(saveimage, window, url['url'], url['name'], rel_directory): url for url in url_tuple}
        for future in concurrent.futures.as_completed(future_to_url):
            url = future_to_url[future]
        try:
            data = future.result()
        except Exception as exc:
            print('%r generated an exception: %s' % (url, exc))

def saveimage(window, url, coordinate, rel_directory):
    try:
        response = requests.get(url, stream=True)
    except ConnectTimeout:
        print(url)
    except Timeout:
        print(url)
    file_name = os.path.join(rel_directory, coordinate)
    with open(file_name, 'wb') as out_file:
        shutil.copyfileobj(response.raw, out_file)
        num = window.progress_current.value()
        window.progress_current.setValue(num + 1)
        print (f'Proccesses Completed {num + 1}')
        num = num + 1
    del response

Do you guys have any idea what the cause could be?

I tried setting up a thread pool to ensure I'm not sending through too many request, I expected the files to download at a reasonable rate and the result was incredibly slow


来源: stackexchange

问:
How to write double string NFC to a single Tag
I am making a attendance application that uses NFC technology. An NFC tag act as the student ID.
however I need to input atleast two (2) data from student to the tag. I came across on a video on yt and copy the whole code and add two lines because I need two data but it seems it doesnt work lol! i hope you help me with this one

this is my code

```<code>

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
//import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;

public class writeHome extends AppCompatActivity {

    public static final String Error_Detected = "No NFC Tag Detected!";
    public static final String Write_Success = "Text Written Successfully!";
    public static final String Write_Error = "Error during Writing, Try again!";
    NfcAdapter nfcAdapter;
    PendingIntent pendingIntent;
    IntentFilter[] writingTagFilters;
    boolean writeMode;
    Tag myTag;
    Context context;
    TextView editTextTextPersonName7;
    TextView editTextTextPersonName3;
    // read
    Button button2;

    @RequiresApi(api = Build.VERSION_CODES.S)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_write_home);
        editTextTextPersonName7 = findViewById(R.id.editTextTextPersonName7);
        editTextTextPersonName3 = findViewById(R.id.editTextTextPersonName3);
        button2 = findViewById(R.id.button2);
        context = this;
        button2.setOnClickListener(view -> {
            try {
                if(myTag == null) {
                    Toast.makeText(context, Error_Detected, Toast.LENGTH_LONG).show();
                } else {
                    write(editTextTextPersonName7.getText().toString(), myTag);
                    write(editTextTextPersonName3.getText().toString(), myTag);
                    Toast.makeText(context, Write_Success, Toast.LENGTH_SHORT).show();
                }
            } catch (IOException | FormatException e) {
                Toast.makeText(context, Write_Error, Toast.LENGTH_LONG).show();
                e.printStackTrace();
            }
        });
        nfcAdapter = NfcAdapter.getDefaultAdapter(this);
        if(nfcAdapter == null) {
            Toast.makeText(this, "This device does not support NFC!", Toast.LENGTH_SHORT).show();
        }
        readFromIntent(getIntent());
        pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_MUTABLE);
        IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
        tagDetected.addCategory(Intent.CATEGORY_DEFAULT);
        writingTagFilters = new IntentFilter[] { tagDetected };

    }
    private void readFromIntent(Intent intent) {
        String action = intent.getAction();
        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)
                || NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)
                || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
            Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
            NdefMessage[] msgs = null;
            if (rawMsgs != null) {
                msgs = new NdefMessage[rawMsgs.length];
                for (int i = 0; i< rawMsgs.length; i++) {
                    msgs[i] = (NdefMessage) rawMsgs[i];
                }
            }
            buildTagViews(msgs);
        }
    }
    private void buildTagViews(NdefMessage[] msgs) {
        if (msgs == null || msgs.length == 0) return;

        String text = "";
        String text2 = "";
        byte [] payload = msgs [0].getRecords()[0].getPayload();
        String textEncoding = ((payload [0]&128) == 0) ? "UTF-8" : "UTF-16";
        int languageCodeLength = payload[0] & 51;

        try {
            text= new String(payload, languageCodeLength +1, payload.length - languageCodeLength - 1, textEncoding);
        } catch (UnsupportedEncodingException e) {
            Log.e("UnsupportedEncoding", e.toString());
        }
        //output
        editTextTextPersonName7.setText(text);
        editTextTextPersonName3.setText(text2);
    }
    private void write(String text, Tag tag) throws IOException, FormatException {
        NdefRecord[] records = { createRecord(text) };
        NdefMessage message = new NdefMessage(records);
        Ndef ndef = Ndef.get(tag);
        ndef.connect();
        ndef.writeNdefMessage(message);
        ndef.close();
    }
    private NdefRecord createRecord(String text) {
        String lang         = "en";
        byte[] textBytes    = text.getBytes();
        byte[] langBytes    = lang.getBytes(StandardCharsets.US_ASCII);
        int langLength      = langBytes.length;
        int textLength      = textBytes.length;
        byte[] payload      = new byte[1 + langLength + textLength];

        payload[0] = (byte) langLength;

        System.arraycopy(langBytes, 0, payload, 1, langLength);
        System.arraycopy(langBytes, 0, payload, 1+langLength, textLength);

        return new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], payload);

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        readFromIntent(intent);
        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
            myTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        WriteModeOff();
    }

    @Override
    public void onResume() {
        super.onResume();
        WriteModeOn();
    }
    //write & read switches
    private void WriteModeOn() {
        writeMode = true;
        String[][] techList = new String[][] { { android.nfc.tech.Ndef.class.getName() }, { android.nfc.tech.NdefFormatable.class.getName() } };
        nfcAdapter.enableForegroundDispatch(this, pendingIntent, writingTagFilters,techList);
    }

    private void WriteModeOff() {
        writeMode = false;
        nfcAdapter.disableForegroundDispatch(this);
    }

}````

I don't know much of these as I am new to programming. Can someone teach me how to make this work? Also I put this in a way that the output can be viewed on the input section if that make sense. I just copy this code from youtube so I didnt expect this to work at all. thanks!

I tried to read as much I can understand but I really don't know what to do so I wrote another question even though this was already ask before.

I just want to record two string data into NFC tag

also if you want to rewrite the code with the same id that would be great! thanks!
```

ContentLicense: CC BY-SA 4.0

Body:
I am making a attendance application that uses NFC technology. An NFC tag act as the student ID.
however I need to input atleast two (2) data from student to the tag. I came across on a video on yt and copy the whole code and add two lines because I need two data but it seems it doesnt work lol! i hope you help me with this one

this is my code

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
//import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;

public class writeHome extends AppCompatActivity {

    public static final String Error_Detected = "No NFC Tag Detected!";
    public static final String Write_Success = "Text Written Successfully!";
    public static final String Write_Error = "Error during Writing, Try again!";
    NfcAdapter nfcAdapter;
    PendingIntent pendingIntent;
    IntentFilter[] writingTagFilters;
    boolean writeMode;
    Tag myTag;
    Context context;
    TextView editTextTextPersonName7;
    TextView editTextTextPersonName3;
    // read
    Button button2;

    @RequiresApi(api = Build.VERSION_CODES.S)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_write_home);
        editTextTextPersonName7 = findViewById(R.id.editTextTextPersonName7);
        editTextTextPersonName3 = findViewById(R.id.editTextTextPersonName3);
        button2 = findViewById(R.id.button2);
        context = this;
        button2.setOnClickListener(view -> {
            try {
                if(myTag == null) {
                    Toast.makeText(context, Error_Detected, Toast.LENGTH_LONG).show();
                } else {
                    write(editTextTextPersonName7.getText().toString(), myTag);
                    write(editTextTextPersonName3.getText().toString(), myTag);
                    Toast.makeText(context, Write_Success, Toast.LENGTH_SHORT).show();
                }
            } catch (IOException | FormatException e) {
                Toast.makeText(context, Write_Error, Toast.LENGTH_LONG).show();
                e.printStackTrace();
            }
        });
        nfcAdapter = NfcAdapter.getDefaultAdapter(this);
        if(nfcAdapter == null) {
            Toast.makeText(this, "This device does not support NFC!", Toast.LENGTH_SHORT).show();
        }
        readFromIntent(getIntent());
        pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_MUTABLE);
        IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
        tagDetected.addCategory(Intent.CATEGORY_DEFAULT);
        writingTagFilters = new IntentFilter[] { tagDetected };

    }
    private void readFromIntent(Intent intent) {
        String action = intent.getAction();
        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)
                || NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)
                || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
            Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
            NdefMessage[] msgs = null;
            if (rawMsgs != null) {
                msgs = new NdefMessage[rawMsgs.length];
                for (int i = 0; i< rawMsgs.length; i++) {
                    msgs[i] = (NdefMessage) rawMsgs[i];
                }
            }
            buildTagViews(msgs);
        }
    }
    private void buildTagViews(NdefMessage[] msgs) {
        if (msgs == null || msgs.length == 0) return;

        String text = "";
        String text2 = "";
        byte [] payload = msgs [0].getRecords()[0].getPayload();
        String textEncoding = ((payload [0]&128) == 0) ? "UTF-8" : "UTF-16";
        int languageCodeLength = payload[0] & 51;

        try {
            text= new String(payload, languageCodeLength +1, payload.length - languageCodeLength - 1, textEncoding);
        } catch (UnsupportedEncodingException e) {
            Log.e("UnsupportedEncoding", e.toString());
        }
        //output
        editTextTextPersonName7.setText(text);
        editTextTextPersonName3.setText(text2);
    }
    private void write(String text, Tag tag) throws IOException, FormatException {
        NdefRecord[] records = { createRecord(text) };
        NdefMessage message = new NdefMessage(records);
        Ndef ndef = Ndef.get(tag);
        ndef.connect();
        ndef.writeNdefMessage(message);
        ndef.close();
    }
    private NdefRecord createRecord(String text) {
        String lang         = "en";
        byte[] textBytes    = text.getBytes();
        byte[] langBytes    = lang.getBytes(StandardCharsets.US_ASCII);
        int langLength      = langBytes.length;
        int textLength      = textBytes.length;
        byte[] payload      = new byte[1 + langLength + textLength];

        payload[0] = (byte) langLength;

        System.arraycopy(langBytes, 0, payload, 1, langLength);
        System.arraycopy(langBytes, 0, payload, 1+langLength, textLength);

        return new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], payload);

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        readFromIntent(intent);
        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
            myTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        WriteModeOff();
    }

    @Override
    public void onResume() {
        super.onResume();
        WriteModeOn();
    }
    //write & read switches
    private void WriteModeOn() {
        writeMode = true;
        String[][] techList = new String[][] { { android.nfc.tech.Ndef.class.getName() }, { android.nfc.tech.NdefFormatable.class.getName() } };
        nfcAdapter.enableForegroundDispatch(this, pendingIntent, writingTagFilters,techList);
    }

    private void WriteModeOff() {
        writeMode = false;
        nfcAdapter.disableForegroundDispatch(this);
    }

}````

I don't know much of these as I am new to programming. Can someone teach me how to make this work? Also I put this in a way that the output can be viewed on the input section if that make sense. I just copy this code from youtube so I didnt expect this to work at all. thanks!

I tried to read as much I can understand but I really don't know what to do so I wrote another question even though this was already ask before.

I just want to record two string data into NFC tag

also if you want to rewrite the code with the same id that would be great! thanks!


问:
Why This Program is not Running
The Work of this program is if you write a number it generates that number multiplication table
i writed this code in python:

```<code>num = int(input("Enter Your Number: "))
for i in range(1, 10):
    print(f"{num} * {i} = ", num * i)
    i = i + 1
</code>```

but why this program is not running when i press the run button it throws an error, The error is given below:

```<code>SyntaxError: invalid syntax
>>> & C:/Python311/python.exe "d:/My Files/Python Files/Python Practice/Chapter7_Q1.py
  File "<stdin>, line 1
    & C:/Python311/python.exe "d:/My Files/Python Files/Python Practice/Chapter7_Q1.py
    ^
</code>```

what did mistake i do

Title: Why This Program is not Running

Body:
The Work of this program is if you write a number it generates that number multiplication table
i writed this code in python:

num = int(input("Enter Your Number: "))
for i in range(1, 10):
    print(f"{num} * {i} = ", num * i)
    i = i + 1

but why this program is not running when i press the run button it throws an error, The error is given below:

SyntaxError: invalid syntax
>>> & C:/Python311/python.exe "d:/My Files/Python Files/Python Practice/Chapter7_Q1.py
  File "<stdin>, line 1
    & C:/Python311/python.exe "d:/My Files/Python Files/Python Practice/Chapter7_Q1.py
    ^

what did mistake i do


问:
ModuleNotFoundError: No module named 'pybullet' even after installing PyBullet
I have installed pybullet with

```<code>!pip install pybullet
</code>```

It shows a warning:

```<code>WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead
</code>```

But otherwise installed successfully.

However when in later code when I try to import it as

```<code>import pybullet as p
</code>```

It shows the following error:

```<code>ModuleNotFoundError: No module named 'pybullet'
</code>```

How do I fix it?

Body:
I have installed pybullet with

!pip install pybullet

It shows a warning:

WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead

But otherwise installed successfully.

However when in later code when I try to import it as

import pybullet as p

It shows the following error:

ModuleNotFoundError: No module named 'pybullet'

How do I fix it?


问:
findLast and findLastIndex not working / existing in codesandbox
In codesandbox for example [1,2,3].findLastIndex(n => n === 2) has an error saying that the method findLastIndex (I've checked and the same is true for findLast) does not exist on a number array. I've tried the same with other types of arrays and it;s the same.

It is not a browser problem since trying that in the browser console works.


问:
Incorrect integer value: 'sstrength' for column 'strength' at row 1"
its a pgm for inserting values to table, but it shows an error while running  "mysql.connector.errors.DatabaseError: 1366 (HY000): Incorrect integer value: 'sstrength' for column 'strength' at row 1".if i change the "%d" to '%s' it will generate other error "not all parameters were used in the sql statement"</p>
```<code>import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="user",
  password="password",
  database="db",

)
mycursor = mydb.cursor()

def create_table(sql: str,mydb):

    mycursor = mydb.cursor()

    mycursor.execute(sql)

def insert_to_students(new_student,mydb):
     sql = ("INSERT INTO students (name, roll_no,reg_no,class_id) VALUES (%s,%d,%d,%d)")
     mydb.commit()
     mycursor.execute(sql,new_student)

def insert_to_classes(new_classes,mydb):
     sql = ("INSERT INTO classes (name,strength) VALUES (%s,%s)")
     mydb.commit()
     mycursor.execute(sql,new_classes)

def create_classes_students_table(mydb):
    # create class table
    sql ="CREATE TABLE classes  (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(20),strength INT)"
    create_table(sql,mydb)
    # create student table
    sql ="CREATE TABLE students (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100),roll_no INT,reg_no VARCHAR(10),class_id INT,FOREIGN KEY (id) REFERENCES classes(id))"
    create_table(sql,mydb)

#create_classes_students_table(mydb)

#Heading of menu-driven approach
print("\nWELCOME TO CLASSES AND STUDENTS TABLE")

#using the while loop to print menu list
while True:
    print("\nMENU")
    print("1. Insert data to students table")
    print("2. Insert data to classes table")
    print("3. List both classes and students table")
    print("4. Update students table using name")
    print("5. Exit")
    table_choice = int(input("\nEnter your choice : "))

    if table_choice == 1:
        while True:
            print("\n1. Insert data to students table")
            print("2. Exit")
            choice1 = int(input("\nInsert data to students table: "))
            #Calling the relevant method based on users choice using if-else loop
            if choice1 == 1:
                sname    = input("Enter Name of Student: ")
                sroll_no = int(input("Enter Roll num of Student: "))
                sreg_no  = int(input("Enter Reg num of Student: "))
                sclass_id= int(input("Enter class id of Student: "))
                new_student_dict = ("sname","sroll_no","sreg_no","sclass_id")
                insert_to_students(new_student_dict,mydb)

            elif choice1 == 2:
                break
            else:
                print("Incorrect Choice!")

    elif table_choice == 2:
        while True:
            print("\n1. Insert data to classes table")
            print("2. Exit")
            choice1 = int(input("\nInsert data to students table: "))
            if choice1 == 1:
                scname    = input("Enter Name of Student: ")
                sstrength = int(input("Enter strength of the classes: "))
                new_classes_dict = ("scname","sstrength")
                insert_to_classes(new_classes_dict,mydb)
            elif choice1 == 2:
                break
            else:
                print("Incorrect Choice!")
    else:
        print("Incorrect Choice. Please, try again.")
    break
</code>```

Body:
its a pgm for inserting values to table, but it shows an error while running  "mysql.connector.errors.DatabaseError: 1366 (HY000): Incorrect integer value: 'sstrength' for column 'strength' at row 1".if i change the "%d" to '%s' it will generate other error "not all parameters were used in the sql statement"

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="user",
  password="password",
  database="db",

)
mycursor = mydb.cursor()

def create_table(sql: str,mydb):

    mycursor = mydb.cursor()

    mycursor.execute(sql)

def insert_to_students(new_student,mydb):
     sql = ("INSERT INTO students (name, roll_no,reg_no,class_id) VALUES (%s,%d,%d,%d)")
     mydb.commit()
     mycursor.execute(sql,new_student)

def insert_to_classes(new_classes,mydb):
     sql = ("INSERT INTO classes (name,strength) VALUES (%s,%s)")
     mydb.commit()
     mycursor.execute(sql,new_classes)

def create_classes_students_table(mydb):
    # create class table
    sql ="CREATE TABLE classes  (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(20),strength INT)"
    create_table(sql,mydb)
    # create student table
    sql ="CREATE TABLE students (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100),roll_no INT,reg_no VARCHAR(10),class_id INT,FOREIGN KEY (id) REFERENCES classes(id))"
    create_table(sql,mydb)

#create_classes_students_table(mydb)

#Heading of menu-driven approach
print("\nWELCOME TO CLASSES AND STUDENTS TABLE")

#using the while loop to print menu list
while True:
    print("\nMENU")
    print("1. Insert data to students table")
    print("2. Insert data to classes table")
    print("3. List both classes and students table")
    print("4. Update students table using name")
    print("5. Exit")
    table_choice = int(input("\nEnter your choice : "))

    if table_choice == 1:
        while True:
            print("\n1. Insert data to students table")
            print("2. Exit")
            choice1 = int(input("\nInsert data to students table: "))
            #Calling the relevant method based on users choice using if-else loop
            if choice1 == 1:
                sname    = input("Enter Name of Student: ")
                sroll_no = int(input("Enter Roll num of Student: "))
                sreg_no  = int(input("Enter Reg num of Student: "))
                sclass_id= int(input("Enter class id of Student: "))
                new_student_dict = ("sname","sroll_no","sreg_no","sclass_id")
                insert_to_students(new_student_dict,mydb)

            elif choice1 == 2:
                break
            else:
                print("Incorrect Choice!")

    elif table_choice == 2:
        while True:
            print("\n1. Insert data to classes table")
            print("2. Exit")
            choice1 = int(input("\nInsert data to students table: "))
            if choice1 == 1:
                scname    = input("Enter Name of Student: ")
                sstrength = int(input("Enter strength of the classes: "))
                new_classes_dict = ("scname","sstrength")
                insert_to_classes(new_classes_dict,mydb)
            elif choice1 == 2:
                break
            else:
                print("Incorrect Choice!")
    else:
        print("Incorrect Choice. Please, try again.")
    break


问:
Python error importDLL: DLL load file: The specified procedure could not be found
I want to reproduce, just changing the database for image detection, a neural network code that I found in git hub using the specifications passed in the link but I've been stuck in this error for some time, if anyone can help me, thanks in advance .

complete error:

```<code>Traceback (most recent call last):
  File "tools/train.py", line 15, in <module>
    from mmdet.apis import set_random_seed, train_detector
  File "c:\users\jterr\documents\projeto_ic\grcnn\grcnn-main\mmdetection\mmdet\apis\__init__.py", line 1, in <module>
    from .inference import (async_inference_detector, inference_detector,
  File "c:\users\jterr\documents\projeto_ic\grcnn\grcnn-main\mmdetection\mmdet\apis\inference.py", line 6, in <module>
    from mmcv.ops import RoIPool
  File "C:\Users\jterr\anaconda3\envs\GRCNN_Detect\lib\site-packages\mmcv\ops\__init__.py", line 2, in <module>
    from .assign_score_withk import assign_score_withk
  File "C:\Users\jterr\anaconda3\envs\GRCNN_Detect\lib\site-packages\mmcv\ops\assign_score_withk.py", line 6, in <module>
    '_ext', ['assign_score_withk_forward', 'assign_score_withk_backward'])
  File "C:\Users\jterr\anaconda3\envs\GRCNN_Detect\lib\site-packages\mmcv\utils\ext_loader.py", line 13, in load_ext
    ext = importlib.import_module('mmcv.' + name)
  File "C:\Users\jterr\anaconda3\envs\GRCNN_Detect\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
ImportError: DLL load failed: Não foi possível encontrar o procedimento especificado.
</code>```

Conda info:

```<code> active environment : GRCNN_Detect
    active env location : C:\Users\jterr\anaconda3\envs\GRCNN_Detect
            shell level : 4
       user config file : C:\Users\jterr\.condarc
 populated config files : C:\Users\jterr\.condarc
          conda version : 22.9.0
    conda-build version : 3.22.0
         python version : 3.8.8.final.0
       virtual packages : __cuda=10.1=0
                          __win=0=0
                          __archspec=1=x86_64
       base environment : C:\Users\jterr\anaconda3  (writable)
      conda av data dir : C:\Users\jterr\anaconda3\etc\conda
  conda av metadata url : None
           channel URLs : https://repo.anaconda.com/pkgs/main/win-64
                          https://repo.anaconda.com/pkgs/main/noarch
                          https://repo.anaconda.com/pkgs/r/win-64
                          https://repo.anaconda.com/pkgs/r/noarch
                          https://repo.anaconda.com/pkgs/msys2/win-64
                          https://repo.anaconda.com/pkgs/msys2/noarch
          package cache : C:\Users\jterr\anaconda3\pkgs
                          C:\Users\jterr\.conda\pkgs
                          C:\Users\jterr\AppData\Local\conda\conda\pkgs
       envs directories : C:\Users\jterr\anaconda3\envs
                          C:\Users\jterr\.conda\envs
                          C:\Users\jterr\AppData\Local\conda\conda\envs
               platform : win-64
             user-agent : conda/22.9.0 requests/2.28.1 CPython/3.8.8 Windows/10 Windows/10.0.19041
          administrator : False
             netrc file : None
           offline mode : False
</code>```

Link gitHub original code: https://github.com/Jianf-Wang/GRCNN

I already fixed some issues with CUDA before this bug, now I would expect when this one is fixed that networking will work as expected.

Body:
I want to reproduce, just changing the database for image detection, a neural network code that I found in git hub using the specifications passed in the link but I've been stuck in this error for some time, if anyone can help me, thanks in advance .

complete error:

Traceback (most recent call last):
  File "tools/train.py", line 15, in <module>
    from mmdet.apis import set_random_seed, train_detector
  File "c:\users\jterr\documents\projeto_ic\grcnn\grcnn-main\mmdetection\mmdet\apis\__init__.py", line 1, in <module>
    from .inference import (async_inference_detector, inference_detector,
  File "c:\users\jterr\documents\projeto_ic\grcnn\grcnn-main\mmdetection\mmdet\apis\inference.py", line 6, in <module>
    from mmcv.ops import RoIPool
  File "C:\Users\jterr\anaconda3\envs\GRCNN_Detect\lib\site-packages\mmcv\ops\__init__.py", line 2, in <module>
    from .assign_score_withk import assign_score_withk
  File "C:\Users\jterr\anaconda3\envs\GRCNN_Detect\lib\site-packages\mmcv\ops\assign_score_withk.py", line 6, in <module>
    '_ext', ['assign_score_withk_forward', 'assign_score_withk_backward'])
  File "C:\Users\jterr\anaconda3\envs\GRCNN_Detect\lib\site-packages\mmcv\utils\ext_loader.py", line 13, in load_ext
    ext = importlib.import_module('mmcv.' + name)
  File "C:\Users\jterr\anaconda3\envs\GRCNN_Detect\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
ImportError: DLL load failed: Não foi possível encontrar o procedimento especificado.

Conda info:

 active environment : GRCNN_Detect
    active env location : C:\Users\jterr\anaconda3\envs\GRCNN_Detect
            shell level : 4
       user config file : C:\Users\jterr\.condarc
 populated config files : C:\Users\jterr\.condarc
          conda version : 22.9.0
    conda-build version : 3.22.0
         python version : 3.8.8.final.0
       virtual packages : __cuda=10.1=0
                          __win=0=0
                          __archspec=1=x86_64
       base environment : C:\Users\jterr\anaconda3  (writable)
      conda av data dir : C:\Users\jterr\anaconda3\etc\conda
  conda av metadata url : None
           channel URLs : https://repo.anaconda.com/pkgs/main/win-64
                          https://repo.anaconda.com/pkgs/main/noarch
                          https://repo.anaconda.com/pkgs/r/win-64
                          https://repo.anaconda.com/pkgs/r/noarch
                          https://repo.anaconda.com/pkgs/msys2/win-64
                          https://repo.anaconda.com/pkgs/msys2/noarch
          package cache : C:\Users\jterr\anaconda3\pkgs
                          C:\Users\jterr\.conda\pkgs
                          C:\Users\jterr\AppData\Local\conda\conda\pkgs
       envs directories : C:\Users\jterr\anaconda3\envs
                          C:\Users\jterr\.conda\envs
                          C:\Users\jterr\AppData\Local\conda\conda\envs
               platform : win-64
             user-agent : conda/22.9.0 requests/2.28.1 CPython/3.8.8 Windows/10 Windows/10.0.19041
          administrator : False
             netrc file : None
           offline mode : False

Link gitHub original code: https://github.com/Jianf-Wang/GRCNN

I already fixed some issues with CUDA before this bug, now I would expect when this one is fixed that networking will work as expected.


问:
I want to have a general search and now only for keyword exact only
This is my search function which is looking only for exact search. What setting should I change to make it like if I type "LO", he should find "HELLO", for example.</p>
```<code>search.setIconifiedByDefault(false);
                    ArrayAdapter<String> adapter = new ArrayAdapter<>(AssetListActivity.this, android.R.layout.simple_list_item_1, assets_list_button);
                    assets_list_view.setAdapter(adapter);

                    search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                        @Override
                        public boolean onQueryTextSubmit(String query) {

                            adapter.getFilter().filter(query);

                            return false;
                        }

                        @Override
                        public boolean onQueryTextChange(String newText) {
                            adapter.getFilter().filter(newText);
                            return false;
                        }
                    });
</code>```

Body:
This is my search function which is looking only for exact search. What setting should I change to make it like if I type "LO", he should find "HELLO", for example.

search.setIconifiedByDefault(false);
                    ArrayAdapter<String> adapter = new ArrayAdapter<>(AssetListActivity.this, android.R.layout.simple_list_item_1, assets_list_button);
                    assets_list_view.setAdapter(adapter);

                    search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                        @Override
                        public boolean onQueryTextSubmit(String query) {

                            adapter.getFilter().filter(query);

                            return false;
                        }

                        @Override
                        public boolean onQueryTextChange(String newText) {
                            adapter.getFilter().filter(newText);
                            return false;
                        }
                    });


问:
Zustand - alternative to "slices" pattern
I have a React Native app that consists of modals (popups) showing up at different places. This can be a user login modal, a modal that allows a user to be added to a list of groups/orgs, a modal that allows editing a user profile etc. For all these types of modals, I decided to create a central state store using the Zustand state management library.

Following the Zustand "slices" pattern mentioned here, I was able to get the following structure for each type of Modal -

Slices

useEditUserProfileModalSlice.ts

```<code>export const createEditUserProfileModalSlice = (set) => ({
    isEditUserProfileModalOpen: false,
    openEditUserProfileModal: () => set(() => ({ isEditUserProfileModalOpen: true })),
    closeEditUserProfileModal: () => set(() => ({ isEditUserProfileModalOpen: false }))
});
</code>```

useAddUserToOrgModalSlice.ts

```<code>export const createAddUserToOrgModalSlice = (set) => ({
    isAddUserToOrgModalOpen: false,
    openAddUserToOrgModal: () => set(() => ({ isAddUserToOrgModalOpen: true })),
    closeAddUserToOrgModal: () => set(() => ({ isAddUserToOrgModalOpen: false }))
});
</code>```

Store

useModalStore.ts

```<code>import create from 'zustand'

export const useModalStore = create((...a) => ({
  ...createEditUserProfileModalSlice(...a),
  ...createAddUserToOrgModalSlice(...a),
}))
</code>```

Usage

```<code>const isEditUserProfileModalOpen = useModalStore((state) => state.isEditUserProfileModalOpen);
const openEditUserProfileModal = useModalStore((state) => state.openEditUserProfileModal);
const closeEditUserProfileModal = useModalStore((state) => state.closeEditUserProfileModal);
</code>```

Is there an alternative to this pattern that you would recommend?
I ask because any time I need to add a new modal type, I'll need to create a new slice file, with basically the same 3 properties (isOpen, open function and close function), which kinda seems boilerplate-y.

Body:
I have a React Native app that consists of modals (popups) showing up at different places. This can be a user login modal, a modal that allows a user to be added to a list of groups/orgs, a modal that allows editing a user profile etc. For all these types of modals, I decided to create a central state store using the Zustand state management library.

Following the Zustand "slices" pattern mentioned here, I was able to get the following structure for each type of Modal -

Slices

useEditUserProfileModalSlice.ts

export const createEditUserProfileModalSlice = (set) => ({
    isEditUserProfileModalOpen: false,
    openEditUserProfileModal: () => set(() => ({ isEditUserProfileModalOpen: true })),
    closeEditUserProfileModal: () => set(() => ({ isEditUserProfileModalOpen: false }))
});

useAddUserToOrgModalSlice.ts

export const createAddUserToOrgModalSlice = (set) => ({
    isAddUserToOrgModalOpen: false,
    openAddUserToOrgModal: () => set(() => ({ isAddUserToOrgModalOpen: true })),
    closeAddUserToOrgModal: () => set(() => ({ isAddUserToOrgModalOpen: false }))
});

Store

useModalStore.ts

import create from 'zustand'

export const useModalStore = create((...a) => ({
  ...createEditUserProfileModalSlice(...a),
  ...createAddUserToOrgModalSlice(...a),
}))

Usage

const isEditUserProfileModalOpen = useModalStore((state) => state.isEditUserProfileModalOpen);
const openEditUserProfileModal = useModalStore((state) => state.openEditUserProfileModal);
const closeEditUserProfileModal = useModalStore((state) => state.closeEditUserProfileModal);

Is there an alternative to this pattern that you would recommend?
I ask because any time I need to add a new modal type, I'll need to create a new slice file, with basically the same 3 properties (isOpen, open function and close function), which kinda seems boilerplate-y.


问:
Tkintermapview does not works without window.mainloop function
I am using a tkinter code which uses a while Loop, and thus i cannot use a window.mainloop() function. I want to use tkintermapview library, but it wont show the map unless window.mainloop() is called. Please help me with this.

I tried using tkintermapview's map_widget inside the while loop but it did not help


问:
Wordpress REST API Fetch = Tracking?
I have some question I didn't find an anwser in the internet. I'm buildung an app and therefore I use my Wordpress Website to receive Data with the REST API and JSON. Now I need to now if there is any tracking, when I fetch the data from my site. Because there is a request to my site so I think something has to be tracked or?

Because of the Tracking Policy.

Hope, anybody knows it!

Thx, Eric

I search many websites and read about the REST API of Wordpress but couldn't found an answer.

Title: Wordpress REST API Fetch = Tracking?


问:
unable to show output through innerHTML
```<code>const quote = document.querySelector("#quotes")
const btn = document.querySelector("#quotesBtn")

const quotes = () =>{
const setHeaders = {
    headers: {
        'X-RapidAPI-Key':
        'X-RapidAPI-Host':
        }
    }
    fetch('https://famous-quotes4.p.rapidapi.com/random?category=education&count=1',setHeaders)
     .then(response => response.json())
     .then(data => quote.innerHTML=data)
     .catch(err => err);

}
btn.addEventListener("click", quotes);
quotes();
</code>```
```<code></code>```

I am unable to show the data of API in element tag. Error showing on website [object].

Title: unable to show output through innerHTML

Body:
const quote = document.querySelector("#quotes")
const btn = document.querySelector("#quotesBtn")

const quotes = () =>{
const setHeaders = {
    headers: {
        'X-RapidAPI-Key':
        'X-RapidAPI-Host':
        }
    }
    fetch('https://famous-quotes4.p.rapidapi.com/random?category=education&count=1',setHeaders)
     .then(response => response.json())
     .then(data => quote.innerHTML=data)
     .catch(err => err);

}
btn.addEventListener("click", quotes);
quotes();

I am unable to show the data of API in element tag. Error showing on website [object].


问:
COLAB: Return values from a python script
I am running a python script in colab and would like to then use the outputs of the script in other cells however whenever I try to use them they seem to be undefined.
`

```<code>from google.colab import drive

drive.mount('/content/gdrive')
root_path = 'gdrive/MyDrive/folder
</code>```
```<code>! python /content/gdrive/MyDrive/folder/main.py
</code>```

For example if in the script I have something like:
`

```<code>
def f(i):
    g=i
    return g

if __name__ == "__main__":
    G=[]
    for i in range(0,10):
        g = f(i)
        G.append(g)
    G=pd.DataFrame(G)

</code>```

If I try to print G in colab after running the script then I get that it is undefined.

I tried saving these as csv files this did not work

G.to_csv('filename.csv')

Body:
I am running a python script in colab and would like to then use the outputs of the script in other cells however whenever I try to use them they seem to be undefined.
`

from google.colab import drive

drive.mount('/content/gdrive')
root_path = 'gdrive/MyDrive/folder

! python /content/gdrive/MyDrive/folder/main.py

For example if in the script I have something like:
`

def f(i):
    g=i
    return g

if __name__ == "__main__":
    G=[]
    for i in range(0,10):
        g = f(i)
        G.append(g)
    G=pd.DataFrame(G)

If I try to print G in colab after running the script then I get that it is undefined.

I tried saving these as csv files this did not work

G.to_csv('filename.csv')


问:
2D binned scatter plot in d3.js? Rect bins are not drawn from origin?
I'm trying to make 2D binned scatter plot in d3.js. The idea is when the user selects number of bins n, we get the nxn matrix of bins colored by number of elements inside. I tried to do it with d3.bin(), but the problem is if we have a different scales on x and y axis and these bins are defined by side value which could be different for x and y axis. How can I fix this code to make it work for 2D binning?

```<code>var margin = {top: 40, right: 40, bottom: 40, left: 40},
    w = 380 - margin.left - margin.right,
    h = 380 - margin.top - margin.bottom;
var color = d3.scale.linear()
    .domain([0, 1000])
    .range(["yellow", "darkred"])
    .interpolate(d3.interpolateLab);

var svg = d3.select("body").append("svg")
    .attr("width", w + margin.left + margin.right)
    .attr("height", h + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" +margin.left+ "," +margin.top+ ")");
var points = [];
d3.csv("static/data/data_for_density2d.csv", function(error, data) {
    data.forEach(function(d) {
        d.time = +d.x;
        d.intensity = +d.y;
        points.push([d.time, d.intensity]);
    });
    function split(left, right, parts) {
    var result = [],
        delta = (right - left) / (parts - 1);
    while (left < right) {
        result.push(left);
        left += delta;
    }
    result.push(right);
    return result;
}
    console.log(split(0, d3.max(data, function(d) {return parseFloat(d.x);}), 10));
    console.log(d3.min(data, function(d) { return parseFloat(d.x); }));
    var x = d3.scale.linear()
    .domain(split(0, d3.max(data, function(d) {return parseFloat(d.x);}), 10))
    .range([0, d3.max(data, function(d) {return parseFloat(d.x);})]);
       console.log(x.domain());
    var y = d3.scale.linear()
        .domain([0, d3.max(data, function(d) { return parseFloat(d.y); })])
        .range([h, 0]);

    var yinv = d3.scale.linear()
        .domain([0, d3.max(data, function(d) { return parseFloat(d.y); })])
        .range([0, h]);

    var xAxis = d3.svg.axis()
        .scale(x)
        .orient("bottom");
    var yAxis = d3.svg.axis()
        .scale(y)
        .orient("left");
    console.log(h);
    console.log(parseFloat(h/10));
    var side = 2;
    console.log(w, h);
    var bins = d3.bin()
        .size([d3.max(data, function(d) { return parseFloat(d.x); }), d3.max(data, function(d) { return parseFloat(d.y); })])
        .side(side);
    svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + h + ")")
        .call(xAxis);
    svg.append("g")
        .attr("class", "y axis")
        .call(yAxis);
        console.log(x(side));
    svg.selectAll(".square")
        .data(bins(points))
        .enter().append("rect")
        .attr("class", "square")
        .attr("x", function(d) { return x(d.x); })
        .attr("y", function(d) { return y(d.y)-yinv(side); })
        .attr("width", x(side))
        .attr("height", yinv(side))
        .style("fill", function(d) { return color(d.length); }); });
</code>```

I've tried to adjust the domain by spliting it in 10 parts, where 10 should be number of bins user selected.

UPDATE: I've decided to use d3.rectbin() function based on this example: https://d3-graph-gallery.com/graph/density2d_histogram2d.html
I define sizes of rectangle like this:

```<code>    var numBin=10;
  // Compute the rectbin
  var size = (d3.max(data, function(d) {return parseFloat(d.x);})-d3.min(data, function(d) {return parseFloat(d.x);}))/numBin;
var sizeY=(d3.max(data, function(d) {return parseFloat(d.y);})-d3.min(data, function(d) {return parseFloat(d.y);}))/numBin;
var rectbinData = d3.rectbin()
    .dx(size)
    .dy(sizeY)
    (inputForRectBinning)
</code>```

But rectangles are not drawn from origin of the scatterplot, how do I fix this so whatever number of bins user selects rectangles are drawn from origin of plot? Example of rects not being drawn from origin:

Body:
I'm trying to make 2D binned scatter plot in d3.js. The idea is when the user selects number of bins n, we get the nxn matrix of bins colored by number of elements inside. I tried to do it with d3.bin(), but the problem is if we have a different scales on x and y axis and these bins are defined by side value which could be different for x and y axis. How can I fix this code to make it work for 2D binning?

var margin = {top: 40, right: 40, bottom: 40, left: 40},
    w = 380 - margin.left - margin.right,
    h = 380 - margin.top - margin.bottom;
var color = d3.scale.linear()
    .domain([0, 1000])
    .range(["yellow", "darkred"])
    .interpolate(d3.interpolateLab);

var svg = d3.select("body").append("svg")
    .attr("width", w + margin.left + margin.right)
    .attr("height", h + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" +margin.left+ "," +margin.top+ ")");
var points = [];
d3.csv("static/data/data_for_density2d.csv", function(error, data) {
    data.forEach(function(d) {
        d.time = +d.x;
        d.intensity = +d.y;
        points.push([d.time, d.intensity]);
    });
    function split(left, right, parts) {
    var result = [],
        delta = (right - left) / (parts - 1);
    while (left < right) {
        result.push(left);
        left += delta;
    }
    result.push(right);
    return result;
}
    console.log(split(0, d3.max(data, function(d) {return parseFloat(d.x);}), 10));
    console.log(d3.min(data, function(d) { return parseFloat(d.x); }));
    var x = d3.scale.linear()
    .domain(split(0, d3.max(data, function(d) {return parseFloat(d.x);}), 10))
    .range([0, d3.max(data, function(d) {return parseFloat(d.x);})]);
       console.log(x.domain());
    var y = d3.scale.linear()
        .domain([0, d3.max(data, function(d) { return parseFloat(d.y); })])
        .range([h, 0]);

    var yinv = d3.scale.linear()
        .domain([0, d3.max(data, function(d) { return parseFloat(d.y); })])
        .range([0, h]);

    var xAxis = d3.svg.axis()
        .scale(x)
        .orient("bottom");
    var yAxis = d3.svg.axis()
        .scale(y)
        .orient("left");
    console.log(h);
    console.log(parseFloat(h/10));
    var side = 2;
    console.log(w, h);
    var bins = d3.bin()
        .size([d3.max(data, function(d) { return parseFloat(d.x); }), d3.max(data, function(d) { return parseFloat(d.y); })])
        .side(side);
    svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + h + ")")
        .call(xAxis);
    svg.append("g")
        .attr("class", "y axis")
        .call(yAxis);
        console.log(x(side));
    svg.selectAll(".square")
        .data(bins(points))
        .enter().append("rect")
        .attr("class", "square")
        .attr("x", function(d) { return x(d.x); })
        .attr("y", function(d) { return y(d.y)-yinv(side); })
        .attr("width", x(side))
        .attr("height", yinv(side))
        .style("fill", function(d) { return color(d.length); }); });

I've tried to adjust the domain by spliting it in 10 parts, where 10 should be number of bins user selected.

UPDATE: I've decided to use d3.rectbin() function based on this example: https://d3-graph-gallery.com/graph/density2d_histogram2d.html
I define sizes of rectangle like this:

    var numBin=10;
  // Compute the rectbin
  var size = (d3.max(data, function(d) {return parseFloat(d.x);})-d3.min(data, function(d) {return parseFloat(d.x);}))/numBin;
var sizeY=(d3.max(data, function(d) {return parseFloat(d.y);})-d3.min(data, function(d) {return parseFloat(d.y);}))/numBin;
var rectbinData = d3.rectbin()
    .dx(size)
    .dy(sizeY)
    (inputForRectBinning)

But rectangles are not drawn from origin of the scatterplot, how do I fix this so whatever number of bins user selects rectangles are drawn from origin of plot? Example of rects not being drawn from origin:


问:
Visualize graphically data from a YAML file, stored in S3 bucket
I've used AWS S3 bucket to store API data, saved in YAML format. Now I'd want to represent some data graphically(like widgets, gauges, etc. containing data from my yaml file). I've read that AWS managed Grafana could do something similar, but can I do this without having an SQL? If not with Grafana, then what else could I use?
I'd like to specify that if possible, I want to solve this without having costs.</p>


问:
Excel, error when using nested filter Formula if the array does have any data that match filter criteria
So, I have a nested Filter formula in excel. I am trying to sort out  data in a array based on multiple criteria. I need to account if the formula does not return nothing.
Here is the syntax:

=FILTER(array, (include)(include)(include)(include)(include), [if_empty])

Here is my starting  code:

=FILTER(Home!$C$1:$L$2000,(Home!$C$1:$C$2000<>"")(Home!$I1:$I$2000=SundayByShift!$A$1)(Home!$J$1:$J$2000=SundayByShift!$B$1)(Home!$L$1:$L$2000=SundayByShift!$C$1)(Home!$F$1:$F$2000=SundayByShift!$D$1),"Empty")

This work correctly.  So then I apply a second filter to give me what I need for non-adjacent columns

=FILTER(FILTER(Home!$C$1:$L$2000,(Home!$C$1:$C$2000<>"")(Home!$I1:$I$2000=SundayByShift!$A$1)(Home!$J$1:$J$2000=SundayByShift!$B$1)(Home!$L$1:$L$2000=SundayByShift!$C$1)(Home!$F$1:$F$2000=SundayByShift!$D$1),"Empty"),{1,1,0,1,0,1,0,0,0,0})

It returns a #CALC! error.

If I remove the argument [if_empty] or "Empty"
=FILTER(FILTER(Home!$C$1:$L$2000,(Home!$C$1:$C$2000<>"")(Home!$I1:$I$2000=SundayByShift!$A$1)(Home!$J$1:$J$2000=SundayByShift!$B$1)(Home!$L$1:$L$2000=SundayByShift!$C$1)(Home!$F$1:$F$2000=SundayByShift!$D$1)),{1,1,0,1,0,1,0,0,0,0})

then it work for only if the formula returns true.

Thank you


问:
Output cards, swift
I am learning swift. I'm getting data from firebase, but I don't understand how to output cards with data now. For example, one per page with a horizontal scroll, or a table.
`

```<code>func itemsList(){
            database.collection("catalog")
                .getDocuments { (snapshot, error) in
                    self.items.removeAll()

                    if let snapshot {
                        for document in snapshot.documents{
                            let docData = document.data()
                            let title: String = docData["title"] as? String ?? ""
                            let imageUrl: String = docData["imageUrl"] as? String ?? ""
                            let description: String = docData["description"] as? String ?? ""
                            let price: Int = docData["price"] as? Int ?? 0

                            let item: Item = Item(title: title, price: price, description: description, imageUrl: imageUrl)

                            self.items.append(item)
                        }
                    }

                    let itemImageView:UIImageView = UIImageView()
                    itemImageView.contentMode = UIView.ContentMode.scaleAspectFit
                    itemImageView.frame.size.width = 150
                    itemImageView.frame.size.height = 150
                    guard let imageUrlnew:URL = URL(string: self.items[0].imageUrl) else {
                                return
                            }
                    guard let imageData = try? Data(contentsOf: imageUrlnew) else {
                      return
                    }
                    itemImageView.image = UIImage(data: imageData)
                    self.view.addSubview(itemImageView)

                }
        }
</code>```

`

I found code examples, but there you need to override collectionView. I have async, so I can't do it. Can you help me with a solution?

Title: Output cards, swift

Body:
I am learning swift. I'm getting data from firebase, but I don't understand how to output cards with data now. For example, one per page with a horizontal scroll, or a table.
`

func itemsList(){
            database.collection("catalog")
                .getDocuments { (snapshot, error) in
                    self.items.removeAll()

                    if let snapshot {
                        for document in snapshot.documents{
                            let docData = document.data()
                            let title: String = docData["title"] as? String ?? ""
                            let imageUrl: String = docData["imageUrl"] as? String ?? ""
                            let description: String = docData["description"] as? String ?? ""
                            let price: Int = docData["price"] as? Int ?? 0

                            let item: Item = Item(title: title, price: price, description: description, imageUrl: imageUrl)

                            self.items.append(item)
                        }
                    }

                    let itemImageView:UIImageView = UIImageView()
                    itemImageView.contentMode = UIView.ContentMode.scaleAspectFit
                    itemImageView.frame.size.width = 150
                    itemImageView.frame.size.height = 150
                    guard let imageUrlnew:URL = URL(string: self.items[0].imageUrl) else {
                                return
                            }
                    guard let imageData = try? Data(contentsOf: imageUrlnew) else {
                      return
                    }
                    itemImageView.image = UIImage(data: imageData)
                    self.view.addSubview(itemImageView)

                }
        }

`

I found code examples, but there you need to override collectionView. I have async, so I can't do it. Can you help me with a solution?


问:
Virtual scroll in Multiple NG2-Chart in Mat-cards , Display Loader until the data is attached
So I have around 100 Mat-Cards on screen , each one containing one NG2 doughnut chart.
This initially gave me performance issue as it took more than a minute to load.
So I used cdk-virtual-scroll to load charts on the run.
The performance is tough better but the scroll is not smooth. Also Till the time it load next sets of data, the screen shows an empty space. I want to display a loader in it but not sure How can I get the property that tell me the charts are still getting loaded and not completed for that scroll index.

welcoming any better approach suggestions!!


问:
Python script works on one setup but fails to import module on another setup
I have been searching the web from any direction to try and find a reasonable idea to why my problem happening.

Important to say, the code is in a shared location that both machines can access with full permissions
I'll take you through it but first I'll share the way my repo is built:

```<code>my_repo
├── installations
│   ├── my_install_script.py
├── topology
│   ├── common_topology.py
├── utils
│   ├── boot_utils.py
│   ├── other_utils.py
</code>```

The flow is:

my_install_script.py is been called, imports boot_utils.py
then from within boot_utils.py I import 2 more modules like that:

```<code>from utils.other_utils import foo, goo, boo
import topology.common_topology as resources
</code>```

My issue that I can't seems to put my finger on:

When running this from 1 machine, the my_install_script.py works great and runs till the end.
When running it from another machine, I am getting exceptions because python fails to import topology.common_topology with "ModuleNotFoundError: No module named 'topology.common_topology'" Error.

I know, it makes no sense.

Even using sys.path.insert(0,path to my_repo) before the second import, it is still failing.

I've been trying using different sys.path.insert, but I don't get lucky to make this work.
But it should not take this effort since I've been using the same code just from 2 different machines

Body:
I have been searching the web from any direction to try and find a reasonable idea to why my problem happening.

Important to say, the code is in a shared location that both machines can access with full permissions
I'll take you through it but first I'll share the way my repo is built:

my_repo
├── installations
│   ├── my_install_script.py
├── topology
│   ├── common_topology.py
├── utils
│   ├── boot_utils.py
│   ├── other_utils.py

The flow is:

my_install_script.py is been called, imports boot_utils.py
then from within boot_utils.py I import 2 more modules like that:

from utils.other_utils import foo, goo, boo
import topology.common_topology as resources

My issue that I can't seems to put my finger on:

When running this from 1 machine, the my_install_script.py works great and runs till the end.
When running it from another machine, I am getting exceptions because python fails to import topology.common_topology with "ModuleNotFoundError: No module named 'topology.common_topology'" Error.

I know, it makes no sense.

Even using sys.path.insert(0,path to my_repo) before the second import, it is still failing.

I've been trying using different sys.path.insert, but I don't get lucky to make this work.
But it should not take this effort since I've been using the same code just from 2 different machines


问:
Photometric Stereo for textile images for 3D structure reconstruction
I am currently working with the Photo-metric Stereo system to reconstruct the surface of a textile sample. I currently have a dataset containing 8 images of the same textile taken under different light conditions. A sample of an image is shown below.

Furthermore, through the VFX Details Capture software I was able to generate the .txt file containing the directions of the light source thanks to the calibration of the images of a sphere (example below).

I open this topic to understand better how to generate the albedo, the normal and the normal image.

I leave a link in a paper which explains what I would like to recreate.


问:
Thymeleaf & DynamoDB & Spring - How can I get a true or false value saved into database using checkbox?
I am relatively new to Spring and would like my user to be able to save the true or false value into the DynamoDB table. It should come from the class working together with Thymeleaf form. This form has a checkbox in it which supposed to be true (checked) or false (unchecked). The issue is that each time I try to do it with th:checked it only saves false into the database, whereas th:field gives the "Whitelabel error page" in AWS Elastic Beanstalk.

Student (shorter version):

```<code>public class Student {
    private boolean isPresent;

    ///Getters.
    public boolean isPresent() {return isPresent;}

    //Setters.
    public void setPresent(boolean isPresent) {this.isPresent = isPresent;}
}
</code>```

StudentItems (shorter version):

```<code>@DynamoDbBean
public class StudentItems {
    private boolean isPresent;

    //Constructor.
    public StudentItems()
    {
    }

    ///Getters.
    public boolean isPresent() {return isPresent;}

    //Setters.
    public void setPresent(boolean isPresent) {this.isPresent = isPresent;}
}
</code>```

StudentController:

```<code>@Controller
public class StudentController {

    @Autowired
    private DynamoDBEnhanced dde;

    @Autowired
    private SMSNotification msg;

    @GetMapping("/")
    public String studentTrackForm(Model model) {
        model.addAttribute("student", new Student());
        return "student";
    }

    @PostMapping("/student")
    public String studentSubmit(@ModelAttribute Student student) {

        //Stores data in an Amazon DynamoDB table.
        dde.insertDynamoItem(student);

        //Sends a notification to the number specified about
        //newly added student.
        msg.sendMessage(student.getStudentName(),
                student.getStudentSurname(),
                student.getStudentID(),
                student.getStudentYear(),
                student.isPresent());

        return "result";
    }
}
</code>```

HTML form page (shorter version):

```<code><form action="#" th:action="@{/student}" th:object="${student}" method="post">
    <div class="form-group">
        <p>Student ID: <input type="text"  class="form-control" th:field="*{studentID}" /></p>
    </div>

    <div class="form-group">
        <p>Present:<input type="checkbox" class="form-control" th:checked="*{isPresent}" /></p>
    </div>

    <p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>

</form>
</code>```

DynamoDB table result:
DynamoDB table result

I have already tried to use:

```<code>@DynamoDBTyped(DynamoDBAttributeType.BOOL)
@DynamoDBAttribute(attributeName = "value")
</code>```

and the many related links such as the one below but nothing seems to work unless I have missed an important step:
Thymeleaf - How to add checked attribute to input conditionally

Please let me know if you know of any solution using either boolean or Boolean and the Thymeleaf form. In another case, I will just try to solve this issue using JavaScript (would prefer not to due to project specs).

Thank you in advance.

Body:
I am relatively new to Spring and would like my user to be able to save the true or false value into the DynamoDB table. It should come from the class working together with Thymeleaf form. This form has a checkbox in it which supposed to be true (checked) or false (unchecked). The issue is that each time I try to do it with th:checked it only saves false into the database, whereas th:field gives the "Whitelabel error page" in AWS Elastic Beanstalk.

Student (shorter version):

public class Student {
    private boolean isPresent;

    ///Getters.
    public boolean isPresent() {return isPresent;}

    //Setters.
    public void setPresent(boolean isPresent) {this.isPresent = isPresent;}
}

StudentItems (shorter version):

@DynamoDbBean
public class StudentItems {
    private boolean isPresent;

    //Constructor.
    public StudentItems()
    {
    }

    ///Getters.
    public boolean isPresent() {return isPresent;}

    //Setters.
    public void setPresent(boolean isPresent) {this.isPresent = isPresent;}
}

StudentController:

@Controller
public class StudentController {

    @Autowired
    private DynamoDBEnhanced dde;

    @Autowired
    private SMSNotification msg;

    @GetMapping("/")
    public String studentTrackForm(Model model) {
        model.addAttribute("student", new Student());
        return "student";
    }

    @PostMapping("/student")
    public String studentSubmit(@ModelAttribute Student student) {

        //Stores data in an Amazon DynamoDB table.
        dde.insertDynamoItem(student);

        //Sends a notification to the number specified about
        //newly added student.
        msg.sendMessage(student.getStudentName(),
                student.getStudentSurname(),
                student.getStudentID(),
                student.getStudentYear(),
                student.isPresent());

        return "result";
    }
}

HTML form page (shorter version):

<form action="#" th:action="@{/student}" th:object="${student}" method="post">

Student ID: <input type="text"  class="form-control" th:field="*{studentID}" />

Present:<input type="checkbox" class="form-control" th:checked="*{isPresent}" />

<input type="submit" value="Submit" /> <input type="reset" value="Reset" />

</form>

DynamoDB table result:
DynamoDB table result

I have already tried to use:

@DynamoDBTyped(DynamoDBAttributeType.BOOL)
@DynamoDBAttribute(attributeName = "value")

and the many related links such as the one below but nothing seems to work unless I have missed an important step:
Thymeleaf - How to add checked attribute to input conditionally

Please let me know if you know of any solution using either boolean or Boolean and the Thymeleaf form. In another case, I will just try to solve this issue using JavaScript (would prefer not to due to project specs).

Thank you in advance.


问:
Unity Camera Rendering
enter image description here

The camera is looking at the character, but there is an object in front of them that makes it invisible.

At this time, I do not know well about the technique to erase the object in front.
Hmm... I also thought about using a raycast to make the object in front disappear.
However, if the map assets are not separated, they are combined into one, or if they are divided into small and small pieces, they cannot be inactivated correctly.
So I heard in a previous lecture that shaders could be used to solve this. But I don't know how to implement it. Thank you.

Title: Unity Camera Rendering


问:
CObject pointer is initialized null when call
When I call a code

```<code>CObject *ptr;
</code>```

From managed code through interop the CObject pointer is initialized with NULL or undefined value. However when I execute it in native code itself, it is getting initialized properly. Why is that??

ContentLicense: CC BY-SA 3.0

Body:
When I call a code

CObject *ptr;

From managed code through interop the CObject pointer is initialized with NULL or undefined value. However when I execute it in native code itself, it is getting initialized properly. Why is that??


问:
cumsum as UDF in xlwings for calculating with high precision
I need to apply cumsum as UDF in xlwings similar to this one below, which works fine however only for float data type.

```<code>import pandas as pd
@xw.func
@xw.arg('x', pd.DataFrame, index=False, header=False)
@xw.ret(index=False, header=False)
def xl_Correl_1(x):
    return x.cumsum()
</code>```

I need to do this cumulative sum function on numbers like this:

```<code>1.41421356237309504880168872421
1.41421356237309504880168872421
2.82842712474619009760337744842
4.24264068711928514640506617263
</code>```

For highly precise calculation I am using python library "decimal". I thought of following code:

```<code>import decimal
from decimal import Decimal
decimal.getcontext().prec = 30

@xw.func
@xw.arg('x', pd.DataFrame.apply(Decimal), index=False, header=False)
@xw.ret(index=False, header=False)
def xl_Correl_2(x):
    return str(x.cumsum())
</code>```

I am aware that this is is quite unusual requirement as not everyone deals with high precision numbers and xlwings. I would appreciate your feedback.

Body:
I need to apply cumsum as UDF in xlwings similar to this one below, which works fine however only for float data type.

import pandas as pd
@xw.func
@xw.arg('x', pd.DataFrame, index=False, header=False)
@xw.ret(index=False, header=False)
def xl_Correl_1(x):
    return x.cumsum()

I need to do this cumulative sum function on numbers like this:

1.41421356237309504880168872421
1.41421356237309504880168872421
2.82842712474619009760337744842
4.24264068711928514640506617263

For highly precise calculation I am using python library "decimal". I thought of following code:

import decimal
from decimal import Decimal
decimal.getcontext().prec = 30

@xw.func
@xw.arg('x', pd.DataFrame.apply(Decimal), index=False, header=False)
@xw.ret(index=False, header=False)
def xl_Correl_2(x):
    return str(x.cumsum())

I am aware that this is is quite unusual requirement as not everyone deals with high precision numbers and xlwings. I would appreciate your feedback.


问:
pairwise comparison of categorical groups
I have proportion data for 10 behaviours for morning, day, and evening and the initial beta regression shows that there is a difference in the proportion of behaviours depending on time of day. I'm now trying to find a test that will let me do a pairwise comparison of these three times to see which behavoiurs are different and driving this result. Ie. morning rest is 0.8, day is 0.5, and night is 0.9, feed is 0.7 morning, 0.69 day, and 0.72 night (these aren't the exact numbers but just to give an idea of what my day looks like).

thanks,

So far I have tried an anova and a manova, but having to link each proportion to the respective behaviours seems to cause these tests to fail as it doesn't link these variables properly.


问:
Wrong UI on real device (IOS) flutter app
I have problems with the UI on real device (IOS) but in the emulator (same iphone) the UI is right. The app is developed with Flutter. The problem is only in iOS

Iphone SE 1st Generation (Emulator device):

Iphone SE 1st Generation (Real device):

Any idea of this behavior?

Edit:

I tried with real device(connected by usb) and is working correctly. The problem is when I use the app in TestFlight.

Any idea? I don't know what to do


问:
unable to use Subroutine during optimization job in Abaqus

Hi there,I’ve got a problem during using the optimization module in abaqus.
I use the  utractload subroutine during static analyzing successfully, while when I want to topology optimize the same model using the optimiztion module and submit the optimization job, an error will come out, says ‘USER SUBROUTINE UTRACLOAD IS MISSING’.

I've maked sure that it's not the problem about the program. Because when I don't use the subroutine, the optimiztion job will run succesfully.
I think the key to the question is how to add a subroutine into the optimization job.But I don't know how.There is no box to insert the subroutine file and even no hint for asking for the subroutine, it just gives the error out.
I’ve searched and thought about how to solve it for a long time, but I still can’t find out the way.
I've already checked the .inp file, while there is no way to add subroutine in it for me.
I also tried to find out how the Tosca which controls the optimization module combined in Abaqus works and change some .bat files. But it still not work.
Help me, plz.Thank u anyway for reading.


问:
HTTPS error, what is happening? Heroku Deployed Site
I am new to website deployment with SSL cert.

So my issue is if I type into chrome - www.example.com , it comes back as unsecure, but if i type:
https://www.example.com it comes back as secure.

I deployed the site with Heroku, and have my domain with GoDaddy and as long as I type https:// before the www. it is fully secure, if I dont put the https it is not.

I am sure I am missing some code somewhere, or I need to divert all www. requets to https.

How do I do this? With most sites it doesn't matter if you type www. it will automatically direct to the HTTPS version.

Thank you in advance.