问:
Type error when trying to push in a model's array Prisma, TypeScript, MongoDB
I don't know what type I should use in the following case:

Here is a part of my schema.prisma file:

```<code>model Device {
  id            String         @id @default(auto()) @map("_id") @db.ObjectId
  modules       Module[]
  sensorRecords SensorRecord[]
  plant         Plant?         @relation(fields: [plantId], references: [id])
  plantId       String?        @db.ObjectId
  User          User?          @relation(fields: [userId], references: [id])
  userId        String?        @db.ObjectId
}

type SensorRecord {
  sensorRecords IndividualSensorRecord
}

type IndividualSensorRecord {
  sensorUnit  String
  sensorData  Float?
  sensorState Boolean
  recordDate  DateTime @default(now())
}
</code>```

And here is the file where I encounter my problem:

```<code>import SensorDataRecord from '../interfaces/SensorDataRecord'
import prisma from '../utils/PrismaClient'

export default async function createSensorDataRecord (deviceId: string, data: SensorDataRecord): Promise<void> {
  const records: any = [ // fix this
    {
      sensorUnit: 'lm',
      sensorData: data.luminosity !== undefined ? data.luminosity : null,
      sensorState: data.luminosity !== undefined
    },
    {
      sensorUnit: 'S/m',
      sensorData: data.electro_conductivity !== undefined ? data.electro_conductivity : null,
      sensorState: data.electro_conductivity !== undefined
    },
    {
      sensorUnit: 'liters',
      sensorData: data.water_level !== undefined ? data.water_level : null,
      sensorState: data.water_level !== undefined
    },
    {
      sensorUnit: 'pH',
      sensorData: data.ph !== undefined ? data.ph : null,
      sensorState: data.ph !== undefined
    }
  ]

  await prisma.device.update({
    where: {
      id: deviceId
    },
    data: {
      sensorRecords: {
        push: records
      }
    }
  })
}
</code>```

I need help at the line 5 (// fix this comment). I don't know what the correct type should be. For now, only setting the variable as any type have worked.

I already tried IndividualSensorRecord[] but when I do so, I get the following error line 34 (in the update statement):

```<code>Type '{ push: IndividualSensorRecord[]; }' is not assignable to type '(Without<SensorRecordListUpdateEnvelopeInput, SensorRecordCreateInput> & SensorRecordCreateInput) | (Without<...> & SensorRecordListUpdateEnvelopeInput) | (Without<...> & SensorRecordCreateInput[])'.
  Types of property 'push' are incompatible.
    Type 'IndividualSensorRecord[]' is not assignable to type 'Enumerable<SensorRecordCreateInput> | ((...items: SensorRecordCreateInput[]) => number) | undefined'.
      Type 'IndividualSensorRecord[]' is not assignable to type 'SensorRecordCreateInput[]'.
        Type 'IndividualSensorRecord' has no properties in common with type 'SensorRecordCreateInput'.ts(2322)
index.d.ts(4771, 5): The expected type comes from property 'sensorRecords' which is declared here on type '(Without<DeviceUpdateInput, DeviceUncheckedUpdateInput> & DeviceUncheckedUpdateInput) | (Without<...> & DeviceUpdateInput)'
</code>```

I also tried without typing the variable or not pushing an array but a single value, but I've got the same error.

Body:
I don't know what type I should use in the following case:

Here is a part of my schema.prisma file:

model Device {
  id            String         @id @default(auto()) @map("_id") @db.ObjectId
  modules       Module[]
  sensorRecords SensorRecord[]
  plant         Plant?         @relation(fields: [plantId], references: [id])
  plantId       String?        @db.ObjectId
  User          User?          @relation(fields: [userId], references: [id])
  userId        String?        @db.ObjectId
}

type SensorRecord {
  sensorRecords IndividualSensorRecord
}

type IndividualSensorRecord {
  sensorUnit  String
  sensorData  Float?
  sensorState Boolean
  recordDate  DateTime @default(now())
}

And here is the file where I encounter my problem:

import SensorDataRecord from '../interfaces/SensorDataRecord'
import prisma from '../utils/PrismaClient'

export default async function createSensorDataRecord (deviceId: string, data: SensorDataRecord): Promise<void> {
  const records: any = [ // fix this
    {
      sensorUnit: 'lm',
      sensorData: data.luminosity !== undefined ? data.luminosity : null,
      sensorState: data.luminosity !== undefined
    },
    {
      sensorUnit: 'S/m',
      sensorData: data.electro_conductivity !== undefined ? data.electro_conductivity : null,
      sensorState: data.electro_conductivity !== undefined
    },
    {
      sensorUnit: 'liters',
      sensorData: data.water_level !== undefined ? data.water_level : null,
      sensorState: data.water_level !== undefined
    },
    {
      sensorUnit: 'pH',
      sensorData: data.ph !== undefined ? data.ph : null,
      sensorState: data.ph !== undefined
    }
  ]

  await prisma.device.update({
    where: {
      id: deviceId
    },
    data: {
      sensorRecords: {
        push: records
      }
    }
  })
}

I need help at the line 5 (// fix this comment). I don't know what the correct type should be. For now, only setting the variable as any type have worked.

I already tried IndividualSensorRecord[] but when I do so, I get the following error line 34 (in the update statement):

Type '{ push: IndividualSensorRecord[]; }' is not assignable to type '(Without<SensorRecordListUpdateEnvelopeInput, SensorRecordCreateInput> & SensorRecordCreateInput) | (Without<...> & SensorRecordListUpdateEnvelopeInput) | (Without<...> & SensorRecordCreateInput[])'.
  Types of property 'push' are incompatible.
    Type 'IndividualSensorRecord[]' is not assignable to type 'Enumerable<SensorRecordCreateInput> | ((...items: SensorRecordCreateInput[]) => number) | undefined'.
      Type 'IndividualSensorRecord[]' is not assignable to type 'SensorRecordCreateInput[]'.
        Type 'IndividualSensorRecord' has no properties in common with type 'SensorRecordCreateInput'.ts(2322)
index.d.ts(4771, 5): The expected type comes from property 'sensorRecords' which is declared here on type '(Without<DeviceUpdateInput, DeviceUncheckedUpdateInput> & DeviceUncheckedUpdateInput) | (Without<...> & DeviceUpdateInput)'

I also tried without typing the variable or not pushing an array but a single value, but I've got the same error.


来源: stackexchange

问:
Dplyr mutate pipe combine multiple columns of adjusted p values
R learner here!

I have a data.frame like this:

```<code>x = data.frame(genes = c("a", "b", "c"),
           pval1 = c(0.0003, NA, NA),
           pval2 = c(0.008, NA, 0.2),
           pval3 = c(0.0009, 0.000007, 0.000001) )
</code>```

I want to combine the p value columns with NA values row-wise using Fisher's (or other suitable stat) and create a new column. How can I do this within a dplyr pipe?

I have done the following, but its obviously not working!

```<code>out_x = x %>% dplyr::mutate(comb_p_val = ezlimma::combine_pvalues(., p.cols = "pval" ))
</code>```

Any help will be much appreciated. Thank you.

ContentLicense: CC BY-SA 4.0

Body:
R learner here!

I have a data.frame like this:

x = data.frame(genes = c("a", "b", "c"),
           pval1 = c(0.0003, NA, NA),
           pval2 = c(0.008, NA, 0.2),
           pval3 = c(0.0009, 0.000007, 0.000001) )

I want to combine the p value columns with NA values row-wise using Fisher's (or other suitable stat) and create a new column. How can I do this within a dplyr pipe?

I have done the following, but its obviously not working!

out_x = x %>% dplyr::mutate(comb_p_val = ezlimma::combine_pvalues(., p.cols = "pval" ))

Any help will be much appreciated. Thank you.


问:
Can not get user info with Spring Security SAML WITHOUT Spring Boot
I´m working on SAML integration in an older project but I can´t get the user information.

I've guided me with the response of this question:
https://stackoverflow.com/questions/70275050/spring-security-saml-identity-metadata-without-spring-boot

The project has these versions:
spring framework 5.3.24
spring security 5.6.10
opensaml 3.4.6

This is my code:

```<code>@Configuration
public class SAMLSecurityConfig {
    private static final String URL_METADATA = "https://auth-dev.mycompany.com/app/id/sso/saml/metadata";

    @Bean("samlRegistration")
    public RelyingPartyRegistrationRepository relyingPartyRegistrationRepository() {
        RelyingPartyRegistration relyingPartyRegistration = RelyingPartyRegistrations.fromMetadataLocation(URL_METADATA)
                .registrationId("id")
                .build();

        return new InMemoryRelyingPartyRegistrationRepository(relyingPartyRegistration);
    }
}
</code>```
```<code>@EnableWebSecurity
public class WebSecurity {

    @Configuration
    @Order(2)
    public static class SAMLSecurityFilter extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity httpSecurity) throws Exception {
            httpSecurity.saml2Login(Customizer.withDefaults())
                    .antMatcher("/login/assertion")
                    .authorizeRequests()
                    .anyRequest()
                    .authenticated();
        }
    }
}
</code>```
```<code>@Controller("loginController")
public class BoCRLoginController {

    @RequestMapping(value = "/login/assertion", method = {RequestMethod.POST},
            consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = MediaType.APPLICATION_XML_VALUE)
    public ResponseEntity<String> assertLoginData(@AuthenticationPrincipal Saml2AuthenticatedPrincipal principal) {
        System.out.println(principal);  //here I get a null
        return new ResponseEntity<>(HttpStatus.OK);
    }

}
</code>```

Once I did the login on okta the  class: Saml2AuthenticatedPrincipal comes null value.

Could you help me to know why I received null value on the object Saml2AuthenticatedPrincipal where suppose have to receive the user information?

Body:
I´m working on SAML integration in an older project but I can´t get the user information.

I've guided me with the response of this question:
https://stackoverflow.com/questions/70275050/spring-security-saml-identity-metadata-without-spring-boot

The project has these versions:
spring framework 5.3.24
spring security 5.6.10
opensaml 3.4.6

This is my code:

@Configuration
public class SAMLSecurityConfig {
    private static final String URL_METADATA = "https://auth-dev.mycompany.com/app/id/sso/saml/metadata";

    @Bean("samlRegistration")
    public RelyingPartyRegistrationRepository relyingPartyRegistrationRepository() {
        RelyingPartyRegistration relyingPartyRegistration = RelyingPartyRegistrations.fromMetadataLocation(URL_METADATA)
                .registrationId("id")
                .build();

        return new InMemoryRelyingPartyRegistrationRepository(relyingPartyRegistration);
    }
}

@EnableWebSecurity
public class WebSecurity {

    @Configuration
    @Order(2)
    public static class SAMLSecurityFilter extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity httpSecurity) throws Exception {
            httpSecurity.saml2Login(Customizer.withDefaults())
                    .antMatcher("/login/assertion")
                    .authorizeRequests()
                    .anyRequest()
                    .authenticated();
        }
    }
}

