问:
partial search and lowercase search in nodejs
I'm trying to implement multiple search functionality such as userName and userId with separate input for userName and userId. If I give userName as "Dave Steve" or "dave steve" or "Dave" or "steve" or "dav" and click on the search button I should get the result But When I give "Dave steve" it working fine but not with other case How do I implement it ?

Json data:

```<code>let logData={
"dataLog":
[
    {
        "userId":"1",
        "userName":"Dave Steve",
    },
    {
        "userId":"2",
        "userName":"John Doe",
    }
],
}
</code>```

Here is my code

```<code>app.get('/getData', (req, res) => {
  let accessData= logData.dataLog;
  let userName = req.query.userName;
  let userId = req.query.userId;
    console.log(userName, userId)
    let filterData = accessData.filter((data) => {
      return (userId === undefined || data.userId === userId) &&
        (userName === undefined || userName === userNameData)
    })
    console.log(filterData)
    const response = {
      header: getSuccessHeader,
      body: filterData
    };
    res.status(200);
    res.send(response);
});
</code>```

答:
Please try it</p>
```<code>app.get('/getData', (req, res) => {
  let accessData= logData.dataLog;
  let userName = req.query.userName;
  let userId = req.query.userId;
    console.log(userName, userId)
    let filterData = accessData.filter((data) => {
      return (userId === undefined || data.userId === userId) &&
        (userName === undefined || userName.toLowerCase().includes(userNameData.toLowerCase()))
    })
    console.log(filterData)
    const response = {
      header: getSuccessHeader,
      body: filterData
    };
    res.status(200);
    res.send(response);
});
</code>```

Body:
I'm trying to implement multiple search functionality such as userName and userId with separate input for userName and userId. If I give userName as "Dave Steve" or "dave steve" or "Dave" or "steve" or "dav" and click on the search button I should get the result But When I give "Dave steve" it working fine but not with other case How do I implement it ?

Json data:

let logData={
"dataLog":
[
    {
        "userId":"1",
        "userName":"Dave Steve",
    },
    {
        "userId":"2",
        "userName":"John Doe",
    }
],
}

Here is my code

app.get('/getData', (req, res) => {
  let accessData= logData.dataLog;
  let userName = req.query.userName;
  let userId = req.query.userId;
    console.log(userName, userId)
    let filterData = accessData.filter((data) => {
      return (userId === undefined || data.userId === userId) &&
        (userName === undefined || userName === userNameData)
    })
    console.log(filterData)
    const response = {
      header: getSuccessHeader,
      body: filterData
    };
    res.status(200);
    res.send(response);
});

Body:
Please try it

app.get('/getData', (req, res) => {
  let accessData= logData.dataLog;
  let userName = req.query.userName;
  let userId = req.query.userId;
    console.log(userName, userId)
    let filterData = accessData.filter((data) => {
      return (userId === undefined || data.userId === userId) &&
        (userName === undefined || userName.toLowerCase().includes(userNameData.toLowerCase()))
    })
    console.log(filterData)
    const response = {
      header: getSuccessHeader,
      body: filterData
    };
    res.status(200);
    res.send(response);
});


来源: stackexchange

问:
How do I compare and verify user input field to stored data BEFORE to sending form in ColdFusion
I’m updating a site for my brother who teaches training courses. He has a registration form on the site that collects name, age, address, etc. That information is sent to him through cfmail with a copy sent to the registrant. The registrants then mails in a check via snail-mail to complete the registration. (My brother does NOT want to use an online payment method.)

Included in the form is the course name, location and fee. He asked if it was possible to implement some sort of “Promo Code” to offer discounts to select users. I’ve added PromoCode and PromoCode_Fee columns in SQL and am able to make it all work throughout the process.

My problem is on the user end. If the user mistypes the PromoCode in the form, the app will obviously not register the discount, send the registration emails out with the standard fee, and store the registration info in the DB. The only way for the user to fix the PromoCode would be to re-register, which would re-send the emails and add a new registration to the DB.

What I’d like to do is verify that the user entered a valid PromoCode in the input field PRIOR to submitting the form by comparing what they typed to the PromoCode stored in the DB. If the PromoCode doesn’t match, add “Promo Code is invalid” under the input field.

I do this as a hobby, am self-taught and am not sure if it’s even possible (or  good idea.) I imagine it’s not possible to do with ColdFusion and would most likely need some sort of JS or jQuery - both of which I’m pretty illiterate in.

I’ve been searching for hours to see if anyone had any similar questions, but have come up short. Any help or pointing me in the right direction would be greatly appreciated.

Here's the code I'm putting together:

```<code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="/scripts/jquery.validate.js"></script>

<script>
    $(document).ready(function() {
        var validator = $("#signupform").validate({
            rules: {
                firstname: "required",
                lastname: "required",
                username: {
                    required: true,
                    minlength: 2,
                    remote: "/components/promocodecomponent.cfc?method=validateUserName"
                }
            }
        });
    });
</script>

<div class="row justify-content-center">
    <div class="col-10">
        <form id="signupform" autocomplete="off" method="get" action="">
            <table>
                <tr>
                    <td class="label">
                        <label id="lfirstname" for="firstname">First Name</label>
                    </td>
                    <td class="field">
                        <input id="firstname" name="firstname" type="text" value="" maxlength="100">
                    </td>
                    <td class="status"></td>
                </tr>
                <tr>
                    <td class="label">
                        <label id="llastname" for="lastname">Last Name</label>
                    </td>
                    <td class="field">
                        <input id="lastname" name="lastname" type="text" value="" maxlength="100">
                    </td>
                    <td class="status"></td>
                </tr>
                <tr>
                    <td class="label">
                        <label id="lusername" for="username">Username</label>
                    </td>
                    <td class="field">
                        <input id="username" name="username" type="text" value="" maxlength="50">
                    </td>
                    <td class="status"></td>
                </tr>
                <tr>
                    <td class="field" colspan="2">
                        <input id="signupsubmit" name="signup" type="submit" value="Signup">
                    </td>
                </tr>
            </table>
        </form>
    </div>
</div>
</code>```

Here's the component code:

```<code>component {
    remote boolean function validateUserName(string username) returnFormat="json"{

        if (arguments.username == "john") {
            return true;
        }

        return "Username already in use";
    }

}
</code>```

答:
Usually, you'd need to post some code that you've tried and isn't working. But you've outlined what you want and are just not sure where to start.

You can test just the value of the discount code before allowing the whole form to be submitted. You don't say how you're doing client-side form validation. I'd suggest using jQuery Validate to handle that, it's very easy to implement.

https://jqueryvalidation.org/documentation/

Go to the demo "The Remember The Milk sign-up form". This form checks the username field via Ajax before the rest of the form can be submitted.

```<code>var validator = $("#signupform").validate({
    rules: {
        firstname: "required",
        lastname: "required",
        username: {
            required: true,
            minlength: 2,
            remote: "users.action"
        }
    }
});
</code>```

If not using this framework, then just make an Ajax request when change is triggered on the discount code field and make sure there's a positive response from that before you allow the form to be submitted.

Also, you need to do server-side validation of the discount code when someone submits the form. If they've entered a discount code that is invalid, then don't allow the form to be processed until they enter a valid code or they clear the value from that field.

ContentLicense: CC BY-SA 4.0

Body:
I’m updating a site for my brother who teaches training courses. He has a registration form on the site that collects name, age, address, etc. That information is sent to him through cfmail with a copy sent to the registrant. The registrants then mails in a check via snail-mail to complete the registration. (My brother does NOT want to use an online payment method.)

Included in the form is the course name, location and fee. He asked if it was possible to implement some sort of “Promo Code” to offer discounts to select users. I’ve added PromoCode and PromoCode_Fee columns in SQL and am able to make it all work throughout the process.

My problem is on the user end. If the user mistypes the PromoCode in the form, the app will obviously not register the discount, send the registration emails out with the standard fee, and store the registration info in the DB. The only way for the user to fix the PromoCode would be to re-register, which would re-send the emails and add a new registration to the DB.

What I’d like to do is verify that the user entered a valid PromoCode in the input field PRIOR to submitting the form by comparing what they typed to the PromoCode stored in the DB. If the PromoCode doesn’t match, add “Promo Code is invalid” under the input field.

I do this as a hobby, am self-taught and am not sure if it’s even possible (or  good idea.) I imagine it’s not possible to do with ColdFusion and would most likely need some sort of JS or jQuery - both of which I’m pretty illiterate in.

I’ve been searching for hours to see if anyone had any similar questions, but have come up short. Any help or pointing me in the right direction would be greatly appreciated.

Here's the code I'm putting together:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

        <form id="signupform" autocomplete="off" method="get" action="">

                        First Name

                        <input id="firstname" name="firstname" type="text" value="" maxlength="100">

                        Last Name

                        <input id="lastname" name="lastname" type="text" value="" maxlength="100">

                        Username

                        <input id="username" name="username" type="text" value="" maxlength="50">

                        <input id="signupsubmit" name="signup" type="submit" value="Signup">

        </form>

Here's the component code:

component {
    remote boolean function validateUserName(string username) returnFormat="json"{

        if (arguments.username == "john") {
            return true;
        }

        return "Username already in use";
    }

}

Body:
Usually, you'd need to post some code that you've tried and isn't working. But you've outlined what you want and are just not sure where to start.

You can test just the value of the discount code before allowing the whole form to be submitted. You don't say how you're doing client-side form validation. I'd suggest using jQuery Validate to handle that, it's very easy to implement.

https://jqueryvalidation.org/documentation/

Go to the demo "The Remember The Milk sign-up form". This form checks the username field via Ajax before the rest of the form can be submitted.

var validator = $("#signupform").validate({
    rules: {
        firstname: "required",
        lastname: "required",
        username: {
            required: true,
            minlength: 2,
            remote: "users.action"
        }
    }
});

If not using this framework, then just make an Ajax request when change is triggered on the discount code field and make sure there's a positive response from that before you allow the form to be submitted.

Also, you need to do server-side validation of the discount code when someone submits the form. If they've entered a discount code that is invalid, then don't allow the form to be processed until they enter a valid code or they clear the value from that field.


问:
How to use default filters using UI component in admin grid Magento 2
I want to apply default filters on records while using magento 2 admin grid using UI Component.

I know there is a way while using block to render admin grid but i want the way using UI component.

答:
You can add this in your ui_component/custom_listing.xml which should create filter button in grid:

```<code><listingToolbar name="listing_top">
    <filters name="listing_filters"/>
</listingToolbar>
</code>```

And columns which should have been filtered needed to have "filter" field in column config, for ex.:

```<code><column name="entity_id">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="filter" xsi:type="string">text</item>
                <item name="sorting" xsi:type="string">asc</item>
                <item name="label" xsi:type="string" translate="true">Entity ID</item>
            </item>
        </argument>
    </column>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can add this in your ui_component/custom_listing.xml which should create filter button in grid:

<listingToolbar name="listing_top">
    <filters name="listing_filters"/>
</listingToolbar>

And columns which should have been filtered needed to have "filter" field in column config, for ex.:

<column name="entity_id">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="filter" xsi:type="string">text</item>
                <item name="sorting" xsi:type="string">asc</item>
                <item name="label" xsi:type="string" translate="true">Entity ID</item>
            </item>
        </argument>
    </column>


问:
What is wrong with my "Collatz conjecture"?
So, I was just trying to create a loop to run the "3n+1" formula and when I enter a negative number I get stuck in an infinite loop with a remainder of 0 and -1.

Is that correct or is my code missing something?

Here is my code:

```<code>    Scanner scan = new Scanner(System.in);
    number = 0;
    method = 0;
int counter= 0;

if(scan.hasNextInt()){
     number = scan.nextInt();
  int original = number;
 while(number!=1){
      method = number%2;
     if(method==0){
    number = number/2;
 }else number = number*3+1;
 counter +=1;
  System.out.println(number);
  System.out.println("the remainder was "+method);
 }

 System.out.println("The original number was "+original);
 System.out.println("it took " + counter+ " times to reach 1.");

}else System.out.println("please enter a number");
</code>```

答:
Several loops get formed.  Further googling will show you there are 3-4 (google for an exact count) loops formed.  And then the rest of the negative numbers should also get back down to $-1$ or in other words "something analogous" to the positive case.  So you got stuck in the first loop! LOL

I think it should be considered extended to the group of integers so that there is a hope of immediately applying Group Cohomology techniques instead of Monoid Cohomology techniques (which are less explored).

Body:
So, I was just trying to create a loop to run the "3n+1" formula and when I enter a negative number I get stuck in an infinite loop with a remainder of 0 and -1.

Is that correct or is my code missing something?

Here is my code:

    Scanner scan = new Scanner(System.in);
    number = 0;
    method = 0;
int counter= 0;

if(scan.hasNextInt()){
     number = scan.nextInt();
  int original = number;
 while(number!=1){
      method = number%2;
     if(method==0){
    number = number/2;
 }else number = number*3+1;
 counter +=1;
  System.out.println(number);
  System.out.println("the remainder was "+method);
 }

 System.out.println("The original number was "+original);
 System.out.println("it took " + counter+ " times to reach 1.");

}else System.out.println("please enter a number");


问:
How can I add a background image to my react native app?
I am fairly new to react native, but I have some experience. I am creating my own app for both ios and android by following along a tutorial that I had already completed and making my own modifications. As I was in the middle of creating an app, I forgot to add a background image. After struggling with this for several days, I'm desperate, so I decided to ask my question on here.

I am trying to add the background image to my App.js file. The image loads properly, but my page content ( which is inside <LifelineNavigator />) is either hidden or has disappeared for android. And for ios, the content seems to be in a small centered flexbox. Also, I am trying to remove the white background.

Any suggestions would definitely help. Thanks so much! God bless!

Here is my code:

```<code>import React, { useState } from "react";
import { StyleSheet, View, ImageBackground } from "react-native";
import * as Font from "expo-font";
import AppLoading from "expo-app-loading";
import { enableScreens } from "react-native-screens";

import LifelineNavigator from "./src/navigation/LifelineNavigator";

enableScreens();

const fetchFonts = () => {
   return Font.loadAsync({
      "Gotham-Medium": require("./src/assets/fonts/Gotham-Font/Gotham-Medium.otf")

const image = {
    uri: "https://i.ibb.co/8z6QbTS/Lifeline-Gradient-Background-24.png",
    };

const App = () => {
  const [fontLoaded, setFontLoaded] = useState(false);

  if (!fontLoaded) {
    return (
      <AppLoading
        startAsync={fetchFonts}
        onFinish={() => setFontLoaded(true)}
        onError={(err) => console.log(err)}
      />
    );
  }

  return (
    <View >
      <ImageBackground source={image} style={styles.image}>
        <View style={ styles.container }>
            <LifelineNavigator />
        </View>
      </ImageBackground>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    // backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center",
  },
  image: {
    width: "100%",
    height: "100%" ,
  }
});

export default App;
</code>```

IOS Screenshot

Android Screenshot

答:
```<code>import React from "react";
import { ImageBackground, StyleSheet, Text, View } from "react-native";

const image = { uri: "https://reactjs.org/logo-og.png" };

const App = () => (
  <View style={styles.container}>
    <ImageBackground source={image} resizeMode="cover" style={styles.image}>
      <Text style={styles.text}>Inside</Text>
    </ImageBackground>
  </View>
);

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  image: {
    flex: 1,
    justifyContent: "center"
  },
  text: {
    color: "white",
    fontSize: 42,
    lineHeight: 84,
    fontWeight: "bold",
    textAlign: "center",
    backgroundColor: "#000000c0"
  }
});

export default App;
</code>```

follow this documentation > https://reactnative.dev/docs/imagebackground
it may solve your problem

Body:
I am fairly new to react native, but I have some experience. I am creating my own app for both ios and android by following along a tutorial that I had already completed and making my own modifications. As I was in the middle of creating an app, I forgot to add a background image. After struggling with this for several days, I'm desperate, so I decided to ask my question on here.

I am trying to add the background image to my App.js file. The image loads properly, but my page content ( which is inside <LifelineNavigator />) is either hidden or has disappeared for android. And for ios, the content seems to be in a small centered flexbox. Also, I am trying to remove the white background.

Any suggestions would definitely help. Thanks so much! God bless!

Here is my code:

import React, { useState } from "react";
import { StyleSheet, View, ImageBackground } from "react-native";
import * as Font from "expo-font";
import AppLoading from "expo-app-loading";
import { enableScreens } from "react-native-screens";

import LifelineNavigator from "./src/navigation/LifelineNavigator";

enableScreens();

const fetchFonts = () => {
   return Font.loadAsync({
      "Gotham-Medium": require("./src/assets/fonts/Gotham-Font/Gotham-Medium.otf")

const image = {
    uri: "https://i.ibb.co/8z6QbTS/Lifeline-Gradient-Background-24.png",
    };

const App = () => {
  const [fontLoaded, setFontLoaded] = useState(false);

  if (!fontLoaded) {
    return (
      <AppLoading
        startAsync={fetchFonts}
        onFinish={() => setFontLoaded(true)}
        onError={(err) => console.log(err)}
      />
    );
  }

  return (
    <View >
      <ImageBackground source={image} style={styles.image}>
        <View style={ styles.container }>
            <LifelineNavigator />
        </View>
      </ImageBackground>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    // backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center",
  },
  image: {
    width: "100%",
    height: "100%" ,
  }
});

export default App;

IOS Screenshot

Android Screenshot

Body:
import React from "react";
import { ImageBackground, StyleSheet, Text, View } from "react-native";

const image = { uri: "https://reactjs.org/logo-og.png" };

const App = () => (
  <View style={styles.container}>
    <ImageBackground source={image} resizeMode="cover" style={styles.image}>
      <Text style={styles.text}>Inside</Text>
    </ImageBackground>
  </View>
);

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  image: {
    flex: 1,
    justifyContent: "center"
  },
  text: {
    color: "white",
    fontSize: 42,
    lineHeight: 84,
    fontWeight: "bold",
    textAlign: "center",
    backgroundColor: "#000000c0"
  }
});

export default App;

follow this documentation > https://reactnative.dev/docs/imagebackground
it may solve your problem


问:
Selecting value using HQL based on a key of a Map
Suppose I have following JPA mapping.

```<code>

    @Entity
    @Table(name = "transaction")
    public class Transaction {

        @ElementCollection(targetClass = String.class, fetch = FetchType.EAGER)
        @JoinTable(name = "trx_addi_info")
        private Map additionalInfo;

    }

</code>```

I want to write HQL to fetch all the transactions which has particular key-value pair in the additionalInfo map. I think I have to do a join like follows,

```<code>

    SELECT trx FROM Transaction trx inner join trx.additionalInfo addInfo WHERE addInfo.????

</code>```

But I'm not clear how to put the WHERE clause to get match with particular key-value pair in additionalInfo map. Can anybody help me on this?

Thanks in advance.

答:
You need to use HQL index() specific function, that applies to aliases of a joined indexed collection (arrays, lists, and maps). See section 14.10. Expressions of the Hibernate reference documentation

```<code>//Example of HQL returning `Transaction` object that have `additianlInfo` with
//the `KEY` equal to the string `test`

SELECT trx FROM Transaction trx inner join trx.additionalInfo addInfo WHERE index(addInfo) > 'test'
</code>```

Body:
Suppose I have following JPA mapping.

    @Entity
    @Table(name = "transaction")
    public class Transaction {

        @ElementCollection(targetClass = String.class, fetch = FetchType.EAGER)
        @JoinTable(name = "trx_addi_info")
        private Map additionalInfo;

    }

I want to write HQL to fetch all the transactions which has particular key-value pair in the additionalInfo map. I think I have to do a join like follows,

    SELECT trx FROM Transaction trx inner join trx.additionalInfo addInfo WHERE addInfo.????

But I'm not clear how to put the WHERE clause to get match with particular key-value pair in additionalInfo map. Can anybody help me on this?

Thanks in advance.

Body:
You need to use HQL index() specific function, that applies to aliases of a joined indexed collection (arrays, lists, and maps). See section 14.10. Expressions of the Hibernate reference documentation

//Example of HQL returning `Transaction` object that have `additianlInfo` with
//the `KEY` equal to the string `test`

SELECT trx FROM Transaction trx inner join trx.additionalInfo addInfo WHERE index(addInfo) > 'test'


问:
how to access snapshot.data inside Listview.builder inside futurebuilder
I am getting error The method '[]' can't be unconditionally invoked because the receiver can be 'null'.

Mydata inside _categoriesList future

```<code>[
        {
            "business_category_id": 1,
            "business_category": "Manufacturer",
            "business_category_image": "164423936662011a06c450d.png"
        },
        {
            "business_category_id": 2,
            "business_category": "Distributor",
            "business_category_image": "164423937762011a11033aa.png"
        },
        {
            "business_category_id": 3,
            "business_category": "Wholesaler",
            "business_category_image": "164423938762011a1bb2e3c.png"
        },
        {
            "business_category_id": 4,
            "business_category": "Retailer",
            "business_category_image": "164423940062011a28189e5.png"
        },
        {
            "business_category_id": 5,
            "business_category": "Reseller",
            "business_category_image": "164423941362011a3554148.png"
        },
        {
            "business_category_id": 6,
            "business_category": "Service Provider",
            "business_category_image": "164423942462011a4096996.png"
        }
    ]
