问:
Material UI Responsive based Appbar covering over main contect? How can I fix this?
I am trying to write out a website with responsive-based app bar with a drawer tagged onto it. I am using this design found at https://medium.com/@tsubasakondo_36683/create-responsive-drawer-menu-with-react-material-ui-617a42764b69 and modifying it accordingly. But unfortunately, I am getting this issue, in which the drawer covers the portion of the content trying to be displayed. Please know that I have seen similar questions on this site, but I couldn't figure out how to solve them or the answers were kind of vague. Any help would be much appreciated, please let me know if I need to clarify anything further. All of this is using Material UI components.

Here is my code:

Material UI App-Bar

//Used code: https://medium.com/@tsubasakondo_36683/create-responsive-drawer-menu-with-react-material-ui-617a42764b69

//Picture/Icon Imports
import home from "../Icons/home.png";
import about from "../Icons/about.png";
import contact from "../Icons/contact.png";
import resume from "../Icons/resume.png";
import minecraft from "../Icons/minecraft.png";
import github from "../Icons/github.png"

import React from 'react';
import PropTypes from 'prop-types';
import AppBar from '@material-ui/core/AppBar';
import CssBaseline from '@material-ui/core/CssBaseline';
import Drawer from '@material-ui/core/Drawer';
import Hidden from '@material-ui/core/Hidden';
import IconButton from '@material-ui/core/IconButton';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemText from '@material-ui/core/ListItemText';
import MenuIcon from '@material-ui/icons/Menu';
import CloseIcon from '@material-ui/icons/Close';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import { makeStyles, useTheme } from '@material-ui/core/styles';
import {Link} from "react-router-dom";
const drawerWidth = 240;

const useStyles = makeStyles(theme => ({
    root: {
        display: 'flex',
    },
    drawer: {
        [theme.breakpoints.up('sm')]: {
            width: drawerWidth,
            flexShrink: 0,
        },
    },
    appBar: {
        zIndex: theme.zIndex.drawer + 1,
    },
    menuButton: {
        marginRight: theme.spacing(2),
        [theme.breakpoints.up('sm')]: {
            display: 'none',
        },
    },
    toolbar: theme.mixins.toolbar,
    drawerPaper: {
        width: drawerWidth
    },
    content: {
        flexGrow: 1,
        padding: theme.spacing(0),
    },
    closeMenuButton: {
        marginRight: 'auto',
        marginLeft: 0,
    },
}));
function NavBar() {
    const DifferentPages = [
        {Text: "Home", location: "/", Image: home},
        {Text: "About", location: "/about", Image: about},
        {Text: "Contact", location: "/contact", Image: contact},
        {Text: "Resume", location: "/resume", Image: resume},
        {Text: "Minecraft", location: "/minecraft", Image: minecraft},
    ]

    const classes = useStyles();
    const theme = useTheme();
    const [mobileOpen, setMobileOpen] = React.useState(false);
    function handleDrawerToggle() {
        setMobileOpen(!mobileOpen)
    }
    const drawer = (

            <List>
                {DifferentPages.map((Text) => (
                    <ListItem button component={Link} to={Text.location}>

                        <ListItemText primary={Text.Text} />
                    </ListItem>
                ))}
                <ListItem button href={"example.com"}>

                    <ListItemText>
                        Github
                    </ListItemText>
                </ListItem>
            </List>

    );
    return (

            <CssBaseline />
            <AppBar position="fixed" className={classes.appBar}>
                <Toolbar>
                    <IconButton
                        color="inherit"
                        aria-label="Open drawer"
                        edge="start"
                        onClick={handleDrawerToggle}
                        className={classes.menuButton}
                    >
                        <MenuIcon />
                    </IconButton>
                    <Typography variant="h6" noWrap>
                        Responsive drawer
                    </Typography>
                </Toolbar>
            </AppBar>

                <Hidden smUp implementation="css">
                    <Drawer
                        variant="temporary"
                        anchor={theme.direction === 'rtl' ? 'right' : 'left'}
                        open={mobileOpen}
                        onClose={handleDrawerToggle}
                        classes={{
                            paper: classes.drawerPaper,
                        }}
                        ModalProps={{
                            keepMounted: true, // Better open performance on mobile.
                        }}
                    >
                        <IconButton onClick={handleDrawerToggle} className={classes.closeMenuButton}>
                            <CloseIcon/>
                        </IconButton>
                        {drawer}
                    </Drawer>
                </Hidden>
                <Hidden xsDown implementation="css">
                    <Drawer
                        className={classes.drawer}
                        variant="permanent"
                        classes={{
                            paper: classes.drawerPaper,
                        }}
                    >

                        {drawer}
                    </Drawer>
                </Hidden>

    );
}
NavBar.propTypes = {
    container: PropTypes.object,
};
export default NavBar;```
</div>
</div>
</p>
<p>App.js: NOTE** in App.js, I can add style={{paddingleft:240}} to the div before routes and it kind of remedy this issue, however, once the screen is small enough (i.e.like mobile) view and the drawer is hidden, 240px padding is still there.
(edited down for simplicity - content still the same)</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import React from 'react';
import './App.css';
import { HashRouter as Router, Routes, Route} from 'react-router-dom';

//Page Routes
import NavigationAppBar from "./Navigation-Bar/NavigationAppBar";
import Home from './Page-Information/main';

function App() {
    return (
        <Router>
            <NavigationAppBar/>
            <div>
                <Routes>
                    <Route exact path='/' exact element={<Home />} />
                </Routes>
            </div>
        </Router>
    );
}

export default App;</code>```

Home.js: (edited down for simplicity - content still the same)

import React from 'react';

const Home = () => {
    return (

Example

    );
};

