问:
Jasmine - how to test functions that should only be called once (executed via a closure variable)
I'm using a closure to ensure that something is only called once:

```<code>var pageDOM = (function() {
  var mounted = false

  return {
    initializePage: function() {
      if (mounted == false) {
        pageDOM.addBoxes();
        mount = true
      }
      pageDOM.otherInitProcedures();
    },
    otherFunction: function() {
    }
  }
})();
</code>```

I'm not sure what's the right way of thinking about unit testing pageDOM.initializePage. Jasmine specs are run in random order, and I think it's important to keep this for testing integrity (i.e., I would NOT want to impose order). This is my spec code:

```<code>describe("pageDOM", function() {
  describe("initializePage", function() {
    beforeEach(function() {
      spyOn(pageDOM, "addBoxes")
      spyOn(pageDOM, "otherInitProcedures")
    })
    describe("calling initializePage first time", function() {
      beforeEach(function() {
        pageDOM.initializePage();
      })
      it("should call both functions", function() {
        expect(pageDOM.otherInitProcedures).toHaveBeenCalled()
        expect(pageDOM.addBoxes).toHaveBeenCalled()
      })
      describe("calling initializePage again", function() {
        beforeEach(function() {
          pageDOM.initializePage();
        })
        it("should only call otherInitProcedures", function() {
          expect(pageDOM.otherInitProcedures).toHaveBeenCalled()
          expect(pageDOM.addBoxes).not.toHaveBeenCalled()
        })
      })
    })
  })
})
</code>```

The problem is that if the specs don't run in order, then both will fail. What's a way to test this, or should I even try to test this?

答:
I would assign the spies to variables and reset the spies in an afterEach hook.

Something like this (follow the !! in the comments):

```<code>describe("pageDOM", function() {
  describe("initializePage", function() {
    // !! initialize these variables
    let addBoxesSpy;
    let otherInitProceduresSpy;
    beforeEach(function() {
      // !! assign the variables
      addBoxesSpy = spyOn(pageDOM, "addBoxes")
      otherInitProceduresSpy = spyOn(pageDOM, "otherInitProcedures")
    })
    describe("calling initializePage first time", function() {
      beforeEach(function() {
        pageDOM.initializePage();
      })
      it("should call both functions", function() {
        expect(pageDOM.otherInitProcedures).toHaveBeenCalled()
        expect(pageDOM.addBoxes).toHaveBeenCalled()
      })
      describe("calling initializePage again", function() {
        beforeEach(function() {
          pageDOM.initializePage();
        })
        it("should only call otherInitProcedures", function() {
          expect(pageDOM.otherInitProcedures).toHaveBeenCalled()
          expect(pageDOM.addBoxes).not.toHaveBeenCalled()
        })
      })
    })

   // !! Reset the spies in an afterEach
   afterEach(() => {
     addBoxesSpy.calls.reset();
     otherInitProceduresSpy.calls.reset();
   });
  })
})
</code>```

After resetting the calls to what you're spying on, order should not matter anymore.

Body:
I'm using a closure to ensure that something is only called once:

var pageDOM = (function() {
  var mounted = false

  return {
    initializePage: function() {
      if (mounted == false) {
        pageDOM.addBoxes();
        mount = true
      }
      pageDOM.otherInitProcedures();
    },
    otherFunction: function() {
    }
  }
})();

I'm not sure what's the right way of thinking about unit testing pageDOM.initializePage. Jasmine specs are run in random order, and I think it's important to keep this for testing integrity (i.e., I would NOT want to impose order). This is my spec code:

describe("pageDOM", function() {
  describe("initializePage", function() {
    beforeEach(function() {
      spyOn(pageDOM, "addBoxes")
      spyOn(pageDOM, "otherInitProcedures")
    })
    describe("calling initializePage first time", function() {
      beforeEach(function() {
        pageDOM.initializePage();
      })
      it("should call both functions", function() {
        expect(pageDOM.otherInitProcedures).toHaveBeenCalled()
        expect(pageDOM.addBoxes).toHaveBeenCalled()
      })
      describe("calling initializePage again", function() {
        beforeEach(function() {
          pageDOM.initializePage();
        })
        it("should only call otherInitProcedures", function() {
          expect(pageDOM.otherInitProcedures).toHaveBeenCalled()
          expect(pageDOM.addBoxes).not.toHaveBeenCalled()
        })
      })
    })
  })
})

The problem is that if the specs don't run in order, then both will fail. What's a way to test this, or should I even try to test this?

Body:
I would assign the spies to variables and reset the spies in an afterEach hook.

Something like this (follow the !! in the comments):

describe("pageDOM", function() {
  describe("initializePage", function() {
    // !! initialize these variables
    let addBoxesSpy;
    let otherInitProceduresSpy;
    beforeEach(function() {
      // !! assign the variables
      addBoxesSpy = spyOn(pageDOM, "addBoxes")
      otherInitProceduresSpy = spyOn(pageDOM, "otherInitProcedures")
    })
    describe("calling initializePage first time", function() {
      beforeEach(function() {
        pageDOM.initializePage();
      })
      it("should call both functions", function() {
        expect(pageDOM.otherInitProcedures).toHaveBeenCalled()
        expect(pageDOM.addBoxes).toHaveBeenCalled()
      })
      describe("calling initializePage again", function() {
        beforeEach(function() {
          pageDOM.initializePage();
        })
        it("should only call otherInitProcedures", function() {
          expect(pageDOM.otherInitProcedures).toHaveBeenCalled()
          expect(pageDOM.addBoxes).not.toHaveBeenCalled()
        })
      })
    })

   // !! Reset the spies in an afterEach
   afterEach(() => {
     addBoxesSpy.calls.reset();
     otherInitProceduresSpy.calls.reset();
   });
  })
})

After resetting the calls to what you're spying on, order should not matter anymore.


来源: stackexchange

问:
Check whether a String is not Null and not Empty
How can I check whether a string is not null and not empty?

```<code>public void doStuff(String str)
{
    if (str != null && str != "**here I want to check the 'str' is empty or not**")
    {
        /* handle empty string */
    }
    /* ... */
}
</code>```

答:
Consider the below example, I have added 4 test cases in main method. three test cases will pass when you follow above commented snipts.

```<code>public class EmptyNullBlankWithNull {
    public static boolean nullEmptyBlankWithNull(String passedStr) {
        if (passedStr != null && !passedStr.trim().isEmpty() && !passedStr.trim().equals("null")) {
            // TODO when string is null , Empty, Blank
            return true;
        }else{
            // TODO when string is null , Empty, Blank
            return false;
        }
    }

    public static void main(String[] args) {
        String stringNull = null; // test case 1
        String stringEmpty = ""; // test case 2
        String stringWhiteSpace = "  "; // test case 3
        String stringWhiteSpaceWithNull = " null"; // test case 4
        System.out.println("TestCase result:------ "+nullEmptyBlankWithNull(stringWhiteSpaceWithNull));

    }
}
</code>```

BUT test case 4 will return true(it has white space before null) which is wrong:

```<code>String stringWhiteSpaceWithNull = " null"; // test case 4
</code>```

We have to add below conditions to make it work propper:

```<code>!passedStr.trim().equals("null")
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How can I check whether a string is not null and not empty?

public void doStuff(String str)
{
    if (str != null && str != "**here I want to check the 'str' is empty or not**")
    {
        /* handle empty string */
    }
    /* ... */
}

Body:
Consider the below example, I have added 4 test cases in main method. three test cases will pass when you follow above commented snipts.

public class EmptyNullBlankWithNull {
    public static boolean nullEmptyBlankWithNull(String passedStr) {
        if (passedStr != null && !passedStr.trim().isEmpty() && !passedStr.trim().equals("null")) {
            // TODO when string is null , Empty, Blank
            return true;
        }else{
            // TODO when string is null , Empty, Blank
            return false;
        }
    }

    public static void main(String[] args) {
        String stringNull = null; // test case 1
        String stringEmpty = ""; // test case 2
        String stringWhiteSpace = "  "; // test case 3
        String stringWhiteSpaceWithNull = " null"; // test case 4
        System.out.println("TestCase result:------ "+nullEmptyBlankWithNull(stringWhiteSpaceWithNull));

    }
}

BUT test case 4 will return true(it has white space before null) which is wrong:

String stringWhiteSpaceWithNull = " null"; // test case 4

We have to add below conditions to make it work propper:

!passedStr.trim().equals("null")


问:
How to calculate relative frequency of array elements using Ramda.js?
I have an array with repeating values, and I want to get the relative frequency (i.e., proportions) for each repeating value.

It seems natural to me to treat this as a 2-step procedure:

count the occurrences of each value; and

divide that count by the length of the original array.

To accomplish the first step we can use R.countBy() from ramda.js:

const R = require("ramda")

const myLetters = ["a", "a", "a", "a", "b", "b", "c", "c", "c", "c"]
const counted = R.countBy(R.identity)(myLetters)
counted // => gives {"a": 4, "b": 2, "c": 4}
```
<p>Now the second step would be to divide <code>counted</code> by the length of <code>myLetters</code>:</p>
<pre class="lang-js prettyprint-override"><code>counted / R.length(myLetters) // obviously this doesn't work because it's not mapped
</code>```

I'm a bit lost with how to map this correctly. My current clunky solution that I dislike:

// 1. manually calculate the length and store to a variable
const nvals = R.length(myLetters)

// 2. create a custom division function
const divide_by_length = (x) => R.divide(x, nvals)

// 3. map custom function to `counted`
R.map(divide_by_length, counted) // gives {"a": 0.4, "b": 0.2, "c": 0.4}
```

Although this works, there's gotta be a more straightforward way with ramda to get from counted to {"a": 0.4, "b": 0.2, "c": 0.4}.

答:
You need to combine the results of counting the items in the array, with the length of the array.

You can use R.ap as the S combinator by supplying it with 2  functions. The S combinator signature is S = (f, g) => x => f(x)(g(x)), where f and g are functions.

In your case:

f - Create a map curried with divide by the length

g - Create an object of counts

const { ap, pipe, length, divide, __, map, countBy, identity } = R

const fn = ap(
  pipe(length, divide(__), map), // curry a map by divide by length
  countBy(identity), // create the counts
)

const myLetters = ["a", "a", "a", "a", "b", "b", "c", "c", "c", "c"]

const counted = fn(myLetters)

