问:
Navigation.navigate is not working under Touchableopacity in React-native
I am using useNavigation() to navigate from homescreen to another screen with onPress function inside TouchableOpacity. The navigation.navigate is not working. The onPress function call is successful but the screen is not navigating although the screen is named inside Navigation.stack().

Card component where the onPress is attached.

```<code>import { View, Text, TouchableOpacity,Image } from 'react-native'
import { StarIcon } from 'react-native-heroicons/solid'

import React from 'react'
import { MapPinIcon } from 'react-native-heroicons/outline'
import { urlFor } from '../sanity'
import { useNavigation } from '@react-navigation/native'

const RestaurantCards = ({
    id,
    imgUrl,
    title,
    rating,
    type,
    address,
    shortDescription,
    dishes,
    longitude,
    latitude
}) => {
  const navigation  = useNavigation()
  return (
    <View>
        <TouchableOpacity
        onPress = {()=>{
            navigation.navigate('Restaurant',{
                id,
                imgUrl,
                title,
                rating,
                type,
                address,
                shortDescription,
                dishes,
                longitude,
                latitude
            })
        }}

        className="bg-white mr-3 shadow"
        >
           <Image source = {{uri:urlFor(imgUrl).url()}} className = "h-36 rounded-sm object-cover"/>
            <View className = "px-3 pb-4">
                <Text className = "font-bold text-lg pt-2">{title}</Text>
                    <View className = "flex-row items-center space-x-1">
                        <StarIcon color={"green"} opacity = {0.5} size={22}/>
                        <Text className = "text-xs text-gray-500">
                            <Text className = "text-green-500">{rating}</Text> .{type}
                        </Text>
                    </View>

                    <View className="flex-row items-center space-x-1">
                        <MapPinIcon color="gray" opacity={0.4} size = {22}/>
                        <Text className="text-xs text-gray-500">NearBy - {address}</Text>
                    </View>
            </View>
        </TouchableOpacity>
    </View>
  )
}

export default RestaurantCards

</code>```

This is where the Restaurant Cards are populated:

```<code>import { View, Text, ScrollView } from 'react-native'
import React, { useEffect, useState } from 'react'
import { ArrowRightIcon } from 'react-native-heroicons/outline'
import RestaurantCards from './RestaurantCards'
import SanityClient from '../sanity';

const FeaturedRow = ({id,featureTitle,description,featureCategory}) => {
    const [restaurants,setRestaurants]  = useState([])
    useEffect(()=>{
        SanityClient.fetch(
        `
                *[_type == "feature" && _id == $id]{
                    ...,
                    restaurants[]->{
                    ...,
                    dishes[]->,
                    type->{
                        name
                    }
                }
        }[0]
        `,{id}
        ).then(data => {
            setRestaurants(data?.restaurants)
        }
        )
    },[restaurants])

  return (
    <View>
        <View className = "justify-between flex-row items-center mt-4 px-4">
            <Text className = "font-bold text-lg">{featureTitle}</Text>
            <ArrowRightIcon color={"#F67511"}/>
        </View>

        <Text className="text-xs text-gray-500 px-4">
            {description}
        </Text>

        <ScrollView horizontal
        contentContainerStyle={{
            paddingHorizontal:15
        }}
        showsHorizontalScrollIndicator = {false}
        className = "pt-4"
        >

            {restaurants.map(restaurant => restaurant!=null &&(
                <RestaurantCards
                id = {restaurant._id}
                imgUrl = {restaurant.image}
                title = {restaurant.name.toString()}
                rating = {restaurant.rating.toString()}
                type = {restaurant._type.toString()}
                address = {restaurant.address.toString()}
                shortDescription ={restaurant.short_description.toString()}
                dishes = {restaurant.dishes}
                longitude = {restaurant.long.toString()}
                latitude = {restaurant.lat.toString()}/>
            ))}
        </ScrollView>

    </View>

  )
}

export default FeaturedRow
</code>```

The home-screen that re-renders after the onPress on RestaurantCard is called.
HomeScreen.js

```<code>import { View, Text,Image, TextInput, ScrollView } from 'react-native'
import React, { useLayoutEffect } from 'react'
import { useNavigation } from '@react-navigation/native'
import { SafeAreaView } from 'react-native-safe-area-context'
import * as Icons from "react-native-heroicons/outline";
import Catagories from '../components/Catagories';
import FeaturedRow from '../components/FeaturedRow';
import { useState } from 'react';
import { useEffect } from 'react';
import SanityClient from '../sanity';

const HomeScreen = () => {
  const navigation = useNavigation()
  const [featureCategory,setFeatureCategory] = useState([])

  useLayoutEffect(()=>{
    navigation.setOptions({
      headerShown: false,

    })
  },[])

  useEffect(()=>{
    console.log('use Effect called again')
    SanityClient.fetch(`
    *[_type == "feature"]{
      ...,
      restaurants[]->{
        ...,
        dishes[]->
      }
    }
    `).then((data) => {
      setFeatureCategory(data)
    })
  },[])

  return (
    <SafeAreaView className="bg-white pt-5">
        <View className = "flex-row pb-3 items-center mx-4 space-x-2">
          <Image
              source = {{uri:"https://i.ibb.co/ZYvGfFY/Untitled-design-7.png"}}
              className = "h-7 w-7 bg-gray-300 p-4 rounded-full"
          />

        <View className="flex-1">
            <Text className = "font-bold text-gray-400 text-xs">Deliver Now!</Text>
            <Text className = "font-bold text-xl">
              Current Location
              <Icons.ChevronDownIcon size={20} color="#F67511" />
            </Text>
        </View>

        <Icons.UserIcon size={25} color="#F67511"/>
      </View>

      <View className="flex-row items-center space-x-2 pb-2 mx-4">
        <View className="flex-row space-x-2 flex-1 bg-gray-100 p-3">
          <Icons.MagnifyingGlassIcon color="#F67511" size={20}/>
          <TextInput placeholder="Restaurants and Cafe" keyboardType="default"/>
        </View>

        <Icons.AdjustmentsVerticalIcon color="#F67511"/>

      </View>

      {/* Body */}

      <ScrollView className="bg-gray-100"
      contentContainerStyle={{
        paddingBottom:100
      }}>
        <Catagories/>
        {featureCategory?.map(category=>(
            <FeaturedRow
            id={category._id}
            featureTitle={category.name}
            description={category.short_description}
            />
        ))}

      </ScrollView>

    </SafeAreaView>
  )
}

export default HomeScreen
</code>```

The expected Screen where it should navigate to:

```<code>import { View, Text } from 'react-native'
import React from 'react'

const RestaurantScreen = () => {
  return (
    <View>
      <Text>RestaurantScreen</Text>
    </View>
  )
}

export default RestaurantScreen
</code>```

The main App component where the navigation screens name are set.

```<code>import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View } from 'react-native';
import HomeScreen from './screens/HomeScreen';
import RestaurantScreen from './screens/HomeScreen';

export default function App() {
  const Stack = createStackNavigator()
  return (
    <NavigationContainer>
        <Stack.Navigator>
          <Stack.Screen name='Home' component={HomeScreen}/>
          <Stack.Screen name='Restaurant' component={RestaurantScreen}/>
        </Stack.Navigator>
    </NavigationContainer>
  );
}

</code>```

After first time onPress the MainScreen just reloads. After, the screens doesn't respond anything onPress to the cards. Also no error is shown up.

Body:
I am using useNavigation() to navigate from homescreen to another screen with onPress function inside TouchableOpacity. The navigation.navigate is not working. The onPress function call is successful but the screen is not navigating although the screen is named inside Navigation.stack().

Card component where the onPress is attached.

import { View, Text, TouchableOpacity,Image } from 'react-native'
import { StarIcon } from 'react-native-heroicons/solid'

import React from 'react'
import { MapPinIcon } from 'react-native-heroicons/outline'
import { urlFor } from '../sanity'
import { useNavigation } from '@react-navigation/native'

const RestaurantCards = ({
    id,
    imgUrl,
    title,
    rating,
    type,
    address,
    shortDescription,
    dishes,
    longitude,
    latitude
}) => {
  const navigation  = useNavigation()
  return (
    <View>
        <TouchableOpacity
        onPress = {()=>{
            navigation.navigate('Restaurant',{
                id,
                imgUrl,
                title,
                rating,
                type,
                address,
                shortDescription,
                dishes,
                longitude,
                latitude
            })
        }}

        className="bg-white mr-3 shadow"
        >
           <Image source = {{uri:urlFor(imgUrl).url()}} className = "h-36 rounded-sm object-cover"/>
            <View className = "px-3 pb-4">
                <Text className = "font-bold text-lg pt-2">{title}</Text>
                    <View className = "flex-row items-center space-x-1">
                        <StarIcon color={"green"} opacity = {0.5} size={22}/>
                        <Text className = "text-xs text-gray-500">
                            <Text className = "text-green-500">{rating}</Text> .{type}
                        </Text>
                    </View>

                    <View className="flex-row items-center space-x-1">
                        <MapPinIcon color="gray" opacity={0.4} size = {22}/>
                        <Text className="text-xs text-gray-500">NearBy - {address}</Text>
                    </View>
            </View>
        </TouchableOpacity>
    </View>
  )
}

export default RestaurantCards

This is where the Restaurant Cards are populated:

import { View, Text, ScrollView } from 'react-native'
import React, { useEffect, useState } from 'react'
import { ArrowRightIcon } from 'react-native-heroicons/outline'
import RestaurantCards from './RestaurantCards'
import SanityClient from '../sanity';

const FeaturedRow = ({id,featureTitle,description,featureCategory}) => {
    const [restaurants,setRestaurants]  = useState([])
    useEffect(()=>{
        SanityClient.fetch(
        `
                *[_type == "feature" && _id == $id]{
                    ...,
                    restaurants[]->{
                    ...,
                    dishes[]->,
                    type->{
                        name
                    }
                }
        }[0]
        `,{id}
        ).then(data => {
            setRestaurants(data?.restaurants)
        }
        )
    },[restaurants])

  return (
    <View>
        <View className = "justify-between flex-row items-center mt-4 px-4">
            <Text className = "font-bold text-lg">{featureTitle}</Text>
            <ArrowRightIcon color={"#F67511"}/>
        </View>

        <Text className="text-xs text-gray-500 px-4">
            {description}
        </Text>

        <ScrollView horizontal
        contentContainerStyle={{
            paddingHorizontal:15
        }}
        showsHorizontalScrollIndicator = {false}
        className = "pt-4"
        >

            {restaurants.map(restaurant => restaurant!=null &&(
                <RestaurantCards
                id = {restaurant._id}
                imgUrl = {restaurant.image}
                title = {restaurant.name.toString()}
                rating = {restaurant.rating.toString()}
                type = {restaurant._type.toString()}
                address = {restaurant.address.toString()}
                shortDescription ={restaurant.short_description.toString()}
                dishes = {restaurant.dishes}
                longitude = {restaurant.long.toString()}
                latitude = {restaurant.lat.toString()}/>
            ))}
        </ScrollView>

    </View>

  )
}

export default FeaturedRow

The home-screen that re-renders after the onPress on RestaurantCard is called.
HomeScreen.js

import { View, Text,Image, TextInput, ScrollView } from 'react-native'
import React, { useLayoutEffect } from 'react'
import { useNavigation } from '@react-navigation/native'
import { SafeAreaView } from 'react-native-safe-area-context'
import * as Icons from "react-native-heroicons/outline";
import Catagories from '../components/Catagories';
import FeaturedRow from '../components/FeaturedRow';
import { useState } from 'react';
import { useEffect } from 'react';
import SanityClient from '../sanity';

