问:
how to get value from a web site using beautifulsoap in python?
Im trying to get words with headers from web site with beautifulsoap in python but I couldnt do it.
I'm trying to make a german dictionary.

Here is the site

https://almancakonulari.com/a1-seviye-almanca-kelimeler/#gsc.tab=0

I'm trying to pull data from the word Hallo, but h3 tags come in between, I want to take these tags and use them as identifiers, so I'm trying to create a data set like this.

```<code> [
     {
      "zahlen":[
        {
            "index": "1.",
            "word": "Hallo",
            "meaning": "Merhaba"
        },
        {
            "index": "2.",
            "word": "Herzlich willkommen",
            "meaning": "Hoş geldiniz"
        },
        {
            "index": "3.",
            "word": "Auf Wiedersehen",
            "meaning": "Hoşça kalın"
        }
      ]
     }
    ]
</code>```

hear is my code but my code doesnt work properly.

```<code>import requests
from bs4 import BeautifulSoup
import pandas as pd
import json

myList = [
    "jeden Tag",
    "Zahlen",
    "Tage – Monate",
    "Jahreszeiten-Farben",
    "Am Flughafen",
    "Im Hotel",
    "Im Restaurant",
    "Transport",
    "Zug",
    "Taxi",
    "Im weg",
    "Theater",
    "Kleidungsladen",
    "Elektrofachgeschäft",
    "Kosmetika",
    "Coiffeur",
    "Buchhandlung",
    "Post",
    "In der Arztpraxis",
    "Polizei",
    "Sport",
    "Zubehör ",
    "Wichtige Verben  Önemli Fiiller",
    "Im Supermarkt  Süpermarkette",
    "Verkehrszeichen",
    "Almanca Tur Kelimeleri"
]

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36'}
url = "https://almancakonulari.com/a1-seviye-almanca-kelimeler/#gsc.tab=0"

result = requests.get(url)
soup = BeautifulSoup(result.text, 'html.parser')
div = soup.find('div', class_='entry-content clearfix')

array = []
list={}

i=0
for h3_tag in range(len(myList)):

    list[myList[h3_tag]] = []
    tempObj = {
     "identifier": myList[h3_tag]
    }
    tempArr = []
    words = div.find_all('table',class_='table table-bordered')[i]
    for word in words:
        for word1 in word.find_all('tbody'):
            rows = word1.find_all('tr')
            for row in rows:
                each_word = row.find_all('td')
                tempArr.append({
                    "index": each_word[0].string,
                    "word": each_word[1].string,
                    "meaning": each_word[2].string
                })
    tempObj["words"] = tempArr
    array.append(tempObj)
    i+=1

with open('almancaKelimeler1.json', 'w', encoding='utf-8') as f:
    json.dump(array, f, ensure_ascii=False, indent=4)
</code>```

how can I do this ?

when i run the current code i get this error:

AttributeError: 'NavigableString' object has no attribute 'find_all'. Did you mean: '_find_all'?

but when I remove

words = div.find_all('table',class_='table table-bordered')[i]

for example like this

words = div.find_all('table',class_='table table-bordered')

in this case there is no error but it brings all the words for each identifier. i.e. it needs to fetch 1000 words in total but returns 1000 words for each title or identifier

Body:
Im trying to get words with headers from web site with beautifulsoap in python but I couldnt do it.
I'm trying to make a german dictionary.

Here is the site

https://almancakonulari.com/a1-seviye-almanca-kelimeler/#gsc.tab=0

I'm trying to pull data from the word Hallo, but h3 tags come in between, I want to take these tags and use them as identifiers, so I'm trying to create a data set like this.

 [
     {
      "zahlen":[
        {
            "index": "1.",
            "word": "Hallo",
            "meaning": "Merhaba"
        },
        {
            "index": "2.",
            "word": "Herzlich willkommen",
            "meaning": "Hoş geldiniz"
        },
        {
            "index": "3.",
            "word": "Auf Wiedersehen",
            "meaning": "Hoşça kalın"
        }
      ]
     }
    ]

hear is my code but my code doesnt work properly.

import requests
from bs4 import BeautifulSoup
import pandas as pd
import json

myList = [
    "jeden Tag",
    "Zahlen",
    "Tage – Monate",
    "Jahreszeiten-Farben",
    "Am Flughafen",
    "Im Hotel",
    "Im Restaurant",
    "Transport",
    "Zug",
    "Taxi",
    "Im weg",
    "Theater",
    "Kleidungsladen",
    "Elektrofachgeschäft",
    "Kosmetika",
    "Coiffeur",
    "Buchhandlung",
    "Post",
    "In der Arztpraxis",
    "Polizei",
    "Sport",
    "Zubehör ",
    "Wichtige Verben  Önemli Fiiller",
    "Im Supermarkt  Süpermarkette",
    "Verkehrszeichen",
    "Almanca Tur Kelimeleri"
]

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36'}
url = "https://almancakonulari.com/a1-seviye-almanca-kelimeler/#gsc.tab=0"

result = requests.get(url)
soup = BeautifulSoup(result.text, 'html.parser')
div = soup.find('div', class_='entry-content clearfix')

array = []
list={}

i=0
for h3_tag in range(len(myList)):

    list[myList[h3_tag]] = []
    tempObj = {
     "identifier": myList[h3_tag]
    }
    tempArr = []
    words = div.find_all('table',class_='table table-bordered')[i]
    for word in words:
        for word1 in word.find_all('tbody'):
            rows = word1.find_all('tr')
            for row in rows:
                each_word = row.find_all('td')
                tempArr.append({
                    "index": each_word[0].string,
                    "word": each_word[1].string,
                    "meaning": each_word[2].string
                })
    tempObj["words"] = tempArr
    array.append(tempObj)
    i+=1

with open('almancaKelimeler1.json', 'w', encoding='utf-8') as f:
    json.dump(array, f, ensure_ascii=False, indent=4)

how can I do this ?

when i run the current code i get this error:

AttributeError: 'NavigableString' object has no attribute 'find_all'. Did you mean: '_find_all'?

but when I remove

words = div.find_all('table',class_='table table-bordered')[i]

for example like this

words = div.find_all('table',class_='table table-bordered')

in this case there is no error but it brings all the words for each identifier. i.e. it needs to fetch 1000 words in total but returns 1000 words for each title or identifier


来源: stackexchange

问:
How to render a custom action results from controller in views using Rails 7 without refreshing the page?
I have this a custom action in Task controller, which has if else

statements and returns Api calls from Safe browsing api, which I need to render to users

in index.html.erb without refreshing the page. I've tried Ajax but it doesn't seem to

work correctly.In addition, I've tried to search and follow some Hotwire and Turbo

tutorials but they seem to solve complicated problems unlike my problem.

My problem and solution are simple, a user submits link to the server to be checked by

Google Safe Browsing API and return results back to the user rendered in the same

page without refreshing. I currently have them rendered in a different page by using

for example

```<code>render plain: "" and return
</code>```

Finally, this's my code and I need a simple solution to render the custom action results

to users without refreshing the page.

This's check_url action in tasks_controller.rb

```<code>def check_url
    @id = params[:id]
    @result = params[:result]
    if params[:link].present?
      api_key = ENV[""]
      # Set up the request parameters
      url = params[:link]

      formatted_url = canonicalize_url(url)

      threat_types = ["MALWARE", "THREAT_TYPE_UNSPECIFIED", "SOCIAL_ENGINEERING", "UNWANTED_SOFTWARE", "POTENTIALLY_HARMFUL_APPLICATION"]
      platform_types = ["ANY_PLATFORM"]
      body = {
        client: {
          clientId: api_key,
          clientVersion: "1.0.0",
        },
        threatInfo: {
          threatTypes: threat_types,
          platformTypes: platform_types,
          threatEntryTypes: %w[URL THREAT_ENTRY_TYPE_UNSPECIFIED EXECUTABLE],
          threatEntries: [
            { url: formatted_url },
          ],
        },
      }

      # Set up the request headers
      headers = {
        "Content-Type" => "application/json",
      }

      # Make the request to the Safe Browsing API
      response = HTTP.post(
        "https://safebrowsing.googleapis.com/v4/threatMatches:find?key=",
        json: body,
        headers: headers,
      )

      # Check the response
      if response.code == 200
        data = JSON.parse(response.body)
        puts JSON.pretty_generate(data)

        @result = response.body
        if data["matches"].try(:empty?)
          render plain: "The URL is safe" and return
        else
          render plain: "The URL is not safe" and return
        end
      else
        render plain: "An error occurred"
      end
    else
      puts "link variable is empty"
    end

    puts "Response code: #{response.code}"
    puts "Response body: #{response.body}"

    puts "Request parameters: #{body}"
    puts "Request headers: #{headers}"
  end

  private

  def task_params
    params.require(:task).permit(:link, :result)
  end

end
</code>```

This's the submission form in _form.html.erb

```<code><%= form_tag("/check_url", method: "post") do %>
  <%= label_tag(:link, "Enter a link:") %>
  <%= text_field_tag(:link) %>
  <%= submit_tag("Submit") %>
<% end %>
</code>```

This's index.html.erb

```<code><% if notice.present? %>
  <p class="py-2 px-3 bg-green-50 mb-5 text-green-500 font-medium rounded-lg inline-block" id="notice">
    <%= notice %>
  </p>
<% end %>
<h1 class="font-bold text-2xl">Task Manager</h1>
<div class="mt-4">
  <%= render "form", task: @task %>
  <%= render 'tasks/check_url' %>
</div>
</code>```

Thank you all and please ask any questions or requests, I'm new to Ruby on

Rails and want to grasp it.

ContentLicense: CC BY-SA 4.0

Body:
I have this a custom action in Task controller, which has if else

statements and returns Api calls from Safe browsing api, which I need to render to users

in index.html.erb without refreshing the page. I've tried Ajax but it doesn't seem to

work correctly.In addition, I've tried to search and follow some Hotwire and Turbo

tutorials but they seem to solve complicated problems unlike my problem.

My problem and solution are simple, a user submits link to the server to be checked by

Google Safe Browsing API and return results back to the user rendered in the same

page without refreshing. I currently have them rendered in a different page by using

for example

render plain: "" and return

Finally, this's my code and I need a simple solution to render the custom action results

to users without refreshing the page.

This's check_url action in tasks_controller.rb