console.log(counted)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.28.0/ramda.min.js" integrity="sha512-t0vPcE8ynwIFovsylwUuLPIbdhDj6fav2prN9fEu/VYBupsmrmk9x43Hvnt+Mgn2h5YPSJOk7PMo9zIeGedD1A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script></code>```

Body:
I have an array with repeating values, and I want to get the relative frequency (i.e., proportions) for each repeating value.

It seems natural to me to treat this as a 2-step procedure:

count the occurrences of each value; and

divide that count by the length of the original array.

To accomplish the first step we can use R.countBy() from ramda.js:

const R = require("ramda")

const myLetters = ["a", "a", "a", "a", "b", "b", "c", "c", "c", "c"]
const counted = R.countBy(R.identity)(myLetters)
counted // => gives {"a": 4, "b": 2, "c": 4}

Now the second step would be to divide counted by the length of myLetters:

counted / R.length(myLetters) // obviously this doesn't work because it's not mapped

I'm a bit lost with how to map this correctly. My current clunky solution that I dislike:

// 1. manually calculate the length and store to a variable
const nvals = R.length(myLetters)

// 2. create a custom division function
const divide_by_length = (x) => R.divide(x, nvals)

// 3. map custom function to `counted`
R.map(divide_by_length, counted) // gives {"a": 0.4, "b": 0.2, "c": 0.4}

Although this works, there's gotta be a more straightforward way with ramda to get from counted to {"a": 0.4, "b": 0.2, "c": 0.4}.

Body:
You need to combine the results of counting the items in the array, with the length of the array.

You can use R.ap as the S combinator by supplying it with 2  functions. The S combinator signature is S = (f, g) => x => f(x)(g(x)), where f and g are functions.

In your case:

f - Create a map curried with divide by the length

g - Create an object of counts

const { ap, pipe, length, divide, __, map, countBy, identity } = R

const fn = ap(
  pipe(length, divide(__), map), // curry a map by divide by length
  countBy(identity), // create the counts
)

const myLetters = ["a", "a", "a", "a", "b", "b", "c", "c", "c", "c"]

const counted = fn(myLetters)

console.log(counted)

<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.28.0/ramda.min.js" integrity="sha512-t0vPcE8ynwIFovsylwUuLPIbdhDj6fav2prN9fEu/VYBupsmrmk9x43Hvnt+Mgn2h5YPSJOk7PMo9zIeGedD1A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>


问:
React Native - How do I direct to Main Stack screen without logging in and redirect back to Auth Stack from Main Stack screen?
I'm building an app that consists of public and private route.

The private route is as below:
Sign in (starting screen) --> (user signed in) --> Main Stack Screens (Home, Country, Communities, etc.)

The public route is as below:
Sign in (starting screen) --> (user not signed in) --> Main Stack Screens (Home, Country, Communities, etc.) with limited functions and content display to the user

In public route, I'm trying to add a login icon in the header of the Main Stack Screens, so users can be redirected back to the Auth flow and log in or sign up at any point of time when they wish to.

Here is my code for AuthStackNavigator.js:

```<code>import React from "react";
import { createStackNavigator } from "@react-navigation/stack";
import SignInScreen from "../screen/authentication/SignInScreen";
import SignUpScreen from "../screen/authentication/SignUpScreen";
import SignUpSuccessScreen from "../screen/authentication/SignUpSuccessScreen";
import PasswordResetScreen from "../screen/authentication/PasswordResetScreen";

const Stack = createStackNavigator();

const AuthStackNavigator = () => {
  return (
    <Stack.Navigator
      initialRouteName="Sign In"
      screenOptions={{ headerShown: false }}
    >
      <Stack.Screen name="Sign In" component={SignInScreen} />
      <Stack.Screen name="Sign Up" component={SignUpScreen} />
      <Stack.Screen name="Sign Up Success" component={SignUpSuccessScreen} />
      <Stack.Screen name="Password Reset" component={PasswordResetScreen} />}
    </Stack.Navigator>
  );
};

export default AuthStackNavigator;
</code>```

Here for MainNavigator.js:

```<code>import React, { useContext } from "react";
import { Platform, StyleSheet } from "react-native";
import { createStackNavigator } from "@react-navigation/stack";
import CountryScreen from "../screen/CountryScreen";
import CommunitiesScreen from "../screen/CommunitiesScreen";
import CommunityCreateScreen from "../screen/authorized/CommunityCreateScreen";
import CommunityHomeScreen from "../screen/CommunityHomeScreen";
import PostCreateScreen from "../screen/authorized/PostCreateScreen";
import CommentPostScreen from "../screen/authorized/CommentPostScreen";
import SearchBar from "../component/SearchBar";
import { generalconfig } from "../helper/generalconfig";
import { stylesconfig } from "../helper/stylesconfig";
import { AuthContext } from "../src/context/AuthContext";
import CustomProfileImg from "../component/CustomProfileImg";
import DefaultProfileIcon from "../component/DefaultProfileIcon";
import { Entypo } from "react-native-vector-icons";
import LoginIcon from "../component/LoginIcon";

const MainNavigator = () => {
  const Stack = createStackNavigator();
  const platform = Platform.OS;

  const { width } = generalconfig.device;
  const headerImageContainer = stylesconfig.global.headerImageContainer;
  const { common, ios, aos } = stylesconfig.navigatorHeader;

  const { profileImg, token } = useContext(AuthContext);

  return (
    <Stack.Navigator>
      <Stack.Screen
        name="Search Country"
        component={CountryScreen}
        options={{
          title: "Search",
          headerStyle: {
            backgroundColor: common.backgroundColor,
          },
          headerTitleAlign: "left",
          headerTintColor: common.color,
          headerTitleStyle: {
            fontFamily: platform === "ios" ? ios.fontFamily : aos.fontFamily,
            fontWeight: platform === "ios" ? ios.fontWeight : aos.fontWeight,
            fontSize: platform === "ios" ? ios.fontSize : aos.fontSize,
          },
          headerRight: () =>
            profileImg ? (
              <CustomProfileImg
                activeOpacity={1.0}
                onPress={() => {}}
                src={{ uri: profileImg }}
                style={headerImageContainer}
              />
            ) : (
              <DefaultProfileIcon
                activeOpacity={1.0}
                onPress={() => {}}
                iconSize={55}
                iconPosition={{ height: 65, marginRight: 11 }}
              />
            ),
        }}
      />
      <Stack.Screen
        name="Communities"
        component={CommunitiesScreen}
        options={{
          headerStyle: {
            backgroundColor: common.backgroundColor,
          },
          headerTintColor: common.color,
          headerTitleStyle: {
            fontFamily: platform === "ios" ? ios.fontFamily : aos.fontFamily,
            fontWeight: platform === "ios" ? ios.fontWeight : aos.fontWeight,
            fontSize: platform === "ios" ? ios.fontSize : aos.fontSize,
          },
          headerBackTitle: " ",
          headerBackImage: () => (
            <Entypo
              name="controller-fast-backward"
              size={23}
              style={{ marginLeft: width - 376 }}
              color={common.color}
            />
          ),
          headerRight: () => (token ? <LoginIcon /> : null),
        }}
      />
      <Stack.Screen
        name="Create Community"
        component={CommunityCreateScreen}
        options={{
          headerTitle: "Create a Community",
        }}
      />
      <Stack.Screen name="Community Home" component={CommunityHomeScreen} />
      <Stack.Screen name="Create Post" component={PostCreateScreen} />
      <Stack.Screen name="Comment Post" component={CommentPostScreen} />
    </Stack.Navigator>
  );
};

const styles = StyleSheet.create({});

export default MainNavigator;
</code>```

LoginIcon.js (component)

```<code>import React from "react";
import { TouchableOpacity } from "react-native";
import { stylesconfig } from "../helper/stylesconfig";
import { MaterialCommunityIcons } from "react-native-vector-icons";
import AuthStackNavigator from "../navigator/AuthStackNavigator";

const LoginIcon = () => {
  const { common } = stylesconfig.navigatorHeader;

  return (
    <TouchableOpacity
      onPress={() => {
        <NavigationContainer>
          <AuthStackNavigator />
        </NavigationContainer>;
      }}
    >
      <MaterialCommunityIcons
        name="login"
        size={23}
        color={common.color}
        style={{ marginRight: 15 }}
      />
    </TouchableOpacity>
  );
};

export default LoginIcon;
</code>```

SignInScreen.js (partial code of the link navigating to Country Screen when it's pressed)

```<code>      <CustomButtonLink
        custBtnLinkName={browseAroundLabel}
        style={[styles.spacing_Browse, styles.align]}
        onNavigate={() => {
          navigation.navigate(MainNavigator, { screen: "Search Country" });
        }}
        onNavigate={() => <MainNavigator />}
      />
</code>```

CustomButtonLink.js (component)

```<code>const CustomButtonLink = ({ custBtnLinkName, style, onNavigate }) => {
  return (
    <TouchableOpacity style={style} onPress={onNavigate}>
      <Text
        style={[
          stylesconfig.global.gtext,
          generalconfig.platform.os === "ios"
            ? stylesconfig.ios.text
            : stylesconfig.aos.text,
        ]}
      >
        {custBtnLinkName}
      </Text>
    </TouchableOpacity>
  );
};
</code>```

So my questions are:

How do I direct the user to the public route (Country Screen) if user is not authenticated?

Once user is directed to the public route (say Country Screen), how do I redirect him back to the AuthStackNavigator (Sign In screen) when he clicks the login icon?

I'm quite new to React Native so deeply appreciate it if anyone can help.  Thanks!

答:
Apart from @Abhishek Sah answer, it's recommended to detect user authentication state and navigator rerender accordingly. This will help when user successfully registered or logged out.</p>
```<code>// Custom hook to continuously listen to user authentication state
const  isSignedIn = useAth()

// listen to authentication state and rerender navigation accordingly

useEffect(()=>{
},[isSignedIn])
isSignedIn ? (
  <>
    <Stack.Screen name="Home" component={HomeScreen} />
    <Stack.Screen name="Profile" component={ProfileScreen} />
    <Stack.Screen name="Settings" component={SettingsScreen} />
  </>
) : (
  <>
    <Stack.Screen name="SignIn" component={SignInScreen} />
    <Stack.Screen name="SignUp" component={SignUpScreen} />
  </>
)