const HomeScreen = () => {
  const navigation = useNavigation()
  const [featureCategory,setFeatureCategory] = useState([])

  useLayoutEffect(()=>{
    navigation.setOptions({
      headerShown: false,

    })
  },[])

  useEffect(()=>{
    console.log('use Effect called again')
    SanityClient.fetch(`
    *[_type == "feature"]{
      ...,
      restaurants[]->{
        ...,
        dishes[]->
      }
    }
    `).then((data) => {
      setFeatureCategory(data)
    })
  },[])

  return (
    <SafeAreaView className="bg-white pt-5">
        <View className = "flex-row pb-3 items-center mx-4 space-x-2">
          <Image
              source = {{uri:"https://i.ibb.co/ZYvGfFY/Untitled-design-7.png"}}
              className = "h-7 w-7 bg-gray-300 p-4 rounded-full"
          />

        <View className="flex-1">
            <Text className = "font-bold text-gray-400 text-xs">Deliver Now!</Text>
            <Text className = "font-bold text-xl">
              Current Location
              <Icons.ChevronDownIcon size={20} color="#F67511" />
            </Text>
        </View>

        <Icons.UserIcon size={25} color="#F67511"/>
      </View>

      <View className="flex-row items-center space-x-2 pb-2 mx-4">
        <View className="flex-row space-x-2 flex-1 bg-gray-100 p-3">
          <Icons.MagnifyingGlassIcon color="#F67511" size={20}/>
          <TextInput placeholder="Restaurants and Cafe" keyboardType="default"/>
        </View>

        <Icons.AdjustmentsVerticalIcon color="#F67511"/>

      </View>

      {/* Body */}

      <ScrollView className="bg-gray-100"
      contentContainerStyle={{
        paddingBottom:100
      }}>
        <Catagories/>
        {featureCategory?.map(category=>(
            <FeaturedRow
            id={category._id}
            featureTitle={category.name}
            description={category.short_description}
            />
        ))}

      </ScrollView>

    </SafeAreaView>
  )
}

export default HomeScreen

The expected Screen where it should navigate to:

import { View, Text } from 'react-native'
import React from 'react'

const RestaurantScreen = () => {
  return (
    <View>
      <Text>RestaurantScreen</Text>
    </View>
  )
}

export default RestaurantScreen

The main App component where the navigation screens name are set.

import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View } from 'react-native';
import HomeScreen from './screens/HomeScreen';
import RestaurantScreen from './screens/HomeScreen';

export default function App() {
  const Stack = createStackNavigator()
  return (
    <NavigationContainer>
        <Stack.Navigator>
          <Stack.Screen name='Home' component={HomeScreen}/>
          <Stack.Screen name='Restaurant' component={RestaurantScreen}/>
        </Stack.Navigator>
    </NavigationContainer>
  );
}

After first time onPress the MainScreen just reloads. After, the screens doesn't respond anything onPress to the cards. Also no error is shown up.


来源: stackexchange

问:
gets() function not working as expected in C
I made a structure and tried obtaining the name using gets(). It worked for the first iteration but accepted nothing for the next iterations.

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

struct student{
    int rollno;
    char name[15];
    struct {
        int sub1;
        int sub2;
        int sub3;
    }marks;
}fs[3];

