问:
403 The caller does not have permission for Firebase Management API addFirebase
I want to add Firebase project through Firebase Management Api. So for that. I made project on Google Cloud Platform console. And created service account with permission as a owner.

I tried to read and create project throw google api explorer for addFirebase and it works. But when i try to do the same through my code it read availableProject successfully and give output as

{
    "projectInfo": [
      {
        "project": "projects/firebase-api-238012",
        "displayName": "Firebase-Api"
      }
    ]
  }

but when i try to add project it give me this error

{
    "error": {
      "code": 403,
      "message": "The caller does not have permission",
      "status": "PERMISSION_DENIED"
    }
  }

I don't know why its is not creating project. What other permission it needs. And why it allowed to me read available projects first.

here is how i am trying to add my project.

jwt.js

```<code>const { google } = require('googleapis');
var serviceAccountJwt = require('./Firebase-Api-b0e41b85ad44.json');

exports.connect = async () => {
return new Promise((resolve, reject) => {

    // scope is based on what is needed in our api
    const scope = ['https://www.googleapis.com/auth/firebase', 'https://www.googleapis.com/auth/cloud-platform'];

    // create our client with the service account JWT
    const { client_email, private_key } = serviceAccountJwt;
    const client = new google.auth.JWT(client_email, null, private_key, scope, null);

    // perform authorization and resolve with the client

    return client.authorize((err) => {
        if (err) { reject(err) }
        else {
            resolve(client)
        };
    });
});
</code>```

}

index.js file

```<code>const { google } = require('googleapis');
const request = require('request');
const { connect } = require('./jwt');
const availableProjects = 'https://firebase.googleapis.com/v1beta1/availableProjects';

async function getAccessToken() {
let client = await connect();
let accessToken = await client.getAccessToken();
let res = await getProjects(accessToken.token)
}

getAccessToken().catch(err => {
console.log(JSON.stringify(err))
})

const bodys = {
"timeZone": "America/Los_Angeles",
"locationId": "asia-south1",
"regionCode": "US"
}

async function getProjects(accesstoken) {

let options = {
url: availableProjects,
headers: {
  'Authorization': 'Bearer ' + accesstoken,
  'Accept': 'application/json',
  'Content-Type': 'application/json'
}
}

return request(options, async function (err, res) {
if (err) {
  console.error(err + " error");
 } else {
  //here it gives successful output
  console.log("response")
  console.log(res.body);
  let bodyJson = JSON.parse(res.body);
  let projectName = bodyJson.projectInfo[0].project;
  console.log(projectName)
  await addProject(accesstoken, projectName)
  return res.body;
 }
 });
 }

async function addProject(accesstoken, projecctID) {

 fbUrl = getAddFBUrl(projecctID);
 let options = {
 url: fbUrl,
  headers: {
  'Authorization': 'Bearer ' + accesstoken,
  'Accept': 'application/json',
  'Content-Type': 'application/json'
  },
  body:JSON.stringify(bodys)
 }

return request.post(options, function (err, res) {
 if (err) {
  console.error(err + " error");
 } else {
//here in response out put as permission denied 403
  console.log("response")
  console.log(res.body);
  console.log(JSON.stringify(res));
  return res.body;
 }

 });
}

function getAddFBUrl(projectId) {
return 'https://firebase.googleapis.com/v1beta1/' + projectId +
':addFirebase';
}
</code>```

i found one similar question to this. But it didn't helped me to resolve my issue which is here

AskFirebase

答:
From the Firebase REST reference: Method: projects.addFirebase

To call projects.addFirebase, a member must be an Editor or Owner for
  the existing GCP Project. <s>Service accounts cannot call
  projects.addFirebase.</s>

Update:

To call projects.addFirebase, a project member or service account must have the following permissions (the IAM roles of Editor and Owner contain these permissions): firebase.projects.update, resourcemanager.projects.get, serviceusage.services.enable, and serviceusage.services.get.

https://firebase.google.com/docs/projects/api/reference/rest/v1beta1/projects/addFirebase

Body:
I want to add Firebase project through Firebase Management Api. So for that. I made project on Google Cloud Platform console. And created service account with permission as a owner.

I tried to read and create project throw google api explorer for addFirebase and it works. But when i try to do the same through my code it read availableProject successfully and give output as

{
    "projectInfo": [
      {
        "project": "projects/firebase-api-238012",
        "displayName": "Firebase-Api"
      }
    ]
  }

but when i try to add project it give me this error

{
    "error": {
      "code": 403,
      "message": "The caller does not have permission",
      "status": "PERMISSION_DENIED"
    }
  }

I don't know why its is not creating project. What other permission it needs. And why it allowed to me read available projects first.

here is how i am trying to add my project.

jwt.js

const { google } = require('googleapis');
var serviceAccountJwt = require('./Firebase-Api-b0e41b85ad44.json');

exports.connect = async () => {
return new Promise((resolve, reject) => {

    // scope is based on what is needed in our api
    const scope = ['https://www.googleapis.com/auth/firebase', 'https://www.googleapis.com/auth/cloud-platform'];

    // create our client with the service account JWT
    const { client_email, private_key } = serviceAccountJwt;
    const client = new google.auth.JWT(client_email, null, private_key, scope, null);

    // perform authorization and resolve with the client

    return client.authorize((err) => {
        if (err) { reject(err) }
        else {
            resolve(client)
        };
    });
});

}

index.js file

const { google } = require('googleapis');
const request = require('request');
const { connect } = require('./jwt');
const availableProjects = 'https://firebase.googleapis.com/v1beta1/availableProjects';

async function getAccessToken() {
let client = await connect();
let accessToken = await client.getAccessToken();
let res = await getProjects(accessToken.token)
}

getAccessToken().catch(err => {
console.log(JSON.stringify(err))
})

const bodys = {
"timeZone": "America/Los_Angeles",
"locationId": "asia-south1",
"regionCode": "US"
}

async function getProjects(accesstoken) {

let options = {
url: availableProjects,
headers: {
  'Authorization': 'Bearer ' + accesstoken,
  'Accept': 'application/json',
  'Content-Type': 'application/json'
}
}

return request(options, async function (err, res) {
if (err) {
  console.error(err + " error");
 } else {
  //here it gives successful output
  console.log("response")
  console.log(res.body);
  let bodyJson = JSON.parse(res.body);
  let projectName = bodyJson.projectInfo[0].project;
  console.log(projectName)
  await addProject(accesstoken, projectName)
  return res.body;
 }
 });
 }

async function addProject(accesstoken, projecctID) {

 fbUrl = getAddFBUrl(projecctID);
 let options = {
 url: fbUrl,
  headers: {
  'Authorization': 'Bearer ' + accesstoken,
  'Accept': 'application/json',
  'Content-Type': 'application/json'
  },
  body:JSON.stringify(bodys)
 }

return request.post(options, function (err, res) {
 if (err) {
  console.error(err + " error");
 } else {
//here in response out put as permission denied 403
  console.log("response")
  console.log(res.body);
  console.log(JSON.stringify(res));
  return res.body;
 }

 });
}

function getAddFBUrl(projectId) {
return 'https://firebase.googleapis.com/v1beta1/' + projectId +
':addFirebase';
}

i found one similar question to this. But it didn't helped me to resolve my issue which is here

AskFirebase


来源: stackexchange

问:
Spring Partial Update Object Data Binding
We are trying to implement a special partial update function in Spring 3.2. We are using Spring for the backend and have a simple Javascript frontend. I've not been able to find a straight-forward solution to our requirements, which is The update() function should take in any number of field:values and update the persistence model accordingly.

We have in-line editing for all of our fields, so that when the user edits a field and confirms, an id and the modified field get passed to the controller as json. The controller should be able to take in any number of fields from the client (1 to n) and update only those fields.

e.g., when a user with id==1 edits his displayName, the data posted to the server looks like this:

```<code>{"id":"1", "displayName":"jim"}
</code>```

Currently, we have an incomplete solution in the UserController as outlined below:

```<code>@RequestMapping(value = "/{id}", method = RequestMethod.POST )
public @ResponseBody ResponseEntity<User> update(@RequestBody User updateUser) {
    dbUser = userRepository.findOne(updateUser.getId());
    customObjectMerger(updateUser, dbUser);
    userRepository.saveAndFlush(updateUuser);
    ...
}
</code>```

The code here works, but has some issues: The @RequestBody creates a new updateUser, fills in the id and the displayName. CustomObjectMerger merges this updateUser with the corresponding dbUser from the database, updating the only fields included in updateUser.

The problem is that Spring populates some fields in updateUser with default values and other auto-generated field values, which, upon merging, overwrites valid data that we have in dbUser. Explicitly declaring that it should ignore these fields is not an option, as we want our update to be able to set these fields as well.

I am looking into some way to have Spring automatically merge ONLY the information explicitly sent into the update() function into the dbUser (without resetting default/auto field values). Is there any simple way to do this?

Update: I've already considered the following option which does almost what I'm asking for, but not quite. The problem is that it takes update data in as @RequestParam and (AFAIK) doesn't do JSON strings:

```<code>//load the existing user into the model for injecting into the update function
@ModelAttribute("user")
public User addUser(@RequestParam(required=false) Long id){
    if (id != null) return userRepository.findOne(id);
    return null;
}
....
//method declaration for using @MethodAttribute to pre-populate the template object
@RequestMapping(value = "/{id}", method = RequestMethod.POST )
public @ResponseBody ResponseEntity<User> update(@ModelAttribute("user") User updateUser){
....
}
</code>```

I've considered re-writing my customObjectMerger() to work more appropriately with JSON, counting and having it take into consideration only the fields coming in from HttpServletRequest. but even having to use a customObjectMerger() in the first place feels hacky when spring provides almost exactly what I am looking, minus the lacking JSON functionality. If anyone knows of how to get Spring to do this, I'd greatly appreciate it!

答:
I've done this with a java Map and some reflection magic:

```<code>public static Entidade setFieldsByMap(Map<String, Object> dados, Entidade entidade) {
        dados.entrySet().stream().
                filter(e -> e.getValue() != null).
                forEach(e -> {
                    try {
                        Method setter = entidade.getClass().
                                getMethod("set"+ Strings.capitalize(e.getKey()),
                                        Class.forName(e.getValue().getClass().getTypeName()));
                        setter.invoke(entidade, e.getValue());
                    } catch (Exception ex) { // a lot of exceptions
                        throw new WebServiceRuntimeException("ws.reflection.error", ex);
                    }
                });
        return entidade;
    }
</code>```

And the entry point:

```<code>    @Transactional
    @PatchMapping("/{id}")
    public ResponseEntity<EntityOutput> partialUpdate(@PathVariable String entity,
            @PathVariable Long id, @RequestBody Map<String, Object> data) {
        // ...
        return new ResponseEntity<>(obj, HttpStatus.OK);
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
We are trying to implement a special partial update function in Spring 3.2. We are using Spring for the backend and have a simple Javascript frontend. I've not been able to find a straight-forward solution to our requirements, which is The update() function should take in any number of field:values and update the persistence model accordingly.

We have in-line editing for all of our fields, so that when the user edits a field and confirms, an id and the modified field get passed to the controller as json. The controller should be able to take in any number of fields from the client (1 to n) and update only those fields.

e.g., when a user with id==1 edits his displayName, the data posted to the server looks like this:

{"id":"1", "displayName":"jim"}

Currently, we have an incomplete solution in the UserController as outlined below:

@RequestMapping(value = "/{id}", method = RequestMethod.POST )
public @ResponseBody ResponseEntity<User> update(@RequestBody User updateUser) {
    dbUser = userRepository.findOne(updateUser.getId());
    customObjectMerger(updateUser, dbUser);
    userRepository.saveAndFlush(updateUuser);
    ...
}

The code here works, but has some issues: The @RequestBody creates a new updateUser, fills in the id and the displayName. CustomObjectMerger merges this updateUser with the corresponding dbUser from the database, updating the only fields included in updateUser.

The problem is that Spring populates some fields in updateUser with default values and other auto-generated field values, which, upon merging, overwrites valid data that we have in dbUser. Explicitly declaring that it should ignore these fields is not an option, as we want our update to be able to set these fields as well.

I am looking into some way to have Spring automatically merge ONLY the information explicitly sent into the update() function into the dbUser (without resetting default/auto field values). Is there any simple way to do this?

Update: I've already considered the following option which does almost what I'm asking for, but not quite. The problem is that it takes update data in as @RequestParam and (AFAIK) doesn't do JSON strings:

//load the existing user into the model for injecting into the update function
@ModelAttribute("user")
public User addUser(@RequestParam(required=false) Long id){
    if (id != null) return userRepository.findOne(id);
    return null;
}
....
//method declaration for using @MethodAttribute to pre-populate the template object
@RequestMapping(value = "/{id}", method = RequestMethod.POST )
public @ResponseBody ResponseEntity<User> update(@ModelAttribute("user") User updateUser){
....
}

I've considered re-writing my customObjectMerger() to work more appropriately with JSON, counting and having it take into consideration only the fields coming in from HttpServletRequest. but even having to use a customObjectMerger() in the first place feels hacky when spring provides almost exactly what I am looking, minus the lacking JSON functionality. If anyone knows of how to get Spring to do this, I'd greatly appreciate it!

Body:
I've done this with a java Map and some reflection magic:

public static Entidade setFieldsByMap(Map<String, Object> dados, Entidade entidade) {
        dados.entrySet().stream().
                filter(e -> e.getValue() != null).
                forEach(e -> {
                    try {
                        Method setter = entidade.getClass().
                                getMethod("set"+ Strings.capitalize(e.getKey()),
                                        Class.forName(e.getValue().getClass().getTypeName()));
                        setter.invoke(entidade, e.getValue());
                    } catch (Exception ex) { // a lot of exceptions
                        throw new WebServiceRuntimeException("ws.reflection.error", ex);
                    }
                });
        return entidade;
    }

And the entry point:

    @Transactional
    @PatchMapping("/{id}")
    public ResponseEntity<EntityOutput> partialUpdate(@PathVariable String entity,
            @PathVariable Long id, @RequestBody Map<String, Object> data) {
        // ...
        return new ResponseEntity<>(obj, HttpStatus.OK);
    }

ContentLicense: CC BY-SA 4.0


问:
How can I send a print to a word document saved with a specific name?
I need to take this:

```<code>for k, v in r.items():
    f.write(str(v) + " " + str(k) + "\n")
</code>```

and print it into a Word document, then save that word document with a name that I provide from within the code. How would I do this?

答:
There are many ways you can do this. One way is by using pickle, as shown below:

Pickle

import pickle
r = dict(reduce(f, lines, defaultdict(int)))
print(r)
filename = 'foobar.docx' #docx is default Word extension
outfile = open(filename,'wb')
pickle.dump(r, outfile)
outfile.close()
```

<p>Another way is through the <code>save()</code> method, as shown below:</p>

<p><strong>Save</strong></p>