</code>```

my code inside futurebuilder. I am having problem accessing snapshot.data[index]

```<code>FutureBuilder(
      future: _categoriesList,
      builder: (_, snapshot) {
        if (snapshot.hasData) {

          return ListView.builder(
              itemCount: 6,
              itemBuilder: (_, index) {
                return Text(snapshot.data[index]); // error The method '[]' can't be unconditionally invoked because the receiver can be 'null'
              });
        }
      },
)
</code>```

答:
Specify your data-type for list in FutureBuilder first.

```<code>FutureBuilder<List<String>>()
</code>```

//
Check if you are getting data. print the data using snapshot.data.

```<code>FutureBuilder<List<String>>(
      future: _categoriesList,
      builder: (_, snapshot) {
        if (snapshot.hasData) {
          print("snapshot:: data >>>> ${snapshot.data}");
          return ListView.builder(
              itemCount: 6,
              itemBuilder: (_, index) {
                return Text(snapshot.data[index]); // error The method '[]' can't be unconditionally invoked because the receiver can be 'null'
              });
        }
      },
)
</code>```

Body:
I am getting error The method '[]' can't be unconditionally invoked because the receiver can be 'null'.

Mydata inside _categoriesList future

[
        {
            "business_category_id": 1,
            "business_category": "Manufacturer",
            "business_category_image": "164423936662011a06c450d.png"
        },
        {
            "business_category_id": 2,
            "business_category": "Distributor",
            "business_category_image": "164423937762011a11033aa.png"
        },
        {
            "business_category_id": 3,
            "business_category": "Wholesaler",
            "business_category_image": "164423938762011a1bb2e3c.png"
        },
        {
            "business_category_id": 4,
            "business_category": "Retailer",
            "business_category_image": "164423940062011a28189e5.png"
        },
        {
            "business_category_id": 5,
            "business_category": "Reseller",
            "business_category_image": "164423941362011a3554148.png"
        },
        {
            "business_category_id": 6,
            "business_category": "Service Provider",
            "business_category_image": "164423942462011a4096996.png"
        }
    ]

my code inside futurebuilder. I am having problem accessing snapshot.data[index]

FutureBuilder(
      future: _categoriesList,
      builder: (_, snapshot) {
        if (snapshot.hasData) {

          return ListView.builder(
              itemCount: 6,
              itemBuilder: (_, index) {
                return Text(snapshot.data[index]); // error The method '[]' can't be unconditionally invoked because the receiver can be 'null'
              });
        }
      },
)

Body:
Specify your data-type for list in FutureBuilder first.

FutureBuilder<List<String>>()

//
Check if you are getting data. print the data using snapshot.data.

FutureBuilder<List<String>>(
      future: _categoriesList,
      builder: (_, snapshot) {
        if (snapshot.hasData) {
          print("snapshot:: data >>>> ${snapshot.data}");
          return ListView.builder(
              itemCount: 6,
              itemBuilder: (_, index) {
                return Text(snapshot.data[index]); // error The method '[]' can't be unconditionally invoked because the receiver can be 'null'
              });
        }
      },
)


问:
The argument type 'Null' can't be assigned to the parameter type 'Key'
I want to call CreateProfile() in my main.dart.. but it gives me an  error.. the below image showing the error in main.dart and I have included my createprofile.dart code for you to refer.

The argument type 'Null' can't be assigned to the parameter type
'Key'.

starting code of CreateProfile.dart

```<code>import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:convert';
import 'package:http/http.dart' ;

class CreateProfile extends StatefulWidget {
  CreateProfile({required Key key}) : super(key: key);

  @override
  _CreateProfileState createState() => _CreateProfileState();
}

class _CreateProfileState extends State<CreateProfile> {

  bool circular = false;
  PickedFile? _imageFile;
  final ImagePicker _picker = ImagePicker();

  final _globalkey = GlobalKey<FormState>();

