问:
How can I get specific view from ExpandableListView?
I have created a expandable list view and two radio buttons in it.
I want to get the value of the radio button which is selected when some button is pressed in my main Activity. My ExpandableListView is working properly but i am not able to get the radio button which is selected in main activity. </p>

```<code>public class ExpandableMenuListAdapter  extends BaseExpandableListAdapter
 {
    private Context context;
    private List<String> listDataHeader;
    private HashMap<String,List<List<String>>> listHashMap;

    public ExpandableMenuListAdapter(Context context, List<String> listDataHeader, HashMap<String, List<List<String>>> listHashMap) {
        this.context = context;
        this.listDataHeader = listDataHeader;
        this.listHashMap = listHashMap;

    }

    @Override
    public int getGroupCount() {
        return listDataHeader.size();
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        return Objects.requireNonNull(listHashMap.get(listDataHeader.get(groupPosition))).size();
    }

    @Override
    public Object getGroup(int groupPosition) {
        return listDataHeader.get(groupPosition);
    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return Objects.requireNonNull(listHashMap.get(listDataHeader.get(groupPosition))).get(childPosition);
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    @Override
    public boolean hasStableIds() {
        return false;
    }

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        String headerTitle = (String)(getGroup(groupPosition)).toString();
        if (convertView==null)
        {
            LayoutInflater inflater =(LayoutInflater)this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.list_menu_days_group,null);

        }
        TextView lblListHeader = convertView.findViewById(R.id.list_days);
        lblListHeader.setTypeface(null, Typeface.BOLD);
        lblListHeader.setText(headerTitle);
        return convertView;
    }

    @Override
    public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
        List<String> childText = (List<String>) getChild(groupPosition,childPosition);
        if (convertView==null)
        {
            LayoutInflater inflater =(LayoutInflater)this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.list_menu_item,null);
        }
        RadioButton txtListChild = convertView.findViewById(R.id.menu_list_daily1);
        RadioButton txtListChild2 = convertView.findViewById(R.id.menu_list_daily2);
        txtListChild.setText(childText.get(0));
        txtListChild2.setText(childText.get(1));
        ViewsList.menu.add(convertView);

        return convertView;
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return false;
    }
}
</code>```

答:
Use onChildClick method in your code.This method is automatically called when you click on child item

```<code>@Override
public boolean onChildClick(ExpandableListView parent, View v,
        int groupPosition, int childPosition, long id) {

    //get your radio here from the view v and do whatever you want

    return true;
}
</code>```

Body:
I have created a expandable list view and two radio buttons in it.
I want to get the value of the radio button which is selected when some button is pressed in my main Activity. My ExpandableListView is working properly but i am not able to get the radio button which is selected in main activity.

public class ExpandableMenuListAdapter  extends BaseExpandableListAdapter
 {
    private Context context;
    private List<String> listDataHeader;
    private HashMap<String,List<List<String>>> listHashMap;

    public ExpandableMenuListAdapter(Context context, List<String> listDataHeader, HashMap<String, List<List<String>>> listHashMap) {
        this.context = context;
        this.listDataHeader = listDataHeader;
        this.listHashMap = listHashMap;

    }

    @Override
    public int getGroupCount() {
        return listDataHeader.size();
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        return Objects.requireNonNull(listHashMap.get(listDataHeader.get(groupPosition))).size();
    }

    @Override
    public Object getGroup(int groupPosition) {
        return listDataHeader.get(groupPosition);
    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return Objects.requireNonNull(listHashMap.get(listDataHeader.get(groupPosition))).get(childPosition);
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    @Override
    public boolean hasStableIds() {
        return false;
    }

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        String headerTitle = (String)(getGroup(groupPosition)).toString();
        if (convertView==null)
        {
            LayoutInflater inflater =(LayoutInflater)this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.list_menu_days_group,null);

        }
        TextView lblListHeader = convertView.findViewById(R.id.list_days);
        lblListHeader.setTypeface(null, Typeface.BOLD);
        lblListHeader.setText(headerTitle);
        return convertView;
    }

    @Override
    public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
        List<String> childText = (List<String>) getChild(groupPosition,childPosition);
        if (convertView==null)
        {
            LayoutInflater inflater =(LayoutInflater)this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.list_menu_item,null);
        }
        RadioButton txtListChild = convertView.findViewById(R.id.menu_list_daily1);
        RadioButton txtListChild2 = convertView.findViewById(R.id.menu_list_daily2);
        txtListChild.setText(childText.get(0));
        txtListChild2.setText(childText.get(1));
        ViewsList.menu.add(convertView);

        return convertView;
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return false;
    }
}

Body:
Use onChildClick method in your code.This method is automatically called when you click on child item

@Override
public boolean onChildClick(ExpandableListView parent, View v,
        int groupPosition, int childPosition, long id) {

    //get your radio here from the view v and do whatever you want

    return true;
}


来源: stackexchange

问:
Password protected zip file using Python
I'm trying to password protect zip files that I'm creating in a python script but have not been able to figure out why when I try to unzip it does not accept the password that the script created.

```<code>#!/usr/bin/env python2.6
import subprocess, random, os

file = "test.csv"
s = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()?"
zipPass = "".join(random.sample(s,12))
print zipPass
devnull = open(os.devnull, 'w')
rc = subprocess.call("zip -P "+str(zipPass)+" "+str(file)+".zip "+str(file), shell=True, stdout=devnull, stderr=devnull)
</code>```

When I run the script and try to unzip I get the following;

```<code>user@server:/tmp/zip> zip.py
xxxxxxxxx
user@server:/tmp/zip> unzip test.csv.zip
Archive:  test.csv.zip
[test.csv.zip] test.csv password:
password incorrect--reenter:
</code>```

I've tried copying/pasting the password and also manually entering just to be sure.

Any ideas?

答: Tested your script worked for me. just to be sure , remove created zip file run script and check if it is zip file which created by your script. I said this because you didn't define path to store zip file, so it is possible your file is created somewhere else and you are looking to wrong one.</p>

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to password protect zip files that I'm creating in a python script but have not been able to figure out why when I try to unzip it does not accept the password that the script created.

#!/usr/bin/env python2.6
import subprocess, random, os

file = "test.csv"
s = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()?"
zipPass = "".join(random.sample(s,12))
print zipPass
devnull = open(os.devnull, 'w')
rc = subprocess.call("zip -P "+str(zipPass)+" "+str(file)+".zip "+str(file), shell=True, stdout=devnull, stderr=devnull)

When I run the script and try to unzip I get the following;

user@server:/tmp/zip> zip.py
xxxxxxxxx
user@server:/tmp/zip> unzip test.csv.zip
Archive:  test.csv.zip
[test.csv.zip] test.csv password:
password incorrect--reenter:

I've tried copying/pasting the password and also manually entering just to be sure.

Any ideas?


问:
$request returns different values depending on where I dump it
In my ReportController.php, my function receives Request $request, as below:

```<code>class ReportController extends Controller{
    public function store(Request $request)
    {
         \Log::info("Request content:");
         \Log::info($request);

         error_log("request:");
         error_log($request);

         $insertID = Report::create([
                    'action' => $request->action,
                    'reportID' => $request->reportID,
                    'incidentDate' => $request->incidentDate,
                    'who' => $request->who,
                    'location' => $request->location,
                    'description' => $request->details,
                    'submittedByName' => $request->submittedByName,
                    'submittedByMobile' => $request->submittedByMobile,
                    'submittedByEmail' => $request->submittedByEmail,
                    'attachments' => $attachments,
                    'attachmentCount' => $attachmentCount,
                    'request' => $request
                ])->id;
    }
}
</code>```

Strangely enough, the value of $request changes depending on where I dump/store them. For example, in my log file where I log using \Log::info($request), it displays something like:

```<code>[2019-05-28 17:35:27] local.INFO: array (
  'action' => 'TellUsMore',
  'reportID' => 'b19xr211gcbvc',
  'incidentDate' => '2019-05-29',
  'location' => 'ggg',
  'description' => 'gg',
  'suggestion' => 'sdfsdf',
  'files' =>
  array (
    0 =>
    Illuminate\Http\UploadedFile::__set_state(array(
       'test' => false,
       'originalName' => 'reports (1).xlsx',
       'mimeType' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
       'error' => 0,
       'hashName' => NULL,
    )),
    1 =>
    Illuminate\Http\UploadedFile::__set_state(array(
       'test' => false,
       'originalName' => 'love your parents - we\'re so busy growing up, we often forget that they\'re growing old.jpg',
       'mimeType' => 'image/jpeg',
       'error' => 0,
       'hashName' => NULL,
    )),
  ),
)
</code>```

but in my error_log($request) which dumps the value in console, it displays

```<code>[Wed May 29 01:35:27 2019] POST /api/report/store HTTP/1.1
Accept:          */*
Accept-Encoding: gzip, deflate
Cache-Control:   no-cache
Connection:      keep-alive
Content-Length:  25172
Content-Type:    multipart/form-data; boundary=--------------------------416520203821764707296428
Host:            localhost:8000
Postman-Token:   76adb08d-631e-4f10-9a5f-60bc8d015aed
User-Agent:      PostmanRuntime/7.6.0
</code>```

It's the same when I stored the $request value inside database. I meant to store the $request value that's being displayed as in my laravel log file, but instead it saved the value of $request as what's being displayed in my console.

What did I miss here?

答: error_log() calls $request->__toString(), your Log class calls var_export() for some reason. That's the difference ;)

Body:
In my ReportController.php, my function receives Request $request, as below:

class ReportController extends Controller{
    public function store(Request $request)
    {
         \Log::info("Request content:");
         \Log::info($request);

         error_log("request:");
         error_log($request);

         $insertID = Report::create([
                    'action' => $request->action,
                    'reportID' => $request->reportID,
                    'incidentDate' => $request->incidentDate,
                    'who' => $request->who,
                    'location' => $request->location,
                    'description' => $request->details,
                    'submittedByName' => $request->submittedByName,
                    'submittedByMobile' => $request->submittedByMobile,
                    'submittedByEmail' => $request->submittedByEmail,
                    'attachments' => $attachments,
                    'attachmentCount' => $attachmentCount,
                    'request' => $request
                ])->id;
    }
}

Strangely enough, the value of $request changes depending on where I dump/store them. For example, in my log file where I log using \Log::info($request), it displays something like:

[2019-05-28 17:35:27] local.INFO: array (
  'action' => 'TellUsMore',
  'reportID' => 'b19xr211gcbvc',
  'incidentDate' => '2019-05-29',
  'location' => 'ggg',
  'description' => 'gg',
  'suggestion' => 'sdfsdf',
  'files' =>
  array (
    0 =>
    Illuminate\Http\UploadedFile::__set_state(array(
       'test' => false,
       'originalName' => 'reports (1).xlsx',
       'mimeType' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
       'error' => 0,
       'hashName' => NULL,
    )),
    1 =>
    Illuminate\Http\UploadedFile::__set_state(array(
       'test' => false,
       'originalName' => 'love your parents - we\'re so busy growing up, we often forget that they\'re growing old.jpg',
       'mimeType' => 'image/jpeg',
       'error' => 0,
       'hashName' => NULL,
    )),
  ),
)

but in my error_log($request) which dumps the value in console, it displays

[Wed May 29 01:35:27 2019] POST /api/report/store HTTP/1.1
Accept:          */*
Accept-Encoding: gzip, deflate
Cache-Control:   no-cache
Connection:      keep-alive
Content-Length:  25172
Content-Type:    multipart/form-data; boundary=--------------------------416520203821764707296428
Host:            localhost:8000
Postman-Token:   76adb08d-631e-4f10-9a5f-60bc8d015aed
User-Agent:      PostmanRuntime/7.6.0

It's the same when I stored the $request value inside database. I meant to store the $request value that's being displayed as in my laravel log file, but instead it saved the value of $request as what's being displayed in my console.

What did I miss here?


问:
Applying a simple function to CSV and save multiple csv files
I am trying to replicate the data by multiplying every value with a range of values and save the results as CSV. </p>

<p>I have created a function "Replicate_Data" which takes the input numpy array and multiply with a random value between a range. What is the best way to create a 100 files and save as P3D1 , P4D1 and so on. </p>

```<code>def Replicate_Data(data: np.ndarray) -> np.ndarray:
    Rep_factor= random.uniform(-3,7)
    data1 = data * Rep_factor
    return data1

P2D1 = Replicate_Data(P1D1)
np.savetxt("P2D1.csv", P2D1, delimiter="," , dtype = complex)
</code>```

答:
Here is an example you can use as reference.

I generate toy data named toy, then I make n random values using np.random.uniform and call it randos, then I multiply these two objects to form out using numpy broadcasting. You could also do this multiplication in a loop (the same one you save in, in fact): depending on the size of your input array it could be very memory intensive as I've written it. A more complete answer probably depends on the shape of your input data.

```<code>import numpy as np
toy = np.random.random(size=(2,2)) # a toy input array
n = 100 # number of random values
randos = np.random.uniform(-3,7,size=n) # generate 100 uniform randoms
# now multiply all elements in toy by the randoms in randos
out = toy[None,...]*randos[...,None,None] # this depends on the shape.
# this will work only if toy has two dimensions. Otherwise requires modification
# it will take a lot of memory... 100*toy.nbytes worth

# now save in the loop..
for i,o in enumerate(out):
    name = 'P{}D1'.format(str(i+1))
    np.savetxt(name,o,delimiter=",")

# a second way without the broadcasting (slow, better on memory)
# more like 2*toy.nbytes
#for i,r in enumerate(randos):
#    name = 'P{}D1'.format(str(i+1))
#    np.savetxt(name,r*toy,delimiter=",")
</code>```

Body:
I am trying to replicate the data by multiplying every value with a range of values and save the results as CSV.

I have created a function "Replicate_Data" which takes the input numpy array and multiply with a random value between a range. What is the best way to create a 100 files and save as P3D1 , P4D1 and so on.

def Replicate_Data(data: np.ndarray) -> np.ndarray:
    Rep_factor= random.uniform(-3,7)
    data1 = data * Rep_factor
    return data1

P2D1 = Replicate_Data(P1D1)
np.savetxt("P2D1.csv", P2D1, delimiter="," , dtype = complex)

Body:
Here is an example you can use as reference.

I generate toy data named toy, then I make n random values using np.random.uniform and call it randos, then I multiply these two objects to form out using numpy broadcasting. You could also do this multiplication in a loop (the same one you save in, in fact): depending on the size of your input array it could be very memory intensive as I've written it. A more complete answer probably depends on the shape of your input data.

import numpy as np
toy = np.random.random(size=(2,2)) # a toy input array
n = 100 # number of random values
randos = np.random.uniform(-3,7,size=n) # generate 100 uniform randoms
# now multiply all elements in toy by the randoms in randos
out = toy[None,...]*randos[...,None,None] # this depends on the shape.
# this will work only if toy has two dimensions. Otherwise requires modification
# it will take a lot of memory... 100*toy.nbytes worth

# now save in the loop..
for i,o in enumerate(out):
    name = 'P{}D1'.format(str(i+1))
    np.savetxt(name,o,delimiter=",")

# a second way without the broadcasting (slow, better on memory)
# more like 2*toy.nbytes
#for i,r in enumerate(randos):
#    name = 'P{}D1'.format(str(i+1))
#    np.savetxt(name,r*toy,delimiter=",")


问:
Change widget state in list remotely
I am currently working on a GridView that builds a Container widget for every item in a list.

```<code>new GridView.count(
        crossAxisCount: 2,
        childAspectRatio: 1.3,
        children: cardSet.map((card){
        Color containerColor = Colors.blue;
        return new GestureDetector(
          onTap: (){
          setState(){
           containerColor = Colors.green;
           //This part is unsolved:
           containerColor.of(matchingWidget) = Colors.green;
          };
          }
          child: new Container(
            color: containerColor,
          ),
        );
          }).toList()),
</code>```

So here is my problem: I would like the user to find matching values in the GridView, and since each Container holds one value each, selecting two values with onTap either results in matching values or non-matching values. In both cases, the color of the two selected Container widgets is supposed to change.

Changing the last selected Container widget is easy, just by changing the color property with setState(), how do I change the color of the previously selected, 'matching' container though? To use the image, how would I change both the color of the 'two' and the '2' container simultaneously, after the user tapped on the matching 'two' container?

Do I use a key property to store a reference to the 'matching' widget or is there another possibility?

答:
I made class myCard as below:

```<code>class myCard {
  String key;
  Color color;
  String match;

  myCard( {
    this.key,
    this.color,
    this.match
  });
}
</code>```

And, created cardSet list as below:

```<code>class _MyHomePageState extends State<MyHomePage> {
  var cardSet = [
    myCard(key:"two", color:Colors.blue, match:"2"),
    myCard(key:"3", color:Colors.blue, match:"three"),
    myCard(key:"one", color:Colors.blue, match:"1"),
    myCard(key:"2", color:Colors.blue, match:"two"),
    myCard(key:"10", color:Colors.blue, match:"ten"),
    myCard(key:"ten", color:Colors.blue, match:"10"),
    myCard(key:"three", color:Colors.blue, match:"3"),
    myCard(key:"1", color:Colors.blue, match:"one"),
  ];
</code>```

I think you can make it by your style. Actually, We can call myCard as model.

And I made getMatchCard function finding out related card.

```<code>  myCard getMatchCard(card){
    return cardSet.where((_card)=>_card.match==card.key).toList()[0];
  }
</code>```

Finally, I set a color of card in setState by myColor's attributes.
containerColor was local variable and its data was not able to be kept. So, I thought that we need member variables to keep data after creating all GestureDetector.

```<code>child: new GridView.count(
    crossAxisCount: 2,
    childAspectRatio: 1.3,
    children: cardSet.map((card){
      return new GestureDetector(
        onTap: (){
          setState((){
            card.color = Colors.green; // a color of Tapped card
            getMatchCard(card).color = Colors.green; // a color of related card
          });
        },
         child: new Container(
           color: card.color,
           child:Text(card.key) // I set the text in myself because I can not see your cardSet data.
         ),
      );
    }).toList()),
</code>```

You know, Flutter derives the reactive programming. So, Separating model and view by state is comfortable.

It works well. Please refer the image as below:

Title: Change widget state in list remotely

Body:
I am currently working on a GridView that builds a Container widget for every item in a list.

new GridView.count(
        crossAxisCount: 2,
        childAspectRatio: 1.3,
        children: cardSet.map((card){
        Color containerColor = Colors.blue;
        return new GestureDetector(
          onTap: (){
          setState(){
           containerColor = Colors.green;
           //This part is unsolved:
           containerColor.of(matchingWidget) = Colors.green;
          };
          }
          child: new Container(
            color: containerColor,
          ),
        );
          }).toList()),

So here is my problem: I would like the user to find matching values in the GridView, and since each Container holds one value each, selecting two values with onTap either results in matching values or non-matching values. In both cases, the color of the two selected Container widgets is supposed to change.

Changing the last selected Container widget is easy, just by changing the color property with setState(), how do I change the color of the previously selected, 'matching' container though? To use the image, how would I change both the color of the 'two' and the '2' container simultaneously, after the user tapped on the matching 'two' container?

Do I use a key property to store a reference to the 'matching' widget or is there another possibility?

Body:
I made class myCard as below:

class myCard {
  String key;
  Color color;
  String match;

  myCard( {
    this.key,
    this.color,
    this.match
  });
}

And, created cardSet list as below:

class _MyHomePageState extends State<MyHomePage> {
  var cardSet = [
    myCard(key:"two", color:Colors.blue, match:"2"),
    myCard(key:"3", color:Colors.blue, match:"three"),
    myCard(key:"one", color:Colors.blue, match:"1"),
    myCard(key:"2", color:Colors.blue, match:"two"),
    myCard(key:"10", color:Colors.blue, match:"ten"),
    myCard(key:"ten", color:Colors.blue, match:"10"),
    myCard(key:"three", color:Colors.blue, match:"3"),
    myCard(key:"1", color:Colors.blue, match:"one"),
  ];

I think you can make it by your style. Actually, We can call myCard as model.

And I made getMatchCard function finding out related card.

  myCard getMatchCard(card){
    return cardSet.where((_card)=>_card.match==card.key).toList()[0];
  }

Finally, I set a color of card in setState by myColor's attributes.
containerColor was local variable and its data was not able to be kept. So, I thought that we need member variables to keep data after creating all GestureDetector.

child: new GridView.count(
    crossAxisCount: 2,
    childAspectRatio: 1.3,
    children: cardSet.map((card){
      return new GestureDetector(
        onTap: (){
          setState((){
            card.color = Colors.green; // a color of Tapped card
            getMatchCard(card).color = Colors.green; // a color of related card
          });
        },
         child: new Container(
           color: card.color,
           child:Text(card.key) // I set the text in myself because I can not see your cardSet data.
         ),
      );
    }).toList()),

You know, Flutter derives the reactive programming. So, Separating model and view by state is comfortable.

It works well. Please refer the image as below:


问:
Collect NGINX access.log statistics to Prometheus
There is nginx web server, that serves API calls from different User-Agents. I want to parse nginx logs and collect statistics about API calls from different User-Agents.

I'm going to write python script to parse nginx access.log like this https://gist.github.com/sysdig-blog/22ef4c07714b1a34fe20dac11a80c4e2#file-prometheus-metrics-python-py

Is there more suitable solution?

答:
When an application doesn't expose whitebox monitoring endpoints, parsing the logs is the only solution.

From there, you have multiple choices depending on the scale and the budget of your setup:

centralizing logs (in ES by example) using a sidecar like Filebeat to parse and ship them. You can then make queries  to export statistics

log parsing that expose statistics: fluentd, telegraf, mtail are good examples

regular executions of a script that dump the data in a prom file to be collected by a node exporter is also a cheap solution

Rolling your own script would be a last resort: if you need statistics you cannot get from of the shelve tools or statistics that need context to be extracted. But it comes at the cost of handling painful scenarios; in your case, following the file when it rolls can be an issue.


问:
Entity Framework Core Assign role to user after created
i would like to know how can i associate a specific role to a user when he is created

I have this on my create User page

```<code>    public async Task<IActionResult> OnPostAsync()
    {
        if (!ModelState.IsValid)
        {
            return Page();
        }

        _context.Users.Add(User);

        await _context.SaveChangesAsync();

        _toastNotification.AddSuccessToastMessage("Utilizador Adicionado com sucesso");

        return RedirectToPage("./Index");
    }
</code>```

I have tried on the model

```<code>    public User()
    {
        IsActivo = true;
        UserRoles.Add(new UserRole { RoleId = 4 });
    }
</code>```

this does not work unfortunely.

答:
Ok I took some time rereading entity framework tutorials and this worked for me</p>

```<code>   public async Task<IActionResult> OnPostAsync()
   {
        if (!ModelState.IsValid)
        {
            return Page();
        }

        _context.Users.Add(User);
        _context.UserRoles.Add(new UserRole { User = User, Role = _context.Roles.FirstOrDefault(r => r.Nome == "User")});

        await _context.SaveChangesAsync();

        _toastNotification.AddSuccessToastMessage("Utilizador Adicionado com sucesso");

        return RedirectToPage("./Index");
    }
</code>```

Body:
i would like to know how can i associate a specific role to a user when he is created

I have this on my create User page

    public async Task<IActionResult> OnPostAsync()
    {
        if (!ModelState.IsValid)
        {
            return Page();
        }

        _context.Users.Add(User);

        await _context.SaveChangesAsync();

        _toastNotification.AddSuccessToastMessage("Utilizador Adicionado com sucesso");

        return RedirectToPage("./Index");
    }

I have tried on the model

    public User()
    {
        IsActivo = true;
        UserRoles.Add(new UserRole { RoleId = 4 });
    }

this does not work unfortunely.

Body:
Ok I took some time rereading entity framework tutorials and this worked for me

   public async Task<IActionResult> OnPostAsync()
   {
        if (!ModelState.IsValid)
        {
            return Page();
        }

        _context.Users.Add(User);
        _context.UserRoles.Add(new UserRole { User = User, Role = _context.Roles.FirstOrDefault(r => r.Nome == "User")});

        await _context.SaveChangesAsync();

        _toastNotification.AddSuccessToastMessage("Utilizador Adicionado com sucesso");

        return RedirectToPage("./Index");
    }


问:
Use lambda function trigger at S3 create file to run c++ code on Cloud9
I want to run a c++ code to process a image that is stored on Aws S3.
Can it be done? If yes... how?</p>

```<code>import boto3
region = 'us-east-1'
instances = ['i-08f007160c7ddd4ba']

def lambda_handler(event, context):
    ec2 = boto3.client('ec2', region_name=region)
    ec2.stop_instances(InstanceIds=instances)
</code>```

答:
Yes, it can be done. There are a lot of tutorials out there, here is an official tutorial on S3 + Lambda integration

To summarize what's required:

Deploy the Lambda that will process the image(s)

Create an S3 bucket

Create an event trigger in S3 for the Lambda

That's it, once you have this, the moment you upload the file the Lambda will get triggered with an event that contains the file prefix (file name essentially), and then your Lambda can get the file (based on the prefix in the event) and process it

Body:
I want to run a c++ code to process a image that is stored on Aws S3.
Can it be done? If yes... how?

import boto3
region = 'us-east-1'
instances = ['i-08f007160c7ddd4ba']

def lambda_handler(event, context):
    ec2 = boto3.client('ec2', region_name=region)
    ec2.stop_instances(InstanceIds=instances)


问:
Adding items into an array - Separately
Goal: Click a button and have ingredients added to an array as separate items.

Current Set Up:

```<code>    <% currentUser.ingredients.forEach(function(items){ %>
   <p class='ingredients'>  <%= items %> </p>
    <% }) %>
</code>```

This gives: Blueberries Mango Lemon Juice

I'd then like to be able to add the ingredients as separate items to an array by clicking a button:

```<code>var allIngredients = []

$("#makeList").click(function() {

allIngredients.push($(".ingredients").text())
console.log(allIngredients)

});
</code>```

This prints ["Blueberrys Mango Lemon Juice"]

The issue is it is all one item not separate items.

What to I need to change to make them separate items?

答:
A mere split or looping over text nodes wouldn't give expected result if a value can be multi-word. For a robust solution, surround the rendered values by some html tag

<% currentUser.ingredients.forEach(function(items){ %>

  <%= items %>

<% }) %>
```

<pre class="lang-js prettyprint-override"><code>var allIngredients = []

$("#makeList").click(function() {

    $(".ingredients").find('.ingredient').each(function() {
        allIngredients.push($(this).text());
    });
    console.log(allIngredients)

});
</code>```

Title: Adding items into an array - Separately

Body:
Goal: Click a button and have ingredients added to an array as separate items.

Current Set Up:

    <% currentUser.ingredients.forEach(function(items){ %>

  <%= items %>

    <% }) %>

This gives: Blueberries Mango Lemon Juice

I'd then like to be able to add the ingredients as separate items to an array by clicking a button:

var allIngredients = []

$("#makeList").click(function() {

allIngredients.push($(".ingredients").text())
console.log(allIngredients)

});

This prints ["Blueberrys Mango Lemon Juice"]

The issue is it is all one item not separate items.

What to I need to change to make them separate items?

Body:
A mere split or looping over text nodes wouldn't give expected result if a value can be multi-word. For a robust solution, surround the rendered values by some html tag

<% currentUser.ingredients.forEach(function(items){ %>
   <p class='ingredients'>  <span class="ingredient"><%= items %></span> </p>
<% }) %>

var allIngredients = []

$("#makeList").click(function() {

    $(".ingredients").find('.ingredient').each(function() {
        allIngredients.push($(this).text());
    });
    console.log(allIngredients)

});


问:
Sitecore login fails when user clicks remember me
I am trying to resolve an issue where users get a stack trace if they click "remember me" on the Sitecore login page. </p>

<p>I can only replicate the issue if I use an incorrect login. </p>

```<code>Server Error in '/' Application.

userName

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: userName

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[InvalidOperationException: userName]
   Sitecore.Caching.UserProfile.UserProfileCache.RemoveUser(String userName) +223
   Sitecore.Caching.CacheManager.ClearSecurityCache(String userName) +32

[TargetInvocationException: Exception has been thrown by the target of an invocation.]
   System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) +0
   System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) +76
   System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +211
   System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters) +35
   Sitecore.Nexus.Pipelines.NexusPipelineApi.Resume(PipelineArgs args, Pipeline pipeline) +379
   Sitecore.Pipelines.Pipeline.Start(String pipelineName, PipelineArgs args, Boolean atomic) +197
   Sitecore.sitecore.login.LoginPage.Login_LoggingIn(Object sender, LoginCancelEventArgs e) +`enter code here`377
   System.Web.UI.WebControls.Login.AttemptLogin() +79
   System.Web.UI.WebControls.Login.OnBubbleEvent(Object source, EventArgs e) +93
   System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +84
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3804
</code>```

答:
In new Sitecore versions, in order to improve the security of the login page, Sitecore recommends to disable the Remember me check box:

Open sitecore.config file

Set Login.DisableRememberMe setting to true

Note, that this also ignores any existing Remember Me cookies and all users will have to re-login again.

Read more details here.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to resolve an issue where users get a stack trace if they click "remember me" on the Sitecore login page.

I can only replicate the issue if I use an incorrect login.

Server Error in '/' Application.

userName

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: userName

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[InvalidOperationException: userName]
   Sitecore.Caching.UserProfile.UserProfileCache.RemoveUser(String userName) +223
   Sitecore.Caching.CacheManager.ClearSecurityCache(String userName) +32

[TargetInvocationException: Exception has been thrown by the target of an invocation.]
   System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) +0
   System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) +76
   System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +211
   System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters) +35
   Sitecore.Nexus.Pipelines.NexusPipelineApi.Resume(PipelineArgs args, Pipeline pipeline) +379
   Sitecore.Pipelines.Pipeline.Start(String pipelineName, PipelineArgs args, Boolean atomic) +197
   Sitecore.sitecore.login.LoginPage.Login_LoggingIn(Object sender, LoginCancelEventArgs e) +`enter code here`377
   System.Web.UI.WebControls.Login.AttemptLogin() +79
   System.Web.UI.WebControls.Login.OnBubbleEvent(Object source, EventArgs e) +93
   System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +84
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3804


问:
in VHDL, how to check if file exists before opening it?
In Verilog, I can check if a file exists by opening the file and then checking if the file descriptor is zero, and if it is not to assume the file doesn't exist.  For example, as follows:

```<code>    module testbench;

    function file_exists;
        input [80*8:0] filename;
        integer        file;
        integer        error;
    begin
        file = $fopen(filename, "r");
        if (!file) begin
           $display("\nFile Open Failed with Error Code = %x", error);
           file_exists = 0;
        end
        else begin
           $fclose(file);
           file_exists = 1;
        end
    end
    endfunction

    integer x;
    initial begin
       x = file_exists("sdfsdf.txt");
       $display("x: %0b", x);
    end

    endmodule
</code>```

How can I do the same thing in vhdl?

答:
When you open a file, for example:

```<code>file_open(status, file_handle, “my_file.txt”, read_mode);
</code>```

You get a status of type file_open_status. It can have a number of values: open_ok, status_error, name_error and mode_error. You'll get name_error if the file isn't found

Body:
In Verilog, I can check if a file exists by opening the file and then checking if the file descriptor is zero, and if it is not to assume the file doesn't exist.  For example, as follows:

    module testbench;

    function file_exists;
        input [80*8:0] filename;
        integer        file;
        integer        error;
    begin
        file = $fopen(filename, "r");
        if (!file) begin
           $display("\nFile Open Failed with Error Code = %x", error);
           file_exists = 0;
        end
        else begin
           $fclose(file);
           file_exists = 1;
        end
    end
    endfunction

    integer x;
    initial begin
       x = file_exists("sdfsdf.txt");
       $display("x: %0b", x);
    end

    endmodule

How can I do the same thing in vhdl?

Body:
When you open a file, for example:

file_open(status, file_handle, “my_file.txt”, read_mode);

You get a status of type file_open_status. It can have a number of values: open_ok, status_error, name_error and mode_error. You'll get name_error if the file isn't found


问:
Are there any ways other than authentication to tell the users apart?
In my app, the user can select a Youtube video that will be downloaded to MEDIA_ROOT folder and then also made available for the user to download.

Whenever the user chooses another video to download, the previous one is deleted from MEDIA_ROOT. So at any given moment there is only one video sitting in the MEDIA_ROOT folder for a particular user.

Is there any way - apart from implementing user authentication and associating the downloaded files with a user through foreign key, which I feel is an overkill for only this task - of telling the users apart whenever such download request is being made, so that one user's request does not cause the deletion of the file downloaded by some other user (as all the files sit in the same MEDIA_ROOT folder)?

答:
You can use cookies to uniquely identify users. Web browsers will keep sending that cookie value to your web server for as long as the web browser's cookie store is not cleared. Make sure to generate an hard to guess value for the web browser to store and you to identify with so that one cannot bruteforce that value and get access to data meant for other users. The common way is to generate say a 32 characters string from a CSPRNG.

You can have a go at this question to find out how to set cookies in Python Django: Django Cookies, how can I set them?

I would personally use built in Django Cookie Sessions: https://docs.djangoproject.com/en/2.2/topics/http/sessions/#using-cookie-based-sessions


问:
How can I view the Git history in Visual Studio Code?
I can execute various Git commands from Visual Studio Code, however I couldn't find a way to visualize the history.</p>

答: I would recommend using Git Graph extension.</p>


问:
Javascript automatic form submission
I took this quick script from another post on StackOverflow, but it doesn't seem to work on my form. It just throws an error saying 'object expected'. Can anyone help me fix it.

```<code><html>
<head></head>
<body onLoad="document.forms[0].submit()">
    <form name="EPDQForm" method="post" action="mypage.aspx" >
        <input name="item" type="hidden" value="data">
    </form>
</body>
</html>
</code>```

EDIT:

This is the exact page code (I removed most of it for displaying on here):

```<code><html>

    <head></head>

    <body onLoad="document.forms[0].submit()">

        <form id="myform" name="myform" method="post" action="https://secure2.mde.epdq.co.uk/cgi-bin/CcxBarclaysEpdq.e">

            <input name="epdqdata" type="hidden" value="972">
            <input name="returnurl" type="hidden" value="http://www.xxxx.co.uk/Secure/EPDQReturn.aspx">
            <input name="merchantdisplayname" type="hidden" value="xxxxxx">
            <input name="submit" type="hidden" value="purchase">
            <input name="shipping" type="hidden" value="0.00">
            <input name="baddr1" type="hidden" value="152 Smith St">
            <input name="baddr2" type="hidden" value="">
            <input name="bcity" type="hidden" value="Manchester">
            <input name="bcountry" type="hidden" value="UK">
            <input name="bpostalcode" type="hidden" value="M4 6DH">
            <input name="email" type="hidden" value="xxxx@xxxx.co.uk">
            <input name="saddr1" type="hidden" value="152 Smith St">
            <input name="scity" type="hidden" value="Manchester">
            <input name="scountyprovince" type="hidden" value="Alderney">
            <input name="scountry" type="hidden" value="UK">
            <input name="spostalcode" type="hidden" value="M4 5GG">

        </form>

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

This code shows the error. And I don't see why. In firefox it says:

```<code>document.forms[0].submit is not a function
</code>```

答:
Ok, the problem is in this part : input name="submit" type="hidden" value="purchase".

Submit input has the same name as the form function.
If you replace the name 'submit' by other name (submit1 as example) it should be working as a charm. :-)

Good luck.

Title: Javascript automatic form submission

Body:
I took this quick script from another post on StackOverflow, but it doesn't seem to work on my form. It just throws an error saying 'object expected'. Can anyone help me fix it.

    <form name="EPDQForm" method="post" action="mypage.aspx" >
        <input name="item" type="hidden" value="data">
    </form>

EDIT:

This is the exact page code (I removed most of it for displaying on here):

        <form id="myform" name="myform" method="post" action="https://secure2.mde.epdq.co.uk/cgi-bin/CcxBarclaysEpdq.e">

            <input name="epdqdata" type="hidden" value="972">
            <input name="returnurl" type="hidden" value="http://www.xxxx.co.uk/Secure/EPDQReturn.aspx">
            <input name="merchantdisplayname" type="hidden" value="xxxxxx">
            <input name="submit" type="hidden" value="purchase">
            <input name="shipping" type="hidden" value="0.00">
            <input name="baddr1" type="hidden" value="152 Smith St">
            <input name="baddr2" type="hidden" value="">
            <input name="bcity" type="hidden" value="Manchester">
            <input name="bcountry" type="hidden" value="UK">
            <input name="bpostalcode" type="hidden" value="M4 6DH">
            <input name="email" type="hidden" value="xxxx@xxxx.co.uk">
            <input name="saddr1" type="hidden" value="152 Smith St">
            <input name="scity" type="hidden" value="Manchester">
            <input name="scountyprovince" type="hidden" value="Alderney">
            <input name="scountry" type="hidden" value="UK">
            <input name="spostalcode" type="hidden" value="M4 5GG">

        </form>

This code shows the error. And I don't see why. In firefox it says:

document.forms[0].submit is not a function


问:
How could I show the uptime in the console that continues to update as the time changes?
I am creating a Discord bot using Node and Discord.js and I want to show the uptime in the console but... I want it to continuously change as time changes.

I have tried and have succeeded in the past of making some loop using process.stdout.write but I can't remember how.

I have tried...

```<code>process.stdout.write(process.uptime());
process.stdout.clear();
</code>```

and it didn't work.

I expect the uptime of the process to show up in the console as...

Uptime: 0D 0H 0M 1S

and as time changes is I want it to update that line and not make another.

答:
You can use setInterval to initiate a loop and update the line periodically:

```<code>setInterval(() => {
  process.stdout.cursorTo(0); // Stay on the same line
  let uptime = Math.floor(process.uptime());
  process.stdout.write('Uptime: ' + uptime + 'S');
}, 1000)
</code>```

I let you make the time conversion in minutes, hours and days for the display.

Credit for cursorTo() method: michelek

Body:
I am creating a Discord bot using Node and Discord.js and I want to show the uptime in the console but... I want it to continuously change as time changes.

I have tried and have succeeded in the past of making some loop using process.stdout.write but I can't remember how.

I have tried...

process.stdout.write(process.uptime());
process.stdout.clear();

and it didn't work.

I expect the uptime of the process to show up in the console as...

Uptime: 0D 0H 0M 1S

and as time changes is I want it to update that line and not make another.

Body:
You can use setInterval to initiate a loop and update the line periodically:

setInterval(() => {
  process.stdout.cursorTo(0); // Stay on the same line
  let uptime = Math.floor(process.uptime());
  process.stdout.write('Uptime: ' + uptime + 'S');
}, 1000)

I let you make the time conversion in minutes, hours and days for the display.

Credit for cursorTo() method: michelek


问:
Calculate text similarity between lists using CountVectorizer, TFIDFVectorizer
I would like to see similarity between lists using TFIDFVectorizer and CountVectorizer.

I have lists like below:

list1 = [['i','love','machine','learning','its','awesome'],
         ['i', 'love', 'coding', 'in', 'python'],
         ['i', 'love', 'building', 'chatbots']]
list2 = ['i', 'love', 'chatbots']
```

I would like to see similarity between list1[0] and list2, list1[1] and list2 , list1[2] and list2.

Expecting output should be like [0.99 , 0.67, 0.54]

答:
From the docs TfidfVectorizer is:
"Equivalent to CountVectorizer followed by TfidfTransformer."

Here is the code

```<code>from sklearn.feature_extraction.text import TfidfVectorizer

corpus = [
    "i love machine learning its awesome",
    "i love coding in python",
    "i love building chatbots",
    "i love chatbots"
]
vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(corpus)
# print(vectorizer.get_feature_names())
arr = X.toarray()
</code>```

And the answers using cosine similarity

```<code># similarity of yours `list1[0] and list2`
np.dot(arr[0], arr[3]) # gives ~0.139
# similarity of yours `list1[1] and list2`
np.dot(arr[1], arr[3]) # gives ~0.159
# similarity of yours `list1[2] and list2`
np.dot(arr[2], arr[3]) # gives ~0.687
</code>```

or using jaccard similarity and CountVectorizer I think is closer to what you are expecting

```<code>from sklearn.metrics import jaccard_score
from sklearn.feature_extraction.text import CountVectorizer
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(corpus)
arr = X.toarray()

jaccard_score(arr[0], arr[3]) # gives 0.5
jaccard_score(arr[1], arr[3]) # gives 0.6
jaccard_score(arr[2], arr[3]) # gives 0.9
</code>```

Body:
I would like to see similarity between lists using TFIDFVectorizer and CountVectorizer.

I have lists like below:

list1 = [['i','love','machine','learning','its','awesome'],
         ['i', 'love', 'coding', 'in', 'python'],
         ['i', 'love', 'building', 'chatbots']]
list2 = ['i', 'love', 'chatbots']

I would like to see similarity between list1[0] and list2, list1[1] and list2 , list1[2] and list2.

Expecting output should be like [0.99 , 0.67, 0.54]

Body:
From the docs TfidfVectorizer is:
"Equivalent to CountVectorizer followed by TfidfTransformer."

Here is the code

from sklearn.feature_extraction.text import TfidfVectorizer

corpus = [
    "i love machine learning its awesome",
    "i love coding in python",
    "i love building chatbots",
    "i love chatbots"
]
vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(corpus)
# print(vectorizer.get_feature_names())
arr = X.toarray()

And the answers using cosine similarity

# similarity of yours `list1[0] and list2`
np.dot(arr[0], arr[3]) # gives ~0.139
# similarity of yours `list1[1] and list2`
np.dot(arr[1], arr[3]) # gives ~0.159
# similarity of yours `list1[2] and list2`
np.dot(arr[2], arr[3]) # gives ~0.687

or using jaccard similarity and CountVectorizer I think is closer to what you are expecting

from sklearn.metrics import jaccard_score
from sklearn.feature_extraction.text import CountVectorizer
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(corpus)
arr = X.toarray()

jaccard_score(arr[0], arr[3]) # gives 0.5
jaccard_score(arr[1], arr[3]) # gives 0.6
jaccard_score(arr[2], arr[3]) # gives 0.9


问:
Maven local repo in a common global directory for multiple parallel execution
I have a machine in which multiple parallel maven execution happen. Each execution executes the below command in a separate workspace directory

mvn -f main/pom.xml clean package -DskipTests -T 6

Can someone let me know should I use a separate maven local repo path (-Dmaven.repo.local=$MAVEN_REPO) for each execution or I can use a common .m2 directory for all parallel runs? What is the common practice followed?

Maven Version 3.5

Java 8

答:
This has been discsussed in maven user mailing list also. Summary of the discussion

Hello,

It is the other way around, there might be situations where one job
  relies on the installed artifacts from the other, in this case you
  would need a shared Repo. It is however bad style. In all other cases
  you can use a executor- or even workspace-local local repository if
  you have enough space.

The advantage of avoiding concurrent access is that you get less
  influences from one job to the other (especially if you work with
  snapshots or multiple different upstream artifacts with same version
  in different Repos) and that there is no concurrent downloads (which
  in itself sometimes leads to checksum errors).

Gruss Bernd


问:
overriding the equals method in java
"Let’s implement the equals method for a Stamp class.
You need to override the equals method of the Object class.
Now you have a slight problem.
The Object class knows nothing about stamps, so
it declares the otherObject
parameter variable of the equals method to have the type
Object. When overriding the method, you are not allowed to change the type of the parameter variable."

Here, it says that we are not allowed to change type of the parameter variable.
However, when I use the below code, it gives me the correct result.

```<code>public class Stamps
{
  private String color;
  private int value;

  public Stamps(String color, int value)
  {
    this.color=color;
    this.value=value;
  }

    public boolean equals(Stamps other)
    {
       return color.equals(other.color)
            && value== other.value;
    }
}

public class Main
{
     public static void main(String[] args)
     {
          Stamps stamp1 = new Stamps("red",10);
          Stamps stamp2 = new Stamps("green",10);

        System.out.println(stamp1.equals(stamp2));
     }
}
</code>```

Here, I'm not overriding the equals() method inherited from Object class since parameter types are different. So, instead of using my code, shouldn't it use the one inherited from Object class ?

答:
The java.lang.Object equals method takes an Object parameter.  You aren't overriding it if you make it take a Stamp.

Joshua Bloch tells you how to override equals and hashCode properly in Effective Java chapter 3.

Follow his recommendation rigorously.  Your posted code isn't correct.  You don't even attempt hashCode. They should be done in pairs.

Title: overriding the equals method in java

Body:
"Let’s implement the equals method for a Stamp class.
You need to override the equals method of the Object class.
Now you have a slight problem.
The Object class knows nothing about stamps, so
it declares the otherObject
parameter variable of the equals method to have the type
Object. When overriding the method, you are not allowed to change the type of the parameter variable."

Here, it says that we are not allowed to change type of the parameter variable.
However, when I use the below code, it gives me the correct result.

public class Stamps
{
  private String color;
  private int value;

  public Stamps(String color, int value)
  {
    this.color=color;
    this.value=value;
  }

    public boolean equals(Stamps other)
    {
       return color.equals(other.color)
            && value== other.value;
    }
}

public class Main
{
     public static void main(String[] args)
     {
          Stamps stamp1 = new Stamps("red",10);
          Stamps stamp2 = new Stamps("green",10);

        System.out.println(stamp1.equals(stamp2));
     }
}

Here, I'm not overriding the equals() method inherited from Object class since parameter types are different. So, instead of using my code, shouldn't it use the one inherited from Object class ?


问:
Error connecting to mongoDB database from dart web
I'm unable to connect to a mongodb database from a dart application.
I can connect only from terminal and from Compass

I've tried to run a simple example of connecting mongodb database from Dart (see the simple code below):

```<code>import 'package:mongo_dart/mongo_dart.dart';

void main() async {

Db db = new Db("mongodb://localhost:27017/test");
await db.open();
print('Connection succeeded!');
//the test database is accessible from Compass or terminal
//localhost:27017 works well
}

await db.open() throws that error:
dart_sdk.js:5822 Uncaught Error: Unsupported operation: Socket
constructor
at Object.dart.throw (dart_sdk.js:4537)
at Function._connect (dart_sdk.js:52279)
at Function.connect (dart_sdk.js:52264)
at mongo_dart._Connection.new.connect (connection.dart:56)
at mongo_dart._ConnectionManager.new._connect
(connection_manager.dart:23)
at _connect.next (<anonymous>)
at runBody (dart_sdk.js:22269)
at Object.async.async (dart_sdk.js:22297)
at mongo_dart._ConnectionManager.new.[_connect]
(connection_manager.dart:22)
at connection_manager.dart:58
at dart_sdk.js:23887
</code>```

答:
mongo_dart.dart imports dart:io and therefore cannot be used on the web. This package mentions that is is server side.

With the latest build_web_compilers this should be a build time error instead of a runtime error.

You'll need to find, or write, a package for mongoDB that uses dart:html instead of dart:io.

Body:
I'm unable to connect to a mongodb database from a dart application.
I can connect only from terminal and from Compass

I've tried to run a simple example of connecting mongodb database from Dart (see the simple code below):

import 'package:mongo_dart/mongo_dart.dart';

void main() async {

Db db = new Db("mongodb://localhost:27017/test");
await db.open();
print('Connection succeeded!');
//the test database is accessible from Compass or terminal
//localhost:27017 works well
}

await db.open() throws that error:
dart_sdk.js:5822 Uncaught Error: Unsupported operation: Socket
constructor
at Object.dart.throw (dart_sdk.js:4537)
at Function._connect (dart_sdk.js:52279)
at Function.connect (dart_sdk.js:52264)
at mongo_dart._Connection.new.connect (connection.dart:56)
at mongo_dart._ConnectionManager.new._connect
(connection_manager.dart:23)
at _connect.next (<anonymous>)
at runBody (dart_sdk.js:22269)
at Object.async.async (dart_sdk.js:22297)
at mongo_dart._ConnectionManager.new.[_connect]
(connection_manager.dart:22)
at connection_manager.dart:58
at dart_sdk.js:23887


问:
Create a cursor from .cur format bytes?
I can find a couple ways to create a cursor in win32 but I need the third, the one I can't find.

The first I can find is to use LoadXXX() to open a file or resource and load the cursor that way.

The second I can find is to use CreateCursor to take the hot-spot points, some data arrays, and make one out of bits.

I want the third way that's between the two: I have an array of bytes that contains a .cur file data.  I want to use that data to make a cursor.  Can this be done?

答:
Whilst looking for the answer to this, I stumbled across CreateIconIndirect, which "Creates an icon or cursor from an ICONINFO structure" that specifies a bitmap handle (HBITMAP) for the cursor image (so you can use the Win32 API bitmap routines to prepare the cursor):

https://learn.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-createiconindirect

```<code>HICON CreateIconIndirect(
    PICONINFO piconinfo
);
</code>```

Though its return type is HICON, the documentation says it returns an icon or cursor.

The ICONINFO structure has a boolean fIcon member to determine whether it is an icon (TRUE) or a cursor (FALSE):

```<code>typedef struct _ICONINFO {
    BOOL    fIcon;
    DWORD   xHotspot;
    DWORD   yHotspot;
    HBITMAP hbmMask;
    HBITMAP hbmColor;
} ICONINFO;
</code>```

I've not yet used this in my program and realise this is a really old question, but hopefully it will point anyone else that is trying to do this in the right direction.

ContentLicense: CC BY-SA 2.5

Title: Create a cursor from .cur format bytes?

Body:
Whilst looking for the answer to this, I stumbled across CreateIconIndirect, which "Creates an icon or cursor from an ICONINFO structure" that specifies a bitmap handle (HBITMAP) for the cursor image (so you can use the Win32 API bitmap routines to prepare the cursor):

https://learn.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-createiconindirect

HICON CreateIconIndirect(
    PICONINFO piconinfo
);

Though its return type is HICON, the documentation says it returns an icon or cursor.

The ICONINFO structure has a boolean fIcon member to determine whether it is an icon (TRUE) or a cursor (FALSE):

typedef struct _ICONINFO {
    BOOL    fIcon;
    DWORD   xHotspot;
    DWORD   yHotspot;
    HBITMAP hbmMask;
    HBITMAP hbmColor;
} ICONINFO;

I've not yet used this in my program and realise this is a really old question, but hopefully it will point anyone else that is trying to do this in the right direction.


问:
Is it a good practice to manually create indexes for the primary keys?
I am recently working with Entity Framework Core and I have some issue about the relation between the primary key and the indexes.

To be more concrete, I found out that in a table containing composite primary keys an index is created for the second property of the key.

You can see an example here

Can you explain me if I should manually create another index for the first one? Or is a clustered index created for that first property?

答: You don't need to create an index on NoteID because it is the first column of the primary key. Generally, you want all foreign keys to be the first column in at least one index. In your case, NoteID is the first column in the primary key which acts as a clustered unique index.</p>


问:
Terser - How to includeSources when original map file also contains source?
I'm building index.js using the typescript transpiler, which produces index.js.map containing the original typescript files.

I would now like to compress that file and preserve the original source in the index.js.map file so I can step through the typescript code and not the transpiled code.

The script I'm running:

```<code>terser index.js --source-map \"url='./index.js.map',includeSources\" -o index.js -c
</code>```

Replaces index.js with a compressed version and replaces index.js.map file with the transpiled source and not the original typescript source.  Is terser able to preserve the source in the sourcemap file?

答:
The answer is readily available in the documentation:

Composed source map When you're compressing JS code that was output by
  a compiler such as CoffeeScript, mapping to the JS code won't be too
  helpful. Instead, you'd like to map back to the original code (i.e.
  CoffeeScript). Terser has an option to take an input source map.
  Assuming you have a mapping from CoffeeScript → compiled JS, Terser
  can generate a map from CoffeeScript → compressed JS by mapping every
  token in the compiled JS to its original location.

To use this feature pass --source-map
  "content='/path/to/input/source.map'" or --source-map "content=inline"
  if the source map is included inline with the sources.

Body:
I'm building index.js using the typescript transpiler, which produces index.js.map containing the original typescript files.

I would now like to compress that file and preserve the original source in the index.js.map file so I can step through the typescript code and not the transpiled code.

The script I'm running:

terser index.js --source-map \"url='./index.js.map',includeSources\" -o index.js -c

Replaces index.js with a compressed version and replaces index.js.map file with the transpiled source and not the original typescript source.  Is terser able to preserve the source in the sourcemap file?


问:
Save value of then in a variable outside of the Promise
I'm fairly new to the concept of Promises and I'm trying to understand how the scopes work. I'm basically trying to store the value from inside a then() into a variable outside of the Promise

Below is a simple function I've written in Nodejs (Express), using Sequelize to run the query on the DB.

```<code>exports.getTest = (req, res, next) => {
    var categories = [];
    var names = ['Category 1', 'Category 2', 'Category 3', 'Category 4'];
    for (var i = 0; i < names.length; i++) {
        model.Category.findOne({
            where: {
                name: names[i]
            },
            attributes: ['id']
        }).then(id => {
            categories.push(
            {
                category_id: id.id
            });
        });
    }
    res.json(categories);
}
</code>```

I have other logic to be run after that, and I have a for loop around the Promise. So, I can't run my next logic inside the then, otherwise I'll have it running multiple times because of the for loop. I need to populate the array categories to use it in my next operation.

Currently, my response (res.json(categories)) is []

Any help would be appreciated.

PS: I know this is a common topic, but as I mentioned, I'm fairly new to this and the other answers didn't fit my scenario and were further confusing me.

Thanks in advance!

答:
```<code>exports.getTest = (req, res, next) => {
    var categories = [];
    var names = ['Category 1', 'Category 2', 'Category 3', 'Category 4'];
    names.forEach(name => {
        Category.findOne({where: {name: name}}).then(category => {
            categories.push({category_id: category.id})
        })
    })
    res.json(categories);
}
</code>```

So basically, model.findeOne() returns a promise with the object of the first category with each of the names. then() catches that promise, resolves it and you give it a callback function that get that object passed as a parameter.

It could look something like

```<code>Categories.findOne({where: {name: name}).then(function(category){
    // do something with that category
})
</code>```

But the arrow function makes it a lot more readable as then(category => {//some
code}).

Body:
I'm fairly new to the concept of Promises and I'm trying to understand how the scopes work. I'm basically trying to store the value from inside a then() into a variable outside of the Promise

Below is a simple function I've written in Nodejs (Express), using Sequelize to run the query on the DB.

exports.getTest = (req, res, next) => {
    var categories = [];
    var names = ['Category 1', 'Category 2', 'Category 3', 'Category 4'];
    for (var i = 0; i < names.length; i++) {
        model.Category.findOne({
            where: {
                name: names[i]
            },
            attributes: ['id']
        }).then(id => {
            categories.push(
            {
                category_id: id.id
            });
        });
    }
    res.json(categories);
}

I have other logic to be run after that, and I have a for loop around the Promise. So, I can't run my next logic inside the then, otherwise I'll have it running multiple times because of the for loop. I need to populate the array categories to use it in my next operation.

Currently, my response (res.json(categories)) is []

Any help would be appreciated.

PS: I know this is a common topic, but as I mentioned, I'm fairly new to this and the other answers didn't fit my scenario and were further confusing me.

Thanks in advance!

Body:
exports.getTest = (req, res, next) => {
    var categories = [];
    var names = ['Category 1', 'Category 2', 'Category 3', 'Category 4'];
    names.forEach(name => {
        Category.findOne({where: {name: name}}).then(category => {
            categories.push({category_id: category.id})
        })
    })
    res.json(categories);
}

So basically, model.findeOne() returns a promise with the object of the first category with each of the names. then() catches that promise, resolves it and you give it a callback function that get that object passed as a parameter.

It could look something like

Categories.findOne({where: {name: name}).then(function(category){
    // do something with that category
})

But the arrow function makes it a lot more readable as then(category => {//some
code}).


问:
echo statement not working? Seems to be formatted correctly
I'm creating a object in javascript echo'd by PHP, the syntax seems to be correct but it is giving me an error.

The variables I am passing to the object are strings and I have tried putting them in quotes, etc. I also tried creating a JS function to do this and it had similar results.

```<code><?PHP

$TEDS = $db->query("
SELECT a.*
FROM TEDS a
");
//Add each TED location into a javascript array.

echo '<script type="text/javascript">';
while($TED = $TEDS->fetch_assoc())
{
   echo 'var pos = {lat: '.$TED['latitude'].', lng: '.$TED['longitude'].'};'; //THIS ECHO STATEMENT IS THE ONE GIVING ME PROBLEMS.
}
echo '</script>';

?>

</code>```

答:
It's highly likely that one of your latitude values does not have a value, causing it to print something like the following:

```<code>var pos = {lat:  , lng: 1234}
</code>```

Without a value to go with the property, the JavaScript parser would unexpectedly see the comma. This would greatly explain an unexpected comma syntax error.

So, first of all, you do NOT manually construct JSON. PHP has json_encode() that converts PHP arrays into JSON. Use that to correctly build JSON for you.

Next, your code prints pos repeatedly, overriding the previous values. If you only care about the last value, don't print everything. If you do care about all the values, store them in an array:

```<code><?php
// Get your TEDS
$teds = $TEDS->fetch_assoc();

// Using array_map to convert the items from latitude-longitude to lat-lng.
$teds_array = array_map(function($ted) {
  return ['lat' => $ted['latitude'], 'lng' => $ted['longitude']];
}, $teds);

// Serialize to JSON
$teds_json = json_encode($teds_array);
?>

// positions will be an array of objects with lat-lng.
var positions = <?php echo $teds_json; ?>
</code>```

Lastly, be careful of XSS. Do not just print unsanitized values like above. Make sure your data is clean before printing it on the page.

Body:
I'm creating a object in javascript echo'd by PHP, the syntax seems to be correct but it is giving me an error.

The variables I am passing to the object are strings and I have tried putting them in quotes, etc. I also tried creating a JS function to do this and it had similar results.

<?PHP

$TEDS = $db->query("
SELECT a.*
FROM TEDS a
");
//Add each TED location into a javascript array.

echo '';

?>

Body:
It's highly likely that one of your latitude values does not have a value, causing it to print something like the following:

var pos = {lat:  , lng: 1234}

Without a value to go with the property, the JavaScript parser would unexpectedly see the comma. This would greatly explain an unexpected comma syntax error.

So, first of all, you do NOT manually construct JSON. PHP has json_encode() that converts PHP arrays into JSON. Use that to correctly build JSON for you.

Next, your code prints pos repeatedly, overriding the previous values. If you only care about the last value, don't print everything. If you do care about all the values, store them in an array:

<?php
// Get your TEDS
$teds = $TEDS->fetch_assoc();

// Using array_map to convert the items from latitude-longitude to lat-lng.
$teds_array = array_map(function($ted) {
  return ['lat' => $ted['latitude'], 'lng' => $ted['longitude']];
}, $teds);

// Serialize to JSON
$teds_json = json_encode($teds_array);
?>

// positions will be an array of objects with lat-lng.
var positions = <?php echo $teds_json; ?>

Lastly, be careful of XSS. Do not just print unsanitized values like above. Make sure your data is clean before printing it on the page.


问:
Trying to use Async and Await from different functions
While I thought I was using Async and Await keywords properly, it appears as though I am doing something wrong.

I am using PouchDB, which is a great Javascript database that syncs with CouchDB. PouchDB uses promises for many of its functions, and has native support for Async and Await.  As an example, to retrieve the basic information about a database, you would use the following code:

```<code>    db.info().then(function (info) {
  console.log(info);
})
</code>```

I understand this, and it works.  But if I try and put this inside a function, and then call that function, things go haywire. And I'm sure it's me and not PouchDB that is the problem...

```<code>function getLocalDBInfo(db){

  try {
    db.info().then(function (info) {
      return info;
    });
  } catch (error) {
    console.log("can't get local DB info: ", error);
  }
}

async function testing(db){
  try {
    var info=await getLocalDBInfo(db);
    await console.log("DB info=", info);
    await console.log("Doc count= ", info.doc_count);
  }
  catch(err){
    console.log("error=",err);
  }

  //info contains...
    //{"doc_count":0,"update_seq":0,"db_name":"kittens"}
}

testing(MY_db);
</code>```

If I log info inside the getLocalDBInfo function, it eventually (ie. after the promise fulfills) logs info to the console.  But, the logs inside the testing function return immediately with undefined.  It makes sense to me that they are returning undefined because they are returning immediately, but I was trying to have them wait for info by using async and await.  Any suggestions as to what I am doing wrong?

答:
You need to return the value from the outer function getLocalDBInfo

```<code>function getLocalDBInfo(db) {
  return new Promise((resolve, reject) => {
    db.info()
      .then(info => resolve(info))
      .catch(err => reject(err))
  })
}
</code>```

Body:
While I thought I was using Async and Await keywords properly, it appears as though I am doing something wrong.

I am using PouchDB, which is a great Javascript database that syncs with CouchDB. PouchDB uses promises for many of its functions, and has native support for Async and Await.  As an example, to retrieve the basic information about a database, you would use the following code:

    db.info().then(function (info) {
  console.log(info);
})

I understand this, and it works.  But if I try and put this inside a function, and then call that function, things go haywire. And I'm sure it's me and not PouchDB that is the problem...

function getLocalDBInfo(db){

  try {
    db.info().then(function (info) {
      return info;
    });
  } catch (error) {
    console.log("can't get local DB info: ", error);
  }
}

async function testing(db){
  try {
    var info=await getLocalDBInfo(db);
    await console.log("DB info=", info);
    await console.log("Doc count= ", info.doc_count);
  }
  catch(err){
    console.log("error=",err);
  }

  //info contains...
    //{"doc_count":0,"update_seq":0,"db_name":"kittens"}
}

testing(MY_db);

If I log info inside the getLocalDBInfo function, it eventually (ie. after the promise fulfills) logs info to the console.  But, the logs inside the testing function return immediately with undefined.  It makes sense to me that they are returning undefined because they are returning immediately, but I was trying to have them wait for info by using async and await.  Any suggestions as to what I am doing wrong?

Body:
You need to return the value from the outer function getLocalDBInfo

function getLocalDBInfo(db) {
  return new Promise((resolve, reject) => {
    db.info()
      .then(info => resolve(info))
      .catch(err => reject(err))
  })
}


问:
Is free embed token app specific or user specific?
As mentioned in Power BI Documentation,
"Embed tokens with PRO license are intended for development testing, so the number of embed tokens a Power BI master account or service principal can generate is limited".

Source: https://learn.microsoft.com/en-us/power-bi/developer/embedded-faq

So my question is...

If developer require more free tokens for testing app in developement environment, can he change master account to acquire more free tokens ? Embed token are app specific or user specific ?

Any comments are appreciated.
I am new to Power BI Embedded.

答:
You have a couple options: You can switch to another account (master service account) if you reach the limit but you will incur the cost of another PowerBI Pro License. You can also work with Microsoft support to have your limited reached to meet your needs until you are production ready. You can reach Microsoft support by going here https://powerbi.microsoft.com/en-us/support/ and scrolling down to "CREATE SUPPORT TICKET"

Note: If you are in Production you will have to buy a capacity. There is no way around that.


问:
Can fixedThreadPool have less threads than it was assigned to?
I have Executors.newFixedThreadPool(/* nThreads= */ 2) executor service. I noticed that sometimes when I pass TWO tasks to the executor service, it runs only ONE task, while I expect it to run TWO tasks. Is that possible and why?