def check_url
    @id = params[:id]
    @result = params[:result]
    if params[:link].present?
      api_key = ENV[""]
      # Set up the request parameters
      url = params[:link]

      formatted_url = canonicalize_url(url)

      threat_types = ["MALWARE", "THREAT_TYPE_UNSPECIFIED", "SOCIAL_ENGINEERING", "UNWANTED_SOFTWARE", "POTENTIALLY_HARMFUL_APPLICATION"]
      platform_types = ["ANY_PLATFORM"]
      body = {
        client: {
          clientId: api_key,
          clientVersion: "1.0.0",
        },
        threatInfo: {
          threatTypes: threat_types,
          platformTypes: platform_types,
          threatEntryTypes: %w[URL THREAT_ENTRY_TYPE_UNSPECIFIED EXECUTABLE],
          threatEntries: [
            { url: formatted_url },
          ],
        },
      }

      # Set up the request headers
      headers = {
        "Content-Type" => "application/json",
      }

      # Make the request to the Safe Browsing API
      response = HTTP.post(
        "https://safebrowsing.googleapis.com/v4/threatMatches:find?key=",
        json: body,
        headers: headers,
      )

      # Check the response
      if response.code == 200
        data = JSON.parse(response.body)
        puts JSON.pretty_generate(data)

        @result = response.body
        if data["matches"].try(:empty?)
          render plain: "The URL is safe" and return
        else
          render plain: "The URL is not safe" and return
        end
      else
        render plain: "An error occurred"
      end
    else
      puts "link variable is empty"
    end

    puts "Response code: #{response.code}"
    puts "Response body: #{response.body}"

    puts "Request parameters: #{body}"
    puts "Request headers: #{headers}"
  end

  private

  def task_params
    params.require(:task).permit(:link, :result)
  end

end

This's the submission form in _form.html.erb

<%= form_tag("/check_url", method: "post") do %>
  <%= label_tag(:link, "Enter a link:") %>
  <%= text_field_tag(:link) %>
  <%= submit_tag("Submit") %>
<% end %>

This's index.html.erb

<% if notice.present? %>

    <%= notice %>

<% end %>

Task Manager

  <%= render "form", task: @task %>
  <%= render 'tasks/check_url' %>

Thank you all and please ask any questions or requests, I'm new to Ruby on

Rails and want to grasp it.


问:
I like to add files from all my Sharepoint sites with share plum
this is my code:

```<code>import logging
import os
from dotenv import load_dotenv

load_dotenv('dic.env')
httpSite = os.getenv('httpSite')
emaila = os.getenv('emaila')
password = os.getenv('password')

from shareplum import Site
from shareplum import Office365
from datetime import datetime

# Configurez le journal pour enregistrer les messages dans un fichier
current_time = str(datetime.now().strftime('%Y-%m-%d_%H-%M-%S'))
logging.basicConfig(level=logging.INFO, filename='download_{}.log'.format(current_time), filemode='w', format='%(asctime)s - %(message)s')

# Vous devez d'abord vous connecter à votre compte SharePoint
try:
    authcookie = Office365(httpSite, username=emaila, password=password).GetCookies()
    logging.info('Connecté avec succès à SharePoint')
except Exception as e:
    logging.error('Erreur lors de la connexion à SharePoint: %s', e)

site = Site(httpSite, authcookie=authcookie)

# Récupérez la liste de tous les fichiers de la racine du site
root_folder = site.ListFolder('Shared%20Documents')
all_files = root_folder.GetListItems()

# Fonction récursive pour télécharger tous les fichiers d'un dossier et de ses sous-dossiers
def download_files(folder, local_path):
    # Créez le répertoire local s'il n'existe pas encore
    if not os.path.exists(local_path):
        os.makedirs(local_path)

    # Récupérez la liste de tous les fichiers dans ce dossier
    files = folder.GetListItems()

    # Pour chaque fichier, téléchargez-le sur votre ordinateur local
    for file in files:
        if not file['FileLeafRef'].endswith('.cab'):
            try:
                file_content = site.GetFile(file['FileRef']).content
                open(os.path.join(local_path, file['FileLeafRef']), 'wb').write(file_content)
                logging.info('Téléchargement réussi: %s', file['FileLeafRef'])
            except Exception as e:
                logging.error('Erreur lors du téléchargement de %s: %s', file['FileLeafRef'], e)

    # Récupérez la liste de tous les sous-dossiers de ce dossier
    sub_folders = folder.GetFolders()

    # Pour chaque sous-dossier, appelez la fonction récursivement
    for sub_folder in sub_folders:
        download_files(sub_folder, os.path.join(local_path, sub_folder.name))

# Appelez la fonction pour télécharger tous les fichiers de la racine du site
download_files(root_folder, '.')
</code>```

I get an error on

```<code>root_folder = site.ListFolder('Shared%20Documents')
</code>```

in fact site is an object 'share plum.site._Site2007' and my variable httpSite has it's value set to https://mysharepoint.sharepoint.com

I want to download all of the files from all of my sites but it doesn't seem to be working as I did not specify /sites/sitename part within my variable httpSite.

So I would like to retrieve a list of my sites and to execute the above code for all my sites...

Error is

AttributeError: '_Site2007' object has no attribute 'ListFolder'

Body:
this is my code:

import logging
import os
from dotenv import load_dotenv

load_dotenv('dic.env')
httpSite = os.getenv('httpSite')
emaila = os.getenv('emaila')
password = os.getenv('password')

from shareplum import Site
from shareplum import Office365
from datetime import datetime

# Configurez le journal pour enregistrer les messages dans un fichier
current_time = str(datetime.now().strftime('%Y-%m-%d_%H-%M-%S'))
logging.basicConfig(level=logging.INFO, filename='download_{}.log'.format(current_time), filemode='w', format='%(asctime)s - %(message)s')

# Vous devez d'abord vous connecter à votre compte SharePoint
try:
    authcookie = Office365(httpSite, username=emaila, password=password).GetCookies()
    logging.info('Connecté avec succès à SharePoint')
except Exception as e:
    logging.error('Erreur lors de la connexion à SharePoint: %s', e)

site = Site(httpSite, authcookie=authcookie)

# Récupérez la liste de tous les fichiers de la racine du site
root_folder = site.ListFolder('Shared%20Documents')
all_files = root_folder.GetListItems()

# Fonction récursive pour télécharger tous les fichiers d'un dossier et de ses sous-dossiers
def download_files(folder, local_path):
    # Créez le répertoire local s'il n'existe pas encore
    if not os.path.exists(local_path):
        os.makedirs(local_path)

    # Récupérez la liste de tous les fichiers dans ce dossier
    files = folder.GetListItems()

    # Pour chaque fichier, téléchargez-le sur votre ordinateur local
    for file in files:
        if not file['FileLeafRef'].endswith('.cab'):
            try:
                file_content = site.GetFile(file['FileRef']).content
                open(os.path.join(local_path, file['FileLeafRef']), 'wb').write(file_content)
                logging.info('Téléchargement réussi: %s', file['FileLeafRef'])
            except Exception as e:
                logging.error('Erreur lors du téléchargement de %s: %s', file['FileLeafRef'], e)

    # Récupérez la liste de tous les sous-dossiers de ce dossier
    sub_folders = folder.GetFolders()

    # Pour chaque sous-dossier, appelez la fonction récursivement
    for sub_folder in sub_folders:
        download_files(sub_folder, os.path.join(local_path, sub_folder.name))

# Appelez la fonction pour télécharger tous les fichiers de la racine du site
download_files(root_folder, '.')

I get an error on

root_folder = site.ListFolder('Shared%20Documents')

in fact site is an object 'share plum.site._Site2007' and my variable httpSite has it's value set to https://mysharepoint.sharepoint.com

I want to download all of the files from all of my sites but it doesn't seem to be working as I did not specify /sites/sitename part within my variable httpSite.

So I would like to retrieve a list of my sites and to execute the above code for all my sites...

Error is

AttributeError: '_Site2007' object has no attribute 'ListFolder'


问:
Im trying to add a matplotlib chart on a Tkinter GUI... Can someone help me?
I have this code here where I am trying to import a seaborn ecdf plot on a Tkinter GUI but it is not working. The plot just doesnt pop up when I run the program. Ultimatly, I would like to make the plot updating with real-time data. Is it possible and if yes, how would I go about doing this. Thank you for your time.</p>
```<code>from tkinter import *
import datetime as dt
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import seaborn as sns
from data import GetData

"""Initiate Root"""
Root = Tk()
Root.title('Profondeur du marché')
Root.iconphoto(False, PhotoImage(file = 'Logo.png'))
Root.configure(background = '#2E2D2B')
Root.geometry('1000x800')

"""Define df"""
df = GetData()

"""Create Plot"""
fig, ax = plt.subplots()
ax.set_title('Le livre de liquidité du Bitcoin en temps réel')
"""Bids"""
BidsPlot = sns.ecdfplot(x="Price",
                        weights="Volume",
                        stat="count",
                        complementary=True,
                        data=df.query("Side == 'bids'"),
                        color="green",
                        ax=ax)
"""Asks"""
AsksPlot = sns.ecdfplot(x="Price",
                        weights="Volume",
                        stat="count",
                        data=df.query("Side == 'asks'"),
                        color="red",
                        ax=ax)
"""Set axes titles"""
ax.set_xlabel('Prix')
ax.set_ylabel('Volume')

"""Initiate Canvas"""
Canvas = FigureCanvasTkAgg(fig,
                           master = Root)

Canvas.draw()

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

Body:
I have this code here where I am trying to import a seaborn ecdf plot on a Tkinter GUI but it is not working. The plot just doesnt pop up when I run the program. Ultimatly, I would like to make the plot updating with real-time data. Is it possible and if yes, how would I go about doing this. Thank you for your time.

from tkinter import *
import datetime as dt
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import seaborn as sns
from data import GetData

"""Initiate Root"""
Root = Tk()
Root.title('Profondeur du marché')
Root.iconphoto(False, PhotoImage(file = 'Logo.png'))
Root.configure(background = '#2E2D2B')
Root.geometry('1000x800')

"""Define df"""
df = GetData()

"""Create Plot"""
fig, ax = plt.subplots()
ax.set_title('Le livre de liquidité du Bitcoin en temps réel')
"""Bids"""
BidsPlot = sns.ecdfplot(x="Price",
                        weights="Volume",
                        stat="count",
                        complementary=True,
                        data=df.query("Side == 'bids'"),
                        color="green",
                        ax=ax)
"""Asks"""
AsksPlot = sns.ecdfplot(x="Price",
                        weights="Volume",
                        stat="count",
                        data=df.query("Side == 'asks'"),
                        color="red",
                        ax=ax)
"""Set axes titles"""
ax.set_xlabel('Prix')
ax.set_ylabel('Volume')

"""Initiate Canvas"""
Canvas = FigureCanvasTkAgg(fig,
                           master = Root)

Canvas.draw()

Root.mainloop()


问:
Google spreadsheet custom UI in html with reverse proxy
I'm currently developped an app script in google sheet to custom an UI by HTML.

All is fine when this app is running without reverse proxy (https://script.google.com), however when I try to launch it with the reverse proxy (https://script.google.com.rproxy.goskope.com), the custom UI stay blank. No error are raised in the console of chrome, however a message appears

"posting uri is not valid: https://docs.google.com.rproxy.goskope.com".

I know that my entreprise limit the scope of authorizations when we pass through the proxy, but today I do not know if my script not run because it is unauthorized, or if something miss in the script to allow him to be run.

Find below the code.gs:

```<code>// Use this code for Google Docs, Slides, Forms, or Sheets.
function onOpen() {
  SpreadsheetApp.getUi() // Or DocumentApp or SlidesApp or FormApp.
      .createMenu('Task Card')
      .addItem('Create', 'openDialog')
      .addToUi();
}

