问:
Send Email with PHPMailer and cPanel email Account
```<code>    I am Using PHPmailer to send mails and using cpanel email account as username and password just like code below but the mail is not sending when i load the page it just rotating and showing the error. the domain using micrsoft 365 business email for send internal mails.

     $mail->Host = 'mail.yourdomain.com';
    $mail->SMTPAuth = true;
    $mail->Username = 'user@yourdomain.com'; // Your email address
    $mail->Password = 'password'; //email box password
    $mail->SMTPSecure = 'tls';
    $mail->Port = 587;
</code>```

I tried the mail function instead of PHPmailer then it's working but I need to attach files with specific sizes so I don't want to use it

mail("user@gmail.com", $phone, $name, $email)

and  I tried PHPmailer with SMTP (Gmail) username and password like the below code but the mail is going to spam.

```<code> $mail->Host = 'smtp.gmail.com';
        $mail->Port = 587;
        $mail->SMTPAuth=true;
        $mail->SMTPSecure='tls';

</code>```

So

Please help me to resolve mail going to spam.

If the domain uses business email like Microsoft email then how can we send emails from Cpanel?
3. If I am using the mail function how can I attach a file with it (with a specific size and format)

```<code></code>```

Body:
    I am Using PHPmailer to send mails and using cpanel email account as username and password just like code below but the mail is not sending when i load the page it just rotating and showing the error. the domain using micrsoft 365 business email for send internal mails.

     $mail->Host = 'mail.yourdomain.com';
    $mail->SMTPAuth = true;
    $mail->Username = 'user@yourdomain.com'; // Your email address
    $mail->Password = 'password'; //email box password
    $mail->SMTPSecure = 'tls';
    $mail->Port = 587;

I tried the mail function instead of PHPmailer then it's working but I need to attach files with specific sizes so I don't want to use it

mail("user@gmail.com", $phone, $name, $email)

and  I tried PHPmailer with SMTP (Gmail) username and password like the below code but the mail is going to spam.

 $mail->Host = 'smtp.gmail.com';
        $mail->Port = 587;
        $mail->SMTPAuth=true;
        $mail->SMTPSecure='tls';

So

Please help me to resolve mail going to spam.

If the domain uses business email like Microsoft email then how can we send emails from Cpanel?
3. If I am using the mail function how can I attach a file with it (with a specific size and format)


来源: stackexchange

问:
pandas_datareader reader giving error on getting financial data
This code should return me bitcoin market data between the two dates. However it is give an error.

TypeError: string indices must be integers

can anyone spot what I am doing wrong here?

```<code>
import datetime
import pandas_datareader as pdr

# Get the current date and time
now = datetime.datetime.now()
df = pdr.get_data_yahoo("BTC-USD", start="2020-01-01", end="2021-01-01")
print(df.head())
</code>```

ContentLicense: CC BY-SA 4.0

Body:
This code should return me bitcoin market data between the two dates. However it is give an error.

TypeError: string indices must be integers

can anyone spot what I am doing wrong here?

import datetime
import pandas_datareader as pdr

# Get the current date and time
now = datetime.datetime.now()
df = pdr.get_data_yahoo("BTC-USD", start="2020-01-01", end="2021-01-01")
print(df.head())


问:
Create dataframe out of plot of feature rank importance
I have the following code which does elastic net to calculate feature importance.

```<code>dataset_path_austin = os.path.join('../datasets/austin_housing/')
file_name_austin = 'processed_austin_housing_onehot.csv'
df_austin = pd.read_csv(dataset_path_austin + file_name_austin)

X_austin = df_austin.drop(['latestPrice'], axis = 1)
y_austin = df_austin['latestPrice']

from sklearn.linear_model import ElasticNetCV, ElasticNet

cv_model = ElasticNetCV(l1_ratio=[.1, .5, .7, .9, .95, .99, .995, 1], eps=0.001, n_alphas=100, fit_intercept=True,
                        precompute='auto', max_iter=2500, tol=0.0001, cv=5, copy_X=True, verbose=0, n_jobs=-1, positive=False,
                        random_state=42, selection='cyclic')

cv_model.fit(X_austin, y_austin)

model = ElasticNet(l1_ratio=cv_model.l1_ratio_, alpha = cv_model.alpha_, max_iter=cv_model.n_iter_, fit_intercept=True, random_state=42)
model.fit(X_austin, y_austin)

feature_importance = pd.Series(index = X_austin.columns, data = np.abs(model.coef_))

n_selected_features = (feature_importance>0).sum()
print('{0:d} features, reduction of {1:2.2f}%'.format(
    n_selected_features,(1-n_selected_features/len(feature_importance))*100))

feature_importance.sort_values().tail(30).plot(kind = 'bar', figsize = (20,12))
plt.xlabel('Features', fontsize = 15)
plt.ylabel('Rank Weight', fontsize = 15)
plt.title('Feature Weights for Austin Housing Dataset', fontsize = 20)
</code>```

Which outputs the following bar plot:

How can I create a dataframe out of the plot that has the 'Rank Weight' as one column and 'Features' as another. I have attempted using

```<code>feature_importance.sort_values()
</code>```

But I get a list with extremely high numbers per features (such as 2.334368e-01) instead.

Body:
I have the following code which does elastic net to calculate feature importance.

dataset_path_austin = os.path.join('../datasets/austin_housing/')
file_name_austin = 'processed_austin_housing_onehot.csv'
df_austin = pd.read_csv(dataset_path_austin + file_name_austin)

X_austin = df_austin.drop(['latestPrice'], axis = 1)
y_austin = df_austin['latestPrice']

from sklearn.linear_model import ElasticNetCV, ElasticNet

cv_model = ElasticNetCV(l1_ratio=[.1, .5, .7, .9, .95, .99, .995, 1], eps=0.001, n_alphas=100, fit_intercept=True,
                        precompute='auto', max_iter=2500, tol=0.0001, cv=5, copy_X=True, verbose=0, n_jobs=-1, positive=False,
                        random_state=42, selection='cyclic')

cv_model.fit(X_austin, y_austin)

model = ElasticNet(l1_ratio=cv_model.l1_ratio_, alpha = cv_model.alpha_, max_iter=cv_model.n_iter_, fit_intercept=True, random_state=42)
model.fit(X_austin, y_austin)

feature_importance = pd.Series(index = X_austin.columns, data = np.abs(model.coef_))

n_selected_features = (feature_importance>0).sum()
print('{0:d} features, reduction of {1:2.2f}%'.format(
    n_selected_features,(1-n_selected_features/len(feature_importance))*100))

feature_importance.sort_values().tail(30).plot(kind = 'bar', figsize = (20,12))
plt.xlabel('Features', fontsize = 15)
plt.ylabel('Rank Weight', fontsize = 15)
plt.title('Feature Weights for Austin Housing Dataset', fontsize = 20)

Which outputs the following bar plot:

How can I create a dataframe out of the plot that has the 'Rank Weight' as one column and 'Features' as another. I have attempted using

feature_importance.sort_values()

But I get a list with extremely high numbers per features (such as 2.334368e-01) instead.


问:
Is it possible to set data class as Request Body in Kotlin?
I want to post a data class object and some images with retrofit.
A data class can be used as a parameter in a post request.

```<code>    @POST("api/image/upload")
    fun postLocalData(@Body userData: UserData): Call<ResponseClass>
</code>```

However, when i have to add some images with my userData, i can't create a post function with both Body and Parts like postLocalData(@Body userData: UserData, @Part vararg images: MultipartBody.Part). So i changed the parameter to @Body postData: RequestBody. Then i created a function that combine my data class object with MultipartBody.Part images like below.

```<code>    private fun createImageBody(filePath: String): RequestBody {
        val file = File(filePath)
        return file.asRequestBody("multipart/form-data".toMediaTypeOrNull())
    }

    fun getRequestBody(userData: User, albumImages: List<Album>): RequestBody{
        val bodyBuilder = MultipartBody.Builder().setType(FORM).addPart(userData as RequestBody)
        for (image in albumImages){
            bodyBuilder.addFormDataPart(
                "image", image.filePath,
                createImageBody(image.filePath)
            )
        }
        return bodyBuilder.build()
    }
</code>```

However, type conversion of data class userData as RequestBody is not possible. Is there a reasonable way to go about this process? Or is my approach completely wrong?

Body:
I want to post a data class object and some images with retrofit.
A data class can be used as a parameter in a post request.

    @POST("api/image/upload")
    fun postLocalData(@Body userData: UserData): Call<ResponseClass>

However, when i have to add some images with my userData, i can't create a post function with both Body and Parts like postLocalData(@Body userData: UserData, @Part vararg images: MultipartBody.Part). So i changed the parameter to @Body postData: RequestBody. Then i created a function that combine my data class object with MultipartBody.Part images like below.

    private fun createImageBody(filePath: String): RequestBody {
        val file = File(filePath)
        return file.asRequestBody("multipart/form-data".toMediaTypeOrNull())
    }

    fun getRequestBody(userData: User, albumImages: List<Album>): RequestBody{
        val bodyBuilder = MultipartBody.Builder().setType(FORM).addPart(userData as RequestBody)
        for (image in albumImages){
            bodyBuilder.addFormDataPart(
                "image", image.filePath,
                createImageBody(image.filePath)
            )
        }
        return bodyBuilder.build()
    }