I have two tasks which communicate with each other. These two tasks are put inside fixed thread pool of size two because I want both tasks to be running at the same time.

答: Executors make sure you will reuse the thread poll most efficiently. But it doesn't gurantee all tasks are executed all at once. I am wondering if you can use 2 threads coming from 2 threadpool which only having 1 thread?</p>


问:
Spark UI - Spark SQL Query Execution
I am using Spark SQL API. When I see the Spark SQL section on the spark UI which details the query execution plan it says it scans parquet stage multiple times even though I am reading the parquet only once.
Is there any logical explanation?

I would also like to understand the different operations like Hash Aggregate, SortMergeJoin etc and understand the Spark UI better as a whole.

答:
If you are doing unions or joins they may force your plan to be "duplicated" since the beginning.

Since spark doesn't keep intermediate states (unless you cache) automatically, it will have to read the sources multiple times

Something like

```<code>1- df = Read ParquetFile1
2- dfFiltered = df.filter('active=1')
3- dfFiltered.union(df)
</code>```

The plan will probably look like :      readParquetFIle1 -->  union <-- filter <-- readParquetFIle1

Title: Spark UI - Spark SQL Query Execution

Body:
If you are doing unions or joins they may force your plan to be "duplicated" since the beginning.

Since spark doesn't keep intermediate states (unless you cache) automatically, it will have to read the sources multiple times

