问:
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for gulpfile.ts
I get the error running yarn run package. Adding NODE_OPTIONS="--loader ts-node/esm" didn't help.

I have seen https://github.com/TypeStrong/ts-node/issues/1062 but I tried different targets and that didn't help.

package.json:

```<code>...
"scripts": {
    "build": "tsc",
    "build:production": "npm run prestart && npm prune --production",
    "watch": "tsc --w",
    "prestart": "npm run build && func extensions install",
    "start:host": "func start",
    "start": "npm-run-all --parallel start:host watch",
    "test": "echo \"No tests yet...\"",
    "package": "gulp build && gulp package"
  },
  "description": "",
  "devDependencies": {
    "@azure/functions": "^1.0.1-beta1",
    "@types/gulp": "^4.0.9",
    "@types/gulp-zip": "^4.0.2",
    "@types/node": "^18.11.13",
    "del": "^7.0.0",
    "gulp-typescript": "^6.0.0-alpha.1",
    "gulp-zip": "^5.1.0",
    "npm-run-all": "^4.1.5",
    "ts-node": "^10.2.1",
    "typescript": "^3.3.3"
  },
  "dependencies": {
    "azure-devops-node-api": "^11.2.0",
    "gulp": "^4.0.2"
  },
  "resolutions": {
    "decode-uri-component": "0.2.2",
    "glob-parent": "6.0.2",
    "qs": "6.10.3",
    "string_decoder": "1.3.0"
  }
</code>```

tsconfig.json:

```<code>{
  "compilerOptions": {
    "module": "commonjs",
    "moduleResolution": "node",
    "target": "es6",
    "outDir": "dist",
    "rootDir": ".",
    "sourceMap": true,
    "noImplicitAny": true,
    "strict": false,
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "lib": [
      "es6"
    ]
  },
  "exclude": [
    "./gulpfile.ts"
  ],
  "ts-node": {
    "esm": true
  }
}
</code>```

node 18.12.1, npm 9.1.3, and yarn 3.3.0.

Body:
I get the error running yarn run package. Adding NODE_OPTIONS="--loader ts-node/esm" didn't help.

I have seen https://github.com/TypeStrong/ts-node/issues/1062 but I tried different targets and that didn't help.

package.json:

...
"scripts": {
    "build": "tsc",
    "build:production": "npm run prestart && npm prune --production",
    "watch": "tsc --w",
    "prestart": "npm run build && func extensions install",
    "start:host": "func start",
    "start": "npm-run-all --parallel start:host watch",
    "test": "echo \"No tests yet...\"",
    "package": "gulp build && gulp package"
  },
  "description": "",
  "devDependencies": {
    "@azure/functions": "^1.0.1-beta1",
    "@types/gulp": "^4.0.9",
    "@types/gulp-zip": "^4.0.2",
    "@types/node": "^18.11.13",
    "del": "^7.0.0",
    "gulp-typescript": "^6.0.0-alpha.1",
    "gulp-zip": "^5.1.0",
    "npm-run-all": "^4.1.5",
    "ts-node": "^10.2.1",
    "typescript": "^3.3.3"
  },
  "dependencies": {
    "azure-devops-node-api": "^11.2.0",
    "gulp": "^4.0.2"
  },
  "resolutions": {
    "decode-uri-component": "0.2.2",
    "glob-parent": "6.0.2",
    "qs": "6.10.3",
    "string_decoder": "1.3.0"
  }

tsconfig.json:

{
  "compilerOptions": {
    "module": "commonjs",
    "moduleResolution": "node",
    "target": "es6",
    "outDir": "dist",
    "rootDir": ".",
    "sourceMap": true,
    "noImplicitAny": true,
    "strict": false,
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "lib": [
      "es6"
    ]
  },
  "exclude": [
    "./gulpfile.ts"
  ],
  "ts-node": {
    "esm": true
  }
}

node 18.12.1, npm 9.1.3, and yarn 3.3.0.


来源: stackexchange

问:
How to use variable from another function (Python and TKinter)
Context: I am working on a program that takes text from the user to process it and prints it out as a PDF.

```<code>def enterData():
    data = la1entry.get()
    textInPre = data
    sumMecha(textInPre)

def textPDF(text):
    a4=210
    chW=2.45
    wTex=a4/chW
    pdf = FPDF(orientation='P', unit='mm', format='A4')
    pdf.set_auto_page_break(True, 10)
    pdf.add_page()
    pdf.set_font(family="Arial", size=15)
    splitted = text.split('.')

    for line in splitted:
        lines = textwrap.wrap(line, wTex)
        if len(lines) == 0:
            pdf.ln()
        for dot in lines:
            pdf.cell(0, 5.5, dot, ln=1)

    pdf.output("Done.pdf")
"""
    directory = filedialog.asksaveasfilename(filetypes=[('PDF File', '*.pdf')],
                                                        defaultextension='.pdf',
                                                        initialdir='C:',
                                                        title='Summary')
"""

def sumMecha(textInPre):
    textInPre = textInPre.replace("[ edit ]", "")
    done = ' '.join(textInPre)
    global done
    #textPDF(done)
    #print(done)
    #return done
</code>```

So, enterData function calls out the sumMecha function to take the text and start processing it and the same works for sumMecha and TextPDF.

```<code>button1 = tkinter.Button(frame, text="Start processing data", command=enterData)
button1.grid(row=3, column=0, sticky="news", padx=20, pady=10)

button2 = tkinter.Button(frame, text="Export PDF", command=textPDF(processed))
button2.grid(row=4, column=0, sticky="news", padx=20, pady=10)

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

The issue lies when i attempt to separate the processing function sumMecha and the text to pdf one textPDF.
Attempting this will fail to execute the program, because i have failed to access the done variable.
I have succeded in doing this by chaining them all into one button,  but working on separating the processing in one button, and the exporting into another button.
I worked with the return function and global function but to no avail.

1- How can i call the done variable to cram it into the textPDF function?
2- Is it possible to cram a save as prompt into the textPDF function?

ContentLicense: CC BY-SA 4.0

Body:
Context: I am working on a program that takes text from the user to process it and prints it out as a PDF.

def enterData():
    data = la1entry.get()
    textInPre = data
    sumMecha(textInPre)

def textPDF(text):
    a4=210
    chW=2.45
    wTex=a4/chW
    pdf = FPDF(orientation='P', unit='mm', format='A4')
    pdf.set_auto_page_break(True, 10)
    pdf.add_page()
    pdf.set_font(family="Arial", size=15)
    splitted = text.split('.')

    for line in splitted:
        lines = textwrap.wrap(line, wTex)
        if len(lines) == 0:
            pdf.ln()
        for dot in lines:
            pdf.cell(0, 5.5, dot, ln=1)

    pdf.output("Done.pdf")
"""
    directory = filedialog.asksaveasfilename(filetypes=[('PDF File', '*.pdf')],
                                                        defaultextension='.pdf',
                                                        initialdir='C:',
                                                        title='Summary')
"""

def sumMecha(textInPre):
    textInPre = textInPre.replace("[ edit ]", "")
    done = ' '.join(textInPre)
    global done
    #textPDF(done)
    #print(done)
    #return done

So, enterData function calls out the sumMecha function to take the text and start processing it and the same works for sumMecha and TextPDF.

button1 = tkinter.Button(frame, text="Start processing data", command=enterData)
button1.grid(row=3, column=0, sticky="news", padx=20, pady=10)

button2 = tkinter.Button(frame, text="Export PDF", command=textPDF(processed))
button2.grid(row=4, column=0, sticky="news", padx=20, pady=10)

window.mainloop()

The issue lies when i attempt to separate the processing function sumMecha and the text to pdf one textPDF.
Attempting this will fail to execute the program, because i have failed to access the done variable.
I have succeded in doing this by chaining them all into one button,  but working on separating the processing in one button, and the exporting into another button.
I worked with the return function and global function but to no avail.

1- How can i call the done variable to cram it into the textPDF function?
2- Is it possible to cram a save as prompt into the textPDF function?


问:
Rails 7 create camelcase output for dry::struct object
I've to build a massive JSON file based on few different API calls. I want to use Dry::Struct To easily manipulate data like:

```<code>obj = Test::DataStruct.new
obj.send_envelope_description = 1
</code>```

but expected output should be camelcase:

#<Test::DataStruct SendEnvelopeDescription=1>

Additionally, passed data into Test::DataStruct obj should accept camelcase keys like:

```<code>data = { SendEnvelopeDescription: 1 }
test = TestDataStruct.new(data)
 => #<Test::DataStruct SendEnvelopeDescription=1>
</code>```

I tried to use transform_keys { |key| key.to_s.camelize } but I'm getting an error:

```<code>3.1.2 :045 > obj = Test::DataStruct.new(send_envelope_description: 1)

`block in resolve_missing_keys': [Test::DataStruct.new] :send_envelope_description is missing in Hash input (Dry::Struct::Error)

`block in resolve_missing_keys': :send_envelope_description is missing in Hash input (Dry::Types::MissingKeyError)
</code>```

Is it possible to do so?

Body:
I've to build a massive JSON file based on few different API calls. I want to use Dry::Struct To easily manipulate data like:

obj = Test::DataStruct.new
obj.send_envelope_description = 1

but expected output should be camelcase:

#<Test::DataStruct SendEnvelopeDescription=1>

Additionally, passed data into Test::DataStruct obj should accept camelcase keys like:

data = { SendEnvelopeDescription: 1 }
test = TestDataStruct.new(data)
 => #<Test::DataStruct SendEnvelopeDescription=1>

I tried to use transform_keys { |key| key.to_s.camelize } but I'm getting an error:

3.1.2 :045 > obj = Test::DataStruct.new(send_envelope_description: 1)

`block in resolve_missing_keys': [Test::DataStruct.new] :send_envelope_description is missing in Hash input (Dry::Struct::Error)

`block in resolve_missing_keys': :send_envelope_description is missing in Hash input (Dry::Types::MissingKeyError)

Is it possible to do so?


问:
how to specify the exact words, like Legend and not derivates like Legendary?
```<code>import requests
import re

# Replace with the path to the text file

file_path = r'C:\'

# Replace with your webhook URL
webhook_url = 'https://discord.com'

# Create a set to store seen messages
seen_messages = set()