<pre class="lang-py prettyprint-override"><code>r = dict(reduce(f, lines, defaultdict(int)))
print(r)
filename = 'foobar.docx' #docx is default Word extension
outfile = open(filename,'wb')
save(r, outfile)
outfile.close()
</code>```

Body:
I need to take this:

for k, v in r.items():
    f.write(str(v) + " " + str(k) + "\n")

and print it into a Word document, then save that word document with a name that I provide from within the code. How would I do this?

Body:
There are many ways you can do this. One way is by using pickle, as shown below:

Pickle

import pickle
r = dict(reduce(f, lines, defaultdict(int)))
print(r)
filename = 'foobar.docx' #docx is default Word extension
outfile = open(filename,'wb')
pickle.dump(r, outfile)
outfile.close()

Another way is through the save() method, as shown below:

Save

r = dict(reduce(f, lines, defaultdict(int)))
print(r)
filename = 'foobar.docx' #docx is default Word extension
outfile = open(filename,'wb')
save(r, outfile)
outfile.close()


问:
ArrayList.add() not working correctly
So I have a function that gets some coordinates from a sql database and stores them in an arraylist. I am printing the values as I read them from the cursor and they are good. However when I immediately after loop through and print out the values I stored in the array list, all the values seem to be set to the last value I added to the arraylist. I am doing something wrong here?

code:

```<code>public ArrayList<Coord> getCoordMarkers(int myUserId)
{
    Log.d("getCoordMarkers()", "Called");
Coord myCoord = new Coord();
ArrayList<Coord> markerArray = new ArrayList<Coord>();
String sql = "SELECT "+ userId + " , " + timestamp + " , " + coordX + " , " +
                 coordY + " , " + coordType + " , " + coordId + " , " + coordTypeTable+ "." +
                 coordTypeDesc + " FROM " + coordTable + " JOIN " + coordTypeTable + " ON " +
                 coordTable + "." + coordType + " = " + coordTypeTable + "." + coordTypeAbbr +
                 " WHERE " + userId + " = '" + myUserId + "' AND " + coordTypeTable + "." +
                 coordTypeDesc + " != 'User Location';";
    // AND it is a marker
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cur = db.rawQuery(sql, null);
    if( cur.moveToFirst()) {
        do {
            myCoord.userId = cur.getInt(0);
            myCoord.timestamp = cur.getLong(1);
            myCoord.x = cur.getDouble(2);
            myCoord.y = cur.getDouble(3);
            myCoord.coordType = cur.getInt(4);
            myCoord.id = cur.getInt(5);
            myCoord.coordTypeDesc = cur.getString(6);
            markerArray.add(myCoord);
            Log.d("getCoordMarkers()", "X: " + myCoord.x + " Y: " + myCoord.y);
        } while( cur.moveToNext());
    }
    cur.close();
    db.close();
    for( int i = 0; i < markerArray.size(); i++ )
    {
        Coord myCoord2 = markerArray.get(i);
        Log.d("Test Marker", "I: "+ i + " X: " + myCoord2.x + " Y: "+ myCoord2.y);

    }
    return markerArray;
}
</code>```

The following is the log printout from the above code

```<code>06-27 01:46:06.588: DEBUG/getCoordMarkers()(541): Called
06-27 01:46:06.638: DEBUG/getCoordMarkers()(541): X: -122.093451 Y: 37.420599
06-27 01:46:06.638: DEBUG/getCoordMarkers()(541): X: -122.093451 Y: 37.420599
06-27 01:46:06.648: DEBUG/getCoordMarkers()(541): X: -122.094695 Y: 37.419679
06-27 01:46:06.648: DEBUG/getCoordMarkers()(541): X: -122.094695 Y: 37.419679
06-27 01:46:06.648: DEBUG/getCoordMarkers()(541): X: -122.090104 Y: 37.423633
06-27 01:46:06.658: DEBUG/getCoordMarkers()(541): X: -122.090104 Y: 37.423633
06-27 01:46:06.658: DEBUG/getCoordMarkers()(541): X: -122.092078 Y: 37.420464
06-27 01:46:06.658: DEBUG/getCoordMarkers()(541): X: -122.092078 Y: 37.420464
06-27 01:46:06.658: DEBUG/getCoordMarkers()(541): X: -122.091992 Y: 37.420668
06-27 01:46:06.668: DEBUG/getCoordMarkers()(541): X: -122.091992 Y: 37.420668
06-27 01:46:06.668: DEBUG/getCoordMarkers()(541): X: -122.09594 Y: 37.42077
06-27 01:46:06.678: DEBUG/getCoordMarkers()(541): X: -122.09594 Y: 37.42077
06-27 01:46:06.678: DEBUG/getCoordMarkers()(541): X: -122.09255 Y: 37.42118
06-27 01:46:06.678: DEBUG/getCoordMarkers()(541): X: -122.09255 Y: 37.42118
06-27 01:46:06.688: DEBUG/getCoordMarkers()(541): X: -122.095897 Y: 37.423633
06-27 01:46:06.698: DEBUG/getCoordMarkers()(541): X: -122.095897 Y: 37.423633
06-27 01:46:06.708: DEBUG/Test Marker(541): I: 0 X: -122.095897 Y: 37.423633
06-27 01:46:06.708: DEBUG/Test Marker(541): I: 1 X: -122.095897 Y: 37.423633
06-27 01:46:06.708: DEBUG/Test Marker(541): I: 2 X: -122.095897 Y: 37.423633
06-27 01:46:06.708: DEBUG/Test Marker(541): I: 3 X: -122.095897 Y: 37.423633
06-27 01:46:06.718: DEBUG/Test Marker(541): I: 4 X: -122.095897 Y: 37.423633
06-27 01:46:06.718: DEBUG/Test Marker(541): I: 5 X: -122.095897 Y: 37.423633
06-27 01:46:06.728: DEBUG/Test Marker(541): I: 6 X: -122.095897 Y: 37.423633
06-27 01:46:06.739: DEBUG/Test Marker(541): I: 7 X: -122.095897 Y: 37.423633
06-27 01:46:06.739: DEBUG/Test Marker(541): I: 8 X: -122.095897 Y: 37.423633
06-27 01:46:06.739: DEBUG/Test Marker(541): I: 9 X: -122.095897 Y: 37.423633
06-27 01:46:06.748: DEBUG/Test Marker(541): I: 10 X: -122.095897 Y: 37.423633
06-27 01:46:06.748: DEBUG/Test Marker(541): I: 11 X: -122.095897 Y: 37.423633
06-27 01:46:06.748: DEBUG/Test Marker(541): I: 12 X: -122.095897 Y: 37.423633
06-27 01:46:06.748: DEBUG/Test Marker(541): I: 13 X: -122.095897 Y: 37.423633
06-27 01:46:06.758: DEBUG/Test Marker(541): I: 14 X: -122.095897 Y: 37.423633
06-27 01:46:06.758: DEBUG/Test Marker(541): I: 15 X: -122.095897 Y: 37.423633
</code>```

答:
your are initialise this code in wrong please. use this code </p>

```<code>ArrayList<Uri> ImageList = new ArrayList<Uri>();
</code>```

<p>inside </p>

```<code>@Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        ArrayList<Uri> ImageList = new ArrayList<Uri>();
        if(requestCode == PICK_FILE)
        {
            if(resultCode == RESULT_OK)
            {
                if(data.getClipData()!=null)
                {
                    int countClipData = data.getClipData().getItemCount();
                    int currentImageSelected = 0;

                    while (currentImageSelected < countClipData)
                    {
                        ImageUri = data.getClipData().getItemAt(currentImageSelected).getUri();
                        ImageList.add(ImageUri);
                        currentImageSelected = currentImageSelected +1;
                    }

                    Alert.setVisibility(View.VISIBLE);
                    Alert.setText("You Have Selected"+ImageList.size()+"Images");
                    Btn_Choose.setVisibility(View.GONE);
                }

                else
                    {
                        Toast.makeText(this, "Please select your car images", Toast.LENGTH_SHORT).show();
                    }
            }
        }
    }
}
</code>```

Title: ArrayList.add() not working correctly

Body:
So I have a function that gets some coordinates from a sql database and stores them in an arraylist. I am printing the values as I read them from the cursor and they are good. However when I immediately after loop through and print out the values I stored in the array list, all the values seem to be set to the last value I added to the arraylist. I am doing something wrong here?

code:

public ArrayList<Coord> getCoordMarkers(int myUserId)
{
    Log.d("getCoordMarkers()", "Called");
Coord myCoord = new Coord();
ArrayList<Coord> markerArray = new ArrayList<Coord>();
String sql = "SELECT "+ userId + " , " + timestamp + " , " + coordX + " , " +
                 coordY + " , " + coordType + " , " + coordId + " , " + coordTypeTable+ "." +
                 coordTypeDesc + " FROM " + coordTable + " JOIN " + coordTypeTable + " ON " +
                 coordTable + "." + coordType + " = " + coordTypeTable + "." + coordTypeAbbr +
                 " WHERE " + userId + " = '" + myUserId + "' AND " + coordTypeTable + "." +
                 coordTypeDesc + " != 'User Location';";
    // AND it is a marker
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cur = db.rawQuery(sql, null);
    if( cur.moveToFirst()) {
        do {
            myCoord.userId = cur.getInt(0);
            myCoord.timestamp = cur.getLong(1);
            myCoord.x = cur.getDouble(2);
            myCoord.y = cur.getDouble(3);
            myCoord.coordType = cur.getInt(4);
            myCoord.id = cur.getInt(5);
            myCoord.coordTypeDesc = cur.getString(6);
            markerArray.add(myCoord);
            Log.d("getCoordMarkers()", "X: " + myCoord.x + " Y: " + myCoord.y);
        } while( cur.moveToNext());
    }
    cur.close();
    db.close();
    for( int i = 0; i < markerArray.size(); i++ )
    {
        Coord myCoord2 = markerArray.get(i);
        Log.d("Test Marker", "I: "+ i + " X: " + myCoord2.x + " Y: "+ myCoord2.y);

    }
    return markerArray;
}

The following is the log printout from the above code

06-27 01:46:06.588: DEBUG/getCoordMarkers()(541): Called
06-27 01:46:06.638: DEBUG/getCoordMarkers()(541): X: -122.093451 Y: 37.420599
06-27 01:46:06.638: DEBUG/getCoordMarkers()(541): X: -122.093451 Y: 37.420599
06-27 01:46:06.648: DEBUG/getCoordMarkers()(541): X: -122.094695 Y: 37.419679
06-27 01:46:06.648: DEBUG/getCoordMarkers()(541): X: -122.094695 Y: 37.419679
06-27 01:46:06.648: DEBUG/getCoordMarkers()(541): X: -122.090104 Y: 37.423633
06-27 01:46:06.658: DEBUG/getCoordMarkers()(541): X: -122.090104 Y: 37.423633
06-27 01:46:06.658: DEBUG/getCoordMarkers()(541): X: -122.092078 Y: 37.420464
06-27 01:46:06.658: DEBUG/getCoordMarkers()(541): X: -122.092078 Y: 37.420464
06-27 01:46:06.658: DEBUG/getCoordMarkers()(541): X: -122.091992 Y: 37.420668
06-27 01:46:06.668: DEBUG/getCoordMarkers()(541): X: -122.091992 Y: 37.420668
06-27 01:46:06.668: DEBUG/getCoordMarkers()(541): X: -122.09594 Y: 37.42077
06-27 01:46:06.678: DEBUG/getCoordMarkers()(541): X: -122.09594 Y: 37.42077
06-27 01:46:06.678: DEBUG/getCoordMarkers()(541): X: -122.09255 Y: 37.42118
06-27 01:46:06.678: DEBUG/getCoordMarkers()(541): X: -122.09255 Y: 37.42118
06-27 01:46:06.688: DEBUG/getCoordMarkers()(541): X: -122.095897 Y: 37.423633
06-27 01:46:06.698: DEBUG/getCoordMarkers()(541): X: -122.095897 Y: 37.423633
06-27 01:46:06.708: DEBUG/Test Marker(541): I: 0 X: -122.095897 Y: 37.423633
06-27 01:46:06.708: DEBUG/Test Marker(541): I: 1 X: -122.095897 Y: 37.423633
06-27 01:46:06.708: DEBUG/Test Marker(541): I: 2 X: -122.095897 Y: 37.423633
06-27 01:46:06.708: DEBUG/Test Marker(541): I: 3 X: -122.095897 Y: 37.423633
06-27 01:46:06.718: DEBUG/Test Marker(541): I: 4 X: -122.095897 Y: 37.423633
06-27 01:46:06.718: DEBUG/Test Marker(541): I: 5 X: -122.095897 Y: 37.423633
06-27 01:46:06.728: DEBUG/Test Marker(541): I: 6 X: -122.095897 Y: 37.423633
06-27 01:46:06.739: DEBUG/Test Marker(541): I: 7 X: -122.095897 Y: 37.423633
06-27 01:46:06.739: DEBUG/Test Marker(541): I: 8 X: -122.095897 Y: 37.423633
06-27 01:46:06.739: DEBUG/Test Marker(541): I: 9 X: -122.095897 Y: 37.423633
06-27 01:46:06.748: DEBUG/Test Marker(541): I: 10 X: -122.095897 Y: 37.423633
06-27 01:46:06.748: DEBUG/Test Marker(541): I: 11 X: -122.095897 Y: 37.423633
06-27 01:46:06.748: DEBUG/Test Marker(541): I: 12 X: -122.095897 Y: 37.423633
06-27 01:46:06.748: DEBUG/Test Marker(541): I: 13 X: -122.095897 Y: 37.423633
06-27 01:46:06.758: DEBUG/Test Marker(541): I: 14 X: -122.095897 Y: 37.423633
06-27 01:46:06.758: DEBUG/Test Marker(541): I: 15 X: -122.095897 Y: 37.423633

Body:
your are initialise this code in wrong please. use this code

ArrayList<Uri> ImageList = new ArrayList<Uri>();

inside

@Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        ArrayList<Uri> ImageList = new ArrayList<Uri>();
        if(requestCode == PICK_FILE)
        {
            if(resultCode == RESULT_OK)
            {
                if(data.getClipData()!=null)
                {
                    int countClipData = data.getClipData().getItemCount();
                    int currentImageSelected = 0;

                    while (currentImageSelected < countClipData)
                    {
                        ImageUri = data.getClipData().getItemAt(currentImageSelected).getUri();
                        ImageList.add(ImageUri);
                        currentImageSelected = currentImageSelected +1;
                    }

                    Alert.setVisibility(View.VISIBLE);
                    Alert.setText("You Have Selected"+ImageList.size()+"Images");
                    Btn_Choose.setVisibility(View.GONE);
                }

                else
                    {
                        Toast.makeText(this, "Please select your car images", Toast.LENGTH_SHORT).show();
                    }
            }
        }
    }
}


问:
How to mod_write query param to path for arbitrarily long path?
I'm building a simple API with apache and I want to map /really/long/path/api/captions.php?caption_id=blah to /really/long/path/api/captions/blah. It's important to NOT have to specify a full path in the rewrite rule because I want this to work no matter where I deploy this code to. However, I can't find/figure out a working example of .htaccess rewrite rules that enable me to match based upon only the final part of the extension.

So, assuming that I have, say, captions.php in a dir called api, what .htaccess file do I need to include in api to accomplish this transform without having /really/long/path/ anywhere therein?

(I also want to be able to map /really/long/path/api/captions.php to /really/long/path/api/captions/ and /really/long/path/api/captions.)

I've tried all sorts of wildcard-like syntax; here's one of those non-working attempts:

```<code>RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*?)/?captions/(.*?)/?$ /captions.php?caption_id=$1 [L]
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /captions\.php\?caption_id=([^\&\ ]+)
RewriteRule ^(.*?)/?captions\.php$ /captions/%1? [L,R=301]
</code>```

Thanks!

答:
Got there in the end. This is all that was needed:</p>

```<code>RewriteEngine On # Turn on the rewriting engine
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^captions/?$ captions.php [NC,L]
RewriteRule ^captions/(.*)/?$ captions.php?caption_id=$1 [NC,L]
</code>```

Body:
I'm building a simple API with apache and I want to map /really/long/path/api/captions.php?caption_id=blah to /really/long/path/api/captions/blah. It's important to NOT have to specify a full path in the rewrite rule because I want this to work no matter where I deploy this code to. However, I can't find/figure out a working example of .htaccess rewrite rules that enable me to match based upon only the final part of the extension.

So, assuming that I have, say, captions.php in a dir called api, what .htaccess file do I need to include in api to accomplish this transform without having /really/long/path/ anywhere therein?

(I also want to be able to map /really/long/path/api/captions.php to /really/long/path/api/captions/ and /really/long/path/api/captions.)

I've tried all sorts of wildcard-like syntax; here's one of those non-working attempts:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*?)/?captions/(.*?)/?$ /captions.php?caption_id=$1 [L]
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /captions\.php\?caption_id=([^\&\ ]+)
RewriteRule ^(.*?)/?captions\.php$ /captions/%1? [L,R=301]

Thanks!

Body:
Got there in the end. This is all that was needed:

RewriteEngine On # Turn on the rewriting engine
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^captions/?$ captions.php [NC,L]
RewriteRule ^captions/(.*)/?$ captions.php?caption_id=$1 [NC,L]


问:
Changing the direction of player movement in accordance to camera
I'm trying to make an first person camera and the camera and player movement work exactly how I need them to however my issue now is that if I look to the right with the camera and press W to move forward it moves forward an accordance to the game world rather than the direction the camera is looking.

I've tried changing the parenting, or using a transform to link the player and camera together.

```<code>// Simple Player movement
Rigidbody rb;
public float speed;

void Start()
{
    rb = GetComponent<Rigidbody>();
}

void FixedUpdate()
{
    float mH = Input.GetAxis("Horizontal");
    float mV = Input.GetAxis("Vertical");
    rb.velocity = new Vector3(mH * speed, rb.velocity.y, mV * speed);
}
</code>```

```<code>// Camera controls (separate script)
private Transform playerBody;

void update()
{
    CameraRotation();
}