export default Home;```

答: I have forked the default persistent demo updated it into separate files.

Body:
I am trying to write out a website with responsive-based app bar with a drawer tagged onto it. I am using this design found at https://medium.com/@tsubasakondo_36683/create-responsive-drawer-menu-with-react-material-ui-617a42764b69 and modifying it accordingly. But unfortunately, I am getting this issue, in which the drawer covers the portion of the content trying to be displayed. Please know that I have seen similar questions on this site, but I couldn't figure out how to solve them or the answers were kind of vague. Any help would be much appreciated, please let me know if I need to clarify anything further. All of this is using Material UI components.

Here is my code:

Material UI App-Bar

//Used code: https://medium.com/@tsubasakondo_36683/create-responsive-drawer-menu-with-react-material-ui-617a42764b69

//Picture/Icon Imports
import home from "../Icons/home.png";
import about from "../Icons/about.png";
import contact from "../Icons/contact.png";
import resume from "../Icons/resume.png";
import minecraft from "../Icons/minecraft.png";
import github from "../Icons/github.png"

import React from 'react';
import PropTypes from 'prop-types';
import AppBar from '@material-ui/core/AppBar';
import CssBaseline from '@material-ui/core/CssBaseline';
import Drawer from '@material-ui/core/Drawer';
import Hidden from '@material-ui/core/Hidden';
import IconButton from '@material-ui/core/IconButton';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemText from '@material-ui/core/ListItemText';
import MenuIcon from '@material-ui/icons/Menu';
import CloseIcon from '@material-ui/icons/Close';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import { makeStyles, useTheme } from '@material-ui/core/styles';
import {Link} from "react-router-dom";
const drawerWidth = 240;

const useStyles = makeStyles(theme => ({
    root: {
        display: 'flex',
    },
    drawer: {
        [theme.breakpoints.up('sm')]: {
            width: drawerWidth,
            flexShrink: 0,
        },
    },
    appBar: {
        zIndex: theme.zIndex.drawer + 1,
    },
    menuButton: {
        marginRight: theme.spacing(2),
        [theme.breakpoints.up('sm')]: {
            display: 'none',
        },
    },
    toolbar: theme.mixins.toolbar,
    drawerPaper: {
        width: drawerWidth
    },
    content: {
        flexGrow: 1,
        padding: theme.spacing(0),
    },
    closeMenuButton: {
        marginRight: 'auto',
        marginLeft: 0,
    },
}));
function NavBar() {
    const DifferentPages = [
        {Text: "Home", location: "/", Image: home},
        {Text: "About", location: "/about", Image: about},
        {Text: "Contact", location: "/contact", Image: contact},
        {Text: "Resume", location: "/resume", Image: resume},
        {Text: "Minecraft", location: "/minecraft", Image: minecraft},
    ]

    const classes = useStyles();
    const theme = useTheme();
    const [mobileOpen, setMobileOpen] = React.useState(false);
    function handleDrawerToggle() {
        setMobileOpen(!mobileOpen)
    }
    const drawer = (

            <List>
                {DifferentPages.map((Text) => (
                    <ListItem button component={Link} to={Text.location}>

                        <ListItemText primary={Text.Text} />
                    </ListItem>
                ))}
                <ListItem button href={"example.com"}>

                    <ListItemText>
                        Github
                    </ListItemText>
                </ListItem>
            </List>

    );
    return (

            <CssBaseline />
            <AppBar position="fixed" className={classes.appBar}>
                <Toolbar>
                    <IconButton
                        color="inherit"
                        aria-label="Open drawer"
                        edge="start"
                        onClick={handleDrawerToggle}
                        className={classes.menuButton}
                    >
                        <MenuIcon />
                    </IconButton>
                    <Typography variant="h6" noWrap>
                        Responsive drawer
                    </Typography>
                </Toolbar>
            </AppBar>

                <Hidden smUp implementation="css">
                    <Drawer
                        variant="temporary"
                        anchor={theme.direction === 'rtl' ? 'right' : 'left'}
                        open={mobileOpen}
                        onClose={handleDrawerToggle}
                        classes={{
                            paper: classes.drawerPaper,
                        }}
                        ModalProps={{
                            keepMounted: true, // Better open performance on mobile.
                        }}
                    >
                        <IconButton onClick={handleDrawerToggle} className={classes.closeMenuButton}>
                            <CloseIcon/>
                        </IconButton>
                        {drawer}
                    </Drawer>
                </Hidden>
                <Hidden xsDown implementation="css">
                    <Drawer
                        className={classes.drawer}
                        variant="permanent"
                        classes={{
                            paper: classes.drawerPaper,
                        }}
                    >

                        {drawer}
                    </Drawer>
                </Hidden>

    );
}
NavBar.propTypes = {
    container: PropTypes.object,
};
export default NavBar;

App.js: NOTE** in App.js, I can add style={{paddingleft:240}} to the div before routes and it kind of remedy this issue, however, once the screen is small enough (i.e.like mobile) view and the drawer is hidden, 240px padding is still there.
(edited down for simplicity - content still the same)

import React from 'react';
import './App.css';
import { HashRouter as Router, Routes, Route} from 'react-router-dom';

//Page Routes
import NavigationAppBar from "./Navigation-Bar/NavigationAppBar";
import Home from './Page-Information/main';

function App() {
    return (
        <Router>
            <NavigationAppBar/>

                <Routes>
                    <Route exact path='/' exact element={<Home />} />
                </Routes>

        </Router>
    );
}

export default App;

Home.js: (edited down for simplicity - content still the same)

import React from 'react';

const Home = () => {
    return (

Example

    );
};

export default Home;


来源: stackexchange

问:
Count occurrences of a char in a string using Bash
I need to count the number of occurrences of a char in a string using Bash.

In the following example, when the char is (for example) t, it echos the correct number of occurrences of t in var, but when the character is comma or semicolon, it prints out zero:

```<code>var = "text,text,text,text"
num = `expr match $var [,]`
echo "$num"
</code>```

答:
The awk solutions provided here so far all break if there's a line break in your text. E.g.:

```<code>text="one,two,thr
ee,four"
DELIM=','
count=$( awk -F"$DELIM" '{print NF-1}' <<<"${text}" )
echo $count
</code>```

Result:

```<code>2
1
</code>```

The solution that will also work correctly with line breaks is:

```<code>text="one,two,thr
ee,four"
DELIM=','
count=$( awk 'BEGIN{RS="'"$DELIM"'";FS=""}END{print NR-1}' <<<"${text}" )
echo $count
</code>```

Result is 3.

ContentLicense: CC BY-SA 3.0

Body:
I need to count the number of occurrences of a char in a string using Bash.

In the following example, when the char is (for example) t, it echos the correct number of occurrences of t in var, but when the character is comma or semicolon, it prints out zero:

var = "text,text,text,text"
num = `expr match $var [,]`
echo "$num"

Body:
The awk solutions provided here so far all break if there's a line break in your text. E.g.:

text="one,two,thr
ee,four"
DELIM=','
count=$( awk -F"$DELIM" '{print NF-1}' <<<"${text}" )
echo $count

Result:

2
1

The solution that will also work correctly with line breaks is:

text="one,two,thr
ee,four"
DELIM=','
count=$( awk 'BEGIN{RS="'"$DELIM"'";FS=""}END{print NR-1}' <<<"${text}" )
echo $count

Result is 3.

ContentLicense: CC BY-SA 4.0


问:
JSON Post with Customized HTTPHeader Field
I have inherited some code that will eventually be part of an API call. Based on the existing code, the call is a post to retrieve JSON code with an access_token. While this would normally be simple and like every other API out there, this code requires that there be a customized httpheader field for the client secret.

I was able to make this work in Objective C with URLRequest, etc. but now that I am creating the call for a web component, I have been roadblocked.

I am using a pretty standard jquery post

```<code>        $.post('https://url.com',
        {access_token:'XXXXXXXXXXXXXXXXXXX',
         function(data){
           console.info(data);
         }, 'json');
</code>```

With a HTTP-EQUIV in the header. But the post never retrieves data and the server itself doesn't recognized that any call was made (even an incomplete one).

I may have to scrap this code and start over, but if anyone has encountered this problem before, please offer any insight.

答:
What you posted has a syntax error, but it makes no difference as you cannot pass HTTP headers via $.post().

Provided you're on jQuery version >= 1.5, switch to $.ajax() and pass the headers (docs) option. (If you're on an older version of jQuery, I will show you how to do it via the beforeSend option.)

```<code>$.ajax({
    url: 'https://url.com',
    type: 'post',
    data: {
        access_token: 'XXXXXXXXXXXXXXXXXXX'
    },
    headers: {
        Header_Name_One: 'Header Value One',   //If your header name has spaces or any other char not appropriate
        "Header Name Two": 'Header Value Two'  //for object property name, use quoted notation shown in second
    },
    dataType: 'json',
    success: function (data) {
        console.info(data);
    }
});
</code>```

Body:
I have inherited some code that will eventually be part of an API call. Based on the existing code, the call is a post to retrieve JSON code with an access_token. While this would normally be simple and like every other API out there, this code requires that there be a customized httpheader field for the client secret.

I was able to make this work in Objective C with URLRequest, etc. but now that I am creating the call for a web component, I have been roadblocked.

I am using a pretty standard jquery post

        $.post('https://url.com',
        {access_token:'XXXXXXXXXXXXXXXXXXX',
         function(data){
           console.info(data);
         }, 'json');

With a HTTP-EQUIV in the header. But the post never retrieves data and the server itself doesn't recognized that any call was made (even an incomplete one).

I may have to scrap this code and start over, but if anyone has encountered this problem before, please offer any insight.

Body:
What you posted has a syntax error, but it makes no difference as you cannot pass HTTP headers via $.post().

Provided you're on jQuery version >= 1.5, switch to $.ajax() and pass the headers (docs) option. (If you're on an older version of jQuery, I will show you how to do it via the beforeSend option.)

$.ajax({
    url: 'https://url.com',
    type: 'post',
    data: {
        access_token: 'XXXXXXXXXXXXXXXXXXX'
    },
    headers: {
        Header_Name_One: 'Header Value One',   //If your header name has spaces or any other char not appropriate
        "Header Name Two": 'Header Value Two'  //for object property name, use quoted notation shown in second
    },
    dataType: 'json',
    success: function (data) {
        console.info(data);
    }
});


问:
Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code
```<code>Showing Recent Messages:-1: mkdir -p /Users/spritzindia/Library/Developer/Xcode/DerivedData/Contigo-atftiouzrdopcmcpprphpilawwzm/Build/Products/Debug-iphonesimulator/Contigo.app/Frameworks

Showing Recent Messages:-1: rsync --delete -av --filter P .*.?????? --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "/Users/pothi/Library/Developer/Xcode/DerivedData/Contigo-atftiouzrdopcmcpprphpilawwzm/Build/Products/Debug-iphonesimulator/IQKeyboardManagerSwift/IQKeyboardManagerSwift.framework" "/Users/pothi/Library/Developer/Xcode/DerivedData/Contigo-atftiouzrdopcmcpprphpilawwzm/Build/Products/Debug-iphonesimulator/Contigo.app/Frameworks"
</code>```

Command PhaseScriptExecution failed with a nonzero exit code

I deleted derived data.
i have tried :

keychain access -> right click on login -> lock & unlock again ->
  clear Xcode project

Restarted machine, no use

How do I resolve "Command PhaseScriptExecution failed with a nonzero exit code" error when trying to archive project.

And I am using those librarys

```<code>pod 'IQKeyboardManagerSwift'
pod 'SDWebImage', '~> 4.0'
pod 'KRPullLoader'
pod 'Paytm-Payments'
</code>```

答:
I encountered this error in the context of a React-Native project running on iOS. I did several things so it's hard to know which one fixed it:

Make sure you don't have errors in your bash or zshrc profile -> I had a error related to my jdk. You will know if when opening a terminal window it shows an error/warning

Make sure you don't have spaces in the path

If you are using Firebase, make sure your GoogleService-Info file is in the ios folder and not in the ios>project folder

Do not keep the project in an iCloud folder, especially if you are low on space. I suspect this was a big factor for mine

Finally, my worked when doing these and running react-native 0.67.2. The newer version on it's own didn't fix it, I had to do at least one of these other assertions to get it working.

Things to consider:

Running the project in Xcode will usually give you more insight into the problem

Clearing the Xcode build folder wasn't enough on it's own to fix it but when trying a potential solution it is important you do it (and potentially also pod deintegrate && pod install) to make sure there are no traces of the previous ios build.

I am running node version 16.13, running node 17 gave me different errors and I wouldn't recommend it to date.
I am running macOS Monterrey and Xcode 13.2.1, but I tried on BigSur and also Xcode 12.5.1 and the still got the error.

For react-native, this error is discussed in length here: https://github.com/facebook/react-native/issues/31181

Body:
Showing Recent Messages:-1: mkdir -p /Users/spritzindia/Library/Developer/Xcode/DerivedData/Contigo-atftiouzrdopcmcpprphpilawwzm/Build/Products/Debug-iphonesimulator/Contigo.app/Frameworks

Showing Recent Messages:-1: rsync --delete -av --filter P .*.?????? --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "/Users/pothi/Library/Developer/Xcode/DerivedData/Contigo-atftiouzrdopcmcpprphpilawwzm/Build/Products/Debug-iphonesimulator/IQKeyboardManagerSwift/IQKeyboardManagerSwift.framework" "/Users/pothi/Library/Developer/Xcode/DerivedData/Contigo-atftiouzrdopcmcpprphpilawwzm/Build/Products/Debug-iphonesimulator/Contigo.app/Frameworks"

Command PhaseScriptExecution failed with a nonzero exit code

I deleted derived data.
i have tried :

keychain access -> right click on login -> lock & unlock again ->
  clear Xcode project

Restarted machine, no use

How do I resolve "Command PhaseScriptExecution failed with a nonzero exit code" error when trying to archive project.

And I am using those librarys

pod 'IQKeyboardManagerSwift'
pod 'SDWebImage', '~> 4.0'
pod 'KRPullLoader'
pod 'Paytm-Payments'


问:
Using MySQL JDBC driver inside Gradle issue?
I am trying to learn how to use Gradle with Java and am starting a brand new project.  I am trying to connect to a database.

My build.gradle file is

```<code>plugins {
    id 'java'
}

repositories {
    mavenCentral()
}

jar {
    manifest {
        attributes 'Main-Class': 'com.brian.Application'
    }
}

dependencies {
    testImplementation 'junit:junit:4.13.2'
    implementation 'mysql:mysql-connector-java:8.0.25'
}

group 'org.brian'
version '1.0-SNAPSHOT'
</code>```

File com.brian.Application is

```<code>package com.brian;

public class Application {
    public static void main(String[] args) {
        DBConnection.runDBTest();
    }
}
</code>```

And my DBConnection is

```<code>package com.brian;

import java.sql.*;

public class DBConnection {
    private static String url = "jdbc:mysql://localhost:3306/RecipeCollection";
    private static String driverName = "com.mysql.cj.jdbc.Driver";
    private static String username = "RecipeCurator";
    private static String password = "Sup3rYumm!";
    private static Connection con;
    private static String urlstring;

    public static Connection getConnection() {
        try {
            Class.forName(driverName);
            try {
                con = DriverManager.getConnection(url, username, password);
            } catch (SQLException e) {
//                System.out.println("Failed to create database connection");
                e.printStackTrace();
            }
        } catch (ClassNotFoundException e) {
            System.out.println("Could not find driver for " + driverName);
            e.printStackTrace();
        }
        return con;
    }

    public static void runDBTest() {
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;
        con = DBConnection.getConnection();
        try {
            stmt = con.createStatement();
            rs = stmt.executeQuery("SELECT 1");
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("Something went wrong");
        }
        System.out.println(rs);
    }
}
</code>```

When I do ./gradlew build it builds successfully.

When I try to run it with java -jar build/libs/recipe-curator-1.0-SNAPSHOT.jar I get this error

```<code>Could not find driver for com.mysql.cj.jdbc.Driver
java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
    at java.base/java.lang.Class.forName0(Native Method)
    at java.base/java.lang.Class.forName(Class.java:315)
    at com.brian.DBConnection.getConnection(DBConnection.java:15)
    at com.brian.DBConnection.runDBTest(DBConnection.java:33)
    at com.brian.Application.main(Application.java:5)
Exception in thread "main" java.lang.NullPointerException
    at com.brian.DBConnection.runDBTest(DBConnection.java:35)
    at com.brian.Application.main(Application.java:5)
</code>```

I am not sure what is going on since I have mysql as a dependency and the build seems to work fine that this does not run.  What am I doing wrong?

答:
This is because Java does not know where to load the MySQL driver class from. The JAR created by your build does not have a Class-Path header that mentions the JAR files (like the MySQL Connector/J JAR) that it needs to run.

You could try and configure jar to populate Class-Path to cite the required JARs. Here is an example that works with Gradle 7.3.3

```<code>jar {
    manifest {
        attributes(
                "Main-Class": "com.brian.Application",
                'Class-Path': configurations.runtimeClasspath.files.collect { it.name }.join(' ')
        )
    }
}
</code>```

This will give you Class-Path: mysql-connector-java-8.0.25.jar protobuf-java-3.11.4.jar in META-INF/MANIFEST.MF inside build/libs/recipe-curator-1.0-SNAPSHOT.jar. What it does not do is make sure that the required JARs are in the same location (build/libs).

A simpler alternative is to use Gradle's Application plugin, which helps you create a distribution that includes a runner script for Windows and Unix.

Add id 'application' to the plugins closure

Replace the jar closure with the following

```<code>application {
    mainClass.set('com.brian.Application')
}
</code>```

Then just run ./gradlew build installDist. This will create tar and zip distributions under build/distributions and also install a distribution under build/install/recipe-curator. You can then run build/install/recipe-curator/bin/recipe-curator on Unix-like systems (or build\install\recipe-curator\bin\recipe-curator.bat on Windows).

Body:
I am trying to learn how to use Gradle with Java and am starting a brand new project.  I am trying to connect to a database.

My build.gradle file is

plugins {
    id 'java'
}

repositories {
    mavenCentral()
}

jar {
    manifest {
        attributes 'Main-Class': 'com.brian.Application'
    }
}

dependencies {
    testImplementation 'junit:junit:4.13.2'
    implementation 'mysql:mysql-connector-java:8.0.25'
}

group 'org.brian'
version '1.0-SNAPSHOT'

File com.brian.Application is

package com.brian;

public class Application {
    public static void main(String[] args) {
        DBConnection.runDBTest();
    }
}

And my DBConnection is

package com.brian;

import java.sql.*;

public class DBConnection {
    private static String url = "jdbc:mysql://localhost:3306/RecipeCollection";
    private static String driverName = "com.mysql.cj.jdbc.Driver";
    private static String username = "RecipeCurator";
    private static String password = "Sup3rYumm!";
    private static Connection con;
    private static String urlstring;

    public static Connection getConnection() {
        try {
            Class.forName(driverName);
            try {
                con = DriverManager.getConnection(url, username, password);
            } catch (SQLException e) {
//                System.out.println("Failed to create database connection");
                e.printStackTrace();
            }
        } catch (ClassNotFoundException e) {
            System.out.println("Could not find driver for " + driverName);
            e.printStackTrace();
        }
        return con;
    }

    public static void runDBTest() {
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;
        con = DBConnection.getConnection();
        try {
            stmt = con.createStatement();
            rs = stmt.executeQuery("SELECT 1");
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("Something went wrong");
        }
        System.out.println(rs);
    }
}

When I do ./gradlew build it builds successfully.

When I try to run it with java -jar build/libs/recipe-curator-1.0-SNAPSHOT.jar I get this error

Could not find driver for com.mysql.cj.jdbc.Driver
java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
    at java.base/java.lang.Class.forName0(Native Method)
    at java.base/java.lang.Class.forName(Class.java:315)
    at com.brian.DBConnection.getConnection(DBConnection.java:15)
    at com.brian.DBConnection.runDBTest(DBConnection.java:33)
    at com.brian.Application.main(Application.java:5)
Exception in thread "main" java.lang.NullPointerException
    at com.brian.DBConnection.runDBTest(DBConnection.java:35)
    at com.brian.Application.main(Application.java:5)

I am not sure what is going on since I have mysql as a dependency and the build seems to work fine that this does not run.  What am I doing wrong?

Body:
This is because Java does not know where to load the MySQL driver class from. The JAR created by your build does not have a Class-Path header that mentions the JAR files (like the MySQL Connector/J JAR) that it needs to run.

You could try and configure jar to populate Class-Path to cite the required JARs. Here is an example that works with Gradle 7.3.3

jar {
    manifest {
        attributes(
                "Main-Class": "com.brian.Application",
                'Class-Path': configurations.runtimeClasspath.files.collect { it.name }.join(' ')
        )
    }
}

This will give you Class-Path: mysql-connector-java-8.0.25.jar protobuf-java-3.11.4.jar in META-INF/MANIFEST.MF inside build/libs/recipe-curator-1.0-SNAPSHOT.jar. What it does not do is make sure that the required JARs are in the same location (build/libs).

A simpler alternative is to use Gradle's Application plugin, which helps you create a distribution that includes a runner script for Windows and Unix.

Add id 'application' to the plugins closure

Replace the jar closure with the following

application {
    mainClass.set('com.brian.Application')
}

Then just run ./gradlew build installDist. This will create tar and zip distributions under build/distributions and also install a distribution under build/install/recipe-curator. You can then run build/install/recipe-curator/bin/recipe-curator on Unix-like systems (or build\install\recipe-curator\bin\recipe-curator.bat on Windows).


问:
In for loops, is there a way to execute a module function with attributes assigned by the for loop?
Python 3.10.1

Totally new to programming, please be patient.

I want to print a list of all foreground colors available in the colorama module in the color named, like so:

PowerShell Colors

My attempt:

```<code>from colorama import init, Fore, Style
init()

# available foreground colors acquired via dir(Fore)
colors = [
    'BLACK',
    'BLUE',
    'CYAN',
    'GREEN',
    'LIGHTBLACK_EX',
    'LIGHTBLUE_EX',
    'LIGHTCYAN_EX',
    'LIGHTGREEN_EX',
    'LIGHTMAGENTA_EX',
    'LIGHTRED_EX',
    'LIGHTWHITE_EX',
    'LIGHTYELLOW_EX',
    'MAGENTA',
    'RED',
    'WHITE',
    'YELLOW'
]

for col in colors:
    fcol = "Fore." + col
    print(f"  {exec(fcol)}[{col}]{Style.RESET_ALL}")
</code>```

My output (no color changes):

```<code>  None[BLACK]
  None[BLUE]
  None[CYAN]
  None[GREEN]
  None[LIGHTBLACK_EX]
  None[LIGHTBLUE_EX]
  None[LIGHTCYAN_EX]
  None[LIGHTGREEN_EX]
  None[LIGHTMAGENTA_EX]
  None[LIGHTRED_EX]
  None[LIGHTWHITE_EX]
  None[LIGHTYELLOW_EX]
  None[MAGENTA]
  None[RED]
  None[WHITE]
  None[YELLOW]
</code>```

答:
What's happening here is when you assign:

```<code>"Fore." + col
</code>```

to the fcol variable, it is stored as a string. This means that when you try to run it, it would be treated like a string and not a function.
What you did is correct, but you just have to add an eval() function so that Python evaluates your Fore.col as a function.

```<code>for col in colors:
    fcol = "Fore." + col
    fcol = eval(fcol)
</code>```

Also, you used the exec() function incorrectly in the last line. It should be done like this:

```<code>print(f"{fcol}[{col}]{Style.RESET_ALL}")
</code>```

A simple way of doing this would be:

```<code>print(fcol+ col, Style.RESET_ALL)
</code>```

Body:
Python 3.10.1

Totally new to programming, please be patient.

I want to print a list of all foreground colors available in the colorama module in the color named, like so:

PowerShell Colors

My attempt:

from colorama import init, Fore, Style
init()

# available foreground colors acquired via dir(Fore)
colors = [
    'BLACK',
    'BLUE',
    'CYAN',
    'GREEN',
    'LIGHTBLACK_EX',
    'LIGHTBLUE_EX',
    'LIGHTCYAN_EX',
    'LIGHTGREEN_EX',
    'LIGHTMAGENTA_EX',
    'LIGHTRED_EX',
    'LIGHTWHITE_EX',
    'LIGHTYELLOW_EX',
    'MAGENTA',
    'RED',
    'WHITE',
    'YELLOW'
]

for col in colors:
    fcol = "Fore." + col
    print(f"  {exec(fcol)}[{col}]{Style.RESET_ALL}")

My output (no color changes):

  None[BLACK]
  None[BLUE]
  None[CYAN]
  None[GREEN]
  None[LIGHTBLACK_EX]
  None[LIGHTBLUE_EX]
  None[LIGHTCYAN_EX]
  None[LIGHTGREEN_EX]
  None[LIGHTMAGENTA_EX]
  None[LIGHTRED_EX]
  None[LIGHTWHITE_EX]
  None[LIGHTYELLOW_EX]
  None[MAGENTA]
  None[RED]
  None[WHITE]
  None[YELLOW]

Body:
What's happening here is when you assign:

"Fore." + col

to the fcol variable, it is stored as a string. This means that when you try to run it, it would be treated like a string and not a function.
What you did is correct, but you just have to add an eval() function so that Python evaluates your Fore.col as a function.

for col in colors:
    fcol = "Fore." + col
    fcol = eval(fcol)

Also, you used the exec() function incorrectly in the last line. It should be done like this:

print(f"{fcol}[{col}]{Style.RESET_ALL}")

A simple way of doing this would be:

print(fcol+ col, Style.RESET_ALL)


问:
How to reach outside of a div in an HTMLDivElement object with Javascript
I have several HTML elements that represent tiles to be flipped on click. Each element has a container div, which holds two divs, one for the front and back of the tile.

```<code><div class="flip-container" data-tile>
    <div class="flipper">
      <div class="front white">
        <!-- front content -->
      </div>
      <div class="back blue">
        <!-- back content -->
      </div>
    </div>
  </div>
</code>```

I have the animation worked out in CSS so the tiles "flip" on hover. So far so good. Now I am trying to change the classList of the "flip-container" on click, so that a different className will be called from my style sheet.

My problem is that my handleClick function is targeting only the inner-div "back-blue", and not the "flip-container" that is holding both divs.

```<code>const tileData = document.querySelectorAll('[data-tile]')
const flipContainers = Array.from(
  document.getElementsByClassName('flip-container')
)

flipContainers.forEach((container) => {
  container.addEventListener('click', handleClick, { once: true })
})

function handleClick(e) {
  console.log('clicked')
  const container = e.target
  const currentClassColor = 'blue'
  fixColor(container, currentClassColor)
}

function fixColor(container, currentClassColor) {
  container.classList.add(currentClass)
}
</code>```

I have tried querying the "flip-container" both by selecting the data tag and also by grabbing an array from the specific className. In both cases, the entire element is still grabbed, and the target of the click applies only to the inner div. I guess it makes sense why this happening, but is there a way I can access the container even if the click target is one of the inner divs?

答:
e.target is the div that was clicked, if you want the div that the event handler is attached to you can use the this keyword or e.currentTarget.

```<code>function handleClick(e) {
  console.log('clicked')
  // const container = this
  const container = e.currentTarget
  const currentClassColor = 'blue'
  fixColor(container, currentClassColor)
}
</code>```

Body:
I have several HTML elements that represent tiles to be flipped on click. Each element has a container div, which holds two divs, one for the front and back of the tile.

I have the animation worked out in CSS so the tiles "flip" on hover. So far so good. Now I am trying to change the classList of the "flip-container" on click, so that a different className will be called from my style sheet.

My problem is that my handleClick function is targeting only the inner-div "back-blue", and not the "flip-container" that is holding both divs.

const tileData = document.querySelectorAll('[data-tile]')
const flipContainers = Array.from(
  document.getElementsByClassName('flip-container')
)

flipContainers.forEach((container) => {
  container.addEventListener('click', handleClick, { once: true })
})

function handleClick(e) {
  console.log('clicked')
  const container = e.target
  const currentClassColor = 'blue'
  fixColor(container, currentClassColor)
}

function fixColor(container, currentClassColor) {
  container.classList.add(currentClass)
}

I have tried querying the "flip-container" both by selecting the data tag and also by grabbing an array from the specific className. In both cases, the entire element is still grabbed, and the target of the click applies only to the inner div. I guess it makes sense why this happening, but is there a way I can access the container even if the click target is one of the inner divs?

Body:
e.target is the div that was clicked, if you want the div that the event handler is attached to you can use the this keyword or e.currentTarget.

function handleClick(e) {
  console.log('clicked')
  // const container = this
  const container = e.currentTarget
  const currentClassColor = 'blue'
  fixColor(container, currentClassColor)
}


问:
Is running git update-index --refresh from PS1 prompt safe?
I've been researching the fastest way to check for changes in a repo to update the PS1 prompt. For reasons not worth elaborating, no access to the __git_ps1() macro, and anyway other posts have suggested various commands, including those used in __git_ps1().

Reason: I'm accessing repos on a remote server over VPN & ssh, with the remote repo tunnelled back through my connection to our in-house git server. I'm guessing (but really not sure if this is true) that this may be the reason that on a fresh connection on a new day, cd'ing into a repo on this remote server can cause git ls-files -m to take 3 or 4 seconds to complete, and still take up to 1 second after file caching has helped.

To improve this I found git diff-index --quiet HEAD is almost instant, but the next day it starts returning '1' even though there are actually no changes (no output from a very slow run of git status). I've found that git update-index --refresh -q seems to fix the issue (quickly) and also returns '0' if in fact there are no changes.

From what I've read I think it should be safe to run from PS1 prompt, but I understand this is a "lower level" git command and I may not be understanding all the implications. So, to be clear, I've currently got the following to check for changes, which always seems to be quick, but after a day starts outputting '*' in clean repos.

```<code>if git diff-index --quiet HEAD 2>/dev/null && [[ -z "$(git ls-files --others --exclude-standard --directory --no-empty-directory)" ]]
    then echo -n " "
    else echo -n " *"
fi
</code>```

Can any "git gurus" out there see a problem with changing 1st test to git update-index --refresh -q?

答:
It should work, except when use in a Git LFS (Large File Storage) where, as explained here, it can trigger racy timestamps.

That is why, with Git 2.36 (Q2 2022), "git update-index --refresh"(man) has been taught to deal better with racy timestamps (just like "git status"(man) already does).

See commit 2ede073, commit 9b71efd, commit 0275e4d, commit ab6245b (07 Jan 2022) by Marc Strapetz (mstrap).

(Merged by Junio C Hamano -- gitster -- in commit ee52b35, 05 Feb 2022)

update-index: refresh should rewrite index in case of racy timestamps

Signed-off-by: Marc Strapetz

'git update-index --refresh'(man) and '--really-refresh' should force writing of the index file if racy timestamps have been encountered, as 'git status'(man) already does.

Note that calling 'git update-index --refresh' still does not guarantee that there will be no more racy timestamps afterwards (the same holds true for 'git status'): - calling 'git update-index --refresh' immediately after touching and adding a file may still leave racy timestamps if all three operations occur within the racy-tolerance (usually 1 second unless USE_NSEC has been defined) - calling 'git update-index --refresh' for timestamps which are set into the future will leave them racy

To guarantee that such racy timestamps will be resolved would require to wait until the system clock has passed beyond these timestamps and only then write the index file.

Especially for future timestamps, this does not seem feasible because of possibly long delays/hangs.

Body:
I've been researching the fastest way to check for changes in a repo to update the PS1 prompt. For reasons not worth elaborating, no access to the __git_ps1() macro, and anyway other posts have suggested various commands, including those used in __git_ps1().

Reason: I'm accessing repos on a remote server over VPN & ssh, with the remote repo tunnelled back through my connection to our in-house git server. I'm guessing (but really not sure if this is true) that this may be the reason that on a fresh connection on a new day, cd'ing into a repo on this remote server can cause git ls-files -m to take 3 or 4 seconds to complete, and still take up to 1 second after file caching has helped.

To improve this I found git diff-index --quiet HEAD is almost instant, but the next day it starts returning '1' even though there are actually no changes (no output from a very slow run of git status). I've found that git update-index --refresh -q seems to fix the issue (quickly) and also returns '0' if in fact there are no changes.

From what I've read I think it should be safe to run from PS1 prompt, but I understand this is a "lower level" git command and I may not be understanding all the implications. So, to be clear, I've currently got the following to check for changes, which always seems to be quick, but after a day starts outputting '*' in clean repos.

if git diff-index --quiet HEAD 2>/dev/null && [[ -z "$(git ls-files --others --exclude-standard --directory --no-empty-directory)" ]]
    then echo -n " "
    else echo -n " *"
fi

Can any "git gurus" out there see a problem with changing 1st test to git update-index --refresh -q?


问:
Applying a half-gaussian filter to binned time series data in python
I am binning some time series data, I need to apply a half-normal filter to the binned data.  How can I do this in python?  I've provided a toy example bellow.  I need Xbinned to be smoothed with a half-gaussian filter with std of 0.25 (or what ever).  I'm pretty sure the half gaussian should be facing the forward time direction.</p>
```<code>import numpy as np

X = np.random.randint(2, size=100) #example random process

bin_size =  5

Xbinned = []

for i in range(0, len(X)+1, bin_size):
    Xbinned.append(sum(X[i:i+(bin_size-1)])/bin_size)
</code>```

答:
How to implement half-gaussian filtering

Scipy has a function called scipy.ndimage.gaussian_filter(). It nearly implements what we want here. Unfortunately, there's no option to use a half-gaussian instead of a gaussian. However, scipy is open-source, so we can just take the source code and modify it to be a half-gaussian.

I used this source code, and removed all of the parts that are not needed for this particular case. At the end, I had this:

import scipy.ndimage

def halfgaussian_kernel1d(sigma, radius):
    """
    Computes a 1-D Half-Gaussian convolution kernel.
    """
    sigma2 = sigma * sigma
    x = np.arange(0, radius+1)
    phi_x = np.exp(-0.5 / sigma2 * x ** 2)
    phi_x = phi_x / phi_x.sum()

    return phi_x

def halfgaussian_filter1d(input, sigma, axis=-1, output=None,
                      mode="constant", cval=0.0, truncate=4.0):
    """
    Convolves a 1-D Half-Gaussian convolution kernel.
    """
    sd = float(sigma)
    # make the radius of the filter equal to truncate standard deviations
    lw = int(truncate * sd + 0.5)
    weights = halfgaussian_kernel1d(sigma, lw)
    origin = -lw // 2
    return scipy.ndimage.convolve1d(input, weights, axis, output, mode, cval, origin)
```
<p>A short summary of how this works:</p>
<ol>
<li>First, it generates a convolution kernel. It uses the formula <code>e^(-1/2 * (x/sigma)^2)</code> to generate the gaussian distribution. It keeps going until you're 4 standard deviations away from the center.</li>
<li>Next, it convolves that kernel against your signal. It adjusts the kernel to start at the current timestep instead of being centered on the current timestep.</li>
</ol>
<p>Trying this on your signal, I get a result like this:</p>
<pre class="lang-py prettyprint-override"><code>array([0.59979879, 0.6       , 0.40006707, 0.59993293, 0.79993293,
       0.40013414, 0.20006707, 0.59986586, 0.40006707, 0.4       ,
       0.99979879, 0.00033535, 0.59979879, 0.40006707, 0.00013414,
       0.59979879, 0.20013414, 0.00006707, 0.19993293, 0.59986586])
</code>```

Choice of standard deviation

If you pick a standard deviation of 0.25, that is going to have almost no effect on your signal. Here are the convolution weights it uses: [0.99966465 0.00033535]. In other words, this has less than a 0.1% effect on the signal.

I'd recommend using a larger sigma value.

Off by one error

Also, I want to point out the off-by-one error here:

for i in range(0, len(X)+1, bin_size):
    Xbinned.append(sum(X[i:i+(bin_size-1)])/bin_size)
```
<p>Numpy ranges are not inclusive, so a range of <code>i</code> to <code>i+(bin_size-1)</code> actually captures 4 elements, not 5.</p>
<p>To fix this, you can change it to this:</p>
<pre class="lang-py prettyprint-override"><code>for i in range(0, len(X), bin_size):
    Xbinned.append(X[i:i+bin_size].mean())
</code>```

(Also, I fixed an off-by-one error in the loop specification and used a numpy shortcut for finding the mean.)

Body:
I am binning some time series data, I need to apply a half-normal filter to the binned data.  How can I do this in python?  I've provided a toy example bellow.  I need Xbinned to be smoothed with a half-gaussian filter with std of 0.25 (or what ever).  I'm pretty sure the half gaussian should be facing the forward time direction.

import numpy as np

X = np.random.randint(2, size=100) #example random process

bin_size =  5

Xbinned = []

for i in range(0, len(X)+1, bin_size):
    Xbinned.append(sum(X[i:i+(bin_size-1)])/bin_size)

Body:
How to implement half-gaussian filtering

Scipy has a function called scipy.ndimage.gaussian_filter(). It nearly implements what we want here. Unfortunately, there's no option to use a half-gaussian instead of a gaussian. However, scipy is open-source, so we can just take the source code and modify it to be a half-gaussian.

I used this source code, and removed all of the parts that are not needed for this particular case. At the end, I had this:

import scipy.ndimage

def halfgaussian_kernel1d(sigma, radius):
    """
    Computes a 1-D Half-Gaussian convolution kernel.
    """
    sigma2 = sigma * sigma
    x = np.arange(0, radius+1)
    phi_x = np.exp(-0.5 / sigma2 * x ** 2)
    phi_x = phi_x / phi_x.sum()

    return phi_x

def halfgaussian_filter1d(input, sigma, axis=-1, output=None,
                      mode="constant", cval=0.0, truncate=4.0):
    """
    Convolves a 1-D Half-Gaussian convolution kernel.
    """
    sd = float(sigma)
    # make the radius of the filter equal to truncate standard deviations
    lw = int(truncate * sd + 0.5)
    weights = halfgaussian_kernel1d(sigma, lw)
    origin = -lw // 2
    return scipy.ndimage.convolve1d(input, weights, axis, output, mode, cval, origin)

A short summary of how this works:

First, it generates a convolution kernel. It uses the formula e^(-1/2 * (x/sigma)^2) to generate the gaussian distribution. It keeps going until you're 4 standard deviations away from the center.

Next, it convolves that kernel against your signal. It adjusts the kernel to start at the current timestep instead of being centered on the current timestep.

Trying this on your signal, I get a result like this:

array([0.59979879, 0.6       , 0.40006707, 0.59993293, 0.79993293,
       0.40013414, 0.20006707, 0.59986586, 0.40006707, 0.4       ,
       0.99979879, 0.00033535, 0.59979879, 0.40006707, 0.00013414,
       0.59979879, 0.20013414, 0.00006707, 0.19993293, 0.59986586])

Choice of standard deviation

If you pick a standard deviation of 0.25, that is going to have almost no effect on your signal. Here are the convolution weights it uses: [0.99966465 0.00033535]. In other words, this has less than a 0.1% effect on the signal.

I'd recommend using a larger sigma value.

Off by one error

Also, I want to point out the off-by-one error here:

for i in range(0, len(X)+1, bin_size):
    Xbinned.append(sum(X[i:i+(bin_size-1)])/bin_size)

Numpy ranges are not inclusive, so a range of i to i+(bin_size-1) actually captures 4 elements, not 5.

To fix this, you can change it to this:

for i in range(0, len(X), bin_size):
    Xbinned.append(X[i:i+bin_size].mean())

(Also, I fixed an off-by-one error in the loop specification and used a numpy shortcut for finding the mean.)


问:
Firefox 3 adds spacing to spans with display:inline-block
In my test, I have 2 spans both set to display:inline-block with a border for visibility. Firefox renders space between each span. Even setting margin:0;padding:0; doesn't do anything to fix this. My expectation when setting the inline span element to display:inline-block is that the 2 spans render flush against each other, as if you floated 2 divs left or right. The only "fix" I have found is to add float:left or right to the spans, but that defeats my original purpose of trying not to use floats at all. Any ideas?

Test
Test2
```

答: Not loving this bug. Something you might want to consider though is setting the word-spacing on the container element to -1em. I've just ran into this bug myself so I'm not sure if it's practical but it will hide that space.</p>

OwnerDisplayName: Geuis

OwnerDisplayName: Ryan Mitchell

ContentLicense: CC BY-SA 2.5


问:
HTML Emails Rendering Text Centered in IE
I'm sending a HTML email from Outlook to my mail.live.com account. When I view the results in mail.live.com using Firefox the email looks ok, but when I use IE all the content is centered.

I have added lots of align=left  and inline CSS style='text-align:left' to control it but it doesn't make any difference.

When I load the HTML file directly into IE it's ok; only when viewing from my Live/Hotmail account it is skewed.

Has anyone had this issue?

```<code> <html>
 <body style='background:#333;font-family:arial;text-align:left;'>

        <style>

            #BlueStripe {

                color:#000000;
                background:#113399;
                width:800px;
                height:35px;

            }

            #Content {
                width:800px;

            }
            #LeftContentPanel {
                border:none;

                padding:20px;
                padding-top:5px;
            }

            #LeftContentPanel h1, h2, h3 {
                color:#113399;
                font-family:Arial,Verdana;
                font-weight:normal;
                margin-bottom:5px;

            }
            #LeftContentPanel p {
                margin-top:5px;
            }

            h1, h2 {
                font-weight:normal;
                font-size:22px;
                padding-bottom:0px;

            }
            #RightContentPanel {

                width:220px;
                padding:10px;

                margin-top:10px;
                margin-right:30px;

                color:#fff;

                font-weight:normal;

            }
            #RightContentPanel h1, h2 {
                font-weight:normal;
                font-size:20px;
                margin-top:5px;
                margin-bottom:-5px;

            }

            #RightContentPanel p {
                font-weight:normal;
                font-size:14px;

            }

            .edition {
                text-align:left;
                font-family:Arial,Verdana;
                font-weight:normal;
                font-size:16px;
                color:#113399;
                margin-left:10px;
                margin-top:15px;

            }

            #FooterText {
                color:#113399;
                font-size:12px;
            }

            p {
                text-align:left;

            }

    </style>

        <table border='0' Id='PageWidth' Style='border:0px;width:800px;background:#fff;text-align:left;' cellpadding=0 cellspacing=0 align='center'>
            <tr>
                <td>
                    <table border='0'  Style='border:0px;width:800px;' cellpadding=0 cellspacing=0 align='left'>

                        <tr Id='BlueStripe' Width='800'>
                            <td ColSpan='3'></td>
                        </tr>

                        <!-- Header -->
                        <tr id='LogoTitle' align='Left'>
                            <!--  Col 1/2 -->   <td align='left'>
                                                    <img src='logo.jpg' alt='club logo' />
                                                </td> <!-- Col 1 -->
                            <!--  Col 2/2 -->   <td class='Panel2' ColSpan='2'>
                                                    <br />
                                                    <img src='title.jpg' alt='club news' />
                                                    <br />
                                                    <br />
                                                    <p class='edition' align='left'>Edition 9 – September 2011</p></td> <!-- Col 2 -->
                        </tr>
                        <!-- Banner Image - Dumb Bells -->
                        <tr Id='BannerImage'  Style='width:800px;'>
                            <!--  Col 1/1 -->
                            <td ColSpan='3' Width='800px' Style='width:800px;text-align:left;' CellSpacing='0' CellPadding='0'  align='Left'>
                                <img src='banner.jpg' alt='Dumb Bells' Width='800px' />

                            </td> <!-- Col 1 -->
                        </tr>
                        <tr Id='Content' align='Left'>
                            <!--  Col 1/1 -->
                            <td ColSpan='3'>
                                <br />
                                <table id='ContentPanel' Style='margin-top:10px'>
                                    <tr  align='Left'>
                                        <td align='Left'>
                                            <table id='' Style='border:0;text-align:left' align='left'>
                                                <tr>
                                                    <td Id='LeftContentPanel' Width='460'>
                                                        <h1>Insert heading here</h1>
                                                        <p>
                                                            Vellant enes mo volupition eati amenima ximpor andis es mil mi,
                                                            optate cum in niatqui dellabo. Turiti quos debis demolen dustis
                                                            que peditat iorione quidignimin non con eaquatia nullore perit,
                                                            totat incimol orrum, coriassequo quia aut eos unt quia dolent
                                                            estemquodio odionseque esed que dolupta sperror sit quia que
                                                            pa dipsape llore, nitiis audi de nonse nisqui quia velit estem rem
                                                            quam rerum autem voluptiae atur?
                                                        </p>
                                                        <h1>Insert heading here</h1>
                                                        <p>
                                                            Feremos quisinte siment. Cium volorpo ressit re, omnisci as
                                                            autent as moluptas nonsece atquaessit eum dolut aut quis
                                                            nobisto quat aborem quis antempore, id moluptatur, sa que et
                                                            ea ium apis delignisi te si aut poribus ullaudae od quia conem
                                                            se verepud itatemporum ulparum re, volut velis eatis es accum
                                                            aut ratur, vende ius si doloriorum ent qui que velesciat que nam,
                                                            alitem ati a non remperorest restrum volentintem voluptatur am
                                                            rem eumqui quat et ea quiame quat.
                                                        </p>
                                                        <p>
                                                            Occatem poreium in rehentio eat el earia iur am, et laborio.
                                                            Itatur? Quiae estiorecese conseque niet estem as etusciur mos
                                                            ipsapid que videbit audit quid ut volupta sperias sequate ctotat
                                                            et et voluptis dellest, simus, secus aute quis iliquis si quia simus.
                                                        </p>

                                                        <div id='FooterText'>
                                                            more text here
                                                        </div>

                                                    </td>
                                                </tr>
                                            </table>

                                        </td>
                                        <td Width=5></td>
                                        <td valign='top' align='left' style='padding:15px;text-align:left'>
                                            <table  Id='RightContentPanel' Style='text-align:left;' >
                                                <tr style='padding:15px;text-align:left'>

                                                    <td style='margin-top:0px;padding:5px;padding:15px;text-align:left;padding-top:5px;   background-color:#113399;'>
                                                            <h1>Insert header here</h1>
                                                            <p align='left' style='text-align:left'>
                                                                Vellant enes mo volupition eati
                                                                amenima ximpor andis es mil
                                                                mi, optate cum in niatqui de
                                                                llabo. Turiti quos debis demo
                                                                len dustis que peditat iorione
                                                                quidignimin non con eaquatia
                                                                nullore perit, totat incimol or
                                                                rum, coriassequo quia aut eos
                                                                unt quia dolent estemquodio.
                                                            </p>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td height='35'>
                                                    </td>
                                                </tr>
                                                <tr>

                                                    <td Style='margin-top:30px;padding-top:5px;padding:5px;padding:15px;text-align:left;background-color:#ff3333;'>
                                                            <h1>Insert header here</h1>
                                                            <p>
                                                                Vellant enes mo volupition eati
                                                                amenima ximpor andis es mil
                                                                mi, optate cum in niatqui de
                                                                llabo. Turiti quos debis demo
                                                                len dustis que peditat iorione
                                                                quidignimin non con eaquatia
                                                                nullore perit, totat incimol or
                                                                rum, coriassequo quia aut eos
                                                                unt quia dolent estemquodio.
                                                            </p>

                                                    </td>
                                                </tr>
                                            </table>

                                        </td>
                                    </tr>
                                </table>

                            </td> <!-- End Col 1 -->

                        </tr>
                        <tr>
                            <td Id='BlueStripe' ColSpan='3'></td>
                        </tr>
                    </table>
                </td>
            </tr>
        </table>
</body>
</code>```

Additional information from another user:

None of the answers so far seem to help. I had my top level stacked tables centered and all the nested tables aligned left with text-align:left; on all possible elements and it didn't change anything.

Then I removed all instances of centered text and tables throughout the code and it STILL renders with centered text in all web email clients in IE 9. Interestingly, if I send the email from Gmail or Yahoo in IE 9, it renders properly (without having to add all the extra align/text-align lefts). However, this email must originate from Outlook, so that isn't a feasible workaround in this case.

答:
As annoying as this sounds, try adding an inline text-align: left; on the paragraph tags.

For future reference, the HTML Email Boilerplate is a great base for those dreaded HTML email projects.

Body:
I'm sending a HTML email from Outlook to my mail.live.com account. When I view the results in mail.live.com using Firefox the email looks ok, but when I use IE all the content is centered.

I have added lots of align=left  and inline CSS style='text-align:left' to control it but it doesn't make any difference.

When I load the HTML file directly into IE it's ok; only when viewing from my Live/Hotmail account it is skewed.

Has anyone had this issue?

Edition 9 – September 2011

Insert heading here

                                                            Vellant enes mo volupition eati amenima ximpor andis es mil mi,
                                                            optate cum in niatqui dellabo. Turiti quos debis demolen dustis
                                                            que peditat iorione quidignimin non con eaquatia nullore perit,
                                                            totat incimol orrum, coriassequo quia aut eos unt quia dolent
                                                            estemquodio odionseque esed que dolupta sperror sit quia que
                                                            pa dipsape llore, nitiis audi de nonse nisqui quia velit estem rem
                                                            quam rerum autem voluptiae atur?

Insert heading here

                                                            Feremos quisinte siment. Cium volorpo ressit re, omnisci as
                                                            autent as moluptas nonsece atquaessit eum dolut aut quis
                                                            nobisto quat aborem quis antempore, id moluptatur, sa que et
                                                            ea ium apis delignisi te si aut poribus ullaudae od quia conem
                                                            se verepud itatemporum ulparum re, volut velis eatis es accum
                                                            aut ratur, vende ius si doloriorum ent qui que velesciat que nam,
                                                            alitem ati a non remperorest restrum volentintem voluptatur am
                                                            rem eumqui quat et ea quiame quat.

                                                            Occatem poreium in rehentio eat el earia iur am, et laborio.
                                                            Itatur? Quiae estiorecese conseque niet estem as etusciur mos
                                                            ipsapid que videbit audit quid ut volupta sperias sequate ctotat
                                                            et et voluptis dellest, simus, secus aute quis iliquis si quia simus.

                                                            more text here

Insert header here

                                                                Vellant enes mo volupition eati
                                                                amenima ximpor andis es mil
                                                                mi, optate cum in niatqui de
                                                                llabo. Turiti quos debis demo
                                                                len dustis que peditat iorione
                                                                quidignimin non con eaquatia
                                                                nullore perit, totat incimol or
                                                                rum, coriassequo quia aut eos
                                                                unt quia dolent estemquodio.

Insert header here

                                                                Vellant enes mo volupition eati
                                                                amenima ximpor andis es mil
                                                                mi, optate cum in niatqui de
                                                                llabo. Turiti quos debis demo
                                                                len dustis que peditat iorione
                                                                quidignimin non con eaquatia
                                                                nullore perit, totat incimol or
                                                                rum, coriassequo quia aut eos
                                                                unt quia dolent estemquodio.

Additional information from another user:

None of the answers so far seem to help. I had my top level stacked tables centered and all the nested tables aligned left with text-align:left; on all possible elements and it didn't change anything.

Then I removed all instances of centered text and tables throughout the code and it STILL renders with centered text in all web email clients in IE 9. Interestingly, if I send the email from Gmail or Yahoo in IE 9, it renders properly (without having to add all the extra align/text-align lefts). However, this email must originate from Outlook, so that isn't a feasible workaround in this case.


问:
In Python how to obtain a partial view of a dict?
Is it possible to get a partial view of a dict in Python analogous of pandas df.tail()/df.head(). Say you have a very long dict, and you just want to check some of the elements (the beginning, the end, etc) of the dict. Something like:

```<code>dict.head(3)  # To see the first 3 elements of the dictionary.

{[1,2], [2, 3], [3, 4]}
</code>```

Thanks

Body:
Is it possible to get a partial view of a dict in Python analogous of pandas df.tail()/df.head(). Say you have a very long dict, and you just want to check some of the elements (the beginning, the end, etc) of the dict. Something like:

dict.head(3)  # To see the first 3 elements of the dictionary.

{[1,2], [2, 3], [3, 4]}

Thanks

Body:
d = {"a": 1,"b": 2,"c": 3}
for i in list(d.items())[:2]:
     print('{}:{}'.format(d[i][0], d[i][1]))

a:1
b:2


问:
Why is this Warning showing when I try to debug my Flutter application
This is not an error, this warning showing when I run or Debugging my app,

```<code>Warning: Mapping new ns http://schemas.android.com/repository/android/generic/02 to old ns http://schemas.android.com/repository/android/generic/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/addon2/02 to old ns http://schemas.android.com/sdk/android/repo/addon2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/repository2/02 to old ns http://schemas.android.com/sdk/android/repo/repository2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/sys-img2/02 to old ns http://schemas.android.com/sdk/android/repo/sys-img2/01
</code>```

how do I fix and what's the exact problem is this?

答:
Try upgrading the gradle wrapper version (gradle-wrapper.properties) and the gradle plugin version (/android/build.gradle) to the latest ones.

In gradle-wrapper.properties:

```<code>distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-all.zip
</code>```

In /android/build.gradle:

```<code>classpath 'com.android.tools.build:gradle:7.1.0'
</code>```

Body:
This is not an error, this warning showing when I run or Debugging my app,

Warning: Mapping new ns http://schemas.android.com/repository/android/generic/02 to old ns http://schemas.android.com/repository/android/generic/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/addon2/02 to old ns http://schemas.android.com/sdk/android/repo/addon2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/repository2/02 to old ns http://schemas.android.com/sdk/android/repo/repository2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/sys-img2/02 to old ns http://schemas.android.com/sdk/android/repo/sys-img2/01

how do I fix and what's the exact problem is this?

Body:
Try upgrading the gradle wrapper version (gradle-wrapper.properties) and the gradle plugin version (/android/build.gradle) to the latest ones.

In gradle-wrapper.properties:

distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-all.zip

In /android/build.gradle:

classpath 'com.android.tools.build:gradle:7.1.0'


问:
Class not found Java
I created artifacts and when starting the program I get the error Class com.abstudio.fakture.MainActivity not found.
When I run a program through the IDE it does everything right.

IDE: Intelij IDEA
JavaFX
Java 8

Manifest file:

```<code>Manifest-Version: 1.0
Main-Class: com.abstudio.fakture.MainActivity
</code>```

MainActivity is in path: src/main/java/com/abstudio/fakture/MainActivity

When in cmd I run the command "jar tf ePDV.jar"
i see that the com/abstudio/fakture/MainActivity  path is compiled with other classes, interfaces, etc.

My build.gradle file:

```<code>plugins {
    id 'java'
    id 'application'
    id 'idea'
}
sourceCompatibility = JavaVersion.VERSION_1_8
group 'org.example'
version '1.0-SNAPSHOT'

repositories {
    mavenCentral()
}
compileJava.options.encoding = 'UTF-8'
tasks.withType(JavaCompile) {
    options.encoding = 'UTF-8'
}
jar {
    manifest {
        attributes(
                'Main-Class': 'com.abstudio.fakture.MainActivity'
        )
    }
}
sourceSets.main {
    java {
        srcDir 'src/main/java' //assume that your source codes are inside this path
    }
    resources {
        srcDirs = ['src/main/java', 'src/main/resources']
        exclude "**/*.java"
    }
}

dependencies {
    testImplementation group: 'junit', name: 'junit', version: '4.12'
    implementation 'com.jfoenix:jfoenix:8.0.10'
    implementation group: 'de.jensd', name: 'fontawesomefx', version: '8.1'
    // https://mvnrepository.com/artifact/mysql/mysql-connector-java
    implementation group: 'mysql', name: 'mysql-connector-java', version: '8.0.22'
    // https://mvnrepository.com/artifact/com.itextpdf/itextpdf
    implementation group: 'com.itextpdf', name: 'itextpdf', version: '5.5.13.2'

    implementation group: 'org.apache.derby', name: 'derby', version: '10.14.1.0'
// https://mvnrepository.com/artifact/org.controlsfx/controlsfx
    implementation group: 'org.controlsfx', name: 'controlsfx', version: '8.40.18'

    implementation 'org.apache.commons:commons-configuration2:2.7'
    implementation 'commons-io:commons-io:2.11.0'
    implementation 'commons-net:commons-net:3.8.0'

}
mainClassName = 'com.abstudio.fakture.MainActivity'
</code>```

In project structures Application class is com.abstudio.fakture.MainActivity

Artifacts and manifest

Artifacts JavaFX

Compiled classes

How to solve this problem?
Thanks

答:
One way to address this is to simply start over from scratch using an alternate method.

This is not an easy task, but will probably give a decent outcome if you can manage it:

Create a new JavaFX project using the IDE.

Use recent software, JDK 17.0.2 and JavaFX 17.0.2 and jfoenix 9, font awesomefx 9, as well as up-to-date versions of other software.

Use Maven to build the project instead of Gradle, because it is easier unless you really know what you are doing.

Copy your existing code into the project created by the wizard and reimport the updated maven pom to get all the dependencies synchronized.

Update module-info.Java file to define your app module requirements,

The latest versions of most of the libraries you defined will be modular and linkable, ones that are not you will need to patch to add module info.

If it is too difficult to get modularity working, delete the module-info and follow instructions at JPackageScriptFX.

Test and debug until it works.

Do not create a fat jar that includes JavaFX.

Use a jlink zip format via the openjfx-maven-plugin or use jpackage to package the app using JPackageScriptFX.

Because you are sharing similar libraries, also see:

Load custom components in scenebuilder 17

Which has info on the library versions to use and recommended dev approach (a lot of the info in the answer is relevant to you,  regardless of whether you use SceneBuilder on not).

Title: Class not found Java

Body:
I created artifacts and when starting the program I get the error Class com.abstudio.fakture.MainActivity not found.
When I run a program through the IDE it does everything right.

IDE: Intelij IDEA
JavaFX
Java 8

Manifest file:

Manifest-Version: 1.0
Main-Class: com.abstudio.fakture.MainActivity

MainActivity is in path: src/main/java/com/abstudio/fakture/MainActivity

When in cmd I run the command "jar tf ePDV.jar"
i see that the com/abstudio/fakture/MainActivity  path is compiled with other classes, interfaces, etc.

My build.gradle file:

plugins {
    id 'java'
    id 'application'
    id 'idea'
}
sourceCompatibility = JavaVersion.VERSION_1_8
group 'org.example'
version '1.0-SNAPSHOT'

repositories {
    mavenCentral()
}
compileJava.options.encoding = 'UTF-8'
tasks.withType(JavaCompile) {
    options.encoding = 'UTF-8'
}
jar {
    manifest {
        attributes(
                'Main-Class': 'com.abstudio.fakture.MainActivity'
        )
    }
}
sourceSets.main {
    java {
        srcDir 'src/main/java' //assume that your source codes are inside this path
    }
    resources {
        srcDirs = ['src/main/java', 'src/main/resources']
        exclude "**/*.java"
    }
}

dependencies {
    testImplementation group: 'junit', name: 'junit', version: '4.12'
    implementation 'com.jfoenix:jfoenix:8.0.10'
    implementation group: 'de.jensd', name: 'fontawesomefx', version: '8.1'
    // https://mvnrepository.com/artifact/mysql/mysql-connector-java
    implementation group: 'mysql', name: 'mysql-connector-java', version: '8.0.22'
    // https://mvnrepository.com/artifact/com.itextpdf/itextpdf
    implementation group: 'com.itextpdf', name: 'itextpdf', version: '5.5.13.2'

    implementation group: 'org.apache.derby', name: 'derby', version: '10.14.1.0'
// https://mvnrepository.com/artifact/org.controlsfx/controlsfx
    implementation group: 'org.controlsfx', name: 'controlsfx', version: '8.40.18'

    implementation 'org.apache.commons:commons-configuration2:2.7'
    implementation 'commons-io:commons-io:2.11.0'
    implementation 'commons-net:commons-net:3.8.0'

}
mainClassName = 'com.abstudio.fakture.MainActivity'

In project structures Application class is com.abstudio.fakture.MainActivity

Artifacts and manifest

Artifacts JavaFX

Compiled classes

How to solve this problem?
Thanks


问:
DDD - always valid domain
Let's say we have a class Product with one field called name. This field has to be unique in the domain. Each product is persisted to database. In order to fulfill always valid approach, we shouldn't let create Product with a name which already exists in the database.

How can I implement such validation inside the Product class so I wouldn't be instanciated when name is not unique?

The same question can be applied for the changeName method.

```<code>public class Product {
   private String name;
   (...)

   public Product(String name) {
        // check if name is unique
        this.name = name;
   }

   public void changeName(String name) {
        // check if name is unique
        this.name = name;
   }
}
</code>```

So far I found two approaches:

Pass ProductValidator class as the parameter to changeName() which seems weird for me.

Allow to change name of the product and then check the constraints, which violates Always valid approach rule.

Are there any better solutions/patterns to meet the requirements of the always valid approach and meanwhile DDD?

答:
The name for the general problem you are trying to solve is set validation.

The most common answer is: don't try to have that problem.  Consider: what is the business impact of a duplicated product name?  Is it something that must never happen (eg: criminal liability), or is it merely something that will negatively impact our productivity until we fix it?

If it is just something that should get fixed, then detection and escalation is probably a more efficient way to invest your design capital.  That's especially true if the cost of fixing the problem is small.

On the other hand, if duplication has Dire Consequences, then you need to look to designs where the set-of-names is a single thing of its own, and it alone has control over which names are assigned to which products.

In domain driven design terms, the set-of-names must be its own aggregate, responsible for ensuring that this critical invariant is never violated.

This doesn't necessarily means we need all of the domain model ceremony.  Relational databases are really good at set validation, providing you can ensure that the entire set is stored in a single database.

Title: DDD - always valid domain

Body:
Let's say we have a class Product with one field called name. This field has to be unique in the domain. Each product is persisted to database. In order to fulfill always valid approach, we shouldn't let create Product with a name which already exists in the database.

How can I implement such validation inside the Product class so I wouldn't be instanciated when name is not unique?

The same question can be applied for the changeName method.

public class Product {
   private String name;
   (...)

   public Product(String name) {
        // check if name is unique
        this.name = name;
   }

   public void changeName(String name) {
        // check if name is unique
        this.name = name;
   }
}

So far I found two approaches:

Pass ProductValidator class as the parameter to changeName() which seems weird for me.

Allow to change name of the product and then check the constraints, which violates Always valid approach rule.

Are there any better solutions/patterns to meet the requirements of the always valid approach and meanwhile DDD?


问:
React pass fetched data from API to another component
I am fetching few products from an API, and displaying them in card. There is a More Details link on the cards, where if the user clicks on it, it will take the user to the selected product details page. My routing to productDetails page works, But I am having troubles to find a way to pass the fetched data to the productDetails page as props.

This is what I have so far:
My FeaturedProduct.js:

```<code>import React from "react";
import { useState, useEffect } from "react";
import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom";
import ProductDetails from "./ProductDetails";
import axios from "axios";

function FeaturedProduct(props) {
  const [products, setProducts] = useState([]);

  useEffect(() => {
    fetchProducts();
  }, []);

  function fetchProducts() {
    axios
      .get("https://shoppingapiacme.herokuapp.com/shopping")
      .then((res) => {
        console.log(res);
        setProducts(res.data);
      })
      .catch((err) => {
        console.log(err);
      });
  }
  return (
    <div>
      <h1> Your Products List is shown below:</h1>
      <div className="item-container">

        {products.map((product) => (
          <div className="card" key={product.id}>
            {" "}

            <h3>{product.item}</h3>
            <p>
              {product.city}, {product.state}
            </p>
            <Router>
              <Link to="/productdetails">More Details</Link>

              <Switch>
                <Route path="/productdetails" component={ProductDetails} />
              </Switch>
            </Router>
          </div>
        ))}
      </div>
    </div>
  );
}

export default FeaturedProduct;
</code>```

My Product Details Page:

```<code>import React from "react";
import FeaturedProduct from "./FeaturedProduct";

function ProductDetails(props) {
  return (
    <div>
      <div>
        <h1>{props.name}</h1>
        <h1>{props.color}</h1>
      </div>
    </div>
  );
}
export default  ProductDetails;
</code>```

答:
I am still learning but this is what I would do:

```<code><Route path="/productdetails">
  <ProductDetails product={product}/>
</Route>
</code>```

====

On ProductDetails you can destructure the props:

```<code>function ProductDetails(props) {
const {name, color} = props.product;

  return (
    <div>
      <div>
        <h1>{name}</h1>
        <h1>{color}</h1>
      </div>
    </div>
  );
}
export default  ProductDetails;
</code>```

Body:
I am fetching few products from an API, and displaying them in card. There is a More Details link on the cards, where if the user clicks on it, it will take the user to the selected product details page. My routing to productDetails page works, But I am having troubles to find a way to pass the fetched data to the productDetails page as props.

This is what I have so far:
My FeaturedProduct.js:

import React from "react";
import { useState, useEffect } from "react";
import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom";
import ProductDetails from "./ProductDetails";
import axios from "axios";

function FeaturedProduct(props) {
  const [products, setProducts] = useState([]);

  useEffect(() => {
    fetchProducts();
  }, []);

  function fetchProducts() {
    axios
      .get("https://shoppingapiacme.herokuapp.com/shopping")
      .then((res) => {
        console.log(res);
        setProducts(res.data);
      })
      .catch((err) => {
        console.log(err);
      });
  }
  return (

 Your Products List is shown below:

        {products.map((product) => (

            {" "}

{product.item}

              {product.city}, {product.state}

            <Router>
              <Link to="/productdetails">More Details</Link>

              <Switch>
                <Route path="/productdetails" component={ProductDetails} />
              </Switch>
            </Router>

        ))}

  );
}

export default FeaturedProduct;

My Product Details Page:

import React from "react";
import FeaturedProduct from "./FeaturedProduct";

function ProductDetails(props) {
  return (

{props.name}

{props.color}

  );
}
export default  ProductDetails;

Body:
I am still learning but this is what I would do:

<Route path="/productdetails">
  <ProductDetails product={product}/>
</Route>

====

On ProductDetails you can destructure the props:

function ProductDetails(props) {
const {name, color} = props.product;

  return (
    <div>
      <div>
        <h1>{name}</h1>
        <h1>{color}</h1>
      </div>
    </div>
  );
}
export default  ProductDetails;


问:
ASP.NET MVC - Approach for global error handling?
I was wondering what the best implementation for a global error (doesn't have to be errors, can also  be success messages) handler would be? Let me break it down for you with an example:

User tries to delete a record

Deletion fails and an error is logged

User redirects to another page

Display error message for user (using a HtmlHelper or something, don't want it to be a specific error page)

I'm just curious what you guys think. I've been considering TempData, ViewData and Session but they all have their pros and cons.

TIA!

UPDATE:

I'll show an example what I exactly mean, maybe I wasn't clear enough.
This is an example of a method that adds a message when user deletes a record.
If user succeeds, user redirects to another page

```<code>public ActionResult DeleteRecord(Record recordToDelete)
{
    // If user succeeds deleting the record
    if (_service.DeleteRecord(recordToDelete)
    {
        // Add success message
        MessageHandler.AddMessage(Status.SUCCESS, "A message to user");

        // And redirect to list view
        return RedirectToAction("RecordsList");
    }
    else
    {
        // Else return records details view
        return View("RecordDetails", recordToDelete);
    }
}
</code>```

And in the view "RecordsList", it would be kinda cool to show all messages (both error and success messages) in a HtmlHelper or something.

```<code><%= Html.RenderAllMessages %>
</code>```

This can be achieved in many ways, I'm just curious what you guys would do.

UPDATE 2:

I have created a custom error (message) handler. You can see the code if you scroll down.

答:
I prefer writing my server layer as an API emitting JSON - in ASP.NET MVC that's real simple - you just create a bunch of nested anonymous objects, and return Json(data);. The JSON object is then consumed by the client layer, which consists of html, css and javascript (I use jQuery a lot, but you might prefer other tools).

Since javascript is dynamic, it is then real easy to just have a property status on the data object, and the client side script can interpret that and display status or error messages as needed.

For example, consider the following action method:

```<code>public ActionResult ListStuff()
{
    var stuff = Repo.GetStuff();

    return Json(new { status = "OK", thestuff = stuff });
}
</code>```

This will return JSON in the following format:

```<code>{ "status": "OK", "thestuf": [{ ... }, { ... }] }
</code>```

where ... is a placeholder for the properties of stuff. Now, if I want error handling, I can just do

```<code>try
{
    var stuff = Repo.GetStuff();
    return Json(new { status = "OK", thestuff = stuff});
}
catch (Exception ex)
{
    Log.Error(ex);
    return Json(new { status = "Fail", reason = ex.Message });
}
</code>```

Since javascript is dynamic, it doesn't matter that the two anonymous objects don't have the same properties. Based on the value of status, I'll only look for properties that are actually there.

This can be implemented even better if you create your own action result classes, which extend JsonResult and add the status property automatically. For example, you can create one for failed requests that takes an exception in the constructor and one for successful ones than take an anonymous object.

Body:
I was wondering what the best implementation for a global error (doesn't have to be errors, can also  be success messages) handler would be? Let me break it down for you with an example:

User tries to delete a record

Deletion fails and an error is logged

User redirects to another page

Display error message for user (using a HtmlHelper or something, don't want it to be a specific error page)

I'm just curious what you guys think. I've been considering TempData, ViewData and Session but they all have their pros and cons.

TIA!

UPDATE:

I'll show an example what I exactly mean, maybe I wasn't clear enough.
This is an example of a method that adds a message when user deletes a record.
If user succeeds, user redirects to another page

public ActionResult DeleteRecord(Record recordToDelete)
{
    // If user succeeds deleting the record
    if (_service.DeleteRecord(recordToDelete)
    {
        // Add success message
        MessageHandler.AddMessage(Status.SUCCESS, "A message to user");

        // And redirect to list view
        return RedirectToAction("RecordsList");
    }
    else
    {
        // Else return records details view
        return View("RecordDetails", recordToDelete);
    }
}

And in the view "RecordsList", it would be kinda cool to show all messages (both error and success messages) in a HtmlHelper or something.

<%= Html.RenderAllMessages %>

This can be achieved in many ways, I'm just curious what you guys would do.

UPDATE 2:

I have created a custom error (message) handler. You can see the code if you scroll down.

Body:
I prefer writing my server layer as an API emitting JSON - in ASP.NET MVC that's real simple - you just create a bunch of nested anonymous objects, and return Json(data);. The JSON object is then consumed by the client layer, which consists of html, css and javascript (I use jQuery a lot, but you might prefer other tools).

Since javascript is dynamic, it is then real easy to just have a property status on the data object, and the client side script can interpret that and display status or error messages as needed.

For example, consider the following action method:

public ActionResult ListStuff()
{
    var stuff = Repo.GetStuff();

    return Json(new { status = "OK", thestuff = stuff });
}

This will return JSON in the following format:

{ "status": "OK", "thestuf": [{ ... }, { ... }] }

where ... is a placeholder for the properties of stuff. Now, if I want error handling, I can just do

try
{
    var stuff = Repo.GetStuff();
    return Json(new { status = "OK", thestuff = stuff});
}
catch (Exception ex)
{
    Log.Error(ex);
    return Json(new { status = "Fail", reason = ex.Message });
}

Since javascript is dynamic, it doesn't matter that the two anonymous objects don't have the same properties. Based on the value of status, I'll only look for properties that are actually there.

This can be implemented even better if you create your own action result classes, which extend JsonResult and add the status property automatically. For example, you can create one for failed requests that takes an exception in the constructor and one for successful ones than take an anonymous object.