# Keep reading and sending the last line of the file
while True:
    try:
        # Read the last line of the file
        with open(file_path, 'rb') as f:
            f.seek(-2, 2)
            while f.read(1) != b'\n':
                f.seek(-2, 1)
            last_line = f.readline().decode()

        # Check if the last line contains [CLAN] and deposited, and doesn't contain vehiculul
        if 'Newbie' in last_line or 'Advanced' in last_line or 'Veteran' in last_line or 'Legend' in last_line or 'Inviter' in last_line or 'The Sentinel' in last_line or 'The King' in last_line or 'deposited' in last_line:
            # Use regular expressions to remove hex codes in the format {FF0000} from the last line
            formatted_line = re.sub(r'\{([0-9A-Fa-f]{6})\}', '', last_line)
            formatted_line = re.sub(r'\[CLAN\]', '', formatted_line)
            formatted_line = re.sub(r']', ' ', formatted_line)
            formatted_line = re.sub(r'\[', '', formatted_line)
            formatted_line = re.sub(r'»', '', formatted_line)

            # Check if the message has been seen before
            if formatted_line not in seen_messages:
                # Add the message to the set of seen messages
                seen_messages.add(formatted_line)

                # Send the message to the Discord webhook
                requests.post(webhook_url, data={'content': formatted_line})
    except:
        # Ignore any errors and continue
        pass
</code>```

this is the code.

I try to use only that lines that are using the exact word.
example
Legend has kicked the ball- to be used because contains the word 'Legend'
Legendary has kicked the ball- not to use because don't contain the exact word 'Legend'

Body:
import requests
import re

# Replace with the path to the text file

file_path = r'C:\'

# Replace with your webhook URL
webhook_url = 'https://discord.com'

# Create a set to store seen messages
seen_messages = set()

# Keep reading and sending the last line of the file
while True:
    try:
        # Read the last line of the file
        with open(file_path, 'rb') as f:
            f.seek(-2, 2)
            while f.read(1) != b'\n':
                f.seek(-2, 1)
            last_line = f.readline().decode()

        # Check if the last line contains [CLAN] and deposited, and doesn't contain vehiculul
        if 'Newbie' in last_line or 'Advanced' in last_line or 'Veteran' in last_line or 'Legend' in last_line or 'Inviter' in last_line or 'The Sentinel' in last_line or 'The King' in last_line or 'deposited' in last_line:
            # Use regular expressions to remove hex codes in the format {FF0000} from the last line
            formatted_line = re.sub(r'\{([0-9A-Fa-f]{6})\}', '', last_line)
            formatted_line = re.sub(r'\[CLAN\]', '', formatted_line)
            formatted_line = re.sub(r']', ' ', formatted_line)
            formatted_line = re.sub(r'\[', '', formatted_line)
            formatted_line = re.sub(r'»', '', formatted_line)

            # Check if the message has been seen before
            if formatted_line not in seen_messages:
                # Add the message to the set of seen messages
                seen_messages.add(formatted_line)

                # Send the message to the Discord webhook
                requests.post(webhook_url, data={'content': formatted_line})
    except:
        # Ignore any errors and continue
        pass

this is the code.

I try to use only that lines that are using the exact word.
example
Legend has kicked the ball- to be used because contains the word 'Legend'
Legendary has kicked the ball- not to use because don't contain the exact word 'Legend'


问:
Entity Framework query root of type 'FromSqlQueryRootExpression' wasn't handled by provider code. From xunit test
I have a method that calls FromSqlRaw, this works fine when making an API call, but it fails when calling from XUnit test return await _dbContext.Entity.FromSqlRaw(sqlSelect, parameters).FirstOrDefaultAsync();

I've setup DbContextOptionsBuilder and used UseInMemoryDatabase instead of quering the database:

```<code>var optionsBuilder = new DbContextOptionsBuilder<MyDbContext>();
            optionsBuilder.UseInMemoryDatabase("My_database");
            _dbContext = new MyDbContext(optionsBuilder.Options);
            _entityRepository = new EntityRepository(_dbContext );
            _dbContext.Database.EnsureDeleted();
</code>```

Unit test call:  var result = await _entityRepository.GetEntityAsync(expectedEntity.EntityID);
I get:  System.InvalidOperationException : Query root of type 'FromSqlQueryRootExpression' wasn't handled by provider code. This issue happens when using a provider specific method on a different provider where it is not supported. when calling this from xUnit test.

I tried removing .FromSqlRaw(sqlSelect, parameters).FirstOrDefaultAsync(); and just said return await _dbContext.Entity.FirstOrDefaultAsync(); this worked fine. It seems like the issue is with the FromSqlRaw method.

Body:
I have a method that calls FromSqlRaw, this works fine when making an API call, but it fails when calling from XUnit test return await _dbContext.Entity.FromSqlRaw(sqlSelect, parameters).FirstOrDefaultAsync();

I've setup DbContextOptionsBuilder and used UseInMemoryDatabase instead of quering the database:

var optionsBuilder = new DbContextOptionsBuilder<MyDbContext>();
            optionsBuilder.UseInMemoryDatabase("My_database");
            _dbContext = new MyDbContext(optionsBuilder.Options);
            _entityRepository = new EntityRepository(_dbContext );
            _dbContext.Database.EnsureDeleted();

Unit test call:  var result = await _entityRepository.GetEntityAsync(expectedEntity.EntityID);
I get:  System.InvalidOperationException : Query root of type 'FromSqlQueryRootExpression' wasn't handled by provider code. This issue happens when using a provider specific method on a different provider where it is not supported. when calling this from xUnit test.

I tried removing .FromSqlRaw(sqlSelect, parameters).FirstOrDefaultAsync(); and just said return await _dbContext.Entity.FirstOrDefaultAsync(); this worked fine. It seems like the issue is with the FromSqlRaw method.


问:
Is There a Way to Make a Java Method that Opens a .txt File as a pop-up?
I am currently making a java project that simulates a website for swimmers. It has multiple classes and incorporates the Jswing GUI. I have buttons that are used to display other classes GUI and data, but I was wondering if there was a way to have it so when I click a button, it would pull up a .txt file as a pop up externally, as opposed to just reading and writing the .txt files data into my console.
I had initially tried to display information from a .txt file into a JLabel or JTextField so it could be seen but I had abandoned that idea in order to pursue the easier and simplier idea of bringing up a entirely new window of a .txt file

```<code>package finalProject;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

public class FrontInterface extends JPanel {
    private static JButton nSwimmer;
    private static JButton cSwimmer;
    private static JButton coach;
    private JLabel heading;
    private static JButton equipment;

public FrontInterface() {
    //construct components
    nSwimmer = new JButton ("New Swimmer");
    cSwimmer = new JButton ("Current Swimmer");
    coach = new JButton ("Coach");
    heading = new JLabel ("Welcome to the Swimming Station");
    equipment = new JButton ("Equipment");

    //adjust size and set layout
    setPreferredSize (new Dimension (752, 425));
    setLayout (null);

    //add components
    add (nSwimmer);
    add (cSwimmer);
    add (coach);
    add (heading);
    add (equipment);

    //set component bounds (only needed by Absolute Positioning)
    nSwimmer.setBounds (280, 150, 200, 20);
    cSwimmer.setBounds (280, 175, 200, 20);
    coach.setBounds (280, 200, 200, 20);
    heading.setBounds (280, 95, 195, 30);
    equipment.setBounds (280, 225, 200, 25);
}

public static void showWindow(){
    JFrame frame = new JFrame ("Front Interface");
    frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(new FrontInterface());
    frame.pack();
    frame.setVisible(true);

    nSwimmer.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            frame.setVisible(false);
            NewSwimmerForm w2 = new NewSwimmerForm();
            w2.showWindow();
        }
    });

    cSwimmer.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            frame.setVisible(false);
            CurrentSwimmer w2_1 = new CurrentSwimmer();
            w2_1.showWindow();
        }
    });

    coach.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            frame.setVisible(false);
            NewSwimmerForm w2 = new NewSwimmerForm();
            w2.showWindow();
        }
    });

    equipment.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            frame.setVisible(false);
            NewSwimmerForm w2 = new NewSwimmerForm();
            w2.showWindow();
        }
    });

    frame.setVisible(true);
}

    public static void main (String[] args) {
        showWindow();
    }
}

</code>```

And below is the code that the cSwimmer button will take you to upon clicking the cSwimmer button:

```<code>package finalProject;

import finalProject.FrontInterface;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

import javax.swing.*;
import java.awt.*;
import java.io.*;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

