问:
Recyclerview not call any Adapter method: onCreateViewHolder, onBindViewHolder
Here are my codes for MyAdapter, ActivityMain, MinActivity, and User

```<code>public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {

   Context context;
   ArrayList<User> list;

   public MyAdapter(Context context, ArrayList<User> list) {
     this.context = context;
     this.list = list;
   }

   @NonNull
   @Override
   public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(context).inflate(R.layout.item, parent, false);
    return new MyViewHolder(v);
   }

   @Override
   public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {

     // here is the problem that I don't know how to fix][1]
     // I'm tryin to pass data from firebase to Recyclerview
     // error I'm getting here is:
     // [Cannot resolve method 'getFirstName' in 'User'
     // Cannot resolve method 'getLastName' in 'User'
     // Cannot resolve method 'getAge' in 'User']

         User user = list.get(position);
         holder.FirstName.setText(user.getFirstName());
         holder.LastName.setText(user.getLastName());
         holder.Age.setText(user.getAge());

    }

    @Override
    public int getItemCount() {
         return list.size();
    }

   public static class MyViewHolder extends RecyclerView.ViewHolder{

         TextView FirstName, LastName, Age;

          public MyViewHolder(@NonNull View itemView) {
             super(itemView);

              FirstName = itemView.findViewById(R.id.tvFirstName);
              LastName = itemView.findViewById(R.id.tvLastName);
              Age = itemView.findViewById(R.id.tvAge);

           }
        }

    }

</code>```

This is MainActivity code

```<code> public class MainActivity extends AppCompatActivity {

       RecyclerView recyclerView;
       DatabaseReference database;
       MyAdapter myAdapter;
       ArrayList<User> list;

       @Override
       protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_Main);

              recyclerView = findViewById(R.id.userList);
              database = FirebaseDatabase.getInstance().getReference("User");
              recyclerView.setHasFixedSize(true);

              recyclerView.setLayoutManager(new LinearLayoutManager(this));

              list = new ArrayList<>();
              myAdapter = new MyAdapter(this,list);

              recyclerView.setAdapter(myAdapter);

              database.addValueEventListener(new ValueEventListener() {
                        @Override
                        public void onDataChange(@NonNull DataSnapshot snapshot) {

                            for (DataSnapshot dataSnapshot : snapshot.getChildren()){

                                User user = dataSnapshot.getValue(User.class);
                                list.add(user);

                            }
                            myAdapter.notifyDataSetChanged();
                        }
                        @Override
                        public void onCancelled(@NonNull DatabaseError error) {
                        }
                    });
                }
            }
</code>```

This is User codes which I generated with getter

```<code>   public class User {

        String FirstName, LastName, Age;

        public String getFirstName() {
            return FirstName;
        }

        public String getLastName() {
            return LastName;
        }

        public String getAge() {
            return Age;
        }

        {

        }
 }

</code>```

This is my layout file

```<code> <?xml version="1.0" encoding="utf-8"?>
 <androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        app:cardElevation="8dp"
        app:cardCornerRadius="8dp"
        android:layout_margin="16dp">

                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="16dp"
                    android:orientation="vertical">

                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_vertical"
                        android:orientation="horizontal">

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text="First Name :"
                            android:textColor="@color/black"
                            android:textSize="26sp"
                            android:textStyle="bold"/>

                        <TextView
                            android:id="@+id/tvFirstName"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_marginLeft="8dp"
                            android:text="Arya"
                            android:textColor="@color/black"
                            android:textSize="20sp" />

                    </LinearLayout>

                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_vertical"
                        android:orientation="horizontal">

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text="@string/last_name"
                            android:textColor="@color/black"
                            android:textSize="26sp"
                            android:textStyle="bold"/>

                        <TextView
                            android:id="@+id/tvLastName"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_marginStart="8dp"
                            android:text="@string/stark"
                            android:textColor="@color/black"
                            android:textSize="20sp" />

                    </LinearLayout>

                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_vertical"
                        android:orientation="horizontal">

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text="@string/age"
                            android:textColor="@color/black"
                            android:textSize="26sp"
                            android:textStyle="bold"/>

                        <TextView
                            android:id="@+id/tvAge"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_marginLeft="8dp"
                            android:text="18"
                            android:textColor="@color/black"
                            android:textSize="20sp" />

                    </LinearLayout>
                </LinearLayout>
            </androidx.cardview.widget.CardView>
</code>```

When I hit RUN it gives me this error:

I'm new to coding.

答:
you can change your code like this

```<code>holder.FirstName.setText(list.getFirstName().get(position));
holder.LastName.setText(list.getLastName().get(position));
holder.Age.setText(list.getAge().get(position);
</code>```

and you should change this code position

```<code>myAdapter = new MyAdapter(this,list);

recyclerView.setAdapter(myAdapter);
</code>```

into under this code

```<code>database.addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot snapshot) {

                        for (DataSnapshot dataSnapshot : snapshot.getChildren()){

                            User user = dataSnapshot.getValue(User.class);
                            list.add(user);

                        }
                        myAdapter.notifyDataSetChanged();
                    }
                    @Override
                    public void onCancelled(@NonNull DatabaseError error) {
                    }
                });
</code>```

hope it can solve your problem :)

Body:
Here are my codes for MyAdapter, ActivityMain, MinActivity, and User

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {

   Context context;
   ArrayList<User> list;

   public MyAdapter(Context context, ArrayList<User> list) {
     this.context = context;
     this.list = list;
   }

   @NonNull
   @Override
   public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(context).inflate(R.layout.item, parent, false);
    return new MyViewHolder(v);
   }

   @Override
   public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {

     // here is the problem that I don't know how to fix][1]
     // I'm tryin to pass data from firebase to Recyclerview
     // error I'm getting here is:
     // [Cannot resolve method 'getFirstName' in 'User'
     // Cannot resolve method 'getLastName' in 'User'
     // Cannot resolve method 'getAge' in 'User']

         User user = list.get(position);
         holder.FirstName.setText(user.getFirstName());
         holder.LastName.setText(user.getLastName());
         holder.Age.setText(user.getAge());

    }

    @Override
    public int getItemCount() {
         return list.size();
    }

   public static class MyViewHolder extends RecyclerView.ViewHolder{

         TextView FirstName, LastName, Age;

          public MyViewHolder(@NonNull View itemView) {
             super(itemView);

              FirstName = itemView.findViewById(R.id.tvFirstName);
              LastName = itemView.findViewById(R.id.tvLastName);
              Age = itemView.findViewById(R.id.tvAge);

           }
        }

    }