int main(){
    int marks, sub1, sub2, sub3, x, y, count;
    struct student temp;
    for (x=0; x<3; x++){
        printf("\nEnter details of the student %d:\n", x+1);
        printf("Please Enter your name: ");
        gets(fs[x].name);
        printf("Please Enter your roll no: ");
        scanf("%d", &fs[x].rollno);
        printf("Please Enter your marks for sub 1: ");
        scanf("%d", &fs[x].marks.sub1);
        printf("Please Enter your marks for sub 2: ");
        scanf("%d", &fs[x].marks.sub2);
        printf("Please Enter your marks for sub 3: ");
        scanf("%d", &fs[x].marks.sub3);
    }
</code>```

The output is something like this. I don't understand if it works for the first time why does it fail for the second iteration itself.

```<code>Enter details of the student 1:
Please Enter your name: Louis
Please Enter your roll no: 12
Please Enter your marks for sub 1: 87
Please Enter your marks for sub 2: 79
Please Enter your marks for sub 3: 83

Enter details of the student 2:
Please Enter your name: Please Enter your roll no: 4
Please Enter your marks for sub 1: 5
Please Enter your marks for sub 2: 3
Please Enter your marks for sub 3: 2

Enter details of the student 3:
Please Enter your name: Please Enter your roll no: 54
Please Enter your marks for sub 1: 32
Please Enter your marks for sub 2: 45
Please Enter your marks for sub 3: 34
Total & Average of each student.
</code>```

The names for the next iterations are taken to ' '. Moreover can any other method be used as I am very new to C.

ContentLicense: CC BY-SA 4.0

Body:
I made a structure and tried obtaining the name using gets(). It worked for the first iteration but accepted nothing for the next iterations.

#include <stdio.h>

struct student{
    int rollno;
    char name[15];
    struct {
        int sub1;
        int sub2;
        int sub3;
    }marks;
}fs[3];

int main(){
    int marks, sub1, sub2, sub3, x, y, count;
    struct student temp;
    for (x=0; x<3; x++){
        printf("\nEnter details of the student %d:\n", x+1);
        printf("Please Enter your name: ");
        gets(fs[x].name);
        printf("Please Enter your roll no: ");
        scanf("%d", &fs[x].rollno);
        printf("Please Enter your marks for sub 1: ");
        scanf("%d", &fs[x].marks.sub1);
        printf("Please Enter your marks for sub 2: ");
        scanf("%d", &fs[x].marks.sub2);
        printf("Please Enter your marks for sub 3: ");
        scanf("%d", &fs[x].marks.sub3);
    }

The output is something like this. I don't understand if it works for the first time why does it fail for the second iteration itself.

Enter details of the student 1:
Please Enter your name: Louis
Please Enter your roll no: 12
Please Enter your marks for sub 1: 87
Please Enter your marks for sub 2: 79
Please Enter your marks for sub 3: 83

Enter details of the student 2:
Please Enter your name: Please Enter your roll no: 4
Please Enter your marks for sub 1: 5
Please Enter your marks for sub 2: 3
Please Enter your marks for sub 3: 2

Enter details of the student 3:
Please Enter your name: Please Enter your roll no: 54
Please Enter your marks for sub 1: 32
Please Enter your marks for sub 2: 45
Please Enter your marks for sub 3: 34
Total & Average of each student.

The names for the next iterations are taken to ' '. Moreover can any other method be used as I am very new to C.


问:
pyglet does not allow to draw sprites with just a region of a image?
Question is simple.

Trying to make simple 2d rogue-like with single texture for map (ascii table)

Seems like pyglet does not allow to draw sprites with just a region of a its image.
For doing so i need to implement my own Sprite | Batch?


问:
Trying to figure out making a popup window with form in JavaScript, also cookies to remember login attempts for 5 minutes
I have searched around everywhere and no answers to this have shown up.
I am trying to make a login page open up in a popup window, with a fixed size, fitting the form.
You don't need to reprimand me about keeping login info client side, it's just an experiment.
Here's my form, with JS and CSS as well, along with my home page that has a button to redirect to the login and signup pages. (The signup page isn't working yet, and I'll probably ask about how to do that too but that's another thing altogether)
The home page is nowhere near complete obviously.
I just want the page to open the login page as a window, and then people can get redirected to the success.html page with their number in it.
The success pages should also appear in the original window, not the popup.

You also don't need to tell me how awful and crude my coding is, I am new to all this.

Thanks!

(P.S.- If anyone happens to know how to use cookies to make the site remember someone's login attempts for 5 minutes even when/if they close the site that would be awsome!!)

These are my files:

LOGIN PAGE HTML:

var attempt = 3; // Variable to count number of attempts.
// Below function Executes on click of login button.
function validate() {
  var username = document.getElementById("username").value;
  var password = document.getElementById("password").value;

  if (username == "Formget" && password == "formget#123") {
    alert("Logged in successfully. Welcome, User 1.");
    window.location = "success1.html"; // Redirecting to other page.
    return false;
  } else if (username == "Formget2" && password == "formget#123") {
    alert("Logged in successfully. Welcome, User 2.");
    window.location = "success2.html"; // Redirecting to other page.
    return false;
  } else if (username == "Formget3" && password == "formget#123") {
    alert("Logged in successfully. Welcome, User 3.");
    window.location = "success3.html"; // Redirecting to other page.
    return false;
  } else {
    attempt--; // Decrementing by one.
    alert("You have left " + attempt + " attempt(s).");
    // Disabling fields after 3 attempts.
    if (attempt == 0) {
      alert("You have run out of attempts, please try again in 5 minutes.");
      document.getElementById("username").disabled = true;
      document.getElementById("password").disabled = true;
      document.getElementById("submit").disabled = true;
    }
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import url(http://fonts.googleapis.com/css?family=Raleway);
h2 {
  background-color: #FEFFED;
  padding: 30px 35px;
  margin: -10px -50px;
  text-align: center;
  border-radius: 10px 10px 0 0;
}

hr {
  margin: 10px -50px;
  border: 0;
  border-top: 1px solid #ccc;
  margin-bottom: 40px;
}

div.container {
  width: 900px;
  height: 610px;
  margin: 35px auto;
  font-family: 'Raleway', sans-serif;
}

div.main {
  width: 300px;
  padding: 10px 50px 25px;
  border: 2px solid gray;
  border-radius: 10px;
  font-family: 'Audiowide', monospace;
  float: left;
  margin-top: 50px;
}

input[type=text],
input[type=password] {
  width: 100%;
  height: 40px;
  padding: 5px;
  margin-bottom: 25px;
  margin-top: 5px;
  border: 2px solid #ccc;
  color: #4f4f4f;
  font-size: 16px;
  border-radius: 5px;
}

label {
  color: #464646;
  text-shadow: 0 1px 0 #fff;
  font-size: 14px;
  font-weight: bold;
}

center {
  font-size: 32px;
}

.note {
  color: red;
}

.valid {
  color: green;
}

.back {
  text-decoration: none;
  border: 1px solid rgb(0, 143, 255);
  background-color: rgb(0, 214, 255);
  padding: 3px 20px;
  border-radius: 2px;
  color: black;
}

input[type=button] {
  font-size: 16px;
  background: linear-gradient(#ffbc00 5%, #ffdd7f 100%);
  border: 1px solid #e5a900;
  color: #4E4D4B;
  font-weight: bold;
  cursor: pointer;
  width: 100%;
  border-radius: 5px;
  padding: 10px 0;
  outline: none;
}

input[type=button]:hover {
  background: linear-gradient(#ffdd7f 5%, #ffbc00 100%);
}</code>```

  <title>Log In</title>
  <link rel="stylesheet" href="login.css" />

Log In

      <form id="form_id" method="post" name="myform">
        User Name :
        <input type="text" name="username" id="username" />
        Password :
        <input type="password" name="password" id="password" />
        <input type="button" value="Login" id="submit" onclick="validate()" />
      </form>

```
</div>
</div>
</p>
<p>HOME PAGE HTML (CSS INSIDE):</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>a {
  border: 1px solid black;
  background-color: lightblue;
  padding: 5px;
  border-radius: 25px;
  text-decoration: none;
  font-family: 'Audiowide', monospace;
  color: black;
}</code>```

Log In
Sign In```

The files above are as follows, in order:
login
login.css
login.js
home

My goal was to to make the login pop up in a new window and then redirect to each user's specific success page, but instead it opens both a window and a tab with the page, not just a window. The window also is not fixed size.

I also am looking to use cookies for the login attempts, as I said, and any tips on that would also be helpful.

Body:
I have searched around everywhere and no answers to this have shown up.
I am trying to make a login page open up in a popup window, with a fixed size, fitting the form.
You don't need to reprimand me about keeping login info client side, it's just an experiment.
Here's my form, with JS and CSS as well, along with my home page that has a button to redirect to the login and signup pages. (The signup page isn't working yet, and I'll probably ask about how to do that too but that's another thing altogether)
The home page is nowhere near complete obviously.
I just want the page to open the login page as a window, and then people can get redirected to the success.html page with their number in it.
The success pages should also appear in the original window, not the popup.

You also don't need to tell me how awful and crude my coding is, I am new to all this.

Thanks!

(P.S.- If anyone happens to know how to use cookies to make the site remember someone's login attempts for 5 minutes even when/if they close the site that would be awsome!!)

These are my files:

LOGIN PAGE HTML:

var attempt = 3; // Variable to count number of attempts.
// Below function Executes on click of login button.
function validate() {
  var username = document.getElementById("username").value;
  var password = document.getElementById("password").value;

  if (username == "Formget" && password == "formget#123") {
    alert("Logged in successfully. Welcome, User 1.");
    window.location = "success1.html"; // Redirecting to other page.
    return false;
  } else if (username == "Formget2" && password == "formget#123") {
    alert("Logged in successfully. Welcome, User 2.");
    window.location = "success2.html"; // Redirecting to other page.
    return false;
  } else if (username == "Formget3" && password == "formget#123") {
    alert("Logged in successfully. Welcome, User 3.");
    window.location = "success3.html"; // Redirecting to other page.
    return false;
  } else {
    attempt--; // Decrementing by one.
    alert("You have left " + attempt + " attempt(s).");
    // Disabling fields after 3 attempts.
    if (attempt == 0) {
      alert("You have run out of attempts, please try again in 5 minutes.");
      document.getElementById("username").disabled = true;
      document.getElementById("password").disabled = true;
      document.getElementById("submit").disabled = true;
    }
  }
}

@import url(http://fonts.googleapis.com/css?family=Raleway);
h2 {
  background-color: #FEFFED;
  padding: 30px 35px;
  margin: -10px -50px;
  text-align: center;
  border-radius: 10px 10px 0 0;
}

hr {
  margin: 10px -50px;
  border: 0;
  border-top: 1px solid #ccc;
  margin-bottom: 40px;
}

div.container {
  width: 900px;
  height: 610px;
  margin: 35px auto;
  font-family: 'Raleway', sans-serif;
}

div.main {
  width: 300px;
  padding: 10px 50px 25px;
  border: 2px solid gray;
  border-radius: 10px;
  font-family: 'Audiowide', monospace;
  float: left;
  margin-top: 50px;
}

input[type=text],
input[type=password] {
  width: 100%;
  height: 40px;
  padding: 5px;
  margin-bottom: 25px;
  margin-top: 5px;
  border: 2px solid #ccc;
  color: #4f4f4f;
  font-size: 16px;
  border-radius: 5px;
}

label {
  color: #464646;
  text-shadow: 0 1px 0 #fff;
  font-size: 14px;
  font-weight: bold;
}

center {
  font-size: 32px;
}

.note {
  color: red;
}

.valid {
  color: green;
}

.back {
  text-decoration: none;
  border: 1px solid rgb(0, 143, 255);
  background-color: rgb(0, 214, 255);
  padding: 3px 20px;
  border-radius: 2px;
  color: black;
}

input[type=button] {
  font-size: 16px;
  background: linear-gradient(#ffbc00 5%, #ffdd7f 100%);
  border: 1px solid #e5a900;
  color: #4E4D4B;
  font-weight: bold;
  cursor: pointer;
  width: 100%;
  border-radius: 5px;
  padding: 10px 0;
  outline: none;
}

input[type=button]:hover {
  background: linear-gradient(#ffdd7f 5%, #ffbc00 100%);
}

  <title>Log In</title>
  <link rel="stylesheet" href="login.css" />

Log In

      <form id="form_id" method="post" name="myform">
        User Name :
        <input type="text" name="username" id="username" />
        Password :
        <input type="password" name="password" id="password" />
        <input type="button" value="Login" id="submit" onclick="validate()" />
      </form>

HOME PAGE HTML (CSS INSIDE):

a {
  border: 1px solid black;
  background-color: lightblue;
  padding: 5px;
  border-radius: 25px;
  text-decoration: none;
  font-family: 'Audiowide', monospace;
  color: black;
}

Log In
Sign In

The files above are as follows, in order:
login
login.css
login.js
home

My goal was to to make the login pop up in a new window and then redirect to each user's specific success page, but instead it opens both a window and a tab with the page, not just a window. The window also is not fixed size.

I also am looking to use cookies for the login attempts, as I said, and any tips on that would also be helpful.


问:
How can I use DataGridView's CellEnter and CellLeave events?
I need to handle some things during a cell enter and a cell leave.  However, I'm finding that these are fired at times where the cell is not physically being entered (tabbed into or mouse-clicked).  For instance, they seem to be getting fired when I change the data source.  I've overridden the OnDataSourceChanged event in such a way:

```<code>protected override void OnDataSourceChanged(EventArgs e)
{
  _isBinding = true;
  base.OnDataSoruceChanged(e);
  _isBinding = false;
}
</code>```

Then, I use the _isBinding flag in the CellEnter event to bypass my logic.  However, then I saw that the OnBindingContextChanged event was also triggering these event.  I could override this event also, but when does it end?  There could be other events that call the CellEnter/CellLeave events that I haven't tested.  Is there a better way?

ContentLicense: CC BY-SA 3.0

Body:
I need to handle some things during a cell enter and a cell leave.  However, I'm finding that these are fired at times where the cell is not physically being entered (tabbed into or mouse-clicked).  For instance, they seem to be getting fired when I change the data source.  I've overridden the OnDataSourceChanged event in such a way:

protected override void OnDataSourceChanged(EventArgs e)
{
  _isBinding = true;
  base.OnDataSoruceChanged(e);
  _isBinding = false;
}

Then, I use the _isBinding flag in the CellEnter event to bypass my logic.  However, then I saw that the OnBindingContextChanged event was also triggering these event.  I could override this event also, but when does it end?  There could be other events that call the CellEnter/CellLeave events that I haven't tested.  Is there a better way?


问:
Cypress test fails due to Mongo ObjectId in string from Mock DB
Trying to make a suite of Cypress tests on my Angular app and using a mock MongoDB to test CRUD on my app. The test fails due to a section of the DB that I think the live version knows how to work with.

```<code>it('visits the administrator page', () => {
 cy.visit('/administrator');
 cy.get('.bi-person-fill-gear').first().click();
</code>```

On the live version, it visits the admin page and finds the first edit icon, clicks it and it opens up the edit component with the data populated as it's set up in the rest of the project.

```<code>it('Intercepts the API GET to /administrator', () => {
 cy.viewport(1366, 900);
 cy.intercept('GET', '/products', {
  fixture: 'intercept/teeshop.json',
 }).as('getProducts-Fixture');
 cy.visit('/administrator');
 cy.get('.bi-person-fill-gear').first().click();
</code>```

The intercept version uses the mockdb data as it's meant to, and clicks through to the administrator link as expected but when it clicks the edit icon it errors on the URL.

```<code>Error: NG04002: Cannot match any routes. URL Segment: 'administrator/edit;$oid=63b5a4b7affeeb54ba2ed910'
</code>```

Comparing live to mock, it appears that; $oid= is being added via the mockdb so my logical course of action was to simply change the mockdb _id line from:

```<code>"_id": {
 "$oid": "63b5a4b7affeeb54ba2ed910"
},
</code>```

to

```<code>"_id": "63b5a4b7affeeb54ba2ed910",
</code>```

Although the test now completes and opens up the edit page, populated with the data, it's is back to using the live data on that item.  I edited the first item name on the mock DB with the word Mock prefixed so I could identify it while I setup the tests.

Does anyone know why the intercept is now being ignored and it's opening the live version, but more importantly any pointers on how to make my click request not fail on the oid. This is only part of the suite with me testing all CRUD operations and my assumption is that it will fail every time for the same reason without working out why it's doing it.

Body:
Trying to make a suite of Cypress tests on my Angular app and using a mock MongoDB to test CRUD on my app. The test fails due to a section of the DB that I think the live version knows how to work with.

it('visits the administrator page', () => {
 cy.visit('/administrator');
 cy.get('.bi-person-fill-gear').first().click();

On the live version, it visits the admin page and finds the first edit icon, clicks it and it opens up the edit component with the data populated as it's set up in the rest of the project.

it('Intercepts the API GET to /administrator', () => {
 cy.viewport(1366, 900);
 cy.intercept('GET', '/products', {
  fixture: 'intercept/teeshop.json',
 }).as('getProducts-Fixture');
 cy.visit('/administrator');
 cy.get('.bi-person-fill-gear').first().click();

The intercept version uses the mockdb data as it's meant to, and clicks through to the administrator link as expected but when it clicks the edit icon it errors on the URL.

Error: NG04002: Cannot match any routes. URL Segment: 'administrator/edit;$oid=63b5a4b7affeeb54ba2ed910'

Comparing live to mock, it appears that; $oid= is being added via the mockdb so my logical course of action was to simply change the mockdb _id line from:

"_id": {
 "$oid": "63b5a4b7affeeb54ba2ed910"
},

to

"_id": "63b5a4b7affeeb54ba2ed910",

Although the test now completes and opens up the edit page, populated with the data, it's is back to using the live data on that item.  I edited the first item name on the mock DB with the word Mock prefixed so I could identify it while I setup the tests.

Does anyone know why the intercept is now being ignored and it's opening the live version, but more importantly any pointers on how to make my click request not fail on the oid. This is only part of the suite with me testing all CRUD operations and my assumption is that it will fail every time for the same reason without working out why it's doing it.


问:
Flask: How to pass a parameter to create_app when running a CLI command
My create_app is structured as follow:

```<code>def create_app(my_condition = True):
  ...
  if (my_condition):
    ...
</code>```

When running the server this is fine and I want to use the default value of True for my_condition. I have also set up a custom command in a blueprint:

```<code>@blueprint.cli.command('do_this')
def do_this():
  ...
</code>```

How could I set it up so that when running this custom command as flask do_this, the create_app could be passed a value of False to the my_condition parameter.

Alternatively, could I have a different create_app for running as a server and for running as CLI?

I tried to find a way of doing this from the documentation and google but couldn't really figure something out.

My goal is basically to have a create_app that executes some database checking code when starting up the server but doesn't execute that code when running my CLI commands (which includes a command to create the database) or my unit tests (which use a separate database). As structured now I can pass parameters to create_app in my unit tests but not when running a CLI command.

Body:
My create_app is structured as follow:

def create_app(my_condition = True):
  ...
  if (my_condition):
    ...

When running the server this is fine and I want to use the default value of True for my_condition. I have also set up a custom command in a blueprint:

@blueprint.cli.command('do_this')
def do_this():
  ...

How could I set it up so that when running this custom command as flask do_this, the create_app could be passed a value of False to the my_condition parameter.

Alternatively, could I have a different create_app for running as a server and for running as CLI?

I tried to find a way of doing this from the documentation and google but couldn't really figure something out.

My goal is basically to have a create_app that executes some database checking code when starting up the server but doesn't execute that code when running my CLI commands (which includes a command to create the database) or my unit tests (which use a separate database). As structured now I can pass parameters to create_app in my unit tests but not when running a CLI command.


问:
GetResponse is throwing time out error after several requests to JIRA Cloud Zephyr
After couple of execution, invoke code activity is encountering exception.

Dim fr As System.Net.HttpWebRequest
Dim targetURI As New Uri(strURL)

fr = DirectCast(HttpWebRequest.Create(targetURI), System.Net.HttpWebRequest)

Dim webProxy As IWebProxy = New WebProxy(strIpAddressAndPort)
webProxy.Credentials = New NetworkCredential(strProxyUsername, strProxyPassword)
fr.Proxy = webProxy
fr.Timeout = 90000
fr.KeepAlive = True

fr.Headers.Add(“Authorization”, jwtOutput)

fr.Headers.Add(“zapiAccessKey”, “MWExM2QyZTYtYzBlMi0zODI5LWIzMjUtZWNjZDJjMDBkODQ5IDYyMjhlODliYzg4ZjEwMDA2ODMyNWRhNCBVU0VSX0RFRkFVTFRf”)

Using res As HttpWebResponse = DirectCast(fr.GetResponse(), System.Net.HttpWebResponse)

webRes = res
Dim html As String = New StreamReader(res.GetResponseStream()).ReadToEnd()
strHtml = html
fr.GetResponse.Close()
res.Dispose()
res.Close()
End Using

Error: The operation has timed out at GetResponse.

It is happening after some couple of requests.

Any help?

Using Uipath>InvokeCode activity

GetResponse should return response but failed due to time out issue.


问:
I want to remove/hide the toolbar from mui DataTable
Is there anyway I can remove or hide the toolbar present in the top right corner of Mui Data tables??</p>


问:
DataTable Ajax Nested List
I am returning a nested list of json from an Ajax call and would like to populate my data table with this. F
or example: In my C# Class:

```<code>public class Product_Browser : Json_Response
{

    public List<PRODUCT_TABLE> ProductData { get; set; }
    public List<ProductPlans> ProductPlan { get; set; }
}
</code>```

Javascript function:

```<code>$dtBrowser = $(dtElementID).dataTable({
            filter: false,

            serverSide: true,
            processing: true,
            responsive: true,

            ajax: {
                url: _Url,
                type: "GET",
                "dataSrc": function (jsonObj) {
                    console.log(jsonObj)
                    return jsonObj
                }
            },
            columns: [
                { data: "ProductData.ProductKey", title:"Key", visible: true },
                { data: "ProductPlan.PlanID", title: "Id", visible: true },

            ],
            order: [[1, "desc"]],

        });
    }
</code>```

Now when i log the jsonObj it is valid JSON, but in my columns, data I don't know the correct way of accessing the two different lists of objects. I am able to do it for one list by changing the dataSrc to return jsonObj.ProductData but I need both pieces of data.

This is what my JSON looks like:

```<code>{
    "ProductData": [
        {
            "ProductKey": 102234,
            "ProductID": "TEST1",

        },
        {
            "ProductKey": 102310,
            "ProductID": "TEST2",

        },
        {
            "ProductKey": 102319,
            "ProductID": "TEST3",
        },
    ],
    "ProductGrabBagPlan": [
        {
            "PlanID": 1,
            "ProductKey": 102234
        },
        {
            "PlanID": 2,
            "ProductKey": 102310
        },
        {
            "PlanID": 3,
            "ProductKey": 102319
        },

    ],
    "Success": true,
    "Messages": [],
}
</code>```

Title: DataTable Ajax Nested List

Body:
I am returning a nested list of json from an Ajax call and would like to populate my data table with this. F
or example: In my C# Class:

public class Product_Browser : Json_Response
{

    public List<PRODUCT_TABLE> ProductData { get; set; }
    public List<ProductPlans> ProductPlan { get; set; }
}

Javascript function:

$dtBrowser = $(dtElementID).dataTable({
            filter: false,

            serverSide: true,
            processing: true,
            responsive: true,

            ajax: {
                url: _Url,
                type: "GET",
                "dataSrc": function (jsonObj) {
                    console.log(jsonObj)
                    return jsonObj
                }
            },
            columns: [
                { data: "ProductData.ProductKey", title:"Key", visible: true },
                { data: "ProductPlan.PlanID", title: "Id", visible: true },

            ],
            order: [[1, "desc"]],

        });
    }

Now when i log the jsonObj it is valid JSON, but in my columns, data I don't know the correct way of accessing the two different lists of objects. I am able to do it for one list by changing the dataSrc to return jsonObj.ProductData but I need both pieces of data.

This is what my JSON looks like:

{
    "ProductData": [
        {
            "ProductKey": 102234,
            "ProductID": "TEST1",

        },
        {
            "ProductKey": 102310,
            "ProductID": "TEST2",

        },
        {
            "ProductKey": 102319,
            "ProductID": "TEST3",
        },
    ],
    "ProductGrabBagPlan": [
        {
            "PlanID": 1,
            "ProductKey": 102234
        },
        {
            "PlanID": 2,
            "ProductKey": 102310
        },
        {
            "PlanID": 3,
            "ProductKey": 102319
        },

    ],
    "Success": true,
    "Messages": [],
}


问:
Jenkins Artifactory Plugin Option
I am not able to discard the old artifacts using artifactory plugin in Jenkins. Is there a way that, we can discard the old artifacts from Jenkins itself.
Note :- I am already using Jenkins artifactory plugin but I am not able to discard it via that.
Jenkins Version: 2.3

I tried deleting from Jenkins but I am not able to delete that.
I am expecting that old artifacts gets deleted because we are having discard old builds option available in Jenkins artifactory plugin.

Title: Jenkins Artifactory Plugin Option


问:
Efficient way to use PyInstaller
I'm producing an .exe file via PyInstaller and I wonder whether there is a specific option or similar to do so while iterating through some changes. For example, I add a simple print statement in the entire code, do I always have to go through the whole building stage of the .exe file?
I'm asking because it takes a while just to try something out. In my case I think it takes between 5-10 min to create the .exe. In general it's ok but when you do that a dozens or more times a day it adds up.</p>

Title: Efficient way to use PyInstaller


问:
Hyperparameter selection for Deep Reinforcement Learning
I am trying to learn machine learning from Andrew NG's Machine learning specilization on Coursera. In the chapter about reinforcement learning Andrew NG said that if you do not selecet correct hyperparameters your model can take a long time to train. Are there any guidelines on picking hyperparameters for Deep Reinforcement Learning? Lets say I have an agent who has 10000 states, how many layers and units my neural network should have? If I am using mini-batches how big should each batch be? If the states are continious states, how far back the agent should look before taking a decision?</p>


问:
Unable to access a property of stdClass object
Running into a problem where I can access every other property of this stdClass object except for the first. I am taking data from an uploaded csv and turning it into an array. from the array I am them converting it to an object. Code below

```<code>case($_FILES['csv_upload'] != NULL);
            $data = [];
            $csv = array_map('str_getcsv', file($_FILES['csv_upload']['tmp_name']));
            $header = array_map('strtolower' , $csv[0]);
            foreach($csv as $row)
            {
               $row = preg_replace("/[\$,]/", "", $row );
               $data[] = array_combine($header, $row);
            }
            $layout->items = json_decode(json_encode($data), FALSE);
            //unsetting the headers
            unset($layout->items[0]);
</code>```

this gives me an array of stdClass objects. When I do a foreach, I am able to access every property of the object except for the first one (id). A print_r($layout->items)  returns the below

```<code>Array
(
    [1] => stdClass Object
        (
            [id] => 253
            [fet] =>  157.50
            [salecost] => 78.75
            [price] => 157.50
            [retail] => 0
        )

    [2] => stdClass Object
        (
            [id] => 243
            [fet] => 150.00
            [salecost] => 75
            [price] => 150.00
            [retail] => 0
        )

</code>```

a vardump returns the below

```<code>array(47) { [1]=> object(stdClass)#2856 (5) { ["id"]=> string(6) "253" ["fet"]=> string(10) " 157.50 " ["salecost"]=> string(5) "78.75" ["price"]=> string(8) "157.50 " ["retail"]=> string(1) "0" } [2]=> object(stdClass)#243 (5) { ["id"]=> string(6) "245815" ["fet"]=> string(8) "150.00 " ["salecost"]=> string(2) "75" ["price"]=> string(8) "150.00 " ["retail"]=> string(1) "0" }
</code>```

I need to be able to access the 'id' property but, when I try to, it does not return anything, however, I can access any other property in the object and it returns correctly. I'm stumped.

Body:
Running into a problem where I can access every other property of this stdClass object except for the first. I am taking data from an uploaded csv and turning it into an array. from the array I am them converting it to an object. Code below

case($_FILES['csv_upload'] != NULL);
            $data = [];
            $csv = array_map('str_getcsv', file($_FILES['csv_upload']['tmp_name']));
            $header = array_map('strtolower' , $csv[0]);
            foreach($csv as $row)
            {
               $row = preg_replace("/[\$,]/", "", $row );
               $data[] = array_combine($header, $row);
            }
            $layout->items = json_decode(json_encode($data), FALSE);
            //unsetting the headers
            unset($layout->items[0]);

this gives me an array of stdClass objects. When I do a foreach, I am able to access every property of the object except for the first one (id). A print_r($layout->items)  returns the below

Array
(
    [1] => stdClass Object
        (
            [id] => 253
            [fet] =>  157.50
            [salecost] => 78.75
            [price] => 157.50
            [retail] => 0
        )

    [2] => stdClass Object
        (
            [id] => 243
            [fet] => 150.00
            [salecost] => 75
            [price] => 150.00
            [retail] => 0
        )

a vardump returns the below

array(47) { [1]=> object(stdClass)#2856 (5) { ["id"]=> string(6) "253" ["fet"]=> string(10) " 157.50 " ["salecost"]=> string(5) "78.75" ["price"]=> string(8) "157.50 " ["retail"]=> string(1) "0" } [2]=> object(stdClass)#243 (5) { ["id"]=> string(6) "245815" ["fet"]=> string(8) "150.00 " ["salecost"]=> string(2) "75" ["price"]=> string(8) "150.00 " ["retail"]=> string(1) "0" }

I need to be able to access the 'id' property but, when I try to, it does not return anything, however, I can access any other property in the object and it returns correctly. I'm stumped.


问:
how to remove an element after the condition is met and return the new array in javascript
I have two array of objects and would like to compare start date of array 1 against array 2 to see if array 1 start date is within the range of array 2 start date and end date

Then also compare end date of array 1 against array 2 to see if array 1 end date is within the range of array 2 start date and end date

If both the condition above are met then validate if array 1 status is overlap.

eg: Dec 15-21 (array 1 - start date -end date ) Dec 18-31 (from array 2 start date -end date)

if array1 start date is outside the range of array 2 start and end date, then validate array 1 status is ready . and if array1 end date is outside the range of array 2 start and end date, then validate array 1 status is ready .

eg: Dec 01-07 (array 1 - start date -end date ) Dec 18-31 (from array 2 start date -end date)

If array 1 start date matches array 2 start date and array 1 end date matches array 2 end date then validate array 1 status is match,

eg: Dec 18-31 (array 1 - start date -end date ) Dec 18-31 (from array 2 start date -end date)

Firstly, I am comparing the month in the snippet so that dec months dates from array 1 are being compared only against dec month dates in array 2, likewise nov month dates from array 1 against nov month dates in array 2 etc. (this comparison works fine to validate all dec and nov month dates from array1)

Next, once date comparison is done for the matching months between array1 and array2(in this case dec and nov months are found in both array 1 and array2), I would like to return left out array objects from array 1 as a new array(say array3) in this case Jan, and Feb array objects.

Just my thoughts:

Overall, I want to return the final array that should remove all those elements(the array object) that satisfies any of the conditions ie if/else in the below code and return the new array at the end of the iteration.

The new array output should like the one mentioned below, and I can loop thru array3 and make sure that the rest of the array objects status is ready. (This is just my thought to extract Jan and feb months (as these months are not part of array2), and verify if all the other months except the ones found in array (in this case Dec and Nov) have the status as "ready".

(or) Please suggest if there is any better solution to verify the status of the array1 objects(jan,feb in this case) whose month is not found in array 2 and verify if the status is "ready".

Final output should be :

```<code>array3= [ {
    start_date: "2022-01-01",
    end_date: "2022-01-07",
  },
  {
    start_date: "2022-02-16",
    end_date: "2022-02-22",
  }]
</code>```

My current code

function compareTwoArrayOfObjects(array1, array2) {
  array2.map(element => {
    const start2 = new Date(element.start_date);
    const end2 = new Date(element.end_date);

    const start2Month = start2.getMonth();
    const end2Month = end2.getFullYear();

    console.log("####################################")
    return array1.map(elm_arr1 => {
      const start1 = new Date(elm_arr1.start_date);
      const end1 = new Date(elm_arr1.end_date);
      let status;

      const start1Month = start1.getMonth();
      const end1Month = end1.getFullYear();

      if (start1.getTime() === start2.getTime() && end1.getTime() === end2.getTime() && ((start1Month === start2Month) || (end1Month === start2Month))) {
        console.log("**************")
        status = "match";
        console.log(start1, end1)
        console.log(start2, end2)
        console.log(start1Month, start2Month)
        console.log(elm_arr1.status)
        //expect(elm_arr1.status).toMatch("match");
        console.log("**************")
      } else if (((start1Month === start2Month) || (end1Month === start2Month)) && ((start1 > start2 && start1 < end2) || (end1 > start2 && end1 < end2) || (start2 > start1 && start2 < end1) || (end2 > start1 && end2 < end1))) {
        status = "overlap";
        console.log("**************")
        console.log(start1, end1)
        console.log(start2, end2)
        console.log(start1Month, start2Month)
        console.log(elm_arr1.status)
        // expect(elm_arr1.status).toMatch("overlap");
        console.log("**************")
      } else if (((start1Month === start2Month) || (end1Month === start2Month)) && ((start1 < start2 && end1 < start2) || (start1 > end2 && end1 > end2))) {
        status = "ready";
        console.log("**************")
        console.log(start1, end1)
        console.log(start2, end2)
        console.log(start1Month, start2Month)
        console.log(elm_arr1.status)
        //expect(elm_arr1.status).toMatch("ready");
        console.log("**************")
      }
    });
  });
}

const result = compareTwoArrayOfObjects(array1, array2);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script>
  let array1 = [{
      start_date: "Dec 01 2022",
      end_date: "Dec 07 2022",
      status: "ready"
    },
    {
      start_date: "Dec 04 2022",
      end_date: "Dec 10 2022",
      status: "ready"
    },
    {
      start_date: "Dec 15 2022",
      end_date: "Dec 21 2022",
      status: "overlap"
    },

    {
      start_date: "Dec 18 2022",
      end_date: "Dec 24 2022",
      status: "overlap"
    },

    {
      start_date: "Dec 12 2022",
      end_date: "Dec 28 2022",
      status: "overlap"
    },
    {
      start_date: "Dec 25 2022",
      end_date: "Dec 31 2022",
      status: "overlap"
    },
    {
      start_date: "Nov 22 2022",
      end_date: "Nov 28 2022",
      status: "match"
    },
    {
      start_date: "Nov 01 2022",
      end_date: "Nov 07 2022",
      status: "ready"
    },
    {
      start_date: "Jan 01 2022",
      end_date: "Jan 07 2022",
      status: "ready"
    },
    {
      start_date: "Feb 16 20226",
      end_date: "Feb 22 2022",
      status: "ready"
    },
  ];

  let array2 = [{
      start_date: "Dec 18 2022",
      end_date: "Dec 31 2022"
    },
    {
      start_date: "Nov 22 2022",
      end_date: "Nov 28 2022"
    },
  ];
</script></code>```

Body:
I have two array of objects and would like to compare start date of array 1 against array 2 to see if array 1 start date is within the range of array 2 start date and end date

Then also compare end date of array 1 against array 2 to see if array 1 end date is within the range of array 2 start date and end date

If both the condition above are met then validate if array 1 status is overlap.

eg: Dec 15-21 (array 1 - start date -end date ) Dec 18-31 (from array 2 start date -end date)

if array1 start date is outside the range of array 2 start and end date, then validate array 1 status is ready . and if array1 end date is outside the range of array 2 start and end date, then validate array 1 status is ready .

eg: Dec 01-07 (array 1 - start date -end date ) Dec 18-31 (from array 2 start date -end date)

If array 1 start date matches array 2 start date and array 1 end date matches array 2 end date then validate array 1 status is match,

eg: Dec 18-31 (array 1 - start date -end date ) Dec 18-31 (from array 2 start date -end date)

Firstly, I am comparing the month in the snippet so that dec months dates from array 1 are being compared only against dec month dates in array 2, likewise nov month dates from array 1 against nov month dates in array 2 etc. (this comparison works fine to validate all dec and nov month dates from array1)

Next, once date comparison is done for the matching months between array1 and array2(in this case dec and nov months are found in both array 1 and array2), I would like to return left out array objects from array 1 as a new array(say array3) in this case Jan, and Feb array objects.

Just my thoughts:

Overall, I want to return the final array that should remove all those elements(the array object) that satisfies any of the conditions ie if/else in the below code and return the new array at the end of the iteration.

The new array output should like the one mentioned below, and I can loop thru array3 and make sure that the rest of the array objects status is ready. (This is just my thought to extract Jan and feb months (as these months are not part of array2), and verify if all the other months except the ones found in array (in this case Dec and Nov) have the status as "ready".

(or) Please suggest if there is any better solution to verify the status of the array1 objects(jan,feb in this case) whose month is not found in array 2 and verify if the status is "ready".

Final output should be :

array3= [ {
    start_date: "2022-01-01",
    end_date: "2022-01-07",
  },
  {
    start_date: "2022-02-16",
    end_date: "2022-02-22",
  }]

My current code

function compareTwoArrayOfObjects(array1, array2) {
  array2.map(element => {
    const start2 = new Date(element.start_date);
    const end2 = new Date(element.end_date);

    const start2Month = start2.getMonth();
    const end2Month = end2.getFullYear();

    console.log("####################################")
    return array1.map(elm_arr1 => {
      const start1 = new Date(elm_arr1.start_date);
      const end1 = new Date(elm_arr1.end_date);
      let status;

      const start1Month = start1.getMonth();
      const end1Month = end1.getFullYear();

      if (start1.getTime() === start2.getTime() && end1.getTime() === end2.getTime() && ((start1Month === start2Month) || (end1Month === start2Month))) {
        console.log("**************")
        status = "match";
        console.log(start1, end1)
        console.log(start2, end2)
        console.log(start1Month, start2Month)
        console.log(elm_arr1.status)
        //expect(elm_arr1.status).toMatch("match");
        console.log("**************")
      } else if (((start1Month === start2Month) || (end1Month === start2Month)) && ((start1 > start2 && start1 < end2) || (end1 > start2 && end1 < end2) || (start2 > start1 && start2 < end1) || (end2 > start1 && end2 < end1))) {
        status = "overlap";
        console.log("**************")
        console.log(start1, end1)
        console.log(start2, end2)
        console.log(start1Month, start2Month)
        console.log(elm_arr1.status)
        // expect(elm_arr1.status).toMatch("overlap");
        console.log("**************")
      } else if (((start1Month === start2Month) || (end1Month === start2Month)) && ((start1 < start2 && end1 < start2) || (start1 > end2 && end1 > end2))) {
        status = "ready";
        console.log("**************")
        console.log(start1, end1)
        console.log(start2, end2)
        console.log(start1Month, start2Month)
        console.log(elm_arr1.status)
        //expect(elm_arr1.status).toMatch("ready");
        console.log("**************")
      }
    });
  });
}

const result = compareTwoArrayOfObjects(array1, array2);


问:
How to filter out groups of groupby of which not all rows are present in another DataFrame
The purpose of this code is to filter out the groups of a pyspark DataFrame that contains rows that do not have a mathing row in the hub DataFrame. The groups are determined based on the primary key.
To check if all rows a the group have matching rows in the hub DataFrame a merge is performed with the hub DataFrame. In case the number of rows of the original group is not equal to the number of rows of the merged result the group should be filtered out.

I tested the condition successfully using the entire DataFrame:

```<code>len(df) == len(df.merge(df_hub, left_on=key, right_on=key, suffixes=["","_hub"]))
</code>```

However when I try to use the same condition inside the groupby filter it results in a TypeError:

```<code>primary_key = ['CURRENCY_ISO_CODE']
key = ['CURRENC_ISO_CODE', 'H_CURRENCY_SK']
df.groupby(primary_key).filter(lambda group: len(group) == len(group.merge(df_hub, left_on=key, right_on=key, suffixes=["","_hub"])))
</code>```
```<code>TypeError: cannot pickle '_thread.RLock' object
</code>```

How do I resolve the TypeError or is there a better way the achieve the desired filtering?

df

```<code>| Index | CURRENCY_ISO_CODE | H_CURRENCY_SK |
| :---- | :---------------- | :------------ |
| 0     | ABC               | 1             |
| 1     | ABC               | 999           |
| 2     | DEF               | 2             |
</code>```

df_hub

```<code>| Index | CURRENCY_ISO_CODE | H_CURRENCY_SK |
| :---- | :---------------- | :------------ |
| 0     | ABC               | 1             |
| 1     | DEF               | 2             |
</code>```

desired result

```<code>| Index | CURRENCY_ISO_CODE | H_CURRENCY_SK |
| ----- | ----------------- | ------------- |
| 2     | DEF               | 2             |
</code>```

Body:
The purpose of this code is to filter out the groups of a pyspark DataFrame that contains rows that do not have a mathing row in the hub DataFrame. The groups are determined based on the primary key.
To check if all rows a the group have matching rows in the hub DataFrame a merge is performed with the hub DataFrame. In case the number of rows of the original group is not equal to the number of rows of the merged result the group should be filtered out.

I tested the condition successfully using the entire DataFrame:

len(df) == len(df.merge(df_hub, left_on=key, right_on=key, suffixes=["","_hub"]))

However when I try to use the same condition inside the groupby filter it results in a TypeError:

primary_key = ['CURRENCY_ISO_CODE']
key = ['CURRENC_ISO_CODE', 'H_CURRENCY_SK']
df.groupby(primary_key).filter(lambda group: len(group) == len(group.merge(df_hub, left_on=key, right_on=key, suffixes=["","_hub"])))

TypeError: cannot pickle '_thread.RLock' object

How do I resolve the TypeError or is there a better way the achieve the desired filtering?

df

| Index | CURRENCY_ISO_CODE | H_CURRENCY_SK |
| :---- | :---------------- | :------------ |
| 0     | ABC               | 1             |
| 1     | ABC               | 999           |
| 2     | DEF               | 2             |

df_hub

| Index | CURRENCY_ISO_CODE | H_CURRENCY_SK |
| :---- | :---------------- | :------------ |
| 0     | ABC               | 1             |
| 1     | DEF               | 2             |

desired result

| Index | CURRENCY_ISO_CODE | H_CURRENCY_SK |
| ----- | ----------------- | ------------- |
| 2     | DEF               | 2             |


问:
How can I parse uploaded csv file and store it in postgres using node js
I can parse csv file from a folder locally using node js and fast-csv package. Then, I have extract the headers and query Insert into postgres.

```<code>const fs = require("fs");
const path = require("path");
const csv = require("fast-csv");
const pool = require("./config/dbconn");

const stream = fs.createReadStream(path.resolve(__dirname, "data", "movies.csv"));

pool.connect();
const csvStream = csv
  .parseStream(stream, { headers: true })
  .on("error", (error) => console.error(error))
  .on("data", (record) => {
    csvStream.pause();
    const tconst = record.tconst;
    const titleType = record.titleType;
    const primaryTitle = record.primaryTitle;
    const runtimeMinutes = record.runtimeMinutes;
    const genres = record.genres;
    pool.query(
      "INSERT INTO movies(tconst, titleType, primaryTitle, runtimeMinutes, genres)
      VALUES($1, $2, $3, $4, $5)",
      [tconst, titleType, primaryTitle, runtimeMinutes, genres],
      (err) => {
        if (err) console.log(err.message);
      }
    );
    csvStream.resume();
  })
  .on("end", (rowCount) => console.log(`Parsed ${rowCount} rows`));
</code>```

However, I am tring to make it automatically that I will upload a csv file from Client then the uploaded file will be stored in a folder and create a table with exact file name and have headers as column name. How can I do it? or, I have to do it from backend for every single file manually like the above code!

Body:
I can parse csv file from a folder locally using node js and fast-csv package. Then, I have extract the headers and query Insert into postgres.

const fs = require("fs");
const path = require("path");
const csv = require("fast-csv");
const pool = require("./config/dbconn");

const stream = fs.createReadStream(path.resolve(__dirname, "data", "movies.csv"));

pool.connect();
const csvStream = csv
  .parseStream(stream, { headers: true })
  .on("error", (error) => console.error(error))
  .on("data", (record) => {
    csvStream.pause();
    const tconst = record.tconst;
    const titleType = record.titleType;
    const primaryTitle = record.primaryTitle;
    const runtimeMinutes = record.runtimeMinutes;
    const genres = record.genres;
    pool.query(
      "INSERT INTO movies(tconst, titleType, primaryTitle, runtimeMinutes, genres)
      VALUES($1, $2, $3, $4, $5)",
      [tconst, titleType, primaryTitle, runtimeMinutes, genres],
      (err) => {
        if (err) console.log(err.message);
      }
    );
    csvStream.resume();
  })
  .on("end", (rowCount) => console.log(`Parsed ${rowCount} rows`));

However, I am tring to make it automatically that I will upload a csv file from Client then the uploaded file will be stored in a folder and create a table with exact file name and have headers as column name. How can I do it? or, I have to do it from backend for every single file manually like the above code!


问:
I would like to move one panorama picture 360 degrees Infinity smoothly from left to write on a webpage. Is that possible?
I have a very broad panorama picture that could connect at the ends to create a 360 degrees view on my website. The picture has a width of 10000 pixels. I want to show a 930 pixels window so it has the effect of sliding slowly through in a loop.  The problem with the Javascripts that I found so far is that they are not smooth enough. They stutter. Is there a smooth solution? Thanks to everybody.</p>


问:
How can I activate an AJAX script using PowerShell?
I try to automate the downloading of a PDF file that I can get in clicking manually on PDF icon on a specific html page.

I have decided to automate this task using PowerShell.

I have "already" written first part

```<code>$page = Invoke-WebRequest https://journal.cinetelerevue.sudinfo.be
</code>```

Now I try to activate click event on ReadPDF button so that PDF file is downloaded.

How can I do that ?

If I analyze html file returned by Invoke-WebRequest I can find following javascript  code

```<code>function readPdf()
    {
    blackOverlay.fadeIn(),adp_loader.fadeIn();
    var e = window.open("","pdf_view");
    e.document.body.innerHTML="<p>Veuillez patienter pendant le chargement du pdf. <p><img src='"+path+"design/loader.svg' style='position:absolute;top:50%;left:50%;' />"
        ,$.ajax({type:"GET",url:urlPdf,success:function()
            {
            e.location.href=urlPdf,blackOverlay.fadeOut(),adp_loader.fadeOut()
            }
        ,error:function(e)
            {
            catch404Error(e)}
            })
    }
</code>```

How can I activate this function using PowerShell so that I can read PDF file ?

Is what I want possible using PowerShell ?

Body:
I try to automate the downloading of a PDF file that I can get in clicking manually on PDF icon on a specific html page.

I have decided to automate this task using PowerShell.

I have "already" written first part

$page = Invoke-WebRequest https://journal.cinetelerevue.sudinfo.be

Now I try to activate click event on ReadPDF button so that PDF file is downloaded.

How can I do that ?

If I analyze html file returned by Invoke-WebRequest I can find following javascript  code

function readPdf()
    {
    blackOverlay.fadeIn(),adp_loader.fadeIn();
    var e = window.open("","pdf_view");
    e.document.body.innerHTML="
Veuillez patienter pendant le chargement du pdf.
"
        ,$.ajax({type:"GET",url:urlPdf,success:function()
            {
            e.location.href=urlPdf,blackOverlay.fadeOut(),adp_loader.fadeOut()
            }
        ,error:function(e)
            {
            catch404Error(e)}
            })
    }

How can I activate this function using PowerShell so that I can read PDF file ?

Is what I want possible using PowerShell ?


问:
Preserving system APK UID across Android image builds
Is there a reliable way to specify the UID that Android assigns to the APK during the AOSP builds?

If there is a system APK that is built into and Android image, we observe that sometimes the UID associated with that APK ends up different between consecutive image builds. There seems to be little information that explains how exactly are the UIDs assigned.

The reason we'd like to preserve the UID, for at least one of the applications, is because an application needs to write to an internal file system areas, and if the UID changes between builds, then after a newer image is installed on a device, the files written by the older application are no longer accessible (the permissions to these files are 0600).

We now know that there is a "sharedUserId" Manifest statement that we can probably use for this, but since the application is already in the field, it's too late to apply that, plus that attribute has been deprecated in 29.


问:
Issue token for application access from ADB2C
Application 1 creates a url with id_token that contains all the necessary info to validate a claim (as of now simply validate the user with email & signed claim).

a. Create a self-signed certificate (New-SelfSignedCertificate )

b. For the same, used tokenbuilder to create a URL as :

```<code>  https://tenant.b2clogin.com/tenant.onmicrosoft.com/oauth2/v2.0/authorize?p=B2C_1A_SIGNIN_WITH_EMAIL&client_id=9994db7f-2dc7-4bac-bf8a-93bf04067890&redirect_uri=https://myredirecturl.com/&nonce=80c307115..&scope=openid&response_type=id_token&id_token_hint=eyJhbGciOiJSUzI1NiIsImtpZCI6IlZWWWwwbUE0YlFYOXg0LVZVTGpfb0VUWHd0VSIsIng1dCI6I......nNpb25fYWdlbmN5
</code>```

c. Hosted the application with self-signed certificate (Example :
https://b2cidtokenbuilder.azurewebsites.net/)
d. In policy blade created a token with the self-signed certificate (following steps in here)
e. In TrustFrameworkBase updated issuer_secret for JwtIssuer Technical Profile

```<code> <CryptographicKeys>
   <Key Id="issuer_secret" StorageReferenceId="B2C_1A_AABIDToken" />
   <Key Id="issuer_refresh_token_key" StorageReferenceId="B2C_1A_TokenEncryptionKeyContainer" />
 </CryptographicKeys>

</code>```

f. In B2C_1A_SIGNIN_WITH_EMAIL policy added the

```<code> <Metadata
    <Item Key="METADATA">https://tenant.b2clogin.com/tenant.onmicrosoft.com/v2.0/.well-known/openid-configuration?p=B2C_1A_SIGNUP_SIGNIN</Item>
    <Item Key="issuer">https://b2cidtokenbuilder.azurewebsites.net/</Item>
  </Metadata>
</code>```

g. Once I click the AD B2C url I am expecting that the policy B2C_1A_SIGNIN_WITH_EMAIL will allow me to login to the application with an access_token.
(Based on info here I should be able to login to my application once the accesstoken has been created by my policy.

```<code>But in my current application what I see is not access_token is getting created but an id_token is created with all the info and since there is no access-token my application is asking for AD B2C login (prompt).
https://myapplication.com/#id_token=eyJ0eXAiOiJKV1QiLCJhbGciOiGVla2FiMmNkZXYuYjJjbG9naW4uY29tLzM4NGIzNTdiLTIzMWUtNGY3MS1iYThhLWUxNzBlZDFiMzA1ZC92Mi4....................kLTE5NDYtNGRkYy04YWViLWY5ZDFiMWVmNWMyMSIsImF1Z
</code>```

Should I be setting some sessionmanagement TP?

My policy is

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<TrustFrameworkPolicy
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  xmlns="http://schemas.microsoft.com/online/cpim/schemas/2013/06"
  PolicySchemaVersion="0.3.0.0"
  TenantId="tenant.onmicrosoft.com"
  PolicyId="B2C_1A_signin_with_email"
  PublicPolicyUri="http://tenant.onmicrosoft.com/B2C_1A_signin_with_email">

  <BasePolicy>
    <TenantId>tenant.onmicrosoft.com</TenantId>
    <PolicyId>B2C_1A_TrustFrameworkExtensions</PolicyId>
  </BasePolicy>

   <BuildingBlocks>
    <ClaimsSchema>
      <!--Sample: Stores the error message for unsolicited request (a request without id_token_hint) and user not found-->
      <ClaimType Id="errorMessage">
          <DisplayName>Error</DisplayName>
          <DataType>string</DataType>
        <UserHelpText>Add help text here</UserHelpText>
          <UserInputType>Paragraph</UserInputType>
      </ClaimType>
    </ClaimsSchema>

    <ClaimsTransformations>
      <!--Sample: Initiates the errorMessage claims type with the error message-->
      <ClaimsTransformation Id="CreateUnsolicitedErrorMessage" TransformationMethod="CreateStringClaim">
        <InputParameters>
          <InputParameter Id="value" DataType="string" Value="You cannot sign-in without invitation. Please click the link in the email" />
        </InputParameters>
        <OutputClaims>
          <OutputClaim ClaimTypeReferenceId="errorMessage" TransformationClaimType="createdClaim" />
        </OutputClaims>
      </ClaimsTransformation>

      <!--Sample: Initiates the errorMessage claims type with the error message user not found-->
      <ClaimsTransformation Id="CreateUserNotFoundErrorMessage" TransformationMethod="CreateStringClaim">
        <InputParameters>
          <InputParameter Id="value" DataType="string" Value="You aren't registered in the system! Please contact the Help Desk on 0800 xxx yyy and ask to be added to the system" />
        </InputParameters>
        <OutputClaims>
          <OutputClaim ClaimTypeReferenceId="errorMessage" TransformationClaimType="createdClaim" />
        </OutputClaims>
      </ClaimsTransformation>
    </ClaimsTransformations>
  </BuildingBlocks>

  <ClaimsProviders>
    <!--Sample: This technical profile specifies how B2C should validate your token, and what claims you want B2C to extract from the token.
      The METADATA value in the TechnicalProfile meta-data is required.
      The “IdTokenAudience” and “issuer” arguments are optional (see later section)-->
    <ClaimsProvider>
      <DisplayName>My ID Token Hint ClaimsProvider</DisplayName>
      <TechnicalProfiles>
        <TechnicalProfile Id="IdTokenHint_ExtractClaims">
          <DisplayName> My ID Token Hint TechnicalProfile</DisplayName>
          <Protocol Name="None" />
          <Metadata>

            <!--Sample action required: replace with your endpoint location -->
            <Item Key="METADATA">https://teanant.b2clogin.com/tenant.onmicrosoft.com/v2.0/.well-known/openid-configuration?p=B2C_1A_SIGNUP_SIGNIN</Item>
            <Item Key="issuer">https://b2cidtokenbuilder.azurewebsites.net/</Item>
          </Metadata>
        <OutputClaims>
          <!--Sample: Read the email cliam from the id_token_hint-->
          <OutputClaim ClaimTypeReferenceId="email" />
        </OutputClaims>
        </TechnicalProfile>
      </TechnicalProfiles>
    </ClaimsProvider>

    <ClaimsProvider>
      <DisplayName>Self Asserted</DisplayName>
      <TechnicalProfiles>
        <!-- Demo: Show error message-->
        <TechnicalProfile Id="SelfAsserted-Error">
          <DisplayName>Unsolicited error message</DisplayName>
          <Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.SelfAssertedAttributeProvider, Web.TPEngine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
          <Metadata>
            <Item Key="ContentDefinitionReferenceId">api.selfasserted</Item>
            <!-- Sample: Remove the continue button-->
            <Item Key="setting.showContinueButton">false</Item>
         </Metadata>
          <InputClaims>
            <InputClaim ClaimTypeReferenceId="errorMessage"/>
          </InputClaims>
          <OutputClaims>
            <OutputClaim ClaimTypeReferenceId="errorMessage"/>
          </OutputClaims>
        </TechnicalProfile>

        <!-- Demo: Show unsolicited error message-->
        <TechnicalProfile Id="SelfAsserted-Unsolicited">
          <InputClaimsTransformations>
            <InputClaimsTransformation ReferenceId="CreateUnsolicitedErrorMessage" />
          </InputClaimsTransformations>
          <IncludeTechnicalProfile ReferenceId="SelfAsserted-Error" />
        </TechnicalProfile>

        <!-- Demo: Show user not found error message-->
        <TechnicalProfile Id="SelfAsserted-UserNotFound">
          <InputClaimsTransformations>
            <InputClaimsTransformation ReferenceId="CreateUserNotFoundErrorMessage" />
          </InputClaimsTransformations>
          <IncludeTechnicalProfile ReferenceId="SelfAsserted-Error" />
        </TechnicalProfile>

    <TechnicalProfile Id="AAD-UserReadUsingEmailAddress-Hint">
                    <Metadata>
                        <Item Key="Operation">Read</Item>
                        <Item Key="RaiseErrorIfClaimsPrincipalDoesNotExist">false</Item>
                        <Item Key="UserMessageIfClaimsPrincipalDoesNotExist">An account could not be found for the provided user ID.</Item>
                    </Metadata>
                    <IncludeInSso>false</IncludeInSso>
                    <InputClaims>
                        <InputClaim ClaimTypeReferenceId="email" PartnerClaimType="signInNames.emailAddress" Required="true" />
                    </InputClaims>
                    <OutputClaims>
                        <!-- Required claims -->
                        <OutputClaim ClaimTypeReferenceId="objectId" />
                        <OutputClaim ClaimTypeReferenceId="authenticationSource" DefaultValue="localAccountAuthentication" />

            <!-- Sample: Change the output email claims-->
            <!--<OutputClaim ClaimTypeReferenceId="email" />-->
            <OutputClaim ClaimTypeReferenceId="signInNames.emailAddress" />
            <OutputClaim ClaimTypeReferenceId="extension_userId" />
            <OutputClaim ClaimTypeReferenceId="extension_tenantAbbreviation" />
            <OutputClaim ClaimTypeReferenceId="extension_dateTimeFormat" />
                    </OutputClaims>
                    <!-- <OutputClaimsTransformations>
                        <OutputClaimsTransformation ReferenceId="AssertAccountEnabledIsTrue" />
                    </OutputClaimsTransformations> -->
                    <IncludeTechnicalProfile ReferenceId="AAD-Common" />
                </TechnicalProfile>
                </TechnicalProfiles>

    </ClaimsProvider>
  </ClaimsProviders>

  <UserJourneys>
    <UserJourney Id="SignInWithEmail">
      <OrchestrationSteps>

        <!--Sample: Read the input claims from the id_token_hint-->
        <OrchestrationStep Order="1" Type="GetClaims" CpimIssuerTechnicalProfileReferenceId="IdTokenHint_ExtractClaims" />

        <!-- Sample: Check if user tries to run the policy without invitation -->
        <OrchestrationStep Order="2" Type="ClaimsExchange">
         <Preconditions>
            <Precondition Type="ClaimsExist" ExecuteActionsIf="true">
              <Value>email</Value>
              <Action>SkipThisOrchestrationStep</Action>
            </Precondition>
          </Preconditions>
          <ClaimsExchanges>
            <ClaimsExchange Id="SelfAsserted-Unsolicited" TechnicalProfileReferenceId="SelfAsserted-Unsolicited" />
          </ClaimsExchanges>
        </OrchestrationStep>

        <!--Sample: Read the user properties from the directory-->
        <OrchestrationStep Order="3" Type="ClaimsExchange">
          <ClaimsExchanges>
            <ClaimsExchange Id="AADUserReadUsingEmailAddress" TechnicalProfileReferenceId="AAD-UserReadUsingEmailAddress-Hint"/>
          </ClaimsExchanges>
        </OrchestrationStep>

        <!-- Sample: Check whether the user not existed in the directory -->
        <OrchestrationStep Order="4" Type="ClaimsExchange">
          <Preconditions>
            <Precondition Type="ClaimsExist" ExecuteActionsIf="true">
              <Value>objectId</Value>
              <Action>SkipThisOrchestrationStep</Action>
            </Precondition>
          </Preconditions>
          <ClaimsExchanges>
            <ClaimsExchange Id="SelfAssertedUserNotFound" TechnicalProfileReferenceId="SelfAsserted-UserNotFound" />
          </ClaimsExchanges>
        </OrchestrationStep>

        <!--Sample: Issue an access token-->
        <OrchestrationStep Order="5" Type="SendClaims" CpimIssuerTechnicalProfileReferenceId="JwtIssuer"/>

      </OrchestrationSteps>
      <ClientDefinition ReferenceId="DefaultWeb"/>
    </UserJourney>
  </UserJourneys>

  <RelyingParty>
    <DefaultUserJourney ReferenceId="SignInWithEmail" />
    <TechnicalProfile Id="PolicyProfile">
      <DisplayName>PolicyProfile</DisplayName>
      <Protocol Name="OpenIdConnect" />
      <!--Sample: Set the input claims to be read from the id_token_hint-->
      <InputClaims>
        <InputClaim ClaimTypeReferenceId="email" />
      </InputClaims>
      <OutputClaims>
        <OutputClaim ClaimTypeReferenceId="correlationId" DefaultValue="{Context:CorrelationId}" />
        <OutputClaim ClaimTypeReferenceId="signInNames.emailAddress" />
        <OutputClaim ClaimTypeReferenceId="extension_userId" />
        <OutputClaim ClaimTypeReferenceId="extension_tenantAbbreviation" />
        <OutputClaim ClaimTypeReferenceId="extension_dateTimeFormat" />
        <OutputClaim ClaimTypeReferenceId="tenantId" AlwaysUseDefaultValue="true" DefaultValue="{Policy:TenantObjectId}" />
        <OutputClaim ClaimTypeReferenceId="objectId" PartnerClaimType="sub" />
      </OutputClaims>
      <SubjectNamingInfo ClaimType="sub" />
    </TechnicalProfile>
  </RelyingParty>
</TrustFrameworkPolicy>
</code>```

Body:
Application 1 creates a url with id_token that contains all the necessary info to validate a claim (as of now simply validate the user with email & signed claim).

a. Create a self-signed certificate (New-SelfSignedCertificate )

b. For the same, used tokenbuilder to create a URL as :

  https://tenant.b2clogin.com/tenant.onmicrosoft.com/oauth2/v2.0/authorize?p=B2C_1A_SIGNIN_WITH_EMAIL&client_id=9994db7f-2dc7-4bac-bf8a-93bf04067890&redirect_uri=https://myredirecturl.com/&nonce=80c307115..&scope=openid&response_type=id_token&id_token_hint=eyJhbGciOiJSUzI1NiIsImtpZCI6IlZWWWwwbUE0YlFYOXg0LVZVTGpfb0VUWHd0VSIsIng1dCI6I......nNpb25fYWdlbmN5

c. Hosted the application with self-signed certificate (Example :
https://b2cidtokenbuilder.azurewebsites.net/)
d. In policy blade created a token with the self-signed certificate (following steps in here)
e. In TrustFrameworkBase updated issuer_secret for JwtIssuer Technical Profile

 <CryptographicKeys>
   <Key Id="issuer_secret" StorageReferenceId="B2C_1A_AABIDToken" />
   <Key Id="issuer_refresh_token_key" StorageReferenceId="B2C_1A_TokenEncryptionKeyContainer" />
 </CryptographicKeys>

f. In B2C_1A_SIGNIN_WITH_EMAIL policy added the

 <Metadata
    <Item Key="METADATA">https://tenant.b2clogin.com/tenant.onmicrosoft.com/v2.0/.well-known/openid-configuration?p=B2C_1A_SIGNUP_SIGNIN</Item>
    <Item Key="issuer">https://b2cidtokenbuilder.azurewebsites.net/</Item>
  </Metadata>

g. Once I click the AD B2C url I am expecting that the policy B2C_1A_SIGNIN_WITH_EMAIL will allow me to login to the application with an access_token.
(Based on info here I should be able to login to my application once the accesstoken has been created by my policy.

But in my current application what I see is not access_token is getting created but an id_token is created with all the info and since there is no access-token my application is asking for AD B2C login (prompt).
https://myapplication.com/#id_token=eyJ0eXAiOiJKV1QiLCJhbGciOiGVla2FiMmNkZXYuYjJjbG9naW4uY29tLzM4NGIzNTdiLTIzMWUtNGY3MS1iYThhLWUxNzBlZDFiMzA1ZC92Mi4....................kLTE5NDYtNGRkYy04YWViLWY5ZDFiMWVmNWMyMSIsImF1Z

Should I be setting some sessionmanagement TP?

My policy is

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<TrustFrameworkPolicy
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  xmlns="http://schemas.microsoft.com/online/cpim/schemas/2013/06"
  PolicySchemaVersion="0.3.0.0"
  TenantId="tenant.onmicrosoft.com"
  PolicyId="B2C_1A_signin_with_email"
  PublicPolicyUri="http://tenant.onmicrosoft.com/B2C_1A_signin_with_email">

  <BasePolicy>
    <TenantId>tenant.onmicrosoft.com</TenantId>
    <PolicyId>B2C_1A_TrustFrameworkExtensions</PolicyId>
  </BasePolicy>

   <BuildingBlocks>
    <ClaimsSchema>

      <ClaimType Id="errorMessage">
          <DisplayName>Error</DisplayName>
          <DataType>string</DataType>
        <UserHelpText>Add help text here</UserHelpText>
          <UserInputType>Paragraph</UserInputType>
      </ClaimType>
    </ClaimsSchema>

    <ClaimsTransformations>

      <ClaimsTransformation Id="CreateUnsolicitedErrorMessage" TransformationMethod="CreateStringClaim">
        <InputParameters>
          <InputParameter Id="value" DataType="string" Value="You cannot sign-in without invitation. Please click the link in the email" />
        </InputParameters>
        <OutputClaims>
          <OutputClaim ClaimTypeReferenceId="errorMessage" TransformationClaimType="createdClaim" />
        </OutputClaims>
      </ClaimsTransformation>

      <ClaimsTransformation Id="CreateUserNotFoundErrorMessage" TransformationMethod="CreateStringClaim">
        <InputParameters>
          <InputParameter Id="value" DataType="string" Value="You aren't registered in the system! Please contact the Help Desk on 0800 xxx yyy and ask to be added to the system" />
        </InputParameters>
        <OutputClaims>
          <OutputClaim ClaimTypeReferenceId="errorMessage" TransformationClaimType="createdClaim" />
        </OutputClaims>
      </ClaimsTransformation>
    </ClaimsTransformations>
  </BuildingBlocks>

  <ClaimsProviders>

    <ClaimsProvider>
      <DisplayName>My ID Token Hint ClaimsProvider</DisplayName>
      <TechnicalProfiles>
        <TechnicalProfile Id="IdTokenHint_ExtractClaims">
          <DisplayName> My ID Token Hint TechnicalProfile</DisplayName>
          <Protocol Name="None" />
          <Metadata>

            <Item Key="METADATA">https://teanant.b2clogin.com/tenant.onmicrosoft.com/v2.0/.well-known/openid-configuration?p=B2C_1A_SIGNUP_SIGNIN</Item>
            <Item Key="issuer">https://b2cidtokenbuilder.azurewebsites.net/</Item>
          </Metadata>
        <OutputClaims>

          <OutputClaim ClaimTypeReferenceId="email" />
        </OutputClaims>
        </TechnicalProfile>
      </TechnicalProfiles>
    </ClaimsProvider>

    <ClaimsProvider>
      <DisplayName>Self Asserted</DisplayName>
      <TechnicalProfiles>

        <TechnicalProfile Id="SelfAsserted-Error">
          <DisplayName>Unsolicited error message</DisplayName>
          <Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.SelfAssertedAttributeProvider, Web.TPEngine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
          <Metadata>
            <Item Key="ContentDefinitionReferenceId">api.selfasserted</Item>

            <Item Key="setting.showContinueButton">false</Item>
         </Metadata>
          <InputClaims>
            <InputClaim ClaimTypeReferenceId="errorMessage"/>
          </InputClaims>
          <OutputClaims>
            <OutputClaim ClaimTypeReferenceId="errorMessage"/>
          </OutputClaims>
        </TechnicalProfile>

        <TechnicalProfile Id="SelfAsserted-Unsolicited">
          <InputClaimsTransformations>
            <InputClaimsTransformation ReferenceId="CreateUnsolicitedErrorMessage" />
          </InputClaimsTransformations>
          <IncludeTechnicalProfile ReferenceId="SelfAsserted-Error" />
        </TechnicalProfile>

        <TechnicalProfile Id="SelfAsserted-UserNotFound">
          <InputClaimsTransformations>
            <InputClaimsTransformation ReferenceId="CreateUserNotFoundErrorMessage" />
          </InputClaimsTransformations>
          <IncludeTechnicalProfile ReferenceId="SelfAsserted-Error" />
        </TechnicalProfile>

    <TechnicalProfile Id="AAD-UserReadUsingEmailAddress-Hint">
                    <Metadata>
                        <Item Key="Operation">Read</Item>
                        <Item Key="RaiseErrorIfClaimsPrincipalDoesNotExist">false</Item>
                        <Item Key="UserMessageIfClaimsPrincipalDoesNotExist">An account could not be found for the provided user ID.</Item>
                    </Metadata>
                    <IncludeInSso>false</IncludeInSso>
                    <InputClaims>
                        <InputClaim ClaimTypeReferenceId="email" PartnerClaimType="signInNames.emailAddress" Required="true" />
                    </InputClaims>
                    <OutputClaims>

                        <OutputClaim ClaimTypeReferenceId="objectId" />
                        <OutputClaim ClaimTypeReferenceId="authenticationSource" DefaultValue="localAccountAuthentication" />

            <OutputClaim ClaimTypeReferenceId="signInNames.emailAddress" />
            <OutputClaim ClaimTypeReferenceId="extension_userId" />
            <OutputClaim ClaimTypeReferenceId="extension_tenantAbbreviation" />
            <OutputClaim ClaimTypeReferenceId="extension_dateTimeFormat" />
                    </OutputClaims>

                    <IncludeTechnicalProfile ReferenceId="AAD-Common" />
                </TechnicalProfile>
                </TechnicalProfiles>

    </ClaimsProvider>
  </ClaimsProviders>

  <UserJourneys>
    <UserJourney Id="SignInWithEmail">
      <OrchestrationSteps>

        <OrchestrationStep Order="1" Type="GetClaims" CpimIssuerTechnicalProfileReferenceId="IdTokenHint_ExtractClaims" />

        <OrchestrationStep Order="2" Type="ClaimsExchange">
         <Preconditions>
            <Precondition Type="ClaimsExist" ExecuteActionsIf="true">
              <Value>email</Value>
              <Action>SkipThisOrchestrationStep</Action>
            </Precondition>
          </Preconditions>
          <ClaimsExchanges>
            <ClaimsExchange Id="SelfAsserted-Unsolicited" TechnicalProfileReferenceId="SelfAsserted-Unsolicited" />
          </ClaimsExchanges>
        </OrchestrationStep>

        <OrchestrationStep Order="3" Type="ClaimsExchange">
          <ClaimsExchanges>
            <ClaimsExchange Id="AADUserReadUsingEmailAddress" TechnicalProfileReferenceId="AAD-UserReadUsingEmailAddress-Hint"/>
          </ClaimsExchanges>
        </OrchestrationStep>

        <OrchestrationStep Order="4" Type="ClaimsExchange">
          <Preconditions>
            <Precondition Type="ClaimsExist" ExecuteActionsIf="true">
              <Value>objectId</Value>
              <Action>SkipThisOrchestrationStep</Action>
            </Precondition>
          </Preconditions>
          <ClaimsExchanges>
            <ClaimsExchange Id="SelfAssertedUserNotFound" TechnicalProfileReferenceId="SelfAsserted-UserNotFound" />
          </ClaimsExchanges>
        </OrchestrationStep>

        <OrchestrationStep Order="5" Type="SendClaims" CpimIssuerTechnicalProfileReferenceId="JwtIssuer"/>

      </OrchestrationSteps>
      <ClientDefinition ReferenceId="DefaultWeb"/>
    </UserJourney>
  </UserJourneys>

  <RelyingParty>
    <DefaultUserJourney ReferenceId="SignInWithEmail" />
    <TechnicalProfile Id="PolicyProfile">
      <DisplayName>PolicyProfile</DisplayName>
      <Protocol Name="OpenIdConnect" />

      <InputClaims>
        <InputClaim ClaimTypeReferenceId="email" />
      </InputClaims>
      <OutputClaims>
        <OutputClaim ClaimTypeReferenceId="correlationId" DefaultValue="{Context:CorrelationId}" />
        <OutputClaim ClaimTypeReferenceId="signInNames.emailAddress" />
        <OutputClaim ClaimTypeReferenceId="extension_userId" />
        <OutputClaim ClaimTypeReferenceId="extension_tenantAbbreviation" />
        <OutputClaim ClaimTypeReferenceId="extension_dateTimeFormat" />
        <OutputClaim ClaimTypeReferenceId="tenantId" AlwaysUseDefaultValue="true" DefaultValue="{Policy:TenantObjectId}" />
        <OutputClaim ClaimTypeReferenceId="objectId" PartnerClaimType="sub" />
      </OutputClaims>
      <SubjectNamingInfo ClaimType="sub" />
    </TechnicalProfile>
  </RelyingParty>
</TrustFrameworkPolicy>


问:
How to properly type grouped options data in react-select
I'm trying to pass grouped options data to the react-select but can't figure out how to properly type my typescript models and what type should be assigned to the option in the onChange handler in particular.

Below are the TS models I use, their shape corresponds to the data retrieved from the remote API.

```<code>export interface ILotCategoryOption {
  readonly label: string;
  readonly value: string;
}

export interface ILotCategoryOptionsGroup {
  readonly label: string;
  readonly options: ILotCategoryOption[];
}
</code>```

Here lotCategories is the ILotCategoryOptionsGroup[];

```<code><Select options={lotCategories} onChange={handleLotCategoryChange} />
</code>```

What type the option should be assigned?

I tried using SingleValue<ILotCategoryOption> but it's incompatible.
The hint in the VS Code shows the SingleValue<ILotCategoryOptionsGroup> as the expected type for the option, but how can I extract current value then?

It works with any, but I understand this is against the intent of using types.

```<code>const handleLotCategoryChange = (option: any) => {
  setSearchFilters(prev => ({
    ...prev, categoryId: +option?.value ?? null
  }));
}
</code>```

Update

It works if I provide the handler with both option: SingleValue<ILotCategoryOption> (or with ILotCategoryOption|null) and actionMeta: ActionMeta<ILotCategoryOption> parameters.

```<code>const handleLotCategoryChange = (
  option: SingleValue<ILotCategoryOption>,
  actionMeta: ActionMeta<ILotCategoryOption>
) => {
  setSearchFilters(prev => ({
    ...prev, categoryId: option?.value ? +option.value : null
  }));
}
</code>```

Is this because the actionMeta is a required parameter?

But at the same time I have this handler for non-grouped items:

```<code>const handleCompanyChange = (option: SingleValue<ICompany>) => {
  setSearchFilters(prev => ({
    ...prev, companyId: option?.id ?? null
  }));
}
</code>```

Body:
I'm trying to pass grouped options data to the react-select but can't figure out how to properly type my typescript models and what type should be assigned to the option in the onChange handler in particular.

Below are the TS models I use, their shape corresponds to the data retrieved from the remote API.

export interface ILotCategoryOption {
  readonly label: string;
  readonly value: string;
}

export interface ILotCategoryOptionsGroup {
  readonly label: string;
  readonly options: ILotCategoryOption[];
}

Here lotCategories is the ILotCategoryOptionsGroup[];

<Select options={lotCategories} onChange={handleLotCategoryChange} />

What type the option should be assigned?

I tried using SingleValue<ILotCategoryOption> but it's incompatible.
The hint in the VS Code shows the SingleValue<ILotCategoryOptionsGroup> as the expected type for the option, but how can I extract current value then?

It works with any, but I understand this is against the intent of using types.

const handleLotCategoryChange = (option: any) => {
  setSearchFilters(prev => ({
    ...prev, categoryId: +option?.value ?? null
  }));
}

Update

It works if I provide the handler with both option: SingleValue<ILotCategoryOption> (or with ILotCategoryOption|null) and actionMeta: ActionMeta<ILotCategoryOption> parameters.

const handleLotCategoryChange = (
  option: SingleValue<ILotCategoryOption>,
  actionMeta: ActionMeta<ILotCategoryOption>
) => {
  setSearchFilters(prev => ({
    ...prev, categoryId: option?.value ? +option.value : null
  }));
}

Is this because the actionMeta is a required parameter?

But at the same time I have this handler for non-grouped items:

const handleCompanyChange = (option: SingleValue<ICompany>) => {
  setSearchFilters(prev => ({
    ...prev, companyId: option?.id ?? null
  }));
}


问:
How can I provide subclass-specific methods to call on an instance of baseclass?
Trivially, if I have a base-class and several sub-classes which all implement the same method signature, I can do the following:

```<code>abstract class BaseClass
{
 public abstract int GetValue();
}

class SubClass : BaseClass
{
 public override int GetValue() => 123;
}
...

class MyClass
{
 public void SomeMethod()
 {
  BaseClass o = ...;
  var i = o.GetValue();
 }
}
</code>```

But what if I want to provide subclass-specific logic outside the subclass (perhaps a Visitor pattern or something)? You cannot do the following because it involves a conversion, you have to know which type 'o' is:

```<code>class MyClass
{
 public void SomeMethod()
 {
  BaseClass o = ...;
  int i = CalculateSomething(o);
 }

 private int CalculateSomething(SubClass o)
 {
  return 999;
 }
}
</code>```

Is there an obvious workaround in code or design that doesn't involve explicitly checking the type?

Body:
Trivially, if I have a base-class and several sub-classes which all implement the same method signature, I can do the following:

abstract class BaseClass
{
 public abstract int GetValue();
}

class SubClass : BaseClass
{
 public override int GetValue() => 123;
}
...

class MyClass
{
 public void SomeMethod()
 {
  BaseClass o = ...;
  var i = o.GetValue();
 }
}

But what if I want to provide subclass-specific logic outside the subclass (perhaps a Visitor pattern or something)? You cannot do the following because it involves a conversion, you have to know which type 'o' is:

class MyClass
{
 public void SomeMethod()
 {
  BaseClass o = ...;
  int i = CalculateSomething(o);
 }

 private int CalculateSomething(SubClass o)
 {
  return 999;
 }
}

Is there an obvious workaround in code or design that doesn't involve explicitly checking the type?