public class CurrentSwimmer extends JPanel {
private static JTextArea informationHeader;

public static void showWindow(){
    try{
     File file = new File("C:\\Users\\trent\\Desktop\\Intro to Computer Science\\Eclipse Codes\\FinalProject\\src\\finalProject\\history.txt");
       System.out.println(file.getCanonicalPath());
       FileInputStream ft = new FileInputStream(file);

       DataInputStream in = new DataInputStream(ft);
       BufferedReader br = new BufferedReader(new InputStreamReader(in));
       String strline;

       while((strline = br.readLine()) != null){
           System.out.println(strline);
       }
       in.close();
   }catch(Exception e){
       System.err.println("Error: " + e.getMessage());

   }
}
    public static void main(String [] args) {
    showWindow();
    }
}
</code>```

Now, I am completely unsure of how to go about my situation, whether it be I display the information from the .txt file onto a jTextArea or if I should just create a method to make a .txt file open externally and replace the pop up window I would otherwise have with the writing to JTextArea.

Body:
I am currently making a java project that simulates a website for swimmers. It has multiple classes and incorporates the Jswing GUI. I have buttons that are used to display other classes GUI and data, but I was wondering if there was a way to have it so when I click a button, it would pull up a .txt file as a pop up externally, as opposed to just reading and writing the .txt files data into my console.
I had initially tried to display information from a .txt file into a JLabel or JTextField so it could be seen but I had abandoned that idea in order to pursue the easier and simplier idea of bringing up a entirely new window of a .txt file

package finalProject;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

public class FrontInterface extends JPanel {
    private static JButton nSwimmer;
    private static JButton cSwimmer;
    private static JButton coach;
    private JLabel heading;
    private static JButton equipment;

public FrontInterface() {
    //construct components
    nSwimmer = new JButton ("New Swimmer");
    cSwimmer = new JButton ("Current Swimmer");
    coach = new JButton ("Coach");
    heading = new JLabel ("Welcome to the Swimming Station");
    equipment = new JButton ("Equipment");

    //adjust size and set layout
    setPreferredSize (new Dimension (752, 425));
    setLayout (null);

    //add components
    add (nSwimmer);
    add (cSwimmer);
    add (coach);
    add (heading);
    add (equipment);

    //set component bounds (only needed by Absolute Positioning)
    nSwimmer.setBounds (280, 150, 200, 20);
    cSwimmer.setBounds (280, 175, 200, 20);
    coach.setBounds (280, 200, 200, 20);
    heading.setBounds (280, 95, 195, 30);
    equipment.setBounds (280, 225, 200, 25);
}

public static void showWindow(){
    JFrame frame = new JFrame ("Front Interface");
    frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(new FrontInterface());
    frame.pack();
    frame.setVisible(true);

    nSwimmer.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            frame.setVisible(false);
            NewSwimmerForm w2 = new NewSwimmerForm();
            w2.showWindow();
        }
    });

    cSwimmer.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            frame.setVisible(false);
            CurrentSwimmer w2_1 = new CurrentSwimmer();
            w2_1.showWindow();
        }
    });

    coach.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            frame.setVisible(false);
            NewSwimmerForm w2 = new NewSwimmerForm();
            w2.showWindow();
        }
    });

    equipment.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            frame.setVisible(false);
            NewSwimmerForm w2 = new NewSwimmerForm();
            w2.showWindow();
        }
    });

    frame.setVisible(true);
}

    public static void main (String[] args) {
        showWindow();
    }
}

And below is the code that the cSwimmer button will take you to upon clicking the cSwimmer button:

package finalProject;

import finalProject.FrontInterface;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

import javax.swing.*;
import java.awt.*;
import java.io.*;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

public class CurrentSwimmer extends JPanel {
private static JTextArea informationHeader;

public static void showWindow(){
    try{
     File file = new File("C:\\Users\\trent\\Desktop\\Intro to Computer Science\\Eclipse Codes\\FinalProject\\src\\finalProject\\history.txt");
       System.out.println(file.getCanonicalPath());
       FileInputStream ft = new FileInputStream(file);

       DataInputStream in = new DataInputStream(ft);
       BufferedReader br = new BufferedReader(new InputStreamReader(in));
       String strline;

       while((strline = br.readLine()) != null){
           System.out.println(strline);
       }
       in.close();
   }catch(Exception e){
       System.err.println("Error: " + e.getMessage());

   }
}
    public static void main(String [] args) {
    showWindow();
    }
}

Now, I am completely unsure of how to go about my situation, whether it be I display the information from the .txt file onto a jTextArea or if I should just create a method to make a .txt file open externally and replace the pop up window I would otherwise have with the writing to JTextArea.


问:
Pandas interpolate does not work on hourly time series data
I have got the below plot of temperature in a time series dates aggregated hourly.

What I am trying to do is to interpolate the missing values between 2019 and 2020, using pandas pd.interpolate, and generate results hourly (same frequency as the rest of the data in weather_data). My data is called weather_data, the index column is called date_time (dtype is float64) and the temperature column has also got float64 as the dtype. Here is what I have tried:

```<code>test = weather_datetime_index.temperature.interpolate("cubicspline")
test.plot()
</code>```

This gave the same plot. I also tried (based on this post):

```<code>interpolated_temp = weather_datetime_index["temperature"].astype(float).interpolate(method="time")
</code>```

still gave the same plot.

I also tried (as per this post):

```<code>test = weather_datetime_index.temperature.interpolate("spline",limit_direction="forward", order=1)
test.plot()
</code>```

but still gave me the same plot.

How can I interpolate this data using pd.interpolate?

Body:
I have got the below plot of temperature in a time series dates aggregated hourly.

What I am trying to do is to interpolate the missing values between 2019 and 2020, using pandas pd.interpolate, and generate results hourly (same frequency as the rest of the data in weather_data). My data is called weather_data, the index column is called date_time (dtype is float64) and the temperature column has also got float64 as the dtype. Here is what I have tried:

test = weather_datetime_index.temperature.interpolate("cubicspline")
test.plot()

This gave the same plot. I also tried (based on this post):

interpolated_temp = weather_datetime_index["temperature"].astype(float).interpolate(method="time")

still gave the same plot.

I also tried (as per this post):

test = weather_datetime_index.temperature.interpolate("spline",limit_direction="forward", order=1)
test.plot()

but still gave me the same plot.

How can I interpolate this data using pd.interpolate?


问:
failed when upload multiple image with description in laravel
i am trying to upload image from mobile, with name of the image of it.
i am using flutter for the mobile and using dio to upload it.
but i got error when it upload to laravel server.

here is my code in laravel 9 :

```<code>foreach ($request->team as $item) {
            $foto = $item->file('id_card');
            $path = public_path() . '/upload/idcard/' . Str::slug($workingPermit->id) . Auth::id() . '/images';
            $fileName = Str::random(6) . $foto->getClientOriginalName();
            $foto->move($path, $fileName);
            $workingPermit->tenant_team()->create([
                'name' => $item['name'],
                // 'id_card' => $item['id_card']
                'id_card' => '/upload/idcard/' . Str::slug($workingPermit->id) . Auth::id() . '/images/'. $fileName
            ]);
        }
</code>```

please help, i really need your help

Body:
i am trying to upload image from mobile, with name of the image of it.
i am using flutter for the mobile and using dio to upload it.
but i got error when it upload to laravel server.

here is my code in laravel 9 :

foreach ($request->team as $item) {
            $foto = $item->file('id_card');
            $path = public_path() . '/upload/idcard/' . Str::slug($workingPermit->id) . Auth::id() . '/images';
            $fileName = Str::random(6) . $foto->getClientOriginalName();
            $foto->move($path, $fileName);
            $workingPermit->tenant_team()->create([
                'name' => $item['name'],
                // 'id_card' => $item['id_card']
                'id_card' => '/upload/idcard/' . Str::slug($workingPermit->id) . Auth::id() . '/images/'. $fileName
            ]);
        }

please help, i really need your help


问:
how to get overview report using stripe api
I got a problem about the stripe documentation, are they have a support api to get the data like this?

I'm using laravel, and want to create the report data like stripe dashboard.

I'm trying to check the console and see their fetch xhr and they have this

link

but I need login first to stripe dashboard to see the data

so, how I can I get the api for report overview like that?


问:
Is there a spec on the base of setuptools' overridden command classes?
I have a Python package with a custom hook on the install class:

```<code>from setuptools.command.install import install

class my_install(install):
    def run(self):
        install.run(self)
        # and then some more