This is MainActivity code

 public class MainActivity extends AppCompatActivity {

       RecyclerView recyclerView;
       DatabaseReference database;
       MyAdapter myAdapter;
       ArrayList<User> list;

       @Override
       protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_Main);

              recyclerView = findViewById(R.id.userList);
              database = FirebaseDatabase.getInstance().getReference("User");
              recyclerView.setHasFixedSize(true);

              recyclerView.setLayoutManager(new LinearLayoutManager(this));

              list = new ArrayList<>();
              myAdapter = new MyAdapter(this,list);

              recyclerView.setAdapter(myAdapter);

              database.addValueEventListener(new ValueEventListener() {
                        @Override
                        public void onDataChange(@NonNull DataSnapshot snapshot) {

                            for (DataSnapshot dataSnapshot : snapshot.getChildren()){

                                User user = dataSnapshot.getValue(User.class);
                                list.add(user);

                            }
                            myAdapter.notifyDataSetChanged();
                        }
                        @Override
                        public void onCancelled(@NonNull DatabaseError error) {
                        }
                    });
                }
            }

This is User codes which I generated with getter

   public class User {

        String FirstName, LastName, Age;

        public String getFirstName() {
            return FirstName;
        }

        public String getLastName() {
            return LastName;
        }

        public String getAge() {
            return Age;
        }

        {

        }
 }

This is my layout file

 <?xml version="1.0" encoding="utf-8"?>
 <androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        app:cardElevation="8dp"
        app:cardCornerRadius="8dp"
        android:layout_margin="16dp">

                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="16dp"
                    android:orientation="vertical">

                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_vertical"
                        android:orientation="horizontal">

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text="First Name :"
                            android:textColor="@color/black"
                            android:textSize="26sp"
                            android:textStyle="bold"/>

                        <TextView
                            android:id="@+id/tvFirstName"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_marginLeft="8dp"
                            android:text="Arya"
                            android:textColor="@color/black"
                            android:textSize="20sp" />

                    </LinearLayout>

                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_vertical"
                        android:orientation="horizontal">

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text="@string/last_name"
                            android:textColor="@color/black"
                            android:textSize="26sp"
                            android:textStyle="bold"/>

                        <TextView
                            android:id="@+id/tvLastName"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_marginStart="8dp"
                            android:text="@string/stark"
                            android:textColor="@color/black"
                            android:textSize="20sp" />

                    </LinearLayout>

                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_vertical"
                        android:orientation="horizontal">

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text="@string/age"
                            android:textColor="@color/black"
                            android:textSize="26sp"
                            android:textStyle="bold"/>

                        <TextView
                            android:id="@+id/tvAge"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_marginLeft="8dp"
                            android:text="18"
                            android:textColor="@color/black"
                            android:textSize="20sp" />

                    </LinearLayout>
                </LinearLayout>
            </androidx.cardview.widget.CardView>

When I hit RUN it gives me this error:

I'm new to coding.

Body:
you can change your code like this

holder.FirstName.setText(list.getFirstName().get(position));
holder.LastName.setText(list.getLastName().get(position));
holder.Age.setText(list.getAge().get(position);

and you should change this code position

myAdapter = new MyAdapter(this,list);

recyclerView.setAdapter(myAdapter);

into under this code

database.addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot snapshot) {

                        for (DataSnapshot dataSnapshot : snapshot.getChildren()){

                            User user = dataSnapshot.getValue(User.class);
                            list.add(user);

                        }
                        myAdapter.notifyDataSetChanged();
                    }
                    @Override
                    public void onCancelled(@NonNull DatabaseError error) {
                    }
                });

hope it can solve your problem :)


来源: stackexchange

问:
Find std::function by string key in unordered_map
This works:

std::unordered_map<std::string, int> m = {};
auto c = m.find(typeName);
if (c == m.end())
{

}
```
<p>This works:</p>
<pre class="lang-cpp prettyprint-override"><code>std::unordered_map<std::string, std::string> m = {};
auto c = m.find(typeName);
if (c == m.end())
{

}
</code>```

This doesn't work:

std::unordered_map<std::string, std::function<void>> m = {};
auto c = m.find(typeName);
if (c == m.end())
{

}
```

== shown as error:

In template: implicit instantiation of undefined template 'std::function' error occurred here (declaration of _T2 second inside  inside pair)

in instantiation of template class 'std::pair<const std::string, std::function>' requested here

in instantiation of template class 'std::__hash_value_type<std::string, std::function>' requested here template is declared here

P.S. is there any other way storing std::function by string key if there is no way making it work?

答:
std::function expects a function type as template argument, while void is not. For example if the function takes nothing and returns void then it should be

```<code>std::unordered_map<std::string, std::function<void()>> m = {};
</code>```

ContentLicense: CC BY-SA 4.0

Body:
This works:

std::unordered_map<std::string, int> m = {};
auto c = m.find(typeName);
if (c == m.end())
{

}

This works:

std::unordered_map<std::string, std::string> m = {};
auto c = m.find(typeName);
if (c == m.end())
{

}

This doesn't work:

std::unordered_map<std::string, std::function<void>> m = {};
auto c = m.find(typeName);
if (c == m.end())
{

}

== shown as error:

In template: implicit instantiation of undefined template 'std::function' error occurred here (declaration of _T2 second inside  inside pair)

in instantiation of template class 'std::pair<const std::string, std::function>' requested here

in instantiation of template class 'std::__hash_value_type<std::string, std::function>' requested here template is declared here

P.S. is there any other way storing std::function by string key if there is no way making it work?

Body:
std::function expects a function type as template argument, while void is not. For example if the function takes nothing and returns void then it should be

std::unordered_map<std::string, std::function<void()>> m = {};


问:
Auto Selecting a Value from Dropdown on Selection of Specific Value from Another Dropdown
Basically I am trying to figure out on selecting a value from dropdown on selection of a value from another dropdown select box.

var gender1 = document.querySelector("#gender1");
var gender2 = document.querySelector("#gender2");

gender1.addEventListener("change", function() {
  var value = gender1.value;
  switch (value) {

    case "Boy":
      gender2.value = "Tipu";
      break;

    case "Girl":
      gender2.value = "Ayubi";
      break;

  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select class="input_select" name="student_gender" id="gender1">
  <option value="Boy" '.$selected_boy.'>Boy</option>
  <option value="Girl" '.$selected_girl.'>Girl</option>
</select>

<select class="input_select" name="student_class_section" id="gender2">
  <option value="Tipu" '.$selected_boy.'>Tipu (Boy)</option>
  <option value="Ayubi" '.$selected_girl.'>Ayubi (Girl)</option>
</select></code>```