private void CameraRotation()
{
    float mouseX = Input.GetAxis(mouseXInputName) * mouseSensitivity * Time.deltaTime;
    float mouseY = Input.GetAxis(mouseYInputName) * mouseSensitivity * Time.deltaTime;
    xAxisClamp += mouseY;

    if (xAxisClamp > 90.0f)
    {
        xAxisClamp = 90.0f;
        mouseY = 0.0f;
        ClampAxisRotationToValue(270.0f);
    }
    else if (xAxisClamp < -90.0f)
    {
        xAxisClamp = -90.0f;
        mouseY = 0.0f;
        ClampAxisRotationToValue(90.0f);
    }
    transform.Rotate(Vector3.left * mouseY);
    playerBody.Rotate(Vector3.up * mouseX);
}
</code>```

With the last line playerBody.rotate I was expecting it to rotate the Object the camera is attached to so when i press forward it would move forward in the direction the camera is looking but it still moves in its static X and Z while ignoring the cameras direction.

答:
When you're moving your character, you're setting its velocity relative to the world's axises and does not take object rotation into consideration.

To add object rotation into the input, simply base the input on the rotation like this:

```<code>void FixedUpdate()
{
    Vector3 mH = transform.right * Input.GetAxis("Horizontal");
    Vector3 mV = transform.forward * Input.GetAxis("Vertical");
    rb.velocity = (mH + mV) * speed;
}
</code>```

The mH & mV should now be relative to where your object is facing because transform.forward (and .right) will be a representation of what "forward" is for your object.

And since GetAxis() will represent a number between -1 & 1 we're basically saying that the Input.GetAxis determines HOW MUCH forward we want to go. 1 or -1? Forward or backwards? forward * 1 or forward * -1. Same with strafing; right * 1 or right * -1.

Body:
I'm trying to make an first person camera and the camera and player movement work exactly how I need them to however my issue now is that if I look to the right with the camera and press W to move forward it moves forward an accordance to the game world rather than the direction the camera is looking.

I've tried changing the parenting, or using a transform to link the player and camera together.

// Simple Player movement
Rigidbody rb;
public float speed;

void Start()
{
    rb = GetComponent<Rigidbody>();
}

void FixedUpdate()
{
    float mH = Input.GetAxis("Horizontal");
    float mV = Input.GetAxis("Vertical");
    rb.velocity = new Vector3(mH * speed, rb.velocity.y, mV * speed);
}

// Camera controls (separate script)
private Transform playerBody;

void update()
{
    CameraRotation();
}

private void CameraRotation()
{
    float mouseX = Input.GetAxis(mouseXInputName) * mouseSensitivity * Time.deltaTime;
    float mouseY = Input.GetAxis(mouseYInputName) * mouseSensitivity * Time.deltaTime;
    xAxisClamp += mouseY;

    if (xAxisClamp > 90.0f)
    {
        xAxisClamp = 90.0f;
        mouseY = 0.0f;
        ClampAxisRotationToValue(270.0f);
    }
    else if (xAxisClamp < -90.0f)
    {
        xAxisClamp = -90.0f;
        mouseY = 0.0f;
        ClampAxisRotationToValue(90.0f);
    }
    transform.Rotate(Vector3.left * mouseY);
    playerBody.Rotate(Vector3.up * mouseX);
}

With the last line playerBody.rotate I was expecting it to rotate the Object the camera is attached to so when i press forward it would move forward in the direction the camera is looking but it still moves in its static X and Z while ignoring the cameras direction.

Body:
When you're moving your character, you're setting its velocity relative to the world's axises and does not take object rotation into consideration.

To add object rotation into the input, simply base the input on the rotation like this:

void FixedUpdate()
{
    Vector3 mH = transform.right * Input.GetAxis("Horizontal");
    Vector3 mV = transform.forward * Input.GetAxis("Vertical");
    rb.velocity = (mH + mV) * speed;
}

The mH & mV should now be relative to where your object is facing because transform.forward (and .right) will be a representation of what "forward" is for your object.

And since GetAxis() will represent a number between -1 & 1 we're basically saying that the Input.GetAxis determines HOW MUCH forward we want to go. 1 or -1? Forward or backwards? forward * 1 or forward * -1. Same with strafing; right * 1 or right * -1.


问:
Powershell Get -ChildItem: filtering csv files and -Recurse not working
I created a short powershell script to convert csv files from Unicode to UTF-8 encoding. My script outputs new files with the the original file name preceded by UTF8. I'm running into two issues:

I'm trying to only run the powershell script on csv files. Currently the script runs on every file in the directory, including the powershell script (it outputs a new file called UTF8pshell_script if the powershell script was called pshell_script for example). The other methods where I've tried to only run the script on csv files just end up making the script not do anything.

I'm trying to run the script on sub-directories. The first issue is that output files created from csv files in subdirectories have no content inside them whatsoever. If the script is ran in the same directory as the csv file this problem does not arise. This is not crucial but I am also uncertain how to get output files created from those in subdirectories to be outputted in the same subdirectories (currently they are outputted in the main directory where the powershell script is).
as

```<code>    Get-Content -Encoding Unicode $_ | Out-File -Encoding UTF8
    Get-ChildItem -Recurse | ForEach-Object {Get-Content -Encoding Unicode $_ | Out-File -Encoding UTF8 "UTF8$_"}
</code>```

The desired output is the powershell script running on only csv files, and outputting files to the same subdirectories where the files they were created form are.

答:
Depending on the original encoding (and presence of a BOM) you might have to specify an encoding also on the input side.</p>

```<code>ForEach($Csv in (Get-ChildItem -Filter *.csv -Recurse -Exclude UTF8*)){
  (Get-Content $Csv.FullName -raw) |
    Set-Content -Path {Join-Path $Csv.Directory ("UTF8"+$Csv.Name)} -Encoding UTF8
}
</code>```

Body:
I created a short powershell script to convert csv files from Unicode to UTF-8 encoding. My script outputs new files with the the original file name preceded by UTF8. I'm running into two issues:

I'm trying to only run the powershell script on csv files. Currently the script runs on every file in the directory, including the powershell script (it outputs a new file called UTF8pshell_script if the powershell script was called pshell_script for example). The other methods where I've tried to only run the script on csv files just end up making the script not do anything.

I'm trying to run the script on sub-directories. The first issue is that output files created from csv files in subdirectories have no content inside them whatsoever. If the script is ran in the same directory as the csv file this problem does not arise. This is not crucial but I am also uncertain how to get output files created from those in subdirectories to be outputted in the same subdirectories (currently they are outputted in the main directory where the powershell script is).
as

    Get-Content -Encoding Unicode $_ | Out-File -Encoding UTF8
    Get-ChildItem -Recurse | ForEach-Object {Get-Content -Encoding Unicode $_ | Out-File -Encoding UTF8 "UTF8$_"}

The desired output is the powershell script running on only csv files, and outputting files to the same subdirectories where the files they were created form are.

Body:
Depending on the original encoding (and presence of a BOM) you might have to specify an encoding also on the input side.

ForEach($Csv in (Get-ChildItem -Filter *.csv -Recurse -Exclude UTF8*)){
  (Get-Content $Csv.FullName -raw) |
    Set-Content -Path {Join-Path $Csv.Directory ("UTF8"+$Csv.Name)} -Encoding UTF8
}


问:
How to Call C++ Setters & Getters from Haskell
I know how to call pure C++ functions from Haskell, but wondering how to get GHC to accept functions that have side effects.

I want Haskell to have read-only access to a C++ linked list, and exclusive write access to a C++ variable. For example:

```<code>class node {
    // Some other class makes a linked list out of these
    int x;
    node* previous;
    node* next;
}

class myHaskellInterface {
    node* presentLocation; // C++ decides what is regarded as current location

    int getVal() {
        // Haskell calls this to get information from C++
        return presentLocation->x;
    }

    int haskellResults; // Store Haskell output here

    void setVal(int x) {
        // Haskell calls this to pass information back
        haskellResults = x;
    }

};
</code>```

Even though getVal() doesn't have side effects, it is part of a class that obviously has side effects, so it's not clear to me whether sneaky tricks are required to get GHC to accept it.

setVal(int) clearly has side effects, so how do you make GHC not care?

答:
Note that the production of side effects isn't the issue.  It's "impure" versus "pure" functions that are important.  While getVal doesn't cause side effects, it relies on side effects to produce a value because it consults presentLocation.  In other words, it's an impure function.

Haskell can call foreign functions whether they are pure or impure, you just need to give them appropriate signatures.  An impure function must be given an IO a return type.  A pure function can be given a non-IO return type.  (Of course, you could give a pure function an IO return type, too, but you don't have to and so usually wouldn't.)

For example, suppose we have the simple C++ "interface":

```<code>int value = 0;   // Haskell code sets value directly
extern "C" int getValue() { return value; }  // and gets it with this
</code>```

If we incorrectly try to import getValue as a pure function:

```<code>foreign import ccall "interface.cc &value" valuePtr :: Ptr CInt
foreign import ccall "interface.cc getValue" getValue :: CInt  -- **NO NO NO!!!**
</code>```

and test it like so:

```<code>main :: IO ()
main = do
  print getValue
  poke valuePtr 5
  print getValue
</code>```

we get incorrect output:

```<code>0
0
</code>```

Instead, we need to give getValue a type IO CInt:

```<code>foreign import ccall "interface.cc getValue" getValue :: IO CInt
</code>```

With appropriate modifications to the rest of the program:

```<code>import Foreign
import Foreign.C

foreign import ccall "interface.cc &value" valuePtr :: Ptr CInt
foreign import ccall "interface.cc getValue" getValue :: IO CInt

main :: IO ()
main = do
  print =<< getValue
  poke valuePtr 5
  print =<< getValue
</code>```

the output is as expected:

```<code>0
5
</code>```

Note that it's only the return value that should be given an IO type.  If we add an impure function that takes arguments, like:

```<code>extern "C" int getMultValue(int scale) { return value*scale; }
</code>```

then you'd use:

```<code>foreign import ccall "interface.cc getMultValue" getMultValue :: CInt -> IO CInt
</code>```

The full programs:

```<code>// interface.cc
int value = 0;
extern "C" int getValue() { return value; }
extern "C" int getMultValue(int scale) { return value*scale; }

-- Main.hs
import Foreign
import Foreign.C

foreign import ccall "interface.cc &value" valuePtr :: Ptr CInt
foreign import ccall "interface.cc getValue" getValue :: IO CInt
foreign import ccall "interface.cc getMultValue" getMultValue :: CInt -> IO CInt

main :: IO ()
main = do
  print =<< getValue
  poke valuePtr 5
  print =<< getValue
  print =<< getMultValue 5
</code>```

Note that things will get a little more complicated when the functions or variables in question are actually methods / instance variables.  Haskell doesn't directly support working with C++ objects, so you need to build some kind of extern "C" interface and pass object pointers as explicit arguments.  If you run into trouble a little further along in your design, maybe post additional questions and we'll try to help.

Body:
I know how to call pure C++ functions from Haskell, but wondering how to get GHC to accept functions that have side effects.

I want Haskell to have read-only access to a C++ linked list, and exclusive write access to a C++ variable. For example:

class node {
    // Some other class makes a linked list out of these
    int x;
    node* previous;
    node* next;
}

class myHaskellInterface {
    node* presentLocation; // C++ decides what is regarded as current location

    int getVal() {
        // Haskell calls this to get information from C++
        return presentLocation->x;
    }

    int haskellResults; // Store Haskell output here

    void setVal(int x) {
        // Haskell calls this to pass information back
        haskellResults = x;
    }

};

Even though getVal() doesn't have side effects, it is part of a class that obviously has side effects, so it's not clear to me whether sneaky tricks are required to get GHC to accept it.

setVal(int) clearly has side effects, so how do you make GHC not care?

Body:
Note that the production of side effects isn't the issue.  It's "impure" versus "pure" functions that are important.  While getVal doesn't cause side effects, it relies on side effects to produce a value because it consults presentLocation.  In other words, it's an impure function.

Haskell can call foreign functions whether they are pure or impure, you just need to give them appropriate signatures.  An impure function must be given an IO a return type.  A pure function can be given a non-IO return type.  (Of course, you could give a pure function an IO return type, too, but you don't have to and so usually wouldn't.)

For example, suppose we have the simple C++ "interface":

int value = 0;   // Haskell code sets value directly
extern "C" int getValue() { return value; }  // and gets it with this

If we incorrectly try to import getValue as a pure function:

foreign import ccall "interface.cc &value" valuePtr :: Ptr CInt
foreign import ccall "interface.cc getValue" getValue :: CInt  -- **NO NO NO!!!**

and test it like so:

main :: IO ()
main = do
  print getValue
  poke valuePtr 5
  print getValue

we get incorrect output:

0
0

Instead, we need to give getValue a type IO CInt:

foreign import ccall "interface.cc getValue" getValue :: IO CInt

With appropriate modifications to the rest of the program:

import Foreign
import Foreign.C

foreign import ccall "interface.cc &value" valuePtr :: Ptr CInt
foreign import ccall "interface.cc getValue" getValue :: IO CInt

main :: IO ()
main = do
  print =<< getValue
  poke valuePtr 5
  print =<< getValue

the output is as expected:

0
5

Note that it's only the return value that should be given an IO type.  If we add an impure function that takes arguments, like:

extern "C" int getMultValue(int scale) { return value*scale; }

then you'd use:

foreign import ccall "interface.cc getMultValue" getMultValue :: CInt -> IO CInt

The full programs:

// interface.cc
int value = 0;
extern "C" int getValue() { return value; }
extern "C" int getMultValue(int scale) { return value*scale; }

-- Main.hs
import Foreign
import Foreign.C

foreign import ccall "interface.cc &value" valuePtr :: Ptr CInt
foreign import ccall "interface.cc getValue" getValue :: IO CInt
foreign import ccall "interface.cc getMultValue" getMultValue :: CInt -> IO CInt

main :: IO ()
main = do
  print =<< getValue
  poke valuePtr 5
  print =<< getValue
  print =<< getMultValue 5

Note that things will get a little more complicated when the functions or variables in question are actually methods / instance variables.  Haskell doesn't directly support working with C++ objects, so you need to build some kind of extern "C" interface and pass object pointers as explicit arguments.  If you run into trouble a little further along in your design, maybe post additional questions and we'll try to help.


问:
Function returns True instead of False over iteration
I am doing some challenges on edabit and I came across a problem with my output. So i have to Create a function that takes in an array (slot machine outcome) and returns true if all elements in the array are identical, and false otherwise. The array will contain 4 elements. Can someone explain why my code isn't working the right way.

I have tried with other inputs and it's working fine.

```<code>   'use strict';

   function array_Validator(e1,e2,e3,e4)
   {
       let m_Array=[e1,e2,e3,e4];
       for(let i=0;i<m_Array.length-1;i++)
       {
           for(let x=i;x<m_Array.length-1;x++)
           {
               if(m_Array[i]!==m_Array[x+1])
               {
                   return false;
               }
               else
               return true;
           }
       }
   }

  let u_Result=array_Validator("SS","SS","Ss","Ss");

   console.log(u_Result);