setup(
    #...
    cmdclass={'install': my_install},
    #...
)
</code>```

Is there any public documentation about the contents of the class setuptools.command.install.install? I'd like to use some of the fields (e. g. self.install_scripts) inside my_install.run(), but without some kind of public API commitment from the setuptools' maintainers that would leave a bad taste.

Body:
I have a Python package with a custom hook on the install class:

from setuptools.command.install import install

class my_install(install):
    def run(self):
        install.run(self)
        # and then some more

setup(
    #...
    cmdclass={'install': my_install},
    #...
)

Is there any public documentation about the contents of the class setuptools.command.install.install? I'd like to use some of the fields (e. g. self.install_scripts) inside my_install.run(), but without some kind of public API commitment from the setuptools' maintainers that would leave a bad taste.


问:
cascade layers with scss and vscode
I would like to add layers to importing component's scss files in my main style.scss in vscode.

I have a style.scss file in which I @import my app's component's _compstyle.scss files with, and my vscode generates the final style.css with watch sass. My question is that is it possible to add cascade layers to the import, or use cascade layers with scss at all? I tried to set layers in my style.scss's first row like this:

```<code>@layer reset, default, comp
</code>```

My initial import row looks like this:

```<code>@import "./comp/compname/compstyle";
</code>```

I tried to add layers to it like this:

```<code>@import "./comp/compname/compstyle" layer(comp);
</code>```

My vscode does not recognize the @layer rule here. Is it possible at all to use layers with sccs, or does it have something similar, or something to replace it with?

I could not find anything on this topic so far, so every bit of help would be appreciated. Thanks in advance!

Title: cascade layers with scss and vscode

Body:
I would like to add layers to importing component's scss files in my main style.scss in vscode.

I have a style.scss file in which I @import my app's component's _compstyle.scss files with, and my vscode generates the final style.css with watch sass. My question is that is it possible to add cascade layers to the import, or use cascade layers with scss at all? I tried to set layers in my style.scss's first row like this:

@layer reset, default, comp

My initial import row looks like this:

@import "./comp/compname/compstyle";

I tried to add layers to it like this:

@import "./comp/compname/compstyle" layer(comp);

My vscode does not recognize the @layer rule here. Is it possible at all to use layers with sccs, or does it have something similar, or something to replace it with?

I could not find anything on this topic so far, so every bit of help would be appreciated. Thanks in advance!


问:
How do I get the max count of queryable keys from a MongoDB document?
Let's say I have the following document:

```<code>{
  "_id": "123", // 1
  "parent1": {
    "child1": "234",  // 2
    "child2": {
      "grandchild1": "345",  // 3
      "grandchild2": {
        "greatgrand1": "456" // 4
      }
    },
    "child3": [
      {
        "grandchild1": "567", // 5
        "grandchild2": {
          "greatgrand1": "678", // 6
          "greatgrand2": {
            "greatgrand1": "789" // 7
          }
        }
      }
    ]
  },
  "parent2": [
    {
      "child1": "567", // 8
      "child2": {
        "grandchild1": "678", // 9
        "grandchild2": {
          "greatgrand1": "789"  // 10
        }
      }
    }
  ]
}
</code>```

The count would return 10 for this document. I have other documents of varying size and depth. I would then like it to compare and return the largest count.

I have tried doing various forms of $objectToArray, but haven't found one that works.

Body:
Let's say I have the following document:

{
  "_id": "123", // 1
  "parent1": {
    "child1": "234",  // 2
    "child2": {
      "grandchild1": "345",  // 3
      "grandchild2": {
        "greatgrand1": "456" // 4
      }
    },
    "child3": [
      {
        "grandchild1": "567", // 5
        "grandchild2": {
          "greatgrand1": "678", // 6
          "greatgrand2": {
            "greatgrand1": "789" // 7
          }
        }
      }
    ]
  },
  "parent2": [
    {
      "child1": "567", // 8
      "child2": {
        "grandchild1": "678", // 9
        "grandchild2": {
          "greatgrand1": "789"  // 10
        }
      }
    }
  ]
}

The count would return 10 for this document. I have other documents of varying size and depth. I would then like it to compare and return the largest count.

I have tried doing various forms of $objectToArray, but haven't found one that works.


问:
Problem while recieving application/x-www-form-urlencoded type Objects from Html to NodeJS
I am recieving textarea data from html page using xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); POST request from client. I printed the data before sending the Object to server in client console and recieved exact same Input to textarea. But some characters in the data got modified when I recieved the data. I observed this by printing the recived data to server in server console.

HTML:

```<code><script>
function postProgram(req, ID) {
console.log(document.getElementById(ID).value);
var xhr = new XMLHttpRequest();
xhr.open("POST", req, true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send(document.getElementById(ID).value);
}
</script>
</code>```

NodeJS:

```<code>app.post('/ExCode.f90', (req, res) => {
  console.log(req.body);
});
</code>```

Textarea Input data:

```<code>PROGRAM ExampleCode
!Example Code of addition of two numbers
IMPLICIT NONE

REAL :: a, b, c

!Numbers to be added
  a = 1;  b = 2

!Add Operation
  c = a + b

!Print Output
print*, "Third Number:", c

END PROGRAM ExampleCode

</code>```

Resulting Output Console Data:

```<code>PROGRAM ExampleCode
!Example Code of addition of two numbers
IMPLICIT NONE

REAL :: a, b, c

!Numbers to be added
  a ":" 1;  b = 2

!Add Operation
  c = a   b

!Print Output
print*, \"Third Number:\", c

END PROGRAM ExampleCode
</code>```

Body:
I am recieving textarea data from html page using xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); POST request from client. I printed the data before sending the Object to server in client console and recieved exact same Input to textarea. But some characters in the data got modified when I recieved the data. I observed this by printing the recived data to server in server console.

HTML:

NodeJS:

app.post('/ExCode.f90', (req, res) => {
  console.log(req.body);
});

Textarea Input data:

PROGRAM ExampleCode
!Example Code of addition of two numbers
IMPLICIT NONE

REAL :: a, b, c

!Numbers to be added
  a = 1;  b = 2

!Add Operation
  c = a + b

!Print Output
print*, "Third Number:", c

END PROGRAM ExampleCode

Resulting Output Console Data:

PROGRAM ExampleCode
!Example Code of addition of two numbers
IMPLICIT NONE

REAL :: a, b, c

!Numbers to be added
  a ":" 1;  b = 2

!Add Operation
  c = a   b

!Print Output
print*, \"Third Number:\", c

END PROGRAM ExampleCode


问:
AttributeError: module 'dominate.tags' has no attribute 'input'
I am running a flask application on python 3.9 and following flask and getting following error:

```<code>File "/usr/local/lib/python3.9/site-packages/flask_bootstrap/forms.py", line 51, in _wrapped_input
    wrap.add(tags.input(type=type, _class=' '.join(classes), **kwargs))
AttributeError: module 'dominate.tags' has no attribute 'input'
</code>```

I can see that input has been removed in dominate/tags.py but not sure which version of dominate should I use!

Body:
I am running a flask application on python 3.9 and following flask and getting following error:

File "/usr/local/lib/python3.9/site-packages/flask_bootstrap/forms.py", line 51, in _wrapped_input
    wrap.add(tags.input(type=type, _class=' '.join(classes), **kwargs))
AttributeError: module 'dominate.tags' has no attribute 'input'

I can see that input has been removed in dominate/tags.py but not sure which version of dominate should I use!


问:
insmod: ERROR could not insert module: Operation not permitted in WSL2 Ubuntu
I followed the instructions in this video to compile the Linux kernel for WSL with video drivers. The kernel is running and I do have access to /dev/video0 which was the whole point.

I can also confirm that the correct kernel is running with uname -a, which gives the following output:

Linux DESKTOP-V575QHO 5.15.74.2-microsoft-standard-WSL2+ #1 SMP Wed Dec 7 14:57:03 CET 2022 x86_64 x86_64 x86_64 GNU/Linux
```
<p>I now installed <code>dkms</code> and used it to compile the akvcam module (a virtual camera driver). Both <code>make</code> and <code>make dkms_install</code> exited successfully.</p>
<p>However, when I'm actually trying to install the module using <code>insmod /lib/modules/$(uname -r)/updates/dkms/akvcam.ko</code> I get the following error:</p>
<pre class="lang-bash prettyprint-override"><code>insmod: ERROR: could not insert module /lib/modules/5.15.74.2-microsoft-standard-WSL2+/updates/dkms/akvcam.ko: Operation not permitted
</code>```

I've seen here that this might be related to Secure Boot, but I don't really understand how this would translate to WSL2 and how this problem could be solved here.

Any help is greatly appreciated!

Body:
I followed the instructions in this video to compile the Linux kernel for WSL with video drivers. The kernel is running and I do have access to /dev/video0 which was the whole point.

I can also confirm that the correct kernel is running with uname -a, which gives the following output:

Linux DESKTOP-V575QHO 5.15.74.2-microsoft-standard-WSL2+ #1 SMP Wed Dec 7 14:57:03 CET 2022 x86_64 x86_64 x86_64 GNU/Linux

I now installed dkms and used it to compile the akvcam module (a virtual camera driver). Both make and make dkms_install exited successfully.

However, when I'm actually trying to install the module using insmod /lib/modules/$(uname -r)/updates/dkms/akvcam.ko I get the following error:

insmod: ERROR: could not insert module /lib/modules/5.15.74.2-microsoft-standard-WSL2+/updates/dkms/akvcam.ko: Operation not permitted

I've seen here that this might be related to Secure Boot, but I don't really understand how this would translate to WSL2 and how this problem could be solved here.

Any help is greatly appreciated!


问:
How to setup AWS Dynamo connection with accessKey, accessSecret and accessToken in DBeaver?
I would like to ask, if is possible to setup new AWS Dynamo connection with
access key, access secret and access token in DBeaver, which I have available in my AWS SSO account.

In DBeaver I'm able to put access key and access secret, but access token field is missing in connection settings.


问:
Android (Kotlin) CameraX in Fragment: Unable to configure camera 0, timeout
I'm quite new to Android app development. However I can't really figure out why this code Fragment is not working, I'm trying to preview the camera in a PreviewView within an android fragment.

Fragment XML:

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Camera">

    <androidx.camera.view.PreviewView
        android:id="@+id/cameraPreview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</FrameLayout>
</code>```

Fragment Kotlin code:

```<code>package dev.splitsecond.splitsecond_poc

import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.camera.core.CameraSelector
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import dev.splitsecond.splitsecond_poc.databinding.FragmentCameraBinding
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

class Camera : Fragment() {
    private lateinit var cameraExecutor: ExecutorService
    private lateinit var binding: FragmentCameraBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = FragmentCameraBinding.inflate(layoutInflater, null, false)
        cameraExecutor = Executors.newSingleThreadExecutor()
        requestRequiredPermissions()
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_camera, container, false)
    }

    private fun requestRequiredPermissions() {
        requestCameraPermissionIfMissing { granted ->
            if (granted)
                startCamera()
            else
                Toast.makeText(activity, "Please allow camera permission", Toast.LENGTH_LONG).show()
        }
    }

    private fun requestCameraPermissionIfMissing(onResult: ((Boolean) -> Unit)) {
        if (ContextCompat.checkSelfPermission(
                requireContext(),
                Manifest.permission.CAMERA
            ) == PackageManager.PERMISSION_GRANTED
        )
            onResult(true)
        else
            registerForActivityResult(ActivityResultContracts.RequestPermission()) {
                onResult(it)
            }.launch(Manifest.permission.CAMERA)
    }

    private fun startCamera() {
        val processCameraProvider = ProcessCameraProvider.getInstance(requireContext())
        processCameraProvider.addListener({

            val cameraProvider = processCameraProvider.get()
            val previewUseCase = buildPreviewUseCase()

            cameraProvider.unbindAll()
            cameraProvider.bindToLifecycle(this, CameraSelector.DEFAULT_BACK_CAMERA, previewUseCase)
        }, ContextCompat.getMainExecutor(requireContext()))
    }

    private fun buildPreviewUseCase(): Preview {
        return Preview.Builder().build()
            .also { it.setSurfaceProvider(binding.cameraPreview.surfaceProvider) }
    }
}
</code>```

And the logcat logs:

```<code>2022-12-01 09:21:15.984 25928-25962/dev.splitsecond.splitsecond_poc D/Camera2CameraImpl: {Camera@43190c8[id=0]} Opening camera.
2022-12-01 09:21:15.984 25928-25962/dev.splitsecond.splitsecond_poc D/Camera2CameraImpl: {Camera@43190c8[id=0]} Transitioning camera internal state: INITIALIZED --> OPENING
2022-12-01 09:21:15.984 25928-25962/dev.splitsecond.splitsecond_poc D/CameraStateMachine: New public camera state CameraState{type=OPENING, error=null} from OPENING and null
2022-12-01 09:21:15.984 25928-25962/dev.splitsecond.splitsecond_poc D/CameraStateMachine: Publishing new public camera state CameraState{type=OPENING, error=null}
2022-12-01 09:21:15.985 25928-25962/dev.splitsecond.splitsecond_poc D/UseCaseAttachState: All use case: [androidx.camera.core.Preview-996def38-14f2-4f96-a3bb-26039503675b19184323] for camera: 0
2022-12-01 09:21:15.996 25928-25962/dev.splitsecond.splitsecond_poc D/Camera2CameraImpl: {Camera@43190c8[id=0]} Use case androidx.camera.core.Preview-996def38-14f2-4f96-a3bb-26039503675b19184323 ACTIVE
2022-12-01 09:21:15.996 25928-25962/dev.splitsecond.splitsecond_poc D/UseCaseAttachState: Active and attached use case: [androidx.camera.core.Preview-996def38-14f2-4f96-a3bb-26039503675b19184323] for camera: 0
2022-12-01 09:21:15.998 25928-25962/dev.splitsecond.splitsecond_poc D/Camera2CameraImpl: {Camera@43190c8[id=0]} CameraDevice.onOpened()
2022-12-01 09:21:15.998 25928-25962/dev.splitsecond.splitsecond_poc D/Camera2CameraImpl: {Camera@43190c8[id=0]} Transitioning camera internal state: OPENING --> OPENED
2022-12-01 09:21:15.998 25928-25962/dev.splitsecond.splitsecond_poc D/CameraStateRegistry: Recalculating open cameras:
    Camera                                       State
    -------------------------------------------------------------------
    Camera@43190c8[id=0]                         OPEN
    Camera@a26fb0c[id=1]                         UNKNOWN
    -------------------------------------------------------------------
    Open count: 1 (Max allowed: 1)
2022-12-01 09:21:15.998 25928-25962/dev.splitsecond.splitsecond_poc D/CameraStateMachine: New public camera state CameraState{type=OPEN, error=null} from OPEN and null
2022-12-01 09:21:15.998 25928-25962/dev.splitsecond.splitsecond_poc D/CameraStateMachine: Publishing new public camera state CameraState{type=OPEN, error=null}
2022-12-01 09:21:15.999 25928-25962/dev.splitsecond.splitsecond_poc D/UseCaseAttachState: All use case: [androidx.camera.core.Preview-996def38-14f2-4f96-a3bb-26039503675b19184323] for camera: 0
2022-12-01 09:21:16.000 25928-25962/dev.splitsecond.splitsecond_poc D/UseCaseAttachState: Active and attached use case: [androidx.camera.core.Preview-996def38-14f2-4f96-a3bb-26039503675b19184323] for camera: 0
2022-12-01 09:21:17.173 25928-25940/dev.splitsecond.splitsecond_poc W/System: A resource failed to call close.
2022-12-01 09:21:21.006 25928-25961/dev.splitsecond.splitsecond_poc D/Camera2CameraImpl: {Camera@43190c8[id=0]} Transitioning camera internal state: OPENED --> OPENED
2022-12-01 09:21:21.007 25928-25961/dev.splitsecond.splitsecond_poc D/CameraStateMachine: New public camera state CameraState{type=OPEN, error=StateError{code=4, cause=java.util.concurrent.TimeoutException: Cannot complete surfaceList within 5000}} from OPEN and StateError{code=4, cause=java.util.concurrent.TimeoutException: Cannot complete surfaceList within 5000}
2022-12-01 09:21:21.007 25928-25961/dev.splitsecond.splitsecond_poc D/CameraStateMachine: Publishing new public camera state CameraState{type=OPEN, error=StateError{code=4, cause=java.util.concurrent.TimeoutException: Cannot complete surfaceList within 5000}}
2022-12-01 09:21:21.008 25928-25961/dev.splitsecond.splitsecond_poc E/Camera2CameraImpl: Unable to configure camera 0, timeout!
</code>```

I would really like to understand what I am doing wrong.

Body:
I'm quite new to Android app development. However I can't really figure out why this code Fragment is not working, I'm trying to preview the camera in a PreviewView within an android fragment.

Fragment XML:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Camera">

    <androidx.camera.view.PreviewView
        android:id="@+id/cameraPreview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</FrameLayout>

Fragment Kotlin code:

package dev.splitsecond.splitsecond_poc

import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.camera.core.CameraSelector
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import dev.splitsecond.splitsecond_poc.databinding.FragmentCameraBinding
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

class Camera : Fragment() {
    private lateinit var cameraExecutor: ExecutorService
    private lateinit var binding: FragmentCameraBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = FragmentCameraBinding.inflate(layoutInflater, null, false)
        cameraExecutor = Executors.newSingleThreadExecutor()
        requestRequiredPermissions()
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_camera, container, false)
    }

    private fun requestRequiredPermissions() {
        requestCameraPermissionIfMissing { granted ->
            if (granted)
                startCamera()
            else
                Toast.makeText(activity, "Please allow camera permission", Toast.LENGTH_LONG).show()
        }
    }

    private fun requestCameraPermissionIfMissing(onResult: ((Boolean) -> Unit)) {
        if (ContextCompat.checkSelfPermission(
                requireContext(),
                Manifest.permission.CAMERA
            ) == PackageManager.PERMISSION_GRANTED
        )
            onResult(true)
        else
            registerForActivityResult(ActivityResultContracts.RequestPermission()) {
                onResult(it)
            }.launch(Manifest.permission.CAMERA)
    }

    private fun startCamera() {
        val processCameraProvider = ProcessCameraProvider.getInstance(requireContext())
        processCameraProvider.addListener({

            val cameraProvider = processCameraProvider.get()
            val previewUseCase = buildPreviewUseCase()

            cameraProvider.unbindAll()
            cameraProvider.bindToLifecycle(this, CameraSelector.DEFAULT_BACK_CAMERA, previewUseCase)
        }, ContextCompat.getMainExecutor(requireContext()))
    }

    private fun buildPreviewUseCase(): Preview {
        return Preview.Builder().build()
            .also { it.setSurfaceProvider(binding.cameraPreview.surfaceProvider) }
    }
}