</code>```

Body:
I'm building an app that consists of public and private route.

The private route is as below:
Sign in (starting screen) --> (user signed in) --> Main Stack Screens (Home, Country, Communities, etc.)

The public route is as below:
Sign in (starting screen) --> (user not signed in) --> Main Stack Screens (Home, Country, Communities, etc.) with limited functions and content display to the user

In public route, I'm trying to add a login icon in the header of the Main Stack Screens, so users can be redirected back to the Auth flow and log in or sign up at any point of time when they wish to.

Here is my code for AuthStackNavigator.js:

import React from "react";
import { createStackNavigator } from "@react-navigation/stack";
import SignInScreen from "../screen/authentication/SignInScreen";
import SignUpScreen from "../screen/authentication/SignUpScreen";
import SignUpSuccessScreen from "../screen/authentication/SignUpSuccessScreen";
import PasswordResetScreen from "../screen/authentication/PasswordResetScreen";

const Stack = createStackNavigator();

const AuthStackNavigator = () => {
  return (
    <Stack.Navigator
      initialRouteName="Sign In"
      screenOptions={{ headerShown: false }}
    >
      <Stack.Screen name="Sign In" component={SignInScreen} />
      <Stack.Screen name="Sign Up" component={SignUpScreen} />
      <Stack.Screen name="Sign Up Success" component={SignUpSuccessScreen} />
      <Stack.Screen name="Password Reset" component={PasswordResetScreen} />}
    </Stack.Navigator>
  );
};

export default AuthStackNavigator;

Here for MainNavigator.js:

import React, { useContext } from "react";
import { Platform, StyleSheet } from "react-native";
import { createStackNavigator } from "@react-navigation/stack";
import CountryScreen from "../screen/CountryScreen";
import CommunitiesScreen from "../screen/CommunitiesScreen";
import CommunityCreateScreen from "../screen/authorized/CommunityCreateScreen";
import CommunityHomeScreen from "../screen/CommunityHomeScreen";
import PostCreateScreen from "../screen/authorized/PostCreateScreen";
import CommentPostScreen from "../screen/authorized/CommentPostScreen";
import SearchBar from "../component/SearchBar";
import { generalconfig } from "../helper/generalconfig";
import { stylesconfig } from "../helper/stylesconfig";
import { AuthContext } from "../src/context/AuthContext";
import CustomProfileImg from "../component/CustomProfileImg";
import DefaultProfileIcon from "../component/DefaultProfileIcon";
import { Entypo } from "react-native-vector-icons";
import LoginIcon from "../component/LoginIcon";

const MainNavigator = () => {
  const Stack = createStackNavigator();
  const platform = Platform.OS;

  const { width } = generalconfig.device;
  const headerImageContainer = stylesconfig.global.headerImageContainer;
  const { common, ios, aos } = stylesconfig.navigatorHeader;

  const { profileImg, token } = useContext(AuthContext);

  return (
    <Stack.Navigator>
      <Stack.Screen
        name="Search Country"
        component={CountryScreen}
        options={{
          title: "Search",
          headerStyle: {
            backgroundColor: common.backgroundColor,
          },
          headerTitleAlign: "left",
          headerTintColor: common.color,
          headerTitleStyle: {
            fontFamily: platform === "ios" ? ios.fontFamily : aos.fontFamily,
            fontWeight: platform === "ios" ? ios.fontWeight : aos.fontWeight,
            fontSize: platform === "ios" ? ios.fontSize : aos.fontSize,
          },
          headerRight: () =>
            profileImg ? (
              <CustomProfileImg
                activeOpacity={1.0}
                onPress={() => {}}
                src={{ uri: profileImg }}
                style={headerImageContainer}
              />
            ) : (
              <DefaultProfileIcon
                activeOpacity={1.0}
                onPress={() => {}}
                iconSize={55}
                iconPosition={{ height: 65, marginRight: 11 }}
              />
            ),
        }}
      />
      <Stack.Screen
        name="Communities"
        component={CommunitiesScreen}
        options={{
          headerStyle: {
            backgroundColor: common.backgroundColor,
          },
          headerTintColor: common.color,
          headerTitleStyle: {
            fontFamily: platform === "ios" ? ios.fontFamily : aos.fontFamily,
            fontWeight: platform === "ios" ? ios.fontWeight : aos.fontWeight,
            fontSize: platform === "ios" ? ios.fontSize : aos.fontSize,
          },
          headerBackTitle: " ",
          headerBackImage: () => (
            <Entypo
              name="controller-fast-backward"
              size={23}
              style={{ marginLeft: width - 376 }}
              color={common.color}
            />
          ),
          headerRight: () => (token ? <LoginIcon /> : null),
        }}
      />
      <Stack.Screen
        name="Create Community"
        component={CommunityCreateScreen}
        options={{
          headerTitle: "Create a Community",
        }}
      />
      <Stack.Screen name="Community Home" component={CommunityHomeScreen} />
      <Stack.Screen name="Create Post" component={PostCreateScreen} />
      <Stack.Screen name="Comment Post" component={CommentPostScreen} />
    </Stack.Navigator>
  );
};

const styles = StyleSheet.create({});

export default MainNavigator;

LoginIcon.js (component)

import React from "react";
import { TouchableOpacity } from "react-native";
import { stylesconfig } from "../helper/stylesconfig";
import { MaterialCommunityIcons } from "react-native-vector-icons";
import AuthStackNavigator from "../navigator/AuthStackNavigator";

const LoginIcon = () => {
  const { common } = stylesconfig.navigatorHeader;

  return (
    <TouchableOpacity
      onPress={() => {
        <NavigationContainer>
          <AuthStackNavigator />
        </NavigationContainer>;
      }}
    >
      <MaterialCommunityIcons
        name="login"
        size={23}
        color={common.color}
        style={{ marginRight: 15 }}
      />
    </TouchableOpacity>
  );
};

export default LoginIcon;

SignInScreen.js (partial code of the link navigating to Country Screen when it's pressed)

      <CustomButtonLink
        custBtnLinkName={browseAroundLabel}
        style={[styles.spacing_Browse, styles.align]}
        onNavigate={() => {
          navigation.navigate(MainNavigator, { screen: "Search Country" });
        }}
        onNavigate={() => <MainNavigator />}
      />

CustomButtonLink.js (component)

const CustomButtonLink = ({ custBtnLinkName, style, onNavigate }) => {
  return (
    <TouchableOpacity style={style} onPress={onNavigate}>
      <Text
        style={[
          stylesconfig.global.gtext,
          generalconfig.platform.os === "ios"
            ? stylesconfig.ios.text
            : stylesconfig.aos.text,
        ]}
      >
        {custBtnLinkName}
      </Text>
    </TouchableOpacity>
  );
};

So my questions are:

How do I direct the user to the public route (Country Screen) if user is not authenticated?

Once user is directed to the public route (say Country Screen), how do I redirect him back to the AuthStackNavigator (Sign In screen) when he clicks the login icon?

I'm quite new to React Native so deeply appreciate it if anyone can help.  Thanks!

Body:
Apart from @Abhishek Sah answer, it's recommended to detect user authentication state and navigator rerender accordingly. This will help when user successfully registered or logged out.

// Custom hook to continuously listen to user authentication state
const  isSignedIn = useAth()

// listen to authentication state and rerender navigation accordingly

useEffect(()=>{
},[isSignedIn])
isSignedIn ? (
  <>
    <Stack.Screen name="Home" component={HomeScreen} />
    <Stack.Screen name="Profile" component={ProfileScreen} />
    <Stack.Screen name="Settings" component={SettingsScreen} />
  </>
) : (
  <>
    <Stack.Screen name="SignIn" component={SignInScreen} />
    <Stack.Screen name="SignUp" component={SignUpScreen} />
  </>
)


问:
How to manually update Entity framework Code first model so that it updates a database (with a new column)?
can somebody tell me how I can add a data member (col) to my mvc3 model (class) and have it update the database without having to generate everything from scratch?  I'm working from code first.  When I change my model then run my project I get an error stating that model has changed.  Any clean and easy way to synch creating a new col/data mamber with the db/model?

Thanks!

答:
you can use this in application start,

```<code> Database.SetInitializer(new DropCreateDatabaseIfModelChanges<YourDBContext>());
</code>```

it will regenerate the database if your model change happens.And if you do not want to drop and create database (To incremental development) you can use SqlMigrations. http://www.hanselman.com/blog/EntityFrameworkCodeFirstMigrationsAlphaNuGetPackageOfTheWeek10.aspx

ContentLicense: CC BY-SA 3.0

Body:
you can use this in application start,

 Database.SetInitializer(new DropCreateDatabaseIfModelChanges<YourDBContext>());

it will regenerate the database if your model change happens.And if you do not want to drop and create database (To incremental development) you can use SqlMigrations. http://www.hanselman.com/blog/EntityFrameworkCodeFirstMigrationsAlphaNuGetPackageOfTheWeek10.aspx


问:
How to use generic types in abstract class
I'm trying to write a base class with some methods I want they are implemented in the classes that they inherit from this class.

In this example:

```<code>abstract public class ServiceBase
{
    public ServiceBase()
    {
    }

    abstract public T Read<T>(string id);
    abstract public T Create<T>(T record);
    abstract public void Delete<T>(T record);
}

public class ServiceA: ServiceBase
{
    public Service(){}

    public override classA Read<classA>(string id)
    {
        ...
    }
    public override classA Create<classA>(classA record)
    {
        ...
    }
    public override void Delete<classA>(classA record)
    {
        ...
    }
}

public class ServiceB: ServiceBase
{
    public Service(){}

    public override classB Read<classB>(string id)
    {
        ...
    }
    public override classB Create<classB>(classB record)
    {
        ...
    }
    public override void Delete<classB>(classB record)
    {
        ...
    }
}
</code>```

this show the next error: "no suitable method found to override"

Is it possible to make this correct? How?

答:
```<code>public class ClassA { }

public class ClassB { }

abstract public class ServiceBase<T> where T : class
{
    abstract public T Read(string id);
    abstract public T Create(T record);
    abstract public void Delete(T record);
}

public class ServiceConcrete1 : ServiceBase<ClassA>
{
    public override ClassA Read(string id)
    {
        throw new NotImplementedException();
    }
    public override ClassA Create(ClassA record)
    {
        throw new NotImplementedException();
    }
    public override void Delete(ClassA record)
    {
        throw new NotImplementedException();
    }
}

public class ServiceConcrete2 : ServiceBase<ClassB>
{
    public override ClassB Read(string id)
    {
        throw new NotImplementedException();
    }
    public override ClassB Create(ClassB record)
    {
        throw new NotImplementedException();
    }
    public override void Delete(ClassB record)
    {
        throw new NotImplementedException();
    }
}
</code>```

Body:
I'm trying to write a base class with some methods I want they are implemented in the classes that they inherit from this class.

In this example:

abstract public class ServiceBase
{
    public ServiceBase()
    {
    }

    abstract public T Read<T>(string id);
    abstract public T Create<T>(T record);
    abstract public void Delete<T>(T record);
}

public class ServiceA: ServiceBase
{
    public Service(){}

    public override classA Read<classA>(string id)
    {
        ...
    }
    public override classA Create<classA>(classA record)
    {
        ...
    }
    public override void Delete<classA>(classA record)
    {
        ...
    }
}

public class ServiceB: ServiceBase
{
    public Service(){}

    public override classB Read<classB>(string id)
    {
        ...
    }
    public override classB Create<classB>(classB record)
    {
        ...
    }
    public override void Delete<classB>(classB record)
    {
        ...
    }
}

this show the next error: "no suitable method found to override"

Is it possible to make this correct? How?


答:
You need to declare the type T as part of your abstract class, and then pass a concrete type in your implementing class.

```<code>abstract public class ServiceBase<T>
{
    public ServiceBase()
    {
    }

    abstract public T Read(string id);
    abstract public T Create<T>(T record);
    abstract public void Delete<T>(T record);
}
</code>```

And then implementing, pass your type (in your example, either classA or classB) as such:

```<code>public class ServiceB: ServiceBase<classB>
{
    public Service(){}

    public override classB Read(string id)
    {
        ...
    }
    public override classB Create<classB>(classB record)
    {
        ...
    }
    public override void Delete<classB>(classB record)
    {
        ...
    }
}
</code>```

Title: How to use generic types in abstract class

Body:
You need to declare the type T as part of your abstract class, and then pass a concrete type in your implementing class.

abstract public class ServiceBase<T>
{
    public ServiceBase()
    {
    }

    abstract public T Read(string id);
    abstract public T Create<T>(T record);
    abstract public void Delete<T>(T record);
}

And then implementing, pass your type (in your example, either classA or classB) as such:

public class ServiceB: ServiceBase<classB>
{
    public Service(){}

    public override classB Read(string id)
    {
        ...
    }
    public override classB Create<classB>(classB record)
    {
        ...
    }
    public override void Delete<classB>(classB record)
    {
        ...
    }
}


问:
Xamarin.forms iOS Black Screen after launching (Xamarin Visual Studio 2022)
I have an App that's in development for quite a while now and I wanted to "port" it to iOS. When I start it, the splash screen appears and it works fine. After that splash screen it turns into a black screen, but it doesn't crash. If I create a New Application and try to run it it works perfectly. I don't use any storyboards and I'm trying to deploy to a iPhone SE. It currently has iOS 15.3 on it. What could cause this?

EDIT:
Here is the Code of the first page that the App opens:

```<code><?xml version="1.0" encoding="UTF-8"?>
<Shell xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="Easy_Learn.Pages.Shellpage"
            xmlns:pages="clr-namespace:Easy_Learn.Pages"
            xmlns:local="clr-namespace:Easy_Learn"
            xmlns:viewtemplates="clr-namespace:Easy_Learn.ViewTemplates"
            xmlns:windows="clr-namespace:Xamarin.Forms.PlatformConfiguration.WindowsSpecific;assembly=Xamarin.Forms.Core"
            windows:Application.ImageDirectory="Assets"
            FlyoutHeaderTemplate="{DataTemplate viewtemplates:FlyoutHeader}"
            Shell.TabBarIsVisible="False"
            Shell.TabBarForegroundColor="{StaticResource backGroundColor}"
            Shell.BackgroundColor="{StaticResource backGroundColor}"
            Shell.TitleColor="{StaticResource textColor}"
            Shell.ForegroundColor="{StaticResource textColor}">
    <ShellContent ContentTemplate="{DataTemplate local:MainPage}" Title="Lernen" Icon="LightBulb.png"/>
    <FlyoutItem FlyoutDisplayOptions="AsMultipleItems">
        <ShellContent ContentTemplate="{DataTemplate pages:AllVocabs}" Title="Alle Vokabeln" Icon="Book.png"/>
        <ShellContent ContentTemplate="{DataTemplate pages:deklkonj}" Title="Deklinationen" Icon="table.png"/>
        <ShellContent ContentTemplate="{DataTemplate pages:Konjugationen}" Title="Konjugationen" Icon="table.png"/>
        <ShellContent ContentTemplate="{DataTemplate pages:adjectives}" Title="Adjektive" Icon="table.png"/>
        <ShellContent ContentTemplate="{DataTemplate pages:profile}" Title="Profil" Icon="account.png"/>
    </FlyoutItem>