</code>```

So when I input Ss it shoes true instead of false.

答:
https://stackoverflow.com/a/24968449/11178909

Answer provided, do not use a double for loop for this method first of all

Body:
I am doing some challenges on edabit and I came across a problem with my output. So i have to Create a function that takes in an array (slot machine outcome) and returns true if all elements in the array are identical, and false otherwise. The array will contain 4 elements. Can someone explain why my code isn't working the right way.

I have tried with other inputs and it's working fine.

   'use strict';

   function array_Validator(e1,e2,e3,e4)
   {
       let m_Array=[e1,e2,e3,e4];
       for(let i=0;i<m_Array.length-1;i++)
       {
           for(let x=i;x<m_Array.length-1;x++)
           {
               if(m_Array[i]!==m_Array[x+1])
               {
                   return false;
               }
               else
               return true;
           }
       }
   }

  let u_Result=array_Validator("SS","SS","Ss","Ss");

   console.log(u_Result);

So when I input Ss it shoes true instead of false.


问:
SFX installer fails to run powershell script after powershell window is opened
I am creating an 7zip sfx installer in latest Windows 10 which is expected to run a powershell script. when extraction is done, the powershell window is shown up but quickly closed without executing the script.

Any help is much appreciated!

I have tried to sign the script file and the installer.exe itself with self signed certificate, but no luck.

I have changed the Powershell ExecutionPolicy to Unrestricted for all scopes for troubleshooting, but no luck either

I use process monitor in sysinternals to capture the powershell.exe behavor, and found powershell starts to exit thread after reading and writing c:\Users\xxx\AppData\Local\Microsoft\Windows\PowerShell\StartupProfileData-Interactive

Here is my config.txt for 7zip sfx:

```<code>;!@Install@!UTF-8!
Title="Cloud API"
BeginPrompt="Do you want to install Cloud API?"
RunProgram="powershell.exe -NoExit –NoProfile -ExecutionPolicy Bypass -File %%T\\cloud_api\\installer.PS1"
Directory="C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\"
;!@InstallEnd@!
</code>```

I am zipping the files in python by:

..\\7zr a -sfx7zSD.sfx cloud-api.7z .\\cloud-api -r -y
```

I am expecting the installer.PS1 getting executed after unzipping, but only powershell.exe is run and exit quickly without running the script at all.

答: A first step to troubleshooting this problem would be to declare the full path of the .ps1 script in your 7zip config. This will ensure you are calling the script you intend to launch.

Body:
I am creating an 7zip sfx installer in latest Windows 10 which is expected to run a powershell script. when extraction is done, the powershell window is shown up but quickly closed without executing the script.

Any help is much appreciated!

I have tried to sign the script file and the installer.exe itself with self signed certificate, but no luck.

I have changed the Powershell ExecutionPolicy to Unrestricted for all scopes for troubleshooting, but no luck either

I use process monitor in sysinternals to capture the powershell.exe behavor, and found powershell starts to exit thread after reading and writing c:\Users\xxx\AppData\Local\Microsoft\Windows\PowerShell\StartupProfileData-Interactive

Here is my config.txt for 7zip sfx:

;!@Install@!UTF-8!
Title="Cloud API"
BeginPrompt="Do you want to install Cloud API?"
RunProgram="powershell.exe -NoExit –NoProfile -ExecutionPolicy Bypass -File %%T\\cloud_api\\installer.PS1"
Directory="C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\"
;!@InstallEnd@!

I am zipping the files in python by:

..\\7zr a -sfx7zSD.sfx cloud-api.7z .\\cloud-api -r -y

I am expecting the installer.PS1 getting executed after unzipping, but only powershell.exe is run and exit quickly without running the script at all.


问:
Multiple where clauses, reading only one
I have to retrieve information with multiple where clauses. I can do this only using nested query. I'm supposed to be able to pull out information of 2 shiftName queries on one command.
Find the first and last name of a staff whose shifts are Classy Evening and Morning Shine.

So far whatever little luck I've found is with this code, but the problem here is it is returning results of 'Morning Shine' but not of 'Classy Evening'.
It's like the nested query is not even being processed. Can someone please help. I'm new to SQL so I apologise if my question is not clear enough.

```<code>SELECT stfName, stlNname
FROM STAFF, STAFF_SHIFT_CENTER
WHERE STAFF.staffID=STAFF_SHIFT_CENTER.staffID
AND STAFF_SHIFT_CENTER.shiftName='Morning Shine'
AND (SELECT staffID FROM STAFF_SHIFT_CENTER
WHERE shiftName='Classy Evening');
</code>```

答:
where is a condition.

When you want to do a condition with another query you need to give the column that you want to compare.

You didn't give a column to compare so it ignored your second part of the where condition.

In your case you want the staffID of 'Morning Shine' and 'Classy Evening' will be equal.

so you need to do:

```<code>SELECT stfName, stlNname
FROM STAFF, STAFF_SHIFT_CENTER
WHERE STAFF.staffID=STAFF_SHIFT_CENTER.staffID
AND STAFF_SHIFT_CENTER.shiftName='Morning Shine'
AND STAFF_SHIFT_CENTER.staffID IN (SELECT staffID FROM STAFF_SHIFT_CENTER
WHERE shiftName='Classy Evening');
</code>```

In addition, I recommend you to use JOIN instead of CARTESIAN to improve your query.

So the query will be:

```<code>SELECT stfName, stlNname
FROM STAFF s JOIN STAFF_SHIFT_CENTER ssc
     ON s.staffID=ssc.staffID
WHERE ssc.shiftName='Morning Shine'
AND ssc.staffID IN (SELECT staffID FROM STAFF_SHIFT_CENTER
WHERE shiftName='Classy Evening');
</code>```

Body:
I have to retrieve information with multiple where clauses. I can do this only using nested query. I'm supposed to be able to pull out information of 2 shiftName queries on one command.
Find the first and last name of a staff whose shifts are Classy Evening and Morning Shine.

So far whatever little luck I've found is with this code, but the problem here is it is returning results of 'Morning Shine' but not of 'Classy Evening'.
It's like the nested query is not even being processed. Can someone please help. I'm new to SQL so I apologise if my question is not clear enough.

SELECT stfName, stlNname
FROM STAFF, STAFF_SHIFT_CENTER
WHERE STAFF.staffID=STAFF_SHIFT_CENTER.staffID
AND STAFF_SHIFT_CENTER.shiftName='Morning Shine'
AND (SELECT staffID FROM STAFF_SHIFT_CENTER
WHERE shiftName='Classy Evening');

Body:
where is a condition.

When you want to do a condition with another query you need to give the column that you want to compare.

You didn't give a column to compare so it ignored your second part of the where condition.

In your case you want the staffID of 'Morning Shine' and 'Classy Evening' will be equal.

so you need to do:

SELECT stfName, stlNname
FROM STAFF, STAFF_SHIFT_CENTER
WHERE STAFF.staffID=STAFF_SHIFT_CENTER.staffID
AND STAFF_SHIFT_CENTER.shiftName='Morning Shine'
AND STAFF_SHIFT_CENTER.staffID IN (SELECT staffID FROM STAFF_SHIFT_CENTER
WHERE shiftName='Classy Evening');

In addition, I recommend you to use JOIN instead of CARTESIAN to improve your query.

So the query will be:

SELECT stfName, stlNname
FROM STAFF s JOIN STAFF_SHIFT_CENTER ssc
     ON s.staffID=ssc.staffID
WHERE ssc.shiftName='Morning Shine'
AND ssc.staffID IN (SELECT staffID FROM STAFF_SHIFT_CENTER
WHERE shiftName='Classy Evening');


问:
ValueError: could not convert string to float <ipython-input-5-1a15d1ec0505> in <module>()
I am trying to implement KNN but when i transform X_train and X_test it gives error, I am new please any help regarding this.

```<code>scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
</code>```

It gives error "could not convert string to float"
what to do?

答:
The first thing I do when I see an error like this is to check my inputs. If you're getting a "could not convert string to float" error, you probably have a non-numeric string somewhere in your inputs (because it looks like this KNN function only takes numbers as input).

I'm assuming X_train and X_test are dataframes--try running the following for each column in your dataframe:

```<code>for i in range(len(X_train.columns)):
    try:
        [float(j) for j in X_train[X_train.columns[i]]]
        print(X_train.columns[i],' is all-numeric')
    except:
        pass
</code>```

Whichever column doesn't print when you run this is the one you need to look at and see if you can clean up the non-numeric entries in that column.

Edit: if you have a column of only non-numeric strings (for example, "Iris-setosa","Iris-versicolor", etc), you will have to convert them into numbers or Dummy Variable columns for the purposes of the KNN function.

Edit 2: Whoooops. I wrote bad code. Fixed it.

Body:
I am trying to implement KNN but when i transform X_train and X_test it gives error, I am new please any help regarding this.

scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)

It gives error "could not convert string to float"
what to do?

Body:
The first thing I do when I see an error like this is to check my inputs. If you're getting a "could not convert string to float" error, you probably have a non-numeric string somewhere in your inputs (because it looks like this KNN function only takes numbers as input).

I'm assuming X_train and X_test are dataframes--try running the following for each column in your dataframe:

for i in range(len(X_train.columns)):
    try:
        [float(j) for j in X_train[X_train.columns[i]]]
        print(X_train.columns[i],' is all-numeric')
    except:
        pass

Whichever column doesn't print when you run this is the one you need to look at and see if you can clean up the non-numeric entries in that column.

Edit: if you have a column of only non-numeric strings (for example, "Iris-setosa","Iris-versicolor", etc), you will have to convert them into numbers or Dummy Variable columns for the purposes of the KNN function.

Edit 2: Whoooops. I wrote bad code. Fixed it.


问:
A good database schema
ok so i have this problem that i need to achieve...Here is my site

What i need to do is for each product sold i need to have 2 other products that are either an upgrade or a downgrade.