@Controller("loginController")
public class BoCRLoginController {

    @RequestMapping(value = "/login/assertion", method = {RequestMethod.POST},
            consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = MediaType.APPLICATION_XML_VALUE)
    public ResponseEntity<String> assertLoginData(@AuthenticationPrincipal Saml2AuthenticatedPrincipal principal) {
        System.out.println(principal);  //here I get a null
        return new ResponseEntity<>(HttpStatus.OK);
    }

}

Once I did the login on okta the  class: Saml2AuthenticatedPrincipal comes null value.

Could you help me to know why I received null value on the object Saml2AuthenticatedPrincipal where suppose have to receive the user information?


问:
Adding SwiftUI to UIKit, and navigation back to UIKit
I have an existing application that is entirely UIKit, but it has been decided that new views should be added in SwiftUI. I am trying to add a new onboarding tutorial which is entirely images and was easy to write in SwiftUI.

```<code>import SwiftUI

struct OnboardingView: View {

var body: some View {
    VStack {
        Spacer()

        ZStack {
            Image("Onboard 1")
                .resizable()
                .scaledToFit()
                .ignoresSafeArea()
                .cornerRadius(25)
                .shadow(color: .gray, radius: 10)

            ZStack {
                Rectangle()
                    .foregroundColor(.black)

                Button(action: {
                    //Navigate back to UIKit here
                }, label: {
                    Text("Exit Tutorial")
                        .foregroundColor(.white)
                        .font(.system(size: 14, weight: .bold))
                })
            }
            .frame(width: 120, height: 40)
            .cornerRadius(10)
            .shadow(color: .gray, radius: 10)
            .offset(x: 70, y: 135)

        }
        Spacer()

        Rectangle()
            .foregroundColor(.black)
            .frame(height: 40)
    }.navigationBarHidden(true)
}
}
</code>```

I've added a new ViewController using storyboard and used a UIHostingController to successfully show the SwiftUI onboarding screens:

```<code>import UIKit
import SwiftUI

class OnboardingII: UIViewController, UIPopoverPresentationControllerDelegate {
let hostingController = UIHostingController(rootView: OnboardingView())

override func viewDidLoad() {
    openSwiftUIOnboardingScreen()
}

func openSwiftUIOnboardingScreen() {
    addChildViewController(hostingController)
    view.addSubview(hostingController.view)

    hostingController.view.translatesAutoresizingMaskIntoConstraints = false
    hostingController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
    hostingController.view.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
    hostingController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
    hostingController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
    hostingController.didMove(toParent: self)
}

func endOnboarding() {
//Add navigation back to the main app here
print("End Onboarding called")
}
}
</code>```

I've been looking for 3 days now and tried about a dozen different ways of navigating away from the SwiftUI onboarding process and back to the UIKit portion of the app (which is 99% of the app) but I've been unsuccessful in every attempt so far. Below are a few of the things that I've tried:

Adding a segue to move back to the beginning of the app

performSegue(withIdentifier: "backToBanner", sender: nil)

The rest of the app is managed by a navigation controller, and I've tried to get back in at several different points including the main navigation controller and two sub controller using segues identified on the storyboard, but in each case the crash error states that those views are not in the current window hierarchy.

I have also tried the below code (one at a time):

```<code>let viewController: UIViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "TestVC") as UIViewController

  self.present(viewController, animated: false, completion: nil)

  dismiss(animated: true, completion: nil)
  popoverPresentationController?.delegate?.popoverPresentationControllerDidDismissPopover?(popoverPresentationController!)
  OnboardingII().dismiss(animated: false)
  OnboardingII().removeFromParentViewController()
  //BannerViewController.willMove(true)
  for child in BannerViewController().childViewControllers {child.removeFromParentViewController()}
  self.didMove(toParentViewController: self)
   hostingController.view.removeFromSuperview()
   hostingController.view.isHidden = true
   hostingController.view.backgroundColor = .blue
   hostingController.willMove(toParent: self)
   hostingController.removeFromParentViewController()
   hostingController.dismiss(animated: false)
   for child in hostingController.childViewControllers {child.removeFromParentViewController()}
   for child in hostingController.view.subviews {child.isHidden = true}
</code>```

Thinking there must be some way to dismiss the UIHostingController (or hiding it) or anyway to get back to UIKit but I haven't had any success.

The strangest part is that if I change the newest ViewController on the Storyboard from .fullScreen to .automatic then I can swipe down to move back from SwiftUI to UIKit. This isn't the desired way to navigate as a button tap to move has been requested, but I haven't been able to replicated this functionality through code at all, I've tried reviewing rewind segues, but then I started to think that the swipe down to go back to the previous view is something else, but there should be a way to call it via code right?

Body:
I have an existing application that is entirely UIKit, but it has been decided that new views should be added in SwiftUI. I am trying to add a new onboarding tutorial which is entirely images and was easy to write in SwiftUI.

import SwiftUI

struct OnboardingView: View {

var body: some View {
    VStack {
        Spacer()

        ZStack {
            Image("Onboard 1")
                .resizable()
                .scaledToFit()
                .ignoresSafeArea()
                .cornerRadius(25)
                .shadow(color: .gray, radius: 10)

            ZStack {
                Rectangle()
                    .foregroundColor(.black)

                Button(action: {
                    //Navigate back to UIKit here
                }, label: {
                    Text("Exit Tutorial")
                        .foregroundColor(.white)
                        .font(.system(size: 14, weight: .bold))
                })
            }
            .frame(width: 120, height: 40)
            .cornerRadius(10)
            .shadow(color: .gray, radius: 10)
            .offset(x: 70, y: 135)

        }
        Spacer()

        Rectangle()
            .foregroundColor(.black)
            .frame(height: 40)
    }.navigationBarHidden(true)
}
}