function openDialog() {
  var html = HtmlService.createHtmlOutputFromFile('main')
    .setWidth(800)
    .setHeight(750)

  SpreadsheetApp.getUi() // Or DocumentApp or SlidesApp or FormApp.
      .showModalDialog(html, 'Create Task card')
}

function include(filename) {
  return HtmlService.createHtmlOutputFromFile(filename)
      .getContent();
}
</code>```

I try to perform a custom UI inside a google sheet by HTML through proxy (https://script.google.com.rproxy.goskope.com).

I expect that the custom UI appears correctly as it is performed without proxy. (All is fine when I do not passed through reverse proxy)

Body:
I'm currently developped an app script in google sheet to custom an UI by HTML.

All is fine when this app is running without reverse proxy (https://script.google.com), however when I try to launch it with the reverse proxy (https://script.google.com.rproxy.goskope.com), the custom UI stay blank. No error are raised in the console of chrome, however a message appears

"posting uri is not valid: https://docs.google.com.rproxy.goskope.com".

I know that my entreprise limit the scope of authorizations when we pass through the proxy, but today I do not know if my script not run because it is unauthorized, or if something miss in the script to allow him to be run.

Find below the code.gs:

// Use this code for Google Docs, Slides, Forms, or Sheets.
function onOpen() {
  SpreadsheetApp.getUi() // Or DocumentApp or SlidesApp or FormApp.
      .createMenu('Task Card')
      .addItem('Create', 'openDialog')
      .addToUi();
}

function openDialog() {
  var html = HtmlService.createHtmlOutputFromFile('main')
    .setWidth(800)
    .setHeight(750)

  SpreadsheetApp.getUi() // Or DocumentApp or SlidesApp or FormApp.
      .showModalDialog(html, 'Create Task card')
}

function include(filename) {
  return HtmlService.createHtmlOutputFromFile(filename)
      .getContent();
}

I try to perform a custom UI inside a google sheet by HTML through proxy (https://script.google.com.rproxy.goskope.com).

I expect that the custom UI appears correctly as it is performed without proxy. (All is fine when I do not passed through reverse proxy)


Title: I want to compare two different observations in one column over another two observations in another column in R

Body:
df1 <- data.frame(inse = c( 25, 125, 25 ,125, 25, 125, 25 ,125, 25 ,125),

bin = c( 'P', 'F', 'P', 'P', 'F', 'P', 'F', 'F', 'P', 'F'),
step = c('1a','2b','1a','2b','1a','2b','1a','2b','1a','2b'),
lot = c('sz12','sz12', 'sz12','sz12', 'sz12', 'sz12', 'sz12','sz12','zs21', 'zs21'),
uni = c(4,4,4,4,4,4,4,4,5,5),
sort_con = c('8,1','8,1','0,1','0,1','11,8','11,8','9,2','9,2','9,2','9,2'))`

df1 %>%

group_by(lot, uni,sort_con) %>%

mutate( check = ifelse ((inse = 25 & bin == "P") & (inse = 125 & bin == "P"), 1, 0))
inse bin step  lot uni sort_con check
1    25   P   1a sz12   4      8,1     1
2   125   F   2b sz12   4      8,1     0
3    25   P   1a sz12   4      0,1     1
4   125   P   2b sz12   4      0,1     1
5    25   F   1a sz12   4     11,8     0
6   125   P   2b sz12   4     11,8     1
7    25   F   1a sz12   4      9,2     0
8   125   F   2b sz12   4      9,2     0
9    25   P   1a zs21   5      9,2     1
10  125   F   2b zs21   5      9,2     0

I am expecting check column should have 1 which is p in both 25 and 125 observations


问:
Python code creates more than Synchronous timers fired once with different actions
I'm trying to write a python code including GUI (tkinter) that runs 2 or even more timers at the same time with different actions/commands, but with the same "Start" button. The problem in my code below is the 2 timers are created but they are sequentially running. Can I create 2 timers with different time set running synchronously.</p>
```<code>import time
from tkinter import *
from tkinter import messagebox

#Create interface#

root = Tk()
root.geometry("500x500")
root.title("Countdown Timer")

#declare variables for Timer1
hrString1 = StringVar()
minuteString1 = StringVar()
secString1 = StringVar()

#Set String to default values
hrString1.set("00")
minuteString1.set("00")
secString1.set("00")

#Get User Input
hourTextBox1 = Entry(root, width=3, font=("Calibri", 20, ""), textvariable=hrString1).place(x=170, y=100)
minuteTextBox1 = Entry(root, width=3, font=("Calibri", 20, ""), textvariable=minuteString1).place(x=220, y=100)
secondTextBox1 = Entry(root, width=3, font=("Calibri", 20, ""), textvariable=secString1).place(x=270, y=100)

#declare variables
hrString2 = StringVar()
minString2 = StringVar()
secString2 = StringVar()

#Set String to default values
hrString2.set("00")
minString2.set("00")
secString2.set("00")

#Get User Input
hourTextBox2 = Entry(root, width=3, font=("Calibri", 20, ""), textvariable=hrString2).place(x=170, y=180)
minuteTextBox2 = Entry(root, width=3, font=("Calibri", 20, ""), textvariable=minString2).place(x=220, y=180)
secondTextBox2 = Entry(root, width=3, font=("Calibri", 20, ""), textvariable=secString2).place(x=270, y=180)

def runTimer1():
    try:
        clockTime = int(hrString1.get())*3600 + int(minuteString1.get())*60 + int(secString1.get())
    except:
        print("Incorrect values")

    while(clockTime > -1):
        totalMinutes, totalSeconds = divmod(clockTime, 60)
        totalHours = 0  #initialize
        if(totalMinutes>60):
            totalHours, totalMinutes = divmod(totalMinutes, 60)

        hrString1.set("{0:2d}".format(totalHours))
        minuteString1.set("{0:2d}".format(totalMinutes))
        secString1.set("{0:2d}".format(totalSeconds))

        #update the interface with each iteration
        root.update()
        time.sleep(1)

        #time expires
        if(clockTime == 0):
            messagebox.showinfo("", "time One has expired!")  #Run Command 1
        clockTime -= 1

def runTimer2():
    try:
        clockTime2 = int(hrString2.get())*3600 + int(minString2.get())*60 + int(secString2.get())
    except:
        print("Incorrect values")

    while(clockTime2 > -1):
        totalMinutes, totalSeconds = divmod(clockTime2, 60)
        totalHours = 0  #initialize
        if(totalMinutes>60):
            totalHours, totalMinutes = divmod(totalMinutes, 60)

        hrString2.set("{0:2d}".format(totalHours))
        minString2.set("{0:2d}".format(totalMinutes))
        secString2.set("{0:2d}".format(totalSeconds))

        #update the interface with each iteration
        root.update()
        time.sleep(1)

        #time expires
        if(clockTime2 == 0):
            messagebox.showinfo("", "time Two has expired!")  #Run Command 2
        clockTime2 -= 1

setTimeButton = Button(root, text='START', bd='5', command=lambda: [runTimer1(), runTimer2()]).place(relx=0.5, rely=0.8, anchor=CENTER)

#Keep Loop

root.mainloop()

</code>```

Body:
I'm trying to write a python code including GUI (tkinter) that runs 2 or even more timers at the same time with different actions/commands, but with the same "Start" button. The problem in my code below is the 2 timers are created but they are sequentially running. Can I create 2 timers with different time set running synchronously.

import time
from tkinter import *
from tkinter import messagebox

#Create interface#

root = Tk()
root.geometry("500x500")
root.title("Countdown Timer")

#declare variables for Timer1
hrString1 = StringVar()
minuteString1 = StringVar()
secString1 = StringVar()

#Set String to default values
hrString1.set("00")
minuteString1.set("00")
secString1.set("00")

#Get User Input
hourTextBox1 = Entry(root, width=3, font=("Calibri", 20, ""), textvariable=hrString1).place(x=170, y=100)
minuteTextBox1 = Entry(root, width=3, font=("Calibri", 20, ""), textvariable=minuteString1).place(x=220, y=100)
secondTextBox1 = Entry(root, width=3, font=("Calibri", 20, ""), textvariable=secString1).place(x=270, y=100)

#declare variables
hrString2 = StringVar()
minString2 = StringVar()
secString2 = StringVar()

#Set String to default values
hrString2.set("00")
minString2.set("00")
secString2.set("00")

#Get User Input
hourTextBox2 = Entry(root, width=3, font=("Calibri", 20, ""), textvariable=hrString2).place(x=170, y=180)
minuteTextBox2 = Entry(root, width=3, font=("Calibri", 20, ""), textvariable=minString2).place(x=220, y=180)
secondTextBox2 = Entry(root, width=3, font=("Calibri", 20, ""), textvariable=secString2).place(x=270, y=180)

def runTimer1():
    try:
        clockTime = int(hrString1.get())*3600 + int(minuteString1.get())*60 + int(secString1.get())
    except:
        print("Incorrect values")

    while(clockTime > -1):
        totalMinutes, totalSeconds = divmod(clockTime, 60)
        totalHours = 0  #initialize
        if(totalMinutes>60):
            totalHours, totalMinutes = divmod(totalMinutes, 60)

        hrString1.set("{0:2d}".format(totalHours))
        minuteString1.set("{0:2d}".format(totalMinutes))
        secString1.set("{0:2d}".format(totalSeconds))

        #update the interface with each iteration
        root.update()
        time.sleep(1)

        #time expires
        if(clockTime == 0):
            messagebox.showinfo("", "time One has expired!")  #Run Command 1
        clockTime -= 1