However, type conversion of data class userData as RequestBody is not possible. Is there a reasonable way to go about this process? Or is my approach completely wrong?


问:
error adding adb forward: reattach the device
I use Linux ubuntu and droidcam I have this error when turn on droidcam and try connect via usb wi

"error adding adb forward: reattach the device"

I try turn on and turn of development tools in my phone but still not workinkg

Any ideas?

Thanks.

I tried reinstall and detach my device but not work.


问:
Jenkins: invalid java version

Installed jenkins freshly gives this error.

Just expecting it run smoothly

Title: Jenkins: invalid java version


问:
Excel Fill Form based on Cell Value then Print
excel sheet

I have a tab that is named setup, in which there will be interviewer's and interviewee's names on this list. I was trying to figure out a way that I could input the quantity of each, then have each sheet printed out, filling out each others name.

For example, I have 3 interviewers, so I would input 3, then given name 1, given name 2 and given name 3 in 3 different cells. Then I have 3 interviewee's, so I again would input 3, then the three names. These would fill out on the interview tab, in 2 different cells.

Then I would have a button to press, that would print out each combination once.

Thank you!

Can't find a way as of yet.


问:
How to setup WebSphere JNDI Lookup without Datasource Credentials in Java
I am trying to use JNDI lookup to access a Datasource defined in WebSphere 9. The datasource is being accessed while the EAR file is being generated using maven. Initially it was using Basic DataSource however I want to remove the datasource credentials from the Java Code. The Datasource in WebSphere has authentication alias setup. Is there a way to do the lookup without specifying the username/password for the DataSource?

I was trying to use JNDI lookup as shown in the attached code however it was giving the error Null userid is not supported.

```<code>public DataSource getDataSource() throws NamingException
    {
        Properties properties = new Properties();
        properties.put(Context.INITIAL_CONTEXT_FACTORY, "com.ibm.websphere.naming.WsnInitialContextFactory");
        properties.put(Context.PROVIDER_URL, "iiop://myip:2809");
        Context initContext = new InitialContext(properties);
        return dataSource = (DataSource)initContext.lookup("jdbc/myDataSource");

    }
</code>```

Body:
I am trying to use JNDI lookup to access a Datasource defined in WebSphere 9. The datasource is being accessed while the EAR file is being generated using maven. Initially it was using Basic DataSource however I want to remove the datasource credentials from the Java Code. The Datasource in WebSphere has authentication alias setup. Is there a way to do the lookup without specifying the username/password for the DataSource?

I was trying to use JNDI lookup as shown in the attached code however it was giving the error Null userid is not supported.

public DataSource getDataSource() throws NamingException
    {
        Properties properties = new Properties();
        properties.put(Context.INITIAL_CONTEXT_FACTORY, "com.ibm.websphere.naming.WsnInitialContextFactory");
        properties.put(Context.PROVIDER_URL, "iiop://myip:2809");
        Context initContext = new InitialContext(properties);
        return dataSource = (DataSource)initContext.lookup("jdbc/myDataSource");

    }


问:
How to make my variable synchronized with a LocalStorage variable?
I'm developing light/dark mode to my fullstack application(.Net/blazor) which has many component;
I'm trying to store the different values of my Tags in localstorage that change with the selected mode(light/dark); there are tags in Blazor  that don't take class as parameter that's why I'm using LocalStorage to set its values.

I have Mainlayout component which is my main component where you can find the switch mode button and also I have a component which contains the tag that i want to change its background color using localstorage :

MainLayout component :

```<code>private async Task ChangeThemeAsync()   //changeMode function linked to my button
    {
        _themeName = await localStorage.GetItemAsync<string>("CurrentTheme");
        if (_themeName == "DarkTheme")
        {

            //_currentTheme = _lightTheme;
            _themeName = "LightTheme";
            await localStorage.SetItemAsync("CurrentTheme", "LightTheme");
            await localStorage.SetItemAsync("DiagramColor", "#e9eaed");
            await localStorage.SetItemAsync("LabelColor", "#000000");
            var module = await _jsRuntime.InvokeAsync<IJSObjectReference>("import", "./js/ThemeChanging.js");
            await module.InvokeVoidAsync("setTheme", _themeName);
            /*            await localStorage.SetItemAsync("CurrentTheme", _currentTheme);  */   //I added this line because i want to store a variable of type Mublazor in my localstorage
        }
        else
        {
            //_currentTheme = _darkTheme;
            _themeName = "DarkTheme";
            await localStorage.SetItemAsync("CurrentTheme", "DarkTheme");
            await localStorage.SetItemAsync("DiagramColor", "#1c1b20");
            await localStorage.SetItemAsync("LabelColor", "#FFFFFF");                      //we an clean the code that we can set the itm
            var module = await _jsRuntime.InvokeAsync<IJSObjectReference>("import", "./js/ThemeChanging.js");
            await module.InvokeVoidAsync("setTheme", _themeName);
            //await localStorage.SetItemAsync("CurrentTheme", _currentTheme);
        }

protected override async Task OnInitializedAsync()
    {
        _themeName = await localStorage.GetItemAsync<string>("CurrentTheme");

        if (_themeName.Equals("DarkTheme"))
        {
            var module = await _jsRuntime.InvokeAsync<IJSObjectReference>("import", "./js/ThemeChanging.js");
            await module.InvokeVoidAsync("setTheme", _themeName);
        }
        else
        {
            var module = await _jsRuntime.InvokeAsync<IJSObjectReference>("import", "./js/ThemeChanging.js");
            await module.InvokeVoidAsync("setTheme", _themeName);
        }
}
</code>```

the component that contains the tag that i want to change its value :

```<code>    <SfChart Background="@DiagramColor" Height="600" Title="Teilemenge pro Prozess" >
       </SfChart>

    @code{
        public string theme ="";
        public string DiagramColor= "";
        public string LabelColor="";

        public async Task load()
        {

    DiagramColor = await localStorage.GetItemAsync<string>("DiagramColor");
    LabelColor = await localStorage.GetItemAsync<string>("LabelColor");
        }
      protected override async Task OnInitializedAsync()
        {
            theme = await localStorage.GetItemAsync<string>("CurrentTheme");
            DiagramColor = await localStorage.GetItemAsync<string>("DiagramColor");
            LabelColor = await localStorage.GetItemAsync<string>("LabelColor");

    }

}
</code>```

All i need is to call the  Task load() in my Mainlayout while pressing on the button ;

I have tried to create an object of the component which contains the load() in Mainlayout component and call the load function throw the object but it shows an error : reference null ; in my case i can't add @ref to my child component because i'm using @body to call all the child component once, so i can't add reference to my @body to create an object,

Any suggestion please .?

Body:
I'm developing light/dark mode to my fullstack application(.Net/blazor) which has many component;
I'm trying to store the different values of my Tags in localstorage that change with the selected mode(light/dark); there are tags in Blazor  that don't take class as parameter that's why I'm using LocalStorage to set its values.

I have Mainlayout component which is my main component where you can find the switch mode button and also I have a component which contains the tag that i want to change its background color using localstorage :

MainLayout component :