I've added a new ViewController using storyboard and used a UIHostingController to successfully show the SwiftUI onboarding screens:

import UIKit
import SwiftUI

class OnboardingII: UIViewController, UIPopoverPresentationControllerDelegate {
let hostingController = UIHostingController(rootView: OnboardingView())

override func viewDidLoad() {
    openSwiftUIOnboardingScreen()
}

func openSwiftUIOnboardingScreen() {
    addChildViewController(hostingController)
    view.addSubview(hostingController.view)

    hostingController.view.translatesAutoresizingMaskIntoConstraints = false
    hostingController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
    hostingController.view.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
    hostingController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
    hostingController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
    hostingController.didMove(toParent: self)
}

func endOnboarding() {
//Add navigation back to the main app here
print("End Onboarding called")
}
}

I've been looking for 3 days now and tried about a dozen different ways of navigating away from the SwiftUI onboarding process and back to the UIKit portion of the app (which is 99% of the app) but I've been unsuccessful in every attempt so far. Below are a few of the things that I've tried:

Adding a segue to move back to the beginning of the app

performSegue(withIdentifier: "backToBanner", sender: nil)

The rest of the app is managed by a navigation controller, and I've tried to get back in at several different points including the main navigation controller and two sub controller using segues identified on the storyboard, but in each case the crash error states that those views are not in the current window hierarchy.

I have also tried the below code (one at a time):

let viewController: UIViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "TestVC") as UIViewController

  self.present(viewController, animated: false, completion: nil)

  dismiss(animated: true, completion: nil)
  popoverPresentationController?.delegate?.popoverPresentationControllerDidDismissPopover?(popoverPresentationController!)
  OnboardingII().dismiss(animated: false)
  OnboardingII().removeFromParentViewController()
  //BannerViewController.willMove(true)
  for child in BannerViewController().childViewControllers {child.removeFromParentViewController()}
  self.didMove(toParentViewController: self)
   hostingController.view.removeFromSuperview()
   hostingController.view.isHidden = true
   hostingController.view.backgroundColor = .blue
   hostingController.willMove(toParent: self)
   hostingController.removeFromParentViewController()
   hostingController.dismiss(animated: false)
   for child in hostingController.childViewControllers {child.removeFromParentViewController()}
   for child in hostingController.view.subviews {child.isHidden = true}

Thinking there must be some way to dismiss the UIHostingController (or hiding it) or anyway to get back to UIKit but I haven't had any success.

The strangest part is that if I change the newest ViewController on the Storyboard from .fullScreen to .automatic then I can swipe down to move back from SwiftUI to UIKit. This isn't the desired way to navigate as a button tap to move has been requested, but I haven't been able to replicated this functionality through code at all, I've tried reviewing rewind segues, but then I started to think that the swipe down to go back to the previous view is something else, but there should be a way to call it via code right?


问:
How do I correct a mistaken commit in master I did?
I made the following mistake and would like to correct it.

I have a git repo that is cloned of a remote repo.
In it there is the master branch.
I wanted to correct a bug there so I did mistakenly

```<code>git checkout -m BugCorrection
</code>```

I didn't realize I had misspelled it! so after that I did

```<code>git add main.py
git commit -m "corrected bug"
</code>```

Then I realized I had commited into the main branch!!

So now I have a main branch that is one commit ahead of the origin/main

After that I did

```<code>git checkout -b BugCorrection
git push origin BugCorrection
</code>```

to push my changes
but how do I restore main to be the same as origin/main??

Body:
I made the following mistake and would like to correct it.

I have a git repo that is cloned of a remote repo.
In it there is the master branch.
I wanted to correct a bug there so I did mistakenly

git checkout -m BugCorrection

I didn't realize I had misspelled it! so after that I did

git add main.py
git commit -m "corrected bug"

Then I realized I had commited into the main branch!!

So now I have a main branch that is one commit ahead of the origin/main

After that I did

git checkout -b BugCorrection
git push origin BugCorrection

to push my changes
but how do I restore main to be the same as origin/main??


问:
Why the output video file in my script javascript is null
I am trying to understand why in the following javascript program the output video file is null, indeed the gold of the download the video file contains no data, here is the program in question:

```<code>let videoStream;
navigator.mediaDevices.getUserMedia({ video: true }).then(function (stream) {
  videoStream = stream;
  const mediaRecorder = new MediaRecorder(videoStream, { mimeType: "video/webm" });

  let recordedBlobs = [];

  mediaRecorder.ondataavailable = function (event) {
    if (event.data && event.data.size > 0) {
      recordedBlobs.push(event.data);
    }
  };

  mediaRecorder.start();
  setTimeout(() => {
    mediaRecorder.stop();

    // Créez un fichier blob à partir des données enregistrées
    const blob = new Blob(recordedBlobs, { type: "video/webm" });

    // Créez un lien vers le fichier blob
    const url = URL.createObjectURL(blob);

    // Créez une balise "a" avec un lien vers le fichier blob et un attribut "download"
    const link = document.createElement("a");
    link.href = url;
    link.download = "mon-fichier.webm";

    // Ajoutez la balise "a" au document
    document.body.appendChild(link);

    // Cliquez sur le lien pour déclencher le téléchargement
    link.click();

    // Supprimez le lien du document une fois le téléchargement terminé
    link.parentNode.removeChild(link);
  }, 15000);
});

</code>```

I tried to extend the time of the video and transform the script with on and off buttons but it still didn't work

Body:
I am trying to understand why in the following javascript program the output video file is null, indeed the gold of the download the video file contains no data, here is the program in question:

let videoStream;
navigator.mediaDevices.getUserMedia({ video: true }).then(function (stream) {
  videoStream = stream;
  const mediaRecorder = new MediaRecorder(videoStream, { mimeType: "video/webm" });

  let recordedBlobs = [];

  mediaRecorder.ondataavailable = function (event) {
    if (event.data && event.data.size > 0) {
      recordedBlobs.push(event.data);
    }
  };

  mediaRecorder.start();
  setTimeout(() => {
    mediaRecorder.stop();

    // Créez un fichier blob à partir des données enregistrées
    const blob = new Blob(recordedBlobs, { type: "video/webm" });

    // Créez un lien vers le fichier blob
    const url = URL.createObjectURL(blob);

    // Créez une balise "a" avec un lien vers le fichier blob et un attribut "download"
    const link = document.createElement("a");
    link.href = url;
    link.download = "mon-fichier.webm";

    // Ajoutez la balise "a" au document
    document.body.appendChild(link);

    // Cliquez sur le lien pour déclencher le téléchargement
    link.click();

    // Supprimez le lien du document une fois le téléchargement terminé
    link.parentNode.removeChild(link);
  }, 15000);
});

I tried to extend the time of the video and transform the script with on and off buttons but it still didn't work


问:
Can UIViewController prevent to change rotated UI when change orientation?
FirstViewController (Portrait only) push LandscapeViewController (Landscape only)
So I use UIDevice 'orientation'
How to lock orientation of one view controller to portrait mode only in Swift

But this method is also rotate FirstViewController
Can I keep FirstViewController in portrait?

FirstViewController set
shouldAutorotate false, supportedInterfaceOrientations only portrait
not worked.

FirstViewController

```<code>override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    return .portrait
}

override var shouldAutorotate: Bool {
   return false
}
</code>```

LandscapeViewController

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    AppUtility.lockOrientation(.landscape, andRotateTo: .landscapeLeft)
}

override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    return .landscape
}