Here is my complete HTML page code. Plz have a look to figure out the issue. So much thanks.

```<code>    <head>
        <title>Jeelani High School & Academy® - '.$page_title.'</title>
        '.$jscript_data.'
        '.$css_data.'
        <script type="text/javascript">
            var gender1 = document.querySelector("#gender1");
            var gender2 = document.querySelector("#gender2");

            gender1.addEventListener("change", function() {
                var value = gender1.value;

                switch (value) {
                    case "Boy":
                        gender2.value = "Tipu";
                        break;

                    case "Girl":
                        gender2.value = "Ayubi";
                        break;
                }
            });

            gender2.addEventListener("change", function() {
                var { value } = gender2;

                switch (value) {
                    case "Tipu":
                        gender1.value = "Boy";
                        break;

                    case "Ayubi":
                        gender1.value = "Girl";
                        break;
                }
            });
        </script>
    </head>
    <body>
    '.$header.'
    <table border="0" cellspacing="1" cellpadding="1" class="tborder">
        <tr>
            <td class="tcat" colspan="2">Create New Student</td>
        <tr>
            <td class="trow1" width="70%" valign="top">
                <form name="CreateStudent" action="students.php" onsubmit="return validateFormStudent()" method="post" enctype="multipart/form-data">
                    <table border="0" cellspacing="1" cellpadding="1" width="100%">
                        <tr>
                            <td class="tcat2" colspan="2">Personal Info</td>
                        </tr>
                        <tr>
                            <td width="20%" class="trow1">Student\'s Name:</td>
                            <td width="50%" class="trow1"><input type="text" class="input_box" name="student_name" value="" size="20" maxlength="40" oninput="this.value = this.value.replace(/[^a-zA-Z \,]/, \'\');" autofocus><span style="margin-left: 10px; color: #FF0000;">*</span>
                                <span style="float: right;">
                                    <div class="image-upload">
                                        <label for="file-input"><span class="profile_image_upload"><img src="./profile_image.png"> Upload Profile Image<input type="checkbox" class="input_checkbox" name="upload_profile_image" value="1"/></span></label>
                                        <input id="file-input" type="file" name="image" />
                                    </div>
                                </span>
                            </td>
                        </tr>
                        <tr>
                            <td width="20%" class="trow2">Student\'s Gender:</td>
                            <td width="80%" class="trow2">
                            <select class="input_select" name="student_gender" id="gender1">
                                <option value="Boy"'.$selected_boy.'>Boy</option>
                                <option value="Girl"'.$selected_girl.'>Girl</option>
                            </select>
                            </td>
                        </tr>
                        <tr>
                            <td width="20%" class="trow1">Father\'s Name:</td>
                            <td width="80%" class="trow1"><input type="text" class="input_box" name="student_father_name" value="" size="20" maxlength="40" oninput="this.value = this.value.replace(/[^a-zA-Z \,]/, \'\');"></td>
                        </tr>
                        <tr>
                            <td width="20%" class="trow2">Contact #:</td>
                            <td width="80%" class="trow2"><input type="text" class="input_box" name="student_contact_no" value="" size="20" oninput="this.value = this.value.replace(/[^0-9,]/, \'\');"><div class="small_text">Comma separated numbers.</div></td>
                        </tr>
                        <tr>
                            <td width="20%" class="trow1">Address:</td>
                            <td width="80%" class="trow1"><input type="text" class="input_box" name="student_address" value="" size="40"></td>
                        </tr>
                        <tr>
                            <td class="tcat2" colspan="2">Class Info</td>
                        </tr>
                        <tr>
                            <td width="20%" class="trow1">Student\'s Class:</td>
                            <td width="80%" class="trow1">
                                <select class="input_select" name="student_class">
                                <option value="Play Group"'.$selected_pg.'>Play Group</option>
                                <option value="Nursery"'.$selected_nur.'>Nursery</option>
                                <option value="Prep."'.$selected_prep.'>Prep.</option>
                                <option value="1"'.$selected_1.'>Class 1</option>
                                <option value="2"'.$selected_2.'>Class 2</option>
                                <option value="3"'.$selected_3.'>Class 3</option>
                                <option value="4"'.$selected_4.'>Class 4</option>
                                <option value="5"'.$selected_5.'>Class 5</option>
                                <option value="6"'.$selected_6.'>Class 6</option>
                                <option value="7"'.$selected_7.'>Class 7</option>
                                <option value="8"'.$selected_8.'>Class 8</option>
                                <option value="Pre-9"'.$selected_pre9.'>Pre 9</option>
                                <option value="9"'.$selected_9.'>Class 9</option>
                                <option value="10"'.$selected_10.'>Class 10</option>
                            </select>
                            </td>
                        </tr>
                        <tr>
                            <td width="20%" class="trow2">Class Section:</td>
                            <td width="80%" class="trow2">
                                <select class="input_select" name="student_class_section" id="gender2">
                                    <option value="Tipu"'.$selected_boy.'>Tipu (Boy)</option>
                                    <option value="Ayubi"'.$selected_girl.'>Ayubi (Girl)</option>
                                </select>
                            </td>
                        </tr>
                        <tr>
                            <td class="tcat2" colspan="2">Fees Info</td>
                        </tr>
                        <tr>
                            <td width="20%" class="trow1">Monthly Fee:</td>
                            <td width="80%" class="trow1"><input type="text" class="input_box" name="student_monthly_fee" value="" size="10" oninput="this.value = this.value.replace(/[^0-9,]/, \'\');" autofocus></td>
                        </tr>
                        <tr>
                            <td class="tcat2" colspan="2" align="center">
                                <input type="hidden" name="action" value="do_create_student">
                                <input type="hidden" name="my_post_key" value="'.$mybb->post_code.'" />
                                <input type="submit" class="input_button" name="submit" value="Create Student" />
                            </td>
                        </tr>
                    </table>
                </form>
            </td>
            <td class="trow1" width="30%" valign="top">'.$menu.'</td>
        </tr>
    </table>
    <br />
    </body>
</html>
</code>```

Here is my complete HTML page code. Plz have a look to figure out the issue. So much thanks.

答:
All you need to do is to add almost the same event listener to #gender2 as well.

var gender1 = document.querySelector("#gender1");
var gender2 = document.querySelector("#gender2");

gender1.addEventListener("change", function() {
    var value = gender1.value;

    switch (value) {
        case "Boy":
            gender2.value = "Tipu";
            break;

        case "Girl":
            gender2.value = "Ayubi";
            break;
    }
});