</Shell>
</code>```

答:
Using this I found that there were a few lines in the info.plist file that cause this issue. You just need to remove these lines from your info.plist and it works fine.</p>
```<code> <key>UIApplicationSceneManifest</key>
 <dict>
     <key>UIApplicationSupportsMultipleScenes</key>
     <true/>
 </dict>

</code>```

Body:
I have an App that's in development for quite a while now and I wanted to "port" it to iOS. When I start it, the splash screen appears and it works fine. After that splash screen it turns into a black screen, but it doesn't crash. If I create a New Application and try to run it it works perfectly. I don't use any storyboards and I'm trying to deploy to a iPhone SE. It currently has iOS 15.3 on it. What could cause this?

EDIT:
Here is the Code of the first page that the App opens:

<?xml version="1.0" encoding="UTF-8"?>
<Shell xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="Easy_Learn.Pages.Shellpage"
            xmlns:pages="clr-namespace:Easy_Learn.Pages"
            xmlns:local="clr-namespace:Easy_Learn"
            xmlns:viewtemplates="clr-namespace:Easy_Learn.ViewTemplates"
            xmlns:windows="clr-namespace:Xamarin.Forms.PlatformConfiguration.WindowsSpecific;assembly=Xamarin.Forms.Core"
            windows:Application.ImageDirectory="Assets"
            FlyoutHeaderTemplate="{DataTemplate viewtemplates:FlyoutHeader}"
            Shell.TabBarIsVisible="False"
            Shell.TabBarForegroundColor="{StaticResource backGroundColor}"
            Shell.BackgroundColor="{StaticResource backGroundColor}"
            Shell.TitleColor="{StaticResource textColor}"
            Shell.ForegroundColor="{StaticResource textColor}">
    <ShellContent ContentTemplate="{DataTemplate local:MainPage}" Title="Lernen" Icon="LightBulb.png"/>
    <FlyoutItem FlyoutDisplayOptions="AsMultipleItems">
        <ShellContent ContentTemplate="{DataTemplate pages:AllVocabs}" Title="Alle Vokabeln" Icon="Book.png"/>
        <ShellContent ContentTemplate="{DataTemplate pages:deklkonj}" Title="Deklinationen" Icon="table.png"/>
        <ShellContent ContentTemplate="{DataTemplate pages:Konjugationen}" Title="Konjugationen" Icon="table.png"/>
        <ShellContent ContentTemplate="{DataTemplate pages:adjectives}" Title="Adjektive" Icon="table.png"/>
        <ShellContent ContentTemplate="{DataTemplate pages:profile}" Title="Profil" Icon="account.png"/>
    </FlyoutItem>
</Shell>

Body:
Using this I found that there were a few lines in the info.plist file that cause this issue. You just need to remove these lines from your info.plist and it works fine.

 <key>UIApplicationSceneManifest</key>
 <dict>
     <key>UIApplicationSupportsMultipleScenes</key>
     <true/>
 </dict>


问:
How to display percentages values in stacked bar chart using px.bar()?
Need to display % sign along with the numeric value. Please check below attached graph. I there any way to add % sign with numeric value?

```<code># Import pandas library
import pandas as pd

# initialize list of lists
data = [['2017/2018', 'Renewable',21], ['2018/2019', 'Renewable',42], ['2019/2020', 'Renewable',75],
       ['2017/2018', 'Non-Renewable',79], ['2018/2019', 'Non-Renewable',58], ['2019/2020', 'Non-Renewable',25]]

# Create the pandas DataFrame
df = pd.DataFrame(data, columns = ['Year', 'Energy','Energy Mix %'])

# print dataframe.
df

fig = px.bar(df, x="Year", y="Energy Mix %", color="Energy", title="RENEWABLE ENERGY MIX",
             text_auto=True,template='plotly_dark')
fig.show()
</code>```

答:
You can use:

```<code>fig.for_each_trace(lambda t: t.update(texttemplate = t.texttemplate + ' %'))
</code>```

And get:

Complete code:

```<code># Import pandas library
import pandas as pd
import plotly.express as px
# initialize list of lists
data = [['2017/2018', 'Renewable',21], ['2018/2019', 'Renewable',42], ['2019/2020', 'Renewable',75],
       ['2017/2018', 'Non-Renewable',79], ['2018/2019', 'Non-Renewable',58], ['2019/2020', 'Non-Renewable',25]]

# Create the pandas DataFrame
df = pd.DataFrame(data, columns = ['Year', 'Energy','Energy Mix %'])

fig = px.bar(df, x="Year", y="Energy Mix %", color="Energy", title="RENEWABLE ENERGY MIX",
             text_auto=True,template='plotly_dark')

fig.for_each_trace(lambda t: t.update(texttemplate = t.texttemplate + ' %'))

fig.show()
</code>```

Body:
Need to display % sign along with the numeric value. Please check below attached graph. I there any way to add % sign with numeric value?

# Import pandas library
import pandas as pd

# initialize list of lists
data = [['2017/2018', 'Renewable',21], ['2018/2019', 'Renewable',42], ['2019/2020', 'Renewable',75],
       ['2017/2018', 'Non-Renewable',79], ['2018/2019', 'Non-Renewable',58], ['2019/2020', 'Non-Renewable',25]]

# Create the pandas DataFrame
df = pd.DataFrame(data, columns = ['Year', 'Energy','Energy Mix %'])

# print dataframe.
df

fig = px.bar(df, x="Year", y="Energy Mix %", color="Energy", title="RENEWABLE ENERGY MIX",
             text_auto=True,template='plotly_dark')
fig.show()

Body:
You can use:

fig.for_each_trace(lambda t: t.update(texttemplate = t.texttemplate + ' %'))

And get:

Complete code:

# Import pandas library
import pandas as pd
import plotly.express as px
# initialize list of lists
data = [['2017/2018', 'Renewable',21], ['2018/2019', 'Renewable',42], ['2019/2020', 'Renewable',75],
       ['2017/2018', 'Non-Renewable',79], ['2018/2019', 'Non-Renewable',58], ['2019/2020', 'Non-Renewable',25]]

# Create the pandas DataFrame
df = pd.DataFrame(data, columns = ['Year', 'Energy','Energy Mix %'])

fig = px.bar(df, x="Year", y="Energy Mix %", color="Energy", title="RENEWABLE ENERGY MIX",
             text_auto=True,template='plotly_dark')

fig.for_each_trace(lambda t: t.update(texttemplate = t.texttemplate + ' %'))

fig.show()


问:
Overflow on CPU, but not GPU

import torch
torch.manual_seed(0)
x = torch.ones(1000000).half()

print(x.mean())
print(x.cuda().mean())
```
```tensor(nan, dtype=torch.float16)
tensor(1., device='cuda:0', dtype=torch.float16)
```

Why?

答:
Quoting wikipedia's float16 entry:

65519 is the largest number that will round to a finite number (65504), 65520 and larger will round to infinity. This is for round-to-even, other rounding strategies will change this cutoff.