def runTimer2():
    try:
        clockTime2 = int(hrString2.get())*3600 + int(minString2.get())*60 + int(secString2.get())
    except:
        print("Incorrect values")

    while(clockTime2 > -1):
        totalMinutes, totalSeconds = divmod(clockTime2, 60)
        totalHours = 0  #initialize
        if(totalMinutes>60):
            totalHours, totalMinutes = divmod(totalMinutes, 60)

        hrString2.set("{0:2d}".format(totalHours))
        minString2.set("{0:2d}".format(totalMinutes))
        secString2.set("{0:2d}".format(totalSeconds))

        #update the interface with each iteration
        root.update()
        time.sleep(1)

        #time expires
        if(clockTime2 == 0):
            messagebox.showinfo("", "time Two has expired!")  #Run Command 2
        clockTime2 -= 1

setTimeButton = Button(root, text='START', bd='5', command=lambda: [runTimer1(), runTimer2()]).place(relx=0.5, rely=0.8, anchor=CENTER)

#Keep Loop

root.mainloop()


问:
How can I set maximum and minimum limit of scaling?
I'm zooming and moving a div using transform translate and scale.
https://jsfiddle.net/Taimurofficial/z78ukb6g/7/
Here is the code:

```<code>var scale = 1,
panning = false,
pointX = 0,
pointY = 0,
start = { x: 0, y: 0 },
zoom = document.getElementById("zoom");

function setTransform() {
zoom.style.transform = "translate(" + pointX + "px, " + pointY + "px) scale(" + scale + ")";
}

zoom.onmousedown = function (e) {
e.preventDefault();
start = { x: e.clientX - pointX, y: e.clientY - pointY };
panning = true;
}

zoom.onmouseup = function (e) {
panning = false;
}

zoom.onmousemove = function (e) {
e.preventDefault();
if (!panning) {
  return;
}
pointX = (e.clientX - start.x);
pointY = (e.clientY - start.y);
setTransform();
}

zoom.onwheel = function (e) {
e.preventDefault();
var xs = (e.clientX - pointX) / scale,
  ys = (e.clientY - pointY) / scale,
  delta = (e.wheelDelta ? e.wheelDelta : -e.deltaY);
(delta > 0) ? (scale *= 1.2) : (scale /= 1.2);
pointX = e.clientX - xs * scale;
pointY = e.clientY - ys * scale;

setTransform();
}
</code>```

I just want to turn off negative scaling.

Body:
I'm zooming and moving a div using transform translate and scale.
https://jsfiddle.net/Taimurofficial/z78ukb6g/7/
Here is the code:

var scale = 1,
panning = false,
pointX = 0,
pointY = 0,
start = { x: 0, y: 0 },
zoom = document.getElementById("zoom");

function setTransform() {
zoom.style.transform = "translate(" + pointX + "px, " + pointY + "px) scale(" + scale + ")";
}

zoom.onmousedown = function (e) {
e.preventDefault();
start = { x: e.clientX - pointX, y: e.clientY - pointY };
panning = true;
}

zoom.onmouseup = function (e) {
panning = false;
}

zoom.onmousemove = function (e) {
e.preventDefault();
if (!panning) {
  return;
}
pointX = (e.clientX - start.x);
pointY = (e.clientY - start.y);
setTransform();
}

zoom.onwheel = function (e) {
e.preventDefault();
var xs = (e.clientX - pointX) / scale,
  ys = (e.clientY - pointY) / scale,
  delta = (e.wheelDelta ? e.wheelDelta : -e.deltaY);
(delta > 0) ? (scale *= 1.2) : (scale /= 1.2);
pointX = e.clientX - xs * scale;
pointY = e.clientY - ys * scale;

setTransform();
}

I just want to turn off negative scaling.


问:
Implementing Refresh and needsRefresh for AWS Chime SDK Messaging Client
I am making use of aws-chime-sdk-js and ChimeSDKMessagingClient, I have read in the docs that if we implement refresh and needsRefresh then aws-chime-sdk-js would take care of refreshing the aws credentials when they expire. How would we do this in aws sdk v3 clients?

I tried but I haven't found a way to do it.


问:
I'm getting this.state.events.map is not a function message on console when trying to send data from spring controller to react Component
I have 2 problems:

I can't pass data from @GetMapping("events/ongoingEvents") endpoint to EventsComponent created in react, all I get when going on localhost:3000/events/ongoingEvents is empty blank page and console message this.state.events.map is not a function, I understand that this.state.events.map is not a function tells me that data is not an array so i can't use map() method on it but what is it then and how can I make it an array, is that what I should do even?
Don't I in

```<code>constructor(props) {
        super(props)

        this.state = {
             events: []
        }
    }
</code>```

set the state of a component to an array and then update it wit data from endpoint, if so then events should be an array, shouldn't it?

Even though in sckage.json  i added "proxy": "http://localhost:8080", and commented out @CrossOrigin(origins = "http://localhost:3000") in allCurrentEvents() method I still have to go to localhost:3000 to see the result, what do I do so I can display the data from react at localhost:8080? Thanks in advance.

Entity class

```<code>@AllArgsConstructor
@Table(name = "zdarzenia")
@Entity
@Builder
@NoArgsConstructor
@Getter
@Setter

public class Event {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column
    public Integer id;

    @ManyToOne()
    @JoinColumn(name = "id_elektrowni", referencedColumnName = "id")
    private PowerPlant powerPlant;

    @Column
    @Enumerated(EnumType.STRING)
    public EventType typeOfEvent;

    @Column
    public Double powerDrop;

    @Column
    public LocalDate startDate;

    @Column
    public LocalDate endDate;

    @Override
    public String toString() {
        return "" + typeOfEvent + "";
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) return false;
        Event event = (Event) o;
        return id != null && Objects.equals(id, event.id);
    }

    @Override
    public int hashCode() {
        return getClass().hashCode();
    }
}
</code>```

Controller class

```<code>@Controller
@RequiredArgsConstructor
public class EventsReactControllers {

    private final EventRepository eventRepository;

    //@CrossOrigin(origins = "http://localhost:3000")
    @GetMapping("events/ongoingEvents")
    public List<Event> allCurrentEvents() {
        return eventRepository.findAll().stream().filter(e -> e.endDate.isAfter(LocalDate.now()))
                .collect(Collectors.toList());
    }

    @GetMapping("events/eventsEndingToday")
    public List<Event> eventsToday() {
        return eventRepository.findAll().stream().filter(e -> e.endDate.isEqual(LocalDate.now()))
                .collect(Collectors.toList());

    }
}

</code>```

package.json

```<code>{
  "name": "frontend",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "axios": "^1.2.2",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "proxy": "http://localhost:8080",

  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

</code>```

App.js

```<code>import React from 'react';
import logo from './logo.svg';
import './App.css';
import EventsComponent from './EventsComponent';

function App() {

  return (
    <div>
          <header className="container">
             <EventsComponent />
          </header>
        </div>
  );
}

export default App;

</code>```

index.js

```<code>import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import 'bootstrap/dist/css/bootstrap.min.css';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

</code>```

ApiService.js

```<code>import axios from 'axios';

const EVENTS_API_REST_URL = "http://localhost:8080/events/ongoingEvents";

class APIService {

    getEvents(){
        return axios.get(EVENTS_API_REST_URL);
    }

}

export default new APIService();
</code>```

EventsComponent.js

```<code>import React from 'react'
import APIService from './APIService'

export default class EventsComponent extends React.Component {

    constructor(props) {
        super(props)

        this.state = {
             events: []
        }
    }

    componentDidMount(){
        APIService.getEvents().then(({data}) => {
            this.setState({ events: data })
            console.log(this.state.data)
          })
          .catch(function (ex) {
              console.log('Response parsing failed. Error: ', ex);
          });;
    }

    render() {
        return (
            <div>
                <h2 className="text-center">Events Details</h2>
                <table className="table table-striped">
                    <thead>
                        <tr>
                            <th>Event Id</th>
                            <th>Event type</th>
                            <th>Power drop</th>
                            <th>End Date</th>
                            <th>Start date</th>
                        </tr>
                    </thead>
                    <tbody>
                        {
                            this.state.events.map(event =>
                                    <tr key={event.id}>
                                        <td>{event.id}</td>
                                        <td>{event.typeOfEvent}</td>
                                        <td>{event.powerDrop}</td>
                                        <td>{event.startDate}</td>
                                        <td>{event.endDate}</td>
                                    </tr>
                            )
                        }
                    </tbody>
                </table>
            </div>
        )
    }
}
</code>```

Security calss

```<code>
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import javax.sql.DataSource;

@EnableWebSecurity
public class Security extends WebSecurityConfigurerAdapter {

    @Autowired
    private DataSource dataSource;

    @Override
    protected void configure(final HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/allUsers").access("hasAuthority('ADMIN')")
                .antMatchers("/users/delete/{id}").access("hasAuthority('ADMIN')")//albo /users/delete* przy @RequestParam
                .antMatchers("/users/update/{id}").access("hasAuthority('ADMIN')")
                .antMatchers("/delete/powerPlants/{id}").access("hasAuthority('ADMIN')")
                .antMatchers("/addEventToPlant/{plantId}/{eventId}").access("hasAuthority('ADMIN')")
                .antMatchers("/powerPlantsIds").access("hasAuthority('ADMIN')")
                .antMatchers("/login*").permitAll()
                .antMatchers("/regist*").permitAll()
                .anyRequest().authenticated();
        http.formLogin()
                .loginPage("/login")
                .loginProcessingUrl("/login")
                .usernameParameter("login")
                .passwordParameter("password")
                .defaultSuccessUrl("/powerPlants", true);
        http.cors().and().csrf().disable()
                .headers().frameOptions().disable();
        http.logout()
                .logoutSuccessUrl("/login")
                .logoutUrl("/logout");
    }

    ////////////
    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
        return source;
    }
    ////////////

    @Override
    public void configure(WebSecurity web) {
        web
                .ignoring()
                .antMatchers("/resources/**", "/css/**", "/js/**", "/img/**", "/icon/**");
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication()
                .usersByUsernameQuery("SELECT u.login, u.password,1 FROM user AS u WHERE u.login=?")
                .authoritiesByUsernameQuery("SELECT u.login, r.typ_roli, 1 " +
                        "FROM user u " +
                        "INNER JOIN user_role ur ON ur.user_id = u.user_id " +
                        "INNER JOIN role r ON r.role_id = ur.role_id " +
                        "WHERE u.login=?")
                .dataSource(dataSource);
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

</code>```

Terminal