so there each product has 3 classes standard, business, and premium and based on what the current product is they either increase or decrease in price..

so basically they are customizing each solution. So what i need is figure out the best way to structure my db for this...here is the query i use to pull what i have now

```<code> $query = "SELECT p.ProductName, p.price, pc.quantity, p.ProductImage, p.Features
            FROM productinfo as p
              join preconfig_categories as pc on p.ProductID = pc.product_id
              join preconfig as c on c.id = pc.category_id
              join subcategory as sc on p.SubCategoryID = sc.SubCategoryID
              WHERE  c.code      = '{$type}_{$count}_{$class}'
              order by sc.ordering";
</code>```

I was thinking of in the productinfo table which is currently structured like this

```<code>CREATE TABLE `productinfo` (
  `ProductID` int(11) NOT NULL AUTO_INCREMENT,
  `ProductName` varchar(255) NOT NULL,
  `ProductImage` varchar(255) NOT NULL,
  `CategoryID` int(11) NOT NULL,
  `SubCategoryID` int(11) NOT NULL,
  `ProductBrief` varchar(255) NOT NULL,
  `Features` text NOT NULL,
  `Specifications` text NOT NULL,
  `Reviews` text NOT NULL,
  `Price` varchar(255) NOT NULL,
  `Status` tinyint(4) NOT NULL,
  `PartName` varchar(255) NOT NULL,
  `skip_step` tinyint(1) DEFAULT NULL,
  PRIMARY KEY (`ProductID`)
) ENGINE=MyISAM AUTO_INCREMENT=164 DEFAULT CHARSET=latin1;
</code>```

I was thinking off adding three extra fields

```<code>class
product1
product2
</code>```

so basically i can use the class to tell what the current product is and then the other two fields product1 and product2 which will have the ProductID of the other two products....This seems like it could work but i feel like theres probably a better solution out there then can work a bit better....any ideas input would be strongly appreciated

答:
I would suggest have one table with the Product information.  A second table with the class of product (Standard, Business, Premium) and then a third table where you map your client's purchase to the product information ID and the Product Class ID.

So if you need to add a new class of product in the future (Freeware, Premium Deluxe etc) you just add it to the Product Class table and then you can map this in the mapping table.

So when a client purchases a product you map the Product ID and Product Class ID in the mapping table.  If they downgrade, you update the mapping table to now map the Product ID to the downgraded Product Class ID.

Title: A good database schema

Body:
ok so i have this problem that i need to achieve...Here is my site

What i need to do is for each product sold i need to have 2 other products that are either an upgrade or a downgrade.

so there each product has 3 classes standard, business, and premium and based on what the current product is they either increase or decrease in price..

so basically they are customizing each solution. So what i need is figure out the best way to structure my db for this...here is the query i use to pull what i have now

 $query = "SELECT p.ProductName, p.price, pc.quantity, p.ProductImage, p.Features
            FROM productinfo as p
              join preconfig_categories as pc on p.ProductID = pc.product_id
              join preconfig as c on c.id = pc.category_id
              join subcategory as sc on p.SubCategoryID = sc.SubCategoryID
              WHERE  c.code      = '{$type}_{$count}_{$class}'
              order by sc.ordering";

I was thinking of in the productinfo table which is currently structured like this

CREATE TABLE `productinfo` (
  `ProductID` int(11) NOT NULL AUTO_INCREMENT,
  `ProductName` varchar(255) NOT NULL,
  `ProductImage` varchar(255) NOT NULL,
  `CategoryID` int(11) NOT NULL,
  `SubCategoryID` int(11) NOT NULL,
  `ProductBrief` varchar(255) NOT NULL,
  `Features` text NOT NULL,
  `Specifications` text NOT NULL,
  `Reviews` text NOT NULL,
  `Price` varchar(255) NOT NULL,
  `Status` tinyint(4) NOT NULL,
  `PartName` varchar(255) NOT NULL,
  `skip_step` tinyint(1) DEFAULT NULL,
  PRIMARY KEY (`ProductID`)
) ENGINE=MyISAM AUTO_INCREMENT=164 DEFAULT CHARSET=latin1;

I was thinking off adding three extra fields

class
product1
product2

so basically i can use the class to tell what the current product is and then the other two fields product1 and product2 which will have the ProductID of the other two products....This seems like it could work but i feel like theres probably a better solution out there then can work a bit better....any ideas input would be strongly appreciated


问:
Match two consecutive words in a sentence
I have a bunch of sentences and want to figure out if the sentence contains a specific set of consecutive words. As an example, I have a list like below

```<code>  list = ["Data Scientist",  "Data Analyst", "Data Engineer"]
</code>```

and have sentences like below

```<code>  Sentence1 = "I am first going to be a Data Analyst and then a Data Scientist"
  Sentence2 = "I only like to be a Data Engineer"
</code>```

with the desired output picking out "Data Analyst" and "Data Scientist" for Sentence1 and "Data Engineer" for Sentence2.

答:
Using Yatu's example data. Use regex which will be definitely faster than in operator

```<code>import re

l = ["Data Scientist",  "Data Analyst", "Data Engineer"]
Sentence1 = "I am first going to be a Data Analyst and then a Data Scientist"

re.findall("|".join(l),Sentence1)
</code>```

Output:

```<code>['Data Analyst', 'Data Scientist']
</code>```

Body:
I have a bunch of sentences and want to figure out if the sentence contains a specific set of consecutive words. As an example, I have a list like below

  list = ["Data Scientist",  "Data Analyst", "Data Engineer"]

and have sentences like below

  Sentence1 = "I am first going to be a Data Analyst and then a Data Scientist"
  Sentence2 = "I only like to be a Data Engineer"

with the desired output picking out "Data Analyst" and "Data Scientist" for Sentence1 and "Data Engineer" for Sentence2.

Body:
Using Yatu's example data. Use regex which will be definitely faster than in operator

import re

l = ["Data Scientist",  "Data Analyst", "Data Engineer"]
Sentence1 = "I am first going to be a Data Analyst and then a Data Scientist"

re.findall("|".join(l),Sentence1)

Output:

['Data Analyst', 'Data Scientist']


答:
You need to move return true to the end of the function and you could use a single loop and check the first element with each others.

'use strict';

function array_Validator(e1, e2, e3, e4) {
    let m_Array = [e1, e2, e3, e4];
    for (let i = 1; i < m_Array.length; i++) {
        if (m_Array[0] !== m_Array[i]) return false;
    }
    return true;
}

let u_Result = array_Validator("SS", "SS", "SS", "Ss");

console.log(u_Result);```

Title: Function returns True instead of False over iteration


答:
Do you want to append to a Word document or do you want to create the file?

Here is how to create a file and write your data to it:

```<code>with open(r'pathforfile/name.docx', 'w+') as f:
    f.write(r)
</code>```

Title: How can I send a print to a word document saved with a specific name?

Body:
I need to take this:

for k, v in r.items():
    f.write(str(v) + " " + str(k) + "\n")

and print it into a Word document, then save that word document with a name that I provide from within the code. How would I do this?

Body:
Do you want to append to a Word document or do you want to create the file?

Here is how to create a file and write your data to it:

with open(r'pathforfile/name.docx', 'w+') as f:
    f.write(r)


问:
Spanner - search by composite primary key behavior
When search by only one of primary key in composite primary key table Spanner behaviors is differ. For Example if a table has ColA and ColB as primary key( mentioned in the same order when defining primary key). If you search by first key select * from table where ColA = 'dfdf' then it scans few rows and brings result much faster ~10ms. But if you search by second key select * from table where ColB = 'dfdf' then it does full table scan. Why this inconsistency, if we are not searching by full key then it should do full table or particular rows scan. primary keys are indexed so it should never go to full table scan.

答:
A composite key is not 2 separate keys, but one single key concatenated from 2 parts...

Imagine a list of words, alphabetically sorted... Finding words whose first letter is H is easy...
But how would you find all words whose second letter is 'H'...

The only way is to do a complete scan of all the words -- unless there is a second index of words by their second letter, which is what secondary indexes are for ..


问:
Querying the 2nd Line from a command output in Perl
I need to query on the 2nd line which I am seeing in the output. I need to check if the command returns on "Listener LISTENER is running on" and provide the desired output. My code is able to read the first line and not the second line which I need to verify. Please advise.

```<code>srvctl status listener
Listener LISTENER is enabled
Listener LISTENER is running on node(s): XYZ
</code>```

I tried updating the code to read the second line and did not work.

```<code>my $cmd="srvctl status listener";
my $listenerstatus0;
my $msg0;
my $msg1;
open(Row1Stat,"$cmd |") || die ("Could not read the pipe\n");
$listenerstatus0 = <Row1Stat>;
close(Row1Stat);
while (<>){
if( $listenerstatus0 =~ m/Listener LISTENER is running/)
{
$msg0="LISTENER is running";
$msg1=1
}
elsif ($listenerstatus0 =~ m/Listener LISTENER is not running/) {
$msg0 = "LISTENER is not running";
$msg1 = 0;
}
else {
$msg0 = "Unable to Query LISTENER Status";
$msg1 = 0;
}
}

print "\nStatistic.Name1:$msg1";
print "\nMessage.Name1:$msg0";
</code>```

I should be able to read Listener LISTENER is running on node(s): XYZ

答:
You are reading only the first line from the pipe. You either need a loop (while <Row1Stat>) { ... }) and read all lines one at a time, or read the whole pipe contents in one go, e.g., by local $/ = undef;, which clears the input record separator (by default a newline).

Here's an example reading in a loop. I've removed the pipe to make it a Minimal Complete Verifiable Example, since the srvctl command is not really necessary.

```<code>use strict;
use warnings;

my $msg0 = "not running";
my $msg1 = 0;

while (<DATA>) {
    if (m/Listener LISTENER is running/) {
        $msg0 = "is running";
        $msg1 = 1;
    }
    elsif (m/Listener LISTENER is enabled/) {
        $msg0 = "is enabled";
        $msg1 = 2;
    }
}

print "Statistic.Name1:$msg1\n";
print "Message.Name1:$msg0\n";

__DATA__
srvctl status listener
Listener LISTENER is enabled
Listener LISTENER is running on node(s): XYZ
</code>```

You cannot use an else block to set "not running" cause you're reading line by line and don't want to override your found line later. Hence I initialize this when I declare the variables.

Now for slurping the whole pipe output and working on that:

```<code>use strict;
use warnings;

my $msg0;
my $msg1;

local $/ = undef;
my $data = <DATA>;

if ($data =~ m/Listener LISTENER is running/) {
    $msg0 = "is running";
    $msg1 = 1;
}
elsif ($data =~ m/Listener LISTENER is enabled/) {
    $msg0 = "is enabled";
    $msg1 = 2;
}
else {
    my $msg0 = "not running";
    my $msg1 = 0;
}

print "Statistic.Name1:$msg1\n";
print "Message.Name1:$msg0\n";