override var shouldAutorotate: Bool {
   return true
}
</code>```

Body:
FirstViewController (Portrait only) push LandscapeViewController (Landscape only)
So I use UIDevice 'orientation'
How to lock orientation of one view controller to portrait mode only in Swift

But this method is also rotate FirstViewController
Can I keep FirstViewController in portrait?

FirstViewController set
shouldAutorotate false, supportedInterfaceOrientations only portrait
not worked.

FirstViewController

override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    return .portrait
}

override var shouldAutorotate: Bool {
   return false
}

LandscapeViewController

override func viewDidLoad() {
    super.viewDidLoad()
    AppUtility.lockOrientation(.landscape, andRotateTo: .landscapeLeft)
}

override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    return .landscape
}

override var shouldAutorotate: Bool {
   return true
}


问:
How to properly handle control records in Aurora-DMS-Kinesis-Redshift pipeline?
I am really stuck here and spend the last 2 days researching this topic. I have the following data sync pipeline with the full-load-and-cdc migration type configured:

```<code>[Aurora MySQL RDS]->[DMS]->[Kinesis Streams]->[Kinesis Firehose]->S3 (intermediate)->[Redshift]
</code>```

When I start DMS migration task, besides JSON data files for the source table, the pipeline also delivers JSON control records to the intermediate S3 bucket, even the JSON for creating awsdms_apply_exceptions control table. Redshift then, in turn, tries to load these JSON files from S3 and fails with this error:

```<code>Error 1213: "Missing data for not-null field"
</code>```

This happens, I believe, because Redshift tries to parse JSON with control records as source table data records. My questions are:

Is it correct that the JSON for control tables (and other tables DDL) is delivered by Firehose to the intermediate S3 bucket? When I had [Aurora MySQL RDS]->[DMS]->[Firehose] pipeline before, I didn't see any DDL delivered to S3 - only data CSV files.

If #1 is not correct, how can I ensure that only the source table data files (which Redshift can successfully load) are pushed to the intermediate S3 bucket?

And if JSON with DDL is not going through a Kinesis Stream, how would DMS communicate it to Redshift when a new column is added, for example?

I appreciate any input as I completely ran out of any ideas at this point. Thank you very much.

Here is an example of control records I get in S3 delivered by Firehose which make Redshift error out with 1213 above:

```<code>{
    "metadata": {
        "timestamp":    "2023-01-09T18:59:13.214656Z",
        "record-type":  "control",
        "operation":    "create-table",
        "partition-key-type":   "task-id",
        "schema-name":  "public",
        "table-name":   "awsdms_apply_exceptions"
    }
}{
    "metadata": {
        "timestamp":    "2023-01-09T18:59:13.872312Z",
        "record-type":  "control",
        "operation":    "create-table",
        "partition-key-type":   "task-id",
        "schema-name":  "epulse",
        "table-name":   "add_voter_preference_options"
    }
}
</code>```

Body:
I am really stuck here and spend the last 2 days researching this topic. I have the following data sync pipeline with the full-load-and-cdc migration type configured:

[Aurora MySQL RDS]->[DMS]->[Kinesis Streams]->[Kinesis Firehose]->S3 (intermediate)->[Redshift]

When I start DMS migration task, besides JSON data files for the source table, the pipeline also delivers JSON control records to the intermediate S3 bucket, even the JSON for creating awsdms_apply_exceptions control table. Redshift then, in turn, tries to load these JSON files from S3 and fails with this error:

Error 1213: "Missing data for not-null field"

This happens, I believe, because Redshift tries to parse JSON with control records as source table data records. My questions are:

Is it correct that the JSON for control tables (and other tables DDL) is delivered by Firehose to the intermediate S3 bucket? When I had [Aurora MySQL RDS]->[DMS]->[Firehose] pipeline before, I didn't see any DDL delivered to S3 - only data CSV files.

If #1 is not correct, how can I ensure that only the source table data files (which Redshift can successfully load) are pushed to the intermediate S3 bucket?

And if JSON with DDL is not going through a Kinesis Stream, how would DMS communicate it to Redshift when a new column is added, for example?

I appreciate any input as I completely ran out of any ideas at this point. Thank you very much.

Here is an example of control records I get in S3 delivered by Firehose which make Redshift error out with 1213 above:

{
    "metadata": {
        "timestamp":    "2023-01-09T18:59:13.214656Z",
        "record-type":  "control",
        "operation":    "create-table",
        "partition-key-type":   "task-id",
        "schema-name":  "public",
        "table-name":   "awsdms_apply_exceptions"
    }
}{
    "metadata": {
        "timestamp":    "2023-01-09T18:59:13.872312Z",
        "record-type":  "control",
        "operation":    "create-table",
        "partition-key-type":   "task-id",
        "schema-name":  "epulse",
        "table-name":   "add_voter_preference_options"
    }
}


问:
how to add logo brand img to my application navbar in Angular as a frontend and .NET API as a backend
how to add image as logo brand, I'm using cloudinary to store users data,
but how to establish the basis to add the logo image to .NET API and cloudinary ,
what's are the steps to do it??

Thank


问:
Python scraping json data based on the response tab
I am scraping about tab in youtube to be able gather description of channels and store the data in my csv, it works but only if I setup manually in the code the actual number of tabs the channel about has.

It means some channels have 5 some 6 or 7 depends if they have also short videos if they have playlist etc...

My working code:

```<code>stats = json_data["contents"]["twoColumnBrowseResultsRenderer"]["tabs"][5]["tabRenderer"]["content"]["sectionListRenderer"]["contents"][0]["itemSectionRenderer"]["contents"][0]["channelAboutFullMetadataRenderer"]
</code>```

So basically I tried to do IF if json_data['status_code'] == 0: then post the code with 5 tabs but I dont know what to do next how to check if there is 5 or more TABS.

Body:
I am scraping about tab in youtube to be able gather description of channels and store the data in my csv, it works but only if I setup manually in the code the actual number of tabs the channel about has.

It means some channels have 5 some 6 or 7 depends if they have also short videos if they have playlist etc...

My working code:

stats = json_data["contents"]["twoColumnBrowseResultsRenderer"]["tabs"][5]["tabRenderer"]["content"]["sectionListRenderer"]["contents"][0]["itemSectionRenderer"]["contents"][0]["channelAboutFullMetadataRenderer"]

So basically I tried to do IF if json_data['status_code'] == 0: then post the code with 5 tabs but I dont know what to do next how to check if there is 5 or more TABS.


问:
Sending Emails with a Gmail signature using SMTP Lib in Python
The program works great but when the emails are sent they do not contain my Gmail signature. Is there anyway to do this using SMTP Lib. Here is my code

```<code># Imports
import pandas as pd
import smtplib
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import sys
import os
import time
from rich.progress import track
import keyboard
import tkinter as tk
from tkinter import filedialog
from os import system
from colored import fg, attr

# User Input Process
sender_address = str(input("Please enter your email address!: "))
automail_art()
sender_pass = str(input(
    "Please enter your Google App Email password (No data is stored anywhere!): "))
automail_art()
user_sub = input("What would you like the subject line to say?: ")
automail_art()
user_greeting = input(
    "What would you like the greeting to be? (Hello, Greetings, etc.) [No symbols or names! JUST ONE WORD!]: ")
automail_art()
root = tk.Tk()
root.withdraw()
input(f"{fg('green_4')}Please choose the Excel File you would like to use for name and email address data. \nAfter selecting file click back into the terminal window. Press ENTER to continue\n\n")
# This prompts user to input the file path of their CSV file.
file_path = filedialog.askopenfilename()
automail_art()
input(f"{fg('yellow')}Please choose the Text File you would like to use for the body of your email. \nAfter selecting file click back into the terminal window. Press ENTER to continue\n\n")
# This prompts user to input the file path of their Text file.
txt_doc_path = filedialog.askopenfilename()
automail_art()
# PDF Process
input("Please choose the PDF File you would like to attach to your email. \nAfter selecting file click back into the terminal window. Press ENTER to continue\n\n")
pdf_path = filedialog.askopenfilename()
automail_art()
pdf_name = input(
    "What would you like to name the PDF file? (Do not inclue .pdf): ")