```<code>Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.

Try the new cross-platform PowerShell https://aka.ms/pscore6

Compiled with warnings.

Warning
(6:29521) autoprefixer: Replace color-adjust to print-color-adjust. The color-adjust shorthand is currently deprecated.

Search for the keywords to learn more about each warning.
To ignore, add // eslint-disable-next-line to the line before.
js.js??ruleSet[1].rules[1].oneOf[5].use[2]!./node_modules/source-map-loader/dist/cjs.js!
../node_modules/bootstrap/dist/css/bootstrap.min.css)
Module Warning (from ./node_modules/postcss-loader/dist/cjs.js):
Warning

(6:29521) autoprefixer: Replace color-adjust to print-color-adjust. The color-adjust sho
rthand is currently deprecated.

webpack compiled with 1 warning
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.

Try the new cross-platform PowerShell https://aka.ms/pscore6

Compiled with warnings.

Warning
(6:29521) autoprefixer: Replace color-adjust to print-color-adjust. The color-adjust shorthand is currently deprecated.

Search for the keywords to learn more about each warning.
To ignore, add // eslint-disable-next-line to the line before.
js.js??ruleSet[1].rules[1].oneOf[5].use[2]!./node_modules/source-map-loader/dist/cjs.js!
../node_modules/bootstrap/dist/css/bootstrap.min.css)
Module Warning (from ./node_modules/postcss-loader/dist/cjs.js):
Warning

(6:29521) autoprefixer: Replace color-adjust to print-color-adjust. The color-adjust sho
rthand is currently deprecated.

webpack compiled with 1 warning
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.

Try the new cross-platform PowerShell https://aka.ms/pscore6

Compiled with warnings.

Warning
(6:29521) autoprefixer: Replace color-adjust to print-color-adjust. The color-adjust shorthand is currently deprecated.

Search for the keywords to learn more about each warning.
To ignore, add // eslint-disable-next-line to the line before.
js.js??ruleSet[1].rules[1].oneOf[5].use[2]!./node_modules/source-map-loader/dist/cjs.js!
../node_modules/bootstrap/dist/css/bootstrap.min.css)
Module Warning (from ./node_modules/postcss-loader/dist/cjs.js):
Warning

(6:29521) autoprefixer: Replace color-adjust to print-color-adjust. The color-adjust sho
rthand is currently deprecated.

webpack compiled with 1 warning
</code>```

Console log

```<code>EventsComponent.js:38 Uncaught TypeError: this.state.events.map is not a function
    at EventsComponent.render (EventsComponent.js:38:1)
    at finishClassComponent (react-dom.development.js:19752:1)
    at updateClassComponent (react-dom.development.js:19698:1)
    at beginWork (react-dom.development.js:21611:1)
    at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:1)
    at invokeGuardedCallback (react-dom.development.js:4277:1)
    at beginWork$1 (react-dom.development.js:27451:1)
    at performUnitOfWork (react-dom.development.js:26557:1)
    at workLoopSync (react-dom.development.js:26466:1)
render @ EventsComponent.js:38
finishClassComponent @ react-dom.development.js:19752
updateClassComponent @ react-dom.development.js:19698
beginWork @ react-dom.development.js:21611
callCallback @ react-dom.development.js:4164
invokeGuardedCallbackDev @ react-dom.development.js:4213
invokeGuardedCallback @ react-dom.development.js:4277
beginWork$1 @ react-dom.development.js:27451
performUnitOfWork @ react-dom.development.js:26557
workLoopSync @ react-dom.development.js:26466
renderRootSync @ react-dom.development.js:26434
performConcurrentWorkOnRoot @ react-dom.development.js:25738
workLoop @ scheduler.development.js:266
flushWork @ scheduler.development.js:239
performWorkUntilDeadline @ scheduler.development.js:533
EventsComponent.js:38 Uncaught TypeError: this.state.events.map is not a function
    at EventsComponent.render (EventsComponent.js:38:1)
    at finishClassComponent (react-dom.development.js:19752:1)
    at updateClassComponent (react-dom.development.js:19698:1)
    at beginWork (react-dom.development.js:21611:1)
    at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:1)
    at invokeGuardedCallback (react-dom.development.js:4277:1)
    at beginWork$1 (react-dom.development.js:27451:1)
    at performUnitOfWork (react-dom.development.js:26557:1)
    at workLoopSync (react-dom.development.js:26466:1)
render @ EventsComponent.js:38
finishClassComponent @ react-dom.development.js:19752
updateClassComponent @ react-dom.development.js:19698
beginWork @ react-dom.development.js:21611
callCallback @ react-dom.development.js:4164
invokeGuardedCallbackDev @ react-dom.development.js:4213
invokeGuardedCallback @ react-dom.development.js:4277
beginWork$1 @ react-dom.development.js:27451
performUnitOfWork @ react-dom.development.js:26557
workLoopSync @ react-dom.development.js:26466
renderRootSync @ react-dom.development.js:26434
recoverFromConcurrentError @ react-dom.development.js:25850
performConcurrentWorkOnRoot @ react-dom.development.js:25750
workLoop @ scheduler.development.js:266
flushWork @ scheduler.development.js:239
performWorkUntilDeadline @ scheduler.development.js:533
react-dom.development.js:18687 The above error occurred in the <EventsComponent> component:

    at EventsComponent (http://localhost:3000/static/js/bundle.js:217:5)
    at header
    at div
    at App

Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.
logCapturedError @ react-dom.development.js:18687
update.callback @ react-dom.development.js:18720
callCallback @ react-dom.development.js:13923
commitUpdateQueue @ react-dom.development.js:13944
commitLayoutEffectOnFiber @ react-dom.development.js:23391
commitLayoutMountEffects_complete @ react-dom.development.js:24688
commitLayoutEffects_begin @ react-dom.development.js:24674
commitLayoutEffects @ react-dom.development.js:24612
commitRootImpl @ react-dom.development.js:26823
commitRoot @ react-dom.development.js:26682
finishConcurrentRender @ react-dom.development.js:25892
performConcurrentWorkOnRoot @ react-dom.development.js:25809
workLoop @ scheduler.development.js:266
flushWork @ scheduler.development.js:239
performWorkUntilDeadline @ scheduler.development.js:533
EventsComponent.js:38 Uncaught TypeError: this.state.events.map is not a function
    at EventsComponent.render (EventsComponent.js:38:1)
    at finishClassComponent (react-dom.development.js:19752:1)
    at updateClassComponent (react-dom.development.js:19698:1)
    at beginWork (react-dom.development.js:21611:1)
    at beginWork$1 (react-dom.development.js:27426:1)
    at performUnitOfWork (react-dom.development.js:26557:1)
    at workLoopSync (react-dom.development.js:26466:1)
    at renderRootSync (react-dom.development.js:26434:1)
    at recoverFromConcurrentError (react-dom.development.js:25850:1)
    at performConcurrentWorkOnRoot (react-dom.development.js:25750:1)
render @ EventsComponent.js:38
finishClassComponent @ react-dom.development.js:19752
updateClassComponent @ react-dom.development.js:19698
beginWork @ react-dom.development.js:21611
beginWork$1 @ react-dom.development.js:27426
performUnitOfWork @ react-dom.development.js:26557
workLoopSync @ react-dom.development.js:26466
renderRootSync @ react-dom.development.js:26434
recoverFromConcurrentError @ react-dom.development.js:25850
performConcurrentWorkOnRoot @ react-dom.development.js:25750
workLoop @ scheduler.development.js:266
flushWork @ scheduler.development.js:239
performWorkUntilDeadline @ scheduler.development.js:533
</code>```

Body:
I have 2 problems:

I can't pass data from @GetMapping("events/ongoingEvents") endpoint to EventsComponent created in react, all I get when going on localhost:3000/events/ongoingEvents is empty blank page and console message this.state.events.map is not a function, I understand that this.state.events.map is not a function tells me that data is not an array so i can't use map() method on it but what is it then and how can I make it an array, is that what I should do even?
Don't I in

constructor(props) {
        super(props)

        this.state = {
             events: []
        }
    }

set the state of a component to an array and then update it wit data from endpoint, if so then events should be an array, shouldn't it?

Even though in sckage.json  i added "proxy": "http://localhost:8080", and commented out @CrossOrigin(origins = "http://localhost:3000") in allCurrentEvents() method I still have to go to localhost:3000 to see the result, what do I do so I can display the data from react at localhost:8080? Thanks in advance.

Entity class

@AllArgsConstructor
@Table(name = "zdarzenia")
@Entity
@Builder
@NoArgsConstructor
@Getter
@Setter

public class Event {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column
    public Integer id;

    @ManyToOne()
    @JoinColumn(name = "id_elektrowni", referencedColumnName = "id")
    private PowerPlant powerPlant;

    @Column
    @Enumerated(EnumType.STRING)
    public EventType typeOfEvent;

    @Column
    public Double powerDrop;

    @Column
    public LocalDate startDate;

    @Column
    public LocalDate endDate;

    @Override
    public String toString() {
        return "" + typeOfEvent + "";
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) return false;
        Event event = (Event) o;
        return id != null && Objects.equals(id, event.id);
    }

    @Override
    public int hashCode() {
        return getClass().hashCode();
    }
}

Controller class

@Controller
@RequiredArgsConstructor
public class EventsReactControllers {

    private final EventRepository eventRepository;

    //@CrossOrigin(origins = "http://localhost:3000")
    @GetMapping("events/ongoingEvents")
    public List<Event> allCurrentEvents() {
        return eventRepository.findAll().stream().filter(e -> e.endDate.isAfter(LocalDate.now()))
                .collect(Collectors.toList());
    }

    @GetMapping("events/eventsEndingToday")
    public List<Event> eventsToday() {
        return eventRepository.findAll().stream().filter(e -> e.endDate.isEqual(LocalDate.now()))
                .collect(Collectors.toList());

    }
}

package.json