And the logcat logs:

2022-12-01 09:21:15.984 25928-25962/dev.splitsecond.splitsecond_poc D/Camera2CameraImpl: {Camera@43190c8[id=0]} Opening camera.
2022-12-01 09:21:15.984 25928-25962/dev.splitsecond.splitsecond_poc D/Camera2CameraImpl: {Camera@43190c8[id=0]} Transitioning camera internal state: INITIALIZED --> OPENING
2022-12-01 09:21:15.984 25928-25962/dev.splitsecond.splitsecond_poc D/CameraStateMachine: New public camera state CameraState{type=OPENING, error=null} from OPENING and null
2022-12-01 09:21:15.984 25928-25962/dev.splitsecond.splitsecond_poc D/CameraStateMachine: Publishing new public camera state CameraState{type=OPENING, error=null}
2022-12-01 09:21:15.985 25928-25962/dev.splitsecond.splitsecond_poc D/UseCaseAttachState: All use case: [androidx.camera.core.Preview-996def38-14f2-4f96-a3bb-26039503675b19184323] for camera: 0
2022-12-01 09:21:15.996 25928-25962/dev.splitsecond.splitsecond_poc D/Camera2CameraImpl: {Camera@43190c8[id=0]} Use case androidx.camera.core.Preview-996def38-14f2-4f96-a3bb-26039503675b19184323 ACTIVE
2022-12-01 09:21:15.996 25928-25962/dev.splitsecond.splitsecond_poc D/UseCaseAttachState: Active and attached use case: [androidx.camera.core.Preview-996def38-14f2-4f96-a3bb-26039503675b19184323] for camera: 0
2022-12-01 09:21:15.998 25928-25962/dev.splitsecond.splitsecond_poc D/Camera2CameraImpl: {Camera@43190c8[id=0]} CameraDevice.onOpened()
2022-12-01 09:21:15.998 25928-25962/dev.splitsecond.splitsecond_poc D/Camera2CameraImpl: {Camera@43190c8[id=0]} Transitioning camera internal state: OPENING --> OPENED
2022-12-01 09:21:15.998 25928-25962/dev.splitsecond.splitsecond_poc D/CameraStateRegistry: Recalculating open cameras:
    Camera                                       State
    -------------------------------------------------------------------
    Camera@43190c8[id=0]                         OPEN
    Camera@a26fb0c[id=1]                         UNKNOWN
    -------------------------------------------------------------------
    Open count: 1 (Max allowed: 1)
2022-12-01 09:21:15.998 25928-25962/dev.splitsecond.splitsecond_poc D/CameraStateMachine: New public camera state CameraState{type=OPEN, error=null} from OPEN and null
2022-12-01 09:21:15.998 25928-25962/dev.splitsecond.splitsecond_poc D/CameraStateMachine: Publishing new public camera state CameraState{type=OPEN, error=null}
2022-12-01 09:21:15.999 25928-25962/dev.splitsecond.splitsecond_poc D/UseCaseAttachState: All use case: [androidx.camera.core.Preview-996def38-14f2-4f96-a3bb-26039503675b19184323] for camera: 0
2022-12-01 09:21:16.000 25928-25962/dev.splitsecond.splitsecond_poc D/UseCaseAttachState: Active and attached use case: [androidx.camera.core.Preview-996def38-14f2-4f96-a3bb-26039503675b19184323] for camera: 0
2022-12-01 09:21:17.173 25928-25940/dev.splitsecond.splitsecond_poc W/System: A resource failed to call close.
2022-12-01 09:21:21.006 25928-25961/dev.splitsecond.splitsecond_poc D/Camera2CameraImpl: {Camera@43190c8[id=0]} Transitioning camera internal state: OPENED --> OPENED
2022-12-01 09:21:21.007 25928-25961/dev.splitsecond.splitsecond_poc D/CameraStateMachine: New public camera state CameraState{type=OPEN, error=StateError{code=4, cause=java.util.concurrent.TimeoutException: Cannot complete surfaceList within 5000}} from OPEN and StateError{code=4, cause=java.util.concurrent.TimeoutException: Cannot complete surfaceList within 5000}
2022-12-01 09:21:21.007 25928-25961/dev.splitsecond.splitsecond_poc D/CameraStateMachine: Publishing new public camera state CameraState{type=OPEN, error=StateError{code=4, cause=java.util.concurrent.TimeoutException: Cannot complete surfaceList within 5000}}
2022-12-01 09:21:21.008 25928-25961/dev.splitsecond.splitsecond_poc E/Camera2CameraImpl: Unable to configure camera 0, timeout!

I would really like to understand what I am doing wrong.


问:
Spotify API POST Request - Add Tracks to Playlist: Items Not Added In Order
This is my fetch request code: (which works fine BUT the songs are not added in the order that they are in in the trackIdArr state).

```<code>// Add tracks to playlist
    await fetch(
      `https://api.spotify.com/v1/playlists/${playlistId}/tracks`,
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify({ uris: trackIdArr }),
      }
    );
</code>```

Spotify API doc reads:
If [position query is] omitted, the items will be appended to the playlist. Items are added in the order they are listed in the query string or request body.

How can I fix this? I have tried using for of loop, axios, adding a position parameter but it seems as though since it is an async await request, the items would not be added in order. So, why does spotify claim that it would? Am I doing something wrong? Thank you!

Body:
This is my fetch request code: (which works fine BUT the songs are not added in the order that they are in in the trackIdArr state).

// Add tracks to playlist
    await fetch(
      `https://api.spotify.com/v1/playlists/${playlistId}/tracks`,
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify({ uris: trackIdArr }),
      }
    );

Spotify API doc reads:
If [position query is] omitted, the items will be appended to the playlist. Items are added in the order they are listed in the query string or request body.

How can I fix this? I have tried using for of loop, axios, adding a position parameter but it seems as though since it is an async await request, the items would not be added in order. So, why does spotify claim that it would? Am I doing something wrong? Thank you!


问:
High memory usage Lambda function (AWS) using Python tarfile Lib
I'm trying to execute a Lambda function to decompress a TAR file inside an S3 bucket containing the file itself.

The point is that the TAR File dimension (12GB) exceeds the maximum RAM that AWS Lambda allows (10GB).

Indeed, I run out of memory when executing the lambda function:

Memory Size: 10240 MB Max Memory Used: 10240 MB

Is there a way to use the tarfile library and keep the memory level low?

Below my Lambda function code:

import logging
import tarfile
from io import BytesIO
from boto3 import resource
from urllib import parse
import io
import boto3
import botocore
import tarfile
import math
from io import BytesIO

s3_client = boto3.client('s3')

def lambda_handler(event, context):

  invocation_id = event['invocationId']
  invocation_schema_version = event['invocationSchemaVersion']
  results = []
  task = event['tasks'][0]
  task_id = task['taskId']
  key = parse.unquote(task['s3Key'], encoding='utf-8')
  obj_version_id = task['s3VersionId']
  bucket = task['s3BucketArn'].split(':')[-1]

  input_tar_file = s3_client.get_object(Bucket = bucket, Key = key)

  with tarfile.open(fileobj=input_tar_file['Body'], mode='r|') as tar:
      for tar_resource in tar:
          if (tar_resource.isfile()):
              inner_file_bytes = tar.extractfile(tar_resource).read()
              s3_client.upload_fileobj(BytesIO(inner_file_bytes), Bucket = bucket, Key = tar_resource.name)

  return {
    "invocationSchemaVersion": invocation_schema_version,
    "treatMissingKeysAs" : "PermanentFailure",
    "invocationId" : invocation_id,
    "results": [
      {
        "taskId": task_id,
        "resultCode": "Succeeded",
        "resultString": "success"
      }
    ]
  }