Something like

1- df = Read ParquetFile1
2- dfFiltered = df.filter('active=1')
3- dfFiltered.union(df)

The plan will probably look like :      readParquetFIle1 -->  union <-- filter <-- readParquetFIle1


问:
php address request
i have this request method:

```<code>if (!$_REQUEST['0'])  {
    echo "Address missing...";
    die();
} else {
    code
    code etc.
}
</code>```

And address is: http://localhost/api.php?0=address

If I open: api.php?0=0 I should get another error which says address doesn't correct. But I get Address missing... In my opinion something wrong with:

```<code>if (!$_REQUEST['0'])
</code>```

Any ideas?

答:
```<code>if (array_key_exists('0', $_REQUEST['0']) === true) {
    echo 'exists';
}
else {
    echo 'does not';
}
</code>```

Sidenote: The best check to see if a key is set in an array is array_key_exists. Opposed to isset, this function does not return false when the value is NULL.

Sidenote 2: You should specify which superglobal to use, using $_REQUEST instead of specifying $_POST or $_GET is can be the cause of vague errors to occur.

Title: php address request

Body:
i have this request method:

if (!$_REQUEST['0'])  {
    echo "Address missing...";
    die();
} else {
    code
    code etc.
}

And address is: http://localhost/api.php?0=address

