问:
Trying to capture data while in a recursive function
I'm working on a personal project to try and help me learn and understand python better.  Presently, I have a decent sized nested dictionary and the information is updating correctly to it.  So what I'm attempting to do is, while I'm going through the nested dictionary, I'm trying to capture all the key, values that have been updated from the previous process.  That means that the values are either 0 or higher than that.

Here are some snippets of the "test area" I've been playing with the data in.
This is the class structure that I've been using.  The nested dictionary is self.skills.

```<code>class Character:
    def __init__(self):
        self.characteristics = {'STR': 0, 'DEX': 0, 'END': 0, 'INT': 0, 'EDU': 0, 'SOC': 0}
        self.other_characteristics = {'MOR': 0, 'LUCK': 0, 'SAN': 0, 'CHA': 0, 'PSI': 0, 'OTHER': 0}
        self.first_name = ''
        self.last_name = ''
        self.age = 18
        self.species = ''
        self.gender = ''
        self.home_world = ''
        self.traits = []
        self.allies = []
        self.contacts = []
        self.rivals = []
        self.enemies = []
        self.pension = ''
        self.debt = ''
        self.honors = False
        self.graduated = False
        self.survival_roll = ''
        self.advancement_roll = ''
        self.pre_career_tries = 0
        self.career_rank = -1
        self.life_terms = {}
        self.dice_modifier = {'STR': 0, 'DEX': 0, 'END': 0, 'INT': 0, 'EDU': 0, 'SOC': 0}
        self.other_dice_modifier = {'MOR': 0, 'LUCK': 0, 'SAN': 0, 'CHA': 0, 'PSI': 0, 'OTHER': 0}
        self.events = []
        self.title = ''
        self.career = 'hippo'
        self.skills = {'Admin': -1, 'Advocate': -1, 'Animals': {'Handling': -1, 'Veterinary': -1, 'Training': -1},
                       'Art': {'Performer': -1, 'Holography': -1, 'Instrument': -1, 'Visual Media': -1, 'Write': -1},
                       'Astrogation': -1, 'Athletics': {'Dexterity': -1, 'Endurance': -1, 'Strength': -1},
                       'Broker': -1, 'Carouse': -1, 'Deception': -1, 'Diplomat': -1,
                       'Drive': {'Hovercraft': -1, 'Mole': -1, 'Track': -1, 'Walker': -1, 'Wheel': -1},
                       'Electronics': {'Comms': -1, 'Computers': -1, 'Remote Ops': -1, 'Sensors': -1},
                       'Engineer': {'M-drive': -1, 'J-drive': -1, 'Life Support': -1, 'Power': -1},
                       'Explosives': -1,
                       'Flyer': {'Airship': -1, 'Grav': -1, 'Ornithopter': -1, 'Rotor': -1, 'Wing': -1}, 'Gambler': -1,
                       'Gunner': {'Turret': -1, 'Ortillery': -1, 'Screen': -1, 'Capital': -1},
                       'Gun Combat': {'Archaic': -1, 'Energy': -1, 'Slug': -1},
                       'Heavy Weapons': {'Artillery': -1, 'Portable': -1, 'Vehicle': -1}, 'Investigate': -1,
                       'Jack-of-All-Trades': -1,
                       'Language': {'Galanglic': -1, 'Vilani': -1, 'Zdetl': -1, 'Oynprith': -1, 'Trokh': -1,
                                    'Gvegh': -1}, 'Leadership': -1, 'Mechanic': -1, 'Medic': -1,
                       'Melee': {'Unarmed': -1, 'Blade': -1, 'Bludgeon': -1, 'Natural': -1}, 'Navigation': -1,
                       'Persuade': -1, 'Pilot': {'Small Craft': -1, 'Spacecraft': -1, 'Capital Ships': -1},
                       'Profession': {'Belter': -1, 'Biologicals': -1, 'Civil Engineering': -1, 'Construction': -1,
                                      'Hydroponics': -1, 'Polymers': -1}, 'Recon': -1,
                       'Science': {'Archaeology': -1, 'Astronomy': -1, 'Biology': -1, 'Chemistry': -1, 'Cosmology': -1,
                                   'Cybernetics': -1, 'Economics': -1, 'Genetics': -1, 'History': -1, 'Linguistics': -1,
                                   'Philosophy': -1, 'Physics': -1, 'Planetology': -1, 'Psionicology': -1,
                                   'Psychology': -1, 'Robotics': -1, 'Sophontology': -1, 'Xenology': -1},
                       'Seafarer': {'Ocean Ships': -1, 'Personal': -1, 'Sail': -1, 'Submarine': -1}, 'Stealth': -1,
                       'Steward': -1, 'Streetwise': -1, 'Survival': -1, 'Tactics': {'Military': -1, 'Naval': -1},
                       'Vacc Suit': -1}
</code>```

Here is the list of skills that I'm pushing off to another function called assign_all_skills.  This portion is working correctly.  It's the portion afterwards that I'm having issues with.

```<code>skill = [['Admin'], ['Animals'], ['Art'], ['Athletics'], ['Carouse'], ['Drive'], ['Electronics'], ['Flyer'],
         ['Language'], ['Mechanic'], ['Medic'], ['Profession'], ['Science'], ['Seafarer'], ['Streetwise'], ['Survival'],
         ['Vacc Suit']]

choice = input('Would you like to do the next thing?  ').lower()
if choice[0] == 'y':
    mil.display()
    assign_skills.assign_all_skills(mil, skill)
    acquired_skills = dict_walk(mil.skills)
    print(f'{acquired_skills}')
</code>```

Here is the recursive function that I put together from the research that I've done.  It prints out correctly and shows all the information the way that I want it, now.

```<code>def dict_walk(d):
    test = []
    for k, v in d.items():
        if type(v) == dict:
            print(k)
            dict_walk(v)
        if type(v) == int and v >= 0:
            print(k, v)
            test.append([k, v])
        else:
            continue

    return test
</code>```