gender2.addEventListener("change", function() {
    var { value } = gender2;

    switch (value) {
        case "Tipu":
            gender1.value = "Boy";
            break;

        case "Ayubi":
            gender1.value = "Girl";
            break;
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select class="input_select" name="student_gender" id="gender1">
    <option value="Boy">Boy</option>
    <option value="Girl">Girl</option>
</select>

<select class="input_select" name="student_class_section" id="gender2">
    <option value="Tipu">Tipu (Boy)</option>
    <option value="Ayubi">Ayubi (Girl)</option>
</select></code>```

Body:
Basically I am trying to figure out on selecting a value from dropdown on selection of a value from another dropdown select box.

var gender1 = document.querySelector("#gender1");
var gender2 = document.querySelector("#gender2");

gender1.addEventListener("change", function() {
  var value = gender1.value;
  switch (value) {

    case "Boy":
      gender2.value = "Tipu";
      break;

    case "Girl":
      gender2.value = "Ayubi";
      break;

  }
})

<select class="input_select" name="student_gender" id="gender1">
  <option value="Boy" '.$selected_boy.'>Boy</option>
  <option value="Girl" '.$selected_girl.'>Girl</option>
</select>

<select class="input_select" name="student_class_section" id="gender2">
  <option value="Tipu" '.$selected_boy.'>Tipu (Boy)</option>
  <option value="Ayubi" '.$selected_girl.'>Ayubi (Girl)</option>
</select>

Here is my complete HTML page code. Plz have a look to figure out the issue. So much thanks.

        <title>Jeelani High School & Academy® - '.$page_title.'</title>
        '.$jscript_data.'
        '.$css_data.'

    '.$header.'

            Create New Student

                <form name="CreateStudent" action="students.php" onsubmit="return validateFormStudent()" method="post" enctype="multipart/form-data">

                            Personal Info

                            Student\'s Name:
                            <input type="text" class="input_box" name="student_name" value="" size="20" maxlength="40" oninput="this.value = this.value.replace(/[^a-zA-Z \,]/, \'\');" autofocus>*

                                         Upload Profile Image<input type="checkbox" class="input_checkbox" name="upload_profile_image" value="1"/>
                                        <input id="file-input" type="file" name="image" />

                            Student\'s Gender:

                            <select class="input_select" name="student_gender" id="gender1">
                                <option value="Boy"'.$selected_boy.'>Boy</option>
                                <option value="Girl"'.$selected_girl.'>Girl</option>
                            </select>

                            Father\'s Name:
                            <input type="text" class="input_box" name="student_father_name" value="" size="20" maxlength="40" oninput="this.value = this.value.replace(/[^a-zA-Z \,]/, \'\');">

                            Contact #:
                            <input type="text" class="input_box" name="student_contact_no" value="" size="20" oninput="this.value = this.value.replace(/[^0-9,]/, \'\');">
Comma separated numbers.

                            Address:
                            <input type="text" class="input_box" name="student_address" value="" size="40">

                            Class Info

                            Student\'s Class:

                                <select class="input_select" name="student_class">
                                <option value="Play Group"'.$selected_pg.'>Play Group</option>
                                <option value="Nursery"'.$selected_nur.'>Nursery</option>
                                <option value="Prep."'.$selected_prep.'>Prep.</option>
                                <option value="1"'.$selected_1.'>Class 1</option>
                                <option value="2"'.$selected_2.'>Class 2</option>
                                <option value="3"'.$selected_3.'>Class 3</option>
                                <option value="4"'.$selected_4.'>Class 4</option>
                                <option value="5"'.$selected_5.'>Class 5</option>
                                <option value="6"'.$selected_6.'>Class 6</option>
                                <option value="7"'.$selected_7.'>Class 7</option>
                                <option value="8"'.$selected_8.'>Class 8</option>
                                <option value="Pre-9"'.$selected_pre9.'>Pre 9</option>
                                <option value="9"'.$selected_9.'>Class 9</option>
                                <option value="10"'.$selected_10.'>Class 10</option>
                            </select>

                            Class Section:

                                <select class="input_select" name="student_class_section" id="gender2">
                                    <option value="Tipu"'.$selected_boy.'>Tipu (Boy)</option>
                                    <option value="Ayubi"'.$selected_girl.'>Ayubi (Girl)</option>
                                </select>

                            Fees Info

                            Monthly Fee:
                            <input type="text" class="input_box" name="student_monthly_fee" value="" size="10" oninput="this.value = this.value.replace(/[^0-9,]/, \'\');" autofocus>

                                <input type="hidden" name="action" value="do_create_student">
                                <input type="hidden" name="my_post_key" value="'.$mybb->post_code.'" />
                                <input type="submit" class="input_button" name="submit" value="Create Student" />

                </form>

            '.$menu.'

Here is my complete HTML page code. Plz have a look to figure out the issue. So much thanks.

Body:
All you need to do is to add almost the same event listener to #gender2 as well.

var gender1 = document.querySelector("#gender1");
var gender2 = document.querySelector("#gender2");

gender1.addEventListener("change", function() {
    var value = gender1.value;

    switch (value) {
        case "Boy":
            gender2.value = "Tipu";
            break;

        case "Girl":
            gender2.value = "Ayubi";
            break;
    }
});

gender2.addEventListener("change", function() {
    var { value } = gender2;

    switch (value) {
        case "Tipu":
            gender1.value = "Boy";
            break;

        case "Ayubi":
            gender1.value = "Girl";
            break;
    }
});

<select class="input_select" name="student_gender" id="gender1">
    <option value="Boy">Boy</option>
    <option value="Girl">Girl</option>
</select>

<select class="input_select" name="student_class_section" id="gender2">
    <option value="Tipu">Tipu (Boy)</option>
    <option value="Ayubi">Ayubi (Girl)</option>
</select>


问:
Leave-one out means by group in R
Imagine a table of individuals over time in different firms. I'm trying to compute for every individual the mean wage of their co-workers (ie the mean wage in their firm at time t excluding them). I have a working code using data.table in R which works, but I'm wondering whether there is a better, more efficient of doing this:</p>
```<code>foo <- data.table(
  i = rep(1:6, each = 2),
  t = rep(1:2, 6),
  f = rep(1:2, each = 6),
  w = 1:12
)

foo[, x := mean(foo[t == .BY$t & f == foo[i == .BY$i & t == .BY$t]$f & i != .BY$i]$w), by = .(i, t)]
</code>```

Title: Leave-one out means by group in R

Body:
Imagine a table of individuals over time in different firms. I'm trying to compute for every individual the mean wage of their co-workers (ie the mean wage in their firm at time t excluding them). I have a working code using data.table in R which works, but I'm wondering whether there is a better, more efficient of doing this:

foo <- data.table(
  i = rep(1:6, each = 2),
  t = rep(1:2, 6),
  f = rep(1:2, each = 6),
  w = 1:12
)

foo[, x := mean(foo[t == .BY$t & f == foo[i == .BY$i & t == .BY$t]$f & i != .BY$i]$w), by = .(i, t)]

Body:
maybe this:

foo[, V1 := sapply(i, function(x) mean(w[-match(x,i)])) , by=.(f, t)]
#    i t f  w V1
# 1: 1 1 1  1  4
# 2: 1 2 1  2  5
# 3: 2 1 1  3  3
# 4: 2 2 1  4  4
# 5: 3 1 1  5  2
# 6: 3 2 1  6  3
# 7: 4 1 2  7 10
# 8: 4 2 2  8 11
# 9: 5 1 2  9  9
# 10: 5 2 2 10 10
# 11: 6 1 2 11  8
# 12: 6 2 2 12  9


问:
Multer does not find the folder that does exist to save images
I am trying to upload images using Multer and although the destination folder does exist Multer tells me the error that it cannot find the folder, this is my code:

```<code>import { Router } from 'express';
import { check, validationResult } from 'express-validator';

const path = require('path');

const multer  = require('multer')

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
      cb(null, path.join(__dirname, '../uploads/'))
    },
    filename: function (req, file, cb) {
        cb(null, new Date().toISOString() + file.originalname)
    }
});

    const fileFilter =  (req, file, cb) => {
        if (file.mimetype === "image/png" || file.mimetype === "image/jpg" || file.mimetype === "image/jpeg") {
          cb(null, true);
        } else {
          cb(null, false);
          return cb(new Error('Only .png, .jpg and .jpeg format allowed!'));
        }
      };

  const upload = multer(
    {
        storage: storage,
        limits:{
            fileSize: 1024 * 1024
        },
        fileFilter: fileFilter
    })