__DATA__
srvctl status listener
Listener LISTENER is enabled
Listener LISTENER is running on node(s): XYZ
</code>```

In both cases you need to decide which line ("LISTENER is enabled" or "LISTENER is running") is more important to you. When reading line by line, add a check that you don't overwrite your variables with the less important message. When slurping, adjust the order of the checks (ifs) so that the most important one goes first.

Body:
I need to query on the 2nd line which I am seeing in the output. I need to check if the command returns on "Listener LISTENER is running on" and provide the desired output. My code is able to read the first line and not the second line which I need to verify. Please advise.

srvctl status listener
Listener LISTENER is enabled
Listener LISTENER is running on node(s): XYZ

I tried updating the code to read the second line and did not work.

my $cmd="srvctl status listener";
my $listenerstatus0;
my $msg0;
my $msg1;
open(Row1Stat,"$cmd |") || die ("Could not read the pipe\n");
$listenerstatus0 = <Row1Stat>;
close(Row1Stat);
while (<>){
if( $listenerstatus0 =~ m/Listener LISTENER is running/)
{
$msg0="LISTENER is running";
$msg1=1
}
elsif ($listenerstatus0 =~ m/Listener LISTENER is not running/) {
$msg0 = "LISTENER is not running";
$msg1 = 0;
}
else {
$msg0 = "Unable to Query LISTENER Status";
$msg1 = 0;
}
}

print "\nStatistic.Name1:$msg1";
print "\nMessage.Name1:$msg0";

I should be able to read Listener LISTENER is running on node(s): XYZ

Body:
You are reading only the first line from the pipe. You either need a loop (while <Row1Stat>) { ... }) and read all lines one at a time, or read the whole pipe contents in one go, e.g., by local $/ = undef;, which clears the input record separator (by default a newline).

Here's an example reading in a loop. I've removed the pipe to make it a Minimal Complete Verifiable Example, since the srvctl command is not really necessary.

use strict;
use warnings;

my $msg0 = "not running";
my $msg1 = 0;

while (<DATA>) {
    if (m/Listener LISTENER is running/) {
        $msg0 = "is running";
        $msg1 = 1;
    }
    elsif (m/Listener LISTENER is enabled/) {
        $msg0 = "is enabled";
        $msg1 = 2;
    }
}

print "Statistic.Name1:$msg1\n";
print "Message.Name1:$msg0\n";

__DATA__
srvctl status listener
Listener LISTENER is enabled
Listener LISTENER is running on node(s): XYZ

You cannot use an else block to set "not running" cause you're reading line by line and don't want to override your found line later. Hence I initialize this when I declare the variables.

Now for slurping the whole pipe output and working on that:

use strict;
use warnings;

my $msg0;
my $msg1;

local $/ = undef;
my $data = <DATA>;

if ($data =~ m/Listener LISTENER is running/) {
    $msg0 = "is running";
    $msg1 = 1;
}
elsif ($data =~ m/Listener LISTENER is enabled/) {
    $msg0 = "is enabled";
    $msg1 = 2;
}
else {
    my $msg0 = "not running";
    my $msg1 = 0;
}

print "Statistic.Name1:$msg1\n";
print "Message.Name1:$msg0\n";

__DATA__
srvctl status listener
Listener LISTENER is enabled
Listener LISTENER is running on node(s): XYZ

In both cases you need to decide which line ("LISTENER is enabled" or "LISTENER is running") is more important to you. When reading line by line, add a check that you don't overwrite your variables with the less important message. When slurping, adjust the order of the checks (ifs) so that the most important one goes first.


问:
Sendgrid stopped sending emails via Expressjs
This is a very weird issue, but I don't know what is wrong with my app. I haven't committed any change, yet for some reason the app stopped sending emails, and shows an POST error: cannot find route api/example

I have a React component that has a email field and a button. When clicked, the button triggers a function:

```<code>sendMail() {
if (this.state.currentEmail !== "") {
  let lastAtPos = this.state.currentEmail.lastIndexOf("@");
  let lastDotPos = this.state.currentEmail.lastIndexOf(".");

  if (
    !(
      lastAtPos < lastDotPos &&
      lastAtPos > 0 &&
      this.state.currentEmail.indexOf("@@") === -1 &&
      lastDotPos > 2 &&
      this.state.currentEmail.length - lastDotPos > 2
    )
  ) {
    this.setState({ error: "Please, provide your real e-mail address!" });
  } else {
    this.setState({
      sending: true,
      buttonText: ""
    });

    let data = {
      email: this.state.currentEmail
    };

    axios
      .post("/api/subscribers", data)
      .then(res => {
        this.setState({ isSent: true }, this.resetForm());
      })
      .catch(() => {
        console.log("Message not sent");
      });
    }
  }
}
</code>```

The ExpressJS route:

```<code>router.post("/", (req, res) => {
    let data = req.body;

    let smtpTransport = nodemailer.createTransport({
      service: "Zoho",
      port: 465,
      auth: {
        user: creds.USER,
        pass: creds.PASS
      }
    });

    let mailOptions = {
      from: "EMAIL",
      to: "EMAIL",
      subject: "New user subscribed via DOMAIN",
      html: `<p>${data.email}</p>`
    };

    smtpTransport.sendMail(mailOptions, (error, response) => {
      if (error) {
        res.send(error);
        console.log(error);
      } else {
        res.send("Success");
      }
      smtpTransport.close();
    });

    const msg = {
      to: data.email,
      from: "DOMAIN <EMAIL>",
      templateId: "TEMPLATE ID",
      subject: "TEXT",
      text: "TEXT"
    };

    //Send Email
    try {
      sgMail.send(msg);
    } catch (err) {
      console.log(err);
    }
  });
</code>```

As I said, this used to work fine a week ago, until I started noticing that emails are not being sent. I debugged, and all I am getting is the "Message not sent" error from the client and the POST error cannot find api/example route error (and an HTML piece of code).

What is wrong with the code?

答: The reason for this was that I enabled the 2 factor Auth for Zoho, and wasn't receiving any error of not successful login attempt! Wasted hours until I found the cause...</p>

Body:
This is a very weird issue, but I don't know what is wrong with my app. I haven't committed any change, yet for some reason the app stopped sending emails, and shows an POST error: cannot find route api/example

I have a React component that has a email field and a button. When clicked, the button triggers a function:

sendMail() {
if (this.state.currentEmail !== "") {
  let lastAtPos = this.state.currentEmail.lastIndexOf("@");
  let lastDotPos = this.state.currentEmail.lastIndexOf(".");

  if (
    !(
      lastAtPos < lastDotPos &&
      lastAtPos > 0 &&
      this.state.currentEmail.indexOf("@@") === -1 &&
      lastDotPos > 2 &&
      this.state.currentEmail.length - lastDotPos > 2
    )
  ) {
    this.setState({ error: "Please, provide your real e-mail address!" });
  } else {
    this.setState({
      sending: true,
      buttonText: ""
    });

    let data = {
      email: this.state.currentEmail
    };

    axios
      .post("/api/subscribers", data)
      .then(res => {
        this.setState({ isSent: true }, this.resetForm());
      })
      .catch(() => {
        console.log("Message not sent");
      });
    }
  }
}

The ExpressJS route:

router.post("/", (req, res) => {
    let data = req.body;

    let smtpTransport = nodemailer.createTransport({
      service: "Zoho",
      port: 465,
      auth: {
        user: creds.USER,
        pass: creds.PASS
      }
    });

    let mailOptions = {
      from: "EMAIL",
      to: "EMAIL",
      subject: "New user subscribed via DOMAIN",
      html: `<p>${data.email}</p>`
    };

    smtpTransport.sendMail(mailOptions, (error, response) => {
      if (error) {
        res.send(error);
        console.log(error);
      } else {
        res.send("Success");
      }
      smtpTransport.close();
    });

    const msg = {
      to: data.email,
      from: "DOMAIN <EMAIL>",
      templateId: "TEMPLATE ID",
      subject: "TEXT",
      text: "TEXT"
    };

    //Send Email
    try {
      sgMail.send(msg);
    } catch (err) {
      console.log(err);
    }
  });

As I said, this used to work fine a week ago, until I started noticing that emails are not being sent. I debugged, and all I am getting is the "Message not sent" error from the client and the POST error cannot find api/example route error (and an HTML piece of code).

What is wrong with the code?


问:
Where is PATH_MAX defined in Linux?
Which header file should I invoke with #include to be able to use PATH_MAX as an int for sizing a string?

I want to be able to declare:

```<code>char *current_path[PATH_MAX];
</code>```

But when I do so my compiler (Clang/LLVM on Linux) issues the following error:

```<code>recursive_find6.c:29:20: error: use of undeclared identifier 'PATH_MAX'
char *current_path[PATH_MAX];
                   ^
</code>```

I tried doing a google search but still no luck.

#include <limits.h> Does NOT fix the problem/error.

Am I also correct that the value of PATH_MAX is an int?

答:
The portable way to do it is:

#define _POSIX_C_SOURCE 1
#include <limits.h>
```

Spec: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/limits.h.html

Title: Where is PATH_MAX defined in Linux?

Body:
Which header file should I invoke with #include to be able to use PATH_MAX as an int for sizing a string?

I want to be able to declare:

char *current_path[PATH_MAX];

But when I do so my compiler (Clang/LLVM on Linux) issues the following error:

recursive_find6.c:29:20: error: use of undeclared identifier 'PATH_MAX'
char *current_path[PATH_MAX];
                   ^

I tried doing a google search but still no luck.

#include <limits.h> Does NOT fix the problem/error.

Am I also correct that the value of PATH_MAX is an int?

Body:
The portable way to do it is:

#define _POSIX_C_SOURCE 1
#include <limits.h>

Spec: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/limits.h.html


问:
Failed to connect Couldn't register this node: Error sending the registration request: Failed to connect while registering SeleniumGrid Node to Hub
Selenium hub is up and running on Windows desktop, set up Windows VM to be node. Node won't register to hub.

Step 1:
Entered command in Windows Desktop:

java -jar selenium-server-standalone-3.14.0.jar -role hub -port 2222

Output:

```<code>`11:11:24.171 INFO [GridLauncherV3.launch] - Selenium build info: version: '3.14.0', revision: 'aacccce0'
11:11:24.175 INFO [GridLauncherV3$2.launch] - Launching Selenium Grid hub on port 2222
11:11:25.108:INFO::main: Logging initialized @2242ms to org.seleniumhq.jetty9.util.log.StdErrLog
11:11:26.832 INFO [Hub.start] - Selenium Grid hub is up and running
11:11:26.832 INFO [Hub.start] - Nodes should register to http://172.20.111.25:2222/grid/register/
11:11:26.832 INFO [Hub.start] - Clients should connect to http://172.20.111.25:2222/wd/hub`
</code>```

Checked the config page on localhost and saw that it was there.

Step 2:
Entered this into the command line in Windows Virtual Machine:

java -jar selenium-server-standalone-3.14.0.jar -role node -hub http://172.20.111.25:2222/grid/register

Output:

10:18:43.108 INFO [GridLauncherV3.launch] - Selenium build info: version: '3.14.0', revision: 'aacccce0'
10:18:43.155 INFO [GridLauncherV3$3.launch] - Launching a Selenium Grid node on port 18004
2019-06-03 10:18:43.676:INFO::main: Logging initialized @1482ms to org.seleniumhq.jetty9.util.log.StdErrLog
10:18:44.108 INFO [SeleniumServer.boot] - Selenium Server is up and running on port 18004
10:18:44.108 INFO [GridLauncherV3$3.launch] - Selenium Grid node is up and ready to register to the hub
10:18:44.280 INFO [SelfRegisteringRemote$1.run] - Starting auto registration thread. Will try to register every 5000 ms.
10:18:44.280 INFO [SelfRegisteringRemote.registerToHub] - Registering the node to the hub: http://172.20.111.25:2222/grid/register
10:19:06.003 INFO [SelfRegisteringRemote$1.run] - Couldn't register this node: Error sending the registration request: Failed to connect to /172.20.111.25:2222

答:
You were almost there. You need to remove the additional forward slash (i.e. /) at the end of the registration uri while registering the Selenium Grid Node and you can use the following steps:

First of all, to start the Selenium Grid Hub on port 2222 you need to issue the following command:

```<code>java -jar selenium-server-standalone-3.14.0.jar -role hub -port 2222
</code>```

You will find the following logs generated:

```<code>16:00:50.746 INFO [GridLauncherV3.launch] - Selenium build info: version: '3.14.0', revision: 'aacccce0'
16:00:50.750 INFO [GridLauncherV3$2.launch] - Launching Selenium Grid hub on port 2222
2019-05-31 16:00:51.392:INFO::main: Logging initialized @1151ms to org.seleniumhq.jetty9.util.log.StdErrLog
16:00:52.139 INFO [Hub.start] - Selenium Grid hub is up and running
16:00:52.141 INFO [Hub.start] - Nodes should register to http://192.168.1.125:2222/grid/register/
16:00:52.141 INFO [Hub.start] - Clients should connect to http://192.168.1.125:2222/wd/hub
</code>```

Now you can access the Selenium Grid Console through the URL:

```<code>http://localhost:2222/grid/console
</code>```

The console will look like:

Now finally to start the Selenium Grid Node you have to issue the following command:

```<code>java -jar selenium-server-standalone-3.14.0.jar -role node -hub http://192.168.1.125:2222/grid/register
</code>```

You will find the following logs generated:

```<code>16:04:48.440 INFO [GridLauncherV3.launch] - Selenium build info: version: '3.14.0', revision: 'aacccce0'
16:04:48.470 INFO [GridLauncherV3$3.launch] - Launching a Selenium Grid node onport 7724
2019-05-31 16:04:48.985:INFO::main: Logging initialized @1059ms to org.seleniumhq.jetty9.util.log.StdErrLog
16:04:49.275 INFO [SeleniumServer.boot] - Selenium Server is up and running on port 7724
16:04:49.275 INFO [GridLauncherV3$3.launch] - Selenium Grid node is up and ready to register to the hub
16:04:49.454 INFO [SelfRegisteringRemote$1.run] - Starting auto registration thread. Will try to register every 5000 ms.
16:04:49.454 INFO [SelfRegisteringRemote.registerToHub] - Registering the node to the hub: http://192.168.1.125:2222/grid/register
16:04:50.355 INFO [SelfRegisteringRemote.registerToHub] - The node is registered to the hub and ready to use
</code>```

Body:
Selenium hub is up and running on Windows desktop, set up Windows VM to be node. Node won't register to hub.

Step 1:
Entered command in Windows Desktop:

java -jar selenium-server-standalone-3.14.0.jar -role hub -port 2222

Output:

`11:11:24.171 INFO [GridLauncherV3.launch] - Selenium build info: version: '3.14.0', revision: 'aacccce0'
11:11:24.175 INFO [GridLauncherV3$2.launch] - Launching Selenium Grid hub on port 2222
11:11:25.108:INFO::main: Logging initialized @2242ms to org.seleniumhq.jetty9.util.log.StdErrLog
11:11:26.832 INFO [Hub.start] - Selenium Grid hub is up and running
11:11:26.832 INFO [Hub.start] - Nodes should register to http://172.20.111.25:2222/grid/register/
11:11:26.832 INFO [Hub.start] - Clients should connect to http://172.20.111.25:2222/wd/hub`

Checked the config page on localhost and saw that it was there.

Step 2:
Entered this into the command line in Windows Virtual Machine:

java -jar selenium-server-standalone-3.14.0.jar -role node -hub http://172.20.111.25:2222/grid/register

Output:

10:18:43.108 INFO [GridLauncherV3.launch] - Selenium build info: version: '3.14.0', revision: 'aacccce0'
10:18:43.155 INFO [GridLauncherV3$3.launch] - Launching a Selenium Grid node on port 18004
2019-06-03 10:18:43.676:INFO::main: Logging initialized @1482ms to org.seleniumhq.jetty9.util.log.StdErrLog
10:18:44.108 INFO [SeleniumServer.boot] - Selenium Server is up and running on port 18004
10:18:44.108 INFO [GridLauncherV3$3.launch] - Selenium Grid node is up and ready to register to the hub
10:18:44.280 INFO [SelfRegisteringRemote$1.run] - Starting auto registration thread. Will try to register every 5000 ms.
10:18:44.280 INFO [SelfRegisteringRemote.registerToHub] - Registering the node to the hub: http://172.20.111.25:2222/grid/register
10:19:06.003 INFO [SelfRegisteringRemote$1.run] - Couldn't register this node: Error sending the registration request: Failed to connect to /172.20.111.25:2222

Body:
You were almost there. You need to remove the additional forward slash (i.e. /) at the end of the registration uri while registering the Selenium Grid Node and you can use the following steps:

First of all, to start the Selenium Grid Hub on port 2222 you need to issue the following command:

java -jar selenium-server-standalone-3.14.0.jar -role hub -port 2222

You will find the following logs generated:

16:00:50.746 INFO [GridLauncherV3.launch] - Selenium build info: version: '3.14.0', revision: 'aacccce0'
16:00:50.750 INFO [GridLauncherV3$2.launch] - Launching Selenium Grid hub on port 2222
2019-05-31 16:00:51.392:INFO::main: Logging initialized @1151ms to org.seleniumhq.jetty9.util.log.StdErrLog
16:00:52.139 INFO [Hub.start] - Selenium Grid hub is up and running
16:00:52.141 INFO [Hub.start] - Nodes should register to http://192.168.1.125:2222/grid/register/
16:00:52.141 INFO [Hub.start] - Clients should connect to http://192.168.1.125:2222/wd/hub

Now you can access the Selenium Grid Console through the URL:

http://localhost:2222/grid/console

The console will look like:

Now finally to start the Selenium Grid Node you have to issue the following command:

java -jar selenium-server-standalone-3.14.0.jar -role node -hub http://192.168.1.125:2222/grid/register

You will find the following logs generated:

16:04:48.440 INFO [GridLauncherV3.launch] - Selenium build info: version: '3.14.0', revision: 'aacccce0'
16:04:48.470 INFO [GridLauncherV3$3.launch] - Launching a Selenium Grid node onport 7724
2019-05-31 16:04:48.985:INFO::main: Logging initialized @1059ms to org.seleniumhq.jetty9.util.log.StdErrLog
16:04:49.275 INFO [SeleniumServer.boot] - Selenium Server is up and running on port 7724
16:04:49.275 INFO [GridLauncherV3$3.launch] - Selenium Grid node is up and ready to register to the hub
16:04:49.454 INFO [SelfRegisteringRemote$1.run] - Starting auto registration thread. Will try to register every 5000 ms.
16:04:49.454 INFO [SelfRegisteringRemote.registerToHub] - Registering the node to the hub: http://192.168.1.125:2222/grid/register
16:04:50.355 INFO [SelfRegisteringRemote.registerToHub] - The node is registered to the hub and ready to use


问:
How do I customize website CSS in a react native webview?
I've been playing around with webviews on react native, but I would like to change the website's css to customize the style. Is there a way to do it?

Using react native cli & android studio

```<code>import React from 'react';
import { StyleSheet, Text, View, Image, StatusBar, ScrollView, TouchableOpacity, WebView, ActivityIndicator } from 'react-native';

class king_of_prussia extends React.Component {

  static navigationOptions = {
       title: 'King Of Prussia',
       headerTitleStyle :{textAlign: 'center', alignSelf:'center', fontSize: 18, fontWeight: 'normal', color: '#3E3E40' },
       headerStyle:{
           backgroundColor:'white',
       },
   };

  ActivityIndicatorLoadingView() {
    return (
      <ActivityIndicator
        color='black'
        size='large'
        style={styles.ActivityIndicatorStyle}
      />
    );
  }

  render() {
    return (
        <View style={styles.container}>
        <StatusBar
            backgroundColor='#F1F1F1'
            barStyle='dark-content'/>
            <WebView
                source={{uri: 'https://www.simon.com/mall/king-of-prussia/map#/'}}
                scalesPageToFit = {false}
                javaScriptEnabled={true}
                domStorageEnabled={true}
                renderLoading={this.ActivityIndicatorLoadingView}
                startInLoadingState={true}
            />
        </View>
    );
  }
}

export default king_of_prussia;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#EFF2F5',
  },
  footer: {
    flexDirection: 'column',
    alignItems: 'center',
    marginBottom: 25,
  },
  shareText:{
    color:'#95989A',
    fontSize: 12
  },
  ActivityIndicatorStyle:{
    position: 'absolute',
    left: 0,
    right: 0,
    top: 0,
    bottom: 0,
    alignItems: 'center',
    justifyContent: 'center'
  }
});
</code>```

I would like to remove the header from the website as well as modifying other styles.

答:
WebView has an "injectedJavaScript" prop available which would allow you to feed it a block of javascript that you could use to manipulate any CSS/HTML on the page.

It's a bit hacky, but I didn't really see an alternative since you're essentially working with an iframe when using a webview.

I'm using this to hide the burger bar in the navbar of a site I reference in a webview in my app:

```<code><WebView
  source={{uri: this.state.magicUrl}}
  style={{ flex: 1 }}
  injectedJavaScript={'function hideHeaderToggle() {var headerToggle = document.getElementsByClassName("navbar-toggle"), i;for (i = 0; i < headerToggle.length; i += 1) {headerToggle[i].style.display = "none";};}; hideHeaderToggle();'}
/>
</code>```

Entirely possible that there are better alternatives out there, but this certainly would be one option.

Body:
I've been playing around with webviews on react native, but I would like to change the website's css to customize the style. Is there a way to do it?

Using react native cli & android studio

import React from 'react';
import { StyleSheet, Text, View, Image, StatusBar, ScrollView, TouchableOpacity, WebView, ActivityIndicator } from 'react-native';

class king_of_prussia extends React.Component {

  static navigationOptions = {
       title: 'King Of Prussia',
       headerTitleStyle :{textAlign: 'center', alignSelf:'center', fontSize: 18, fontWeight: 'normal', color: '#3E3E40' },
       headerStyle:{
           backgroundColor:'white',
       },
   };

  ActivityIndicatorLoadingView() {
    return (
      <ActivityIndicator
        color='black'
        size='large'
        style={styles.ActivityIndicatorStyle}
      />
    );
  }

  render() {
    return (
        <View style={styles.container}>
        <StatusBar
            backgroundColor='#F1F1F1'
            barStyle='dark-content'/>
            <WebView
                source={{uri: 'https://www.simon.com/mall/king-of-prussia/map#/'}}
                scalesPageToFit = {false}
                javaScriptEnabled={true}
                domStorageEnabled={true}
                renderLoading={this.ActivityIndicatorLoadingView}
                startInLoadingState={true}
            />
        </View>
    );
  }
}

export default king_of_prussia;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#EFF2F5',
  },
  footer: {
    flexDirection: 'column',
    alignItems: 'center',
    marginBottom: 25,
  },
  shareText:{
    color:'#95989A',
    fontSize: 12
  },
  ActivityIndicatorStyle:{
    position: 'absolute',
    left: 0,
    right: 0,
    top: 0,
    bottom: 0,
    alignItems: 'center',
    justifyContent: 'center'
  }
});

I would like to remove the header from the website as well as modifying other styles.

Body:
WebView has an "injectedJavaScript" prop available which would allow you to feed it a block of javascript that you could use to manipulate any CSS/HTML on the page.

It's a bit hacky, but I didn't really see an alternative since you're essentially working with an iframe when using a webview.

I'm using this to hide the burger bar in the navbar of a site I reference in a webview in my app:

<WebView
  source={{uri: this.state.magicUrl}}
  style={{ flex: 1 }}
  injectedJavaScript={'function hideHeaderToggle() {var headerToggle = document.getElementsByClassName("navbar-toggle"), i;for (i = 0; i < headerToggle.length; i += 1) {headerToggle[i].style.display = "none";};}; hideHeaderToggle();'}
/>

Entirely possible that there are better alternatives out there, but this certainly would be one option.