automail_art()
# Amount of emails the user wishes to send
amount = int(input("How many emails would you like to send? "))
automail_art()
txt_doc = open(txt_doc_path, "r")
txt_doc_contents = txt_doc.read()
# DataFrame Variable
# Variable made for DataFrame to save time and make it more simple
df = pd.read_excel(file_path, usecols=['First', 'MainEmail'])
# Email sending process
print("\n")
# Amount is how many emails the user wants to send out. "cell_value" is which cell from the spreadsheet it is pulling data from.
for cell_value in track(range(amount), description=f"{fg('green_1')}Sending Emails :) "):
    # "name_cell" is the cell that contains the first name of the recipient
    name_cell = df["First"].values[cell_value]
    # "email_cell" is the cell that contains the email address of the recipient
    email_cell = df["MainEmail"].values[cell_value]
    receiver_address = email_cell
    email_subj = user_sub  # This variable contains the subject line
    # This is the intro sentence of the email being sent
    email_intro = user_greeting + " " + name_cell + ","
    message = MIMEMultipart()  # Variable made to save time and make it more simple

    # Variable made to save time and make it more simple
    session = smtplib.SMTP('smtp.gmail.com', 587)
    session.starttls()  # enable security
    # Login with email and password (The User's)
    session.login(sender_address, sender_pass)

    message['From'] = sender_address  # From user's email address
    message['To'] = receiver_address  # To recipient email address
    # The variable that contains the desired subject line
    message['Subject'] = email_subj
    message.attach(MIMEText(email_intro + txt_doc_contents, 'plain'))
    with open(pdf_path, "rb") as f:
        attach = MIMEApplication(f.read(), _subtype="pdf")
    attach.add_header('Content-Disposition', 'attachment',
                      filename=str(pdf_name))
    message.attach(attach)
    text = message.as_string()

    session.sendmail(sender_address, receiver_address,
                     text)  # This sends the email
input("Emails have been sent successfully! Press any key to close the program!")
# The End :)

</code>```

I'm not sure how to try to fix this considering the program needs to be flexible for different gmail accounts so I can't specifically add my signature to the code if that makes any sense. This is a program I use for work and I would like for other people to be able to use it as well but as of now without the signature it's not ready to be used by others.

Body:
The program works great but when the emails are sent they do not contain my Gmail signature. Is there anyway to do this using SMTP Lib. Here is my code

# Imports
import pandas as pd
import smtplib
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import sys
import os
import time
from rich.progress import track
import keyboard
import tkinter as tk
from tkinter import filedialog
from os import system
from colored import fg, attr

# User Input Process
sender_address = str(input("Please enter your email address!: "))
automail_art()
sender_pass = str(input(
    "Please enter your Google App Email password (No data is stored anywhere!): "))
automail_art()
user_sub = input("What would you like the subject line to say?: ")
automail_art()
user_greeting = input(
    "What would you like the greeting to be? (Hello, Greetings, etc.) [No symbols or names! JUST ONE WORD!]: ")
automail_art()
root = tk.Tk()
root.withdraw()
input(f"{fg('green_4')}Please choose the Excel File you would like to use for name and email address data. \nAfter selecting file click back into the terminal window. Press ENTER to continue\n\n")
# This prompts user to input the file path of their CSV file.
file_path = filedialog.askopenfilename()
automail_art()
input(f"{fg('yellow')}Please choose the Text File you would like to use for the body of your email. \nAfter selecting file click back into the terminal window. Press ENTER to continue\n\n")
# This prompts user to input the file path of their Text file.
txt_doc_path = filedialog.askopenfilename()
automail_art()
# PDF Process
input("Please choose the PDF File you would like to attach to your email. \nAfter selecting file click back into the terminal window. Press ENTER to continue\n\n")
pdf_path = filedialog.askopenfilename()
automail_art()
pdf_name = input(
    "What would you like to name the PDF file? (Do not inclue .pdf): ")
automail_art()
# Amount of emails the user wishes to send
amount = int(input("How many emails would you like to send? "))
automail_art()
txt_doc = open(txt_doc_path, "r")
txt_doc_contents = txt_doc.read()
# DataFrame Variable
# Variable made for DataFrame to save time and make it more simple
df = pd.read_excel(file_path, usecols=['First', 'MainEmail'])
# Email sending process
print("\n")
# Amount is how many emails the user wants to send out. "cell_value" is which cell from the spreadsheet it is pulling data from.
for cell_value in track(range(amount), description=f"{fg('green_1')}Sending Emails :) "):
    # "name_cell" is the cell that contains the first name of the recipient
    name_cell = df["First"].values[cell_value]
    # "email_cell" is the cell that contains the email address of the recipient
    email_cell = df["MainEmail"].values[cell_value]
    receiver_address = email_cell
    email_subj = user_sub  # This variable contains the subject line
    # This is the intro sentence of the email being sent
    email_intro = user_greeting + " " + name_cell + ","
    message = MIMEMultipart()  # Variable made to save time and make it more simple

    # Variable made to save time and make it more simple
    session = smtplib.SMTP('smtp.gmail.com', 587)
    session.starttls()  # enable security
    # Login with email and password (The User's)
    session.login(sender_address, sender_pass)

    message['From'] = sender_address  # From user's email address
    message['To'] = receiver_address  # To recipient email address
    # The variable that contains the desired subject line
    message['Subject'] = email_subj
    message.attach(MIMEText(email_intro + txt_doc_contents, 'plain'))
    with open(pdf_path, "rb") as f:
        attach = MIMEApplication(f.read(), _subtype="pdf")
    attach.add_header('Content-Disposition', 'attachment',
                      filename=str(pdf_name))
    message.attach(attach)
    text = message.as_string()

    session.sendmail(sender_address, receiver_address,
                     text)  # This sends the email
input("Emails have been sent successfully! Press any key to close the program!")
# The End :)

I'm not sure how to try to fix this considering the program needs to be flexible for different gmail accounts so I can't specifically add my signature to the code if that makes any sense. This is a program I use for work and I would like for other people to be able to use it as well but as of now without the signature it's not ready to be used by others.


问:
Sub Tabs in dropdown menu using flexDashboard
I am trying to add a tabbed pillset within  a Tab of a dropdwon menu in rmarkdown and flexdashboard.  In the code below  I would like  two tabs  one for the cars plot  and one for the iris plot within the dropdown for A and Sub-Tab 1. My attempt below is stacking the plots instead of creating tabs. TIA

```<code>---
title: "Flex Template"
output:
  flexdashboard::flex_dashboard:
    orientation: columns
    vertical_layout: fill
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(include = TRUE)
library(flexdashboard)
library(knitr)
library(tidyverse)
library(kableExtra)

```

# Tab1

Random Text

# Tab2

Random Text

# Tab3

```{r}
head(iris)  %>%  kable()
```

# A {data-navmenu="Dropdown"}

## Column {.tabset data-width="650"}

[**A**]{.underline} \

### Sub-Tab 0

```{r}
iris %>%  kable()
```

### Sub-Tab 1 {.tabset .tabset-pills}

#### cars plot

```{r}
plot(mtcars)
```

#### Iris plot

```{r}
plot(iris$Petal.Length, iris$Petal.Width)
```

### Sub-Tab 2

```{r}

```

### Sub Tab 3

```{r}

```

# B {data-navmenu="Dropdown"}

# C {data-navmenu="Dropdown"}
</code>```

Body:
I am trying to add a tabbed pillset within  a Tab of a dropdwon menu in rmarkdown and flexdashboard.  In the code below  I would like  two tabs  one for the cars plot  and one for the iris plot within the dropdown for A and Sub-Tab 1. My attempt below is stacking the plots instead of creating tabs. TIA

---
title: "Flex Template"
output:
  flexdashboard::flex_dashboard:
    orientation: columns
    vertical_layout: fill
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(include = TRUE)
library(flexdashboard)
library(knitr)
library(tidyverse)
library(kableExtra)

```

# Tab1

Random Text

# Tab2

Random Text

# Tab3

```{r}
head(iris)  %>%  kable()
```

# A {data-navmenu="Dropdown"}

## Column {.tabset data-width="650"}

[**A**]{.underline} \

### Sub-Tab 0

```{r}
iris %>%  kable()
```

### Sub-Tab 1 {.tabset .tabset-pills}

#### cars plot

```{r}
plot(mtcars)
```

#### Iris plot

```{r}
plot(iris$Petal.Length, iris$Petal.Width)
```

### Sub-Tab 2

```{r}

```

### Sub Tab 3

```{r}