```

Appreciate the help.

Body:
I'm trying to execute a Lambda function to decompress a TAR file inside an S3 bucket containing the file itself.

The point is that the TAR File dimension (12GB) exceeds the maximum RAM that AWS Lambda allows (10GB).

Indeed, I run out of memory when executing the lambda function:

Memory Size: 10240 MB Max Memory Used: 10240 MB

Is there a way to use the tarfile library and keep the memory level low?

Below my Lambda function code:

import logging
import tarfile
from io import BytesIO
from boto3 import resource
from urllib import parse
import io
import boto3
import botocore
import tarfile
import math
from io import BytesIO

s3_client = boto3.client('s3')

def lambda_handler(event, context):

  invocation_id = event['invocationId']
  invocation_schema_version = event['invocationSchemaVersion']
  results = []
  task = event['tasks'][0]
  task_id = task['taskId']
  key = parse.unquote(task['s3Key'], encoding='utf-8')
  obj_version_id = task['s3VersionId']
  bucket = task['s3BucketArn'].split(':')[-1]

  input_tar_file = s3_client.get_object(Bucket = bucket, Key = key)

  with tarfile.open(fileobj=input_tar_file['Body'], mode='r|') as tar:
      for tar_resource in tar:
          if (tar_resource.isfile()):
              inner_file_bytes = tar.extractfile(tar_resource).read()
              s3_client.upload_fileobj(BytesIO(inner_file_bytes), Bucket = bucket, Key = tar_resource.name)

  return {
    "invocationSchemaVersion": invocation_schema_version,
    "treatMissingKeysAs" : "PermanentFailure",
    "invocationId" : invocation_id,
    "results": [
      {
        "taskId": task_id,
        "resultCode": "Succeeded",
        "resultString": "success"
      }
    ]
  }

Appreciate the help.


问:
Django merge multiple dictionaries based on a common date and shift filed name
I have two table

sale which has field like this

And other table is product

I am fetching tag count and avg product price with this query

```<code>today = timezone.now().today()
start_date = today - relativedelta(months=12)
end_date = today
sale_filters = (
    Q(tags__name__in=['Device','Mobile']) &
    (Q(date_created__gte=start_date) & Q(date_created__lte=end_date))
)
sale_year = Sale.objects.using('read_rep') \
        .prefetch_related('products') \
        .annotate(month=TruncMonth('date_created')) \
        .filter(
            sale_filters
        ).order_by('month') \
        .values(
            'tags__name','month'
        ).annotate(
            tags_count=Count('tags__name'),
            price_avg=Coalesce(Avg('products__price'), Decimal('0')),
            price_sum=Coalesce(Sum('products__price'), Decimal('0'))
        )
</code>```

Result:

```<code>{'tags__name': 'Device', 'date_created': datetime.datetime(2022, 11, 12, 3, 20, 3, tzinfo=<UTC>), 'tags_count': 1, 'price_avg': Decimal('234.000000'), 'price_sum': Decimal('234.00')},
{'tags__name': 'Mobile', 'date_created': datetime.datetime(2022, 11, 12, 3, 20, 3, tzinfo=<UTC>), 'tags_count': 1, 'price_avg': Decimal('234.000000'), 'price_sum': Decimal('234.00')},
{'tags__name': 'Device', 'date_created': datetime.datetime(2022, 12, 6, 16, 25, 6, 178045, tzinfo=<UTC>), 'tags_count': 1, 'price_avg': Decimal('100.000000'), 'price_sum': Decimal('100.00')},
{'tags__name': 'Mobile', 'date_created': datetime.datetime(2022, 12, 6, 16, 25, 6, 178045, tzinfo=<UTC>), 'tags_count': 1, 'price_avg': Decimal('100.000000'), 'price_sum': Decimal('100.00')}
</code>```

I want result like this

```<code>{'date_created': datetime.datetime(2022, 11, 12, 3, 20, 3, tzinfo=<UTC>), 'Device': 1, 'Mobile': 1, 'price_avg': Decimal('100.000000'), 'price_sum': Decimal('100.00')}
{'date_created': datetime.datetime(2022, 12, 6, 16, 25, 6, 178045, tzinfo=<UTC>), 'Device': 1, 'Mobile': 1, 'price_avg': Decimal('100.000000'), 'price_sum': Decimal('100.00')}
</code>```

Is there any way that I can achieve this data format.
Any help will be appreciated.

Body:
I have two table

sale which has field like this

And other table is product

I am fetching tag count and avg product price with this query

today = timezone.now().today()
start_date = today - relativedelta(months=12)
end_date = today
sale_filters = (
    Q(tags__name__in=['Device','Mobile']) &
    (Q(date_created__gte=start_date) & Q(date_created__lte=end_date))
)
sale_year = Sale.objects.using('read_rep') \
        .prefetch_related('products') \
        .annotate(month=TruncMonth('date_created')) \
        .filter(
            sale_filters
        ).order_by('month') \
        .values(
            'tags__name','month'
        ).annotate(
            tags_count=Count('tags__name'),
            price_avg=Coalesce(Avg('products__price'), Decimal('0')),
            price_sum=Coalesce(Sum('products__price'), Decimal('0'))
        )

Result:

{'tags__name': 'Device', 'date_created': datetime.datetime(2022, 11, 12, 3, 20, 3, tzinfo=<UTC>), 'tags_count': 1, 'price_avg': Decimal('234.000000'), 'price_sum': Decimal('234.00')},
{'tags__name': 'Mobile', 'date_created': datetime.datetime(2022, 11, 12, 3, 20, 3, tzinfo=<UTC>), 'tags_count': 1, 'price_avg': Decimal('234.000000'), 'price_sum': Decimal('234.00')},
{'tags__name': 'Device', 'date_created': datetime.datetime(2022, 12, 6, 16, 25, 6, 178045, tzinfo=<UTC>), 'tags_count': 1, 'price_avg': Decimal('100.000000'), 'price_sum': Decimal('100.00')},
{'tags__name': 'Mobile', 'date_created': datetime.datetime(2022, 12, 6, 16, 25, 6, 178045, tzinfo=<UTC>), 'tags_count': 1, 'price_avg': Decimal('100.000000'), 'price_sum': Decimal('100.00')}

I want result like this

{'date_created': datetime.datetime(2022, 11, 12, 3, 20, 3, tzinfo=<UTC>), 'Device': 1, 'Mobile': 1, 'price_avg': Decimal('100.000000'), 'price_sum': Decimal('100.00')}
{'date_created': datetime.datetime(2022, 12, 6, 16, 25, 6, 178045, tzinfo=<UTC>), 'Device': 1, 'Mobile': 1, 'price_avg': Decimal('100.000000'), 'price_sum': Decimal('100.00')}

Is there any way that I can achieve this data format.
Any help will be appreciated.


问:
Querying Data from MySQL via PHP
Good afternoon.  I'm teaching myself SQL and PHP, and have run into a roadblock.  I imagine it's quite simple but of course I can't figure it out.
I have a server running Apache2, MySQL, and PHP8.1.  I need to host a local webpage that lists DB table information using the PDO method.  I've written the HTML and PHP, but when running the PHP script within the HTML page, I get a blank space, and if I run the PHP script on its own, I get a 500 error.  After looking at Apache logs, I've found that it's a 500 185 error, which I have learned is essentially a "too much to handle" error (but it's not).
Here's my code:

```<code>
  $servername = "[local IP:port]";
  $username = "[sql username]";
  $password = "[sql password]";
  $databasename = "labeling";

  // CREATE CONNECTION
  $conn = mysqli_connect($servername,
    $username, $password, $databasename);

  // GET CONNECTION ERRORS
  if (!$conn) {
      die("Connection failed: " . mysqli_connect_error());
  }

  // SQL QUERY
  $query = "SELECT partnum, partdesc, colorant, material, quantity, monum, boxnum FROM `press01`";

  try
  {
      $conn = new PDO(
        "mysql:host=$servername;dbname=$databasename",
        $username, $password);

      $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      $stmt = $conn->prepare($query);
      // EXECUTING THE QUERY
      $stmt->execute();

      $r = $stmt->setFetchMode(PDO::FETCH_ASSOC);
      // FETCHING DATA FROM DATABASE
      $result = $stmt->fetchAll();
      // OUTPUT DATA OF EACH ROW
      foreach ($result as $row)
      {
          echo "Part #: " . $row["partnum"]. "Part Description: " .
            $row["partdesc"]. "Color: " . $row["colorant"]. "Material: " .
            $row["material"]. "Box Quantity: " . $row["quantity"]. "MO#: " . $row ["monum"].
            "Box #: " . $row["boxnum"]. "<br>";
      }
  } catch(PDOException $e) {
      echo "Error: " . $e->getMessage();
  }

$conn->close();