If I open: api.php?0=0 I should get another error which says address doesn't correct. But I get Address missing... In my opinion something wrong with:

if (!$_REQUEST['0'])

Any ideas?

Body:
if (array_key_exists('0', $_REQUEST['0']) === true) {
    echo 'exists';
}
else {
    echo 'does not';
}

Sidenote: The best check to see if a key is set in an array is array_key_exists. Opposed to isset, this function does not return false when the value is NULL.

Sidenote 2: You should specify which superglobal to use, using $_REQUEST instead of specifying $_POST or $_GET is can be the cause of vague errors to occur.


问:
How to iterate on results inside then() and call other chained then() inside the loop
I cannot find any documentation or example in typescript  that illustrates how to nest then() inside a loop which is inside a then().

I have the following chained then() functions that work perfectly.

but i need to make the functions 1 to 3 run n number of times based on an array property of the process object after it has been returned from the _promptUploadDialog

```<code>    .then(process => this._promptUploadDialog(process))
        .then(process => this._function1(process))
        .then(process => this._function2(process))
        .then(process => this._function3(process))
</code>```

needs to become something like this:

```<code> .then(process => this._promptUploadDialog(process)
     process.array1.forEach(function (value) {
        process.currentobject = value;
        this._function1(process))
            .then(process => this._function2(process))
            .then(process => this._function3(process))
     });
)
</code>```