The CPU version is triggering an overflow when computing the mean (it is probably summing all values, then dividing by their number).
The GPU version works correctly (well, it seems to work on the ones, it didn't on the random distribution you provided in your first version of the question), maybe it starts by dividing all values by the size of the tensor, then adds them up?

Interestingly, np.mean specifically documents that float16 need special attention:

By default, float16 results are computed using float32 intermediates for extra precision.

If you run your test with np instead or torch, it works fine on CPU.

Title: Overflow on CPU, but not GPU

Body:
import torch
torch.manual_seed(0)
x = torch.ones(1000000).half()

print(x.mean())
print(x.cuda().mean())

tensor(nan, dtype=torch.float16)
tensor(1., device='cuda:0', dtype=torch.float16)

Why?


问:
How to solve error DNS_PROBE_FINISHED_BAD_CONFIG in Chrome
I got this error suddenly when I was surfing.

I deleted temp files and I cleaned cache, but it still did not work.

I solved with:

Open Windows services Manager (Windows key + r and put services.msc)

Restart DNS Client

答: please enter this URL chrome://settings/security in the chrome web browser  . after navigating to the chrome security settings, under the "Use Secure DNS" option, please select "with your current service provider" option. now it will work as expected.


问:
Any production scenario where External table in Hive is definitely needed?
I know when we try to delete the table, it only deletes meta data but not data. But what could be the particular production use case in industry where internal tables may not be useful and it can only be achieved through external tables?

If we think that through external table, we can make sure data is safe and not deleted by anyone, this can be achieved in managed table by setting no_drop option which restricts table deletion.

If we think that using same underlying data, many tables can be created, even that can be easily achieved through managed tables.

Is there any particular industry scenario where managed table may not be useful and we need external table there?

答:
no_drop just restricts dropping the table, but there are scenarios when you may need to drop/create the table keeping the data.

You may need to change table definition and recreate it without deleting the data. For example you have some JSON files loaded by upstream process, upstream process added one more attribute to the JSON and you want to re-create your table definition to include new column and have all the data as is. Or add more columns which are being parsed from semi-structured files (Using RegexSerDe), or just change regex in table DDL to improve extraction.

Scenario 2: You are loading data into partition folders daily. and some downstream process needs only latest partition, and you can not pass the parameter to it, while some other process wants the whole table. In this case you can create partitioned table and not partitioned latest one on top of the latest partition dir in the upstream process, dropping and re-creating each time and changing location. Downstream process can use latest table (whithout knowing in advance which is the latest partition and no need in finding it) and the whole partitioned one also can be used.

You may want to load data into location outside configured managed tables location root dir, see https://stackoverflow.com/a/67073849/2700344 And there are policies in your warehouse restricting loading raw data into managed tables dir. On Cloudera distribution you can not create managed table and specify location other than default one. This is why you may need EXTERNAL table.

Tables which are using JDBC storage handler, or Kafka storage handler, HBASE can be created as External only.

Of course in some cases you can use ALTER TABLE instead of DROP/CREATE but it is convenient to store table DDL file, versioned in the repo without ALTERs.

And maybe there are some other possible use-cases.


问:
Box-shadow and dynamic arrow position for custom select
I found on internet a custom select, made only with HTML and CSS.

* {
    position: relative;
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    border-color: inherit;
}

form {
    width: 114px;
    height: 100%;
    padding-bottom: 75px;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-left: 30px;
}

ul {
    list-style: none;
}

.select {
    width: 225px;
    height: 40px;
    cursor: pointer;
    background-color: white;
    box-shadow: 0 2px 0 white;
    border-radius: 2px;
}

.select_expand {
    width: 0;
    height: 40px;
    position: absolute;
    top: 0;
    right: 0;
}

.select_expand::after {
    content: '\003E';
    position: absolute;
    top: 50%;
    right: 70px;
    transform: translate(-50%, -50%) rotate(90deg) scaleY(1.75);
    color: black;
    font-size: 10px;
    pointer-events: none;
    z-index: 2;
    transition: all 250ms cubic-bezier(.4, .25, .3, 1);

}

.select_expand:hover::after {
    opacity: 1;
}

.select_expand:checked::after {
    transform: translate(-50%, -50%) rotate(90deg) scaleX(-1) scaleY(1.75);
}

.select_expandLabel {
    display: block;
    width: 100%;
    height: 40px;
    position: absolute;
    top: 0;
    left: 0;
    cursor: pointer;
}

.select_close {
    display: none
}

.select_closeLabel {
    width: 100vw;
    height: 100vh;
    position: fixed;
    top: 0;
    left: 0;
    display: none;
}

.select_items {
    width: 100%;
    position: absolute;
    top: 0;
    left: 0;
    padding-top: 40px;
}

.select_input {
    display: none
}

.select_label {
    transition: all 250ms cubic-bezier(.4, .25, .3, 1);
    display: block;
    height: 0;
    font-size: 18px;
    line-height: 40px;
    overflow: hidden;
    color: black;
    background-color: #fff;
    cursor: pointer;
    padding-left: 15px;
}

.select_label-placeholder {
    height: 40px;
    vertical-align: middle;
    position: absolute;
    top: 0;
    padding-left: 15px;
}

.select_expand:checked+.select_closeLabel {
    display: block;
    box-shadow: 0 15px 30px 10px rgba(0, 0, 0, 0.1);
}

.select_expand:checked+.select_closeLabel+.select_options .select_label {
    height: 40px;
}

.select_expand:checked+.select_closeLabel+.select_options .select_label:hover {
    background-color: #f7f7f7
}

.select_expand:checked+.select_closeLabel+.select_options+.select_expandLabel {
    display: none
}

.select_input:checked+.select_label {
    height: 40px;
    margin-top: -40px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>

    <ul class="select">
        <li>
            <input class="select_close" type="radio" name="awesomeness" id="awesomeness-close" value=""/>
            <span class="select_label select_label-placeholder">#</span>
        </li>

        <li class="select_items">
            <input class="select_expand" type="radio" name="awesomeness" id="awesomeness-opener"/>
            <label class="select_closeLabel" for="awesomeness-close"></label>

            <ul class="select_options">
                <li class="select_option">
                    <input class="select_input" type="radio" name="awesomeness" id="awesomeness-ridiculous"/>
                    <label class="select_label" for="awesomeness-ridiculous">@ ASD</label>
                </li>

                <li class="select_option">
                    <input class="select_input" type="radio" name="awesomeness" id="awesomeness-reasonable"/>
                    <label class="select_label" for="awesomeness-reasonable">E* ERD</label>
                </li>

                <li class="select_option">
                    <input class="select_input" type="radio" name="awesomeness" id="awesomeness-lacking"/>
                    <label class="select_label" for="awesomeness-lacking">@ TRF</label>
                </li>

                <li class="select_option">
                    <input class="select_input" type="radio" name="awesomeness" id="awesomeness-awesomeless"/>
                    <label class="select_label" for="awesomeness-awesomeless">% QWE</label>
                </li>
            </ul>

            <label class="select_expandLabel" for="awesomeness-opener"></label>
        </li>
    </ul>

</form></code>```

I tried to add a box shadow for the open dropdown menu and I did not succed.

Also I want the arrow to have a dynamic position: to be all the time on the right side and to not overlap with the selected option,as it is doing now, and I don't know how to achieve this one. Is this possible only with css?

I am planning to use this form in a reactjs component.

Here is the JSFiddle link (HTML and CSS).

Could you please help me?

Thank you!

Update

Desired output:

I want that the arrow to move automaticaly to the right of the selected option. I tried with float: right, but not any results.

Maybe it is better to use an image here: content: '\003E';?

答:
* {
    position: relative;
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    border-color: inherit;
}

form {
    width: 114px;
    height: 100%;
    padding-bottom: 75px;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-left: 30px;
}

ul {
    list-style: none;
}

.select {
    width: 225px;
    height: 40px;
    cursor: pointer;
    background-color: white;
    box-shadow: 0 2px 0 white;
    border-radius: 2px;
}

.select_expand {
    width: 0;
    height: 40px;
    position: absolute;
    top: 0;
    right: 0;
}

.select_expand::after {
    content: '\003E';
    position: absolute;
    top: 50%;
    right: 25px;

    transform: translate(-50%, -50%) rotate(90deg) scaleY(1.75);
    color: black;
    font-size: 10px;
    pointer-events: none;
    z-index: 2;
    transition: all 250ms cubic-bezier(.4, .25, .3, 1);

}

.select_expand:hover::after {
    opacity: 1;
}

.select_expand:checked::after {
    transform: translate(-50%, -50%) rotate(90deg) scaleX(-1) scaleY(1.75);
}

.select_expandLabel {
    display: block;
    width: 100%;
    height: 40px;
    position: absolute;
    top: 0;
    left: 0;
    cursor: pointer;
}

.select_close {
    display: none
}

.select_closeLabel {
    width: 100vw;
    height: 100vh;
    position: fixed;
    top: 0;
    left: 0;
    display: none;
}

.select_items {
    width: 100%;
    position: absolute;
    top: 0;
    left: 0;
    padding-top: 40px;

}

.select_input {
    display: none;

}

.select_label {
    transition: all 250ms cubic-bezier(.4, .25, .3, 1);
    display: block;
    height: 0;
    font-size: 18px;
    line-height: 40px;
    overflow: hidden;
    color: black;
    background-color: #fff;
    cursor: pointer;
    padding-left: 15px;

}

.select_label-placeholder {
    height: 40px;
    vertical-align: middle;
    position: absolute;
    top: 0;
    padding-left: 15px;

}

.select_expand:checked+.select_closeLabel {
    display: block;

}

.select_expand:checked+.select_closeLabel+.select_options .select_label:hover {
    background-color: #f7f7f7;
}

.select_expand:checked+.select_closeLabel+.select_options+.select_expandLabel {
    display: none;
}

.select_input:checked+.select_label {
    height: 40px;
    margin-top: -40px;/*changed*/

}

.select_expand:checked+.select_closeLabel+.select_options .select_label {
    height: 40px;
    /*box-shadow: 0 15px 30px 10px rgba(0, 0, 0, 0.1);*/

}
.select_options {
/*coment the below line and uncoment above for diffrent effect*/
    box-shadow: 0 15px 30px 10px rgba(0, 0, 0, 0.1);

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>

    <ul class="select">
        <li>
            <input class="select_close" type="radio" name="awesomeness" id="awesomeness-close" value=""/>
            <span class="select_label select_label-placeholder">#</span>
        </li>

        <li class="select_items">
            <input class="select_expand" type="radio" name="awesomeness" id="awesomeness-opener"/>
            <label class="select_closeLabel" for="awesomeness-close"></label>

            <ul class="select_options">
                <li class="select_option">
                    <input class="select_input" type="radio" name="awesomeness" id="awesomeness-ridiculous"/>
                    <label class="select_label" for="awesomeness-ridiculous">@ ASD</label>
                </li>

                <li class="select_option">
                    <input class="select_input" type="radio" name="awesomeness" id="awesomeness-reasonable"/>
                    <label class="select_label" for="awesomeness-reasonable">E* ERD</label>
                </li>

                <li class="select_option">
                    <input class="select_input" type="radio" name="awesomeness" id="awesomeness-lacking"/>
                    <label class="select_label" for="awesomeness-lacking">@ TRF</label>
                </li>

                <li class="select_option">
                    <input class="select_input" type="radio" name="awesomeness" id="awesomeness-awesomeless"/>
                    <label class="select_label" for="awesomeness-awesomeless">% QWE</label>
                </li>
            </ul>

            <label class="select_expandLabel" for="awesomeness-opener"></label>
        </li>
    </ul>

</form></code>```

First things first,

and first thing is putting ;

Second,

to put box shadow

add the code to .select_options

Third,

to avoid overlap

change right from 70px to 25px(reduce right means increase left)

Body:
I found on internet a custom select, made only with HTML and CSS.

* {
    position: relative;
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    border-color: inherit;
}

form {
    width: 114px;
    height: 100%;
    padding-bottom: 75px;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-left: 30px;
}

ul {
    list-style: none;
}

.select {
    width: 225px;
    height: 40px;
    cursor: pointer;
    background-color: white;
    box-shadow: 0 2px 0 white;
    border-radius: 2px;
}

.select_expand {
    width: 0;
    height: 40px;
    position: absolute;
    top: 0;
    right: 0;
}

.select_expand::after {
    content: '\003E';
    position: absolute;
    top: 50%;
    right: 70px;
    transform: translate(-50%, -50%) rotate(90deg) scaleY(1.75);
    color: black;
    font-size: 10px;
    pointer-events: none;
    z-index: 2;
    transition: all 250ms cubic-bezier(.4, .25, .3, 1);

}

.select_expand:hover::after {
    opacity: 1;
}

.select_expand:checked::after {
    transform: translate(-50%, -50%) rotate(90deg) scaleX(-1) scaleY(1.75);
}

.select_expandLabel {
    display: block;
    width: 100%;
    height: 40px;
    position: absolute;
    top: 0;
    left: 0;
    cursor: pointer;
}

.select_close {
    display: none
}

.select_closeLabel {
    width: 100vw;
    height: 100vh;
    position: fixed;
    top: 0;
    left: 0;
    display: none;
}

.select_items {
    width: 100%;
    position: absolute;
    top: 0;
    left: 0;
    padding-top: 40px;
}

.select_input {
    display: none
}

.select_label {
    transition: all 250ms cubic-bezier(.4, .25, .3, 1);
    display: block;
    height: 0;
    font-size: 18px;
    line-height: 40px;
    overflow: hidden;
    color: black;
    background-color: #fff;
    cursor: pointer;
    padding-left: 15px;
}

.select_label-placeholder {
    height: 40px;
    vertical-align: middle;
    position: absolute;
    top: 0;
    padding-left: 15px;
}

.select_expand:checked+.select_closeLabel {
    display: block;
    box-shadow: 0 15px 30px 10px rgba(0, 0, 0, 0.1);
}

.select_expand:checked+.select_closeLabel+.select_options .select_label {
    height: 40px;
}

.select_expand:checked+.select_closeLabel+.select_options .select_label:hover {
    background-color: #f7f7f7
}

.select_expand:checked+.select_closeLabel+.select_options+.select_expandLabel {
    display: none
}

.select_input:checked+.select_label {
    height: 40px;
    margin-top: -40px;
}

<form>

            <input class="select_close" type="radio" name="awesomeness" id="awesomeness-close" value=""/>
            #

            <input class="select_expand" type="radio" name="awesomeness" id="awesomeness-opener"/>

                    <input class="select_input" type="radio" name="awesomeness" id="awesomeness-ridiculous"/>
                    @ ASD

                    <input class="select_input" type="radio" name="awesomeness" id="awesomeness-reasonable"/>
                    E* ERD

                    <input class="select_input" type="radio" name="awesomeness" id="awesomeness-lacking"/>
                    @ TRF

                    <input class="select_input" type="radio" name="awesomeness" id="awesomeness-awesomeless"/>
                    % QWE

</form>

I tried to add a box shadow for the open dropdown menu and I did not succed.

Also I want the arrow to have a dynamic position: to be all the time on the right side and to not overlap with the selected option,as it is doing now, and I don't know how to achieve this one. Is this possible only with css?

I am planning to use this form in a reactjs component.

Here is the JSFiddle link (HTML and CSS).

Could you please help me?

Thank you!

Update

Desired output:

I want that the arrow to move automaticaly to the right of the selected option. I tried with float: right, but not any results.

Maybe it is better to use an image here: content: '\003E';?

Body:
* {
    position: relative;
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    border-color: inherit;
}

form {
    width: 114px;
    height: 100%;
    padding-bottom: 75px;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-left: 30px;
}

ul {
    list-style: none;
}

.select {
    width: 225px;
    height: 40px;
    cursor: pointer;
    background-color: white;
    box-shadow: 0 2px 0 white;
    border-radius: 2px;
}

.select_expand {
    width: 0;
    height: 40px;
    position: absolute;
    top: 0;
    right: 0;
}

.select_expand::after {
    content: '\003E';
    position: absolute;
    top: 50%;
    right: 25px;

    transform: translate(-50%, -50%) rotate(90deg) scaleY(1.75);
    color: black;
    font-size: 10px;
    pointer-events: none;
    z-index: 2;
    transition: all 250ms cubic-bezier(.4, .25, .3, 1);

}

.select_expand:hover::after {
    opacity: 1;
}

.select_expand:checked::after {
    transform: translate(-50%, -50%) rotate(90deg) scaleX(-1) scaleY(1.75);
}

.select_expandLabel {
    display: block;
    width: 100%;
    height: 40px;
    position: absolute;
    top: 0;
    left: 0;
    cursor: pointer;
}

.select_close {
    display: none
}

.select_closeLabel {
    width: 100vw;
    height: 100vh;
    position: fixed;
    top: 0;
    left: 0;
    display: none;
}

.select_items {
    width: 100%;
    position: absolute;
    top: 0;
    left: 0;
    padding-top: 40px;

}

.select_input {
    display: none;

}

.select_label {
    transition: all 250ms cubic-bezier(.4, .25, .3, 1);
    display: block;
    height: 0;
    font-size: 18px;
    line-height: 40px;
    overflow: hidden;
    color: black;
    background-color: #fff;
    cursor: pointer;
    padding-left: 15px;

}

.select_label-placeholder {
    height: 40px;
    vertical-align: middle;
    position: absolute;
    top: 0;
    padding-left: 15px;

}

.select_expand:checked+.select_closeLabel {
    display: block;

}

.select_expand:checked+.select_closeLabel+.select_options .select_label:hover {
    background-color: #f7f7f7;
}

.select_expand:checked+.select_closeLabel+.select_options+.select_expandLabel {
    display: none;
}

.select_input:checked+.select_label {
    height: 40px;
    margin-top: -40px;/*changed*/

}

.select_expand:checked+.select_closeLabel+.select_options .select_label {
    height: 40px;
    /*box-shadow: 0 15px 30px 10px rgba(0, 0, 0, 0.1);*/

}
.select_options {
/*coment the below line and uncoment above for diffrent effect*/
    box-shadow: 0 15px 30px 10px rgba(0, 0, 0, 0.1);

}

<form>

    <ul class="select">
        <li>
            <input class="select_close" type="radio" name="awesomeness" id="awesomeness-close" value=""/>
            <span class="select_label select_label-placeholder">#</span>
        </li>

        <li class="select_items">
            <input class="select_expand" type="radio" name="awesomeness" id="awesomeness-opener"/>
            <label class="select_closeLabel" for="awesomeness-close"></label>

            <ul class="select_options">
                <li class="select_option">
                    <input class="select_input" type="radio" name="awesomeness" id="awesomeness-ridiculous"/>
                    <label class="select_label" for="awesomeness-ridiculous">@ ASD</label>
                </li>

                <li class="select_option">
                    <input class="select_input" type="radio" name="awesomeness" id="awesomeness-reasonable"/>
                    <label class="select_label" for="awesomeness-reasonable">E* ERD</label>
                </li>

                <li class="select_option">
                    <input class="select_input" type="radio" name="awesomeness" id="awesomeness-lacking"/>
                    <label class="select_label" for="awesomeness-lacking">@ TRF</label>
                </li>

                <li class="select_option">
                    <input class="select_input" type="radio" name="awesomeness" id="awesomeness-awesomeless"/>
                    <label class="select_label" for="awesomeness-awesomeless">% QWE</label>
                </li>
            </ul>

            <label class="select_expandLabel" for="awesomeness-opener"></label>
        </li>
    </ul>

</form>

First things first,

and first thing is putting ;

Second,

to put box shadow

add the code to .select_options

Third,

to avoid overlap

change right from 70px to 25px(reduce right means increase left)


问:
Difference between buffers in Kotlin flow
As far as I know there are three types of buffers in Kotlin flow: Buffer, Conflate and CollectLatest and I'm having trouble figuring out the differences between these three terminal operators.

```<code>flow.buffer().collect{...}
flow.collectLatest{...}
flow.conflate().collect{...}
</code>```

I apologize the brevity, but what are the differences between these buffers and when should we use each of them?

Any help is appreciated in advance.

答:
Normally, emitting and collecting code runs sequentially, "emitter" emits new value after previous one collected somewhere. ("Collected" means terminal operator's lambda is finished). Buffering allows to run emitting code concurrently with collecting code.

buffer() allows emitter to emit new values while the old ones is still being processed (and saves them in buffer for later).

collectLatest() restarts its lambda on each new value collected, even if old one is still being processed.

conflate() operator skips intermediate values, which means that after processing the current value, collector collects only the most recent value received during processing previous one (same as buffer(capacity = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST).

Body:
As far as I know there are three types of buffers in Kotlin flow: Buffer, Conflate and CollectLatest and I'm having trouble figuring out the differences between these three terminal operators.

flow.buffer().collect{...}
flow.collectLatest{...}
flow.conflate().collect{...}

I apologize the brevity, but what are the differences between these buffers and when should we use each of them?

Any help is appreciated in advance.


问:
jQuery .fadeOut problems in FireFox 6.0
So far, I have the fadeIn working, but the fadeOut has not been quite right.  Right now, as soon as the mouse leaves the hover area, it doesn't look like any fadeOut is happening at all.  I would like to have a smooth fade out that completes before the next animation (the next fadeIn) begins and doesn't queue up.  Basically this is over some links that are within  tags.  I'm in the home stretch now!

P.S. I know I'm not using .hover.  I'd rather stick with mouseover and mouseleave for now, or even mouseout.  Please accomodate this small request.

```<code><script>
    $("a").mouseover(function () {
        $("div").fadeIn(0, function () {
            $("span").fadeIn(3000,0.0);
        });
        return false;
    });

    $dequeue;

    $("a").mouseleave(function () {
        $("span").fadeOut(3000,0.0);
    });
</script>

<!DOCTYPE html>

<html>
<head>
<script type="text/javascript" src="jQuery.js"></script>
</head>
<body>

<a href="#">MouseOver!</a>

<div>

<h3><span>Sample Text</span></h3>

</div>
</body>
</html>
</code>```

Edit: 08/18/2011

I realized that there may be script conflicting with the one above.  I have an additional jquery script running on the same page.  By itself it works fine, but when I add the script for the text box (above) the .fadeOut on both images and text becomes ignored or at the very least, inconsistent.

2nd jQuery script:

```<code><script>
$(document).ready(function(){

$(".latest_img").fadeTo("slow", 0.0);
$(".latest_img").hover(function(){
$(this).fadeTo(1000, 1.0).dequeue();

},function(){
$(this).fadeTo(1000, 0.0).dequeue();
});
});
</script>
</code>```

Here is an example of one of the four "targets" that should prompt the text and image to display (there are four text boxes accompanying four images - each get shown by a mouseover on the target).

HTML:

```<code><div class="gallerycontainer">
<div width="100%" height="30%">

<a class="thumbnail" href="#thumb"><h2 class="ftb" id="tg1">Target A</h2>

<span class="txspan">
<img src="img/ima.jpg" class="latest_img" id="images" />
<h3 class="text"><br>Textbox content for Target A</h3></span></a>

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

答:
You do not have to use dequeue. Use stop() instead:

```<code>$("a").mouseover(function () {
    $("div").fadeIn(0, function () {
        $("span").fadeIn(3000,0.0);
    });
});

// using ".stop()" will stop the previous animation, and immediatly fade it out

$("a").mouseleave(function () {
    $("span").stop().fadeOut(3000,0.0);
});
</code>```

Title: jQuery .fadeOut problems in FireFox 6.0

Body:
So far, I have the fadeIn working, but the fadeOut has not been quite right.  Right now, as soon as the mouse leaves the hover area, it doesn't look like any fadeOut is happening at all.  I would like to have a smooth fade out that completes before the next animation (the next fadeIn) begins and doesn't queue up.  Basically this is over some links that are within  tags.  I'm in the home stretch now!

P.S. I know I'm not using .hover.  I'd rather stick with mouseover and mouseleave for now, or even mouseout.  Please accomodate this small request.

<!DOCTYPE html>

MouseOver!

Sample Text

Edit: 08/18/2011

I realized that there may be script conflicting with the one above.  I have an additional jquery script running on the same page.  By itself it works fine, but when I add the script for the text box (above) the .fadeOut on both images and text becomes ignored or at the very least, inconsistent.

2nd jQuery script:

Here is an example of one of the four "targets" that should prompt the text and image to display (there are four text boxes accompanying four images - each get shown by a mouseover on the target).

HTML:

Target A

Textbox content for Target A

Body:
You do not have to use dequeue. Use stop() instead:

$("a").mouseover(function () {
    $("div").fadeIn(0, function () {
        $("span").fadeIn(3000,0.0);
    });
});

// using ".stop()" will stop the previous animation, and immediatly fade it out

$("a").mouseleave(function () {
    $("span").stop().fadeOut(3000,0.0);
});


问:
ReactJS - Element type is invalid
I keep getting this weird error in my React that says

```<code>Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

Check the render method of `ContactTemplate`.
</code>```

I tried to remove each of the import to see where the error is, but nothing works.

My ContactTemplate.jsx:

```<code>import React from 'react';
import { Container } from '~/components/interface/Container';
import PreviewBar from '~/components/PreviewBar';
import HeroFull from '~/components/HeroFull/HeroFull';
import { Wrapper, Columns, Paragraph, BigText } from './ContactTemplate.styles';
import { Link } from '~/components/interface/Link';

const ContactTemplate = ({ preview }) => {
  const data = [
    {
      name: 'Name 1',
      job: 'Bestuursrechts',
      phone: '+31 (0) 612345678',
      email: 'Email',
      link: 'https://www.linkedin.com',
    },
    {
      name: 'Name 2',
      job: 'Intellectuele eigendom en contractenrecht',
      phone: '+31 (0) 612345678',
      email: 'email',
      link: 'https://www.linkedin.com',
    },
  ];

  return (
    <>
      <Wrapper>
        {preview && <PreviewBar />}
        <HeroFull
          title="Contact"
          intro="We offer ...."
        />
      </Wrapper>
      <Container>
        <Columns>
          {data.map(item => (
            <div>
              <BigText>{item.name}</BigText>
              <Paragraph>{item.job}</Paragraph>
              <Paragraph>{item.phone}</Paragraph>
              <Paragraph>{item.email}</Paragraph>
              <Link>{item.link}</Link>
            </div>
          ))}
        </Columns>
      </Container>
    </>
  );
};

export default ContactTemplate;
</code>```

Could someone help me out with this please?
If there are more files needed I'll add them on request.

答: I solved it myself. The first problem was that my Docker was stuck so I had to restart it. After I restarted it I tried to remove each import individually to see where the problem was and it was the { Link } that needed to be just Link. Thanks everyone else for helping!

Title: ReactJS - Element type is invalid

Body:
I keep getting this weird error in my React that says

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

Check the render method of `ContactTemplate`.

I tried to remove each of the import to see where the error is, but nothing works.

My ContactTemplate.jsx:

import React from 'react';
import { Container } from '~/components/interface/Container';
import PreviewBar from '~/components/PreviewBar';
import HeroFull from '~/components/HeroFull/HeroFull';
import { Wrapper, Columns, Paragraph, BigText } from './ContactTemplate.styles';
import { Link } from '~/components/interface/Link';

const ContactTemplate = ({ preview }) => {
  const data = [
    {
      name: 'Name 1',
      job: 'Bestuursrechts',
      phone: '+31 (0) 612345678',
      email: 'Email',
      link: 'https://www.linkedin.com',
    },
    {
      name: 'Name 2',
      job: 'Intellectuele eigendom en contractenrecht',
      phone: '+31 (0) 612345678',
      email: 'email',
      link: 'https://www.linkedin.com',
    },
  ];

  return (
    <>
      <Wrapper>
        {preview && <PreviewBar />}
        <HeroFull
          title="Contact"
          intro="We offer ...."
        />
      </Wrapper>
      <Container>
        <Columns>
          {data.map(item => (

              <BigText>{item.name}</BigText>
              <Paragraph>{item.job}</Paragraph>
              <Paragraph>{item.phone}</Paragraph>
              <Paragraph>{item.email}</Paragraph>
              <Link>{item.link}</Link>

          ))}
        </Columns>
      </Container>
    </>
  );
};

export default ContactTemplate;

Could someone help me out with this please?
If there are more files needed I'll add them on request.


问:
Import Jenkins WorkflowScript class
Instead of using def in my groovy scripts, I would like to be able to import the WorkflowScript class.

Instead of:

```<code>def script
</code>```

I want:

```<code>WorkflowScript script
</code>```

I want that because when I want to pass a script to a function, like get_branch(script) it usually crash. For a weird reason it works with constructor, not methods.

For my IDE, I would also need to be able to get the dependency, which I do not find on maven, any way for that ?

答:
One more option I have found

```<code>Script script
</code>```

And you don't need to import anything more.

Title: Import Jenkins WorkflowScript class

Body:
Instead of using def in my groovy scripts, I would like to be able to import the WorkflowScript class.

Instead of:

def script

I want:

WorkflowScript script

I want that because when I want to pass a script to a function, like get_branch(script) it usually crash. For a weird reason it works with constructor, not methods.

For my IDE, I would also need to be able to get the dependency, which I do not find on maven, any way for that ?

Body:
One more option I have found

Script script

And you don't need to import anything more.


问:
Run-Time error '3048' happening even though I close connections
I've been getting an error that I've never seen before. I keep seeing this:

Run-time error '3048':

Cannot open any more databases.

Having Googled it, it seems this happens when there are very complicated forms that have lots of lists or combo boxes that have their sources as a table/query. However, I've not changed these forms for a while now and I'm all of a sudden seeing this. Plus, my forms really aren't that complicated, usually just a single list and maybe 1 or 2 combo boxes. I just started seeing this error yesterday (2/2/22)

Almost in all cases I'm accessing the tables by using this code:

```<code>Dim rst As Recordset: Set rst = CurrentDb.OpenRecordset("table name or SQL statement")
</code>```

Then I'll access data using something like, whether it be AddNew, Edit, or just looping through a recordset.

```<code>With rst
    .AddNew
    .Fields("name") = "Value"
End With
</code>```

OR

```<code>Do Until rst.EOF
    'Do something
    .MoveNext
Loop
</code>```

And I've already double checked that every time I open a recordset I close it

```<code>rst.Close
Set rst = Nothing
</code>```

However, I keep seeing that error now. Is there some other way that I'm supposed to close these recordsets that properly closes the connection? I'm guessing opening these is causing something to linger that I'm not aware of.

the only solution I have right now is to completely restart my PC and then I can use it for a bit before I see the error again.

Thanks for your help!

EDIT: When I get that error, I can't even close everything in Access and manually open a table to look at it. I get this error message

Reserved error (-1104); there is no message for this error.

答: I also got these problems after updating Office 365 tot the latest version (221, build 14827.20158). When I close the Access application and reopen it, I immediately get the error. Then I first have to resatart my computer in order to have the application working until it reaches the max amount of conections.</p>

Body:
I've been getting an error that I've never seen before. I keep seeing this:

Run-time error '3048':

Cannot open any more databases.

Having Googled it, it seems this happens when there are very complicated forms that have lots of lists or combo boxes that have their sources as a table/query. However, I've not changed these forms for a while now and I'm all of a sudden seeing this. Plus, my forms really aren't that complicated, usually just a single list and maybe 1 or 2 combo boxes. I just started seeing this error yesterday (2/2/22)

Almost in all cases I'm accessing the tables by using this code:

Dim rst As Recordset: Set rst = CurrentDb.OpenRecordset("table name or SQL statement")

Then I'll access data using something like, whether it be AddNew, Edit, or just looping through a recordset.

With rst
    .AddNew
    .Fields("name") = "Value"
End With

OR

Do Until rst.EOF
    'Do something
    .MoveNext
Loop

And I've already double checked that every time I open a recordset I close it

rst.Close
Set rst = Nothing

However, I keep seeing that error now. Is there some other way that I'm supposed to close these recordsets that properly closes the connection? I'm guessing opening these is causing something to linger that I'm not aware of.

the only solution I have right now is to completely restart my PC and then I can use it for a bit before I see the error again.

Thanks for your help!

EDIT: When I get that error, I can't even close everything in Access and manually open a table to look at it. I get this error message

Reserved error (-1104); there is no message for this error.


问:
Plotly or geom_smooth get lost date format?
I have multiple time-series plots. An example plot and code can be found below. I construct the plot using ggplot2 and make it interactive using ggplotly().

However, date format on the smoothed curve get lost. Interactive chart shows date as some numeric values.

How can I fix the problem?

Thank you very much

```<code>structure(list(Date = structure(c(15736, 15764, 15795, 15825,
15856, 15886), class = "Date"), CLI = c(99.93, 100.3, 100.96,
100.71, 100.62, 101.15)), row.names = c(NA, -6L), class = c("tbl_df",
"tbl", "data.frame"))

plot5 <- df %>%
  ggplot(aes(x = Date, y = CLI))+
  geom_line(size = 0.5, alpha = 0.75, show.legend = FALSE, color = "steelblue4")+
  scale_x_date(date_breaks = "6 month", date_labels =  "%m/%y")+
  theme_pander()+
  geom_line(stat='smooth', method = "glm", alpha=0.5, color = "firebrick2", formula = y ~ poly(x, 5))+
  geom_ribbon(stat='smooth',method = "glm", se=TRUE,formula = y ~ poly(x, 5), alpha=0.01)+
  labs(x = "Date",
       y = "Composite Leading Indicator")
ggplotly(plot5)
</code>```

答:
Adapting my answer on this post to your case one option to get the date format in the tooltip would be to make use of the text aesthetic to manually create the tooltip and convert the numbers to proper dates like so:

```<code>plot <- df %>%
  ggplot(aes(x = Date, y = CLI)) +
  geom_line(size = 0.5, alpha = 0.75, show.legend = FALSE, color = "steelblue4") +
  scale_x_date(date_labels = "%m/%y") +
  # theme_pander()+
  geom_line(aes(text = paste(
    "date: ", as.Date(..x.., origin = "1970-01-01"), "<br>",
    "y:", ..y..
  )), stat = "smooth", method = "glm", alpha = 0.5, color = "firebrick2", formula = y ~ poly(x, 5)) +
  geom_ribbon(stat = "smooth", method = "glm", se = TRUE, formula = y ~ poly(x, 5), alpha = 0.01) +
  labs(
    x = "Date",
    y = "Composite Leading Indicator"
  )
ggplotly(plot, tooltip = c("text"))
</code>```

Body:
I have multiple time-series plots. An example plot and code can be found below. I construct the plot using ggplot2 and make it interactive using ggplotly().

However, date format on the smoothed curve get lost. Interactive chart shows date as some numeric values.

How can I fix the problem?

Thank you very much

structure(list(Date = structure(c(15736, 15764, 15795, 15825,
15856, 15886), class = "Date"), CLI = c(99.93, 100.3, 100.96,
100.71, 100.62, 101.15)), row.names = c(NA, -6L), class = c("tbl_df",
"tbl", "data.frame"))

plot5 <- df %>%
  ggplot(aes(x = Date, y = CLI))+
  geom_line(size = 0.5, alpha = 0.75, show.legend = FALSE, color = "steelblue4")+
  scale_x_date(date_breaks = "6 month", date_labels =  "%m/%y")+
  theme_pander()+
  geom_line(stat='smooth', method = "glm", alpha=0.5, color = "firebrick2", formula = y ~ poly(x, 5))+
  geom_ribbon(stat='smooth',method = "glm", se=TRUE,formula = y ~ poly(x, 5), alpha=0.01)+
  labs(x = "Date",
       y = "Composite Leading Indicator")
ggplotly(plot5)

Body:
Adapting my answer on this post to your case one option to get the date format in the tooltip would be to make use of the text aesthetic to manually create the tooltip and convert the numbers to proper dates like so:

plot <- df %>%
  ggplot(aes(x = Date, y = CLI)) +
  geom_line(size = 0.5, alpha = 0.75, show.legend = FALSE, color = "steelblue4") +
  scale_x_date(date_labels = "%m/%y") +
  # theme_pander()+
  geom_line(aes(text = paste(
    "date: ", as.Date(..x.., origin = "1970-01-01"), "<br>",
    "y:", ..y..
  )), stat = "smooth", method = "glm", alpha = 0.5, color = "firebrick2", formula = y ~ poly(x, 5)) +
  geom_ribbon(stat = "smooth", method = "glm", se = TRUE, formula = y ~ poly(x, 5), alpha = 0.01) +
  labs(
    x = "Date",
    y = "Composite Leading Indicator"
  )
ggplotly(plot, tooltip = c("text"))


问:
i want to align my elements so that they start in the same place (vertically)
I try to do some CSS and I have 4 items on a line.
I would like to align my 2 "sous-jacent de référence" but I don't know how can I do it.
I tried to use position: relative but it didn't work

there is my code:

body {
  background-color: rgb(0, 0, 0);
  text-align: center;
}

.title {
  color: white;
  border: 2px solid black;
  margin: 2%;
  padding-bottom: 2%;
}

.left {
  padding-left: 2%;
  float: left;
  color: white;
  font-size: 20px;
  padding-top: 2%;
}

.left2 {
  padding-left: 2%;
  float: left;
  color: white;
  font-size: 20px;
  padding-top: 2%;
}

.left3 {
  color: white;
  font-size: 20px;
  padding-top: 2%;
  position: absolute;
}

.right {
  float: left;
  padding-left: 30%;
  color: white;
  font-size: 20px;
  padding-top: 2%;
}

.right2 {
  float: left;
  padding-left: 30%;
  color: white;
  font-size: 20px;
  padding-top: 2%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>

</head>

<body>

  <div class="title">
    <h2>Formulaire</h2>

  </div>

  <div class="left">
    typologie du produit
  </div>
  <div class="left2">
    <input type="text" id="typologie" name="typologie" required minlength="2" maxlength="50" size="10"> </div>
  <div class="right">
    Sous-jacent de référence
  </div>
  <div class="left2">
    <input type="text" id="Sous-jacent" name="Sous-jacent" required minlength="2" maxlength="50" size="10"> </div>

  <div class="left">
    Nom du produit

  </div>
  <div class="left2">
    <input type="text" id="typologie" name="typologi2" required minlength="2" maxlength="50" size="10"> </div>

  <div class="right">
    Sous-jacent de référence
  </div>
  <div class="left2">
    <input type="text" id="Sous-jacent" name="Sous-jacent2" required minlength="2" maxlength="50" size="10"> </div>

</body>

</html></code>```

I want to say to my algorithm: "my 3 and div begins at x%"

I tried a lot of things (it works when I use float: right but it's quite confusing)

Thanks for your help!

答:
Remove all floats and padding associated with the left and right divs. Then nest each side into wrappers and use flexbox. Then you can space them by using gap. Lastly, you can restrict the width of each div's text so that the spacing is all the same and the inputs stack right on top of each other, you can do that by setting a min-width

body {
  background-color: rgb(0, 0, 0);
  text-align: center;
}

.title {
  color: white;
  border: 2px solid black;
  margin: 2%;
  padding-bottom: 2%;
}

.wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 40px;
}

.left,
.right {
  min-width: 170px;
  color: white;
  font-size: 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
   <head>
   </head>
   <body>
      <div class="title">
         <h2>Formulaire</h2>
      </div>
      <div class="wrapper">
         <div class="left">
            typologie du produit
         </div>
         <div class="left2">
            <input type="text" id="typologie" name="typologie" required minlength="2" maxlength="50" size="10">
         </div>
         <div class="right">
            Sous-jacent de référence
         </div>
         <div class="left2">
            <input type="text" id="Sous-jacent" name="Sous-jacent" required minlength="2" maxlength="50" size="10">
         </div>
       </div>
       <div class="wrapper">
         <div class="left">
            Nom du produit
         </div>
         <div class="left2">
            <input type="text" id="typologie" name="typologi2" required minlength="2" maxlength="50" size="10">
         </div>
         <div class="right">
            Sous-jacent de référence
         </div>
         <div class="left2">
            <input type="text" id="Sous-jacent" name="Sous-jacent2" required minlength="2" maxlength="50" size="10">
         </div>
      </div>
   </body>
</html></code>```

Body:
I try to do some CSS and I have 4 items on a line.
I would like to align my 2 "sous-jacent de référence" but I don't know how can I do it.
I tried to use position: relative but it didn't work

there is my code:

body {
  background-color: rgb(0, 0, 0);
  text-align: center;
}

.title {
  color: white;
  border: 2px solid black;
  margin: 2%;
  padding-bottom: 2%;
}

.left {
  padding-left: 2%;
  float: left;
  color: white;
  font-size: 20px;
  padding-top: 2%;
}

.left2 {
  padding-left: 2%;
  float: left;
  color: white;
  font-size: 20px;
  padding-top: 2%;
}

.left3 {
  color: white;
  font-size: 20px;
  padding-top: 2%;
  position: absolute;
}

.right {
  float: left;
  padding-left: 30%;
  color: white;
  font-size: 20px;
  padding-top: 2%;
}

.right2 {
  float: left;
  padding-left: 30%;
  color: white;
  font-size: 20px;
  padding-top: 2%;
}

<!DOCTYPE html>

Formulaire

    typologie du produit

    <input type="text" id="typologie" name="typologie" required minlength="2" maxlength="50" size="10">

    Sous-jacent de référence

    <input type="text" id="Sous-jacent" name="Sous-jacent" required minlength="2" maxlength="50" size="10">

    Nom du produit

    <input type="text" id="typologie" name="typologi2" required minlength="2" maxlength="50" size="10">

    Sous-jacent de référence

    <input type="text" id="Sous-jacent" name="Sous-jacent2" required minlength="2" maxlength="50" size="10">

I want to say to my algorithm: "my 3 and div begins at x%"

I tried a lot of things (it works when I use float: right but it's quite confusing)

Thanks for your help!

Body:
Remove all floats and padding associated with the left and right divs. Then nest each side into wrappers and use flexbox. Then you can space them by using gap. Lastly, you can restrict the width of each div's text so that the spacing is all the same and the inputs stack right on top of each other, you can do that by setting a min-width

body {
  background-color: rgb(0, 0, 0);
  text-align: center;
}

.title {
  color: white;
  border: 2px solid black;
  margin: 2%;
  padding-bottom: 2%;
}

.wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 40px;
}

.left,
.right {
  min-width: 170px;
  color: white;
  font-size: 20px;
}

<!DOCTYPE html>
<html>
   <head>
   </head>
   <body>
      <div class="title">
         <h2>Formulaire</h2>
      </div>
      <div class="wrapper">
         <div class="left">
            typologie du produit
         </div>
         <div class="left2">
            <input type="text" id="typologie" name="typologie" required minlength="2" maxlength="50" size="10">
         </div>
         <div class="right">
            Sous-jacent de référence
         </div>
         <div class="left2">
            <input type="text" id="Sous-jacent" name="Sous-jacent" required minlength="2" maxlength="50" size="10">
         </div>
       </div>
       <div class="wrapper">
         <div class="left">
            Nom du produit
         </div>
         <div class="left2">
            <input type="text" id="typologie" name="typologi2" required minlength="2" maxlength="50" size="10">
         </div>
         <div class="right">
            Sous-jacent de référence
         </div>
         <div class="left2">
            <input type="text" id="Sous-jacent" name="Sous-jacent2" required minlength="2" maxlength="50" size="10">
         </div>
      </div>
   </body>
</html>


问:
_TypeError (type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Iterable<dynamic>'

// To parse this JSON data, do
//
//     final plans = plansFromJson(jsonString);

import 'dart:convert';

List<Plans> PlansFromJson(String str) => List.from(json.decode(str))
    .map((x) => Plans.fromJson(Map.from(x)))
    .toList();
// ignore: non_constant_identifier_names
String PlansToJson(List<Plans> data) =>
    json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class Plans {
  Plans({
    required this.id,
    required this.title,
    required this.details,
    required this.selectSubCategory,
  });

  int id;
  String title;
  String details;
  List<SelectSubCategory> selectSubCategory;

  factory Plans.fromJson(Map<String, dynamic> json) => Plans(
        id: json["id"],
        title: json["title"],
        details: json["details"],
        selectSubCategory: List<SelectSubCategory>.from(
            json["select_sub_category"]
                .map((x) => SelectSubCategory.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "title": title,
        "details": details,
        "select_sub_category":
            List<dynamic>.from(selectSubCategory.map((x) => x.toJson())),
      };
}

class SelectSubCategory {
  SelectSubCategory({
    required this.id,
    required this.subcategorName,
    required this.details,
  });

  int id;
  String subcategorName;
  String details;

  factory SelectSubCategory.fromJson(Map<String, dynamic> json) =>
      SelectSubCategory(
        id: json["id"],
        subcategorName: json["subcategor_name"],
        details: json["details"],
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "subcategor_name": subcategorName,
        "details": details,
      };
}```

List PlansFromJson(String str) => List.from(json.decode(str))
.map((x) => Plans.fromJson(Map.from(x)))
.toList(); this line show the error _TypeError (type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Iterable' how to fix this error and why this error repeated my projects lot of times and explain

答:
```<code>json.decode(str)
</code>```

I doubt that str is an json object, not an array. So json.decode(str) return a Map.
I recommend you checkout retrofit library to auto handle json mapping.

Body:
// To parse this JSON data, do
//
//     final plans = plansFromJson(jsonString);

import 'dart:convert';

List<Plans> PlansFromJson(String str) => List.from(json.decode(str))
    .map((x) => Plans.fromJson(Map.from(x)))
    .toList();
// ignore: non_constant_identifier_names
String PlansToJson(List<Plans> data) =>
    json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class Plans {
  Plans({
    required this.id,
    required this.title,
    required this.details,
    required this.selectSubCategory,
  });

  int id;
  String title;
  String details;
  List<SelectSubCategory> selectSubCategory;

  factory Plans.fromJson(Map<String, dynamic> json) => Plans(
        id: json["id"],
        title: json["title"],
        details: json["details"],
        selectSubCategory: List<SelectSubCategory>.from(
            json["select_sub_category"]
                .map((x) => SelectSubCategory.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "title": title,
        "details": details,
        "select_sub_category":
            List<dynamic>.from(selectSubCategory.map((x) => x.toJson())),
      };
}

class SelectSubCategory {
  SelectSubCategory({
    required this.id,
    required this.subcategorName,
    required this.details,
  });

  int id;
  String subcategorName;
  String details;

  factory SelectSubCategory.fromJson(Map<String, dynamic> json) =>
      SelectSubCategory(
        id: json["id"],
        subcategorName: json["subcategor_name"],
        details: json["details"],
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "subcategor_name": subcategorName,
        "details": details,
      };
}

List PlansFromJson(String str) => List.from(json.decode(str))
.map((x) => Plans.fromJson(Map.from(x)))
.toList(); this line show the error _TypeError (type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Iterable' how to fix this error and why this error repeated my projects lot of times and explain

Body:
json.decode(str)

I doubt that str is an json object, not an array. So json.decode(str) return a Map.
I recommend you checkout retrofit library to auto handle json mapping.