BLUF:  What I'm trying to do is have a comprehensive list that I can display to the user showing what skills they have selected(key), what rank they have been updated too(value) and  printed out in a way that isn't offensive to the eyes (currently what I'm working on).

Here is the print out that I get at the end.  The individual lines are what's produced from the recursive function.  The list of lists at the end, that's supposed to be all of the entries above that have a key, value pair that meets the criteria for printing.

```<code>Admin 0
Animals
Handling 0
Art
Holography 0
Athletics
Strength 0
Carouse 0
Drive
Hovercraft 0
Electronics
Computers 0
Engineer
Flyer
Ornithopter 0
Gunner
Gun Combat
Heavy Weapons
Language
Galanglic 0
Mechanic 0
Medic 0
Melee
Pilot
Profession
Biologicals 0
Science
Biology 0
Seafarer
Ocean Ships 0
Streetwise 0
Survival 0
Tactics
Vacc Suit 0
[['Admin', 0], ['Handling', 0], ['Holography', 0], ['Strength', 0], ['Carouse', 0], ['Hovercraft', 0], ['Computers', 0], ['Ornithopter', 0], ['Galanglic', 0], ['Mechanic', 0], ['Medic', 0], ['Biologicals', 0], ['Biology', 0], ['Ocean Ships', 0], ['Streetwise', 0], ['Survival', 0], ['Vacc Suit', 0]]
</code>```

My question now is, what I have now is a super long list of items that I want to print out aesthetically pleasing.  It's going to be a dynamic list, so it could be 10 entries long, it could be 27.  Is there a way to break a list up uniformly to print it out neatly instead of just printing off of the screen?  Any insight would be greatly appreciated.

Body:
I'm working on a personal project to try and help me learn and understand python better.  Presently, I have a decent sized nested dictionary and the information is updating correctly to it.  So what I'm attempting to do is, while I'm going through the nested dictionary, I'm trying to capture all the key, values that have been updated from the previous process.  That means that the values are either 0 or higher than that.

Here are some snippets of the "test area" I've been playing with the data in.
This is the class structure that I've been using.  The nested dictionary is self.skills.

class Character:
    def __init__(self):
        self.characteristics = {'STR': 0, 'DEX': 0, 'END': 0, 'INT': 0, 'EDU': 0, 'SOC': 0}
        self.other_characteristics = {'MOR': 0, 'LUCK': 0, 'SAN': 0, 'CHA': 0, 'PSI': 0, 'OTHER': 0}
        self.first_name = ''
        self.last_name = ''
        self.age = 18
        self.species = ''
        self.gender = ''
        self.home_world = ''
        self.traits = []
        self.allies = []
        self.contacts = []
        self.rivals = []
        self.enemies = []
        self.pension = ''
        self.debt = ''
        self.honors = False
        self.graduated = False
        self.survival_roll = ''
        self.advancement_roll = ''
        self.pre_career_tries = 0
        self.career_rank = -1
        self.life_terms = {}
        self.dice_modifier = {'STR': 0, 'DEX': 0, 'END': 0, 'INT': 0, 'EDU': 0, 'SOC': 0}
        self.other_dice_modifier = {'MOR': 0, 'LUCK': 0, 'SAN': 0, 'CHA': 0, 'PSI': 0, 'OTHER': 0}
        self.events = []
        self.title = ''
        self.career = 'hippo'
        self.skills = {'Admin': -1, 'Advocate': -1, 'Animals': {'Handling': -1, 'Veterinary': -1, 'Training': -1},
                       'Art': {'Performer': -1, 'Holography': -1, 'Instrument': -1, 'Visual Media': -1, 'Write': -1},
                       'Astrogation': -1, 'Athletics': {'Dexterity': -1, 'Endurance': -1, 'Strength': -1},
                       'Broker': -1, 'Carouse': -1, 'Deception': -1, 'Diplomat': -1,
                       'Drive': {'Hovercraft': -1, 'Mole': -1, 'Track': -1, 'Walker': -1, 'Wheel': -1},
                       'Electronics': {'Comms': -1, 'Computers': -1, 'Remote Ops': -1, 'Sensors': -1},
                       'Engineer': {'M-drive': -1, 'J-drive': -1, 'Life Support': -1, 'Power': -1},
                       'Explosives': -1,
                       'Flyer': {'Airship': -1, 'Grav': -1, 'Ornithopter': -1, 'Rotor': -1, 'Wing': -1}, 'Gambler': -1,
                       'Gunner': {'Turret': -1, 'Ortillery': -1, 'Screen': -1, 'Capital': -1},
                       'Gun Combat': {'Archaic': -1, 'Energy': -1, 'Slug': -1},
                       'Heavy Weapons': {'Artillery': -1, 'Portable': -1, 'Vehicle': -1}, 'Investigate': -1,
                       'Jack-of-All-Trades': -1,
                       'Language': {'Galanglic': -1, 'Vilani': -1, 'Zdetl': -1, 'Oynprith': -1, 'Trokh': -1,
                                    'Gvegh': -1}, 'Leadership': -1, 'Mechanic': -1, 'Medic': -1,
                       'Melee': {'Unarmed': -1, 'Blade': -1, 'Bludgeon': -1, 'Natural': -1}, 'Navigation': -1,
                       'Persuade': -1, 'Pilot': {'Small Craft': -1, 'Spacecraft': -1, 'Capital Ships': -1},
                       'Profession': {'Belter': -1, 'Biologicals': -1, 'Civil Engineering': -1, 'Construction': -1,
                                      'Hydroponics': -1, 'Polymers': -1}, 'Recon': -1,
                       'Science': {'Archaeology': -1, 'Astronomy': -1, 'Biology': -1, 'Chemistry': -1, 'Cosmology': -1,
                                   'Cybernetics': -1, 'Economics': -1, 'Genetics': -1, 'History': -1, 'Linguistics': -1,
                                   'Philosophy': -1, 'Physics': -1, 'Planetology': -1, 'Psionicology': -1,
                                   'Psychology': -1, 'Robotics': -1, 'Sophontology': -1, 'Xenology': -1},
                       'Seafarer': {'Ocean Ships': -1, 'Personal': -1, 'Sail': -1, 'Submarine': -1}, 'Stealth': -1,
                       'Steward': -1, 'Streetwise': -1, 'Survival': -1, 'Tactics': {'Military': -1, 'Naval': -1},
                       'Vacc Suit': -1}

Here is the list of skills that I'm pushing off to another function called assign_all_skills.  This portion is working correctly.  It's the portion afterwards that I'm having issues with.

skill = [['Admin'], ['Animals'], ['Art'], ['Athletics'], ['Carouse'], ['Drive'], ['Electronics'], ['Flyer'],
         ['Language'], ['Mechanic'], ['Medic'], ['Profession'], ['Science'], ['Seafarer'], ['Streetwise'], ['Survival'],
         ['Vacc Suit']]

choice = input('Would you like to do the next thing?  ').lower()
if choice[0] == 'y':
    mil.display()
    assign_skills.assign_all_skills(mil, skill)
    acquired_skills = dict_walk(mil.skills)
    print(f'{acquired_skills}')

Here is the recursive function that I put together from the research that I've done.  It prints out correctly and shows all the information the way that I want it, now.

def dict_walk(d):
    test = []
    for k, v in d.items():
        if type(v) == dict:
            print(k)
            dict_walk(v)
        if type(v) == int and v >= 0:
            print(k, v)
            test.append([k, v])
        else:
            continue

    return test

BLUF:  What I'm trying to do is have a comprehensive list that I can display to the user showing what skills they have selected(key), what rank they have been updated too(value) and  printed out in a way that isn't offensive to the eyes (currently what I'm working on).

Here is the print out that I get at the end.  The individual lines are what's produced from the recursive function.  The list of lists at the end, that's supposed to be all of the entries above that have a key, value pair that meets the criteria for printing.

Admin 0
Animals
Handling 0
Art
Holography 0
Athletics
Strength 0
Carouse 0
Drive
Hovercraft 0
Electronics
Computers 0
Engineer
Flyer
Ornithopter 0
Gunner
Gun Combat
Heavy Weapons
Language
Galanglic 0
Mechanic 0
Medic 0
Melee
Pilot
Profession
Biologicals 0
Science
Biology 0
Seafarer
Ocean Ships 0
Streetwise 0
Survival 0
Tactics
Vacc Suit 0
[['Admin', 0], ['Handling', 0], ['Holography', 0], ['Strength', 0], ['Carouse', 0], ['Hovercraft', 0], ['Computers', 0], ['Ornithopter', 0], ['Galanglic', 0], ['Mechanic', 0], ['Medic', 0], ['Biologicals', 0], ['Biology', 0], ['Ocean Ships', 0], ['Streetwise', 0], ['Survival', 0], ['Vacc Suit', 0]]

My question now is, what I have now is a super long list of items that I want to print out aesthetically pleasing.  It's going to be a dynamic list, so it could be 10 entries long, it could be 27.  Is there a way to break a list up uniformly to print it out neatly instead of just printing off of the screen?  Any insight would be greatly appreciated.


来源: stackexchange

问:
call usb cam stream function into kv ScreenManager as VR Screen
I'm new to python. I learned it a bit as I need to make an app interface into my endoscope. I am trying to call my usb endoscope camera into my kv file to view it in VR VRLeft and VRRight on 1 screen in my VR Box goggles.
The usb cam capture code in the function cam_connect() itself works. I only placed in the function within the

```<code>class VRWindow(Screen):
</code>```

in order to call it from the vrgui.kv FloatLayout to be displayed. I plan on using screen manager to switch between VR view and standard view, but I just want to be able to view the camera feed for now as two (Left/Right) feeds on 1 screen. I will work out the ScreenManager later. I am not sure how to just display the camera feed only. Do I use the Label: format?

See below for my files:
test3.py

import cv2
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.lang import Builder
from kivy.uix.widget import Widget
from kivy.uix.label import Label
from kivy.uix.floatlayout import FloatLayout

class VRWindow(Screen):
    def cam_connect(self):
        cap=cv2.VideoCapture(0)
        while cap.isOpened():
            ret, frame=cap.read()
            cv2.imshow('VR',frame)
            # if cv2.waitKey(1) & 0xFF == ord('q'):
            #     break
    pass

class Window(Screen):
    pass

class ScreenManger(ScreenManager):
    pass

kv = Builder.load_file('vrgui.kv')

class VRApp(App):
    def build(self):
        return kv

if __name__ == '__main__':
    VRApp().run()

#For webcam testing connectivity
capture=cv2.VideoCapture(0)

# showing values of the properties
print("CV_CAP_PROP_FRAME_WIDTH: '{}'".format(capture.get(cv2.CAP_PROP_FRAME_WIDTH)))
print("CV_CAP_PROP_FRAME_HEIGHT : '{}'".format(capture.get(cv2.CAP_PROP_FRAME_HEIGHT)))
print("CAP_PROP_FPS : '{}'".format(capture.get(cv2.CAP_PROP_FPS)))
print("CAP_PROP_POS_MSEC : '{}'".format(capture.get(cv2.CAP_PROP_POS_MSEC)))
print("CAP_PROP_FRAME_COUNT : '{}'".format(capture.get(cv2.CAP_PROP_FRAME_COUNT)))
print("CAP_PROP_BRIGHTNESS : '{}'".format(capture.get(cv2.CAP_PROP_BRIGHTNESS)))
print("CAP_PROP_CONTRAST : '{}'".format(capture.get(cv2.CAP_PROP_CONTRAST)))
print("CAP_PROP_SATURATION : '{}'".format(capture.get(cv2.CAP_PROP_SATURATION)))
print("CAP_PROP_HUE : '{}'".format(capture.get(cv2.CAP_PROP_HUE)))
print("CAP_PROP_GAIN : '{}'".format(capture.get(cv2.CAP_PROP_GAIN)))
print("CAP_PROP_CONVERT_RGB : '{}'".format(capture.get(cv2.CAP_PROP_CONVERT_RGB)))

```
<p>here is my <code>vrgui.kv</code></p>
<p>I tried to call the function using <code>root.cam_connect()</code>, but it throws the below error. I know I am not calling or passing he function correctly:</p>
``` kivy.lang.parser.ParserException: Parser: File "C:\Users\natea\OneDrive\Documents\python\system\310\sandbox\Lib\site-packages\vrgui.kv", line 16:
 ...
      14:            pos_hint: {'x': 0, 'y': .0}
      15:            size_hint: .5, 1.0
 >>   16:            root.cam_connect()
      17:        Label:
      18:            text: 'VRRight'
 ...
 Invalid property name
```
<p>Thank you for your insight and patience. python Newb here. Greatly appreciated.</p>
<p>vrgui.kv</p>
```ScreenManager:
    VRWindow:
    Window:

<VRWindow>:
    name: "first"

    FloatLayout:
        #orientation:'horizontal'
        Label:
            text: 'VRLeft'
            size: root.width, root.height
            pos_hint: {'x': 0, 'y': .0}
            size_hint: .5, 1.0
            #root.cam_connect()
        Label:
            text: 'VRRight'
            size: root.width, root.height
            pos_hint: {'x': .5, 'y': .0}
            size_hint: .5, 1.0
            #root.cam_connect()
<Window>:
    name: "second"

    FloatLayout:
        #orientation:'horizontal'
        size: root.width, root.height
        pos_hint: {'x': 0, 'y': .0}
        size_hint: 1.0, 1.0
        #root.cam_connect()
```

ContentLicense: CC BY-SA 4.0

Body:
I'm new to python. I learned it a bit as I need to make an app interface into my endoscope. I am trying to call my usb endoscope camera into my kv file to view it in VR VRLeft and VRRight on 1 screen in my VR Box goggles.
The usb cam capture code in the function cam_connect() itself works. I only placed in the function within the

class VRWindow(Screen):

in order to call it from the vrgui.kv FloatLayout to be displayed. I plan on using screen manager to switch between VR view and standard view, but I just want to be able to view the camera feed for now as two (Left/Right) feeds on 1 screen. I will work out the ScreenManager later. I am not sure how to just display the camera feed only. Do I use the Label: format?

See below for my files:
test3.py

import cv2
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.lang import Builder
from kivy.uix.widget import Widget
from kivy.uix.label import Label
from kivy.uix.floatlayout import FloatLayout

class VRWindow(Screen):
    def cam_connect(self):
        cap=cv2.VideoCapture(0)
        while cap.isOpened():
            ret, frame=cap.read()
            cv2.imshow('VR',frame)
            # if cv2.waitKey(1) & 0xFF == ord('q'):
            #     break
    pass

class Window(Screen):
    pass

class ScreenManger(ScreenManager):
    pass

kv = Builder.load_file('vrgui.kv')

class VRApp(App):
    def build(self):
        return kv

if __name__ == '__main__':
    VRApp().run()

#For webcam testing connectivity
capture=cv2.VideoCapture(0)

# showing values of the properties
print("CV_CAP_PROP_FRAME_WIDTH: '{}'".format(capture.get(cv2.CAP_PROP_FRAME_WIDTH)))
print("CV_CAP_PROP_FRAME_HEIGHT : '{}'".format(capture.get(cv2.CAP_PROP_FRAME_HEIGHT)))
print("CAP_PROP_FPS : '{}'".format(capture.get(cv2.CAP_PROP_FPS)))
print("CAP_PROP_POS_MSEC : '{}'".format(capture.get(cv2.CAP_PROP_POS_MSEC)))
print("CAP_PROP_FRAME_COUNT : '{}'".format(capture.get(cv2.CAP_PROP_FRAME_COUNT)))
print("CAP_PROP_BRIGHTNESS : '{}'".format(capture.get(cv2.CAP_PROP_BRIGHTNESS)))
print("CAP_PROP_CONTRAST : '{}'".format(capture.get(cv2.CAP_PROP_CONTRAST)))
print("CAP_PROP_SATURATION : '{}'".format(capture.get(cv2.CAP_PROP_SATURATION)))
print("CAP_PROP_HUE : '{}'".format(capture.get(cv2.CAP_PROP_HUE)))
print("CAP_PROP_GAIN : '{}'".format(capture.get(cv2.CAP_PROP_GAIN)))
print("CAP_PROP_CONVERT_RGB : '{}'".format(capture.get(cv2.CAP_PROP_CONVERT_RGB)))

here is my vrgui.kv

I tried to call the function using root.cam_connect(), but it throws the below error. I know I am not calling or passing he function correctly:

 kivy.lang.parser.ParserException: Parser: File "C:\Users\natea\OneDrive\Documents\python\system\310\sandbox\Lib\site-packages\vrgui.kv", line 16:
 ...
      14:            pos_hint: {'x': 0, 'y': .0}
      15:            size_hint: .5, 1.0
 >>   16:            root.cam_connect()
      17:        Label:
      18:            text: 'VRRight'
 ...
 Invalid property name

Thank you for your insight and patience. python Newb here. Greatly appreciated.

vrgui.kv

ScreenManager:
    VRWindow:
    Window:

<VRWindow>:
    name: "first"

    FloatLayout:
        #orientation:'horizontal'
        Label:
            text: 'VRLeft'
            size: root.width, root.height
            pos_hint: {'x': 0, 'y': .0}
            size_hint: .5, 1.0
            #root.cam_connect()
        Label:
            text: 'VRRight'
            size: root.width, root.height
            pos_hint: {'x': .5, 'y': .0}
            size_hint: .5, 1.0
            #root.cam_connect()
<Window>:
    name: "second"

    FloatLayout:
        #orientation:'horizontal'
        size: root.width, root.height
        pos_hint: {'x': 0, 'y': .0}
        size_hint: 1.0, 1.0
        #root.cam_connect()


问:
How to bypass pyqtgraph's built-in methods?
I'm trying to plot a grid of squares given in the following format
{'p0a0': [[1255.1929931640625, 1430.1819458007812, 1428.170166015625, 1253.1811828613281, 1255.1929931640625], [407.78900146484375, 409.629638671875, 600.617431640625, 598.7767791748047, 407.78900146484375]], 'p0a1': ....} and once plotted it should look like this
I'm trying to pyqtgraph.PlotDataItem.setData() method. My idea was to use a for loop to iterate over all the keys in the dictionary and plot all the grid points (squares) in the same plot but, the setData() method inherently any clears previous data before plotting. Resulting in giving me the following output only one square is highlighted instead of all 64 squares
So, my question is how do I bypass the built-in resting when I call .setData() method? or If that can't be done, would anyone have a suggestion to go arround it?

I tryed giving the whole dictionary but, it didn't work. also I tried other ploting items but, couldn't find anything that works for my requiremnts.


问:
API Loop through vba excel
I'm very new to API coding but I have created an API Code that inputs pressure and outputs temperature for a specific refrigerant on a website. However, I can only call for one refrigerant at a time, I was wondering if it is possible to create a string with all the refrigerant id (refId) numbers, so the API code could run through all of them in one long run?

```<code>Option Explicit

Public Function GetPressureFromTemp(ByVal Temperature As Double) As Double
    Dim body As String

    body = "{""Temperature"":""" & Temperature & """,""refId"":""r13"",""temperatureUnit"":""fahrenheit"",""pressureUnit"":""psi"","
    body = body & """pressureReferencePoint"":""gauge"","
    body = body & """pressureCalculationPoint"":""bubble"",""gaugeType"":""dry"",""altitudeInMeter"":0}"

    With CreateObject("MSXML2.XMLHTTP")
        .Open "POST", "https://reftools.danfoss.com/api/ref-slider/Pressure?refId=r13", False
        .setRequestHeader "content-type", "application/json; charset=utf-8"
        .send body
        GetPressureFromTemp = CDbl(.responseText)
    End With
End Function

Public Sub test()
Dim n As Double
Dim a As Double
a = 4984
n = -150.8

Do Until n >= 74.93
n = n + 0.1

'Debug.Print GetPressureFromTemp(n)
 Range("J" & a) = GetPressureFromTemp(n)
 a = a + 1

Loop

End Sub
</code>```

I'm not sure how to loop through each ref ID, however I have the whole list containing the refrigerant id

Title: API Loop through vba excel

Body:
I'm very new to API coding but I have created an API Code that inputs pressure and outputs temperature for a specific refrigerant on a website. However, I can only call for one refrigerant at a time, I was wondering if it is possible to create a string with all the refrigerant id (refId) numbers, so the API code could run through all of them in one long run?

Option Explicit

Public Function GetPressureFromTemp(ByVal Temperature As Double) As Double
    Dim body As String

    body = "{""Temperature"":""" & Temperature & """,""refId"":""r13"",""temperatureUnit"":""fahrenheit"",""pressureUnit"":""psi"","
    body = body & """pressureReferencePoint"":""gauge"","
    body = body & """pressureCalculationPoint"":""bubble"",""gaugeType"":""dry"",""altitudeInMeter"":0}"

    With CreateObject("MSXML2.XMLHTTP")
        .Open "POST", "https://reftools.danfoss.com/api/ref-slider/Pressure?refId=r13", False
        .setRequestHeader "content-type", "application/json; charset=utf-8"
        .send body
        GetPressureFromTemp = CDbl(.responseText)
    End With
End Function

Public Sub test()
Dim n As Double
Dim a As Double
a = 4984
n = -150.8

Do Until n >= 74.93
n = n + 0.1

'Debug.Print GetPressureFromTemp(n)
 Range("J" & a) = GetPressureFromTemp(n)
 a = a + 1

Loop

End Sub

I'm not sure how to loop through each ref ID, however I have the whole list containing the refrigerant id


问:
How to do error handling in dropdown flutter
Hi I am using dropdown_search: ^3.0.1 and list of the data in dropdown is from api. So, what I would like to ask is.. when data from api is throwing error, I would like to show something like warning icon that there was an error while getting data from api. Here is part of the code

```<code>DropdownSearch<String>(
      errorBuilder: (context, message, errorMessage) {
        print("error is running");
        return Center(
          child: Text("error")
        );
      },
      mode: Mode.MENU,
      maxHeight: 250,
      showSelectedItems: true,
      items: dataShow,
      onChanged: (value) {
       ...... // my function
      },
      selectedItem: valData
      showSearchBox: true,
    );
</code>```

I have used errorBuilder here but don't know when it is fired

Body:
Hi I am using dropdown_search: ^3.0.1 and list of the data in dropdown is from api. So, what I would like to ask is.. when data from api is throwing error, I would like to show something like warning icon that there was an error while getting data from api. Here is part of the code

DropdownSearch<String>(
      errorBuilder: (context, message, errorMessage) {
        print("error is running");
        return Center(
          child: Text("error")
        );
      },
      mode: Mode.MENU,
      maxHeight: 250,
      showSelectedItems: true,
      items: dataShow,
      onChanged: (value) {
       ...... // my function
      },
      selectedItem: valData
      showSearchBox: true,
    );

I have used errorBuilder here but don't know when it is fired


问:
Capitalized Component Not Rendering in React
I am importing a component, but it does not render. The component is capitalized. I think there is something wrong with the import statement because when I remove it and replace  with "Navbar", it renders, but if i keep the import then it does not render.

```<code>import styles from "./style";
import { Billing, Business, CardDeal, Clients, CTA, Footer, Navbar, Stats, Testimonials, Hero }
from "./components";

const App = () => { return (
  <div className="bg-primary w-full overflow-hidden">
    <div className={`${styles.paddingX} ${styles.flexCenter}`}>
      <div className={`${styles.boxWidth}`}>

        <Navbar />
      </div>
    </div>

  </div>
);
  };

export default App;
</code>```
```<code>import React from 'react';

const Navbar = () => {
  return (
    <div>Navbar</div>
  );
};

export default Navbar;
</code>```
```<code>import Navbar from "./Navbar";
import Billing from "./Billing";
import CardDeal from "./CardDeal";
import Business from "./Business";
import Clients from "./Clients";
import CTA from "./CTA";
import Stats from "./Stats";
import Footer from "./Footer";
import Testimonials from "./Testimonials";
import Hero from "./Hero";

export {
  Navbar,
  Billing,
  CardDeal,
  Business,
  Clients,
  CTA,
  Stats,
  Footer,
  Testimonials,
  Hero,
};
</code>```

If i exchange the component

for basic text like "Navbar" or "Navbar" it does not render either. These 2 display when I remove the import components statement.
When i control click , it brings me to the correct Navbar component.

I am following a yt tutorial
https://github.com/adrianhajdin/project_hoobank

my repo is here: https://github.com/lukasmckaine22/userbet_landing_page

I made sure the component was capitalized. I confirmed the component actually leads to the correct component by control clicking it. I confirmed the code renders plain text only when the import is removed. I confirmed the import leads to the correct file by control clicking. I tried only importing the Navbar with and without brackets. I changed the import directory to pull the navbar directory.

Body:
I am importing a component, but it does not render. The component is capitalized. I think there is something wrong with the import statement because when I remove it and replace  with "Navbar", it renders, but if i keep the import then it does not render.

import styles from "./style";
import { Billing, Business, CardDeal, Clients, CTA, Footer, Navbar, Stats, Testimonials, Hero }
from "./components";

const App = () => { return (

    <div className={`${styles.paddingX} ${styles.flexCenter}`}>
      <div className={`${styles.boxWidth}`}>

        <Navbar />

);
  };

export default App;

import React from 'react';

const Navbar = () => {
  return (

Navbar

  );
};

export default Navbar;

import Navbar from "./Navbar";
import Billing from "./Billing";
import CardDeal from "./CardDeal";
import Business from "./Business";
import Clients from "./Clients";
import CTA from "./CTA";
import Stats from "./Stats";
import Footer from "./Footer";
import Testimonials from "./Testimonials";
import Hero from "./Hero";

export {
  Navbar,
  Billing,
  CardDeal,
  Business,
  Clients,
  CTA,
  Stats,
  Footer,
  Testimonials,
  Hero,
};

If i exchange the component

for basic text like "Navbar" or "Navbar" it does not render either. These 2 display when I remove the import components statement.
When i control click , it brings me to the correct Navbar component.

I am following a yt tutorial
https://github.com/adrianhajdin/project_hoobank

my repo is here: https://github.com/lukasmckaine22/userbet_landing_page

I made sure the component was capitalized. I confirmed the component actually leads to the correct component by control clicking it. I confirmed the code renders plain text only when the import is removed. I confirmed the import leads to the correct file by control clicking. I tried only importing the Navbar with and without brackets. I changed the import directory to pull the navbar directory.


问:
Error: Request failed with status code 404 in react native on a working API call
I'm facing an issue from axios which is returning a 404 error on api call. This
API end point is already using many times in my application but in a particular scenario this API is returning 404 error status in catch block. Here is the scenario..

I have created an invite link to my application and when a user click on the invite link they will redirect to the Application and on startup I'm displaying a popup component with buttons. when the user click the button to join a particular event on the Application axios patch request is returning 404 error status on catch block. But in other cases this API is working fine. Anybody knows how this is happening..

here is the code sample

```<code>{gameId != "" &&
      <GameInvitationPopup
        id={gameId}
        setGameId={setGameId}
      />
    }
</code>```

When we click on the GameInvitation pupup,

```<code> <View style={{ alignItems: 'center', marginVertical: 20 }}>
                                <Text style={styles.h3Black}>Will you join the game?</Text>
                                <View style={[styles.rowFlex, { marginTop: 10 }]}>
                                    <TouchableOpacity
                                        onPress={() => updateGameData(1)}
                                        activeOpacity={0.6}
                                        style={styles.yesView}>
                                        <Text style={styles.h3Medium}>Yes</Text>
                                    </TouchableOpacity>
                                    <TouchableOpacity
                                        onPress={() => updateGameData(2)}
                                        activeOpacity={0.6}
                                        style={styles.noView}>
                                        <Text style={styles.h3Medium}>No</Text>
                                    </TouchableOpacity>
                                    <TouchableOpacity
                                        onPress={() => updateGameData(3)}
                                        activeOpacity={0.6}
                                        style={styles.maybeView}>
                                        <Text style={styles.h3Medium}>Maybe</Text>
                                    </TouchableOpacity>
                                </View>
                            </View>
</code>```

When we click on the updateGameData function,

```<code>const updateGameData = (stat) => {

    setLoading(true)
   gameStatusUpdateApiNw(id, stat)
        .then((out) => {
            setGameId("")
            setLoading(false)
            setShowAlert(true)
        })
        .catch(() => {

            setLoading(false)
        })
}
</code>```

This is the API request code, this API is a working API and and the body provide is correct, but still I'm getting 404 error status,

```<code>  const gameStatusUpdateApiNw = async (id, status) => {
  const state = store.default.getState();
  const token = state.authReducer.authToken;
  const url = `${BASE_URL}/api/games/status/${id}`;
  console.log('status url is ', url);
  try {
    const {data} = await patchRequest(
      url,
      {status: status},
      {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      },
    );
    console.log('data game ', data);
    return data;
  } catch (e) {
    throw e;
  }
};
</code>```

Anybody knows how this error occur in a working API when we provide correct body into it. Please help

Body:
I'm facing an issue from axios which is returning a 404 error on api call. This
API end point is already using many times in my application but in a particular scenario this API is returning 404 error status in catch block. Here is the scenario..

I have created an invite link to my application and when a user click on the invite link they will redirect to the Application and on startup I'm displaying a popup component with buttons. when the user click the button to join a particular event on the Application axios patch request is returning 404 error status on catch block. But in other cases this API is working fine. Anybody knows how this is happening..

here is the code sample

{gameId != "" &&
      <GameInvitationPopup
        id={gameId}
        setGameId={setGameId}
      />
    }

When we click on the GameInvitation pupup,

 <View style={{ alignItems: 'center', marginVertical: 20 }}>
                                <Text style={styles.h3Black}>Will you join the game?</Text>
                                <View style={[styles.rowFlex, { marginTop: 10 }]}>
                                    <TouchableOpacity
                                        onPress={() => updateGameData(1)}
                                        activeOpacity={0.6}
                                        style={styles.yesView}>
                                        <Text style={styles.h3Medium}>Yes</Text>
                                    </TouchableOpacity>
                                    <TouchableOpacity
                                        onPress={() => updateGameData(2)}
                                        activeOpacity={0.6}
                                        style={styles.noView}>
                                        <Text style={styles.h3Medium}>No</Text>
                                    </TouchableOpacity>
                                    <TouchableOpacity
                                        onPress={() => updateGameData(3)}
                                        activeOpacity={0.6}
                                        style={styles.maybeView}>
                                        <Text style={styles.h3Medium}>Maybe</Text>
                                    </TouchableOpacity>
                                </View>
                            </View>

When we click on the updateGameData function,

const updateGameData = (stat) => {

    setLoading(true)
   gameStatusUpdateApiNw(id, stat)
        .then((out) => {
            setGameId("")
            setLoading(false)
            setShowAlert(true)
        })
        .catch(() => {

            setLoading(false)
        })
}

This is the API request code, this API is a working API and and the body provide is correct, but still I'm getting 404 error status,

  const gameStatusUpdateApiNw = async (id, status) => {
  const state = store.default.getState();
  const token = state.authReducer.authToken;
  const url = `${BASE_URL}/api/games/status/${id}`;
  console.log('status url is ', url);
  try {
    const {data} = await patchRequest(
      url,
      {status: status},
      {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      },
    );
    console.log('data game ', data);
    return data;
  } catch (e) {
    throw e;
  }
};

Anybody knows how this error occur in a working API when we provide correct body into it. Please help


问:
Why my chrome custom tab pops out every time I press back button
guys I want to ask why every time i pressed back button will pop out chrome customtab since I set for a few url only can be pop out chrome customtab but seem not working is there any problem?

Chrome customtab

```<code>public class Callback extends WebViewClient {

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
 if (!url.contains(".pdf") || url.contains("/report/PersonalPurchaseHistory") ||
  url.contains("/user/changeProfile") || url.contains("linkedin.com") ||
  url.contains("/bonus/MonthlyIncomeStatement")) {
  CustomTabsIntent.Builder customIntent = new CustomTabsIntent.Builder();
  customIntent.setToolbarColor(ContextCompat.getColor(MainActivity.this, R.color.purple_200));
 openCustomTab(MainActivity.this, customIntent.build(), Uri.parse(url));
}
else {
  view.loadUrl(url);
  }
 return true;
 }
}
</code>```

Back Press

```<code>@Override
    public void onBackPressed() {
        if (doubleBackToExitPressed == 2) {
            finishAffinity();
            System.exit(0);
        }
        else {
            doubleBackToExitPressed++;
            Toast.makeText(this, "Please press Back again to exit", Toast.LENGTH_SHORT).show();
            web.goBack();
        }

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                doubleBackToExitPressed=1;
            }
        }, 2000);
    }
</code>```

Body:
guys I want to ask why every time i pressed back button will pop out chrome customtab since I set for a few url only can be pop out chrome customtab but seem not working is there any problem?

Chrome customtab

public class Callback extends WebViewClient {

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
 if (!url.contains(".pdf") || url.contains("/report/PersonalPurchaseHistory") ||
  url.contains("/user/changeProfile") || url.contains("linkedin.com") ||
  url.contains("/bonus/MonthlyIncomeStatement")) {
  CustomTabsIntent.Builder customIntent = new CustomTabsIntent.Builder();
  customIntent.setToolbarColor(ContextCompat.getColor(MainActivity.this, R.color.purple_200));
 openCustomTab(MainActivity.this, customIntent.build(), Uri.parse(url));
}
else {
  view.loadUrl(url);
  }
 return true;
 }
}

Back Press

@Override
    public void onBackPressed() {
        if (doubleBackToExitPressed == 2) {
            finishAffinity();
            System.exit(0);
        }
        else {
            doubleBackToExitPressed++;
            Toast.makeText(this, "Please press Back again to exit", Toast.LENGTH_SHORT).show();
            web.goBack();
        }

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                doubleBackToExitPressed=1;
            }
        }, 2000);
    }


问:
Cookie error in node.JS app with next.js client program
I am actually write a node.JS application on natours project. It is actually a course project that was designed by jonas. I am designing a next.JS client side program of this backend program. Problem was that when I submit a request on http://localhost:3000/api/v1/users/signup url everything is ok, cookie is set but when I send a request on others url on this server like http://localhost:3000/api/v1/tours cookie is not read by the server and req.cookies is null. I am trying to solve this problem but I am stuck.

app.js Code

```<code>const express = require("express");
const morgan = require("morgan");
const bodyParser = require("body-parser");
const rateLimit = require("express-rate-limit");
const helmet = require("helmet");
const xss = require("xss-clean");
const mongoSanitize = require("express-mongo-sanitize");
const hpp = require("hpp");
const cors = require("cors");
const cookieParser = require("cookie-parser");

const globalErrorHandler = require("./controllers/errorController");
const tourRouter = require("./routes/tourRoutes");
const userRouter = require("./routes/userRoutes");
const reviewRouter = require("./routes/reviewRoutes");
const AppError = require("./utils/appError");
const app = express();

app.set("view engine", "pug");
app.set("views", `${__dirname}/views`);

// GLOBAL MIDDLEWARE
if (process.env.NODE_ENV === "development") {
  app.use(morgan("dev"));
}
const limiter = rateLimit({
  max: 100,
  windowMs: 60 * 60 * 1000,
  message: "Too many requests from this IP, Please try again in an hour.",
});
app.use(cors({ credentials: true, origin: "http://localhost:3001" }));
app.use(helmet());
app.use(xss());
app.use("/api", limiter);
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json({ limit: "10kb" }));
app.use(express.static(`${__dirname}/public`));
app.use(mongoSanitize());
app.use(
  hpp({
    whitelist: [
      "duration",
      "ratingsQuantiry",
      "ratingsAverage",
      "difficulty",
      "maxGroupSize",
      "price",
    ],
  })
);

app.use((req, res, next) => {
  req.requestTime = Date.now();
  console.log(req.cookies.jwt);

  next();
});

app.get("/", (req, res) => {
  res.status(200).render("base", {
    title: "Natours",
  });
});

app.use("/api/v1/tours", tourRouter);
app.use("/api/v1/users", userRouter);
app.use("/api/v1/reviews", reviewRouter);

app.all("*", (req, res, next) => {
  // res.status(404).json({
  //   status: "fail",
  //   message: `Can't find ${req.originalUrl} on ther server.`,
  // });
  const err = new AppError(
    `Can't find ${req.originalUrl} on ther server.`,
    404
  );
  next(err);
});

app.use(globalErrorHandler);
module.exports = app;

</code>```

Client Code in Next.js

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

import Layout from "../components/Layout";
const url = "http://localhost:3000/api/v1/users/signup";

const styles = {
  "input-group": "flex flex-col gap-3",
  "input-label": "px-2 text-md font-thin",
  "text-input": "px-2 py-4",
  button:
    "px-4 py-3 font-thin uppercase text-md bg-teal-700 hover:bg-teal-600 text-slate-50 rounded-sm",
  "cancle-button": "bg-red-700 hover:bg-red-600",
};

function Register() {
  const [formData, setFormData] = useState({
    name: "",
    email: "",
    password: "",
    passwordConfirm: "",
    photo: "",
  });

  const handleChange = (event) => {
    setFormData({
      ...formData,
      [event.target.name]: event.target.value,
    });
  };

  const handleSubmit = async (event) => {
    event.preventDefault();
    axios
      .post("http://localhost:3000/api/v1/users/signup", formData, {
        withCredentials: true,
      })
      .then((response) => console.log(response))
      .catch((err) => console.log(err));
    alert(JSON.stringify(formData));
  };

  const handleReset = (event) => {
    setFormData({
      name: "",
      email: "",
      password: "",
      passwordConfirm: "",
      photo: "",
    });
  };
  return (
    <Layout>
      <div className="p-10 bg-slate-50">
        <form onSubmit={handleSubmit}>
          <h1 className="text-2xl mb-5 text-teal-700">Register your account</h1>

          <div className="w-1/2 flex flex-col gap-3">
            <div className={styles["input-group"]}>
              <label className={styles["input-label"]}>Name</label>
              <input
                className={styles["text-input"]}
                placeholder="Enter your name"
                type="text"
                name="name"
                value={formData.name}
                onChange={handleChange}
                required
              />
            </div>
            <div className={styles["input-group"]}>
              <label className={styles["input-label"]}>Email</label>
              <input
                className={styles["text-input"]}
                placeholder="Enter your email"
                type="email"
                name="email"
                value={formData.email}
                onChange={handleChange}
                required
              />
            </div>
            <div className={styles["input-group"]}>
              <label className={styles["input-label"]}>Password</label>
              <input
                className={styles["text-input"]}
                placeholder="Enter your password"
                type="password"
                name="password"
                value={formData.password}
                onChange={handleChange}
                required
              />
            </div>
            <div className={styles["input-group"]}>
              <label className={styles["input-label"]}>Confirm Password</label>
              <input
                className={styles["text-input"]}
                placeholder="Enter your confirm password"
                type="password"
                name="passwordConfirm"
                value={formData.passwordConfirm}
                onChange={handleChange}
                required
              />
            </div>
          </div>

          <div className="bg-slate-100 flex gap-3 mt-5 px-3 py-6 w-1/2">
            <button className={styles.button} type="submit">
              Register
            </button>
            <button
              className={`${styles.button} ${styles["cancle-button"]}`}
              type="reset"
              onClick={handleReset}
            >
              Cancle
            </button>
          </div>
        </form>
      </div>
    </Layout>
  );
}

export default Register;

</code>```

Body:
I am actually write a node.JS application on natours project. It is actually a course project that was designed by jonas. I am designing a next.JS client side program of this backend program. Problem was that when I submit a request on http://localhost:3000/api/v1/users/signup url everything is ok, cookie is set but when I send a request on others url on this server like http://localhost:3000/api/v1/tours cookie is not read by the server and req.cookies is null. I am trying to solve this problem but I am stuck.

app.js Code

const express = require("express");
const morgan = require("morgan");
const bodyParser = require("body-parser");
const rateLimit = require("express-rate-limit");
const helmet = require("helmet");
const xss = require("xss-clean");
const mongoSanitize = require("express-mongo-sanitize");
const hpp = require("hpp");
const cors = require("cors");
const cookieParser = require("cookie-parser");

const globalErrorHandler = require("./controllers/errorController");
const tourRouter = require("./routes/tourRoutes");
const userRouter = require("./routes/userRoutes");
const reviewRouter = require("./routes/reviewRoutes");
const AppError = require("./utils/appError");
const app = express();

app.set("view engine", "pug");
app.set("views", `${__dirname}/views`);

// GLOBAL MIDDLEWARE
if (process.env.NODE_ENV === "development") {
  app.use(morgan("dev"));
}
const limiter = rateLimit({
  max: 100,
  windowMs: 60 * 60 * 1000,
  message: "Too many requests from this IP, Please try again in an hour.",
});
app.use(cors({ credentials: true, origin: "http://localhost:3001" }));
app.use(helmet());
app.use(xss());
app.use("/api", limiter);
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json({ limit: "10kb" }));
app.use(express.static(`${__dirname}/public`));
app.use(mongoSanitize());
app.use(
  hpp({
    whitelist: [
      "duration",
      "ratingsQuantiry",
      "ratingsAverage",
      "difficulty",
      "maxGroupSize",
      "price",
    ],
  })
);

app.use((req, res, next) => {
  req.requestTime = Date.now();
  console.log(req.cookies.jwt);

  next();
});

app.get("/", (req, res) => {
  res.status(200).render("base", {
    title: "Natours",
  });
});

app.use("/api/v1/tours", tourRouter);
app.use("/api/v1/users", userRouter);
app.use("/api/v1/reviews", reviewRouter);

app.all("*", (req, res, next) => {
  // res.status(404).json({
  //   status: "fail",
  //   message: `Can't find ${req.originalUrl} on ther server.`,
  // });
  const err = new AppError(
    `Can't find ${req.originalUrl} on ther server.`,
    404
  );
  next(err);
});

app.use(globalErrorHandler);
module.exports = app;

Client Code in Next.js

import React, { useState } from "react";
import axios from "axios";

import Layout from "../components/Layout";
const url = "http://localhost:3000/api/v1/users/signup";

const styles = {
  "input-group": "flex flex-col gap-3",
  "input-label": "px-2 text-md font-thin",
  "text-input": "px-2 py-4",
  button:
    "px-4 py-3 font-thin uppercase text-md bg-teal-700 hover:bg-teal-600 text-slate-50 rounded-sm",
  "cancle-button": "bg-red-700 hover:bg-red-600",
};

function Register() {
  const [formData, setFormData] = useState({
    name: "",
    email: "",
    password: "",
    passwordConfirm: "",
    photo: "",
  });

  const handleChange = (event) => {
    setFormData({
      ...formData,
      [event.target.name]: event.target.value,
    });
  };

  const handleSubmit = async (event) => {
    event.preventDefault();
    axios
      .post("http://localhost:3000/api/v1/users/signup", formData, {
        withCredentials: true,
      })
      .then((response) => console.log(response))
      .catch((err) => console.log(err));
    alert(JSON.stringify(formData));
  };

  const handleReset = (event) => {
    setFormData({
      name: "",
      email: "",
      password: "",
      passwordConfirm: "",
      photo: "",
    });
  };
  return (
    <Layout>

        <form onSubmit={handleSubmit}>

Register your account

              Name
              <input
                className={styles["text-input"]}
                placeholder="Enter your name"
                type="text"
                name="name"
                value={formData.name}
                onChange={handleChange}
                required
              />

              Email
              <input
                className={styles["text-input"]}
                placeholder="Enter your email"
                type="email"
                name="email"
                value={formData.email}
                onChange={handleChange}
                required
              />

              Password
              <input
                className={styles["text-input"]}
                placeholder="Enter your password"
                type="password"
                name="password"
                value={formData.password}
                onChange={handleChange}
                required
              />

              Confirm Password
              <input
                className={styles["text-input"]}
                placeholder="Enter your confirm password"
                type="password"
                name="passwordConfirm"
                value={formData.passwordConfirm}
                onChange={handleChange}
                required
              />

            <button className={styles.button} type="submit">
              Register
            </button>
            <button
              className={`${styles.button} ${styles["cancle-button"]}`}
              type="reset"
              onClick={handleReset}
            >
              Cancle
            </button>

        </form>

    </Layout>
  );
}

export default Register;


问:
Google Indexing Api in clojure
```<code>  (:require [utils.base64 :as base64])
  (:import [com.google.api.client.googleapis.auth.oauth2 GoogleCredential]
           [com.google.api.services.indexing.v3 Indexing]
           [com.google.api.services.indexing.v3.model UrlNotification]
           [com.google.api.client.http HttpTransport]
           [com.google.api.client.json.gson GsonFactory]
           [java.io ByteArrayInputStream]
           [java.util Base64]
           [com.google.api.services.indexing.v3 IndexingScopes]))

;; Set the private key and client email
(def private-key "")
(def client-email "my-client-email")

(def encoded-private-key (base64/encode-string private-key))

;; Set the private key and client email
(def private-key-json '{
                        "type": "service_account",
                        "client_email": "' client-email '",
                        "private_key": "' encoded-private-key '"
                        }')

;; Create the input stream from the JSON string
(def input-stream (ByteArrayInputStream. (.getBytes private-key-json)))

;; Create the OAuth 2.0 credentials
(def credentials (doto (GoogleCredential/fromStream input-stream)
                    (.createScoped (java.util.Collections/singleton IndexingScopes/INDEXING))))

;; Set up the HTTP transport and JSON factory
(def http-transport (HttpTransport/newTrustedTransport))
(def json-factory (GsonFactory/getDefaultInstance))

;; Set up the Indexing API client
(def indexing-client (doto (Indexing/Builder. http-transport json-factory credentials)
                       (.setApplicationName "My Indexing App")
                       (.build)))

;; Publish a URL notification
(def url-notification (UrlNotification. "https://aaa.com" "URL_UPDATED"))

(.execute (indexing-client/urlNotifications) (publish url-notification))
</code>```

I'm trying to use private-key-json but the format is not valid. What is the best way to pass data? I referred https://developers.google.com/search/apis/indexing-api/v3/prereqs#examples.
Here I'm trying not to upload json file which we get once we create a service account and make use of only mandatory fields like client_email, private_key and type fields.

Modified code:

```<code>  (:require [cheshire.core :as json]
            [sketches.utils.base64 :as base64]
            [clojure.string :as str])
  (:import [com.google.api.client.googleapis.auth.oauth2 GoogleCredential]
           [com.google.api.services.indexing.v3 Indexing$Builder]
           [com.google.api.services.indexing.v3.model UrlNotification]
           [com.google.api.client.googleapis.javanet GoogleNetHttpTransport]
           [com.google.api.client.http HttpTransport]
           [com.google.api.client.json.gson GsonFactory]
           [java.io ByteArrayInputStream]
           [com.google.api.services.indexing.v3 IndexingScopes]))

(def creds-json {:type "service_account",
                 :client_email "test-indexing-api",
                 :client_id "117578194507835125202",
                 :private_key_id "964321e5fc29980944da518887116ea50dfb7803",
                 :private_key ""})

(defn string->stream
  ([s] (string->stream s "UTF-8"))
  ([s encoding]
   (-> s
       (.getBytes encoding)
       (ByteArrayInputStream.))))

(defn authorize [cred]
  (-> cred
      (json/encode)
      (string->stream)
      (GoogleCredential/fromStream)
      (.createScoped [(IndexingScopes/INDEXING)])))

(defn valid-private-key [private-key]
  (try
    (when private-key
      (->> (str/trim private-key)
           (re-matches #"^-----BEGIN PRIVATE KEY-----[\s|\S]*-----END PRIVATE KEY-----[\\|n]*")
           (some?)))

    (catch Exception e
      false)))

(def encoded-private-key (base64/encode-string private-key))

(def private-creds-json-string (json/generate-string creds-json))

(def input-stream (ByteArrayInputStream. (.getBytes private-creds-json-string)))

(defn build-analytics-client [creds]
  (-> (Indexing$Builder. (GoogleNetHttpTransport/newTrustedTransport) (GsonFactory/getDefaultInstance) (authorize creds))
      (.build)))

(defn url-notification []
  (-> (UrlNotification.)
      (.setType "URL_update")
      (.setUrl "http://ace.madrid.quintype.io")))

(defn realtime-data [creds]
  (-> (build-analytics-client creds)
      (.urlNotifications)
      (.publish (url-notification))
      (.execute)))
    ```

But I get this error `Execution error (NoSuchMethodError) at com.google.api.client.http.ConsumingInputStream/close (ConsumingInputStream.java:40).
com.google.common.io.ByteStreams.exhaust(Ljava/io/InputStream;)J`
```

Title: Google Indexing Api in clojure

Body:
  (:require [utils.base64 :as base64])
  (:import [com.google.api.client.googleapis.auth.oauth2 GoogleCredential]
           [com.google.api.services.indexing.v3 Indexing]
           [com.google.api.services.indexing.v3.model UrlNotification]
           [com.google.api.client.http HttpTransport]
           [com.google.api.client.json.gson GsonFactory]
           [java.io ByteArrayInputStream]
           [java.util Base64]
           [com.google.api.services.indexing.v3 IndexingScopes]))

;; Set the private key and client email
(def private-key "")
(def client-email "my-client-email")

(def encoded-private-key (base64/encode-string private-key))

;; Set the private key and client email
(def private-key-json '{
                        "type": "service_account",
                        "client_email": "' client-email '",
                        "private_key": "' encoded-private-key '"
                        }')

;; Create the input stream from the JSON string
(def input-stream (ByteArrayInputStream. (.getBytes private-key-json)))

;; Create the OAuth 2.0 credentials
(def credentials (doto (GoogleCredential/fromStream input-stream)
                    (.createScoped (java.util.Collections/singleton IndexingScopes/INDEXING))))

;; Set up the HTTP transport and JSON factory
(def http-transport (HttpTransport/newTrustedTransport))
(def json-factory (GsonFactory/getDefaultInstance))

;; Set up the Indexing API client
(def indexing-client (doto (Indexing/Builder. http-transport json-factory credentials)
                       (.setApplicationName "My Indexing App")
                       (.build)))

;; Publish a URL notification
(def url-notification (UrlNotification. "https://aaa.com" "URL_UPDATED"))

(.execute (indexing-client/urlNotifications) (publish url-notification))

I'm trying to use private-key-json but the format is not valid. What is the best way to pass data? I referred https://developers.google.com/search/apis/indexing-api/v3/prereqs#examples.
Here I'm trying not to upload json file which we get once we create a service account and make use of only mandatory fields like client_email, private_key and type fields.

Modified code:

  (:require [cheshire.core :as json]
            [sketches.utils.base64 :as base64]
            [clojure.string :as str])
  (:import [com.google.api.client.googleapis.auth.oauth2 GoogleCredential]
           [com.google.api.services.indexing.v3 Indexing$Builder]
           [com.google.api.services.indexing.v3.model UrlNotification]
           [com.google.api.client.googleapis.javanet GoogleNetHttpTransport]
           [com.google.api.client.http HttpTransport]
           [com.google.api.client.json.gson GsonFactory]
           [java.io ByteArrayInputStream]
           [com.google.api.services.indexing.v3 IndexingScopes]))

(def creds-json {:type "service_account",
                 :client_email "test-indexing-api",
                 :client_id "117578194507835125202",
                 :private_key_id "964321e5fc29980944da518887116ea50dfb7803",
                 :private_key ""})

(defn string->stream
  ([s] (string->stream s "UTF-8"))
  ([s encoding]
   (-> s
       (.getBytes encoding)
       (ByteArrayInputStream.))))

(defn authorize [cred]
  (-> cred
      (json/encode)
      (string->stream)
      (GoogleCredential/fromStream)
      (.createScoped [(IndexingScopes/INDEXING)])))

(defn valid-private-key [private-key]
  (try
    (when private-key
      (->> (str/trim private-key)
           (re-matches #"^-----BEGIN PRIVATE KEY-----[\s|\S]*-----END PRIVATE KEY-----[\\|n]*")
           (some?)))

    (catch Exception e
      false)))

(def encoded-private-key (base64/encode-string private-key))

(def private-creds-json-string (json/generate-string creds-json))

(def input-stream (ByteArrayInputStream. (.getBytes private-creds-json-string)))

(defn build-analytics-client [creds]
  (-> (Indexing$Builder. (GoogleNetHttpTransport/newTrustedTransport) (GsonFactory/getDefaultInstance) (authorize creds))
      (.build)))

(defn url-notification []
  (-> (UrlNotification.)
      (.setType "URL_update")
      (.setUrl "http://ace.madrid.quintype.io")))

(defn realtime-data [creds]
  (-> (build-analytics-client creds)
      (.urlNotifications)
      (.publish (url-notification))
      (.execute)))
    ```

But I get this error `Execution error (NoSuchMethodError) at com.google.api.client.http.ConsumingInputStream/close (ConsumingInputStream.java:40).
com.google.common.io.ByteStreams.exhaust(Ljava/io/InputStream;)J`


问:
Anonymise selected column in R shiny using sapply
I am creating an R Shiny app, where a user can upload their own csv, and the app generates a synthetic dataset. I am trying to add an additional function where the user can select a column they wish to anonymise to make it a shareable file. The rest of the app is currently working, however when I select the column which I want to anonomise, when I press update, the datatable isn't refreshing.

Any help or insight here would be greatly appreciated! I've tried and tried to solve it, but am stuck.
A shortened/reproducible version of the code app is below

`

```<code>library(shiny)
library(synthpop)
library(DT)
library(tidyverse)
library(data.table)
library(rsconnect)
library(fontawesome)
library(DT)
library(htmltools)
library(shinythemes)
library(RcppRoll)
library(grid)
library(reactable)
library(shinydashboard)
library(shinydashboardPlus)
library(formattable)
library(dashboardthemes)
library(deidentifyr)
library(anonymizer)
library(digest)

# User interface
ui <- fluidPage(theme = shinytheme("cosmo"),

                navbarPage("Synthetic data",

                           # Upload data tab
                           tabPanel("Upload data",

                                    sidebarLayout(

                                      sidebarPanel(width = 3,

                                                   h4(strong("Upload original data")),
                                                   br(),
                                                   fileInput(inputId = "datafile", label = "1. Upload a csv file then press 'Update' below.
                               Note, the larger your dataset, the longer it will take to load", multiple = FALSE, placeholder = "No file selected",
                                                             accept = c("text/csv", "text/comma-separated-values,text/plain", ".csv")),

                                                   actionButton(inputId = "update", label = "Update", icon = icon("fas fa-sync")),

                                                   br(),
                                                   br(),

                                                   h5(strong("2. To view and download the synthesised dataset, click on the 'Synthetic data' tab at the top"))),

                                      mainPanel(dataTableOutput("table"), style = "font-size:80%"))),

                           # Synthetic data download
                           tabPanel("Synthetic data",

                                    sidebarLayout(

                                      sidebarPanel(width = 3,

                                                   h4(strong("Anonomise data?")),

                                                   br(),

                                                   uiOutput(outputId = "anon"),

                                                   br(),

                                                   actionButton(inputId = "update2", label = "Update", icon = icon("fas fa-sync"))),

                                      mainPanel(dataTableOutput("synth"), style = "font-size:75%"))),

                ))

# Server function
server <- function(input, output, session) {
  options(shiny.maxRequestSize=20*1024^2)

  contentsrea <- reactive({
    inFile <- input$datafile
    if(is.null(inFile))
      return(NULL)
    dataset <- read_csv(inFile$datapath)

  })

  observeEvent(input$update, {
    if(!is.null(input$datafile)){

      original <- read_csv(input$datafile$datapath)
      my.seed <- 17914709
      synResult <- syn(original, seed = my.seed, maxfaclevels = 150)

      # Synthetic data
      df <- synResult$syn

      # Add 'SYNTH' to column headings
      colnames(df) <- paste("SYNTH", colnames(df), sep="_")

      # Variable dropdown to anonomise data
      output$anon <- renderUI({

        selectInput(inputId = "anon",
                    label="1. Select the variable you'd like to anonomise (i.e., athlete name). If not necessary, leave as blank",
                    choices = c(" ", colnames(df)),
                    selected = NULL)
      })

      ## Original
      output$table <- DT::renderDataTable(original,
                                          caption = htmltools::tags$caption(
                                            style = 'caption-side: top; text-align: left; color: black; font-size:140%',
                                            h3(strong("Original data"))), server = FALSE, rownames=FALSE,
                                          options = list(bFilter=0, iDisplayLength=18,
                                                         columnDefs = list(list(className = 'dt-center', targets = '_all')),
                                                         dom = 'frtip'))

      # Synthetic dataset
      output$synth <- DT::renderDataTable(df,
                                          caption = htmltools::tags$caption(
                                          style = 'caption-side: top; text-align: left; color: black; font-size:140%',
                                          h3(strong("Simulated synthetic data"))),
                                          server = FALSE, rownames=FALSE, extensions = c("Buttons"),
                                          options = list(iDisplayLength=18, bFilter=0,
                                                         columnDefs = list(list(className = 'dt-center', targets = '_all')),
                                                         dom = 'Bfrtip'))

    }})
}

  # Synthetic dataset with update for anon
  observeEvent(input$update2, {
    if(!is.null(input$datafile)){

  output$synth <- DT::renderDataTable({

    # Anonomise
    df$ID <- sapply(input$anon, digest, algo = "crc32")

    datatable(df,
              caption = htmltools::tags$caption(
              style = 'caption-side: top; text-align: left; color: black; font-size:140%',
              h3(strong("Simulated synthetic data"))),
              server = FALSE, rownames=FALSE, extensions = c("Buttons"),
              options = list(iDisplayLength=18, bFilter=0,
                             columnDefs = list(list(className = 'dt-center', targets = '_all')),
                             dom = 'Bfrtip'))

  })

}})

# Run the app ----
shinyApp(ui, server)

</code>```

`

I have tried removing the update button ans using a reactive table, as well as other anonomise functions. I am completely stuck.

Body:
I am creating an R Shiny app, where a user can upload their own csv, and the app generates a synthetic dataset. I am trying to add an additional function where the user can select a column they wish to anonymise to make it a shareable file. The rest of the app is currently working, however when I select the column which I want to anonomise, when I press update, the datatable isn't refreshing.

Any help or insight here would be greatly appreciated! I've tried and tried to solve it, but am stuck.
A shortened/reproducible version of the code app is below

`

library(shiny)
library(synthpop)
library(DT)
library(tidyverse)
library(data.table)
library(rsconnect)
library(fontawesome)
library(DT)
library(htmltools)
library(shinythemes)
library(RcppRoll)
library(grid)
library(reactable)
library(shinydashboard)
library(shinydashboardPlus)
library(formattable)
library(dashboardthemes)
library(deidentifyr)
library(anonymizer)
library(digest)

# User interface
ui <- fluidPage(theme = shinytheme("cosmo"),

                navbarPage("Synthetic data",

                           # Upload data tab
                           tabPanel("Upload data",

                                    sidebarLayout(

                                      sidebarPanel(width = 3,

                                                   h4(strong("Upload original data")),
                                                   br(),
                                                   fileInput(inputId = "datafile", label = "1. Upload a csv file then press 'Update' below.
                               Note, the larger your dataset, the longer it will take to load", multiple = FALSE, placeholder = "No file selected",
                                                             accept = c("text/csv", "text/comma-separated-values,text/plain", ".csv")),

                                                   actionButton(inputId = "update", label = "Update", icon = icon("fas fa-sync")),

                                                   br(),
                                                   br(),

                                                   h5(strong("2. To view and download the synthesised dataset, click on the 'Synthetic data' tab at the top"))),

                                      mainPanel(dataTableOutput("table"), style = "font-size:80%"))),

                           # Synthetic data download
                           tabPanel("Synthetic data",

                                    sidebarLayout(

                                      sidebarPanel(width = 3,

                                                   h4(strong("Anonomise data?")),

                                                   br(),

                                                   uiOutput(outputId = "anon"),

                                                   br(),

                                                   actionButton(inputId = "update2", label = "Update", icon = icon("fas fa-sync"))),

                                      mainPanel(dataTableOutput("synth"), style = "font-size:75%"))),

                ))

# Server function
server <- function(input, output, session) {
  options(shiny.maxRequestSize=20*1024^2)

  contentsrea <- reactive({
    inFile <- input$datafile
    if(is.null(inFile))
      return(NULL)
    dataset <- read_csv(inFile$datapath)

  })

  observeEvent(input$update, {
    if(!is.null(input$datafile)){

      original <- read_csv(input$datafile$datapath)
      my.seed <- 17914709
      synResult <- syn(original, seed = my.seed, maxfaclevels = 150)

      # Synthetic data
      df <- synResult$syn

      # Add 'SYNTH' to column headings
      colnames(df) <- paste("SYNTH", colnames(df), sep="_")

      # Variable dropdown to anonomise data
      output$anon <- renderUI({

        selectInput(inputId = "anon",
                    label="1. Select the variable you'd like to anonomise (i.e., athlete name). If not necessary, leave as blank",
                    choices = c(" ", colnames(df)),
                    selected = NULL)
      })

      ## Original
      output$table <- DT::renderDataTable(original,
                                          caption = htmltools::tags$caption(
                                            style = 'caption-side: top; text-align: left; color: black; font-size:140%',
                                            h3(strong("Original data"))), server = FALSE, rownames=FALSE,
                                          options = list(bFilter=0, iDisplayLength=18,
                                                         columnDefs = list(list(className = 'dt-center', targets = '_all')),
                                                         dom = 'frtip'))

      # Synthetic dataset
      output$synth <- DT::renderDataTable(df,
                                          caption = htmltools::tags$caption(
                                          style = 'caption-side: top; text-align: left; color: black; font-size:140%',
                                          h3(strong("Simulated synthetic data"))),
                                          server = FALSE, rownames=FALSE, extensions = c("Buttons"),
                                          options = list(iDisplayLength=18, bFilter=0,
                                                         columnDefs = list(list(className = 'dt-center', targets = '_all')),
                                                         dom = 'Bfrtip'))

    }})
}

  # Synthetic dataset with update for anon
  observeEvent(input$update2, {
    if(!is.null(input$datafile)){

  output$synth <- DT::renderDataTable({

    # Anonomise
    df$ID <- sapply(input$anon, digest, algo = "crc32")

    datatable(df,
              caption = htmltools::tags$caption(
              style = 'caption-side: top; text-align: left; color: black; font-size:140%',
              h3(strong("Simulated synthetic data"))),
              server = FALSE, rownames=FALSE, extensions = c("Buttons"),
              options = list(iDisplayLength=18, bFilter=0,
                             columnDefs = list(list(className = 'dt-center', targets = '_all')),
                             dom = 'Bfrtip'))

  })

}})

# Run the app ----
shinyApp(ui, server)

`

I have tried removing the update button ans using a reactive table, as well as other anonomise functions. I am completely stuck.


问:
Can't apply filter to dynamic column in React
I'm building an application in React where I have a column built dynamically based on the value of other columns, but for some reason I can't apply a filter to this dynamic column, but in the other columns the filter works perfectly.

```<code>export const COLUMNS =  [
    {
        Header: 'Computer',
        accessor: 'Computer',
        Filter: ColumnFilter,
        disableSortBy: true,
        style: {'whiteSpace': 'unset'}

    },
    {
        Header: 'Platform',
        accessor: 'Platform',
        Filter: ColumnFilter,
        disableSortBy: true
    },
    {
        Header: 'Agent Version',
        accessor: 'Agent Version',
        Filter: ColumnFilter,
        disableSortBy: true
    },
    {
        Header: 'Policy Name',
        accessor: 'Policy Name',
        Filter: ColumnFilter,
        disableSortBy: true
    },
    {
        Header: 'Severity',
        accessor: 'Severity',
        disableSortBy: true,
        Cell: ({ row }) => {
           if(row.original['Agent Version'] !== '0.0.0.0'){
                if(
                row.original['Anti-Malware Enabled'] !== 'YES' |
                row.original['Machine Learning Enabled'] !== 'YES'  |
                row.original['Behavior Monitoring Enabled'] !== 'YES' |
                row.original['Backup and Restore Files Enabled'] !== 'YES' & row.original['Platform'].includes('Windows') |
                row.original['Scan Compressed Files Enabled'] !== 'YES' |
                row.original['Web Reputation Enabled'] !== 'YES' |
                row.original['Action for Behavior Monitoring'] !== 'YES'

                ){
                    return row.original['Severity'] = "Critical"
                }else if(

                    row.original['ScanActionForAmsi'] !== 'YES' & row.original['Platform'].includes('Windows')
                    ){
                    return row.original['Severity'] = "Warning"

                }else{
                    return row.original['Severity'] = "No Issues"

                }
        }else{
            return row.original['Severity'] = "No Data"

        }
    }

    },]
</code>```

Body:
I'm building an application in React where I have a column built dynamically based on the value of other columns, but for some reason I can't apply a filter to this dynamic column, but in the other columns the filter works perfectly.

export const COLUMNS =  [
    {
        Header: 'Computer',
        accessor: 'Computer',
        Filter: ColumnFilter,
        disableSortBy: true,
        style: {'whiteSpace': 'unset'}

    },
    {
        Header: 'Platform',
        accessor: 'Platform',
        Filter: ColumnFilter,
        disableSortBy: true
    },
    {
        Header: 'Agent Version',
        accessor: 'Agent Version',
        Filter: ColumnFilter,
        disableSortBy: true
    },
    {
        Header: 'Policy Name',
        accessor: 'Policy Name',
        Filter: ColumnFilter,
        disableSortBy: true
    },
    {
        Header: 'Severity',
        accessor: 'Severity',
        disableSortBy: true,
        Cell: ({ row }) => {
           if(row.original['Agent Version'] !== '0.0.0.0'){
                if(
                row.original['Anti-Malware Enabled'] !== 'YES' |
                row.original['Machine Learning Enabled'] !== 'YES'  |
                row.original['Behavior Monitoring Enabled'] !== 'YES' |
                row.original['Backup and Restore Files Enabled'] !== 'YES' & row.original['Platform'].includes('Windows') |
                row.original['Scan Compressed Files Enabled'] !== 'YES' |
                row.original['Web Reputation Enabled'] !== 'YES' |
                row.original['Action for Behavior Monitoring'] !== 'YES'

                ){
                    return row.original['Severity'] = "Critical"
                }else if(

                    row.original['ScanActionForAmsi'] !== 'YES' & row.original['Platform'].includes('Windows')
                    ){
                    return row.original['Severity'] = "Warning"

                }else{
                    return row.original['Severity'] = "No Issues"

                }
        }else{
            return row.original['Severity'] = "No Data"

        }
    }

    },]


问:
how to delete token django rest framework simple jwt
Currently users are being issued a new token each time they login in, so there are several outstanding tokens linked to each user. This means the user cannot be deleted.

How can I delete tokens?

I'm looking for resources rather than help with coding please.

Update:
been researching my query today and I found flushexpiredtokens which I set up as a command and ran in the CLI and got rid of the expired tokens. However the current tokens are still preventing the user from being deleted as they are an outstanding token.

I'm very new to Django. I have some questions now:

do I need to set up a cron job?

can I someone make a function that when a user presses delte, it first expires all current tokens, then flushes the expired tokens and then deletes the user?

I ran the flushexpiredcommand I created in the CLI, should these commands be executed from the UI?


问:
How to automate data extraction from many PDFs into Excel without Power Automate?
I have a set of PDF files that contain multiple tables but are all in the exact same format. I have tested data extraction on one file myself and have found the table of interest, and although the data extraction itself is messy and full of NAs, it's good enough to be salvaged with some cleaning.

My question then is how do I automate data extraction from these pdf files into a single table? I have tried some python PDF extraction libraries but the inbuilt excel tool seems to do the best job. Will this require VBA? I want this program to run on work computers and be run by other people.

Thanks.


问:
JPA adding insert for manyToMany table
I have got two entity. Employee and Project

```<code>
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import jakarta.persistence.*;
import lombok.*;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Entity
@Table(name = "EMPLOYEE_DB")
@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
public class Employee {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int emp_id;

    private String name;

    private String email;

    private String phone;

    @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinTable(name = "EMP_PRO_DB", joinColumns = {
            @JoinColumn(name = "empId", referencedColumnName = "emp_id")
    },
    inverseJoinColumns = {
            @JoinColumn(name = "proId", referencedColumnName = "pro_id")
    }
    )
//    @JsonManagedReference

    private Set<Project> projects;
}
</code>```

and

```<code>
import com.fasterxml.jackson.annotation.JsonBackReference;
import jakarta.persistence.*;
import lombok.*;

import java.util.Set;

@Entity
@Table(name = "PROJECT_DB")
@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
public class Project {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int pro_id;

    private String projectName;

    private String projectType;

    @ManyToMany(mappedBy = "projects", fetch = FetchType.LAZY)
    @JsonBackReference
    private Set<Employee> employees;

}
</code>```

So there were three tables created:

employee_db

project_db

emp_pro_db

I have a EmployeeRepo and ProjectRepo. I can add data to both employee_db and project_db.
Now I would like to assignProject.

I have tried using workbench to insert: INSERT INTO emp_pro_db (emp_id, pro_id) VALUES (1, 6);
Which is working.

How do I use Jpa to do that?

Title: JPA adding insert for manyToMany table

Body:
I have got two entity. Employee and Project

import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import jakarta.persistence.*;
import lombok.*;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Entity
@Table(name = "EMPLOYEE_DB")
@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
public class Employee {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int emp_id;

    private String name;

    private String email;

    private String phone;

    @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinTable(name = "EMP_PRO_DB", joinColumns = {
            @JoinColumn(name = "empId", referencedColumnName = "emp_id")
    },
    inverseJoinColumns = {
            @JoinColumn(name = "proId", referencedColumnName = "pro_id")
    }
    )
//    @JsonManagedReference

    private Set<Project> projects;
}

and

import com.fasterxml.jackson.annotation.JsonBackReference;
import jakarta.persistence.*;
import lombok.*;

import java.util.Set;

@Entity
@Table(name = "PROJECT_DB")
@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
public class Project {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int pro_id;

    private String projectName;

    private String projectType;

    @ManyToMany(mappedBy = "projects", fetch = FetchType.LAZY)
    @JsonBackReference
    private Set<Employee> employees;

}

So there were three tables created:

employee_db

project_db

emp_pro_db

I have a EmployeeRepo and ProjectRepo. I can add data to both employee_db and project_db.
Now I would like to assignProject.

I have tried using workbench to insert: INSERT INTO emp_pro_db (emp_id, pro_id) VALUES (1, 6);
Which is working.

How do I use Jpa to do that?


问:
How to exclude a file from a gitlab tag?
I created a tag after build/deploy job using gitlab api command.
curl --request POST --header "PRIVATE-TOKEN: <your_access_token>" "https://gitlab.example.com/api/v4/projects/5/repository/tags?tag_name=test&ref=master"

But I want to exclude one file from the tag when it's created.

Is there a way I can pass some arguments to exclude the file in the api command itself?


问:
What is reduced time precision and is it adding time to the results?
I just read that when using Date.now() it adds 2 ms reduced time precision. From the documentation:

Reduced time precision
To offer protection against timing attacks and
fingerprinting, the precision of Date.now() might get rounded
depending on browser settings. In Firefox, the
privacy.reduceTimerPrecision preference is enabled by default and
defaults to 20µs in Firefox 59; in 60 it will be 2ms.

Does that mean when I check the duration of my code using Date.now() it will add from 0 to 2ms to the difference?

No, I don't have performance.now in my Javascript environment. Don't ask.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now


问:
Connection bias in Cloud Run using http/2, GCLB
Connection bias in Cloud Run using http/2, GCLB

GCLB , Serverless NEG, CloudRun(http/2) is used to configure the backend.
This is a chart that records access counts per container by our own log-based metrics.

Request Count

Clearly, the containers appear to be grouped. And there appears to be a large bias in the number of requests between one group and another. (Not enough requests are being allocated to the container groups that have just been launched.)
This was not seen when http1 was used in the connection between GCLB and CloudRun.

During this time, application logs are normal(few 503), so there is no application layer limiting requests. (The metrics are based on the standard request log, so the only metric is whether or not the request was made.)

How should this be remedied?

CloudRun Setting is as below

```<code>    metadata:
      name: app
      annotations:
        run.googleapis.com/client-name: gcloud
        run.googleapis.com/client-version: 411.0.0
        autoscaling.knative.dev/minScale: '4'
        run.googleapis.com/execution-environment: gen2
        autoscaling.knative.dev/maxScale: '200'
        run.googleapis.com/cpu-throttling: 'false'
        run.googleapis.com/startup-cpu-boost: 'true'
    spec:
      containerConcurrency: 100
      timeoutSeconds: 300
      containers:
        ports:
        - name: h2c
          containerPort: 8080

</code>```

I have tried changing the number of containerConcurrency, but this does not improve things much. There is still an imbalance, as it appears that requests are allocated to containers that have just been launched or not allocated at all.

Body:
Connection bias in Cloud Run using http/2, GCLB

GCLB , Serverless NEG, CloudRun(http/2) is used to configure the backend.
This is a chart that records access counts per container by our own log-based metrics.

Request Count

Clearly, the containers appear to be grouped. And there appears to be a large bias in the number of requests between one group and another. (Not enough requests are being allocated to the container groups that have just been launched.)
This was not seen when http1 was used in the connection between GCLB and CloudRun.

During this time, application logs are normal(few 503), so there is no application layer limiting requests. (The metrics are based on the standard request log, so the only metric is whether or not the request was made.)

How should this be remedied?

CloudRun Setting is as below

    metadata:
      name: app
      annotations:
        run.googleapis.com/client-name: gcloud
        run.googleapis.com/client-version: 411.0.0
        autoscaling.knative.dev/minScale: '4'
        run.googleapis.com/execution-environment: gen2
        autoscaling.knative.dev/maxScale: '200'
        run.googleapis.com/cpu-throttling: 'false'
        run.googleapis.com/startup-cpu-boost: 'true'
    spec:
      containerConcurrency: 100
      timeoutSeconds: 300
      containers:
        ports:
        - name: h2c
          containerPort: 8080

I have tried changing the number of containerConcurrency, but this does not improve things much. There is still an imbalance, as it appears that requests are allocated to containers that have just been launched or not allocated at all.