Tried

```<code>return Promise.resolve<UploadDataProcess>({
            uploadResponse: undefined,
            arrayProp: [1,2,3]
        })
            .then(process => this._promptUploadDialog(process))
            .then(process =>
                process.arrayProp.forEach((value) => {
                    this._function1(process)
                        .then(process => this._function2(process))
                        .then(process => this._function3(process));
                    })
            );
</code>```

But I am getting a compile error:

TS2322    Type 'Promise' is not assignable to type 'Promise'.

答:
What if you do something like:

```<code>.then(process => this._promptUploadDialog(process))
  .then(process => process.array1.forEach((value)=>
     {
       this._function1(process)
        .then(process => this._function2(process))
        .then(process => this._function3(process))
     });
</code>```

your functions 1,2,3 are going to be in a loop based on process.array1 that what you want if I understand your question.

Body:
I cannot find any documentation or example in typescript  that illustrates how to nest then() inside a loop which is inside a then().

I have the following chained then() functions that work perfectly.

but i need to make the functions 1 to 3 run n number of times based on an array property of the process object after it has been returned from the _promptUploadDialog

    .then(process => this._promptUploadDialog(process))
        .then(process => this._function1(process))
        .then(process => this._function2(process))
        .then(process => this._function3(process))

needs to become something like this:

 .then(process => this._promptUploadDialog(process)
     process.array1.forEach(function (value) {
        process.currentobject = value;
        this._function1(process))
            .then(process => this._function2(process))
            .then(process => this._function3(process))
     });
)