{
  "name": "frontend",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "axios": "^1.2.2",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "proxy": "http://localhost:8080",

  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

App.js

import React from 'react';
import logo from './logo.svg';
import './App.css';
import EventsComponent from './EventsComponent';

function App() {

  return (

             <EventsComponent />

  );
}

export default App;

index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import 'bootstrap/dist/css/bootstrap.min.css';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

ApiService.js

import axios from 'axios';

const EVENTS_API_REST_URL = "http://localhost:8080/events/ongoingEvents";

class APIService {

    getEvents(){
        return axios.get(EVENTS_API_REST_URL);
    }

}

export default new APIService();

EventsComponent.js

import React from 'react'
import APIService from './APIService'

export default class EventsComponent extends React.Component {

    constructor(props) {
        super(props)

        this.state = {
             events: []
        }
    }

    componentDidMount(){
        APIService.getEvents().then(({data}) => {
            this.setState({ events: data })
            console.log(this.state.data)
          })
          .catch(function (ex) {
              console.log('Response parsing failed. Error: ', ex);
          });;
    }

    render() {
        return (

Events Details

                            Event Id
                            Event type
                            Power drop
                            End Date
                            Start date

                        {
                            this.state.events.map(event =>

                                        {event.id}
                                        {event.typeOfEvent}
                                        {event.powerDrop}
                                        {event.startDate}
                                        {event.endDate}

                            )
                        }

        )
    }
}

Security calss

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import javax.sql.DataSource;

@EnableWebSecurity
public class Security extends WebSecurityConfigurerAdapter {

    @Autowired
    private DataSource dataSource;

    @Override
    protected void configure(final HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/allUsers").access("hasAuthority('ADMIN')")
                .antMatchers("/users/delete/{id}").access("hasAuthority('ADMIN')")//albo /users/delete* przy @RequestParam
                .antMatchers("/users/update/{id}").access("hasAuthority('ADMIN')")
                .antMatchers("/delete/powerPlants/{id}").access("hasAuthority('ADMIN')")
                .antMatchers("/addEventToPlant/{plantId}/{eventId}").access("hasAuthority('ADMIN')")
                .antMatchers("/powerPlantsIds").access("hasAuthority('ADMIN')")
                .antMatchers("/login*").permitAll()
                .antMatchers("/regist*").permitAll()
                .anyRequest().authenticated();
        http.formLogin()
                .loginPage("/login")
                .loginProcessingUrl("/login")
                .usernameParameter("login")
                .passwordParameter("password")
                .defaultSuccessUrl("/powerPlants", true);
        http.cors().and().csrf().disable()
                .headers().frameOptions().disable();
        http.logout()
                .logoutSuccessUrl("/login")
                .logoutUrl("/logout");
    }

    ////////////
    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
        return source;
    }
    ////////////

    @Override
    public void configure(WebSecurity web) {
        web
                .ignoring()
                .antMatchers("/resources/**", "/css/**", "/js/**", "/img/**", "/icon/**");
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication()
                .usersByUsernameQuery("SELECT u.login, u.password,1 FROM user AS u WHERE u.login=?")
                .authoritiesByUsernameQuery("SELECT u.login, r.typ_roli, 1 " +
                        "FROM user u " +
                        "INNER JOIN user_role ur ON ur.user_id = u.user_id " +
                        "INNER JOIN role r ON r.role_id = ur.role_id " +
                        "WHERE u.login=?")
                .dataSource(dataSource);
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

Terminal

Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.

Try the new cross-platform PowerShell https://aka.ms/pscore6

Compiled with warnings.

Warning
(6:29521) autoprefixer: Replace color-adjust to print-color-adjust. The color-adjust shorthand is currently deprecated.

Search for the keywords to learn more about each warning.
To ignore, add // eslint-disable-next-line to the line before.
js.js??ruleSet[1].rules[1].oneOf[5].use[2]!./node_modules/source-map-loader/dist/cjs.js!
../node_modules/bootstrap/dist/css/bootstrap.min.css)
Module Warning (from ./node_modules/postcss-loader/dist/cjs.js):
Warning

(6:29521) autoprefixer: Replace color-adjust to print-color-adjust. The color-adjust sho
rthand is currently deprecated.

webpack compiled with 1 warning
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.

Try the new cross-platform PowerShell https://aka.ms/pscore6

Compiled with warnings.

Warning
(6:29521) autoprefixer: Replace color-adjust to print-color-adjust. The color-adjust shorthand is currently deprecated.

Search for the keywords to learn more about each warning.
To ignore, add // eslint-disable-next-line to the line before.
js.js??ruleSet[1].rules[1].oneOf[5].use[2]!./node_modules/source-map-loader/dist/cjs.js!
../node_modules/bootstrap/dist/css/bootstrap.min.css)
Module Warning (from ./node_modules/postcss-loader/dist/cjs.js):
Warning

(6:29521) autoprefixer: Replace color-adjust to print-color-adjust. The color-adjust sho
rthand is currently deprecated.

webpack compiled with 1 warning
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.

Try the new cross-platform PowerShell https://aka.ms/pscore6

Compiled with warnings.

Warning
(6:29521) autoprefixer: Replace color-adjust to print-color-adjust. The color-adjust shorthand is currently deprecated.

Search for the keywords to learn more about each warning.
To ignore, add // eslint-disable-next-line to the line before.
js.js??ruleSet[1].rules[1].oneOf[5].use[2]!./node_modules/source-map-loader/dist/cjs.js!
../node_modules/bootstrap/dist/css/bootstrap.min.css)
Module Warning (from ./node_modules/postcss-loader/dist/cjs.js):
Warning

(6:29521) autoprefixer: Replace color-adjust to print-color-adjust. The color-adjust sho
rthand is currently deprecated.

webpack compiled with 1 warning

Console log

EventsComponent.js:38 Uncaught TypeError: this.state.events.map is not a function
    at EventsComponent.render (EventsComponent.js:38:1)
    at finishClassComponent (react-dom.development.js:19752:1)
    at updateClassComponent (react-dom.development.js:19698:1)
    at beginWork (react-dom.development.js:21611:1)
    at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:1)
    at invokeGuardedCallback (react-dom.development.js:4277:1)
    at beginWork$1 (react-dom.development.js:27451:1)
    at performUnitOfWork (react-dom.development.js:26557:1)
    at workLoopSync (react-dom.development.js:26466:1)
render @ EventsComponent.js:38
finishClassComponent @ react-dom.development.js:19752
updateClassComponent @ react-dom.development.js:19698
beginWork @ react-dom.development.js:21611
callCallback @ react-dom.development.js:4164
invokeGuardedCallbackDev @ react-dom.development.js:4213
invokeGuardedCallback @ react-dom.development.js:4277
beginWork$1 @ react-dom.development.js:27451
performUnitOfWork @ react-dom.development.js:26557
workLoopSync @ react-dom.development.js:26466
renderRootSync @ react-dom.development.js:26434
performConcurrentWorkOnRoot @ react-dom.development.js:25738
workLoop @ scheduler.development.js:266
flushWork @ scheduler.development.js:239
performWorkUntilDeadline @ scheduler.development.js:533
EventsComponent.js:38 Uncaught TypeError: this.state.events.map is not a function
    at EventsComponent.render (EventsComponent.js:38:1)
    at finishClassComponent (react-dom.development.js:19752:1)
    at updateClassComponent (react-dom.development.js:19698:1)
    at beginWork (react-dom.development.js:21611:1)
    at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:1)
    at invokeGuardedCallback (react-dom.development.js:4277:1)
    at beginWork$1 (react-dom.development.js:27451:1)
    at performUnitOfWork (react-dom.development.js:26557:1)
    at workLoopSync (react-dom.development.js:26466:1)