```

# B {data-navmenu="Dropdown"}

# C {data-navmenu="Dropdown"}


问:
how to merge arrays from 2 different arrays
this is an image from the API that returns the test results before and after each other.

Initially when the user has not entered the test result, the array result = null, After the user enters, the array will have the same result as the image below:

my problem is after user input test, and then we update field result_template can be add or remove subjects so how do i merge subjects if use edit again result_template,
If there are new subjects but no scores are available, the default is set = 0

You can watch the video for better understanding: link

desired result: image

here is my code:

 const { data } = await this.$store.dispatch(
    `${UserGeneral.STORE_ADMIN_USER_KEY}/getDetailSchoolResults`,
     this.$route.params.id
);
const formData = data.data;
      if (formData.result) {
        const listResultTemplate = formData.result.result.map((item) => {
          let data = {
            title: item.title,
            subjects: [],
            files: [],
          };

          item.files.forEach((file) => {
            data.files.push(file);
          });

          item.subjects.forEach((subject) => {
            data.subjects.push({
              name: subject.name,
              scores: {
                total_score: subject.scores.total_score,
                medium_score: subject.scores.medium_score,
                private_score: subject.scores.private_score,
              },
            });
          });
          return data;
        });

        this.result = listResultTemplate;
      } else {
        const listResultTemplate = formData.result_template.result_template.map(
          (item) => {
            let data = {
              title: item.title,
              subjects: [],
              files: [],
            };

            item.subjects.forEach((subject) => {
              data.subjects.push({
                name: subject,
                scores: {
                  total_score: 0,
                  medium_score: 0,
                  private_score: 0,
                },
              });
            });
            return data;
          }
        );

        this.result = listResultTemplate;
      }```

thanks for your help !

Body:
this is an image from the API that returns the test results before and after each other.

Initially when the user has not entered the test result, the array result = null, After the user enters, the array will have the same result as the image below:

my problem is after user input test, and then we update field result_template can be add or remove subjects so how do i merge subjects if use edit again result_template,
If there are new subjects but no scores are available, the default is set = 0

You can watch the video for better understanding: link

desired result: image

here is my code:

 const { data } = await this.$store.dispatch(
    `${UserGeneral.STORE_ADMIN_USER_KEY}/getDetailSchoolResults`,
     this.$route.params.id
);
const formData = data.data;
      if (formData.result) {
        const listResultTemplate = formData.result.result.map((item) => {
          let data = {
            title: item.title,
            subjects: [],
            files: [],
          };

          item.files.forEach((file) => {
            data.files.push(file);
          });

          item.subjects.forEach((subject) => {
            data.subjects.push({
              name: subject.name,
              scores: {
                total_score: subject.scores.total_score,
                medium_score: subject.scores.medium_score,
                private_score: subject.scores.private_score,
              },
            });
          });
          return data;
        });

        this.result = listResultTemplate;
      } else {
        const listResultTemplate = formData.result_template.result_template.map(
          (item) => {
            let data = {
              title: item.title,
              subjects: [],
              files: [],
            };

            item.subjects.forEach((subject) => {
              data.subjects.push({
                name: subject,
                scores: {
                  total_score: 0,
                  medium_score: 0,
                  private_score: 0,
                },
              });
            });
            return data;
          }
        );

        this.result = listResultTemplate;
      }

thanks for your help !


问:
nextui table shrinks when adding onLoadMore

when I add the onLoadMore function to the table it shrinks have no clue how to fix it
using nextui

```<code> <Table
      aria-label="Example table with custom cells"
      css={{
        height: "30vh",
        minWidth: "100%",
      }}

      selectionMode="multiple"
    >
      <Table.Header columns={columns}>
        {(column) => (
          <Table.Column
            key={column.uid}
            hideHeader={column.uid === "actions"}
            align={column.uid === "actions" ? "center" : "start"}
          >
            {column.name}
          </Table.Column>
        )}
      </Table.Header>
      <Table.Body loadingState={"f"}
        onLoadMore={()=>console.log("hhh")} items={users}>
        {(item) => (
          <Table.Row>
            {(columnKey) => (
              <Table.Cell>{renderCell(item, columnKey)}</Table.Cell>
            )}
          </Table.Row>
        )}
      </Table.Body>
    </Table>
  );
</code>```

when I add the onLoadMore function to the table it shrinks have no clue how to fix it
using nextui

when I add the onLoadMore function to the table it shrinks have no clue how to fix it
using nextui

when I add the onLoadMore function to the table it shrinks have no clue how to fix it
using nextui

Body:
when I add the onLoadMore function to the table it shrinks have no clue how to fix it
using nextui

        {(column) => (

            {column.name}

        )}

console.log("hhh")} items={users}>
        {(item) => (

            {(columnKey) => (

{renderCell(item, columnKey)}

            )}

        )}

  );

when I add the onLoadMore function to the table it shrinks have no clue how to fix it
using nextui

when I add the onLoadMore function to the table it shrinks have no clue how to fix it
using nextui

when I add the onLoadMore function to the table it shrinks have no clue how to fix it
using nextui


问:
How do i add items to a column in SQL/jpql
I have a Student model class, and one of the entities is a List of courses offered by the student. when a sudent account is created, it is created with some courses, but this would need to be updated every semester. I want to update that column to add a new course but I don't know how to do that. I tried a SQL update query, but that just changes the values. I'm not very good with SQL and I would like to know if there's any other way to achieve this.Here's my model class.</p>
```<code>@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {

    @Id
    private int studentId;

    @JsonProperty
    private String name;

    @JsonProperty
    private String email;

    @JsonProperty
    private String department;

    @JsonProperty
    private int level;

    @JsonProperty
    private double cgpa;

    @JsonProperty
    @ManyToMany
    private List<Course> coursesOffered;
</code>```