  TextEditingController _name = TextEditingController();
  TextEditingController _profession = TextEditingController();
  TextEditingController _dob = TextEditingController();
  TextEditingController _title = TextEditingController();
  TextEditingController _about = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Form(
        key: _globalkey,
        child: ListView(
          padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 30),
          children: <Widget>[
            imageProfile(),
            SizedBox(
              height: 20,
            ),
</code>```

答:
Pass a UniqueKey to CreateProfile like this.

```<code>CreateProfile(key: UniqueKey())
</code>```

Body:
I want to call CreateProfile() in my main.dart.. but it gives me an  error.. the below image showing the error in main.dart and I have included my createprofile.dart code for you to refer.

The argument type 'Null' can't be assigned to the parameter type
'Key'.

starting code of CreateProfile.dart

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:convert';
import 'package:http/http.dart' ;

class CreateProfile extends StatefulWidget {
  CreateProfile({required Key key}) : super(key: key);

  @override
  _CreateProfileState createState() => _CreateProfileState();
}

class _CreateProfileState extends State<CreateProfile> {

  bool circular = false;
  PickedFile? _imageFile;
  final ImagePicker _picker = ImagePicker();

  final _globalkey = GlobalKey<FormState>();

  TextEditingController _name = TextEditingController();
  TextEditingController _profession = TextEditingController();
  TextEditingController _dob = TextEditingController();
  TextEditingController _title = TextEditingController();
  TextEditingController _about = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Form(
        key: _globalkey,
        child: ListView(
          padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 30),
          children: <Widget>[
            imageProfile(),
            SizedBox(
              height: 20,
            ),

Body:
Pass a UniqueKey to CreateProfile like this.

CreateProfile(key: UniqueKey())


问:
Change toolbar layout design

I am trying to make the toolbar in my app look like its curving dowbward like in the photo any ideas how i can do this

答:
Well rather then applying toolbar why don't you add a background Color black with two textViews (i.e) No connection and retry and make a cardView with white background and overlap it to the black background just below the text view this can solve it
Something Like This and adjust the height and everything according to your need!!</p>
```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/black">

    <TextView
        android:id="@+id/textView30"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="10dp"
        android:layout_marginTop="10dp"
        android:text="No Connection"
        android:textColor="@color/white"
        android:textSize="18dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_marginEnd="20dp"
        android:text="Retry"
        android:textColor="@color/white"
        android:textSize="18dp"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="600dp"
        android:layout_marginTop="10dp"
        app:cardCornerRadius="40dp"
        app:layout_constraintTop_toBottomOf="@+id/textView30" />

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Title: Change toolbar layout design

Body:
Well rather then applying toolbar why don't you add a background Color black with two textViews (i.e) No connection and retry and make a cardView with white background and overlap it to the black background just below the text view this can solve it
Something Like This and adjust the height and everything according to your need!!

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/black">

    <TextView
        android:id="@+id/textView30"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="10dp"
        android:layout_marginTop="10dp"
        android:text="No Connection"
        android:textColor="@color/white"
        android:textSize="18dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_marginEnd="20dp"
        android:text="Retry"
        android:textColor="@color/white"
        android:textSize="18dp"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="600dp"
        android:layout_marginTop="10dp"
        app:cardCornerRadius="40dp"
        app:layout_constraintTop_toBottomOf="@+id/textView30" />

</androidx.constraintlayout.widget.ConstraintLayout>


问:
how to change the value of  in javascript?
i have an element in html as shown below.

```<code><tr><td class="HELPTEXT"><span lang="HLPMTXT1" id="HLPMTXT1"></span></td></tr>
</code>```

i want to change the value of lang according to particular condition.
I tried as given below.but its not working.

Could anyone help me for changing the value of lang attribute of span?

答:
```<code>document.getElementById('HLPMTXT1').setAttribute('lang', 'HLPMTXT2');
</code>```

Not all attributes can be accessed through the object properties

Title: how to change the value of <span lang> in javascript?

Body:
i have an element in html as shown below.

i want to change the value of lang according to particular condition.
I tried as given below.but its not working.

Could anyone help me for changing the value of lang attribute of span?

Body:
document.getElementById('HLPMTXT1').setAttribute('lang', 'HLPMTXT2');

Not all attributes can be accessed through the object properties


Title: Gathering separate rows into one based on three grouping variables R

Body:
I have some data-wrangling I'm struggling with. Below is a minimal working example. I need some rolling loop which for every unique participant*item*cond combination, looks from the first row to the last row, pasting together each value in thresh into a new column (should look like what_I_want). Does anyone have any tips?

my_df <- data.frame("participant" = c("1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1",
                                "2", "2", "2", "2", "2", "2", "2", "2", "2", "2", "2", "2", "2", "2", "2", "2"),
              "item" = c("101", "101", "101", "101", "101", "101", "101", "101", "102", "102", "102", "102", "102", "102", "102", "102", "101", "101", "101", "101", "101", "101", "101", "101", "103", "103", "103", "103", "103", "103", "103", "103"),
              "cond" = c("a", "a", "a", "a", "b", "b", "b", "b", "a", "a", "a", "a", "b", "b", "b", "b", "a", "a", "a", "a", "b", "b", "b", "b", "a", "a", "a", "a", "b", "b", "b", "b"),
              "thresh" = c(1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1),
              "what_I_want" = c("1011", "1011", "1011", "1011", "1101", "1101", "1101", "1101", "1001", "1001", "1001", "1001", "1111", "1111", "1111", "1111", "0011", "0011", "0011", "0011", "0000", "0000", "0000", "0000", "1010", "1010", "1010", "1010", "1011", "1011", "1011", "1011"))

Body:
You can group by the three columns (i.e., participant, item, cond), then use collapse within paste0 to combine all values in the group for thresh.

library(tidyverse)

my_df %>%
  group_by(participant, item, cond) %>%
  mutate(result = paste0(thresh, collapse = ""))

base R option:

merge(my_df,
      setNames(
        aggregate(thresh ~ participant + item + cond, my_df, paste, collapse = ""),
        c("participant", "item", "cond", "result")
      ),
      by = c("participant", "item", "cond"))

Output

   participant item  cond  thresh what_I_want result
   <chr>       <chr> <chr>  <dbl> <chr>       <chr>
 1 1           101   a          1 1011        1011
 2 1           101   a          0 1011        1011
 3 1           101   a          1 1011        1011
 4 1           101   a          1 1011        1011
 5 1           101   b          1 1101        1101
 6 1           101   b          1 1101        1101
 7 1           101   b          0 1101        1101
 8 1           101   b          1 1101        1101
 9 1           102   a          1 1001        1001
10 1           102   a          0 1001        1001
11 1           102   a          0 1001        1001
12 1           102   a          1 1001        1001
13 1           102   b          1 1111        1111
14 1           102   b          1 1111        1111
15 1           102   b          1 1111        1111
16 1           102   b          1 1111        1111
17 2           101   a          0 0011        0011
18 2           101   a          0 0011        0011
19 2           101   a          1 0011        0011
20 2           101   a          1 0011        0011
21 2           101   b          0 0000        0000
22 2           101   b          0 0000        0000
23 2           101   b          0 0000        0000
24 2           101   b          0 0000        0000
25 2           103   a          1 1010        1010
26 2           103   a          0 1010        1010
27 2           103   a          1 1010        1010
28 2           103   a          0 1010        1010
29 2           103   b          1 1011        1011
30 2           103   b          0 1011        1011
31 2           103   b          1 1011        1011
32 2           103   b          1 1011        1011


问:
Should properties of constants be capitalized?
I know that it is conventional to capitalize constant values in programming, but would you do the same for their keys? I am trying to make a string based enum in javascript:

```<code>const SEASONS = {
  spring: 'spring',
  summer: 'summer',
  fall: 'fall',
  winter: 'winter'
}

// or

const SEASONS = {
  SPRING: 'spring',
  SUMMER: 'summer',
  FALL: 'fall',
  WINTER: 'winter'
}
</code>```

Is it conventional to capitalize the keys, if they are also constant? So that you access their values by SEASONS.SPRING instead of SEASONS.spring?

答:
As per MDN, Constants can be declared with uppercase or lowercase, but a common convention is to use all-uppercase letters.

There is no specific rule that the declaration SHOULD be in uppercase.

Uppercase indicates that the variable is a constant and they are immutable.

But the properties inside a constant are mutable and hence they CAN be declared as lowercase.

```<code>const SEASONS = {
  spring: 'spring',
  summer: 'summer',
  fall: 'fall',
  winter: 'winter'
}
</code>```

SEASONS are immutable but SEASONS.spring is mutable, hence that CAN be considered as lowercase.

And again, there is no predefined rule for this. Its upto you, but you should follow the same pattern throughout the application.

Body:
I know that it is conventional to capitalize constant values in programming, but would you do the same for their keys? I am trying to make a string based enum in javascript:

const SEASONS = {
  spring: 'spring',
  summer: 'summer',
  fall: 'fall',
  winter: 'winter'
}

// or

const SEASONS = {
  SPRING: 'spring',
  SUMMER: 'summer',
  FALL: 'fall',
  WINTER: 'winter'
}

Is it conventional to capitalize the keys, if they are also constant? So that you access their values by SEASONS.SPRING instead of SEASONS.spring?

Body:
As per MDN, Constants can be declared with uppercase or lowercase, but a common convention is to use all-uppercase letters.

There is no specific rule that the declaration SHOULD be in uppercase.

Uppercase indicates that the variable is a constant and they are immutable.

But the properties inside a constant are mutable and hence they CAN be declared as lowercase.

const SEASONS = {
  spring: 'spring',
  summer: 'summer',
  fall: 'fall',
  winter: 'winter'
}

SEASONS are immutable but SEASONS.spring is mutable, hence that CAN be considered as lowercase.

And again, there is no predefined rule for this. Its upto you, but you should follow the same pattern throughout the application.


问:
Why does this error state my class does not implement this interface method?
I have a class that implements an interface and legacy from other class.

I don't know why my code is bad.

The error I get is:

CS0738 'SizeTypeService' does not implement interface member 'IGenericService<ItemType>.GetAll()'.

'GenericService<SizeType>.GetAll()' cannot implement 'IGenericService<ItemType>.GetAll()' because it does not have the matching return type of 'Task<List<ItemType>>'.
```
<p>I think that my interface and class are ok. I don't know why VS is throwing an error.</p>
<pre class="lang-csharp prettyprint-override"><code>public interface IGenericService<TEntity> where TEntity : class
{
    Task<List<TEntity>> GetAll();
    Task<TEntity> GetById(int id);
    Task<TEntity> Insert(TEntity entity);
    Task<TEntity> Update(TEntity entity);
    Task Delete(int id);
}

public class GenericService<TEntity> : IGenericService<TEntity> where TEntity : class
{
    private IGenericRepository<TEntity> genericRepository;

    public GenericService(IGenericRepository<TEntity> genericRepository)
    {
        this.genericRepository = genericRepository;
    }

    public async Task Delete(int id)
    {
        await genericRepository.Delete(id);
    }

    public async Task<List<TEntity>> GetAll()
    {
        return await genericRepository.GetAll();
    }

    public async Task<TEntity> GetById(int id)
    {
        return await genericRepository.GetById(id);
    }

    public async Task<TEntity> Insert(TEntity entity)
    {
        return await genericRepository.Insert(entity);
    }

    public async Task<TEntity> Update(TEntity entity)
    {
        return await genericRepository.Update(entity);
    }
}

public interface ISizeTypeService : IGenericService<ItemType>
{
    Task<List<SizeType>> GetAllSizeTypeActives(int id);
    Task LogicDelete(int id);
}

public class SizeTypeService : GenericService<SizeType>, ISizeTypeService
{
    private ISizeTypeRepository sizeTypeRepository;

    public SizeTypeService(ISizeTypeRepository sizeTypeRepository) : base(sizeTypeRepository)
    {
        this.sizeTypeRepository = sizeTypeRepository;
    }

    public Task<List<SizeType>> GetAllSizeTypeActives(int id)
    {
        return sizeTypeRepository.GetAllSizeTypeActives(id);
    }

    public Task LogicDelete(int id)
    {
        return sizeTypeRepository.LogicDelete(id);
    }
}
</code>```

答:
Simply Ged explained clearly. As code in your ISizeTypeService

```<code>public interface ISizeTypeService: IGenericService<ItemType>
    {
    }
</code>```

Because you get  Task<List> IGenericRepository.GetAll() in  GenericService.
So

I also got a similar error, then I added the following code in SizeTypeService.cs and the error went away

```<code>Task<List<ItemType>> IGenericService<ItemType>.GetAll()
        {
            throw new NotImplementedException();
        }
</code>```

Body:
I have a class that implements an interface and legacy from other class.

I don't know why my code is bad.

The error I get is:

CS0738 'SizeTypeService' does not implement interface member 'IGenericService<ItemType>.GetAll()'.

'GenericService<SizeType>.GetAll()' cannot implement 'IGenericService<ItemType>.GetAll()' because it does not have the matching return type of 'Task<List<ItemType>>'.

I think that my interface and class are ok. I don't know why VS is throwing an error.

public interface IGenericService<TEntity> where TEntity : class
{
    Task<List<TEntity>> GetAll();
    Task<TEntity> GetById(int id);
    Task<TEntity> Insert(TEntity entity);
    Task<TEntity> Update(TEntity entity);
    Task Delete(int id);
}

public class GenericService<TEntity> : IGenericService<TEntity> where TEntity : class
{
    private IGenericRepository<TEntity> genericRepository;

    public GenericService(IGenericRepository<TEntity> genericRepository)
    {
        this.genericRepository = genericRepository;
    }

    public async Task Delete(int id)
    {
        await genericRepository.Delete(id);
    }

    public async Task<List<TEntity>> GetAll()
    {
        return await genericRepository.GetAll();
    }

    public async Task<TEntity> GetById(int id)
    {
        return await genericRepository.GetById(id);
    }

    public async Task<TEntity> Insert(TEntity entity)
    {
        return await genericRepository.Insert(entity);
    }

    public async Task<TEntity> Update(TEntity entity)
    {
        return await genericRepository.Update(entity);
    }
}

public interface ISizeTypeService : IGenericService<ItemType>
{
    Task<List<SizeType>> GetAllSizeTypeActives(int id);
    Task LogicDelete(int id);
}

public class SizeTypeService : GenericService<SizeType>, ISizeTypeService
{
    private ISizeTypeRepository sizeTypeRepository;

    public SizeTypeService(ISizeTypeRepository sizeTypeRepository) : base(sizeTypeRepository)
    {
        this.sizeTypeRepository = sizeTypeRepository;
    }

    public Task<List<SizeType>> GetAllSizeTypeActives(int id)
    {
        return sizeTypeRepository.GetAllSizeTypeActives(id);
    }

    public Task LogicDelete(int id)
    {
        return sizeTypeRepository.LogicDelete(id);
    }
}

Body:
Simply Ged explained clearly. As code in your ISizeTypeService

public interface ISizeTypeService: IGenericService<ItemType>
    {
    }

Because you get  Task<List> IGenericRepository.GetAll() in  GenericService.
So

I also got a similar error, then I added the following code in SizeTypeService.cs and the error went away

Task<List<ItemType>> IGenericService<ItemType>.GetAll()
        {
            throw new NotImplementedException();
        }


问:
Flutter: How to save multiple values to json?
I have a model class for saving last login info

```<code>class LastLogin {
  @JsonKey(name: 'full_name')
  final String? fullName;
  @JsonKey(name: 'login_date')
  final String? loginDate;

  const LastLogin({
    this.fullName,
    this.loginDate,
  });

  factory LastLogin.fromJson(Map<String, dynamic> json) =>
      _$LastLoginFromJson(json);

  Map<String, dynamic> toJson() => _$LastLoginToJson(this);

  @override
  String toString() => toJson().toString();
}
</code>```

I use sharedPrefs. So I created PrefsKey static TypeStoreKey<LastLogin> lastLogin = TypeStoreKey<LastLogin>('LastLogin'); to save last login data in local storage. My app has a list of items. When user presses the button on listTile I save lastLogin info like this

```<code>List<LastLogin> _loginInfo = [
      LastLogin(fullName: orgUnitList.fullName, loginDate: _loginDate)
    ];

onTap: () {
  _sharedPrefsStore.write(PrefsKeys.lastLogin, _lastLoginDate);
}
</code>```

It works fine, I can see that it saved my data and I can used it. Here comes my problem. When user presses another listTile button it overrides last entry. So my lastLogin prefKey only displays last entry. How can I store multiple entries in my prefKey?

答:
Assuming that _sharedPrefStore.write accepts a String as new value, you can do this:

// Get last login
String loginJsonString = _sharedPrefsStore.read(PrefsKeys.lastLogin);
final List loginJsonList = jsonDecode(loginJsonString) as List;
final List<LastLogin> lastLogins = loginJsonList
    .cast<Map<String, dynamic>>()
    .map(LastLogin.fromJson)
    .toList();

LastLogin? latestLogin;

if (lastLogins.isNotEmpty) {
  latestLogin = lastLogins.last;
}

// Add new login
LastLogin newLogin = LastLogin(fullName: 'fullname', loginDate: 'some date');
lastLogins.add(newLogin);
loginJsonString = jsonEncode(loginJsonList);
_sharedPrefsStore.write(PrefsKeys.lastLogin, loginJsonString);
```

You can modify the code above to suit your needs.

Body:
I have a model class for saving last login info

class LastLogin {
  @JsonKey(name: 'full_name')
  final String? fullName;
  @JsonKey(name: 'login_date')
  final String? loginDate;

  const LastLogin({
    this.fullName,
    this.loginDate,
  });

  factory LastLogin.fromJson(Map<String, dynamic> json) =>
      _$LastLoginFromJson(json);

  Map<String, dynamic> toJson() => _$LastLoginToJson(this);

  @override
  String toString() => toJson().toString();
}

I use sharedPrefs. So I created PrefsKey static TypeStoreKey<LastLogin> lastLogin = TypeStoreKey<LastLogin>('LastLogin'); to save last login data in local storage. My app has a list of items. When user presses the button on listTile I save lastLogin info like this

List<LastLogin> _loginInfo = [
      LastLogin(fullName: orgUnitList.fullName, loginDate: _loginDate)
    ];

onTap: () {
  _sharedPrefsStore.write(PrefsKeys.lastLogin, _lastLoginDate);
}

It works fine, I can see that it saved my data and I can used it. Here comes my problem. When user presses another listTile button it overrides last entry. So my lastLogin prefKey only displays last entry. How can I store multiple entries in my prefKey?

Body:
Assuming that _sharedPrefStore.write accepts a String as new value, you can do this:

// Get last login
String loginJsonString = _sharedPrefsStore.read(PrefsKeys.lastLogin);
final List loginJsonList = jsonDecode(loginJsonString) as List;
final List<LastLogin> lastLogins = loginJsonList
    .cast<Map<String, dynamic>>()
    .map(LastLogin.fromJson)
    .toList();

LastLogin? latestLogin;

if (lastLogins.isNotEmpty) {
  latestLogin = lastLogins.last;
}

// Add new login
LastLogin newLogin = LastLogin(fullName: 'fullname', loginDate: 'some date');
lastLogins.add(newLogin);
loginJsonString = jsonEncode(loginJsonList);
_sharedPrefsStore.write(PrefsKeys.lastLogin, loginJsonString);

You can modify the code above to suit your needs.


问:
Is it possible to show alert in `clickedButtonAtIndex` method of alertview
In delegate method ofUIalerview I am trying to show another alert after finishing the process on clicking button index. Is it possible to do so?  Also I want to call a method on button click of alert. How can I do that?

I am trying in this way. Is is correct?

```<code>- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(buttonIndex == 1)
    {
        inappPurchaseViewController  = [[InAppPurchaseViewController alloc] init];
        [inappPurchaseViewController Upgrade:nil];
        [inappPurchaseViewController release];

        UIAlertView *purchasedone = [[UIAlertView alloc] initWithTitle:@"Enable Ads" message:@"You can Enable Ads from Settings Option" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [purchasedone show];
        [purchasedone release];
    }
}
</code>```

答:
You want to use tags for your UIAlertViews

Assigning tags

```<code>UIAlertView *firstAlert = [[UIAlertView alloc] initWithTitle:@"Do something first" message:@"This is the first UIAlertView" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[firstAlert setTag: 0];
[firstAlert show];
[firstAlert release];
</code>```

Handling those tags

```<code>- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (alertView.tag)
    {
        case 0: /* firstAlert */
        {
            if(buttonIndex == 1)
            {
                inappPurchaseViewController  = [[InAppPurchaseViewController alloc] init];
                [inappPurchaseViewController Upgrade:nil];
                [inappPurchaseViewController release];

                UIAlertView *purchaseDone = [[UIAlertView alloc] initWithTitle:@"Enable Ads" message:@"You can Enable Ads from Settings Option" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
                [purchaseDone setTag: 1];
                [purchaseDone show];
                [purchaseDone release];
            }
        }
            break;
        case 1: /* purchaseDone */
        {
            /*  purchaseDone uialertview was triggered, handle it here.   */
        }
            break;
    }
}
</code>```

Body:
In delegate method ofUIalerview I am trying to show another alert after finishing the process on clicking button index. Is it possible to do so?  Also I want to call a method on button click of alert. How can I do that?

I am trying in this way. Is is correct?

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(buttonIndex == 1)
    {
        inappPurchaseViewController  = [[InAppPurchaseViewController alloc] init];
        [inappPurchaseViewController Upgrade:nil];
        [inappPurchaseViewController release];

        UIAlertView *purchasedone = [[UIAlertView alloc] initWithTitle:@"Enable Ads" message:@"You can Enable Ads from Settings Option" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [purchasedone show];
        [purchasedone release];
    }
}

Body:
You want to use tags for your UIAlertViews

Assigning tags

UIAlertView *firstAlert = [[UIAlertView alloc] initWithTitle:@"Do something first" message:@"This is the first UIAlertView" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[firstAlert setTag: 0];
[firstAlert show];
[firstAlert release];

Handling those tags

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (alertView.tag)
    {
        case 0: /* firstAlert */
        {
            if(buttonIndex == 1)
            {
                inappPurchaseViewController  = [[InAppPurchaseViewController alloc] init];
                [inappPurchaseViewController Upgrade:nil];
                [inappPurchaseViewController release];

                UIAlertView *purchaseDone = [[UIAlertView alloc] initWithTitle:@"Enable Ads" message:@"You can Enable Ads from Settings Option" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
                [purchaseDone setTag: 1];
                [purchaseDone show];
                [purchaseDone release];
            }
        }
            break;
        case 1: /* purchaseDone */
        {
            /*  purchaseDone uialertview was triggered, handle it here.   */
        }
            break;
    }
}


问:
How to change between iframes in Selenium and Python
I was trying to understand how to change between iframes in selenium webdriver, but I could not figure it out.
In the image ahead, is the iframe that I want to switch to:

Snapshot:

答:
```<code> //iframe[@class='viewer pbi-frame']
</code>```

Should be a simple xpath using driver.switch_to.frame()

Or

```<code> //iframe[@title='Power BI Report Viewer']
</code>```

Body:
 //iframe[@class='viewer pbi-frame']

Should be a simple xpath using driver.switch_to.frame()

Or

 //iframe[@title='Power BI Report Viewer']


问:
string functions don't work on {{ run_id }} in Airflow
I have a DAG containing;

```<code>run_id = "{{ run_id }}"
session_id = str(run_id).replace(":","-").replace("+","-")
</code>```

and when I run the dag and just print the session_id i get:

```<code>manual__2021-05-07T08:28:31.651045+00:00
</code>```

so obviously replace functions don't work.

When I execute code like this:

```<code>run_id = "manual__2021-05-07T08:28:31.651045+00:00"
session_id = str(run_id).replace(":","-").replace("+","-")
</code>```

it works and returns

```<code>manual__2021-05-07T08-28-31.651045-00-00
</code>```

Why it doesn't work with {{ run_id }} ?
I'm stuck. Any hint?

Airflow 2.0

Regards
Pawel

答:
The jinja template is running when the task is run, not when the script is run. You need to add user_defined_macros to your DAG. It will be something like this:

```<code>def run_id_format(run_id):
   return str(run_id).replace(":","-").replace("+","-")

user_defined_macros={
   "run_id_format":run_id_format,
}
dag=DAG(
   dag_id="test",
   user_defined_macros=user_defined_macros
)

task=BashOperator(
   task_id="task_test",
   bash_command="echo {{ user_defined_macros(run_id) }}",
   dag=dag
)

task
</code>```

Or, you can use provide_context if you use PythonOperator.

Body:
I have a DAG containing;

run_id = "{{ run_id }}"
session_id = str(run_id).replace(":","-").replace("+","-")

and when I run the dag and just print the session_id i get:

manual__2021-05-07T08:28:31.651045+00:00

so obviously replace functions don't work.

When I execute code like this:

run_id = "manual__2021-05-07T08:28:31.651045+00:00"
session_id = str(run_id).replace(":","-").replace("+","-")

it works and returns

manual__2021-05-07T08-28-31.651045-00-00

Why it doesn't work with {{ run_id }} ?
I'm stuck. Any hint?

Airflow 2.0

Regards
Pawel

Body:
The jinja template is running when the task is run, not when the script is run. You need to add user_defined_macros to your DAG. It will be something like this:

def run_id_format(run_id):
   return str(run_id).replace(":","-").replace("+","-")

user_defined_macros={
   "run_id_format":run_id_format,
}
dag=DAG(
   dag_id="test",
   user_defined_macros=user_defined_macros
)

task=BashOperator(
   task_id="task_test",
   bash_command="echo {{ user_defined_macros(run_id) }}",
   dag=dag
)

task

Or, you can use provide_context if you use PythonOperator.


问:
How can I use auth0 getSession() from nextjs middleware function, or is there some other way to get user particulars via middleware
I have this code in /pages/api/_middleware.js:

```<code>import { getSession } from '@auth0/nextjs-auth0'

export default async function middleware(req, ev) {
    const session = await getSession(req)
    console.log(session)
    return NextResponse.next()
}
</code>```

Whenever I run an API call that hits this I get this message:

error - node_modules@auth0\nextjs-auth0\dist\index.browser.js?b875 (11:0) @ Object.getSession
Error: The getSession method can only be used from the server side

答:
I'm not sure it's possible with the @auth0/nextjs-auth0 lib, but I'm lazily just checking if the appSession cookie is in storage like so:

```<code>import type { NextRequest } from 'next/server'

export function middleware(req: NextRequest) {
  if (req.nextUrl.pathname === '/' && req.cookies.appSession) {
    return Response.redirect('/app')
  }
  if (req.nextUrl.pathname === '/app' && !req.cookies.appSession) {
    return Response.redirect('/')
  }
}
</code>```

Body:
I have this code in /pages/api/_middleware.js:

import { getSession } from '@auth0/nextjs-auth0'

export default async function middleware(req, ev) {
    const session = await getSession(req)
    console.log(session)
    return NextResponse.next()
}

Whenever I run an API call that hits this I get this message:

error - node_modules@auth0\nextjs-auth0\dist\index.browser.js?b875 (11:0) @ Object.getSession
Error: The getSession method can only be used from the server side

Body:
I'm not sure it's possible with the @auth0/nextjs-auth0 lib, but I'm lazily just checking if the appSession cookie is in storage like so:

import type { NextRequest } from 'next/server'

export function middleware(req: NextRequest) {
  if (req.nextUrl.pathname === '/' && req.cookies.appSession) {
    return Response.redirect('/app')
  }
  if (req.nextUrl.pathname === '/app' && !req.cookies.appSession) {
    return Response.redirect('/')
  }
}


问:
I didnt get the desired result with wampserver in the <? syntax.Why?
I am using wamp server 2.0 on windows XP with PHP version 5.2.5 when I am using the following code

```<code><?
  echo "hai";
?>
</code>```

I am not getting the output. But when I am using

```<code><?php
  echo "hai";
?>
</code>```

Got the result.If I am using the first one in Linux server I got the output.One of my large project like the first one in all php pages.I want to configure with wamp.SO if first coding needs to work what can I do?

答:
My first guess is your php.ini isn't configured for this. The parameter short_open_tag is responsible for it.

Edit your php.ini, search the following parameter and activate it (or add it when its missing there):

```<code>short_open_tag = On
</code>```

More details are in the php-manual.

Body:
I am using wamp server 2.0 on windows XP with PHP version 5.2.5 when I am using the following code

<?
  echo "hai";
?>

I am not getting the output. But when I am using

<?php
  echo "hai";
?>

Got the result.If I am using the first one in Linux server I got the output.One of my large project like the first one in all php pages.I want to configure with wamp.SO if first coding needs to work what can I do?

Body:
My first guess is your php.ini isn't configured for this. The parameter short_open_tag is responsible for it.

Edit your php.ini, search the following parameter and activate it (or add it when its missing there):

short_open_tag = On

More details are in the php-manual.


问:
Dataframe column match with list and create new columns
I have data frame DF column A , check how much List a=["enter", 'Enter', 'Click', 'click'] available in data frame column,
and create another column B  on the same names. i want to my data frame to look like this :

```<code>DF=       A
       "enter Username"
       "click UserBox"
       "Enter Password"
       "Click login"
       "click checkbox"
       "Enter Phonenumber"
</code>```

OUTPUT :

```<code>DF=       A                         B
       "enter Username"             enter
       "click UserBox"              click
       "Enter Password"             Enter
       "Click login"                Click
       "click checkbox"             click
       "Enter Phonenumber"          Enter
</code>```

答:
Use Series.apply with set intersection using operator &:

```<code>In [1003]: s = set(a)
In [994]: df['B'] = df['A'].apply(lambda x: (set(x.split()) & s).pop() if len((set(x.split()) & s)) > 0 else '')

In [995]: df
Out[995]:
                   A      B
0     enter Username  enter
1      click UserBox  click
2     Enter Password  Enter
3        Click login  Click
4     click checkbox  click
5  Enter Phonenumber  Enter
</code>```

Body:
I have data frame DF column A , check how much List a=["enter", 'Enter', 'Click', 'click'] available in data frame column,
and create another column B  on the same names. i want to my data frame to look like this :

DF=       A
       "enter Username"
       "click UserBox"
       "Enter Password"
       "Click login"
       "click checkbox"
       "Enter Phonenumber"

OUTPUT :

DF=       A                         B
       "enter Username"             enter
       "click UserBox"              click
       "Enter Password"             Enter
       "Click login"                Click
       "click checkbox"             click
       "Enter Phonenumber"          Enter

Body:
Use Series.apply with set intersection using operator &:

In [1003]: s = set(a)
In [994]: df['B'] = df['A'].apply(lambda x: (set(x.split()) & s).pop() if len((set(x.split()) & s)) > 0 else '')

In [995]: df
Out[995]:
                   A      B
0     enter Username  enter
1      click UserBox  click
2     Enter Password  Enter
3        Click login  Click
4     click checkbox  click
5  Enter Phonenumber  Enter


问:
Correct async function export in node.js
I had my custom module with following code:

```<code>module.exports.PrintNearestStore = async function PrintNearestStore(session, lat, lon) {
...
}
</code>```

It worked fine if call the function outside my module, however if I called inside I got error while running:

(node:24372) UnhandledPromiseRejectionWarning: Unhandled promise
  rejection (rejection id: 1): ReferenceError: PrintNearestStore is not
  defined

When I changed syntax to:

```<code>module.exports.PrintNearestStore = PrintNearestStore;

var PrintNearestStore = async function(session, lat, lon) {

}
</code>```

It started to work fine inside module, but fails outside the module - I got error:

(node:32422) UnhandledPromiseRejectionWarning: Unhandled promise
  rejection (rejection id: 1): TypeError: mymodule.PrintNearestStore is
  not a function

So I've changed code to:

```<code>module.exports.PrintNearestStore = async function(session, lat, lon) {
    await PrintNearestStore(session, lat, lon);
}

var PrintNearestStore = async function(session, lat, lon) {
...
}
</code>```

And now it works in all cases: inside and outside. However want to understand semantics and if there is more beautiful and shorter way to write it? How to correctly  define and use async function both: inside and outside (exports) module?

答:
an alternative would be to export like this.
// foo.js

export async function foo(){
 console.log('I am greatest of all.'); // for the person who reads it, just say it.
}
```
<p>then use it in other scripts like</p>
<pre class="lang-js prettyprint-override"><code>import { foo } from './foo'

foo();
</code>```

Body:
I had my custom module with following code:

module.exports.PrintNearestStore = async function PrintNearestStore(session, lat, lon) {
...
}

It worked fine if call the function outside my module, however if I called inside I got error while running:

(node:24372) UnhandledPromiseRejectionWarning: Unhandled promise
  rejection (rejection id: 1): ReferenceError: PrintNearestStore is not
  defined

When I changed syntax to:

module.exports.PrintNearestStore = PrintNearestStore;

var PrintNearestStore = async function(session, lat, lon) {

}

It started to work fine inside module, but fails outside the module - I got error:

(node:32422) UnhandledPromiseRejectionWarning: Unhandled promise
  rejection (rejection id: 1): TypeError: mymodule.PrintNearestStore is
  not a function

So I've changed code to:

module.exports.PrintNearestStore = async function(session, lat, lon) {
    await PrintNearestStore(session, lat, lon);
}

var PrintNearestStore = async function(session, lat, lon) {
...
}

And now it works in all cases: inside and outside. However want to understand semantics and if there is more beautiful and shorter way to write it? How to correctly  define and use async function both: inside and outside (exports) module?

Body:
an alternative would be to export like this.
// foo.js

export async function foo(){
 console.log('I am greatest of all.'); // for the person who reads it, just say it.
}

then use it in other scripts like

import { foo } from './foo'

foo();


答:
This error occurred because you used the required keyword in CreateProfile.dart.
If you want to pass a null value as the key you can change the constructor like this :

  CreateProfile({Key? key}) : super(key: key);
```

Body:
I want to call CreateProfile() in my main.dart.. but it gives me an  error.. the below image showing the error in main.dart and I have included my createprofile.dart code for you to refer.

The argument type 'Null' can't be assigned to the parameter type
'Key'.

starting code of CreateProfile.dart

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:convert';
import 'package:http/http.dart' ;

class CreateProfile extends StatefulWidget {
  CreateProfile({required Key key}) : super(key: key);

  @override
  _CreateProfileState createState() => _CreateProfileState();
}

class _CreateProfileState extends State<CreateProfile> {

  bool circular = false;
  PickedFile? _imageFile;
  final ImagePicker _picker = ImagePicker();

  final _globalkey = GlobalKey<FormState>();

  TextEditingController _name = TextEditingController();
  TextEditingController _profession = TextEditingController();
  TextEditingController _dob = TextEditingController();
  TextEditingController _title = TextEditingController();
  TextEditingController _about = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Form(
        key: _globalkey,
        child: ListView(
          padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 30),
          children: <Widget>[
            imageProfile(),
            SizedBox(
              height: 20,
            ),


问:
How to keep system alive in case of inactivity?
Is there any way in Python to keep it system active all the time?</p>

答:
one way worked for me on windows

Python3 Windows

this will keep your windows awake and prevent it from locking/hibernating

```<code>#Devil
import ctypes
import sys

#use this to reset the status
def display_reset():
    ctypes.windll.kernel32.SetThreadExecutionState(0x80000000)
    sys.exit(0)

def display_on():
    print("Always On")
    ctypes.windll.kernel32.SetThreadExecutionState(0x80000002)

display_on()
</code>```

Body:
one way worked for me on windows

Python3 Windows

this will keep your windows awake and prevent it from locking/hibernating

#Devil
import ctypes
import sys

#use this to reset the status
def display_reset():
    ctypes.windll.kernel32.SetThreadExecutionState(0x80000000)
    sys.exit(0)

def display_on():
    print("Always On")
    ctypes.windll.kernel32.SetThreadExecutionState(0x80000002)

display_on()


问:
R does not recognize NA as missing data when I am importing a csv file
In my first R script, I am creating a large dataset and exporting as a csv file.

In my second R script, I am importing by every SampleID to analyze the data.

The problem is that R is not recognizing NA as missing. How can I import the csv file into R so that my data are recognized as numeric?

Thank you.

```<code>### R Script One
SampleID <- c(1,1, 2,2, 3,3, 4,4)
x1 <- runif(8) * 10
x2 <- runif(8) * 10

my_df<- as.data.frame(cbind(SampleID, x1, x2))

my_df[2,3] <- NA
my_df[5,2] <- NA

write.csv(my_df, "my_df.csv", row.names = FALSE) #write out csv file from first R script

### R Script Two
library(sqldf)

j <- 3
select <- paste0("select * from file where SampleID=",j,"")
my_df2 <- read.csv.sql("my_df.csv", select) #Import only certain records into second R script

mode(my_df2$x1)
</code>```

答:
After reading in the csv file, you can use readr::type_convert() to convert the column types.

```<code>library(read)

my_df2 <- read.csv.sql("./Downloads/my_df.csv", select) %>% readr::type_convert()

mode(my_df2$x1)
[1] "numeric"
</code>```

Body:
In my first R script, I am creating a large dataset and exporting as a csv file.

In my second R script, I am importing by every SampleID to analyze the data.

The problem is that R is not recognizing NA as missing. How can I import the csv file into R so that my data are recognized as numeric?

Thank you.

### R Script One
SampleID <- c(1,1, 2,2, 3,3, 4,4)
x1 <- runif(8) * 10
x2 <- runif(8) * 10

my_df<- as.data.frame(cbind(SampleID, x1, x2))

my_df[2,3] <- NA
my_df[5,2] <- NA

write.csv(my_df, "my_df.csv", row.names = FALSE) #write out csv file from first R script

### R Script Two
library(sqldf)

j <- 3
select <- paste0("select * from file where SampleID=",j,"")
my_df2 <- read.csv.sql("my_df.csv", select) #Import only certain records into second R script

mode(my_df2$x1)

Body:
After reading in the csv file, you can use readr::type_convert() to convert the column types.

library(read)

my_df2 <- read.csv.sql("./Downloads/my_df.csv", select) %>% readr::type_convert()

mode(my_df2$x1)
[1] "numeric"


问:
Pegman has disappeared from my map
For as long as I can remember, the street view pegman has appeared on my map.  Today, I noticed that he doesn't appear (although if you know where to mouse over to grab him, you can still get a streetview happening).  My zoom control has similarly disappeared (but is still there if you know where to mouse for it) but not on mobile devices where it seems to display just fine.

My first guess is that this is a bug in the Maps API that's been introduced recently.  But specifying v=3.4 in the URL for the API doesn't correct the issue.

Am I doing something wrong?  If not, is there a workaround?

Here's how I create the map:

```<code><script type="text/javascript">
var lat=<?php echo $lat; ?>;
var lon=<?php echo $lon; ?>;
var initialZoom=<?php echo $initialZoom; ?>;
var mapTypeId = 'Custom Map';
var mapStyle = [{featureType:"administrative", elementType:"all", stylers:[{hue:"#dae6c3"},{saturation:22},{lightness:-5}]},
                {featureType:"landscape", elementType:"all", stylers:[{hue:"#dae6c3"},{saturation:16},{lightness:-7}]},
                {featureType:"road", elementType:"geometry", stylers:[{hue:"#ffffff"},{saturation:-100},{lightness:100}]}];
var styledMap = new google.maps.StyledMapType(mapStyle);

var mapType = new google.maps.ImageMapType({
    tileSize: new google.maps.Size(256,256),
    getTileUrl: function(coord,zoom) {
        return "img/tiles/"+zoom+"/"+coord.x+"/"+coord.y+".png";
    }
});
var map = new google.maps.Map(document.getElementById("map_canvas"),
        {center:new google.maps.LatLng(lat,lon),
         mapTypeId:google.maps.MapTypeId.ROADMAP,
         zoom:initialZoom,
         mapTypeControl:false});
map.overlayMapTypes.insertAt(0, mapType);

map.mapTypes.set(mapTypeId, styledMap);
map.setMapTypeId(mapTypeId);
</script>
</code>```

答:
I had recently added this CSS rule which was causing the problem:

```<code>img {
    max-width: 100%;
}
</code>```

Removing that rule fixed the problem.

Title: Pegman has disappeared from my map

Body:
I had recently added this CSS rule which was causing the problem:

img {
    max-width: 100%;
}

Removing that rule fixed the problem.


问:
partial search and lowercase search in nodejs
I'm trying to implement multiple search functionality such as userName and userId with separate input for userName and userId. If I give userName as "Dave Steve" or "dave steve" or "Dave" or "steve" or "dav" and click on the search button I should get the result But When I give "Dave steve" it working fine but not with other case How do I implement it ?

Json data:

```<code>let logData={
"dataLog":
[
    {
        "userId":"1",
        "userName":"Dave Steve",
    },
    {
        "userId":"2",
        "userName":"John Doe",
    }
],
}
</code>```

Here is my code

```<code>app.get('/getData', (req, res) => {
  let accessData= logData.dataLog;
  let userName = req.query.userName;
  let userId = req.query.userId;
    console.log(userName, userId)
    let filterData = accessData.filter((data) => {
      return (userId === undefined || data.userId === userId) &&
        (userName === undefined || userName === userNameData)
    })
    console.log(filterData)
    const response = {
      header: getSuccessHeader,
      body: filterData
    };
    res.status(200);
    res.send(response);
});
</code>```

答:
It's because Dave Steve isn't really equal to Dave steve when you are comparing strings using ===. It's case sensitive.

You can use .toLowerCase() to both userName and userNameData when comparing the two.

So your comparison would look like:

```<code>userName.toLowerCase() === userNameData.toLowerCase()
</code>```

EDIT:

I completely glossed over that you want partial string comparison. So you should instead use .includes(string) instead.

```<code>userName.toLowerCase().includes(userNameData.toLowerCase())
</code>```

Body:
I'm trying to implement multiple search functionality such as userName and userId with separate input for userName and userId. If I give userName as "Dave Steve" or "dave steve" or "Dave" or "steve" or "dav" and click on the search button I should get the result But When I give "Dave steve" it working fine but not with other case How do I implement it ?

Json data:

let logData={
"dataLog":
[
    {
        "userId":"1",
        "userName":"Dave Steve",
    },
    {
        "userId":"2",
        "userName":"John Doe",
    }
],
}

Here is my code

app.get('/getData', (req, res) => {
  let accessData= logData.dataLog;
  let userName = req.query.userName;
  let userId = req.query.userId;
    console.log(userName, userId)
    let filterData = accessData.filter((data) => {
      return (userId === undefined || data.userId === userId) &&
        (userName === undefined || userName === userNameData)
    })
    console.log(filterData)
    const response = {
      header: getSuccessHeader,
      body: filterData
    };
    res.status(200);
    res.send(response);
});

Body:
It's because Dave Steve isn't really equal to Dave steve when you are comparing strings using ===. It's case sensitive.

You can use .toLowerCase() to both userName and userNameData when comparing the two.

So your comparison would look like:

userName.toLowerCase() === userNameData.toLowerCase()

EDIT:

I completely glossed over that you want partial string comparison. So you should instead use .includes(string) instead.

userName.toLowerCase().includes(userNameData.toLowerCase())


问:
Extracting matrix values from indices using Python
I want to access the elements of matrix A using T to yield a new matrix, Anew with the elements of A using Python. Is there a way to do it?

```<code>import numpy as np
A=np.array([[1,2,3],[4,5,6],[7,8,9]])
T=array([[0, 2],
       [1, 1],
       [1, 0]],dtype=int64)
</code>```

Desired output:

```<code>Anew=array([[3],
            [5],
           [4]])
</code>```

答:
Use advanced indexing -- the 1st column of T as row index, 2nd column of T as column index:</p>
```<code>A[T[:,0], T[:,1]]
# array([3, 5, 4])
</code>```

Body:
I want to access the elements of matrix A using T to yield a new matrix, Anew with the elements of A using Python. Is there a way to do it?

import numpy as np
A=np.array([[1,2,3],[4,5,6],[7,8,9]])
T=array([[0, 2],
       [1, 1],
       [1, 0]],dtype=int64)

Desired output:

Anew=array([[3],
            [5],
           [4]])

Body:
Use advanced indexing -- the 1st column of T as row index, 2nd column of T as column index:

A[T[:,0], T[:,1]]
# array([3, 5, 4])


问:
update value in google sheet with if condition in another column using python
I have a similar data as below in google sheet.
I want to update the pageId for pagename "abc".

I'm able to update manually passing B3 sheet.update('B3','updated_value')
but How should I get B3 by adding a if condition where pagename=abc in python code.

Need help.

答:
If your provided script in your comment is used, how about the following modification?

Modified script:

# Your provided script in your comment.
records_data = sheet_instance.get_all_records()
test = sheet_instance.col_values(1)
rownum = test.index('abc') + 1
print(rownum)
row = sheet_instance.row_values(rownum)
print(row)

sheet_instance.update_cell(rownum, 2, 'Updated') # Added
```

In this case, rownum can be directly used.

Reference:

Updating Cells

Body:
If your provided script in your comment is used, how about the following modification?

Modified script:

# Your provided script in your comment.
records_data = sheet_instance.get_all_records()
test = sheet_instance.col_values(1)
rownum = test.index('abc') + 1
print(rownum)
row = sheet_instance.row_values(rownum)
print(row)

sheet_instance.update_cell(rownum, 2, 'Updated') # Added

In this case, rownum can be directly used.

Reference:

Updating Cells


问:
Create a child resource by ARM connector in Logic App
How can you create a child resource (e.g. container for Blob Storage, or consumer group for Eventhub) using Logic App?

To create a resource with the ARM connector in Logic App, you need to specify provider and short resource id which are used to construct the path to the new service. However, they do not correspond to the "type" and "name" parameters from ARM template (which would be in the example "Microsoft.Eventhub/namespaces" and "vvtesteventhub").

```<code>"inputs": {
    "body": {...},
    "host": {
        "connection": {
            "name": "@parameters('$connections')['arm']['connectionId']"
        }
    },
    "method": "put",
    "path": "/subscriptions/@{variables('subscriptionId')}/resourcegroups/@{variables('resourceGroup')}/providers/Microsoft.EventHub/namespaces/vvtesteventhub",
    "queries": {
        "x-ms-api-version": "2021-06-01-preview"
    }
}
</code>```

For a child resource, it is necessary to somehow construct the full path including the parent resource name. However, I am not able to construct it even when editing the directly through the code view (see below). The run fails with error message "Resource not found", despite the fact that it includes the correct path to the existing eventhub where I want to create the consumer group.

```<code>{
    "inputs": {
        "host": {
            "connection": {
                "name": "@parameters('$connections')['arm']['connectionId']"
            }
        },
        "method": "put",
        "path": "/subscriptions/@{variables('subscriptionId')}/resourcegroups/@{variables('resourceGroup')}/providers/Microsoft.EventHub/namespaces/eventhubs/@{variables('eventhubNamespacesName')}/@{variables('eventhubName')}/consumergroups/@{variables('platformName')}",
        "queries": {
            "x-ms-api-version": "2021-06-01-preview"
        }
    }
}
</code>```

答:
We have tested this in our local environment it is working fine, Below statements are based on the analysis.

In our local environment, we have created an event hub Namespace & a logic app.

Using logic app Azure resource Manager connector actions Create or Update a Resource we are able to create EventHub & followed it by a consumer group in it.

Here is the logic app :

Here is the code view of the logic app:

{
    "definition": {
        "$schema": "https://schema.management.azure.com/providers/Microsoft.Logic/schemas/2016-06-01/workflowdefinition.json#",
        "actions": {
            "Compose": {
                "inputs": "Microsoft.EventHub/namespaces",
                "runAfter": {},
                "type": "Compose"
            },
            "Create_a_ConsumerGroup_to_existing_EventHub": {
                "inputs": {
                    "body": {
                        "location": "westus"
                    },
                    "host": {
                        "connection": {
                            "name": "@parameters('$connections')['arm']['connectionId']"
                        }
                    },
                    "method": "put",
                    "path": "/subscriptions/@{encodeURIComponent('')}/resourcegroups/@{encodeURIComponent('<rgName>')}/providers/@{encodeURIComponent(outputs('Compose'))}/@{encodeURIComponent('/<EventHubNamespacesName>/eventhubs/<EventHubName>/consumergroups/<ConsumerGroupName>')}",
                    "queries": {
                        "x-ms-api-version": "2021-11-01"
                    }
                },
                "runAfter": {
                    "Creates_a_EventHub_to_existing_EventHubNamespaces_": [
                        "Succeeded"
                    ]
                },
                "type": "ApiConnection"
            },
            "Creates_a_EventHub_to_existing_EventHubNamespaces_": {
                "inputs": {
                    "body": {
                        "location": "westus"
                    },
                    "host": {
                        "connection": {
                            "name": "@parameters('$connections')['arm']['connectionId']"
                        }
                    },
                    "method": "put",
                    "path": "/subscriptions/@{encodeURIComponent('')}/resourcegroups/@{encodeURIComponent('<rgName>')}/providers/@{encodeURIComponent(outputs('Compose'))}/@{encodeURIComponent('/<EventHubNamespacesName>/eventhubs/<EventHubName>')}",
                    "queries": {
                        "x-ms-api-version": "2021-11-01"
                    }
                },
                "runAfter": {
                    "Compose": [
                        "Succeeded"
                    ]
                },
                "type": "ApiConnection"
            }
        },
        "contentVersion": "1.0.0.0",
        "outputs": {},
        "parameters": {
            "$connections": {
                "defaultValue": {},
                "type": "Object"
            }
        },
        "triggers": {
            "Recurrence": {
                "recurrence": {
                    "frequency": "Hour",
                    "interval": 3
                },
                "type": "Recurrence"
            }
        }
    },
    "parameters": {
        "$connections": {
            "value": {
                "arm": {
                    "connectionId": "/subscriptions//resourceGroups/<rgName>/providers/Microsoft.Web/connections/arm",
                    "connectionName": "arm",
                    "id": "/subscriptions//providers/Microsoft.Web/locations/eastus/managedApis/arm"
                }
            }
        }
    }
}
```

Here is the sample output for reference:

Note:

In order to create a consumer group to EventHub you need to have an existing EventHub or you Need to create a New Event Hub.

Body:
How can you create a child resource (e.g. container for Blob Storage, or consumer group for Eventhub) using Logic App?

To create a resource with the ARM connector in Logic App, you need to specify provider and short resource id which are used to construct the path to the new service. However, they do not correspond to the "type" and "name" parameters from ARM template (which would be in the example "Microsoft.Eventhub/namespaces" and "vvtesteventhub").

"inputs": {
    "body": {...},
    "host": {
        "connection": {
            "name": "@parameters('$connections')['arm']['connectionId']"
        }
    },
    "method": "put",
    "path": "/subscriptions/@{variables('subscriptionId')}/resourcegroups/@{variables('resourceGroup')}/providers/Microsoft.EventHub/namespaces/vvtesteventhub",
    "queries": {
        "x-ms-api-version": "2021-06-01-preview"
    }
}

For a child resource, it is necessary to somehow construct the full path including the parent resource name. However, I am not able to construct it even when editing the directly through the code view (see below). The run fails with error message "Resource not found", despite the fact that it includes the correct path to the existing eventhub where I want to create the consumer group.

{
    "inputs": {
        "host": {
            "connection": {
                "name": "@parameters('$connections')['arm']['connectionId']"
            }
        },
        "method": "put",
        "path": "/subscriptions/@{variables('subscriptionId')}/resourcegroups/@{variables('resourceGroup')}/providers/Microsoft.EventHub/namespaces/eventhubs/@{variables('eventhubNamespacesName')}/@{variables('eventhubName')}/consumergroups/@{variables('platformName')}",
        "queries": {
            "x-ms-api-version": "2021-06-01-preview"
        }
    }
}

Body:
We have tested this in our local environment it is working fine, Below statements are based on the analysis.

In our local environment, we have created an event hub Namespace & a logic app.

Using logic app Azure resource Manager connector actions Create or Update a Resource we are able to create EventHub & followed it by a consumer group in it.

Here is the logic app :

Here is the code view of the logic app:

{
    "definition": {
        "$schema": "https://schema.management.azure.com/providers/Microsoft.Logic/schemas/2016-06-01/workflowdefinition.json#",
        "actions": {
            "Compose": {
                "inputs": "Microsoft.EventHub/namespaces",
                "runAfter": {},
                "type": "Compose"
            },
            "Create_a_ConsumerGroup_to_existing_EventHub": {
                "inputs": {
                    "body": {
                        "location": "westus"
                    },
                    "host": {
                        "connection": {
                            "name": "@parameters('$connections')['arm']['connectionId']"
                        }
                    },
                    "method": "put",
                    "path": "/subscriptions/@{encodeURIComponent('<sub-id>')}/resourcegroups/@{encodeURIComponent('<rgName>')}/providers/@{encodeURIComponent(outputs('Compose'))}/@{encodeURIComponent('/<EventHubNamespacesName>/eventhubs/<EventHubName>/consumergroups/<ConsumerGroupName>')}",
                    "queries": {
                        "x-ms-api-version": "2021-11-01"
                    }
                },
                "runAfter": {
                    "Creates_a_EventHub_to_existing_EventHubNamespaces_": [
                        "Succeeded"
                    ]
                },
                "type": "ApiConnection"
            },
            "Creates_a_EventHub_to_existing_EventHubNamespaces_": {
                "inputs": {
                    "body": {
                        "location": "westus"
                    },
                    "host": {
                        "connection": {
                            "name": "@parameters('$connections')['arm']['connectionId']"
                        }
                    },
                    "method": "put",
                    "path": "/subscriptions/@{encodeURIComponent('<sub-id>')}/resourcegroups/@{encodeURIComponent('<rgName>')}/providers/@{encodeURIComponent(outputs('Compose'))}/@{encodeURIComponent('/<EventHubNamespacesName>/eventhubs/<EventHubName>')}",
                    "queries": {
                        "x-ms-api-version": "2021-11-01"
                    }
                },
                "runAfter": {
                    "Compose": [
                        "Succeeded"
                    ]
                },
                "type": "ApiConnection"
            }
        },
        "contentVersion": "1.0.0.0",
        "outputs": {},
        "parameters": {
            "$connections": {
                "defaultValue": {},
                "type": "Object"
            }
        },
        "triggers": {
            "Recurrence": {
                "recurrence": {
                    "frequency": "Hour",
                    "interval": 3
                },
                "type": "Recurrence"
            }
        }
    },
    "parameters": {
        "$connections": {
            "value": {
                "arm": {
                    "connectionId": "/subscriptions/<sub-id>/resourceGroups/<rgName>/providers/Microsoft.Web/connections/arm",
                    "connectionName": "arm",
                    "id": "/subscriptions/<sub-id>/providers/Microsoft.Web/locations/eastus/managedApis/arm"
                }
            }
        }
    }
}

Here is the sample output for reference:

Note:

In order to create a consumer group to EventHub you need to have an existing EventHub or you Need to create a New Event Hub.


答:
I'm assuming that the arrays are numpy arrays, in Your case this can be solved with:

A[T.T[0], T.T[1]]

Title: Extracting matrix values from indices using Python


问:
How to pass key as a value through a database model class in Kotlin
This is what my database looks like:

Realtime Database Layout

And this is my model class:

```<code>class Registrations {
private var userEmail:String =""
private var verified:Boolean = false

constructor()
constructor(userEmail:String, verified:Boolean){
    this.userEmail = userEmail
    this.verified = verified

}

fun getUserEmail():String{
    return userEmail
}

fun setUserEmail(userEmail: String){
    this.userEmail = userEmail
}

fun getVerified():Boolean{
    return verified
}

fun setVerified(verified: Boolean){
    this.verified = verified
}
}
</code>```

I am using a RecyclerAdapter to get the data and my code to do that is:

```<code>private fun getRegistrations() {
    FirebaseDatabase.getInstance().reference.child("Registrations").addListenerForSingleValueEvent(object : ValueEventListener {
        override fun onDataChange(dataSnapshot: DataSnapshot) {
            if (dataSnapshot.exists()) {
                itemList!!.clear()
                for (snapshot in dataSnapshot.children) {
                    Log.d("ITEM", snapshot.toString())

                    val item = snapshot.getValue(Registrations::class.java)

                    itemList!!.add(item!!)
                }
                registrationsAdapter!!.notifyDataSetChanged()
            }
        }

        override fun onCancelled(error: DatabaseError) {
            TODO("Not yet implemented")
        }
    })
}

}
</code>```

Now as you can see in the database image how do I pass the key value(email of the user) as a value to the model class?

I have tried creating an object but I am doing something wrong/don't know how to, any help is appreciated.

Also, this app is in production so I can't change the data to have email as a value in firebase now.

Any help is appreciated.

答:
It's always recommended that the fields in the class must match the ones in the database. So if a node in the database contains two fields, verified and activationCode, then the class should contain the same.

this app is in production so I can't change the data to have email as a value in fFirebase now.

So if you cannot add the email as a value, which I doubt as it's a really simple update operation, then you can only read the key and use the setter to add in your object like this:

```<code>val item = snapshot.getValue(Registrations::class.java)
val userEmail = snapshot.getKey()
item.setUserEmail(userEmail)
itemList!!.add(item!!)
</code>```

Body:
This is what my database looks like:

Realtime Database Layout

And this is my model class:

class Registrations {
private var userEmail:String =""
private var verified:Boolean = false

constructor()
constructor(userEmail:String, verified:Boolean){
    this.userEmail = userEmail
    this.verified = verified

}

fun getUserEmail():String{
    return userEmail
}

fun setUserEmail(userEmail: String){
    this.userEmail = userEmail
}

fun getVerified():Boolean{
    return verified
}

fun setVerified(verified: Boolean){
    this.verified = verified
}
}

I am using a RecyclerAdapter to get the data and my code to do that is:

private fun getRegistrations() {
    FirebaseDatabase.getInstance().reference.child("Registrations").addListenerForSingleValueEvent(object : ValueEventListener {
        override fun onDataChange(dataSnapshot: DataSnapshot) {
            if (dataSnapshot.exists()) {
                itemList!!.clear()
                for (snapshot in dataSnapshot.children) {
                    Log.d("ITEM", snapshot.toString())

                    val item = snapshot.getValue(Registrations::class.java)

                    itemList!!.add(item!!)
                }
                registrationsAdapter!!.notifyDataSetChanged()
            }
        }

        override fun onCancelled(error: DatabaseError) {
            TODO("Not yet implemented")
        }
    })
}

}

Now as you can see in the database image how do I pass the key value(email of the user) as a value to the model class?

I have tried creating an object but I am doing something wrong/don't know how to, any help is appreciated.

Also, this app is in production so I can't change the data to have email as a value in firebase now.

Any help is appreciated.

Body:
It's always recommended that the fields in the class must match the ones in the database. So if a node in the database contains two fields, verified and activationCode, then the class should contain the same.

this app is in production so I can't change the data to have email as a value in fFirebase now.

So if you cannot add the email as a value, which I doubt as it's a really simple update operation, then you can only read the key and use the setter to add in your object like this:

val item = snapshot.getValue(Registrations::class.java)
val userEmail = snapshot.getKey()
item.setUserEmail(userEmail)
itemList!!.add(item!!)