render @ EventsComponent.js:38
finishClassComponent @ react-dom.development.js:19752
updateClassComponent @ react-dom.development.js:19698
beginWork @ react-dom.development.js:21611
callCallback @ react-dom.development.js:4164
invokeGuardedCallbackDev @ react-dom.development.js:4213
invokeGuardedCallback @ react-dom.development.js:4277
beginWork$1 @ react-dom.development.js:27451
performUnitOfWork @ react-dom.development.js:26557
workLoopSync @ react-dom.development.js:26466
renderRootSync @ react-dom.development.js:26434
recoverFromConcurrentError @ react-dom.development.js:25850
performConcurrentWorkOnRoot @ react-dom.development.js:25750
workLoop @ scheduler.development.js:266
flushWork @ scheduler.development.js:239
performWorkUntilDeadline @ scheduler.development.js:533
react-dom.development.js:18687 The above error occurred in the <EventsComponent> component:

    at EventsComponent (http://localhost:3000/static/js/bundle.js:217:5)
    at header
    at div
    at App

Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.
logCapturedError @ react-dom.development.js:18687
update.callback @ react-dom.development.js:18720
callCallback @ react-dom.development.js:13923
commitUpdateQueue @ react-dom.development.js:13944
commitLayoutEffectOnFiber @ react-dom.development.js:23391
commitLayoutMountEffects_complete @ react-dom.development.js:24688
commitLayoutEffects_begin @ react-dom.development.js:24674
commitLayoutEffects @ react-dom.development.js:24612
commitRootImpl @ react-dom.development.js:26823
commitRoot @ react-dom.development.js:26682
finishConcurrentRender @ react-dom.development.js:25892
performConcurrentWorkOnRoot @ react-dom.development.js:25809
workLoop @ scheduler.development.js:266
flushWork @ scheduler.development.js:239
performWorkUntilDeadline @ scheduler.development.js:533
EventsComponent.js:38 Uncaught TypeError: this.state.events.map is not a function
    at EventsComponent.render (EventsComponent.js:38:1)
    at finishClassComponent (react-dom.development.js:19752:1)
    at updateClassComponent (react-dom.development.js:19698:1)
    at beginWork (react-dom.development.js:21611:1)
    at beginWork$1 (react-dom.development.js:27426:1)
    at performUnitOfWork (react-dom.development.js:26557:1)
    at workLoopSync (react-dom.development.js:26466:1)
    at renderRootSync (react-dom.development.js:26434:1)
    at recoverFromConcurrentError (react-dom.development.js:25850:1)
    at performConcurrentWorkOnRoot (react-dom.development.js:25750:1)
render @ EventsComponent.js:38
finishClassComponent @ react-dom.development.js:19752
updateClassComponent @ react-dom.development.js:19698
beginWork @ react-dom.development.js:21611
beginWork$1 @ react-dom.development.js:27426
performUnitOfWork @ react-dom.development.js:26557
workLoopSync @ react-dom.development.js:26466
renderRootSync @ react-dom.development.js:26434
recoverFromConcurrentError @ react-dom.development.js:25850
performConcurrentWorkOnRoot @ react-dom.development.js:25750
workLoop @ scheduler.development.js:266
flushWork @ scheduler.development.js:239
performWorkUntilDeadline @ scheduler.development.js:533


问:
How to define correct path to files php js and json
I've bootstrap dashboard and now I need to rewrite to my codeigniter 3 admin panel app.

My address url  strcuture:  https://myadmin.com/admin

I've put assets folder in root public_html

and Now when I call script in footer:

```<code><script src="assets/js/pages/api-key.init.js"></script>
</code>```

then I have error 404 because function try open file in path:

https://myadmin.com/admin/assets/js/pages/api-key.init.js

but correct path is:

https://myadmin.com/assets/js/pages/api-key.init.js

the next problem script api-key.init.js have content and try open another path:

```<code>assets/json/api-key-list.json
</code>```

and in api-key-list.json I have another path example to images:

```<code>assets/img/avatar-1.jpg
</code>```

issue describe:

how can I define in all these files like footer php/html  .js and .json to search for these files instead of constantly opening each file individually and giving the full address with domain name?

example in footer I can give:

```<code><script src="<?php echo base_url(); ?>assets/js/pages/api-key.init.js"></script>
</code>```

but when in .js file I cannot give  because .js files not read this variable and im not sure how to correct resolve because due to this I;ve most issues and most functions in dashboard not working correct and I need spend more time to debug and step by step check in log console and change path.

Body:
I've bootstrap dashboard and now I need to rewrite to my codeigniter 3 admin panel app.

My address url  strcuture:  https://myadmin.com/admin

I've put assets folder in root public_html

and Now when I call script in footer:

then I have error 404 because function try open file in path:

https://myadmin.com/admin/assets/js/pages/api-key.init.js

but correct path is:

https://myadmin.com/assets/js/pages/api-key.init.js

the next problem script api-key.init.js have content and try open another path:

assets/json/api-key-list.json

and in api-key-list.json I have another path example to images:

assets/img/avatar-1.jpg

issue describe:

how can I define in all these files like footer php/html  .js and .json to search for these files instead of constantly opening each file individually and giving the full address with domain name?

example in footer I can give:

but when in .js file I cannot give  because .js files not read this variable and im not sure how to correct resolve because due to this I;ve most issues and most functions in dashboard not working correct and I need spend more time to debug and step by step check in log console and change path.


问:
How can I get my submit button to work in react.js?
I'm trying to use Mailchimp with react to create a newsletter signup form. However I'm having the issue of the button I've created not working. I can enter information into the form but I cannot submit it. I'm unsure what I'm doing wrong. The code is below. Any explanation is appreciated.

```<code>import React, { useState } from 'react';

const SubscribeForm = () => {
  const [email, setEmail] = useState('');

  const handleSubmit = (e) => {
    e.preventDefault();
    // perform form submission here
  }

  return (
    <div id="mc_embed_signup">
      <form
        action="https://eclipsecard.us8.list-manage.com/subscribe/post?u=apigoeshere&id=listidhoeshere&f_id=anotheridhere"
        method="post"
        id="mc-embedded-subscribe-form"
        name="mc-embedded-subscribe-form"
        className="validate"
        target="_self"
        onSubmit={handleSubmit}
      >
        <div id="mc_embed_signup_scroll">
          <h2>Subscribe to Eclipse</h2>
          <div className="indicates-required">
            <span className="asterisk">*</span> indicates required
          </div>
          <div className="mc-field-group">
            <label htmlFor="mce-EMAIL">
              Email Address <span className="asterisk">*</span>
            </label>
            <input
              type="email"
              value={email}
              name="EMAIL"
              className="required email"
              id="mce-EMAIL"
              required
              onChange={e => setEmail(e.target.value)}
            />
            <span id="mce-EMAIL-HELPERTEXT" className="helper_text"></span>
          </div>
          <div id="mce-responses" className="clear foot">
            <div className="response" id="mce-error-response" style={{ display: 'none' }}></div>
            <div className="response" id="mce-success-response" style={{ display: 'none' }}></div>
          </div>
          <div style={{ position: 'absolute', left: '-5000px' }} aria-hidden="true">
            <input type="text" name="b_5dc03094f057ba65239f4c04b_1ef7f96bf7" tabIndex="-1" value="" />
          </div>
          <div className="optionalParent">
            <div className="clear foot">
              <input
                type="submit"
                value="Subscribe"
                name="subscribe"
                id="mc-embedded-subscribe"
                className="button"
              />
            </div>
          </div>
        </div>
      </form>
    </div>
  );
};

export default SubscribeForm;
</code>```

Everything else seems to be working alright, it just appears to be an issue with how I've down the button, however I cannot identify a way to make it better or fix it.

Body:
I'm trying to use Mailchimp with react to create a newsletter signup form. However I'm having the issue of the button I've created not working. I can enter information into the form but I cannot submit it. I'm unsure what I'm doing wrong. The code is below. Any explanation is appreciated.

import React, { useState } from 'react';

const SubscribeForm = () => {
  const [email, setEmail] = useState('');

  const handleSubmit = (e) => {
    e.preventDefault();
    // perform form submission here
  }

  return (

      <form
        action="https://eclipsecard.us8.list-manage.com/subscribe/post?u=apigoeshere&id=listidhoeshere&f_id=anotheridhere"
        method="post"
        id="mc-embedded-subscribe-form"
        name="mc-embedded-subscribe-form"
        className="validate"
        target="_self"
        onSubmit={handleSubmit}
      >

Subscribe to Eclipse

            * indicates required

              Email Address *

            <input
              type="email"
              value={email}
              name="EMAIL"
              className="required email"
              id="mce-EMAIL"
              required
              onChange={e => setEmail(e.target.value)}
            />

            <input type="text" name="b_5dc03094f057ba65239f4c04b_1ef7f96bf7" tabIndex="-1" value="" />

              <input
                type="submit"
                value="Subscribe"
                name="subscribe"
                id="mc-embedded-subscribe"
                className="button"
              />

      </form>

  );
};

export default SubscribeForm;

Everything else seems to be working alright, it just appears to be an issue with how I've down the button, however I cannot identify a way to make it better or fix it.


问:
Call to WriteHtml method produces TypeError while using mpdf with CodeIgniter4
I'm trying to use mPDF with Codeigniter4. When I call the function $mpdf->WriteHtml($html) after rendering the view and storing the result in $html variable, it throws an error at line $mpdf->WriteHtml($html). The error is

TypeError Unsupported operand types: string * int.

Pl. help resolve this.

I generated view without calling MPDF and it works fine. So there is no issue with the view.

Updated on Jan 02, 2023

I experimented further by removing all the HTML rendered and gradually adding elements. I am using MDBootstrap CSS using MSN (https://mdbootstrap.com/). I noted that as soon as I add "bg-secondary" to the class in one of the divs, the above error is thrown. There may be other such classes but this is the first one noted here.
PHP version is 8.1

     <link href="https://cdnjs.cloudflare.com/ajax/libs/font-
     awesome/6.0.0/css/all.min.css" rel="stylesheet" />

     <link href="https://fonts.googleapis.com/css
     family=Roboto:300,400,500,700&display=swap" rel="stylesheet"
     />

     <link href="https://cdnjs.cloudflare.com/ajax/libs/mdb-ui-
     kit/6.0.1/mdb.min.css" rel="stylesheet" />

    '

Meenakshi Sehkari Awaas Samiti

(Reg. No 1523. Plot No. 7, Sector PI,
    Greater Noida, (Distt. Gautam Budh Nagar), U.P - 201308.

    <div class="col-md-12 text-center justify-content-center"

Maintenance Bill Note

```


问:
How to redirect webpage if copyright text removed using JavaScript or jQuery
I have some HTML template, that has developed by HTML CSS JavaScript and jQuery. I want to add a copyright text to all of my theme. But there's a fact. If anybody remove the code or text, the theme will be automatically redirect to an URL. I saw this system in Blogger/Blogspot templates. They use a copyright text in all theme footer (Paid and Free).

Even if anybody remove the code or make the copyright span invisible (visibility:hidden) or (display:none), the theme also will be redirect automatically. They did it with just jQuery and JavaScript.

This is my simple code:

```<code><footer>
<span id='copyright'> Copyright 2023 - Theme Title </span> | All Rights Reserved.
</footer>
</code>```

I've also asked this question before Stack Overflow in here. But they were unable to give me a proper solution.

How I can do it...?

Body:
I have some HTML template, that has developed by HTML CSS JavaScript and jQuery. I want to add a copyright text to all of my theme. But there's a fact. If anybody remove the code or text, the theme will be automatically redirect to an URL. I saw this system in Blogger/Blogspot templates. They use a copyright text in all theme footer (Paid and Free).

Even if anybody remove the code or make the copyright span invisible (visibility:hidden) or (display:none), the theme also will be redirect automatically. They did it with just jQuery and JavaScript.

This is my simple code:

 Copyright 2023 - Theme Title  | All Rights Reserved.

I've also asked this question before Stack Overflow in here. But they were unable to give me a proper solution.

How I can do it...?


问:
Rank-Order Coding of a FFT spectrum in Python
I'm currently working on a Spiking Neural Network for Structural Health Monitoring, based on an acceleration dataset.

I need to do the event-driven encoding of the FFT obtained from the dataset (which is a 129x5651 matrix).
Sensor FFT

This is the Rank Order Code to implement in Python for my specific work:

```<code># Algorithm 1: Compute Time-to-Event
# input : A signal S of I coefficients and a inference time tinf
# output :A Time-to-Event T array of I spiking intervals

m = min(S);
M = max(S);
for i ← 0 to I − 1 do
   t = (S[i] − m)/(M − m);
   tcheck = round(1/t);
   if tcheck ≤ tinf then
     T[i] = tcheck
   end
end
return T;
</code>```

This is the function I wrote to emulate that, where I can choose a suitable tinf and I:

```<code>def get_spikes(FFT, tinf, I):

    m = np.min(FFT);
    M = np.max(FFT);

    T = [];
    tcheck= [];
    t= [];

    for i in range(0, I-1):
      t= (FFT[i]-m)/(M-m);
      tcheck= np.around((1/t), decimals=3);
      if (tcheck <= tinf):
        T= tcheck;
    return T;
</code>```

but when I try to run the code I get this error, and I don't understand why:

```<code>ValueError                                Traceback (most recent call last)
<ipython-input-72-e1029f7d67a4> in <module>
 ---> 1 encoding= get_spikes(S,tinf,I);
      2 print(encoding);

<ipython-input-71-f0b6636c3797> in get_spikes(data, tinf, InputNeurons)
     11       t= (data[i]-m)/(M-m);
     12       tcheck= np.around((1/t), decimals=3);
---> 13       if (tcheck <= tinf):
     14         T= tcheck;
     15     return T;

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
</code>```

How can I get the same result as the first code?

Body:
I'm currently working on a Spiking Neural Network for Structural Health Monitoring, based on an acceleration dataset.

I need to do the event-driven encoding of the FFT obtained from the dataset (which is a 129x5651 matrix).
Sensor FFT

This is the Rank Order Code to implement in Python for my specific work:

# Algorithm 1: Compute Time-to-Event
# input : A signal S of I coefficients and a inference time tinf
# output :A Time-to-Event T array of I spiking intervals

m = min(S);
M = max(S);
for i ← 0 to I − 1 do
   t = (S[i] − m)/(M − m);
   tcheck = round(1/t);
   if tcheck ≤ tinf then
     T[i] = tcheck
   end
end
return T;

This is the function I wrote to emulate that, where I can choose a suitable tinf and I:

def get_spikes(FFT, tinf, I):

    m = np.min(FFT);
    M = np.max(FFT);

    T = [];
    tcheck= [];
    t= [];

    for i in range(0, I-1):
      t= (FFT[i]-m)/(M-m);
      tcheck= np.around((1/t), decimals=3);
      if (tcheck <= tinf):
        T= tcheck;
    return T;

but when I try to run the code I get this error, and I don't understand why:

ValueError                                Traceback (most recent call last)
<ipython-input-72-e1029f7d67a4> in <module>
 ---> 1 encoding= get_spikes(S,tinf,I);
      2 print(encoding);

<ipython-input-71-f0b6636c3797> in get_spikes(data, tinf, InputNeurons)
     11       t= (data[i]-m)/(M-m);
     12       tcheck= np.around((1/t), decimals=3);
---> 13       if (tcheck <= tinf):
     14         T= tcheck;
     15     return T;

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

How can I get the same result as the first code?


问:
How to effectively use explicit argument names to clear up "magic numbers" in this polymorphic context
I have this code:

```<code>    class Base
    {
        public:
          Base(int attributeA, int attributeB, int attributeC) : attributeA_(attributeA),
              attributeB_(attributeB), attributeC_(attributeC) {}
        private:
          int attributeA_;
          int attributeB_;
          int attributeC_;
    }
</code>```

And then I have a couple child classes like this

```<code>class ChildA : public Base
{
   public:
     ChildA() : Base(1, 2, 3) {} // magic values
}

class ChildB : public Base
{
   public:
     ChildB() : Base(4, 1, 7) {} // magic values
}
</code>```

t's hard for me to remember what arguments go in what order (they aren't actually called A B C so when I see Base(4, 1, 7), I might say "What is 1 doing already?". A solution I came up with is the following:

```<code>class ChildA : public Base
{
   public:
     ChildA() : Base(attributeA, attributeB, attributeC) {} // no magic values
   private:
     static constexpr int attributeA = 1;
     static constexpr int attributeB = 2;
     static constexpr int attributeC = 3;
}

class ChildB : public Base
{
   public:
     ChildB() : Base(attributeA, attributeB, attributeC) {} // no magic values
   private:
     static constexpr int attributeA = 4;
     static constexpr int attributeB = 1;
     static constexpr int attributeC = 7;
}
</code>```

And now it's crystal clear that when I see 1 in ChildB's call the Base, I know it will be set to attributeB. I'm unsure this is a great solution because ChildA and B already have access to the protected values of Base attributeA_ and so forth as well as the private static declarations. This means that from the child classes we have two different variables to access the same value.

Since these variables are only used once, I was thinking on just putting them in the header file. Such as

child_b.h:

```<code>  static constexpr int attributeA = 4;
  static constexpr int attributeB = 1;
  static constexpr int attributeC = 7;

class ChildB : public Base
{
   public:
     ChildB() : Base(attributeA, attributeB, attributeC) {}
}
</code>```

That way, ChildB can only access the attributeB with the protected variable from Base attributeB_. This solution works fine for one child class, but if I do this for multiple header files and include them there's redefinition conflicts (since they have the same name). Is there a good way for me to have these argument hints without having the data accessible twice inside of the class? I guess I could do the second solution and use static constexpr int childBattributeB = 1. Alternatively, perhaps my concern is not that bad and I should just roll with my first solution. Thoughts?

Body:
I have this code:

    class Base
    {
        public:
          Base(int attributeA, int attributeB, int attributeC) : attributeA_(attributeA),
              attributeB_(attributeB), attributeC_(attributeC) {}
        private:
          int attributeA_;
          int attributeB_;
          int attributeC_;
    }

And then I have a couple child classes like this

class ChildA : public Base
{
   public:
     ChildA() : Base(1, 2, 3) {} // magic values
}

class ChildB : public Base
{
   public:
     ChildB() : Base(4, 1, 7) {} // magic values
}

t's hard for me to remember what arguments go in what order (they aren't actually called A B C so when I see Base(4, 1, 7), I might say "What is 1 doing already?". A solution I came up with is the following:

class ChildA : public Base
{
   public:
     ChildA() : Base(attributeA, attributeB, attributeC) {} // no magic values
   private:
     static constexpr int attributeA = 1;
     static constexpr int attributeB = 2;
     static constexpr int attributeC = 3;
}

class ChildB : public Base
{
   public:
     ChildB() : Base(attributeA, attributeB, attributeC) {} // no magic values
   private:
     static constexpr int attributeA = 4;
     static constexpr int attributeB = 1;
     static constexpr int attributeC = 7;
}

And now it's crystal clear that when I see 1 in ChildB's call the Base, I know it will be set to attributeB. I'm unsure this is a great solution because ChildA and B already have access to the protected values of Base attributeA_ and so forth as well as the private static declarations. This means that from the child classes we have two different variables to access the same value.

Since these variables are only used once, I was thinking on just putting them in the header file. Such as

child_b.h:

  static constexpr int attributeA = 4;
  static constexpr int attributeB = 1;
  static constexpr int attributeC = 7;

class ChildB : public Base
{
   public:
     ChildB() : Base(attributeA, attributeB, attributeC) {}
}

That way, ChildB can only access the attributeB with the protected variable from Base attributeB_. This solution works fine for one child class, but if I do this for multiple header files and include them there's redefinition conflicts (since they have the same name). Is there a good way for me to have these argument hints without having the data accessible twice inside of the class? I guess I could do the second solution and use static constexpr int childBattributeB = 1. Alternatively, perhaps my concern is not that bad and I should just roll with my first solution. Thoughts?


问:
Getting gradle sync failed error when I try creating a module
I tried creating a module in Android Studio. The module appears in my project structure but not the sidebar. Its dependencies aren't showing up under gradle scripts and I'm getting an error message saying that gradle sync failed.

I tried creating a module named MeepMeepTesting in Android Studio using New --> Module --> Java or Kotlin Library. I gave the library and class the same name. The module shows up in my Project Structure, but not in the sidebar, and I also cannot find its build.gradle under Gradle Scripts. This is the error I get when I tried creating the module: Gradle project sync failed. Basic functionality (e.g. editing, debugging) will not work properly. In my build window, I'm getting the message "null"

I updated my gradle and made sure I'm not in offline mode.

I'm unsure why this is happening, as I have already completed this process twice successfully.


问:
Find the shortest cycle in a directed graph passing through certain nodes
I have a weighted directed graph G, including the vertices V and edges E. I have certain nodes, namely S, which are the subset of the set V. Among the nodes in S, one of them is considered as the starting point, namely, t.

How can I find the shortest cycle that starts from t, passes through the nodes in S, and ends at t?  I am wondering if the starting point plays an important role in our problem.

I saw a similar question asked before in the below link, but the question in the link says that the cycle passes through at list one of the nodes in the set U, which in our case is the set S. In fact, in my case the cycle must pass through all the nodes in the set U or in my case set S.
Finding the lightest path to one vertex from all others in a graph

A similar question in the below link asks for the path, not the cycle I am looking for.
Find the shortest path in a graph which visits certain nodes

A similar question in the below link concerns an undirected graph, while in my case, the graph is directed.
Finding shortest circuit in a graph that visits X nodes at least once


问:
Function overloading with C++20 concepts but different cv-qualifiers: call is ambiguous
Minimal example:

```<code>#include <iostream>
#include <concepts>

using namespace std;

void foo(const auto&)
{
    cout << "const auto&" << endl;
}

void foo(integral auto)
{
    cout << "integral" << endl;
}

int main()
{
    foo(5.5);
    foo(5);

    return 0;
}
</code>```

In the case of foo(5.5), the argument is not integral so there is no ambuigity
and const auto& is printed.

In the case of foo(5), everything would also be fine if generic foo was defined with just auto.
But with const auto&, both functions are defined with different cv-qualifiers and it might be uncertain which one should be viable for the overload resolution.

GCC 12.2.0 fails with call of overloaded ‘foo(int)’ is ambiguous

However, Clang 14.0.6 works "as desired" and the resulting program prints integral.

What does the standard say here? I suppose it is not an undefined situation, so one of the compilers is probably not compliant with the standard...

Body:
Minimal example:

#include <iostream>
#include <concepts>

using namespace std;

void foo(const auto&)
{
    cout << "const auto&" << endl;
}

void foo(integral auto)
{
    cout << "integral" << endl;
}

int main()
{
    foo(5.5);
    foo(5);

    return 0;
}

In the case of foo(5.5), the argument is not integral so there is no ambuigity
and const auto& is printed.

In the case of foo(5), everything would also be fine if generic foo was defined with just auto.
But with const auto&, both functions are defined with different cv-qualifiers and it might be uncertain which one should be viable for the overload resolution.

GCC 12.2.0 fails with call of overloaded ‘foo(int)’ is ambiguous

However, Clang 14.0.6 works "as desired" and the resulting program prints integral.

What does the standard say here? I suppose it is not an undefined situation, so one of the compilers is probably not compliant with the standard...


问:
CSRF Token keeps refreshing every 2nd request. (Spring boot 3 and Next.JS)
I've been creating a Spring boot 3 and Next.JS app with Spring Security.  Been having some problems with the "Set-Cookie" header being refreshed on every 2nd request I make to the backend. I can illustrate the problem as:

Make a request to /finances (with XSRF-TOKEN provided post-successful login)

The request goes through (contains all the necessary data for a valid request [CSRF cookie, JWT token, etc..]).  The response contains a "Set-Cookie: XSRF-TOKEN= ...." header without the TOKEN.

I refresh the page (make a new request using the useEffect hook) and the CSRF cookie appears again, a new one.

If i refresh the page (make a new request using the useEffect hook) again, the CSRF cookie is deleted.

And so on.

I pass the cookie value on every request to the backend (whenever it is available) and the backend operates on it correctly. So there are no problems with the token validation.

I've also read that the spring security will provide a new XSRF cookie/value if the request from the client does not provide a cookie of the same name.

Could some one please help?

I've tried configuring the response on the backend to attach a new cookie with the same value, and also saving the cookie value in the session storage for later use. None of the options seem to work.

Making two requests to the server would solve the issue (probably) but that would not be an optimal solution. To the problem.