?>
</code>```

I expect to be given a list with the aforementioned values.  What am I doing wrong?  Forgive me, I'm still green with PHP.

After enabling error reporting, I'm met with the following:

```<code>Fatal error: Uncaught Error: Call to undefined method PDO::close() in /var/www/html/press01.php:55 Stack trace: #0 {main} thrown in /var/www/html/press01.php on line 55
</code>```

Title: Querying Data from MySQL via PHP

Body:
Good afternoon.  I'm teaching myself SQL and PHP, and have run into a roadblock.  I imagine it's quite simple but of course I can't figure it out.
I have a server running Apache2, MySQL, and PHP8.1.  I need to host a local webpage that lists DB table information using the PDO method.  I've written the HTML and PHP, but when running the PHP script within the HTML page, I get a blank space, and if I run the PHP script on its own, I get a 500 error.  After looking at Apache logs, I've found that it's a 500 185 error, which I have learned is essentially a "too much to handle" error (but it's not).
Here's my code:

  $servername = "[local IP:port]";
  $username = "[sql username]";
  $password = "[sql password]";
  $databasename = "labeling";

  // CREATE CONNECTION
  $conn = mysqli_connect($servername,
    $username, $password, $databasename);

  // GET CONNECTION ERRORS
  if (!$conn) {
      die("Connection failed: " . mysqli_connect_error());
  }

  // SQL QUERY
  $query = "SELECT partnum, partdesc, colorant, material, quantity, monum, boxnum FROM `press01`";

  try
  {
      $conn = new PDO(
        "mysql:host=$servername;dbname=$databasename",
        $username, $password);

      $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      $stmt = $conn->prepare($query);
      // EXECUTING THE QUERY
      $stmt->execute();

      $r = $stmt->setFetchMode(PDO::FETCH_ASSOC);
      // FETCHING DATA FROM DATABASE
      $result = $stmt->fetchAll();
      // OUTPUT DATA OF EACH ROW
      foreach ($result as $row)
      {
          echo "Part #: " . $row["partnum"]. "Part Description: " .
            $row["partdesc"]. "Color: " . $row["colorant"]. "Material: " .
            $row["material"]. "Box Quantity: " . $row["quantity"]. "MO#: " . $row ["monum"].
            "Box #: " . $row["boxnum"]. "
";
      }
  } catch(PDOException $e) {
      echo "Error: " . $e->getMessage();
  }

$conn->close();

?>

I expect to be given a list with the aforementioned values.  What am I doing wrong?  Forgive me, I'm still green with PHP.

After enabling error reporting, I'm met with the following:

Fatal error: Uncaught Error: Call to undefined method PDO::close() in /var/www/html/press01.php:55 Stack trace: #0 {main} thrown in /var/www/html/press01.php on line 55


问:
Perform repeating check in spring controller
I am building a website that works with a "Ticket" entity. This entity has an id and various operations are performed on the ticket based on the given ID. I have to handle the cases where this id leads to a non-existing ticket, and so I just take the ID at the start of pretty much every controller method and check if I find this object in the repository.

This seems very repeating and not like good style to me and I was wondering if there was any more elegant way to do this. This is how my controller looks at the present time:

public class TicketController {
    //Services and repositories are initialized on top

    @PostMapping("/ticket/reassign/{id}")
    public String reassign(@PathVariable int id, TicketReassignForm reassignForm) {
        Optional<Ticket> ticket = ticketRepository.findById(id);
        if (!ticket.isPresent()) {
            eventMessageService.addMessage(EventMessageBag.Type.ERROR, "Ticket wurde nicht gefunden", "Das gewünschte Ticket wurde nicht gefunden.");
            return "redirect:/ticket";
        } //these lines are present at the start of almost all methods in the controller
        //method does stuff with the ticket...
    }

    @PostMapping("/ticket/removelabel/{ticketId}/{labelId}")
    public String removeLabel(@PathVariable int ticketId, @PathVariable int labelId) {
        Optional<Ticket> ticket = ticketRepository.findById(ticketId);
        if (!ticket.isPresent()) {
            eventMessageService.addMessage(EventMessageBag.Type.ERROR, "Ticket wurde nicht gefunden", "Das gewünschte Ticket wurde nicht gefunden.");
            return "redirect:/ticket";
        } //Again, code lines are repeated...
        //Method does stuff...
    }

}
```

I wish to put these lines in a separate method or so, repeating this check in the current manner does not seem optimal to me. How can I improve this?

Body:
I am building a website that works with a "Ticket" entity. This entity has an id and various operations are performed on the ticket based on the given ID. I have to handle the cases where this id leads to a non-existing ticket, and so I just take the ID at the start of pretty much every controller method and check if I find this object in the repository.

This seems very repeating and not like good style to me and I was wondering if there was any more elegant way to do this. This is how my controller looks at the present time:

public class TicketController {
    //Services and repositories are initialized on top

    @PostMapping("/ticket/reassign/{id}")
    public String reassign(@PathVariable int id, TicketReassignForm reassignForm) {
        Optional<Ticket> ticket = ticketRepository.findById(id);
        if (!ticket.isPresent()) {
            eventMessageService.addMessage(EventMessageBag.Type.ERROR, "Ticket wurde nicht gefunden", "Das gewünschte Ticket wurde nicht gefunden.");
            return "redirect:/ticket";
        } //these lines are present at the start of almost all methods in the controller
        //method does stuff with the ticket...
    }

    @PostMapping("/ticket/removelabel/{ticketId}/{labelId}")
    public String removeLabel(@PathVariable int ticketId, @PathVariable int labelId) {
        Optional<Ticket> ticket = ticketRepository.findById(ticketId);
        if (!ticket.isPresent()) {
            eventMessageService.addMessage(EventMessageBag.Type.ERROR, "Ticket wurde nicht gefunden", "Das gewünschte Ticket wurde nicht gefunden.");
            return "redirect:/ticket";
        } //Again, code lines are repeated...
        //Method does stuff...
    }

}

I wish to put these lines in a separate method or so, repeating this check in the current manner does not seem optimal to me. How can I improve this?


问:
generate an automatic sales code for a Snack, this is for a school project
I use Java, this is for a school project

I looked for how to solve the problem on YouTube, but none helped me since I did not understand the procedures very well and what things I had to create.


问:
Perfect forward to an intermediate reference object before forwarding to an expensive constructor
I have a function foo that receives a forwarding/universal reference and I would like to hold that reference in a short-lived object, key, which I then pass to a third-party library that will evaluate whether or not it is necessary to construct a heavier object, heavy, and then perfectly forward the held reference from within key to heavy.

Assume this library has a function emplace that knows to construct heavy in place from key.

E.g., something like:

// template <class T> ??
struct key {
    key(auto&& arg) : _ref(???), _v(proccess(arg)) {}

    ?? _ref{};
    int _v{};   // used by third-party library to evaluate whether to construct `heavy`
};

struct heavy {
    heavy(key&& k) :
      _expensive( ??? (k._ref) ),  // should be equivalent to as if `key` was never created
                                   // and instead we called:
                                   //    Expensive(std::forward<decltype(arg)>(arg))
                                   // Assuming Expensive has a forwarding ref overload
      _v(k._v) {}

    Expensive _expensive{};
    int _v{};
};

void foo(auto&& arg) {
    container<heavy> c;

    c.emplace(key{std::forward<decltype(arg)>(arg)}); // may or may not actually decide
                                                      // to create `heavy`
}
```

I'm a little stumped on if this is at all possible...

Edit: the only things I cannot change are the implementation of container and Expensive in the above example. key does not necessarily have to be done in the way shown but I need to be able to pass the int _v along with _ref to container

Body:
I have a function foo that receives a forwarding/universal reference and I would like to hold that reference in a short-lived object, key, which I then pass to a third-party library that will evaluate whether or not it is necessary to construct a heavier object, heavy, and then perfectly forward the held reference from within key to heavy.

Assume this library has a function emplace that knows to construct heavy in place from key.

E.g., something like:

// template <class T> ??
struct key {
    key(auto&& arg) : _ref(???), _v(proccess(arg)) {}

    ?? _ref{};
    int _v{};   // used by third-party library to evaluate whether to construct `heavy`
};

struct heavy {
    heavy(key&& k) :
      _expensive( ??? (k._ref) ),  // should be equivalent to as if `key` was never created
                                   // and instead we called:
                                   //    Expensive(std::forward<decltype(arg)>(arg))
                                   // Assuming Expensive has a forwarding ref overload
      _v(k._v) {}

    Expensive _expensive{};
    int _v{};
};

void foo(auto&& arg) {
    container<heavy> c;

    c.emplace(key{std::forward<decltype(arg)>(arg)}); // may or may not actually decide
                                                      // to create `heavy`
}

I'm a little stumped on if this is at all possible...

Edit: the only things I cannot change are the implementation of container and Expensive in the above example. key does not necessarily have to be done in the way shown but I need to be able to pass the int _v along with _ref to container


问:
how to get/export pods without pod-template-hash in kubernetes
I am trying to export pods without pod-template-hash. However, couldn't find a way to do so
I have tried:

```<code>kubectl get pods -o custom-columns=":metadata.name" > test.json
</code>```

The above command exports the pod name with pod-template-hash. For example: "mariadb-8XCV5GHI", I just want the export to list the pod name as "mariadb"

Body:
I am trying to export pods without pod-template-hash. However, couldn't find a way to do so
I have tried:

kubectl get pods -o custom-columns=":metadata.name" > test.json

The above command exports the pod name with pod-template-hash. For example: "mariadb-8XCV5GHI", I just want the export to list the pod name as "mariadb"


问:
reference lambda layer locally
So I am trying to add a lambda layer to my lambda.  I have added the arn to my function in the serverless, but referencing a layer locally seems to be a problem (it is never found).  I have been googling, and it seems like everyone who want to reference a layer locally makes a copy of it in their lambda.

Am I correct on this?  Is there no simple way to reference a lambda locally directly from AWS?

Thanks

Title: reference lambda layer locally


问:
Why is this error occurring when I use writerow?
Why am I getting this error when I try to use writerow

db.writerow(loanList[i])
TypeError: writerows() argument must be iterable

'''

```<code>import csv

header = ['Name','Results']
file = open("loanResults.csv", "w", newline = "")

a = 10000
b = [0.032,0.043,0.037,0.043,0.044,0.029,0.028,0.030]
c = [6,7,4,3,4,6,7,9,]

loanList = []

def monthlyRepayment(principalAmount,interest,year):
    for i in range(len(b)):
        finalAmount = principalAmount * ((1 + interest[i]) **year[i])
        monthlyAmount = (finalAmount / (year[i]*12))
        loanList.append(round(monthlyAmount))
        print(round(monthlyAmount))

testCase1 = monthlyRepayment(a,b,c)

db = csv.writer(file)
db.writerow(header)

for i in range(len(loanList)):
    db.writerows(loanList[i])

file.close()
</code>```

'''

Body:
Why am I getting this error when I try to use writerow

db.writerow(loanList[i])
TypeError: writerows() argument must be iterable

'''

import csv

header = ['Name','Results']
file = open("loanResults.csv", "w", newline = "")

a = 10000
b = [0.032,0.043,0.037,0.043,0.044,0.029,0.028,0.030]
c = [6,7,4,3,4,6,7,9,]

loanList = []

def monthlyRepayment(principalAmount,interest,year):
    for i in range(len(b)):
        finalAmount = principalAmount * ((1 + interest[i]) **year[i])
        monthlyAmount = (finalAmount / (year[i]*12))
        loanList.append(round(monthlyAmount))
        print(round(monthlyAmount))

testCase1 = monthlyRepayment(a,b,c)

db = csv.writer(file)
db.writerow(header)

for i in range(len(loanList)):
    db.writerows(loanList[i])

file.close()

'''


问:
Routes not found in angular routing with multiple child modules
I have a module tree in my Angular project, with each module incorporating its own routing.
I have a parent module and a number of child modules.
Parent module routing works but none of the child routes work: Error: NG04002: Cannot match any routes.

Here is my parent module :

```<code>import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { FrameworkComponent } from './framework/framework.component';
import { AboutComponent } from './about/about.component';
import { HomeListComponent } from './home-list/home-list.component';
import { HomepageComponent } from './homepage/homepage.component';
import { RayonsModule } from './rayons/rayons.module';
import { SharedModule } from './shared/shared.module';
import { NotFoundComponent } from './not-found/not-found.component';