let router = Router();

router.post('/', upload.single('img'),

    newProduct
);
</code>```

But when doing the test from Postman it tells me the error:

Error: ENOENT: no such file or directory, open 'C:\project\uploads\2022-02-11T03:17:32.711Zcloud.png'

The strange thing is that the folder path does exist:

And more strange is that if I use the basic code of multer without using multer.diskStorage if I can save in the folder in this way:

```<code>const express = require('express')
const multer  = require('multer')
const upload = multer({ dest: 'uploads/' })
</code>```

I really don't know why when using simply if it shows the path that exists but multer can't find the directory even though it exists.

Thanks.

答:
I changed this line:

```<code>cb(null, new Date().toISOString() + file.originalname)
</code>```

By this line:

```<code>cb(null, new Date().toISOString().replace(/:/g, '-') + file.originalname)
</code>```

Replacing the colon with a hyphen means that windows doesn't seem to understand colon paths properly.

Body:
I am trying to upload images using Multer and although the destination folder does exist Multer tells me the error that it cannot find the folder, this is my code:

import { Router } from 'express';
import { check, validationResult } from 'express-validator';

const path = require('path');

const multer  = require('multer')

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
      cb(null, path.join(__dirname, '../uploads/'))
    },
    filename: function (req, file, cb) {
        cb(null, new Date().toISOString() + file.originalname)
    }
});

    const fileFilter =  (req, file, cb) => {
        if (file.mimetype === "image/png" || file.mimetype === "image/jpg" || file.mimetype === "image/jpeg") {
          cb(null, true);
        } else {
          cb(null, false);
          return cb(new Error('Only .png, .jpg and .jpeg format allowed!'));
        }
      };

  const upload = multer(
    {
        storage: storage,
        limits:{
            fileSize: 1024 * 1024
        },
        fileFilter: fileFilter
    })

let router = Router();

router.post('/', upload.single('img'),

    newProduct
);

But when doing the test from Postman it tells me the error:

Error: ENOENT: no such file or directory, open 'C:\project\uploads\2022-02-11T03:17:32.711Zcloud.png'

The strange thing is that the folder path does exist:

And more strange is that if I use the basic code of multer without using multer.diskStorage if I can save in the folder in this way:

const express = require('express')
const multer  = require('multer')
const upload = multer({ dest: 'uploads/' })

I really don't know why when using simply if it shows the path that exists but multer can't find the directory even though it exists.

Thanks.

Body:
I changed this line:

cb(null, new Date().toISOString() + file.originalname)

By this line:

cb(null, new Date().toISOString().replace(/:/g, '-') + file.originalname)

Replacing the colon with a hyphen means that windows doesn't seem to understand colon paths properly.


问:
Reducing iterator based on value
I have an iterator as such:

```<code>Iterator(List(1, 2012), List(2, 2015), List(5, 2017), List(7, 2020))
</code>```

I'm trying to return an iterator, but with the values slightly changed. The values for all multiples of 5 must be added to the previous row. So the result would be:

```<code>Iterator(List(1, 2012), List(2, 4032), List(7, 2020))
</code>```

I've tried using the following method:

```<code>val a = Iterator(List(1, 2012), List(2, 2015), List(5, 2017), List(7, 2020))

val aTransformed = a.reduce((x,y) => if (y(0)%5 == 0) List(x(0),x(1)+y(1)) else x)
</code>```

but it gives me the final value val aTransformed: List[Int] = List(1, 4029)

What can I do to get an iterator in my desired format? Is there a method to just check the previous/next row without folding it all into one final value?

I know this is possible by converting the iterator to a List, traversing, mutating and converting back to an iterator, but is there a more elegant solution?

Edit for clarification:

Consecutive multiples of 5 will get collated into one sum

Ex:

```<code>Iterator(List(1, 2012), List(2, 2015), List(5, 2017), List(10, 2025))
</code>```

should become

```<code>Iterator(List(1, 2012), List(2, 6057))
</code>```

答:
Since we cant directly get last element from Iterator, we need a buffer to store the last element, and after calcuate, we check the buffer state and append it the final result.

Here I append a empty Iterator[List[Int]] element to simplify the check step.

def convert(xs: Iterator[List[Int]]): Iterator[List[Int]] = {
      val res = (xs ++ Iterator(List[Int]())).foldLeft(Iterator[List[Int]](), List[Int]())((x, y)=> {
        if (y.nonEmpty && y(0) % 5 == 0) {
          if (x._2.nonEmpty) {
            (x._1, List(x._2(0), x._2(1) + y(1)))
          } else {
            (x._1, y)
          }
        } else {
          if (x._2.nonEmpty) {
            (x._1 ++ Iterator(x._2), y)
          } else {
            (x._1, y)
          }
        }
      })

      res._1
    }
```
<p>test</p>
```scala> val xs1 = Iterator(List(1, 2012), List(2, 2015), List(5, 2017), List(7, 2020))
val xs1: Iterator[List[Int]] = <iterator>

scala> val xs2 = Iterator(List(1, 2012), List(2, 2015), List(5, 2017), List(10, 2025))
val xs2: Iterator[List[Int]] = <iterator>

scala> convert(xs1)
val res44: Iterator[List[Int]] = <iterator>

scala> res44.toList
val res45: List[List[Int]] = List(List(1, 2012), List(2, 4032), List(7, 2020))

scala> convert(xs2)
val res47: Iterator[List[Int]] = <iterator>

scala> res47.toList
val res48: List[List[Int]] = List(List(1, 2012), List(2, 6057))
```