Tried

return Promise.resolve<UploadDataProcess>({
            uploadResponse: undefined,
            arrayProp: [1,2,3]
        })
            .then(process => this._promptUploadDialog(process))
            .then(process =>
                process.arrayProp.forEach((value) => {
                    this._function1(process)
                        .then(process => this._function2(process))
                        .then(process => this._function3(process));
                    })
            );

But I am getting a compile error:

TS2322    Type 'Promise' is not assignable to type 'Promise'.

Body:
What if you do something like:

.then(process => this._promptUploadDialog(process))
  .then(process => process.array1.forEach((value)=>
     {
       this._function1(process)
        .then(process => this._function2(process))
        .then(process => this._function3(process))
     });

your functions 1,2,3 are going to be in a loop based on process.array1 that what you want if I understand your question.


问:
Perfom get query with value other than key
Is it possible for me to use the get query to query for a value other than the primary key? Cuz it seems I can only pass in the id column but is there no way in which i could perform the get query with a column other than the id column.
  Or can I just do this with a normal list query using maybe a filter or something? Thanks for any help!</p>

答:
Yes you can issue any DynamoDB query through AppSync. This provides a good introduction that covers PutItem, UpdateItem, and GetItem https://docs.aws.amazon.com/appsync/latest/devguide/tutorial-dynamodb-resolvers.html. If you need to get multiple values by a key then you should use the DynamoDB Query operation https://docs.aws.amazon.com/appsync/latest/devguide/resolver-mapping-template-reference-dynamodb.html#aws-appsync-resolver-mapping-template-reference-dynamodb-query.

When using DynamoDB you need to bake your access patterns into the key schema(s) of your DynamoDB table and secondary indexes. For example, if you want to get a record by "email" then you should create a table where the hash key is "email". You would then be able to perform a GetItem operation by "email". If you need to query by email and have records sorted by date, then you would need a table where the hash key is "email" and the sort key is "date". Etc..

You are able to create secondary indexes and if you want to get a bit more advanced create composite index values and overload indexes to optimize your DynamoDB tables for your access patterns. Checkout the DynamoDB docs to learn more https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-indexes.html.


问:
cmd and bat behaving differently
EDIT:

After discussing the issue with a colleague, we think we know why the .bat runs differently than when typing line by line in cmd window. We think that the line ./venv/Scripts/activate.bat activates a virtual environment in a shell different than where the rest of the code runs. I would need all of the code to run within the same shell from that line onwards. (FYI, I'm not sure if this makes sense as I'm relatively new to this.)

I am trying to create a virtual environment by running a bat file with the necessary commands to do so. When I run the lines from my .bat code by copy pasting them into the cmd window and running each individually, the code works as expected. When I run the .bat file though, it doesn't work.

I think the challenge comes from the fact that the bat script must move around directories, as the virtual environment must be created in a local folder, while the scripts and files it then calls are hosted in a network folder.

This setup can't change, so I instead need to be able to move around directories properly in my .bat file.

I've looked around in StackOverflow and couldn't find any questions relating to similar behaviour. I've been reading through the relevant documentation, but haven't found anything helpful yet.
I'm running the anaconda3 distribution. Windows 10.
I'm not sure what information might be helpful to troubleshoot, so please let me know if you need more information. You'll find my code below.

```<code>echo ON

REM Change directory to user's local dir
chdir C:\Users\USERNAME
C:

REM Check whether environments folder exists, if not, create it.
if not exist "C:\Users\USERNAME\Environments\" mkdir C:\Users\USERNAME\Environments

REM Create virtual environment in this new/existing folder and activate it.
python -m venv venv/
"./venv/Scripts/activate.bat"

REM Change directory to network drive where document files are located
chdir I:\NETWORKDIR_PATH\FOLDER_OF_INTEREST
I:

REM Make sure necessary packages are installed.
pip install -r ./src/requirements.txt

REM Run script and close shell after 20 secs
python "./src/main_script.py"

REM FOLDER_OF_INTEREST contains the following items:
REM two excel files which will interact with the main_script.py script
REM a folder called "src" which has the packages to be installed within my environment
REM "src" also contains two python scripts. The first is the main_script.py, the other contains functions called by main_script.py
</code>```

As it stands, when I run each line individually in the cmd window, everything works just fine.

If I try to run the .bat file instead, the code runs until

```<code>python -m venv venv/
"./venv/Scripts/activate.bat"
</code>```

at this point, the cmd window exits and  and nothing else happens...

Any help/advice is appreciated!

PS: the ping commands are there because if not, the cmd window exits too quickly and I can't see what happened.

答:
We think that the line ./venv/Scripts/activate.bat activates a virtual
  environment in a shell different than where the rest of the code runs.

No. Batch files are executed line by line until it hits an EOF (End Of File). So at the end of activate.bat, the interpreter considers its job done and that's it.

To be able to "return" to the calling script, you need to call the called script (which basically saves a return point)

To literally start a script in another cmd instance (what you called "a virtual environment in a shell"), you'd need the start command.

Title: cmd and bat behaving differently

Body:
EDIT:

After discussing the issue with a colleague, we think we know why the .bat runs differently than when typing line by line in cmd window. We think that the line ./venv/Scripts/activate.bat activates a virtual environment in a shell different than where the rest of the code runs. I would need all of the code to run within the same shell from that line onwards. (FYI, I'm not sure if this makes sense as I'm relatively new to this.)

I am trying to create a virtual environment by running a bat file with the necessary commands to do so. When I run the lines from my .bat code by copy pasting them into the cmd window and running each individually, the code works as expected. When I run the .bat file though, it doesn't work.

I think the challenge comes from the fact that the bat script must move around directories, as the virtual environment must be created in a local folder, while the scripts and files it then calls are hosted in a network folder.

This setup can't change, so I instead need to be able to move around directories properly in my .bat file.

I've looked around in StackOverflow and couldn't find any questions relating to similar behaviour. I've been reading through the relevant documentation, but haven't found anything helpful yet.
I'm running the anaconda3 distribution. Windows 10.
I'm not sure what information might be helpful to troubleshoot, so please let me know if you need more information. You'll find my code below.

echo ON

REM Change directory to user's local dir
chdir C:\Users\USERNAME
C:

REM Check whether environments folder exists, if not, create it.
if not exist "C:\Users\USERNAME\Environments\" mkdir C:\Users\USERNAME\Environments

REM Create virtual environment in this new/existing folder and activate it.
python -m venv venv/
"./venv/Scripts/activate.bat"

REM Change directory to network drive where document files are located
chdir I:\NETWORKDIR_PATH\FOLDER_OF_INTEREST
I:

REM Make sure necessary packages are installed.
pip install -r ./src/requirements.txt

REM Run script and close shell after 20 secs
python "./src/main_script.py"

REM FOLDER_OF_INTEREST contains the following items:
REM two excel files which will interact with the main_script.py script
REM a folder called "src" which has the packages to be installed within my environment
REM "src" also contains two python scripts. The first is the main_script.py, the other contains functions called by main_script.py

As it stands, when I run each line individually in the cmd window, everything works just fine.

If I try to run the .bat file instead, the code runs until

python -m venv venv/
"./venv/Scripts/activate.bat"

at this point, the cmd window exits and  and nothing else happens...

Any help/advice is appreciated!

PS: the ping commands are there because if not, the cmd window exits too quickly and I can't see what happened.


问:
How to use template property in Facebook Instant Game SDK
reference : https://developers.facebook.com/docs/games/instant-games/getting-started/quickstart

```<code>FBInstant.updateAsync({
  action:
  cta:
  image:
  text:
  template: 'this property',
  data:
  strategy:
  notification:
})
</code>```

I know this property is relative with app config (fbapp-config.json).
but I don't know how to use this property exactly. 'text' and 'template' are same thing?

Does anyone have an easier example?

ps. sorry for English.

答:
The intention of the template is to categorize different messages. E.g. if you send a message for a new high score, you could use a 'HIGH_SCORE' template. If you had a different message for a gift, you could use a 'SEND_GIFT' template. The analytics for these templates are broken out in Facebook Analytics for analysis.

It is not required to use a different template for different messages today, but it is recommended.

Body:
reference : https://developers.facebook.com/docs/games/instant-games/getting-started/quickstart

FBInstant.updateAsync({
  action:
  cta:
  image:
  text:
  template: 'this property',
  data:
  strategy:
  notification:
})

I know this property is relative with app config (fbapp-config.json).
but I don't know how to use this property exactly. 'text' and 'template' are same thing?

Does anyone have an easier example?

ps. sorry for English.


问:
Looping through dataframe names in R and saving out corresponding dataframe as Rds file
I have about 30 separate dataframes loaded in my R session each with various names.  I also have a character vector called mydfs which contains the names of all those dataframes loaded into my R session.  I am trying to loop over mydfs and save out as an rds file each dataframe listed in the elements of mydfs, but for some reason, I'm only able to save out the character string of the name of the dataframe I'm trying to save (not the datafame itself).  Here is simulated, reproducible example of what I have:

```<code>#Create vector of dataframes that exist in base r to create a reproducible example
mydfs<-c("cars","iris","iris3","mtcars")

#My code that creates files, but they don't contain my dataframe data for some reason
for (i in 1:length(mydfs)){
  savefile<-paste0(paste0("D:/Data/", mydfs[i]), ".Rds")
  saveRDS(mydfs[i], file=savefile)
  print(paste("Dataframe Saved:", mydfs[i]))
}
</code>```

This results in the following log output:

```<code>[1] "Dataframe Saved: cars"
[1] "Dataframe Saved: iris"
[1] "Dataframe Saved: iris3"
[1] "Dataframe Saved: mtcars"
</code>```

Then I try to read back in any of the files I created:

```<code>#But when read back in only contain a single character string of the dataframe name
a<-readRDS("D:/Data/iris3.Rds")
str(a)

chr "iris3"
</code>```

Note that when I read iris3.Rds back into a new R session using readRDS, I don't have a dataframe as I was expecting, but a single character vector containing the name of the datafame and not the data.

I haven't been programming in R for a while, since my current client preferred SAS, so I think I am somehow getting macro variable looping in SAS confused with R and so that when I call saveRDS, I'm passing in a single character vector instead of the actual dataframe.  How can I get the dataframe to be passed into saveRDS instead of the character?

Thanks for helping me untangle my SAS thinking with my somewhat rusty R thinking.

答:
You're currently just saving the names of the dataframes. You can use the get function as follows:

```<code>mydfs<-c("cars","iris","iris3","mtcars")

for (i in 1:length(mydfs)){
  savefile<-paste0(paste0("D:/Data/", mydfs[i]), ".Rds")
  saveRDS(get(mydfs[i]), file=savefile)
  print(paste("Dataframe Saved:", mydfs[i]))
}

readRDS('D:/Data/iris3.RDS')
</code>```

Body:
I have about 30 separate dataframes loaded in my R session each with various names.  I also have a character vector called mydfs which contains the names of all those dataframes loaded into my R session.  I am trying to loop over mydfs and save out as an rds file each dataframe listed in the elements of mydfs, but for some reason, I'm only able to save out the character string of the name of the dataframe I'm trying to save (not the datafame itself).  Here is simulated, reproducible example of what I have:

#Create vector of dataframes that exist in base r to create a reproducible example
mydfs<-c("cars","iris","iris3","mtcars")

#My code that creates files, but they don't contain my dataframe data for some reason
for (i in 1:length(mydfs)){
  savefile<-paste0(paste0("D:/Data/", mydfs[i]), ".Rds")
  saveRDS(mydfs[i], file=savefile)
  print(paste("Dataframe Saved:", mydfs[i]))
}

This results in the following log output:

[1] "Dataframe Saved: cars"
[1] "Dataframe Saved: iris"
[1] "Dataframe Saved: iris3"
[1] "Dataframe Saved: mtcars"

Then I try to read back in any of the files I created:

#But when read back in only contain a single character string of the dataframe name
a<-readRDS("D:/Data/iris3.Rds")
str(a)

chr "iris3"

Note that when I read iris3.Rds back into a new R session using readRDS, I don't have a dataframe as I was expecting, but a single character vector containing the name of the datafame and not the data.

I haven't been programming in R for a while, since my current client preferred SAS, so I think I am somehow getting macro variable looping in SAS confused with R and so that when I call saveRDS, I'm passing in a single character vector instead of the actual dataframe.  How can I get the dataframe to be passed into saveRDS instead of the character?

Thanks for helping me untangle my SAS thinking with my somewhat rusty R thinking.

Body:
You're currently just saving the names of the dataframes. You can use the get function as follows:

mydfs<-c("cars","iris","iris3","mtcars")

for (i in 1:length(mydfs)){
  savefile<-paste0(paste0("D:/Data/", mydfs[i]), ".Rds")
  saveRDS(get(mydfs[i]), file=savefile)
  print(paste("Dataframe Saved:", mydfs[i]))
}

readRDS('D:/Data/iris3.RDS')


问:
What are the options for the -Encoding parameter in the Import-DbaCsv tool?
I can't figure out what the Import-DbaCsv tool is expecting for the -Encoding parameter.

The docs aren't helpful - https://docs.dbatools.io/#Import-DbaCsv

I've tried UTF-8, UTF8, and UTF in upper case, lower case, with quotes, and without quotes.

I always get and error message like this:

Cannot convert the "UTF-8" value of type "System.String" to type "System.Text.Encoding"

答:
The link you gave us shows the -Encoding parameter is of type <Encoding>, which leads me to believe you need to use any of the [System.Text.Encoding] encoding classes instead of a string:

So in your case, use [System.Text.Encoding]::UTF8