private async Task ChangeThemeAsync()   //changeMode function linked to my button
    {
        _themeName = await localStorage.GetItemAsync<string>("CurrentTheme");
        if (_themeName == "DarkTheme")
        {

            //_currentTheme = _lightTheme;
            _themeName = "LightTheme";
            await localStorage.SetItemAsync("CurrentTheme", "LightTheme");
            await localStorage.SetItemAsync("DiagramColor", "#e9eaed");
            await localStorage.SetItemAsync("LabelColor", "#000000");
            var module = await _jsRuntime.InvokeAsync<IJSObjectReference>("import", "./js/ThemeChanging.js");
            await module.InvokeVoidAsync("setTheme", _themeName);
            /*            await localStorage.SetItemAsync("CurrentTheme", _currentTheme);  */   //I added this line because i want to store a variable of type Mublazor in my localstorage
        }
        else
        {
            //_currentTheme = _darkTheme;
            _themeName = "DarkTheme";
            await localStorage.SetItemAsync("CurrentTheme", "DarkTheme");
            await localStorage.SetItemAsync("DiagramColor", "#1c1b20");
            await localStorage.SetItemAsync("LabelColor", "#FFFFFF");                      //we an clean the code that we can set the itm
            var module = await _jsRuntime.InvokeAsync<IJSObjectReference>("import", "./js/ThemeChanging.js");
            await module.InvokeVoidAsync("setTheme", _themeName);
            //await localStorage.SetItemAsync("CurrentTheme", _currentTheme);
        }

protected override async Task OnInitializedAsync()
    {
        _themeName = await localStorage.GetItemAsync<string>("CurrentTheme");

        if (_themeName.Equals("DarkTheme"))
        {
            var module = await _jsRuntime.InvokeAsync<IJSObjectReference>("import", "./js/ThemeChanging.js");
            await module.InvokeVoidAsync("setTheme", _themeName);
        }
        else
        {
            var module = await _jsRuntime.InvokeAsync<IJSObjectReference>("import", "./js/ThemeChanging.js");
            await module.InvokeVoidAsync("setTheme", _themeName);
        }
}

the component that contains the tag that i want to change its value :

    <SfChart Background="@DiagramColor" Height="600" Title="Teilemenge pro Prozess" >
       </SfChart>

    @code{
        public string theme ="";
        public string DiagramColor= "";
        public string LabelColor="";

        public async Task load()
        {

    DiagramColor = await localStorage.GetItemAsync<string>("DiagramColor");
    LabelColor = await localStorage.GetItemAsync<string>("LabelColor");
        }
      protected override async Task OnInitializedAsync()
        {
            theme = await localStorage.GetItemAsync<string>("CurrentTheme");
            DiagramColor = await localStorage.GetItemAsync<string>("DiagramColor");
            LabelColor = await localStorage.GetItemAsync<string>("LabelColor");

    }

}

All i need is to call the  Task load() in my Mainlayout while pressing on the button ;

I have tried to create an object of the component which contains the load() in Mainlayout component and call the load function throw the object but it shows an error : reference null ; in my case i can't add @ref to my child component because i'm using @body to call all the child component once, so i can't add reference to my @body to create an object,

Any suggestion please .?


问:
Plot mixed model fixed coefficients results
```<code>library(reshape2)
library(lme4)
set.seed(123)

# Generate a vector of 1000 participant IDs
subnum <- 1:1000

# Generate a vector of random ages for each participant
age <- round(rnorm(1000, mean=30, sd=5))

# Generate a matrix of random scores for each participant
scores <- matrix(rnorm(4000, mean=50, sd=10), nrow=1000, ncol=4)

# Generate two additional continuous variables
cont1 <- rnorm(1000, mean=0, sd=1)
cont2 <- rnorm(1000, mean=0, sd=1)

# Generate two additional dichotomous variables
dich1 <- rbinom(1000, size=1, prob=0.5)
dich2 <- rbinom(1000, size=1, prob=0.5)

# Combine the data into a single data frame
df <- cbind(subnum, age, scores, cont1, cont2, dich1, dich2)
df=as.data.frame(df)

df_long <- melt(df, id.vars=c("subnum", "age", "cont1", "cont2", "dich1", "dich2"), variable.name="followup", value.name="score")
df_long$followup = as.factor(df_long$followup)

mm=lmer(score~age+cont1+cont2+dich1+dich2+(1+subnum|followup),data=df_long)
sjPlot:: tab_model(mm)
</code>```

Here is a reproducible example similar to my data, I am trying to plot the mixed model fixed effects without intercept or random effect, only fixed effects with their estimate and pv / confidence interval.
thanks.

Body:
library(reshape2)
library(lme4)
set.seed(123)

# Generate a vector of 1000 participant IDs
subnum <- 1:1000

# Generate a vector of random ages for each participant
age <- round(rnorm(1000, mean=30, sd=5))

# Generate a matrix of random scores for each participant
scores <- matrix(rnorm(4000, mean=50, sd=10), nrow=1000, ncol=4)

# Generate two additional continuous variables
cont1 <- rnorm(1000, mean=0, sd=1)
cont2 <- rnorm(1000, mean=0, sd=1)

# Generate two additional dichotomous variables
dich1 <- rbinom(1000, size=1, prob=0.5)
dich2 <- rbinom(1000, size=1, prob=0.5)

# Combine the data into a single data frame
df <- cbind(subnum, age, scores, cont1, cont2, dich1, dich2)
df=as.data.frame(df)

df_long <- melt(df, id.vars=c("subnum", "age", "cont1", "cont2", "dich1", "dich2"), variable.name="followup", value.name="score")
df_long$followup = as.factor(df_long$followup)

mm=lmer(score~age+cont1+cont2+dich1+dich2+(1+subnum|followup),data=df_long)
sjPlot:: tab_model(mm)

Here is a reproducible example similar to my data, I am trying to plot the mixed model fixed effects without intercept or random effect, only fixed effects with their estimate and pv / confidence interval.
thanks.


问:
Send Mail with AppleScript without showing anything onto the screen
how is it possible to send an email with apple mail into osx based onto an AppleScript without showing anything onto the screen.

Based on a rule, an AppleScript is executed in another application that automatically sends several e-mails.

Something is briefly displayed on the screen for about half a second for each email that is sent. I assume that this is the email that is being sent. As a result, it flickers on the screen several times for every 10 emails.

Thanks for help.


问:
visual stdio take so much time to load or compile
hi I'm junior developer and I work for company that doesnt have SSD on thier servers ♂♂ but my workstation have 100G ram , I think the problem is from HHD , is there ant way to cash my solution in to ram so that visual stdio load and build faster, it take 30 secend to just compile hello world in C# , now Im working in vsto extension it take 2 minutes to load
and no they dont just buy me a ssd
help please
thanks in advance

I tried to clear %temp% file and prefetch files but non of them helped


问:
Zooming in/out relative to the position of the mouse
Below is a minimal reproducible code example in which you can zoom in and out with the scroll wheel and the size of the panel is auto adjusted.

```<code>package testpane;
import java.awt.event.MouseAdapter;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.WindowConstants;

public class TestPane
{
    public static Drawing d;
    public static double zoomFactor = 1;

    public static void main(String[] args)
    {
        JFrame f = new JFrame("Tree Diagram");
        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        f.getContentPane().add(new TestPane().makeDiagram());
        f.setSize(1600, 800);
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public JComponent makeDiagram()
    {
        d = new Drawing();

        MouseAdapter mouseAdapter = new TestPaneMouseListener();
        d.addMouseListener(mouseAdapter);
        d.addMouseMotionListener(mouseAdapter);
        d.addMouseWheelListener(mouseAdapter);

        return new JScrollPane(d);
    }
}
</code>```
```<code>package testpane;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.MouseInfo;
import java.awt.Rectangle;
import java.awt.geom.AffineTransform;
import javax.swing.JPanel;
import static testpane.TestPane.zoomFactor;

public class Drawing extends JPanel
{
    private final AffineTransform zoomTransform = new AffineTransform();
    private final Rectangle rect = new Rectangle(1600, 800);
    private double xOffset = 0;
    private double yOffset = 0;
    private double prevZoomFactor = 1;

    public Drawing()
    {
        Font currentFont = getFont();
        Font newFont = currentFont.deriveFont(currentFont.getSize() * 25F);
        setFont(newFont);
        setBackground(Color.WHITE);
    }

    public void setZoomFactor(double zoomFactor)
    {
        zoomTransform.scale(zoomFactor, zoomFactor);
        revalidate();
        repaint();
    }

    @Override
    protected void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g.create();
        AffineTransform scrollTransform = g2d.getTransform();

        double xRel = MouseInfo.getPointerInfo().getLocation().getX() - getLocationOnScreen().getX();
        double yRel = MouseInfo.getPointerInfo().getLocation().getY() - getLocationOnScreen().getY();

        double zoomDiv = zoomFactor / prevZoomFactor;

        xOffset = (zoomDiv) * (xOffset) + (1 - zoomDiv) * xRel;
        yOffset = (zoomDiv) * (yOffset) + (1 - zoomDiv) * yRel;

        prevZoomFactor = zoomFactor;

        scrollTransform.translate((int)xOffset, (int)yOffset);

        scrollTransform.concatenate(zoomTransform);

        g2d.setTransform(scrollTransform);

        g2d.drawString("Example", 300, 400);

        g2d.dispose();
    }

    @Override
        public Dimension getPreferredSize()
        {
            Rectangle r = zoomTransform.createTransformedShape(rect).getBounds();
            return new Dimension(r.width, r.height);
        }
}

</code>```
```<code>package testpane;
import java.awt.Component;
import java.awt.Container;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import javax.swing.JComponent;
import javax.swing.JViewport;
import javax.swing.SwingUtilities;
import static testpane.TestPane.d;
import static testpane.TestPane.zoomFactor;

public class TestPaneMouseListener extends MouseAdapter
{
    private final Point origin = new Point();

    @Override
    public void mouseDragged(MouseEvent e)
    {
        Component c = e.getComponent();
        Container p = SwingUtilities.getUnwrappedParent(c);
        if (p instanceof JViewport)
        {
            JViewport viewport = (JViewport) p;
            Point cp = SwingUtilities.convertPoint(c, e.getPoint(), viewport);
            Point vp = viewport.getViewPosition();
            vp.translate(origin.x - cp.x, origin.y - cp.y);
            ((JComponent) c).scrollRectToVisible(new Rectangle(vp, viewport.getSize()));
            origin.setLocation(cp);
        }
    }

   @Override
   public void mousePressed(MouseEvent e)
   {
       Component c = e.getComponent();
       Container p = SwingUtilities.getUnwrappedParent(c);
       if(p instanceof JViewport)
       {
           JViewport viewport = (JViewport) p;
           Point cp = SwingUtilities.convertPoint(c, e.getPoint(), viewport);
           origin.setLocation(cp);
       }
   }

   @Override
    public void mouseWheelMoved(MouseWheelEvent e)
    {
        if(e.getWheelRotation()<0)
        {
            d.setZoomFactor(1.05);
            zoomFactor*=1.05;
        }

        if(e.getWheelRotation()>0)
        {
            d.setZoomFactor(1/1.05);
            zoomFactor/=1.05;
        }
    }
}
</code>```

I am aware that there are others who have asked the same exact question, but I'm having troubles implementing their solution into my code. I actually have no issues with the zooming itself, but what occurs after the zooming is a problem. As I zoom in more and more, I eventually lose part of the "Example" text which is written on the scroll panel. I realized that I need to translate the Panel in the opposite direction after the initial offset translation and zooming, but even after putting in the code for translating with the negatives of "xOffset" and "yOffset", I still lose part of the "Example" text I've written. Is an additional translation what I need to fix this problem, or would it be better to use a Viewport to specify the position of the Scroll panel that I want to see after the transformation is done?

Body:
Below is a minimal reproducible code example in which you can zoom in and out with the scroll wheel and the size of the panel is auto adjusted.

package testpane;
import java.awt.event.MouseAdapter;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.WindowConstants;

public class TestPane
{
    public static Drawing d;
    public static double zoomFactor = 1;

    public static void main(String[] args)
    {
        JFrame f = new JFrame("Tree Diagram");
        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        f.getContentPane().add(new TestPane().makeDiagram());
        f.setSize(1600, 800);
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public JComponent makeDiagram()
    {
        d = new Drawing();

        MouseAdapter mouseAdapter = new TestPaneMouseListener();
        d.addMouseListener(mouseAdapter);
        d.addMouseMotionListener(mouseAdapter);
        d.addMouseWheelListener(mouseAdapter);

        return new JScrollPane(d);
    }
}

package testpane;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.MouseInfo;
import java.awt.Rectangle;
import java.awt.geom.AffineTransform;
import javax.swing.JPanel;
import static testpane.TestPane.zoomFactor;

public class Drawing extends JPanel
{
    private final AffineTransform zoomTransform = new AffineTransform();
    private final Rectangle rect = new Rectangle(1600, 800);
    private double xOffset = 0;
    private double yOffset = 0;
    private double prevZoomFactor = 1;

    public Drawing()
    {
        Font currentFont = getFont();
        Font newFont = currentFont.deriveFont(currentFont.getSize() * 25F);
        setFont(newFont);
        setBackground(Color.WHITE);
    }

    public void setZoomFactor(double zoomFactor)
    {
        zoomTransform.scale(zoomFactor, zoomFactor);
        revalidate();
        repaint();
    }

    @Override
    protected void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g.create();
        AffineTransform scrollTransform = g2d.getTransform();

        double xRel = MouseInfo.getPointerInfo().getLocation().getX() - getLocationOnScreen().getX();
        double yRel = MouseInfo.getPointerInfo().getLocation().getY() - getLocationOnScreen().getY();

        double zoomDiv = zoomFactor / prevZoomFactor;

        xOffset = (zoomDiv) * (xOffset) + (1 - zoomDiv) * xRel;
        yOffset = (zoomDiv) * (yOffset) + (1 - zoomDiv) * yRel;

        prevZoomFactor = zoomFactor;

        scrollTransform.translate((int)xOffset, (int)yOffset);

        scrollTransform.concatenate(zoomTransform);

        g2d.setTransform(scrollTransform);

        g2d.drawString("Example", 300, 400);

        g2d.dispose();
    }

    @Override
        public Dimension getPreferredSize()
        {
            Rectangle r = zoomTransform.createTransformedShape(rect).getBounds();
            return new Dimension(r.width, r.height);
        }
}

package testpane;
import java.awt.Component;
import java.awt.Container;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import javax.swing.JComponent;
import javax.swing.JViewport;
import javax.swing.SwingUtilities;
import static testpane.TestPane.d;
import static testpane.TestPane.zoomFactor;

public class TestPaneMouseListener extends MouseAdapter
{
    private final Point origin = new Point();

    @Override
    public void mouseDragged(MouseEvent e)
    {
        Component c = e.getComponent();
        Container p = SwingUtilities.getUnwrappedParent(c);
        if (p instanceof JViewport)
        {
            JViewport viewport = (JViewport) p;
            Point cp = SwingUtilities.convertPoint(c, e.getPoint(), viewport);
            Point vp = viewport.getViewPosition();
            vp.translate(origin.x - cp.x, origin.y - cp.y);
            ((JComponent) c).scrollRectToVisible(new Rectangle(vp, viewport.getSize()));
            origin.setLocation(cp);
        }
    }

   @Override
   public void mousePressed(MouseEvent e)
   {
       Component c = e.getComponent();
       Container p = SwingUtilities.getUnwrappedParent(c);
       if(p instanceof JViewport)
       {
           JViewport viewport = (JViewport) p;
           Point cp = SwingUtilities.convertPoint(c, e.getPoint(), viewport);
           origin.setLocation(cp);
       }
   }

   @Override
    public void mouseWheelMoved(MouseWheelEvent e)
    {
        if(e.getWheelRotation()<0)
        {
            d.setZoomFactor(1.05);
            zoomFactor*=1.05;
        }

        if(e.getWheelRotation()>0)
        {
            d.setZoomFactor(1/1.05);
            zoomFactor/=1.05;
        }
    }
}

I am aware that there are others who have asked the same exact question, but I'm having troubles implementing their solution into my code. I actually have no issues with the zooming itself, but what occurs after the zooming is a problem. As I zoom in more and more, I eventually lose part of the "Example" text which is written on the scroll panel. I realized that I need to translate the Panel in the opposite direction after the initial offset translation and zooming, but even after putting in the code for translating with the negatives of "xOffset" and "yOffset", I still lose part of the "Example" text I've written. Is an additional translation what I need to fix this problem, or would it be better to use a Viewport to specify the position of the Scroll panel that I want to see after the transformation is done?


问:
Unique mapping of 3 integer parameters to an index in a lookup table with offset
I'm working on university assignment, where the goal is to design a recursive algorithm to compute the maximum size of a tower built using a sequence(s) of pallets under the condition that the pallet below should always be strictly larger then the pallets above.

I attempt to implement memoization with a lookup table to improve the efficiency of otherwise slow algorithm.

Below is my input processing:

```<code>
int
main(int argc, char const *argv[])
{
    int lookup_memb = 0;

    // read number of element in two stacks
    scanf("%i %i\n", &lenA, &lenB);

    // it's guaranteed for the first stack to always have more then zero elements
    stackA = (int*) malloc(lenA*sizeof(int));
    for (int i = 0; i < lenA; i ++) {
        scanf(" %i", stackA+i);
        stack_max = max(stack_max, stackA[i]);
    }

    // so far we estimate lookuptable size has to be at least lenA*stack_max;
    lookup_memb = lenA*stack_max;

    // however, second stack might be empty
    if (lenB) {
        stackB = (int*) malloc(lenB*sizeof(int));
        for (int i = 0; i < lenB; i ++) {
            scanf(" %i", stackB+i);
            stack_max = max(stack_max, stackB[i]);
        }

        // we have to override lookup_memb since we know stack B is not empty
        lookup_memb = lenA * lenB * stack_max;

    }

    lookup = (int*) calloc(lookup_memb, sizeof(int));
    printf("%i\n", solve2(stackA, stackB, lenA, lenB, stack_max));

    free(lookup);
    free(stackA);
    free(stackB);

    return 0;
}
</code>```

Then in my solving routine's i make use of

```<code>static
inline
int
idx(int llenA, int llenB, int constraint) {
    // I use local-length A as x coordinate
    // local-length B as y coordinate
    // and constraint as z coordinate

    return  llenA // final pad to the specific column in row and plane
            + llenB * lenA // pad to the specific row in a plane
            + constraint * lenB * lenA; // pad to a sepcific plane
}
</code>```

to determine the offset in the table.

There is a bug in the code, and it seems to be caused by out of bound array access. Now this if expected, since I start my algorithm looking up solution for full length of A, full length of B, and maximum possible constraint. Which makes it 1 row and 1 column out of bound.

I can fix it by allocating extra space, taking lenA to be lenA + 1, lenB to be lenB + 1, and constraint to be constraint + 1, but that seems unnecessary since if values for lenA and lenB are both zero or value of constraint is zero (moreover, constraint is guaranteed to be larger then zero), hard coding the return of zero is easier and arguably more efficient.

This means that table already contains one extra row, and one extra plane. I'm curios, how can I shift my index function so the mapping is still unique but it uses full table reducing the extra allocation I have to make.

I was asked to provide minimal reproducible example for this question. Here it is, I was hesitant to include it int the question, since I did not want to prompt people to provide a solution since that would be academic dishonesty.

```<code>#include<malloc.h>
#include<stdio.h>

int* stackA = NULL;
int* stackB = NULL;
int* lookup = NULL;
int lenA = 0, lenB = 0;
int stack_max = 0;

// returns maximum of two integers
static inline int max(int a, int b);

// maps unique set of parameters to a unique index in lookup table
static inline int idx(int llenA, int llenB, int constraint);

// find the maximum height of a tower which can be built using a sequence of pallets
// under condition that every next level of the tower must be strictly larger then the next one
int solve1(int* stack, int llen, int constraint, int isA);

// find the maximum height of a tower which can be built using ywo sequences of pallets
// under condition that every next level of the tower must be strictly larger then the next one
int solve2(int* stackA, int* stackB, int llenA, int llenB, int constraint);

static
inline
int
max(int a, int b) {
    return a < b ? b : a;
}

static
inline
int
idx(int llenA, int llenB, int constraint) {
    // I use local-length A as x coordinate
    // local-length B as y coordinate
    // and constraint as z coordinate

    return  llenA // final pad to the specific column in row and plane
            + llenB * lenA // pad to the specific row in a plane
            + constraint * lenB * lenA; // pad to a sepcific plane
}

int
solve1(int* stack, int llen, int constraint, int isA) {
    int fo,  // first-out element of the stack
        ret, // return value
        // lookup index of return value for parameters given
        // if we have stack A remaining, we pass local-len as length of A, and pass 0 as length of B
        // if we have stack B remaining, we do the opposite
        iself = idx(isA*llen, (!isA)*llen, constraint);

    if (!llen) // if we have empty stack, we know the height of a tower we can build using it is 0
        return 0;

    // we first attempt to lookup the value, hoping it was already calculated
    ret = lookup[iself];
    if (ret) // calloc zeroes out lookup table, hence if ret is not zero it was already populated
        return ret;

    // if we got here, we know we have to compute the value
    fo = stack[0];

    // we either have the opportunity to take the pallet or we do not
    // in first case, we need to find whether it's better to use or discard the pallet
    // in second case we have no choice, we we discard the pallet
    ret = (constraint <= fo) ? solve1(stack+1, llen-1, constraint, isA) :  max(1 + solve1(stack+1, llen-1, fo, isA), solve1(stack+1, llen-1, constraint, isA));
    lookup[iself] = ret;
    return ret;
}

int
solve2(int* stackA, int* stackB, int llenA, int llenB, int constraint) {

    int foA, // first-out element of stack A
        foB, // first-out element of stack B
        ret, // return value
        iself = idx(llenA, llenB, constraint); // lookup index of return value for parameters given

    if (!(llenA || llenB))
        return 0; // if both stacks are empty we know maximum height of a tower is zero

    // we first attempt to lookup the value, hoping that this calculation was already made
    ret = lookup[iself];
    if (ret) { // calloc zeroes out lookup table, hence if ret is not zero it was already populated
        return ret;
    }

    // if we got here, we must solve for value
    if (!llenA) { // if we only have stackB we simplify
        ret = solve1(stackB, llenB, constraint, 0);
        lookup[iself] = ret;
        return ret;
    }

    if (!llenB) { // likewise, if we only got stack A we simplify
        ret = solve1(stackA, llenA, constraint, 1);
        lookup[iself] = ret;
        return ret;
    }

    // if we got here, we must solve full problem
    foA = stackA[0];
    foB = stackB[0];

    // if we decide to make choice based on stack A, we either have the opportunity to take the pallet or we do not
    // in the first case, we need to find whether it's better to take or discard the pallet
    // in the second case we have no choice, hence we just discard it
    int chooseA = foA < constraint ? max(1 + solve2(stackA+1, stackB, llenA-1, llenB, foA), solve2(stackA+1, stackB, llenA-1, llenB, constraint)) : solve2(stackA+1, stackB, llenA-1, llenB, constraint);

    // if we decide to make choice based on stack B, we either have the opportunity to take the pallet or we do not
    // in the first case, we need to find whether it's better to take or discard the pallet
    // in the second case we have no choice, hence we just discard it
    int chooseB = foB < constraint ? max(1 + solve2(stackA, stackB+1, llenA, llenB-1, foB), solve2(stackA, stackB+1, llenA, llenB-1, constraint)) : solve2(stackA, stackB+1, llenA, llenB-1, constraint);

    // the solution for the current parameters is the maximum solution of stack A "route" and stack B "route"
    ret = max(chooseA, chooseB);
    lookup[iself] = ret;

    return ret;
}

int
main(int argc, char const *argv[])
{
    int lookup_memb = 0;

    // read number of element in two stacks
    scanf("%i %i\n", &lenA, &lenB);

    // it's guaranteed for the first stack to always have more then zero elements
    stackA = (int*) malloc(lenA*sizeof(int));
    for (int i = 0; i < lenA; i ++) {
        scanf(" %i", stackA+i);
        stack_max = max(stack_max, stackA[i]);
    }

    // so far we estimate lookuptable size has to be at least lenA*stack_max;
    lookup_memb = lenA*stack_max;

    // however, second stack might be empty
    if (lenB) {
        stackB = (int*) malloc(lenB*sizeof(int));
        for (int i = 0; i < lenB; i ++) {
            scanf(" %i", stackB+i);
            stack_max = max(stack_max, stackB[i]);
        }

        // we have to override lookup_memb since we know stack B is not empty
        lookup_memb = lenA * lenB * stack_max;
    }

    lookup = (int*) calloc(lookup_memb, sizeof(int));
    printf("%i\n", solve2(stackA, stackB, lenA, lenB, stack_max));

    free(lookup);
    free(stackA);
    free(stackB);

    return 0;
}
</code>```

Body:
I'm working on university assignment, where the goal is to design a recursive algorithm to compute the maximum size of a tower built using a sequence(s) of pallets under the condition that the pallet below should always be strictly larger then the pallets above.

I attempt to implement memoization with a lookup table to improve the efficiency of otherwise slow algorithm.

Below is my input processing:

int
main(int argc, char const *argv[])
{
    int lookup_memb = 0;

    // read number of element in two stacks
    scanf("%i %i\n", &lenA, &lenB);

    // it's guaranteed for the first stack to always have more then zero elements
    stackA = (int*) malloc(lenA*sizeof(int));
    for (int i = 0; i < lenA; i ++) {
        scanf(" %i", stackA+i);
        stack_max = max(stack_max, stackA[i]);
    }

    // so far we estimate lookuptable size has to be at least lenA*stack_max;
    lookup_memb = lenA*stack_max;

    // however, second stack might be empty
    if (lenB) {
        stackB = (int*) malloc(lenB*sizeof(int));
        for (int i = 0; i < lenB; i ++) {
            scanf(" %i", stackB+i);
            stack_max = max(stack_max, stackB[i]);
        }

        // we have to override lookup_memb since we know stack B is not empty
        lookup_memb = lenA * lenB * stack_max;

    }

    lookup = (int*) calloc(lookup_memb, sizeof(int));
    printf("%i\n", solve2(stackA, stackB, lenA, lenB, stack_max));

    free(lookup);
    free(stackA);
    free(stackB);

    return 0;
}

Then in my solving routine's i make use of

static
inline
int
idx(int llenA, int llenB, int constraint) {
    // I use local-length A as x coordinate
    // local-length B as y coordinate
    // and constraint as z coordinate

    return  llenA // final pad to the specific column in row and plane
            + llenB * lenA // pad to the specific row in a plane
            + constraint * lenB * lenA; // pad to a sepcific plane
}

to determine the offset in the table.

There is a bug in the code, and it seems to be caused by out of bound array access. Now this if expected, since I start my algorithm looking up solution for full length of A, full length of B, and maximum possible constraint. Which makes it 1 row and 1 column out of bound.

I can fix it by allocating extra space, taking lenA to be lenA + 1, lenB to be lenB + 1, and constraint to be constraint + 1, but that seems unnecessary since if values for lenA and lenB are both zero or value of constraint is zero (moreover, constraint is guaranteed to be larger then zero), hard coding the return of zero is easier and arguably more efficient.

This means that table already contains one extra row, and one extra plane. I'm curios, how can I shift my index function so the mapping is still unique but it uses full table reducing the extra allocation I have to make.

I was asked to provide minimal reproducible example for this question. Here it is, I was hesitant to include it int the question, since I did not want to prompt people to provide a solution since that would be academic dishonesty.

#include<malloc.h>
#include<stdio.h>

int* stackA = NULL;
int* stackB = NULL;
int* lookup = NULL;
int lenA = 0, lenB = 0;
int stack_max = 0;

// returns maximum of two integers
static inline int max(int a, int b);

// maps unique set of parameters to a unique index in lookup table
static inline int idx(int llenA, int llenB, int constraint);

// find the maximum height of a tower which can be built using a sequence of pallets
// under condition that every next level of the tower must be strictly larger then the next one
int solve1(int* stack, int llen, int constraint, int isA);

// find the maximum height of a tower which can be built using ywo sequences of pallets
// under condition that every next level of the tower must be strictly larger then the next one
int solve2(int* stackA, int* stackB, int llenA, int llenB, int constraint);

static
inline
int
max(int a, int b) {
    return a < b ? b : a;
}

static
inline
int
idx(int llenA, int llenB, int constraint) {
    // I use local-length A as x coordinate
    // local-length B as y coordinate
    // and constraint as z coordinate

    return  llenA // final pad to the specific column in row and plane
            + llenB * lenA // pad to the specific row in a plane
            + constraint * lenB * lenA; // pad to a sepcific plane
}

int
solve1(int* stack, int llen, int constraint, int isA) {
    int fo,  // first-out element of the stack
        ret, // return value
        // lookup index of return value for parameters given
        // if we have stack A remaining, we pass local-len as length of A, and pass 0 as length of B
        // if we have stack B remaining, we do the opposite
        iself = idx(isA*llen, (!isA)*llen, constraint);

    if (!llen) // if we have empty stack, we know the height of a tower we can build using it is 0
        return 0;

    // we first attempt to lookup the value, hoping it was already calculated
    ret = lookup[iself];
    if (ret) // calloc zeroes out lookup table, hence if ret is not zero it was already populated
        return ret;

    // if we got here, we know we have to compute the value
    fo = stack[0];

    // we either have the opportunity to take the pallet or we do not
    // in first case, we need to find whether it's better to use or discard the pallet
    // in second case we have no choice, we we discard the pallet
    ret = (constraint <= fo) ? solve1(stack+1, llen-1, constraint, isA) :  max(1 + solve1(stack+1, llen-1, fo, isA), solve1(stack+1, llen-1, constraint, isA));
    lookup[iself] = ret;
    return ret;
}

int
solve2(int* stackA, int* stackB, int llenA, int llenB, int constraint) {

    int foA, // first-out element of stack A
        foB, // first-out element of stack B
        ret, // return value
        iself = idx(llenA, llenB, constraint); // lookup index of return value for parameters given

    if (!(llenA || llenB))
        return 0; // if both stacks are empty we know maximum height of a tower is zero

    // we first attempt to lookup the value, hoping that this calculation was already made
    ret = lookup[iself];
    if (ret) { // calloc zeroes out lookup table, hence if ret is not zero it was already populated
        return ret;
    }

    // if we got here, we must solve for value
    if (!llenA) { // if we only have stackB we simplify
        ret = solve1(stackB, llenB, constraint, 0);
        lookup[iself] = ret;
        return ret;
    }

    if (!llenB) { // likewise, if we only got stack A we simplify
        ret = solve1(stackA, llenA, constraint, 1);
        lookup[iself] = ret;
        return ret;
    }

    // if we got here, we must solve full problem
    foA = stackA[0];
    foB = stackB[0];

    // if we decide to make choice based on stack A, we either have the opportunity to take the pallet or we do not
    // in the first case, we need to find whether it's better to take or discard the pallet
    // in the second case we have no choice, hence we just discard it
    int chooseA = foA < constraint ? max(1 + solve2(stackA+1, stackB, llenA-1, llenB, foA), solve2(stackA+1, stackB, llenA-1, llenB, constraint)) : solve2(stackA+1, stackB, llenA-1, llenB, constraint);

    // if we decide to make choice based on stack B, we either have the opportunity to take the pallet or we do not
    // in the first case, we need to find whether it's better to take or discard the pallet
    // in the second case we have no choice, hence we just discard it
    int chooseB = foB < constraint ? max(1 + solve2(stackA, stackB+1, llenA, llenB-1, foB), solve2(stackA, stackB+1, llenA, llenB-1, constraint)) : solve2(stackA, stackB+1, llenA, llenB-1, constraint);

    // the solution for the current parameters is the maximum solution of stack A "route" and stack B "route"
    ret = max(chooseA, chooseB);
    lookup[iself] = ret;

    return ret;
}

int
main(int argc, char const *argv[])
{
    int lookup_memb = 0;

    // read number of element in two stacks
    scanf("%i %i\n", &lenA, &lenB);

    // it's guaranteed for the first stack to always have more then zero elements
    stackA = (int*) malloc(lenA*sizeof(int));
    for (int i = 0; i < lenA; i ++) {
        scanf(" %i", stackA+i);
        stack_max = max(stack_max, stackA[i]);
    }

    // so far we estimate lookuptable size has to be at least lenA*stack_max;
    lookup_memb = lenA*stack_max;

    // however, second stack might be empty
    if (lenB) {
        stackB = (int*) malloc(lenB*sizeof(int));
        for (int i = 0; i < lenB; i ++) {
            scanf(" %i", stackB+i);
            stack_max = max(stack_max, stackB[i]);
        }

        // we have to override lookup_memb since we know stack B is not empty
        lookup_memb = lenA * lenB * stack_max;
    }

    lookup = (int*) calloc(lookup_memb, sizeof(int));
    printf("%i\n", solve2(stackA, stackB, lenA, lenB, stack_max));

    free(lookup);
    free(stackA);
    free(stackB);

    return 0;
}


问:
Lua uart connection serial port
I am trying to connect my sensor in uart to my device. I am supposed to send a couple of bytes, wait, and listen to the output. Unfortunately, I haven't found a way that works for me.

I tried to first send the bytes through io.open(locaation port) and then write into it, wait and then again read to obtain the response.

I wasn't sure I could use io.open to write, so I then used echo -ne byte > port. For listening, I still use io.read()

I have found library that enable a serial connection in Lua, but they make use of C libraries, something I cannot use.

How can I then write and listens to a serial port in Lua/linux with very basic commands.

Title: Lua uart connection serial port


问:
Including a number in gtk3 widget
I'm doing a Matrix program and I have done a widget for entering the dimension but I want to show the numbers into the widget and I don't know how.

```<code>#include <stdlib.h>
#include <gtk/gtk.h>
static int d,e;
void on_button_click(GtkWidget *widget, gpointer data)
{if ((char *) data=="1")
    {d=d+1; }
    if ((char *) data=="2")
    {d=d-1;}
    if ((char *) data=="3")
    { e=e+1; }
    if ((char *) data=="4")
    { e=e-1; }
    g_print("The dimension is height: %d y width : %d\n",d,e);
}
int main (int argc, char *argv[])
{ GtkWidget *window;
  GtkWidget *button;
  GtkWidget *table;
  GtkWidget *label;
  GtkWidget *frame;
  gtk_init (&argc, &argv){
  window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
  gtk_window_set_title (GTK_WINDOW (window), "Start ...");
  gtk_container_set_border_width (GTK_CONTAINER (window), 10);
  table = gtk_table_new (3,4,FALSE);
  gtk_container_add (GTK_CONTAINER (window), table);
  button = gtk_button_new_with_label ("More x");
  g_signal_connect (G_OBJECT (button), "clicked", G_CALLBACK (on_button_click), (gpointer) "1");
  gtk_table_attach (GTK_TABLE(table),button,0,1,0,1,0,0,2,2);
  button = gtk_button_new_with_label ("Less x");
  g_signal_connect (G_OBJECT (button), "clicked", G_CALLBACK(on_button_click), (gpointer) "2");
  gtk_table_attach (GTK_TABLE (table),button,1,2,0,1,0,0,2,2);
  button = gtk_button_new_with_label ("More y");
  g_signal_connect (G_OBJECT (button), "clicked", G_CALLBACK(on_button_click), (gpointer) "3");
  gtk_table_attach (GTK_TABLE(table),button,2,3,0,1,0,0,2,2);
  button = gtk_button_new_with_label ("Less y");
  g_signal_connect (G_OBJECT (button), "clicked", G_CALLBACK(on_button_click), (gpointer) "4");
  gtk_table_attach (GTK_TABLE(table),button,2,3,0,3,0,0,2,2);
  button=gtk_button_new_with_label ("Quit");
  gtk_table_attach (GTK_TABLE (table),button,0,2,1,2,0,0,2,2);
  g_signal_connect (G_OBJECT(window),"destroy",G_CALLBACK(gtk_main_quit),NULL);
  g_signal_connect_swapped (G_OBJECT(button),"clicked",G_CALLBACK(gtk_main_quit),(gpointer)window);
  frame=gtk_frame_new(NULL);
  label=gtk_label_new("Columns x\n Rows y");
  gtk_container_add(GTK_CONTAINER(frame),label);
  gtk_table_attach(GTK_TABLE(table),frame,3,4,0,2,GTK_EXPAND|GTK_FILL, GTK_EXPAND|GTK_FILL,0,0);
  frame=gtk_frame_new(NULL);
  label=gtk_label_new("Redim the matrix... ");
  gtk_container_add (GTK_CONTAINER(frame),label);
  gtk_table_attach (GTK_TABLE(table),frame,0,4,2,3,GTK_EXPAND|GTK_FILL, GTK_EXPAND|GTK_FILL,0,0);
gtk_widget_show_all(window);
gtk_main();

return 0;
}
      ...

</code>```

The problem is that the variables d and e appeared in the console when I clicked one of the four buttons.  For me it doesn't matter because the program ran anyway. But I believe that it looks better if the two numbers appear into the widget in a box.

Title: Including a number in gtk3 widget

Body:
I'm doing a Matrix program and I have done a widget for entering the dimension but I want to show the numbers into the widget and I don't know how.

#include <stdlib.h>
#include <gtk/gtk.h>
static int d,e;
void on_button_click(GtkWidget *widget, gpointer data)
{if ((char *) data=="1")
    {d=d+1; }
    if ((char *) data=="2")
    {d=d-1;}
    if ((char *) data=="3")
    { e=e+1; }
    if ((char *) data=="4")
    { e=e-1; }
    g_print("The dimension is height: %d y width : %d\n",d,e);
}
int main (int argc, char *argv[])
{ GtkWidget *window;
  GtkWidget *button;
  GtkWidget *table;
  GtkWidget *label;
  GtkWidget *frame;
  gtk_init (&argc, &argv){
  window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
  gtk_window_set_title (GTK_WINDOW (window), "Start ...");
  gtk_container_set_border_width (GTK_CONTAINER (window), 10);
  table = gtk_table_new (3,4,FALSE);
  gtk_container_add (GTK_CONTAINER (window), table);
  button = gtk_button_new_with_label ("More x");
  g_signal_connect (G_OBJECT (button), "clicked", G_CALLBACK (on_button_click), (gpointer) "1");
  gtk_table_attach (GTK_TABLE(table),button,0,1,0,1,0,0,2,2);
  button = gtk_button_new_with_label ("Less x");
  g_signal_connect (G_OBJECT (button), "clicked", G_CALLBACK(on_button_click), (gpointer) "2");
  gtk_table_attach (GTK_TABLE (table),button,1,2,0,1,0,0,2,2);
  button = gtk_button_new_with_label ("More y");
  g_signal_connect (G_OBJECT (button), "clicked", G_CALLBACK(on_button_click), (gpointer) "3");
  gtk_table_attach (GTK_TABLE(table),button,2,3,0,1,0,0,2,2);
  button = gtk_button_new_with_label ("Less y");
  g_signal_connect (G_OBJECT (button), "clicked", G_CALLBACK(on_button_click), (gpointer) "4");
  gtk_table_attach (GTK_TABLE(table),button,2,3,0,3,0,0,2,2);
  button=gtk_button_new_with_label ("Quit");
  gtk_table_attach (GTK_TABLE (table),button,0,2,1,2,0,0,2,2);
  g_signal_connect (G_OBJECT(window),"destroy",G_CALLBACK(gtk_main_quit),NULL);
  g_signal_connect_swapped (G_OBJECT(button),"clicked",G_CALLBACK(gtk_main_quit),(gpointer)window);
  frame=gtk_frame_new(NULL);
  label=gtk_label_new("Columns x\n Rows y");
  gtk_container_add(GTK_CONTAINER(frame),label);
  gtk_table_attach(GTK_TABLE(table),frame,3,4,0,2,GTK_EXPAND|GTK_FILL, GTK_EXPAND|GTK_FILL,0,0);
  frame=gtk_frame_new(NULL);
  label=gtk_label_new("Redim the matrix... ");
  gtk_container_add (GTK_CONTAINER(frame),label);
  gtk_table_attach (GTK_TABLE(table),frame,0,4,2,3,GTK_EXPAND|GTK_FILL, GTK_EXPAND|GTK_FILL,0,0);
gtk_widget_show_all(window);
gtk_main();

return 0;
}
      ...

The problem is that the variables d and e appeared in the console when I clicked one of the four buttons.  For me it doesn't matter because the program ran anyway. But I believe that it looks better if the two numbers appear into the widget in a box.


问:
Is it possible to store the token in react context and how we can do?
How we can store the token in react context and also why it is bad way for storing the token in local and session storage.?

I have suppose to do by creating create context and consuming it in our login component.


问:
Dompdf Table Cell rendering error (TableCell.php file)
Am facing this unique error in my dompdf execution and i see this file belongs to the core of dompdf library. Does anyone faced this ?

```<code>in_array() expects parameter 2 to be array, null given [/var/www/html/projeX/app/libraries/dompdf/src/Renderer/TableCell.php:67] (at ErrorHandler::error)
</code>```

We are using dompdf 0.8.0 version. Not sure if it is a good idea to change anything in core file.

Body:
Am facing this unique error in my dompdf execution and i see this file belongs to the core of dompdf library. Does anyone faced this ?

in_array() expects parameter 2 to be array, null given [/var/www/html/projeX/app/libraries/dompdf/src/Renderer/TableCell.php:67] (at ErrorHandler::error)

We are using dompdf 0.8.0 version. Not sure if it is a good idea to change anything in core file.


问:
Runtime models based on L1-TLB metrics
We are building a model to predict the CPU runtime of a Haswell Intel Xeon E5-x600 v3 processor using the perf tool from the linux-tools package and running various benchmarks. The model uses TLB events, including dTLB and sTLB, as predictors. However, the results we obtained were unexpected, as a single-feature model over the same benchmark (and several others) showed a trend opposite to what we anticipated:

Actual L1 runtime model

We would expect that higher number of hits will lead to decrease in cpu cycles.

Upon further investigation, we realized that we had not considered the out-of-order execution (OOOE) characteristics of the Haswell processor, which includes both retired uops and speculative events. As our goal is to compare "apples to apples," we want to ensure that we are comparing either retired events to retired events or speculative events to speculative events. We are now seeking to include speculative dTLB accesses and retired sTLB hits in our model to achieve proper predictors.

speculative dTLB accesses attempt: L1-dcache-loads and L1-dcache-stores counters as potential predictors for speculative dTLB accesses, but we later learned that these counters refer to retired events rather than speculative ones.

retired sTLB hits: We have been unable to identify a suitable counter for retired sTLB hits out of perf –list options.

Perhaps there is another way to calculate those features indirectly using other counters we hadn't considered

Title: Runtime models based on L1-TLB metrics


问:
I have an issue with my code: "Column 'userid' cannot be null"
I have used many-to-one mapping while running it and giving the details in postman it says that the column userid cannot be null, when I change the userid in creditcard table then it is running but the userid is showing null and when i change it as not null the the above error is shown there are other errors as well such as: " SQL Error: 1048, SQLState: 23000
: Column 'userid' cannot be null
: On release of batch it still contained JDBC statements"

Here is my Code:
creditcard.java

```<code>import java.io.Serializable;

import javax.persistence.Access;
import javax.persistence.AccessType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import org.hibernate.annotations.ManyToAny;
import org.hibernate.annotations.NotFound;
import org.hibernate.annotations.NotFoundAction;

import com.fasterxml.jackson.annotation.JsonIgnore;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Entity
@Table(name="creditcard")
public class creditcard implements Serializable {
  @Id
  private int Cardnumber;

  private String cvv;

  private String expiry_date;

  private String name;

  @NotFound(action = NotFoundAction.IGNORE)
  @ManyToOne(fetch = FetchType.LAZY, optional = true)
  @JoinColumn(name = "userid", insertable = true, updatable = true)
  @Access(AccessType.PROPERTY)
  private users users;

public String getExpiry_date() {
    return expiry_date;
}

public void setExpiry_date(String expiry_date) {
    this.expiry_date = expiry_date;
}

public int getCardnumber() {
    return Cardnumber;
}

public void setCardnumber(int cardnumber) {
    Cardnumber = cardnumber;
}

public String getCvv() {
    return cvv;
}

public void setCvv(String cvv) {
    this.cvv = cvv;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

@JsonIgnore
public users getUsers() {
    return users;
}

public void setUsers(users users) {
    this.users = users;
}

public creditcard(String cvv, String expiry_date, String name, com.example.Accessories.model.users users) {
    super();
    this.cvv = cvv;
    this.expiry_date = expiry_date;
    this.name = name;
    this.users = users;
}

public creditcard() {
    super();
    // TODO Auto-generated constructor stub
}

}

</code>```

users.java

```<code>import java.io.Serializable;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Entity
@Table(name="users")
public class users implements Serializable {
  @Id
  @Column(name = "id", unique = true, nullable = false)
  private int id;
  @Column(name="Firstname")
  private String firstname;
  @Column(name="Lastname")
  private String lastname;
  private String email;
  //@Column(name="password")
  private String password;
  private String phonenumber;
  private String address;

  @OneToMany(mappedBy = "users",targetEntity =creditcard.class, fetch = FetchType.LAZY,cascade = CascadeType.ALL)
  private List<creditcard> creditcards;

public users(int id, String firstname, String lastname, String email, String password, String phonenumber,
        String address) {
    super();
    this.id = id;
    this.firstname = firstname;
    this.lastname = lastname;
    this.email = email;
    this.password = password;
    this.phonenumber = phonenumber;
    this.address = address;
}

public List<orders> getOrders() {
    return orders;
}

public void setCreditcards(List<creditcard> creditcards) {
    this.creditcards = creditcards;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getFirstname() {
    return firstname;
}

public void setFirstname(String firstname) {
    this.firstname = firstname;
}

public String getLastname() {
    return lastname;
}

public void setLastname(String lastname) {
    this.lastname = lastname;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

public String getPhonenumber() {
    return phonenumber;
}

public void setPhonenumber(String phonenumber) {
    this.phonenumber = phonenumber;
}

public String getAddress() {
    return address;
}

public void setAddress(String address) {
    this.address = address;
}

public users() {
    super();
}

}
</code>```

credicardcontroller.java:

```<code>import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.example.Accessories.model.creditcard;
import com.example.Accessories.model.orders;
import com.example.Accessories.model.users;
import com.example.Accessories.repository.creditcardrepository;
import com.example.Accessories.repository.ordersrepository;

@RestController
public class creditcardcontroller {
    @Autowired
    private creditcardrepository creditcardRepository;

    @Autowired
       private PasswordEncoder passwordEncoder;

    @GetMapping("/creditcard")
    public List<creditcard> getAllrings()
    {
        return creditcardRepository.findAll();
    }
    @PostMapping("/card")
      public ResponseEntity<String> registerusers(@RequestBody creditcard credit) {
        creditcard savedAccessory = null;
        ResponseEntity response = null;
        try {
            String hashPwd=passwordEncoder.encode(credit.getCvv());
            credit.setCvv(hashPwd);
            savedAccessory = creditcardRepository.save(credit);
            if (savedAccessory.getCardnumber() > 0) {
                response = ResponseEntity
                        .status(HttpStatus.CREATED)
                        .body("Given user details are successfully registered");
            }
        } catch (Exception ex) {
            response = ResponseEntity
                    .status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("An exception occured due to " + ex.getMessage());
        }
        return response;
    }

}

</code>```

userscontroller.java:

```<code>import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.example.Accessories.model.users;
import com.example.Accessories.repository.usersrepository;

@RestController
@RequestMapping
public class userscontroller {

    @Autowired
    private usersrepository usersRepository;

    @Autowired
       private PasswordEncoder passwordEncoder;

    @GetMapping("/use")
    public List<users> getAllusers()
    {
        return usersRepository.findAll();
    }

//         @PostMapping("/welcome")
//         public users getWelcome(@RequestBody users user) {
//             String username= user.getEmail();
//             String password = user.getPassword();
//
//             users findByUsername = (users) usersRepository.findByEmail(username);
//             boolean status;
//
//            if(findByUsername != null) {
//           if(password.equals(findByUsername.getPassword())) {
//                     status = true;
//                 }
//                 else {
//                     status = false;                 }
//         }
//             else {
//                 status = false;
//             }
//
//            if(status) {
//                 //return "Login Successful";
//                 return findByUsername;
//             }
//             else {
//                 return null;            }
//         }

//  @PostMapping
//  public users addUser(@RequestBody users user) {
//      return usersRepository.save(user);
//  }
      @PostMapping("/add")
      public ResponseEntity<String> registerusers(@RequestBody users user) {
          users savedFarmers = null;
          ResponseEntity response = null;
          try {
              String hashPwd=passwordEncoder.encode(user.getPassword());
              user.setPassword(hashPwd);
              savedFarmers = usersRepository.save(user);
              if (savedFarmers.getId() > 0) {
                  response = ResponseEntity
                          .status(HttpStatus.CREATED)
                          .body("Given user details are successfully registered");
              }
          } catch (Exception ex) {
              response = ResponseEntity
                      .status(HttpStatus.INTERNAL_SERVER_ERROR)
                      .body("An exception occured due to " + ex.getMessage());
          }
          return response;
      }

      }

</code>```

creditcardrepository.java

```<code>import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.example.Accessories.model.creditcard;
import com.example.Accessories.model.users;
@Repository
public interface creditcardrepository extends JpaRepository<creditcard, Integer> {
    List<creditcard> findByCvv(String cvv);
}

</code>```

usersrepository.java

```<code>import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.example.Accessories.model.users;

@Repository
public interface usersrepository extends JpaRepository<users, Integer>{

    List<users> findByEmail(String email);
}
</code>```

Body:
I have used many-to-one mapping while running it and giving the details in postman it says that the column userid cannot be null, when I change the userid in creditcard table then it is running but the userid is showing null and when i change it as not null the the above error is shown there are other errors as well such as: " SQL Error: 1048, SQLState: 23000
: Column 'userid' cannot be null
: On release of batch it still contained JDBC statements"

Here is my Code:
creditcard.java

import java.io.Serializable;

import javax.persistence.Access;
import javax.persistence.AccessType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import org.hibernate.annotations.ManyToAny;
import org.hibernate.annotations.NotFound;
import org.hibernate.annotations.NotFoundAction;

import com.fasterxml.jackson.annotation.JsonIgnore;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Entity
@Table(name="creditcard")
public class creditcard implements Serializable {
  @Id
  private int Cardnumber;

  private String cvv;

  private String expiry_date;

  private String name;

  @NotFound(action = NotFoundAction.IGNORE)
  @ManyToOne(fetch = FetchType.LAZY, optional = true)
  @JoinColumn(name = "userid", insertable = true, updatable = true)
  @Access(AccessType.PROPERTY)
  private users users;

public String getExpiry_date() {
    return expiry_date;
}

public void setExpiry_date(String expiry_date) {
    this.expiry_date = expiry_date;
}

public int getCardnumber() {
    return Cardnumber;
}

public void setCardnumber(int cardnumber) {
    Cardnumber = cardnumber;
}

public String getCvv() {
    return cvv;
}

public void setCvv(String cvv) {
    this.cvv = cvv;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

@JsonIgnore
public users getUsers() {
    return users;
}

public void setUsers(users users) {
    this.users = users;
}

public creditcard(String cvv, String expiry_date, String name, com.example.Accessories.model.users users) {
    super();
    this.cvv = cvv;
    this.expiry_date = expiry_date;
    this.name = name;
    this.users = users;
}

public creditcard() {
    super();
    // TODO Auto-generated constructor stub
}

}

users.java

import java.io.Serializable;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Entity
@Table(name="users")
public class users implements Serializable {
  @Id
  @Column(name = "id", unique = true, nullable = false)
  private int id;
  @Column(name="Firstname")
  private String firstname;
  @Column(name="Lastname")
  private String lastname;
  private String email;
  //@Column(name="password")
  private String password;
  private String phonenumber;
  private String address;

  @OneToMany(mappedBy = "users",targetEntity =creditcard.class, fetch = FetchType.LAZY,cascade = CascadeType.ALL)
  private List<creditcard> creditcards;

public users(int id, String firstname, String lastname, String email, String password, String phonenumber,
        String address) {
    super();
    this.id = id;
    this.firstname = firstname;
    this.lastname = lastname;
    this.email = email;
    this.password = password;
    this.phonenumber = phonenumber;
    this.address = address;
}

public List<orders> getOrders() {
    return orders;
}

public void setCreditcards(List<creditcard> creditcards) {
    this.creditcards = creditcards;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getFirstname() {
    return firstname;
}

public void setFirstname(String firstname) {
    this.firstname = firstname;
}

public String getLastname() {
    return lastname;
}

public void setLastname(String lastname) {
    this.lastname = lastname;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

public String getPhonenumber() {
    return phonenumber;
}

public void setPhonenumber(String phonenumber) {
    this.phonenumber = phonenumber;
}

public String getAddress() {
    return address;
}

public void setAddress(String address) {
    this.address = address;
}

public users() {
    super();
}

}

credicardcontroller.java:

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.example.Accessories.model.creditcard;
import com.example.Accessories.model.orders;
import com.example.Accessories.model.users;
import com.example.Accessories.repository.creditcardrepository;
import com.example.Accessories.repository.ordersrepository;

@RestController
public class creditcardcontroller {
    @Autowired
    private creditcardrepository creditcardRepository;

    @Autowired
       private PasswordEncoder passwordEncoder;

    @GetMapping("/creditcard")
    public List<creditcard> getAllrings()
    {
        return creditcardRepository.findAll();
    }
    @PostMapping("/card")
      public ResponseEntity<String> registerusers(@RequestBody creditcard credit) {
        creditcard savedAccessory = null;
        ResponseEntity response = null;
        try {
            String hashPwd=passwordEncoder.encode(credit.getCvv());
            credit.setCvv(hashPwd);
            savedAccessory = creditcardRepository.save(credit);
            if (savedAccessory.getCardnumber() > 0) {
                response = ResponseEntity
                        .status(HttpStatus.CREATED)
                        .body("Given user details are successfully registered");
            }
        } catch (Exception ex) {
            response = ResponseEntity
                    .status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("An exception occured due to " + ex.getMessage());
        }
        return response;
    }

}

userscontroller.java:

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.example.Accessories.model.users;
import com.example.Accessories.repository.usersrepository;

@RestController
@RequestMapping
public class userscontroller {

    @Autowired
    private usersrepository usersRepository;

    @Autowired
       private PasswordEncoder passwordEncoder;

    @GetMapping("/use")
    public List<users> getAllusers()
    {
        return usersRepository.findAll();
    }

//         @PostMapping("/welcome")
//         public users getWelcome(@RequestBody users user) {
//             String username= user.getEmail();
//             String password = user.getPassword();
//
//             users findByUsername = (users) usersRepository.findByEmail(username);
//             boolean status;
//
//            if(findByUsername != null) {
//           if(password.equals(findByUsername.getPassword())) {
//                     status = true;
//                 }
//                 else {
//                     status = false;                 }
//         }
//             else {
//                 status = false;
//             }
//
//            if(status) {
//                 //return "Login Successful";
//                 return findByUsername;
//             }
//             else {
//                 return null;            }
//         }

//  @PostMapping
//  public users addUser(@RequestBody users user) {
//      return usersRepository.save(user);
//  }
      @PostMapping("/add")
      public ResponseEntity<String> registerusers(@RequestBody users user) {
          users savedFarmers = null;
          ResponseEntity response = null;
          try {
              String hashPwd=passwordEncoder.encode(user.getPassword());
              user.setPassword(hashPwd);
              savedFarmers = usersRepository.save(user);
              if (savedFarmers.getId() > 0) {
                  response = ResponseEntity
                          .status(HttpStatus.CREATED)
                          .body("Given user details are successfully registered");
              }
          } catch (Exception ex) {
              response = ResponseEntity
                      .status(HttpStatus.INTERNAL_SERVER_ERROR)
                      .body("An exception occured due to " + ex.getMessage());
          }
          return response;
      }

      }

creditcardrepository.java

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.example.Accessories.model.creditcard;
import com.example.Accessories.model.users;
@Repository
public interface creditcardrepository extends JpaRepository<creditcard, Integer> {
    List<creditcard> findByCvv(String cvv);
}

usersrepository.java

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.example.Accessories.model.users;

@Repository
public interface usersrepository extends JpaRepository<users, Integer>{

    List<users> findByEmail(String email);
}