Title: Reducing iterator based on value

Body:
I have an iterator as such:

Iterator(List(1, 2012), List(2, 2015), List(5, 2017), List(7, 2020))

I'm trying to return an iterator, but with the values slightly changed. The values for all multiples of 5 must be added to the previous row. So the result would be:

Iterator(List(1, 2012), List(2, 4032), List(7, 2020))

I've tried using the following method:

val a = Iterator(List(1, 2012), List(2, 2015), List(5, 2017), List(7, 2020))

val aTransformed = a.reduce((x,y) => if (y(0)%5 == 0) List(x(0),x(1)+y(1)) else x)

but it gives me the final value val aTransformed: List[Int] = List(1, 4029)

What can I do to get an iterator in my desired format? Is there a method to just check the previous/next row without folding it all into one final value?

I know this is possible by converting the iterator to a List, traversing, mutating and converting back to an iterator, but is there a more elegant solution?

Edit for clarification:

Consecutive multiples of 5 will get collated into one sum

Ex:

Iterator(List(1, 2012), List(2, 2015), List(5, 2017), List(10, 2025))

should become

Iterator(List(1, 2012), List(2, 6057))

Body:
Since we cant directly get last element from Iterator, we need a buffer to store the last element, and after calcuate, we check the buffer state and append it the final result.

Here I append a empty Iterator[List[Int]] element to simplify the check step.

def convert(xs: Iterator[List[Int]]): Iterator[List[Int]] = {
      val res = (xs ++ Iterator(List[Int]())).foldLeft(Iterator[List[Int]](), List[Int]())((x, y)=> {
        if (y.nonEmpty && y(0) % 5 == 0) {
          if (x._2.nonEmpty) {
            (x._1, List(x._2(0), x._2(1) + y(1)))
          } else {
            (x._1, y)
          }
        } else {
          if (x._2.nonEmpty) {
            (x._1 ++ Iterator(x._2), y)
          } else {
            (x._1, y)
          }
        }
      })

      res._1
    }

test

scala> val xs1 = Iterator(List(1, 2012), List(2, 2015), List(5, 2017), List(7, 2020))
val xs1: Iterator[List[Int]] = <iterator>

scala> val xs2 = Iterator(List(1, 2012), List(2, 2015), List(5, 2017), List(10, 2025))
val xs2: Iterator[List[Int]] = <iterator>

scala> convert(xs1)
val res44: Iterator[List[Int]] = <iterator>

scala> res44.toList
val res45: List[List[Int]] = List(List(1, 2012), List(2, 4032), List(7, 2020))

scala> convert(xs2)
val res47: Iterator[List[Int]] = <iterator>

scala> res47.toList
val res48: List[List[Int]] = List(List(1, 2012), List(2, 6057))


问:
Can you simplify Else If?
Currently working on a project from school. And they want us to take a users input and display their grades.

Now I am just being curious here, but is there any way to make this more simple? I feel like this could easily get out of hand.

My first thought was instead of creating each grade as a variable. You could make it an array. Could you then create some sort of loop that will check instead of creating an if else?

Sorry if this isn't possible. Just very curious about how i could improve on this.

```<code>> Grades = [
    '9',
    '8',
    '7',
    '6',
    '5',
    '4',
    '3',
    '2',
    '1',
    'U'
]

Component_1 = int(input("Enter your Component 1 mark here: "))
if Component_1 <= 9:
    print(f"You got the grade {Grades[9]} ")
elif Component_1 <= 17:
    print(f"You got the grade {Grades[8]}")
elif Component_1 <= 25:
    print(f"You got the grade {Grades[7]}")
elif Component_1 <= 34:
    print(f"You got the grade {Grades[6]}")
</code>```

The task I was originally asked to do:

答:
If the Grades structure is provided, here's how to do what you want without modifying it:

```<code>grade_cutoffs = [9, 17, 25, 34, 44, 55, 66, 77, 88]
for i in range(len(grade_cutoffs)):
    if Component_1 <= grade_cutoffs[i]:
        print(f"You got the grade {Grades[9-i]}")
        break
else:
    print(f"You got the grade {Grades[0]}")
</code>```

Some sample runs:

```<code>Enter your Component 1 mark here: 45
You got the grade 5

Enter your Component 1 mark here: 3
You got the grade U

Enter your Component 1 mark here: 5555
You got the grade 9
</code>```

Or, if you can assume the simple nature of Grades to be what you show here, then you don't even need that structure:

```<code>grade_cutoffs = [9, 17, 25, 34, 44, 55, 66, 77, 88]
for i in range(len(grade_cutoffs)):
    if Component_1 <= grade_cutoffs[i]:
        print(f"You got the grade {i if i else 'U'}")
        break
else:
    print(f"You got the grade 9")
</code>```

which gives the same results.

Title: Can you simplify Else If?

Body:
Currently working on a project from school. And they want us to take a users input and display their grades.

Now I am just being curious here, but is there any way to make this more simple? I feel like this could easily get out of hand.

My first thought was instead of creating each grade as a variable. You could make it an array. Could you then create some sort of loop that will check instead of creating an if else?

Sorry if this isn't possible. Just very curious about how i could improve on this.

> Grades = [
    '9',
    '8',
    '7',
    '6',
    '5',
    '4',
    '3',
    '2',
    '1',
    'U'
]

Component_1 = int(input("Enter your Component 1 mark here: "))
if Component_1 <= 9:
    print(f"You got the grade {Grades[9]} ")
elif Component_1 <= 17:
    print(f"You got the grade {Grades[8]}")
elif Component_1 <= 25:
    print(f"You got the grade {Grades[7]}")
elif Component_1 <= 34:
    print(f"You got the grade {Grades[6]}")

The task I was originally asked to do:

Body:
If the Grades structure is provided, here's how to do what you want without modifying it:

grade_cutoffs = [9, 17, 25, 34, 44, 55, 66, 77, 88]
for i in range(len(grade_cutoffs)):
    if Component_1 <= grade_cutoffs[i]:
        print(f"You got the grade {Grades[9-i]}")
        break
else:
    print(f"You got the grade {Grades[0]}")

Some sample runs:

Enter your Component 1 mark here: 45
You got the grade 5

Enter your Component 1 mark here: 3
You got the grade U

Enter your Component 1 mark here: 5555
You got the grade 9

Or, if you can assume the simple nature of Grades to be what you show here, then you don't even need that structure:

grade_cutoffs = [9, 17, 25, 34, 44, 55, 66, 77, 88]
for i in range(len(grade_cutoffs)):
    if Component_1 <= grade_cutoffs[i]:
        print(f"You got the grade {i if i else 'U'}")
        break
else:
    print(f"You got the grade 9")

which gives the same results.


问:
Visual studio code : remove word wrap line on editor
Please help I need to remove the below line when editing .dart files on visual studio code.

Visual studio code editor view

答:
Shift + CMD + P.

Type "settings"

Click on "preferences: open settings(JSON)"

That will open settings.json file, then remove the "editor.rulers" and save it.
The vertical line will be gone.


问:
Is there a way to loop this in R?
I have 2 different group of matrices where the first group has data of 95 subjects with the name FC_sub-*.xlsx and the second group also with data of 95 subjects with the name SC_sub-*.xlsx. I need to do correlation between similar subjects in these 2 different groups. I know to do them individually. For eg:

SC_FC_sub_0152 <- corr.test(SC_sub_0152,FC_sub_0152, method="spearman", adjust="none")
SC_FC_sub_0225 <- corr.test(SC_sub_0225,FC_sub_0225, method="spearman", adjust="none")
```

but I couldn't write a code to loop through 2 different groups performing correlation on similar subjects. Is there any way to do this in R studio?

Any help would be appreciated, Thank you!

答:
Consider Map (wrapper to mapply) after building lists (not separate data frames) of your subject data:

SC_lst <- list.files(path="/path/to/folder", pattern="SC_sub.*xlsx", full.names=TRUE)
SC_dfs <- lapply(SC_lst, readxl::read_excel)

FC_lst <- list.files(path="/path/to/myfolder", pattern="FC_sub.*xlsx", full.names=TRUE)
FC_dfs <- lapply(FC_lst, readxl::read_excel)

corr_list <- Map(
   function(sc, fc) corr.test(sc, fc, method="spearman", adjust="none")
   sc = SC_dfs,
   fc = FC_dfs
)
```

Title: Is there a way to loop this in R?

Body:
I have 2 different group of matrices where the first group has data of 95 subjects with the name FC_sub-*.xlsx and the second group also with data of 95 subjects with the name SC_sub-*.xlsx. I need to do correlation between similar subjects in these 2 different groups. I know to do them individually. For eg:

SC_FC_sub_0152 <- corr.test(SC_sub_0152,FC_sub_0152, method="spearman", adjust="none")
SC_FC_sub_0225 <- corr.test(SC_sub_0225,FC_sub_0225, method="spearman", adjust="none")

but I couldn't write a code to loop through 2 different groups performing correlation on similar subjects. Is there any way to do this in R studio?

Any help would be appreciated, Thank you!


问:
Unable to trigger AWS Lambda from SNS
I am trying to create trigger for AWS lambda from SNS codestar-notifications .

While creating a trigger using Console it automatically adds subscription to the SNS topic. . Also, this works in alternate direction i.e. if I create a subscription for SNS as the Lambda function by explicitly adding its arn, it automatically links a trigger to Lambda function.

But when using terraform to create a subscription as below:

```<code>resource "aws_sns_topic_subscription" "subscribe_lambda_to_first_topic" {
  topic_arn = module.first_topic.sns-topic-detail.arn
  protocol  = "lambda"
  endpoint  = module.lambda_function.lambda_function.arn
}
</code>```

it doesn't create a trigger in AWS Lambda.

I tried creating a trigger using event source mapping in Terraform as below

```<code>resource "aws_lambda_event_source_mapping" "lambda_source" {
 event_source_arn  = module.first_topic.sns-topic-detail.arn
 function_name     = module.lambda_function.lambda_function.arn
 starting_position = "LATEST"
}
</code>```

it throws me an error saying it is possible only for

Error: error creating Lambda Event Source Mapping (arn:aws:sns:us-west-2:619867110810:codestar-notifications-emc-sns-to-lambda): InvalidParameterValueException: Unrecognized event source, must be kinesis, dynamodb stream or sqs. Unsupported source arn : arn:aws:sns:us-west-2:619867110810:codestar-notifications-emc-sns-to-lambda
{
RespMetadata: {
StatusCode: 400,
RequestID: "83bf57cb-b50d-49a8-9547-72fac69778d1"
},
Message_: "Unrecognized event source, must be kinesis, dynamodb stream or sqs. Unsupported source arn : arn:aws:sns:us-west-2:619867110810:codestar-notifications-emc-sns-to-lambda",
Type: "User"
}