@NgModule({
  declarations: [
    AppComponent,
    FrameworkComponent,
    AboutComponent,
    HomeListComponent,
    HomepageComponent,
    NotFoundComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    PlanningModule,
    RayonsModule,
    SharedModule,
  ],
  providers: [],
  bootstrap: [FrameworkComponent],
})
export class AppModule {}
</code>```

and here is his routing module :

```<code>import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AboutComponent } from './about/about.component';
import { HomeListComponent } from './home-list/home-list.component';
import { ListesHomeComponent } from './listes/listes-home/listes-home.component';
import { NotFoundComponent } from './not-found/not-found.component';

const routes: Routes = [
  { path: 'about', component: AboutComponent },
  { path: 'listes', component: ListesHomeComponent },
  { path: '', component: HomeListComponent },
  { path: '**', component: NotFoundComponent },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
})
export class AppRoutingModule {}
</code>```

So far everything is working fine
I then have child modules that look like this

```<code>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SharedModule } from 'src/app/shared/shared.module';
import { PlanningHomeComponent } from './planning-home/planning-home.component';
import { PlanningRoutingModule } from './planning-routing.module';

@NgModule({
  declarations: [PlanningHomeComponent],
  imports: [CommonModule, SharedModule, PlanningRoutingModule],
})
export class PlanningModule {}
</code>```

and the routing module :

```<code>import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { PlanningHomeComponent } from './planning-home/planning-home.component';

const routes: Routes = [{ path: 'planning', component: PlanningHomeComponent }];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule],
})
export class PlanningRoutingModule {}
</code>```

And my links are like this :

```<code>  <a
    routerLink="planning"
    routerLinkActive="active"
    class="nav-link"
    aria-current="page"
    >Planning</a
  >
</code>```

I don't understand why it can't find the child routes. Thank you in advance for your precious help.

Body:
I have a module tree in my Angular project, with each module incorporating its own routing.
I have a parent module and a number of child modules.
Parent module routing works but none of the child routes work: Error: NG04002: Cannot match any routes.

Here is my parent module :

import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { FrameworkComponent } from './framework/framework.component';
import { AboutComponent } from './about/about.component';
import { HomeListComponent } from './home-list/home-list.component';
import { HomepageComponent } from './homepage/homepage.component';
import { RayonsModule } from './rayons/rayons.module';
import { SharedModule } from './shared/shared.module';
import { NotFoundComponent } from './not-found/not-found.component';

@NgModule({
  declarations: [
    AppComponent,
    FrameworkComponent,
    AboutComponent,
    HomeListComponent,
    HomepageComponent,
    NotFoundComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    PlanningModule,
    RayonsModule,
    SharedModule,
  ],
  providers: [],
  bootstrap: [FrameworkComponent],
})
export class AppModule {}

and here is his routing module :

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AboutComponent } from './about/about.component';
import { HomeListComponent } from './home-list/home-list.component';
import { ListesHomeComponent } from './listes/listes-home/listes-home.component';
import { NotFoundComponent } from './not-found/not-found.component';

const routes: Routes = [
  { path: 'about', component: AboutComponent },
  { path: 'listes', component: ListesHomeComponent },
  { path: '', component: HomeListComponent },
  { path: '**', component: NotFoundComponent },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
})
export class AppRoutingModule {}

So far everything is working fine
I then have child modules that look like this

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SharedModule } from 'src/app/shared/shared.module';
import { PlanningHomeComponent } from './planning-home/planning-home.component';
import { PlanningRoutingModule } from './planning-routing.module';

@NgModule({
  declarations: [PlanningHomeComponent],
  imports: [CommonModule, SharedModule, PlanningRoutingModule],
})
export class PlanningModule {}

and the routing module :

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { PlanningHomeComponent } from './planning-home/planning-home.component';

const routes: Routes = [{ path: 'planning', component: PlanningHomeComponent }];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule],
})
export class PlanningRoutingModule {}

And my links are like this :

  Planning

I don't understand why it can't find the child routes. Thank you in advance for your precious help.


问:
Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment] using JPA with Hibernate and MariaDB
I have a project that is supposed to connect to a database using JPA and Hibernate as connection provider.

The MySQL server is running in a Docker container - image: mysql:latest - with port mapping: 127.0.0.1:3306:3306. I can connect to the server via command line (with mysql -h0.0.0.0... command, not docker exec mysql-server mysql...).

I'm using javax persistence annotations for my entity classes. This is my project structure:
project structure
Entity classes are defined in students package, whereas the DAO objects that are responsible for connecting to the database in the model package.

persistence.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
             http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
             version="2.1">

    <persistence-unit name="Students">
        <description>Persistence unit for the Students database</description>

        <class>main.java.students.Student</class>
        <class>main.java.students.Class</class>
        <class>main.java.students.ClassContainer</class>

        <properties>
            <!-- MySQL Configuration -->
            <property name="javax.persistence.jdbc.driver" value="org.mariadb.jdbc.Driver" />
            <property name="javax.persistence.jdbc.url" value="jdbc:mariadb://0.0.0.0/students_db" />
            <property name="javax.persistence.jdbc.username" value="root" />
            <property name="javax.persistence.jdbc.password" value="my-secret-pw" />

            <!-- Hibernate Configuration -->
            <property name="javax.persistence.provider" value="org.hibernate.jpa.HibernatePersistenceProvider"/>
            <property name="hibernate.dialect" value="org.hibernate.dialect.MariaDBDialect" />
            <property name="hibernate.show_sql" value="true" />
            <property name="hibernate.format_sql" value="true" />

            <!-- Schema Generation -->
            <property name = "javax.persistence.schema-generation.create-database-schemas" value="true"/>
            <property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
<!--            <property name="hibernate.hbm2ddl.auto" value="create" />-->

            <!-- Scanning -->
            <property name="hibernate.scan.packages" value="main.java.students,main.java.model" />

        </properties>
    </persistence-unit>

</persistence>
</code>```

This is my dependencies section from pom.xml :

```<code><dependencies>

<!-- Irrelevant dependencies were ommited -->

<dependency>
    <groupId>org.hibernate.orm</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>6.1.6.Final</version>
  </dependency>

  <dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-search-orm</artifactId>
    <version>5.11.11.Final</version>
  </dependency>

  <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.30</version>
  </dependency>

  <!-- https://mvnrepository.com/artifact/org.mariadb.jdbc/mariadb-java-client -->
  <dependency>
    <groupId>org.mariadb.jdbc</groupId>
    <artifactId>mariadb-java-client</artifactId>
    <version>3.1.0</version>
  </dependency>

</dependencies>
</code>```

Every time I run the project I get the error:
Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]

This is the stacktrace:

```<code>[org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:271),
org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:233),
org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210),
org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:51),
org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94),
org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:242),
org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210),
org.hibernate.boot.model.process.spi.MetadataBuildingProcess.handleTypes(MetadataBuildingProcess.java:352),
org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:111),
org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:858),
org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:885),
org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:58),
javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:55),
javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39),
model.StudentDAO.setUp(StudentDAO.java:40), model.StudentDAO.<init>(StudentDAO.java:26),
students.Class.<init>(Class.java:31), students.App.main(App.java:19)]

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "javax.persistence.EntityManager.getTransaction()" because "this.entityManager" is null
    at model.StudentDAO.executeInsideTransaction(StudentDAO.java:78)
    at model.StudentDAO.save(StudentDAO.java:64)
    at students.Class.addStudent(Class.java:58)
    at students.App.main(App.java:24)
</code>```

Body:
I have a project that is supposed to connect to a database using JPA and Hibernate as connection provider.

The MySQL server is running in a Docker container - image: mysql:latest - with port mapping: 127.0.0.1:3306:3306. I can connect to the server via command line (with mysql -h0.0.0.0... command, not docker exec mysql-server mysql...).

I'm using javax persistence annotations for my entity classes. This is my project structure:
project structure
Entity classes are defined in students package, whereas the DAO objects that are responsible for connecting to the database in the model package.

persistence.xml:

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
             http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
             version="2.1">

    <persistence-unit name="Students">
        <description>Persistence unit for the Students database</description>

        <class>main.java.students.Student</class>
        <class>main.java.students.Class</class>
        <class>main.java.students.ClassContainer</class>

        <properties>

            <property name="javax.persistence.jdbc.driver" value="org.mariadb.jdbc.Driver" />
            <property name="javax.persistence.jdbc.url" value="jdbc:mariadb://0.0.0.0/students_db" />
            <property name="javax.persistence.jdbc.username" value="root" />
            <property name="javax.persistence.jdbc.password" value="my-secret-pw" />

            <property name="javax.persistence.provider" value="org.hibernate.jpa.HibernatePersistenceProvider"/>
            <property name="hibernate.dialect" value="org.hibernate.dialect.MariaDBDialect" />
            <property name="hibernate.show_sql" value="true" />
            <property name="hibernate.format_sql" value="true" />

            <property name = "javax.persistence.schema-generation.create-database-schemas" value="true"/>
            <property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>

            <property name="hibernate.scan.packages" value="main.java.students,main.java.model" />

        </properties>
    </persistence-unit>

</persistence>

This is my dependencies section from pom.xml :

<dependencies>

<dependency>
    <groupId>org.hibernate.orm</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>6.1.6.Final</version>
  </dependency>

  <dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-search-orm</artifactId>
    <version>5.11.11.Final</version>
  </dependency>

  <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.30</version>
  </dependency>

  <dependency>
    <groupId>org.mariadb.jdbc</groupId>
    <artifactId>mariadb-java-client</artifactId>
    <version>3.1.0</version>
  </dependency>

</dependencies>

Every time I run the project I get the error:
Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]

This is the stacktrace:

[org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:271),
org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:233),
org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210),
org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:51),
org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94),
org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:242),
org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210),
org.hibernate.boot.model.process.spi.MetadataBuildingProcess.handleTypes(MetadataBuildingProcess.java:352),
org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:111),
org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:858),
org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:885),
org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:58),
javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:55),
javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39),
model.StudentDAO.setUp(StudentDAO.java:40), model.StudentDAO.<init>(StudentDAO.java:26),
students.Class.<init>(Class.java:31), students.App.main(App.java:19)]

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "javax.persistence.EntityManager.getTransaction()" because "this.entityManager" is null
    at model.StudentDAO.executeInsideTransaction(StudentDAO.java:78)
    at model.StudentDAO.save(StudentDAO.java:64)
    at students.Class.addStudent(Class.java:58)
    at students.App.main(App.java:24)