Body:
I have a Student model class, and one of the entities is a List of courses offered by the student. when a sudent account is created, it is created with some courses, but this would need to be updated every semester. I want to update that column to add a new course but I don't know how to do that. I tried a SQL update query, but that just changes the values. I'm not very good with SQL and I would like to know if there's any other way to achieve this.Here's my model class.

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {

    @Id
    private int studentId;

    @JsonProperty
    private String name;

    @JsonProperty
    private String email;

    @JsonProperty
    private String department;

    @JsonProperty
    private int level;

    @JsonProperty
    private double cgpa;

    @JsonProperty
    @ManyToMany
    private List<Course> coursesOffered;


问:
How to add some routes into the current proxy?
I have a problem with adding some new routes to the current proxy which I have on the server .
The current file is located on :

```<code>/etc/nginx/sites-enabled/proxy_nginx
</code>```

with this content :

```<code># proxy cache
proxy_cache_path /tmp/cache keys_zone=cache:10m levels=1:2 inactive=600s max_size=100m;

# redirect all HTTP to HTTPS
server {
    listen 80 default_server;
    return 301 https://$host$request_uri;
}

server {
    return 301 https://$host$request_uri;

    server_name www.api.mysite.org; # managed by Certbot

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/api.mysite.org/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/api.mysite.org/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}
server {
    if ($host = www.api.mysite.org) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    listen 80 ;
    server_name www.api.mysite.org;
    return 404; # managed by Certbot

}
</code>```

Now I need to add these lines into it but I'm confused where to put them :

```<code>server {
    listen 80 default backlog=16384;
    listen [::]:80 default backlog=16384;

    location /route1{
        proxy_set_header Host decide.externalURL.com;
        proxy_set_header X-Real-IP $http_x_forwarded_for;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Host $server_name;
        proxy_pass https://z.externalURL.com/route1;
    }

    location /route2 {
        proxy_set_header Host api.externalURL.com;
        proxy_set_header X-Real-IP $http_x_forwarded_for;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Host $server_name;
        proxy_pass https://api.externalURL.com/route2;
    }
</code>```

I know that I shouldn't have a duplicate default-server because I wasn't able to add the above lines into my default nginx.conf file.
So the question is how to mix these lines into the /etc/nginx/sites-enabled/proxy_nginx file.

Body:
I have a problem with adding some new routes to the current proxy which I have on the server .
The current file is located on :

/etc/nginx/sites-enabled/proxy_nginx

with this content :

# proxy cache
proxy_cache_path /tmp/cache keys_zone=cache:10m levels=1:2 inactive=600s max_size=100m;

# redirect all HTTP to HTTPS
server {
    listen 80 default_server;
    return 301 https://$host$request_uri;
}

server {
    return 301 https://$host$request_uri;

    server_name www.api.mysite.org; # managed by Certbot

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/api.mysite.org/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/api.mysite.org/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}
server {
    if ($host = www.api.mysite.org) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    listen 80 ;
    server_name www.api.mysite.org;
    return 404; # managed by Certbot

}

Now I need to add these lines into it but I'm confused where to put them :

server {
    listen 80 default backlog=16384;
    listen [::]:80 default backlog=16384;

    location /route1{
        proxy_set_header Host decide.externalURL.com;
        proxy_set_header X-Real-IP $http_x_forwarded_for;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Host $server_name;
        proxy_pass https://z.externalURL.com/route1;
    }

    location /route2 {
        proxy_set_header Host api.externalURL.com;
        proxy_set_header X-Real-IP $http_x_forwarded_for;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Host $server_name;
        proxy_pass https://api.externalURL.com/route2;
    }

I know that I shouldn't have a duplicate default-server because I wasn't able to add the above lines into my default nginx.conf file.
So the question is how to mix these lines into the /etc/nginx/sites-enabled/proxy_nginx file.


问:
Unable to deliver variable value to function inside class pycord
I'm having a problem with delivering a variable value to a function inside a class.

The specific issue occurs in the following code:

```<code>@discord.ui.select(
    row = 0,
    options = self.r
)
</code>```

Here is the relevant code for the class:

```<code>class MyView(discord.ui.View):
    def __init__(self, no):
        super().__init__()
        self.no = no
        self.manga = None
        self.chapters = None
        self.startnum = -25
        self.endnum = 0 # add 25
        self.twentyfives = 0
        self.r = []
        r = []
        for i in data:
            if  str(i["MangaName"]).lower() == no:
                self.manga =i
                break
        if self.manga != None:
            self.chapters = int(self.manga["ChaptersNumber"])
            self.twentyfives = (self.chapters // 25)+1
        self.startnum += 25

        if self.endnum + 25 > self.chapters:
            self.endnum = self.chapters
        else:
            self.endnum +=25
            self.startnum +=25
        for title in range(self.startnum,self.endnum):
            self.r.append(discord.SelectOption(
            label=self.manga["Chaptersinfo"][title]))
        r = self.r
    @discord.ui.select(
        row = 0,
        options = self.r
    )
    async def select_callback(self, select, interaction): # the function called when the user is done selecting options
            manga_selected = select.values[0]
            await interaction.response.send_message(f"Awesome! I like {select.values[0]} too!")
</code>```

i tried using different function to store the data then receive it again but it didn't work
and i tried to let

```<code>async def select_callback
</code>```

and

```<code> @discord.ui.select
</code>```

inside the class but the async def select_callback didn't work and the options didn't show

Body:
I'm having a problem with delivering a variable value to a function inside a class.

The specific issue occurs in the following code:

@discord.ui.select(
    row = 0,
    options = self.r
)

Here is the relevant code for the class:

class MyView(discord.ui.View):
    def __init__(self, no):
        super().__init__()
        self.no = no
        self.manga = None
        self.chapters = None
        self.startnum = -25
        self.endnum = 0 # add 25
        self.twentyfives = 0
        self.r = []
        r = []
        for i in data:
            if  str(i["MangaName"]).lower() == no:
                self.manga =i
                break
        if self.manga != None:
            self.chapters = int(self.manga["ChaptersNumber"])
            self.twentyfives = (self.chapters // 25)+1
        self.startnum += 25

        if self.endnum + 25 > self.chapters:
            self.endnum = self.chapters
        else:
            self.endnum +=25
            self.startnum +=25
        for title in range(self.startnum,self.endnum):
            self.r.append(discord.SelectOption(
            label=self.manga["Chaptersinfo"][title]))
        r = self.r
    @discord.ui.select(
        row = 0,
        options = self.r
    )
    async def select_callback(self, select, interaction): # the function called when the user is done selecting options
            manga_selected = select.values[0]
            await interaction.response.send_message(f"Awesome! I like {select.values[0]} too!")

i tried using different function to store the data then receive it again but it didn't work
and i tried to let

async def select_callback

and

 @discord.ui.select

inside the class but the async def select_callback didn't work and the options didn't show


问:
Unclear Correspondence Between C and Assembly
I am reading about x64 Assembly through this online textbook. It takes the following C function:

```<code>int adder2(int a) {
    return a + 2;
}
</code>```

And shows how it is compiled into x64 Assembly:

```<code>push %rbp
mov %rsp,%rbp
mov %edi,-0x4(%rbp)
mov -0x4(%rbp),%eax
add $0x2,%eax
pop %rbp
retq
</code>```

I understand that push %rbp pushes the adder2 function onto the call stack, pop %rbp pops it from the call stack, and retq returns control to the function that had called adder2. I also get that add $0x2, %eax adds 2 to a, and the result is what will be returned.

However, why are there three lines that call the mov command? There is only one variable (a), so why are there so many registers? There is no clear line-by-line connection between the C and Assembly code.

Body:
I am reading about x64 Assembly through this online textbook. It takes the following C function:

int adder2(int a) {
    return a + 2;
}

And shows how it is compiled into x64 Assembly:

push %rbp
mov %rsp,%rbp
mov %edi,-0x4(%rbp)
mov -0x4(%rbp),%eax
add $0x2,%eax
pop %rbp
retq

I understand that push %rbp pushes the adder2 function onto the call stack, pop %rbp pops it from the call stack, and retq returns control to the function that had called adder2. I also get that add $0x2, %eax adds 2 to a, and the result is what will be returned.

However, why are there three lines that call the mov command? There is only one variable (a), so why are there so many registers? There is no clear line-by-line connection between the C and Assembly code.


问:
Modeling asynchronous "read-message-then-dispatch" loop in `java.nio.channels.AsynchronousSocketChannel`, is `CompleteableFuture<>` the proper tool?
I'm writing a Postgres wire-protocol server on the JVM, and the core loop of the server is to receive a command over a socket from a PSQL client, handle it, and then read/wait for another command over the wire.

I've made a method, read(), which is the entrypoint for reading from the socket. Some decoding and business logic happens, and then it dispatches to handleClientMessage(), which I made return a CompleteableFuture<> so that when it finishes, I can then call .thenRun(() -> read()) to have it loop back 'round again to read().

The alternative I had before to was remember to call read() at the end of every method.

My hesitation with using CompleteableFuture<> is that I believe it queues tasks to be run in a pool, which sounds like it has a lot of overhead potentially? Is this a poor practice just so that I can call .thenRun(() -> {}) on the result?

Code is below, with most of the non-relevant bits removed:

// A single client connection to the Postgres wire-protocol server
class PostgresServerClientConnection {
    private AsynchronousSocketChannel client;
    private MemorySegment buffer;

    public PostgresServerClientConnection(AsynchronousSocketChannel client) {
        this.client = client;
        this.buffer = MemorySegment.allocateNative(1024, SegmentScope.global());
    }

    public void read() {
        ByteBuffer byteBuffer = buffer.asByteBuffer();
        client.read(byteBuffer, null, new CompletionHandler<>() {
            @Override
            public void completed(Integer result, Object attachment) {
                // Create an infinite loop of reading and handling messages
                handleClientMessage(msg).thenRun(() -> read());
            }

            @Override
            public void failed(Throwable exc, Object attachment) {
                System.err.println("[SERVER] Failed to read from client: " + exc);
            }
        });
    }

    CompletableFuture<Void> handleClientMessage(ClientMessage msg) {
        if (msg.isSSLRequest()) {
            return handleSSLRequest(msg);
        } else if (msg.isStartupMessage()) {
            return handleStartupMessage(msg);
        } else {
            return handleRegularMessage(msg);
        }
    }

    CompletableFuture<Void> handleSSLRequest(ClientMessage msg) {
        return CompletableFuture.runAsync(() -> {
            try {
                client.write(byteBuffer).get();
            } catch (InterruptedException | ExecutionException e) {
            }
        });
    }

    CompletableFuture<Void> handleStartupMessage(ClientMessage msg) {
        return CompletableFuture.runAsync(() -> {
            try {
                client.write(byteBuffer).get();
            } catch (InterruptedException | ExecutionException e) {
            }
        });
    }
}
```


问:
Integrate postit-js with bpmn modeler?
I have been looking on how to add Postit-js functions on my currently existing bpmn, as I googled, I’ve got into " Custom Elements in bpmn-js" but I am not sure if that’s how I’d do it since postit-js already exists… the goal would be to add Post-it functions on my BPMN “tool bar”/properties panel… is it possible? Are there any directions I could follow to make it happen?

And should that be way too complicated - is it possible to have both post-it properties panel AND bpmn panel coexisting?

Add this  "toolbars" functionalities into BPMN-js 'toolbar'

Title: Integrate postit-js with bpmn modeler?


问:
How to use a value for psql copy command parameter?
Using python and psql.

```<code>sql = '''
      SELECT * FROM test
      '''.format(self.schema)

self.cur.execute(sql)

return self.cur.fetchall()

-----------------------------
export_data = self.get_data() // the return of fetchall

if export_data:
cmd = [
'psql',
"\COPY {0} to 'test/test_dump.csv' DELIMITER ',' NULL ''"
.format(export_data)
]
</code>```

For example, after get a query result and fetchall it at a value.

How to I copy or export it as file with psql command?

```<code>
COPY (SELECT * FROM my_table) TO :path CSV DELIMITER ',' HEADER;
</code>```

I know how to get a data from copy parameter directly.
But I want to use the fetched value as parameter.

```<code>cmd = [
'psql',
"\COPY {0} to 'test/test_dump.csv' DELIMITER ',' NULL ''"
.format(export_data)
]
</code>```

Above setting seems weird... how to I do it?

Body:
Using python and psql.

sql = '''
      SELECT * FROM test
      '''.format(self.schema)

self.cur.execute(sql)

return self.cur.fetchall()

-----------------------------
export_data = self.get_data() // the return of fetchall

if export_data:
cmd = [
'psql',
"\COPY {0} to 'test/test_dump.csv' DELIMITER ',' NULL ''"
.format(export_data)
]

For example, after get a query result and fetchall it at a value.

How to I copy or export it as file with psql command?

COPY (SELECT * FROM my_table) TO :path CSV DELIMITER ',' HEADER;

I know how to get a data from copy parameter directly.
But I want to use the fetched value as parameter.

cmd = [
'psql',
"\COPY {0} to 'test/test_dump.csv' DELIMITER ',' NULL ''"
.format(export_data)
]

Above setting seems weird... how to I do it?


问:
nginx/flask/gunicorn/supervisor on linode: connect() failed (111: Unknown error), site hangs on https
I am trying to run the simplest possible Flask app on a Linode. I have my Linode set up to serve a domain I bought on namecheap. This app was up and running no problem with Flask, gunicorn, nginx and supervisor as the stack. Out of the blue any https requests started totally hanging. All of the logs look fine except nginx. Going through the stack:

The supervisor logs are fine:

```<code>[2023-01-10 01:08:52 +0000] [1315] [INFO] Starting gunicorn 20.1.0
[2023-01-10 01:08:52 +0000] [1315] [INFO] Listening at: https://0.0.0.0:8000 (1315)
[2023-01-10 01:08:52 +0000] [1315] [INFO] Using worker: sync
[2023-01-10 01:08:52 +0000] [1316] [INFO] Booting worker with pid: 1316
[2023-01-10 01:08:52 +0000] [1317] [INFO] Booting worker with pid: 1317
[2023-01-10 01:08:52 +0000] [1318] [INFO] Booting worker with pid: 1318
</code>```

The nginx logs show connect() failed (111: Unknown error):

```<code>➜  ~ sudo cat /var/log/nginx/error.log
2023/01/10 00:17:43 [error] 752#752: *133 connect() failed (111: Unknown error) while connecting to upstream, client: 205.210.31.6, server: cambins.co.uk, request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8000/", host: "45.79.170.153:443"
2023/01/10 00:51:05 [error] 752#752: *170 recv() failed (104: Unknown error) while reading response header from upstream, client: 64.41.200.113, server: cambins.co.uk, request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8000/", host: "cambins.co.uk"
2023/01/10 00:51:23 [crit] 752#752: *237 SSL_do_handshake() failed (SSL: error:0A0C0103:SSL routines::internal error) while SSL handshaking, client: 64.41.200.113, server: 0.0.0.0:443
2023/01/10 01:08:40 [notice] 1295#1295: signal process started
</code>```

And the output of openssl s_client:

```<code>➜  ~ openssl s_client -host cambins.co.uk -port 993
40378FC20B7F0000:error:8000006F:system library:BIO_connect:Connection refused:../crypto/bio/bio_sock2.c:125:calling connect()
40378FC20B7F0000:error:10000067:BIO routines:BIO_connect:connect error:../crypto/bio/bio_sock2.c:127:
connect:errno=111
</code>```

Finally my /etc/nginx/sites-enabled/backend:

```<code>server {
    server_name cambins.co.uk;
    #server_name 45.79.170.153;

    location / {
        #proxy_pass http://127.0.0.1:8000;
        proxy_pass http://0.0.0.0:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/cambins.co.uk/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/cambins.co.uk/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}
server {
    if ($host = cambins.co.uk) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    listen 80;
    server_name cambins.co.uk;
    return 404; # managed by Certbot

}
</code>```

Body:
I am trying to run the simplest possible Flask app on a Linode. I have my Linode set up to serve a domain I bought on namecheap. This app was up and running no problem with Flask, gunicorn, nginx and supervisor as the stack. Out of the blue any https requests started totally hanging. All of the logs look fine except nginx. Going through the stack:

The supervisor logs are fine:

[2023-01-10 01:08:52 +0000] [1315] [INFO] Starting gunicorn 20.1.0
[2023-01-10 01:08:52 +0000] [1315] [INFO] Listening at: https://0.0.0.0:8000 (1315)
[2023-01-10 01:08:52 +0000] [1315] [INFO] Using worker: sync
[2023-01-10 01:08:52 +0000] [1316] [INFO] Booting worker with pid: 1316
[2023-01-10 01:08:52 +0000] [1317] [INFO] Booting worker with pid: 1317
[2023-01-10 01:08:52 +0000] [1318] [INFO] Booting worker with pid: 1318

The nginx logs show connect() failed (111: Unknown error):

➜  ~ sudo cat /var/log/nginx/error.log
2023/01/10 00:17:43 [error] 752#752: *133 connect() failed (111: Unknown error) while connecting to upstream, client: 205.210.31.6, server: cambins.co.uk, request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8000/", host: "45.79.170.153:443"
2023/01/10 00:51:05 [error] 752#752: *170 recv() failed (104: Unknown error) while reading response header from upstream, client: 64.41.200.113, server: cambins.co.uk, request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8000/", host: "cambins.co.uk"
2023/01/10 00:51:23 [crit] 752#752: *237 SSL_do_handshake() failed (SSL: error:0A0C0103:SSL routines::internal error) while SSL handshaking, client: 64.41.200.113, server: 0.0.0.0:443
2023/01/10 01:08:40 [notice] 1295#1295: signal process started

And the output of openssl s_client:

➜  ~ openssl s_client -host cambins.co.uk -port 993
40378FC20B7F0000:error:8000006F:system library:BIO_connect:Connection refused:../crypto/bio/bio_sock2.c:125:calling connect()
40378FC20B7F0000:error:10000067:BIO routines:BIO_connect:connect error:../crypto/bio/bio_sock2.c:127:
connect:errno=111

Finally my /etc/nginx/sites-enabled/backend:

server {
    server_name cambins.co.uk;
    #server_name 45.79.170.153;

    location / {
        #proxy_pass http://127.0.0.1:8000;
        proxy_pass http://0.0.0.0:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/cambins.co.uk/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/cambins.co.uk/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}
server {
    if ($host = cambins.co.uk) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    listen 80;
    server_name cambins.co.uk;
    return 404; # managed by Certbot

}


问:
R Switch statement combined with more complex interactions such as %in%
Is there any way to use multi-selectivity (e.g. switch statements) with more complex requirements in R?
Specifically, it seems sub-optimal to need to write the following:

```<code>if(is.POSIXct(value)) {
  ...
} else if(is.integer(value)) {
  ...
} else if(is.double(value)) {
  ...
}
</code>```

I mean, switch(typeof(value), ... almost works, except that it doesn't work for classes like dates.
I'm thinking something like %in% would be really handy if it were possible to use in combination with a switch statement.

Body:
Is there any way to use multi-selectivity (e.g. switch statements) with more complex requirements in R?
Specifically, it seems sub-optimal to need to write the following:

if(is.POSIXct(value)) {
  ...
} else if(is.integer(value)) {
  ...
} else if(is.double(value)) {
  ...
}

I mean, switch(typeof(value), ... almost works, except that it doesn't work for classes like dates.
I'm thinking something like %in% would be really handy if it were possible to use in combination with a switch statement.