with aws_lambda_event_source_mapping.lambda_source,
on main.tf line 43, in resource "aws_lambda_event_source_mapping" "lambda_source":
43: resource "aws_lambda_event_source_mapping" "lambda_source" {

答:
aws_lambda_event_source_mapping is not for SNS, just like the error message says. Instead you use aws_sns_topic_subscription as you did.

However, you forgot about aws_lambda_permission which should be (generic form from the docs - you need to adjust to your own setup):

```<code>resource "aws_lambda_permission" "with_sns" {
  statement_id  = "AllowExecutionFromSNS"
  action        = "lambda:InvokeFunction"
  function_name = aws_lambda_function.func.function_name
  principal     = "sns.amazonaws.com"
  source_arn    = aws_sns_topic.default.arn
}
</code>```

Title: Unable to trigger AWS Lambda from SNS

Body:
I am trying to create trigger for AWS lambda from SNS codestar-notifications .

While creating a trigger using Console it automatically adds subscription to the SNS topic. . Also, this works in alternate direction i.e. if I create a subscription for SNS as the Lambda function by explicitly adding its arn, it automatically links a trigger to Lambda function.

But when using terraform to create a subscription as below:

resource "aws_sns_topic_subscription" "subscribe_lambda_to_first_topic" {
  topic_arn = module.first_topic.sns-topic-detail.arn
  protocol  = "lambda"
  endpoint  = module.lambda_function.lambda_function.arn
}

it doesn't create a trigger in AWS Lambda.

I tried creating a trigger using event source mapping in Terraform as below

resource "aws_lambda_event_source_mapping" "lambda_source" {
 event_source_arn  = module.first_topic.sns-topic-detail.arn
 function_name     = module.lambda_function.lambda_function.arn
 starting_position = "LATEST"
}

it throws me an error saying it is possible only for

Error: error creating Lambda Event Source Mapping (arn:aws:sns:us-west-2:619867110810:codestar-notifications-emc-sns-to-lambda): InvalidParameterValueException: Unrecognized event source, must be kinesis, dynamodb stream or sqs. Unsupported source arn : arn:aws:sns:us-west-2:619867110810:codestar-notifications-emc-sns-to-lambda
{
RespMetadata: {
StatusCode: 400,
RequestID: "83bf57cb-b50d-49a8-9547-72fac69778d1"
},
Message_: "Unrecognized event source, must be kinesis, dynamodb stream or sqs. Unsupported source arn : arn:aws:sns:us-west-2:619867110810:codestar-notifications-emc-sns-to-lambda",
Type: "User"
}

with aws_lambda_event_source_mapping.lambda_source,
on main.tf line 43, in resource "aws_lambda_event_source_mapping" "lambda_source":
43: resource "aws_lambda_event_source_mapping" "lambda_source" {

Body:
aws_lambda_event_source_mapping is not for SNS, just like the error message says. Instead you use aws_sns_topic_subscription as you did.

However, you forgot about aws_lambda_permission which should be (generic form from the docs - you need to adjust to your own setup):

resource "aws_lambda_permission" "with_sns" {
  statement_id  = "AllowExecutionFromSNS"
  action        = "lambda:InvokeFunction"
  function_name = aws_lambda_function.func.function_name
  principal     = "sns.amazonaws.com"
  source_arn    = aws_sns_topic.default.arn
}


问:
Jasper Reports OutOfMemoryError on export
I have written a web app for managing and running Jasper reports.  Lately I've been working with some reports that generate extremely large (1500+ page) outputs, and attempting to resolve the resultant memory issues.  I have discovered the JRFileVirtualizer, which has allowed me to run the report successfully with a very limited memory footprint.  However, one of the features of my application is that it stores output files from previously run reports, and allows them to be exported to various formats (PDF, CSV, etc.).  Therefore, I find myself in the situation of having a 500+MB .jrprint file and wanting to export it to, for example, CSV on demand.  Here is some simplified example code:

```<code>JRCsvExporter exporter = new JRCsvExporter();
exporter.setParameter(JRExporterParameter.INPUT_FILE_NAME, jrprintPath);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, outputStream);
exporter.exportReport();
</code>```

Unfortunately, when I attempt this on the large file I mentioned, I get an OutOfMemoryError:

```<code>Caused by: java.lang.OutOfMemoryError: GC overhead limit exceeded
    at java.io.ObjectInputStream$HandleTable.grow(ObjectInputStream.java:3421)
    at java.io.ObjectInputStream$HandleTable.assign(ObjectInputStream.java:3227)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1744)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:351)
    at java.util.ArrayList.readObject(ArrayList.java:593)
    at sun.reflect.GeneratedMethodAccessor184.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:974)
    at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1849)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1753)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:351)
    at net.sf.jasperreports.engine.base.JRVirtualPrintPage.readObject(JRVirtualPrintPage.java:423)
    ...
</code>```

From browsing some of the Jasper internals, it looks like no matter how I attempt to set up this export (I have also tried loading and setting the JASPER_PRINT parameter directly), there will ultimately be a call to JRLoader.loadObject(...) which will attempt to load my entire 500MB report into memory (see net.sf.jasperreports.engine.JRAbstractExporter.setInput()).

My question is, is there a way around this that doesn't involve just throwing memory at the problem?  500MB is doable, but it doesn't leave my application very future-proof, and the JRVirtualizer solution for report execution leaves me hoping there will be something similar for export.  I am willing to get my hands dirty and extend some of the Jasper internal classes, but the ideal solution would be one provided by Jasper itself, for obvious reasons.

答:
Thank you for your question and your own answer.

But I have a further question on your solution:

You said you use the method JRVirtualizationHelper.setThreadVirtualizer to set the JRSwapFileVirtualizer instance associated with current thread. But since your requirement is to export some previously generated reports into PDF/CSV files, I think the GENERATE and EXPORT actions are run in two separated threads, because these two actions are probably generated by two separated user clicks.

So, why can you set a single JRSwapFileVirtualizer instance for the two threads? You are using a single server JVM?

ContentLicense: CC BY-SA 3.0

Body:
I have written a web app for managing and running Jasper reports.  Lately I've been working with some reports that generate extremely large (1500+ page) outputs, and attempting to resolve the resultant memory issues.  I have discovered the JRFileVirtualizer, which has allowed me to run the report successfully with a very limited memory footprint.  However, one of the features of my application is that it stores output files from previously run reports, and allows them to be exported to various formats (PDF, CSV, etc.).  Therefore, I find myself in the situation of having a 500+MB .jrprint file and wanting to export it to, for example, CSV on demand.  Here is some simplified example code:

JRCsvExporter exporter = new JRCsvExporter();
exporter.setParameter(JRExporterParameter.INPUT_FILE_NAME, jrprintPath);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, outputStream);
exporter.exportReport();

Unfortunately, when I attempt this on the large file I mentioned, I get an OutOfMemoryError:

Caused by: java.lang.OutOfMemoryError: GC overhead limit exceeded
    at java.io.ObjectInputStream$HandleTable.grow(ObjectInputStream.java:3421)
    at java.io.ObjectInputStream$HandleTable.assign(ObjectInputStream.java:3227)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1744)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:351)
    at java.util.ArrayList.readObject(ArrayList.java:593)
    at sun.reflect.GeneratedMethodAccessor184.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:974)
    at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1849)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1753)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:351)
    at net.sf.jasperreports.engine.base.JRVirtualPrintPage.readObject(JRVirtualPrintPage.java:423)
    ...

From browsing some of the Jasper internals, it looks like no matter how I attempt to set up this export (I have also tried loading and setting the JASPER_PRINT parameter directly), there will ultimately be a call to JRLoader.loadObject(...) which will attempt to load my entire 500MB report into memory (see net.sf.jasperreports.engine.JRAbstractExporter.setInput()).

My question is, is there a way around this that doesn't involve just throwing memory at the problem?  500MB is doable, but it doesn't leave my application very future-proof, and the JRVirtualizer solution for report execution leaves me hoping there will be something similar for export.  I am willing to get my hands dirty and extend some of the Jasper internal classes, but the ideal solution would be one provided by Jasper itself, for obvious reasons.