问:
How can I change the owner of a Google Sheets spreadsheet?
With the following, I can programmatically create a spreadsheet in Google sheets, but the owner of the sheet is the developer account (a crazy string ending in "gserviceaccount.com"), and my normal account can't view the spreadsheet.  What else do I need to do in order to add Google users to the read/write permissions?

from oauth2client.service_account import ServiceAccountCredentials
from googleapiclient import discovery

# ... json_key is the json blob that has the credentials
scope = ['https://spreadsheets.google.com/feeds']
credentials = ServiceAccountCredentials.from_json_keyfile_dict(json_key, scope)
service = discovery.build('sheets', 'v4', credentials=credentials)

spreadsheet = {
  "properties": {"title": "my test spreadsheet"}
}

service.spreadsheets().create(body=spreadsheet).execute()
```

<p>Edit:<br>
I tried changing the scope to <code>['https://www.googleapis.com/auth/drive']</code> but the answer below still doesn't work for me.  When I run  </p>

```print [xx for xx in dir(service) if not xx.startswith('_')]
```

<p>I get</p>

```['new_batch_http_request', u'spreadsheets']
```

In other words, permissions() isn't a method in service as I have service defined.  What should I be doing differently?

答:
Service is just a generic name for the result of a discovery.build call. In this case, not having the 'permissions' method is just that its not available on the same service. The following code should be sufficient if changing owner isn't required. To add someone with read and write access, the following works for me:

```<code>def grant_permissions(spreadsheet_id, writer):
    drive_service = discovery.build('drive', 'v3')

    permission = drive_service.permissions().create(
        fileId=spreadsheet_id,
        body={
            'type': 'user',
            'role': 'writer',
            'emailAddress': writer,
        }
    ).execute()

    drive_service.files().update(
        fileId=spreadsheet_id,
        body={'permissionIds': [permission['id']]}
    ).execute()
</code>```

To actually change the owner, the transfer ownership flag must be set:

```<code>def change_owner(spreadsheet_id, writer):
    drive_service = discovery.build('drive', 'v3')

    permission = drive_service.permissions().create(
        fileId=spreadsheet_id,
        transferOwnership=True,
        body={
            'type': 'user',
            'role': 'owner',
            'emailAddress': writer,
        }
    ).execute()

    drive_service.files().update(
        fileId=spreadsheet_id,
        body={'permissionIds': [permission['id']]}
    ).execute()
</code>```

The service account being used must have the right permissions though. I believe the ones that worked for me was checking the g suite box when first creating the service account.

Body:
With the following, I can programmatically create a spreadsheet in Google sheets, but the owner of the sheet is the developer account (a crazy string ending in "gserviceaccount.com"), and my normal account can't view the spreadsheet.  What else do I need to do in order to add Google users to the read/write permissions?

from oauth2client.service_account import ServiceAccountCredentials
from googleapiclient import discovery

# ... json_key is the json blob that has the credentials
scope = ['https://spreadsheets.google.com/feeds']
credentials = ServiceAccountCredentials.from_json_keyfile_dict(json_key, scope)
service = discovery.build('sheets', 'v4', credentials=credentials)

spreadsheet = {
  "properties": {"title": "my test spreadsheet"}
}

service.spreadsheets().create(body=spreadsheet).execute()

Edit:

I tried changing the scope to ['https://www.googleapis.com/auth/drive'] but the answer below still doesn't work for me.  When I run

print [xx for xx in dir(service) if not xx.startswith('_')]

I get

['new_batch_http_request', u'spreadsheets']

In other words, permissions() isn't a method in service as I have service defined.  What should I be doing differently?

Body:
Service is just a generic name for the result of a discovery.build call. In this case, not having the 'permissions' method is just that its not available on the same service. The following code should be sufficient if changing owner isn't required. To add someone with read and write access, the following works for me:

def grant_permissions(spreadsheet_id, writer):
    drive_service = discovery.build('drive', 'v3')

    permission = drive_service.permissions().create(
        fileId=spreadsheet_id,
        body={
            'type': 'user',
            'role': 'writer',
            'emailAddress': writer,
        }
    ).execute()

    drive_service.files().update(
        fileId=spreadsheet_id,
        body={'permissionIds': [permission['id']]}
    ).execute()

To actually change the owner, the transfer ownership flag must be set:

def change_owner(spreadsheet_id, writer):
    drive_service = discovery.build('drive', 'v3')

    permission = drive_service.permissions().create(
        fileId=spreadsheet_id,
        transferOwnership=True,
        body={
            'type': 'user',
            'role': 'owner',
            'emailAddress': writer,
        }
    ).execute()

    drive_service.files().update(
        fileId=spreadsheet_id,
        body={'permissionIds': [permission['id']]}
    ).execute()

The service account being used must have the right permissions though. I believe the ones that worked for me was checking the g suite box when first creating the service account.


来源: stackexchange

答:
You can use a variable to track if "err" has been found, and use that information to decide where to .splice() the new member.

```<code>var found = false
for (const a of data) {
  if (!found && a[0] === "err")
    found = true;
  else
    a.splice(found ? 1 : 2, 0, 0);
}
</code>```

If you want to make use of the index where the err was found, then use .entries() on the array and change the found variable to store the index instead.

```<code>var foundIdx = -1;
for (const [idx, a] of data.entries()) {
  const found = foundIdx !== -1;

  if (!found && a[0] === "err")
    foundIdx = idx;
  else
    a.splice(found ? 1 : 2, 0, 0);
}

console.log("the err index was", foundIdx);
</code>```

ContentLicense: CC BY-SA 3.0

Title: transform array of arrays inserting nulls, Javascript

Body:
I am receiving data in this way:

  [Sun Jan 01 2006 00:00:00 GMT-0600 (CST), 8.605613643557573]
  [Mon Jan 01 2007 00:00:00 GMT-0600 (CST), 4.639263458390814]
  [Tue Jan 01 2008 00:00:00 GMT-0600 (CST), 3.690424190442011]
  [Thu Jan 01 2009 00:00:00 GMT-0600 (CST), -6.068362055704255]
  [Fri Jan 01 2010 00:00:00 GMT-0600 (CST), 0.011317380895792274]
  [Sat Jan 01 2011 00:00:00 GMT-0600 (CST), 3.9984661908088825]
  [Sun Jan 01 2012 00:00:00 GMT-0600 (CST), 2.4211622308876173]
  [Tue Jan 01 2013 00:00:00 GMT-0600 (CST), -1.5740599423273804]
  [Wed Jan 01 2014 00:00:00 GMT-0600 (CST), 2.6624793033769967]
  [Thu Jan 01 2015 00:00:00 GMT-0600 (CST), 1744.9379869455643]
  ["err", NaN]
  [Wed Jan 01 2020 00:00:00 GMT-0600 (CST), 3417.1886283181875]
  [Wed Jan 01 2025 00:00:00 GMT-0600 (CST), 3331.7059850696196]
  [Tue Jan 01 2030 00:00:00 GMT-0600 (CST), 3237.940431993671]

And I'm trying to make a dataset to look like this:

  [Sun Jan 01 2006 00:00:00 GMT-0600 (CST), 8.605613643557573, 0]
  [Mon Jan 01 2007 00:00:00 GMT-0600 (CST), 4.639263458390814, 0]
  [Tue Jan 01 2008 00:00:00 GMT-0600 (CST), 3.690424190442011, 0]
  [Thu Jan 01 2009 00:00:00 GMT-0600 (CST), -6.068362055704255, 0]
  [Fri Jan 01 2010 00:00:00 GMT-0600 (CST), 0.011317380895792274, 0]
  [Sat Jan 01 2011 00:00:00 GMT-0600 (CST), 3.9984661908088825, 0]
  [Sun Jan 01 2012 00:00:00 GMT-0600 (CST), 2.4211622308876173, 0]
  [Tue Jan 01 2013 00:00:00 GMT-0600 (CST), -1.5740599423273804, 0]
  [Wed Jan 01 2014 00:00:00 GMT-0600 (CST), 2.6624793033769967, 0]
  [Thu Jan 01 2015 00:00:00 GMT-0600 (CST), 1744.9379869455643, 0]
  ["err", NaN]
  [Wed Jan 01 2020 00:00:00 GMT-0600 (CST),0 , 3417.1886283181875]
  [Wed Jan 01 2025 00:00:00 GMT-0600 (CST),0 , 3331.7059850696196]
  [Tue Jan 01 2030 00:00:00 GMT-0600 (CST),0 , 3237.940431993671]

Is there a way to do this by looking at the index of "err" ?

Body:
You can use a variable to track if "err" has been found, and use that information to decide where to .splice() the new member.

var found = false
for (const a of data) {
  if (!found && a[0] === "err")
    found = true;
  else
    a.splice(found ? 1 : 2, 0, 0);
}

If you want to make use of the index where the err was found, then use .entries() on the array and change the found variable to store the index instead.

var foundIdx = -1;
for (const [idx, a] of data.entries()) {
  const found = foundIdx !== -1;

  if (!found && a[0] === "err")
    foundIdx = idx;
  else
    a.splice(found ? 1 : 2, 0, 0);
}

console.log("the err index was", foundIdx);


问:
Make Lambda function execute now, and/or in an hour
I'm trying to implement an AWS Lambda function that should send an HTTP request. If that request fails (response is anything but status 200) I should wait another hour before retrying (longer that the Lambda stays hot). What the best way to implement this?

What comes to mind is to persist my HTTP request in some way and being able to trigger the Lambda function again in a specified amount of time in case of a persisted HTTP request. But I'm not completely sure which AWS service that would provide that functionality for me. Is SQS an option that can help here?

Or, can I dynamically schedule Lambda execution for this? Note that the request to be retried should be identical to the first one.

Any other suggestions? What's the best practice for this?

(Lambda function is my option. No EC2 or such things are possible)

答:
As jarmod mentioned, you cannot trigger Lambda functions directly by SQS. But a workaround (one I've used personally) would be to do the following:

If the request fails, push an item to an SQS Delay Queue (docs)

This SQS message will only become visible on the queue after a certain delay (you mentioned an hour).

Then have a second scheduled lambda function which is triggered by a cron value of a smaller timeframe (I used a minute).

This second function would then scan the SQS queue and if an item is on the queue, call your first Lambda function (either by SNS or with the AWS SDK) to retry it.

PS: Note that you can put data in an SQS item, since you mentioned you needed the lambda functions to be identical you can store your first function's input in here to be reused after an hour.


问:
React setState not updating state; callback not being called
I'm trying to take the metronome I built following the "Tale of Two Clocks" tutorial and convert it into a simple React project. I figured it would be trivially easy to map the metronome's parameters (tempo, note divisions, etc.) and expand on it to build out a step sequencer (hooray for techno!). That said, I'm having trouble with a specific piece and I'm wondering why.

I've got pretty much all the salient pieces as state on the Metronome component, like so:

```<code>import React from 'react'

class Metronome extends React.Component {
  constructor (props) {
    super(props)

    this.audioContext = new (window.AudioContext || window.webkitAudioContext)()

    this.state = {
      tempo: 120.0,
      noteResolution: 0,
      isPlaying: false,
      current16thNote: 0,
      gateLength: 0.05,
      noteLength: 0.25,
      nextNoteTime: 0.0
    }

    this.lookahead = 0.1
    this.schedulerInterval = 25.0
    this.timerID = null

    this.updateStartStopText = this.updateStartStopText.bind(this)
    this.play = this.play.bind(this)
    this.scheduler = this.scheduler.bind(this)
    this.scheduleNote = this.scheduleNote.bind(this)
    this.nextNote = this.nextNote.bind(this)
  }

  updateStartStopText () {
    return this.state.isPlaying ? 'Stop' : 'Start'
  }

  play () {
    this.setState({ isPlaying: !this.state.isPlaying }, () => {
      if (this.state.isPlaying) {
        this.setState({ current16thNote: 0 }, () => {
          this.setState({
            nextNoteTime: this.audioContext.currentTime
          }, this.scheduler)
        })
      } else {
        window.clearTimeout(this.timerID)
      }
    })
  }

  scheduler () {
    while (this.state.nextNoteTime < this.audioContext.currentTime + this.lookahead) {
      this.scheduleNote(this.state.current16thNote, this.state.nextNoteTime)
      this.nextNote()
    }

    this.timerID = window.setTimeout(this.scheduler, this.schedulerInterval)
  }

  scheduleNote (beatNumber, time) {
    if ((this.state.noteResolution === 1) && (beatNumber % 2)) {
      return
    } else if ((this.state.noteResolution === 2) && (beatNumber % 4)) {
      return
    }
    const osc = this.audioContext.createOscillator()
    osc.connect(this.audioContext.destination)
    if (!(beatNumber % 16)) {
      osc.frequency.value = 220
    } else if (beatNumber % 4) {
      osc.frequency.value = 440
    } else {
      osc.frequency.value = 880
    }

    osc.start(time)
    osc.stop(time + this.state.gateLength)
  }

  nextNote () {
    var secondsPerBeat = 60.0 / this.state.tempo
    let nextTime = this.state.nextNoteTime + (secondsPerBeat * this.state.noteLength)

    this.setState({
      nextNoteTime: nextTime,
      current16thNote: (this.state.current16thNote + 1)
    }, () => {
      if (this.state.current16thNote === 16) {
        this.setState({ current16thNote: 0 })
      }
    })
  }

  render () {
    return (
      <div>
        Metronome

        <button type='button' onClick={this.play}>{this.updateStartStopText()}</button>
      </div>
    )
  }
}

export default Metronome
</code>```

More or less everything plays out like you'd expect from React, swapping out vanilla JS variable reassignment/incrementing with this.setState() calls, . There are quite a few situations where I need to do calculations with an updated value in state and, knowing that setState() is asynchronous and often batches calls, I rely somewhat heavily on the optional callback that setState takes.

The one place where things seem to be going awry is in the nextNote() method. The state never updates properly: this.state.nextNoteTime never gets an updated value beyond that which it is assigned in the play() method The code as it is will never get into the callback passed to setState() called from nextNote(). If I remove nextNoteTime from the component's state and save it as a property on the component, manually updating and tracking its value, the metronome seems to work as expected, à la the end state of my metronome in vanilla JS. Technically a success, but not the answer I'm looking for.

I tried using Promises and I tried using the React Component API (componentWillUpdate, shouldComponentUpdate, etc.) to figure out whether or not the next state is the one I'm looking for. But beyond a certain point (like 3 recursive calls of the scheduler() method), the while loop goes haywire since this.state.nextNoteTime never increases. Gah!

Thoughts?

答:
I think it's because you have nested setStates.

Try below as play method.

```<code>play() {
  const { isPlaying } = this.state;
  const newState = { isPlaying: !isPlaying };
  if (!isPlaying) {
    Object.assign(newState, {
      current16thNote: 0,
      nextNoteTime: this.audioContext.currentTime
    });
  }

  this.setState(newState, (...args) => {
    if (!isPlaying) {
      this.scheduler(...args);
    } else {
      window.clearTimeout(this.timerID)
    }
  });
}
</code>```

Remove setState nesting for nextNote as well.

Body:
I'm trying to take the metronome I built following the "Tale of Two Clocks" tutorial and convert it into a simple React project. I figured it would be trivially easy to map the metronome's parameters (tempo, note divisions, etc.) and expand on it to build out a step sequencer (hooray for techno!). That said, I'm having trouble with a specific piece and I'm wondering why.

I've got pretty much all the salient pieces as state on the Metronome component, like so:

import React from 'react'

class Metronome extends React.Component {
  constructor (props) {
    super(props)

    this.audioContext = new (window.AudioContext || window.webkitAudioContext)()

    this.state = {
      tempo: 120.0,
      noteResolution: 0,
      isPlaying: false,
      current16thNote: 0,
      gateLength: 0.05,
      noteLength: 0.25,
      nextNoteTime: 0.0
    }

    this.lookahead = 0.1
    this.schedulerInterval = 25.0
    this.timerID = null

    this.updateStartStopText = this.updateStartStopText.bind(this)
    this.play = this.play.bind(this)
    this.scheduler = this.scheduler.bind(this)
    this.scheduleNote = this.scheduleNote.bind(this)
    this.nextNote = this.nextNote.bind(this)
  }

  updateStartStopText () {
    return this.state.isPlaying ? 'Stop' : 'Start'
  }

  play () {
    this.setState({ isPlaying: !this.state.isPlaying }, () => {
      if (this.state.isPlaying) {
        this.setState({ current16thNote: 0 }, () => {
          this.setState({
            nextNoteTime: this.audioContext.currentTime
          }, this.scheduler)
        })
      } else {
        window.clearTimeout(this.timerID)
      }
    })
  }

  scheduler () {
    while (this.state.nextNoteTime < this.audioContext.currentTime + this.lookahead) {
      this.scheduleNote(this.state.current16thNote, this.state.nextNoteTime)
      this.nextNote()
    }

    this.timerID = window.setTimeout(this.scheduler, this.schedulerInterval)
  }

  scheduleNote (beatNumber, time) {
    if ((this.state.noteResolution === 1) && (beatNumber % 2)) {
      return
    } else if ((this.state.noteResolution === 2) && (beatNumber % 4)) {
      return
    }
    const osc = this.audioContext.createOscillator()
    osc.connect(this.audioContext.destination)
    if (!(beatNumber % 16)) {
      osc.frequency.value = 220
    } else if (beatNumber % 4) {
      osc.frequency.value = 440
    } else {
      osc.frequency.value = 880
    }

    osc.start(time)
    osc.stop(time + this.state.gateLength)
  }

  nextNote () {
    var secondsPerBeat = 60.0 / this.state.tempo
    let nextTime = this.state.nextNoteTime + (secondsPerBeat * this.state.noteLength)

    this.setState({
      nextNoteTime: nextTime,
      current16thNote: (this.state.current16thNote + 1)
    }, () => {
      if (this.state.current16thNote === 16) {
        this.setState({ current16thNote: 0 })
      }
    })
  }

  render () {
    return (

        Metronome

        <button type='button' onClick={this.play}>{this.updateStartStopText()}</button>

    )
  }
}

export default Metronome

More or less everything plays out like you'd expect from React, swapping out vanilla JS variable reassignment/incrementing with this.setState() calls, . There are quite a few situations where I need to do calculations with an updated value in state and, knowing that setState() is asynchronous and often batches calls, I rely somewhat heavily on the optional callback that setState takes.

The one place where things seem to be going awry is in the nextNote() method. The state never updates properly: this.state.nextNoteTime never gets an updated value beyond that which it is assigned in the play() method The code as it is will never get into the callback passed to setState() called from nextNote(). If I remove nextNoteTime from the component's state and save it as a property on the component, manually updating and tracking its value, the metronome seems to work as expected, à la the end state of my metronome in vanilla JS. Technically a success, but not the answer I'm looking for.

I tried using Promises and I tried using the React Component API (componentWillUpdate, shouldComponentUpdate, etc.) to figure out whether or not the next state is the one I'm looking for. But beyond a certain point (like 3 recursive calls of the scheduler() method), the while loop goes haywire since this.state.nextNoteTime never increases. Gah!

Thoughts?

Body:
I think it's because you have nested setStates.

Try below as play method.

play() {
  const { isPlaying } = this.state;
  const newState = { isPlaying: !isPlaying };
  if (!isPlaying) {
    Object.assign(newState, {
      current16thNote: 0,
      nextNoteTime: this.audioContext.currentTime
    });
  }

  this.setState(newState, (...args) => {
    if (!isPlaying) {
      this.scheduler(...args);
    } else {
      window.clearTimeout(this.timerID)
    }
  });
}

Remove setState nesting for nextNote as well.


问:
Group values in different columns to one column
I searched for a solution on Google for hours, I sincerely apologize if its simple one line code and I missed it. I basically want to group together identical values in different columns on every row here;

Sample data as per Maurits' suggestion

```<code>       event_1 event_2 event_3 event_4 event_5 event_6 event_7 event_8 event_9 event_10
seq_1      200     211     114     117     118     146
seq_2      200     211     114     117     118     146
seq_3      200     243     211     101     114     117     118     146
seq_4      200     211     114     117     118     146
seq_5      200     243     211     101     114     117     118     146
</code>```

Expected output like this;

```<code>           Column_211      Column_101
seq_1             1         0
seq_2             1         0
seq_3             1         1
seq_4             1         0
seq_5             1         1
</code>```

答:
Is this what you're after?

Explanation: We use apply(df, 1, ...) to process df row by row, then use %in% to flag whether any of the values are present in that row. The resulting logical vector (like c(TRUE, FALSE)) is then converted to a numeric vector (like c(1, 0)). Finally, we need to transpose the resulting matrix using t(...), and give column names in accordance with your expected outcome.

```<code> values <- c(211, 101);
 df.new <- t(apply(df, 1, function(x) as.numeric(values %in% x)));
 colnames(df.new) <- paste0("Column_", values);
 df.new;
 #      Column_211 Column_101
 #seq_1          1          0
 #seq_2          1          0
 #seq_3          1          1
 #seq_4          1          0
 #seq_5          1          1
</code>```

Sample data

```<code> df <- read.delim(text =
     "  event_1 event_2 event_3 event_4 event_5 event_6 event_7 event_8 event_9 event_10
 seq_1      200     211     114     117     118     146
 seq_2      200     211     114     117     118     146
 seq_3      200     243     211     101     114     117     118     146
 seq_4      200     211     114     117     118     146
 seq_5      200     243     211     101     114     117     118     146                      ",
 header = T, row.names = 1, sep = "")
</code>```

Body:
I searched for a solution on Google for hours, I sincerely apologize if its simple one line code and I missed it. I basically want to group together identical values in different columns on every row here;

Sample data as per Maurits' suggestion

       event_1 event_2 event_3 event_4 event_5 event_6 event_7 event_8 event_9 event_10
seq_1      200     211     114     117     118     146
seq_2      200     211     114     117     118     146
seq_3      200     243     211     101     114     117     118     146
seq_4      200     211     114     117     118     146
seq_5      200     243     211     101     114     117     118     146

Expected output like this;

           Column_211      Column_101
seq_1             1         0
seq_2             1         0
seq_3             1         1
seq_4             1         0
seq_5             1         1

Body:
Is this what you're after?

Explanation: We use apply(df, 1, ...) to process df row by row, then use %in% to flag whether any of the values are present in that row. The resulting logical vector (like c(TRUE, FALSE)) is then converted to a numeric vector (like c(1, 0)). Finally, we need to transpose the resulting matrix using t(...), and give column names in accordance with your expected outcome.

 values <- c(211, 101);
 df.new <- t(apply(df, 1, function(x) as.numeric(values %in% x)));
 colnames(df.new) <- paste0("Column_", values);
 df.new;
 #      Column_211 Column_101
 #seq_1          1          0
 #seq_2          1          0
 #seq_3          1          1
 #seq_4          1          0
 #seq_5          1          1

Sample data

 df <- read.delim(text =
     "  event_1 event_2 event_3 event_4 event_5 event_6 event_7 event_8 event_9 event_10
 seq_1      200     211     114     117     118     146
 seq_2      200     211     114     117     118     146
 seq_3      200     243     211     101     114     117     118     146
 seq_4      200     211     114     117     118     146
 seq_5      200     243     211     101     114     117     118     146                      ",
 header = T, row.names = 1, sep = "")


问:
Ajax calls working in Android but not iOS
I'm developing an app in Nativescript for the first time and running into an issue where AJAX calls work on Android but not iOS. I have a login.js file which requires a user-view-model (user-view-model.js), and when I test the code on Android it takes me to the "home" page but it hits the catch function on iOS.

login.js:

var dialogsModule = require("ui/dialogs");
var UserViewModel = require("../../shared/view-models/user-view-model");
var applicationSettings = require("application-settings");

var user = new UserViewModel({
  email: "aaa@aaa.com",
  password: "aaa"
});

var frameModule = require("ui/frame");
var page;

exports.loaded = function(args) {
  page = args.object;
  page.bindingContext = user;
};

exports.login = function () {
  user.login().catch(function(error) {
    dialogsModule.alert({
      message: "Unfortunately we could not find your account.",
      okButtonText: "OK"
    });
    return Promise.reject();
  }).then(function(response) {
    console.dir(response)
    console.log("past response")
    applicationSettings.setString("user_id", response.user_id);
    applicationSettings.setString("first_name", response.first_name);
    applicationSettings.setString("last_name", response.last_name);
    applicationSettings.setString("user_type", response.user_type);
    var topmost = frameModule.topmost();
    topmost.navigate("views/home/home");
  });
};```
</div>
</div>
</p>

<p>user-view-model.js:
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var config = require("../../shared/config");
var fetchModule = require("fetch");
var observableModule = require("data/observable");
var http = require("http");

function User(info) {
    info = info || {};

    var viewModel = new observableModule.fromObject({
        email: info.email || "",
        password: info.password || ""
    });

    viewModel.login = function() {
        let loginEmail = JSON.stringify(this.get("email")).replace(/['"]+/g, '');
        let loginPassword = JSON.stringify(this.get("password")).replace(/['"]+/g, '');
        console.log(loginEmail, loginPassword);
        let loginUrl = config.serverPHPServiceUrl + "Login.php?user_id=" + loginEmail + "&password=" + loginPassword;
        console.log(loginUrl);

        // I tried this way first and wasn't able to login on iOS, which made me try the second method below.
        // return fetchModule.fetch(loginUrl, {
        //   method: "POST",
        //   headers: {
        //     "Content-Type": "application/json"
        //   }
        // }).then(handleErrors).then(function(response) {
        //   return response.json();
        // }).then(function(data) {
        //   console.dir(data);
        //   console.log(data["results"][0]["user_id"])
        //   return data["results"][0];
        // });

        // This method works on Android but not iOS.
        return http.getJSON(loginUrl).then(function(response) {
              console.dir(response);
              return response.results[0];
        })

    };

    return viewModel;
};

function handleErrors(response) {
    console.log("in errors")
    if (!response.ok) {
        console.log(JSON.stringify(response));
        throw Error(response.statusText);
    }
    return response;
}

module.exports = User;</code>```

Is there anything fundamentally wrong with my code, or do asynchronous calls work differently on iOS vs Android in Nativescript? I did the Grocery tutorial and didn't run into this issue, so I didn't think this was the case. Does it matter that the backend is using PHP?

答: I fixed my issue: I started a new project with Angular 2 and ran into the same error, but then it gave me the error message "Error: The resource could not be loaded because the App Transport Security policy requires the use of a secure connection." I solved it by adding "https" to my url call, but this post has another solution.</p>

Body:
I'm developing an app in Nativescript for the first time and running into an issue where AJAX calls work on Android but not iOS. I have a login.js file which requires a user-view-model (user-view-model.js), and when I test the code on Android it takes me to the "home" page but it hits the catch function on iOS.

login.js:

var dialogsModule = require("ui/dialogs");
var UserViewModel = require("../../shared/view-models/user-view-model");
var applicationSettings = require("application-settings");

var user = new UserViewModel({
  email: "aaa@aaa.com",
  password: "aaa"
});

var frameModule = require("ui/frame");
var page;

exports.loaded = function(args) {
  page = args.object;
  page.bindingContext = user;
};

exports.login = function () {
  user.login().catch(function(error) {
    dialogsModule.alert({
      message: "Unfortunately we could not find your account.",
      okButtonText: "OK"
    });
    return Promise.reject();
  }).then(function(response) {
    console.dir(response)
    console.log("past response")
    applicationSettings.setString("user_id", response.user_id);
    applicationSettings.setString("first_name", response.first_name);
    applicationSettings.setString("last_name", response.last_name);
    applicationSettings.setString("user_type", response.user_type);
    var topmost = frameModule.topmost();
    topmost.navigate("views/home/home");
  });
};

user-view-model.js:

var config = require("../../shared/config");
var fetchModule = require("fetch");
var observableModule = require("data/observable");
var http = require("http");

function User(info) {
    info = info || {};

    var viewModel = new observableModule.fromObject({
        email: info.email || "",
        password: info.password || ""
    });

    viewModel.login = function() {
        let loginEmail = JSON.stringify(this.get("email")).replace(/['"]+/g, '');
        let loginPassword = JSON.stringify(this.get("password")).replace(/['"]+/g, '');
        console.log(loginEmail, loginPassword);
        let loginUrl = config.serverPHPServiceUrl + "Login.php?user_id=" + loginEmail + "&password=" + loginPassword;
        console.log(loginUrl);

        // I tried this way first and wasn't able to login on iOS, which made me try the second method below.
        // return fetchModule.fetch(loginUrl, {
        //   method: "POST",
        //   headers: {
        //     "Content-Type": "application/json"
        //   }
        // }).then(handleErrors).then(function(response) {
        //   return response.json();
        // }).then(function(data) {
        //   console.dir(data);
        //   console.log(data["results"][0]["user_id"])
        //   return data["results"][0];
        // });

        // This method works on Android but not iOS.
        return http.getJSON(loginUrl).then(function(response) {
              console.dir(response);
              return response.results[0];
        })

    };

    return viewModel;
};

function handleErrors(response) {
    console.log("in errors")
    if (!response.ok) {
        console.log(JSON.stringify(response));
        throw Error(response.statusText);
    }
    return response;
}

module.exports = User;

Is there anything fundamentally wrong with my code, or do asynchronous calls work differently on iOS vs Android in Nativescript? I did the Grocery tutorial and didn't run into this issue, so I didn't think this was the case. Does it matter that the backend is using PHP?


问:
Save calculated value as a model field
As a follow up to my eariler question I have a new one. How can I save this calculated value as a model field. I would like to use it in my views and templates to order list by this field.

My models:

```<code>class Tournament(models.Model):
   name = models.CharField(max_length=100)
   date = models.DateTimeField('date')
   player_num = models.IntegerField(verbose_name="")
   points = models.FloatField(default=1000.00)
   def get_rating(self):
       return self.points / 1000.00

class TournamentStandings(models.Model):
   tournament = models.ForeignKey(Tournament, on_delete=models.CASCADE)
   player = models.ForeignKey(Player, on_delete=models.CASCADE)
   player_place = models.FloatField(verbose_name=u"")
   player_points = models.FloatField(verbose_name="",
   blank=True) #added for testing to save the calculated value in it
   @property
   def get_player_points(self, obj):
       return obj.tournament.player_num * obj.tournament.get_rating() -
       obj.tournament.get_rating()*(obj.player_place - 1.00)

   def save(self, *args, **kwargs):
       self.player_points = self.get_player_points
       super(TournamentStandings, self).save(*args, **kwargs)

   def __float__(self):
     return self.player_points
</code>```

Funny as on the admin list I have a column where player_points are calculated correctly but when I add a new model instance and try to save it I get this error : 'TournamentStandings' object has no attribute 'get_player_points'. Is it bacause I am trying  to do a "self" save and my calculation is (self, obj) ?? Any hints are wellcome.

答:
get_player_points() is a method and requires parentheses.</p>

```<code>def save(self, *args, **kwargs):
     self.player_points = self.get_player_points()
</code>```

Title: Save calculated value as a model field

Body:
As a follow up to my eariler question I have a new one. How can I save this calculated value as a model field. I would like to use it in my views and templates to order list by this field.

My models:

class Tournament(models.Model):
   name = models.CharField(max_length=100)
   date = models.DateTimeField('date')
   player_num = models.IntegerField(verbose_name="")
   points = models.FloatField(default=1000.00)
   def get_rating(self):
       return self.points / 1000.00

class TournamentStandings(models.Model):
   tournament = models.ForeignKey(Tournament, on_delete=models.CASCADE)
   player = models.ForeignKey(Player, on_delete=models.CASCADE)
   player_place = models.FloatField(verbose_name=u"")
   player_points = models.FloatField(verbose_name="",
   blank=True) #added for testing to save the calculated value in it
   @property
   def get_player_points(self, obj):
       return obj.tournament.player_num * obj.tournament.get_rating() -
       obj.tournament.get_rating()*(obj.player_place - 1.00)

   def save(self, *args, **kwargs):
       self.player_points = self.get_player_points
       super(TournamentStandings, self).save(*args, **kwargs)

   def __float__(self):
     return self.player_points

Funny as on the admin list I have a column where player_points are calculated correctly but when I add a new model instance and try to save it I get this error : 'TournamentStandings' object has no attribute 'get_player_points'. Is it bacause I am trying  to do a "self" save and my calculation is (self, obj) ?? Any hints are wellcome.

Body:
get_player_points() is a method and requires parentheses.

def save(self, *args, **kwargs):
     self.player_points = self.get_player_points()


问:
Running regex from windows BATCH
I'm trying to use regex running from a batch

```<code><zed>(.*?)<zed>
</code>```

to find values I've stored in a file

```<code><process>34593845387<process>
<zed>M567<zed>
<encode>UTF16<encode>
</code>```

I'm able to do that from java not from batch

答:
Why not use cscript to access use Javascript regex?

type data.txt | cscript //nologo match.js "<zed>(.*)<zed>"
```

<p>Where <code>match.js</code> is defined as:</p>

<pre class="lang-js prettyprint-override"><code>if (WScript.Arguments.Count() !== 1) {
  WScript.Echo("Syntax: match.js regex");
  WScript.Quit(1);
}
var rx = new RegExp(WScript.Arguments(0), "i");
var matched = false;
while (!WScript.StdIn.AtEndOfStream) {
  var str = WScript.StdIn.ReadLine();
  if (str.match(rx)) {
    WScript.Echo(str);
    matched = true;
  }
}
if (!matched) {
  WScript.Quit(1);
}
</code>```

Title: Running regex from windows BATCH

Body:
I'm trying to use regex running from a batch

<zed>(.*?)<zed>

to find values I've stored in a file

<process>34593845387<process>
<zed>M567<zed>
<encode>UTF16<encode>

I'm able to do that from java not from batch

Body:
Why not use cscript to access use Javascript regex?

type data.txt | cscript //nologo match.js "<zed>(.*)<zed>"

Where match.js is defined as:

if (WScript.Arguments.Count() !== 1) {
  WScript.Echo("Syntax: match.js regex");
  WScript.Quit(1);
}
var rx = new RegExp(WScript.Arguments(0), "i");
var matched = false;
while (!WScript.StdIn.AtEndOfStream) {
  var str = WScript.StdIn.ReadLine();
  if (str.match(rx)) {
    WScript.Echo(str);
    matched = true;
  }
}
if (!matched) {
  WScript.Quit(1);
}


问:
FirebaseAuth returns null
Okay when i click on the register button to register a new user, it gives me this following behaviour.

The error :

Attempt to invoke virtual method 'com.google.android.gms.tasks.Task
  com.google.android.gms.common.api.GoogleApi.zzb(com.google.android.gms.common.api.internal.zzdf)'
  on a null object reference

The source of error :

at
  com.example.cmd.pop.Fragments.RegisterFragment$1.onClick(RegisterFragment.java:64)

And it points to this line:

```<code>mAuth.createUserWithEmailAndPassword(mail,pass)
                                .addOnCompleteListener(getActivity(), new OnCompleteListener<AuthResult>()
</code>```

RegisterFragment Class:

```<code>public class RegisterFragment extends Fragment {
private EditText mMail,mPass,mPassConf;
private Button mLogin,mRegister;
private FirebaseAuth mAuth;
private String mail,pass,passConf;

public RegisterFragment() {
    mAuth = FirebaseAuth.getInstance();
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.register_fragment_layout,container,false);
    find(v);
    onClick();
    return v;
}

private void find(View v) {
    mMail = (EditText)v.findViewById(R.id.registerName);
    mPass = (EditText)v.findViewById(R.id.registerPassword);
    mPassConf = (EditText)v.findViewById(R.id.registerPasswordConfirmation);
    mLogin = (Button)v.findViewById(R.id.btnLoginRegister);
    mRegister = (Button)v.findViewById(R.id.btnRegisterRegister);
}

private void onClick() {
    mRegister.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mail = mMail.getText().toString();
            pass = mPass.getText().toString();
            passConf = mPassConf.getText().toString();
            if(!isEmpty(mail) && !isEmpty(pass) && !isEmpty(passConf) ) {
                if(TextUtils.equals(pass,passConf)) {
                    mAuth.createUserWithEmailAndPassword(mail,pass)
                            .addOnCompleteListener(getActivity(), new OnCompleteListener<AuthResult>() {
                                @Override
                                public void onComplete(@NonNull Task<AuthResult> task) {
                                    if (task.isSuccessful()) {
                                        getActivity().startActivity(new Intent(getActivity(), MainActivity.class));
                                        getActivity().finish();
                                    } else {
                                        Toast.makeText(getActivity(), "Error registering....", Toast.LENGTH_SHORT).show();
                                    }
                                }
                            });

                } else {
                    Toast.makeText(getActivity(), "Password didn't match.", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(getActivity(), "All fields need to be filled.", Toast.LENGTH_SHORT).show();
            }
        }
    });

    mLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Fragment loginFragment = new LoginFragment();
            getActivity().getSupportFragmentManager().beginTransaction()
                    .replace(R.id.loginActivityContainer,loginFragment).commit();

        }
    });

}

private boolean isEmpty(String name) {
    return TextUtils.isEmpty(name);
}
</code>```

App level Gradle

```<code> apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion "27.0.0"
    defaultConfig {
        applicationId "com.example.cmd.pop"
        minSdkVersion 19
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    implementation 'com.android.support:support-v4:26.1.0'
    implementation 'com.google.firebase:firebase-database:11.6.0'
    implementation 'com.google.firebase:firebase-auth:11.6.0'
    compile 'com.android.support:design:26.1.0'
    compile 'com.android.support:cardview-v7:26.1.0'
    compile 'com.android.support:recyclerview-v7:26.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation('com.android.support.test.espresso:espresso-core:3.0.1', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
}

apply plugin: 'com.google.gms.google-services'
</code>```

Project Level Gradle

```<code>   // Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.0-alpha03'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        classpath 'com.google.gms:google-services:3.1.0'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

答:
Try downgrading firebase to an earlier version after verifying you enabled email/password in the console</p>

```<code>implementation 'com.google.firebase:firebase-auth: 9.6.0'
</code>```

Title: FirebaseAuth returns null

Body:
Okay when i click on the register button to register a new user, it gives me this following behaviour.

The error :

Attempt to invoke virtual method 'com.google.android.gms.tasks.Task
  com.google.android.gms.common.api.GoogleApi.zzb(com.google.android.gms.common.api.internal.zzdf)'
  on a null object reference

The source of error :

at
  com.example.cmd.pop.Fragments.RegisterFragment$1.onClick(RegisterFragment.java:64)

And it points to this line:

mAuth.createUserWithEmailAndPassword(mail,pass)
                                .addOnCompleteListener(getActivity(), new OnCompleteListener<AuthResult>()

RegisterFragment Class:

public class RegisterFragment extends Fragment {
private EditText mMail,mPass,mPassConf;
private Button mLogin,mRegister;
private FirebaseAuth mAuth;
private String mail,pass,passConf;

public RegisterFragment() {
    mAuth = FirebaseAuth.getInstance();
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.register_fragment_layout,container,false);
    find(v);
    onClick();
    return v;
}

private void find(View v) {
    mMail = (EditText)v.findViewById(R.id.registerName);
    mPass = (EditText)v.findViewById(R.id.registerPassword);
    mPassConf = (EditText)v.findViewById(R.id.registerPasswordConfirmation);
    mLogin = (Button)v.findViewById(R.id.btnLoginRegister);
    mRegister = (Button)v.findViewById(R.id.btnRegisterRegister);
}

private void onClick() {
    mRegister.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mail = mMail.getText().toString();
            pass = mPass.getText().toString();
            passConf = mPassConf.getText().toString();
            if(!isEmpty(mail) && !isEmpty(pass) && !isEmpty(passConf) ) {
                if(TextUtils.equals(pass,passConf)) {
                    mAuth.createUserWithEmailAndPassword(mail,pass)
                            .addOnCompleteListener(getActivity(), new OnCompleteListener<AuthResult>() {
                                @Override
                                public void onComplete(@NonNull Task<AuthResult> task) {
                                    if (task.isSuccessful()) {
                                        getActivity().startActivity(new Intent(getActivity(), MainActivity.class));
                                        getActivity().finish();
                                    } else {
                                        Toast.makeText(getActivity(), "Error registering....", Toast.LENGTH_SHORT).show();
                                    }
                                }
                            });

                } else {
                    Toast.makeText(getActivity(), "Password didn't match.", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(getActivity(), "All fields need to be filled.", Toast.LENGTH_SHORT).show();
            }
        }
    });

    mLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Fragment loginFragment = new LoginFragment();
            getActivity().getSupportFragmentManager().beginTransaction()
                    .replace(R.id.loginActivityContainer,loginFragment).commit();

        }
    });

}

private boolean isEmpty(String name) {
    return TextUtils.isEmpty(name);
}

App level Gradle

 apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion "27.0.0"
    defaultConfig {
        applicationId "com.example.cmd.pop"
        minSdkVersion 19
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    implementation 'com.android.support:support-v4:26.1.0'
    implementation 'com.google.firebase:firebase-database:11.6.0'
    implementation 'com.google.firebase:firebase-auth:11.6.0'
    compile 'com.android.support:design:26.1.0'
    compile 'com.android.support:cardview-v7:26.1.0'
    compile 'com.android.support:recyclerview-v7:26.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation('com.android.support.test.espresso:espresso-core:3.0.1', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
}

apply plugin: 'com.google.gms.google-services'

Project Level Gradle

   // Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.0-alpha03'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        classpath 'com.google.gms:google-services:3.1.0'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Body:
Try downgrading firebase to an earlier version after verifying you enabled email/password in the console

implementation 'com.google.firebase:firebase-auth: 9.6.0'


问:
Discarding changes with a DataGridView BindingSource to EF
I have a little problem with my windows form app.
Two forms: Parent Form - here I have DataGridView which presents list of Company. From here, I can open another form, CompanyForm, where you can add or edit selected Company. Add options work fine but when I edit company and want to discard changes, on Parent Form selected row was changed although I don't save change on my context. Someone can help me?

ParentForm:

```<code>private void CompaniesForm_Load(object sender, EventArgs e)
    {
        using (var connect = new ContactEntities())
        {
            companyBindingSource.DataSource = connect.Companies.ToList();
        }
    }
</code>```

Button Edit company:

```<code>private void buttonEditCompany_Click(object sender, EventArgs e)
    {
        CompanyForm company = new CompanyForm();
        company.MdiParent = this.MdiParent;
        company.Company = (Company)companyBindingSource.Current;
        company.Show();
    }
</code>```

CompanyForm:

```<code>public Company Company { get; set; }
private void CompanyForm_Load(object sender, EventArgs e)
        {
            using (var connect = new ContactEntities())
            {
                companyBindingSource.DataSource = Company;
            }
        }
</code>```

As you can see, I use bindingsource and I don't know why grid it was automatically updates.

答:
EDIT: Answered the wrong question. Thanks @Reza Aghaei for pointing that out to me.

Just a guess, but if you're using Mode=TwoWay in your binding,  try setting UpdateSourceTrigger=Explicit and call UpdateSource() when you save the changes.

Body:
I have a little problem with my windows form app.
Two forms: Parent Form - here I have DataGridView which presents list of Company. From here, I can open another form, CompanyForm, where you can add or edit selected Company. Add options work fine but when I edit company and want to discard changes, on Parent Form selected row was changed although I don't save change on my context. Someone can help me?

ParentForm:

private void CompaniesForm_Load(object sender, EventArgs e)
    {
        using (var connect = new ContactEntities())
        {
            companyBindingSource.DataSource = connect.Companies.ToList();
        }
    }

Button Edit company:

private void buttonEditCompany_Click(object sender, EventArgs e)
    {
        CompanyForm company = new CompanyForm();
        company.MdiParent = this.MdiParent;
        company.Company = (Company)companyBindingSource.Current;
        company.Show();
    }

CompanyForm:

public Company Company { get; set; }
private void CompanyForm_Load(object sender, EventArgs e)
        {
            using (var connect = new ContactEntities())
            {
                companyBindingSource.DataSource = Company;
            }
        }

As you can see, I use bindingsource and I don't know why grid it was automatically updates.


问:
Windows Native API: When and why use Zw vs Nt prefixed api calls?
In Native API Microsoft exports two versions of each api call, one prefixed with Zw and one with Nt, for eg. ZwCreateThread and NtCreateThread.

My question is what is the difference between those two versions of the calls and when and why one should use Zw or Nt exclusively?
To my understanding Zw version ensures that the caller resides in kernel mode, whereas Nt doesn't.

I am also wondering about the specific meaning for Zw and Nt prefixes/abbreviations?
One can guess Nt probably refers to NT(New Technology) Windows family or Native(probably not)?
As for Zw, does it stand for something?

答:
Update:

Aside from Larry Osterman's answer (which you should definitely read), there's another thing I should mention:

Since the NtXxx variants perform checks as though the call is coming from user-mode, this means that any buffers passed to the NtXxs function must reside in user-mode address spaces, not kernel-mode. So if you call a function like NtCreateFile in your driver and pass it pointers to kernel-mode buffers, you will get back a STATUS_ACCESS_VIOLATION because of this.

See Using Nt and Zw Versions of the Native System Services Routines.

A kernel-mode driver calls the Zw version of a native system services routine to inform the routine that the parameters come from a trusted, kernel-mode source. In this case, the routine assumes that it can safely use the parameters without first validating them. However, if the parameters might be from either a user-mode source or a kernel-mode source, the driver instead calls the Nt version of the routine, which determines, based on the history of the calling thread, whether the parameters originated in user mode or kernel mode.

Native system services routines make additional assumptions about the parameters that they receive. If a routine receives a pointer to a buffer that was allocated by a kernel-mode driver, the routine assumes that the buffer was allocated in system memory, not in user-mode memory. If the routine receives a handle that was opened by a user-mode application, the routine looks for the handle in the user-mode handle table, not in the kernel-mode handle table.

Also, Zw doesn't stand for anything. See What Does the Zw Prefix Mean?:

The Windows native system services routines have names that begin with the prefixes Nt and Zw. The Nt prefix is an abbreviation of Windows NT, but the Zw prefix has no meaning. Zw was selected partly to avoid potential naming conflicts with other APIs, and partly to avoid using any potentially useful two-letter prefixes that might be needed in the future.

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 4.0


问:
Goal: stripping whitespace adjacent to certain characters
What I am doing:

```<code>> ' { foo ( bar: 8 ) { baz: 9 fun: bun } } '.replace(/\s[{}():]\s/g, '');
< "foobar: 8{ baz: 9 fun: bun} "
</code>```

What I am trying to do:

```<code>> ???
< "{foo(bar:8){baz:9 fun:bun}}"
</code>```

This has to do with compressing queries for sending from a client to a graphql server. ;-)

答:
You have to use capture group in the regex to replace the character without space :

```<code>> '{ foo ( bar: 8 ) { baz: 9 fun: bun } } '.replace(/\s*(\[|\]|\{|\}|\(|\)|\:)\s*/g, '$1')
< "{foo(bar:8){baz:9 fun:bun}}"
</code>```

The parenthesis capture the expression, and $1 allow you to use this expression.

Body:
What I am doing:

> ' { foo ( bar: 8 ) { baz: 9 fun: bun } } '.replace(/\s[{}():]\s/g, '');
< "foobar: 8{ baz: 9 fun: bun} "

What I am trying to do:

> ???
< "{foo(bar:8){baz:9 fun:bun}}"

This has to do with compressing queries for sending from a client to a graphql server. ;-)

Body:
You have to use capture group in the regex to replace the character without space :

> '{ foo ( bar: 8 ) { baz: 9 fun: bun } } '.replace(/\s*(\[|\]|\{|\}|\(|\)|\:)\s*/g, '$1')
< "{foo(bar:8){baz:9 fun:bun}}"

The parenthesis capture the expression, and $1 allow you to use this expression.


问:
Excluding Keycode (android)
I want to exclude the "Enter"(keycode 13) key on Android when a user selects a quantity but I need to still have him able to remove a quantity(keycode 8).

```<code><input type="number" name="quantity" value="<?php echo $this->request-
>quantity; ?>" size="3" onkeypress="return event.charCode <= 57"
maxlength="3"/>
</code>```

I tried using "&& event.charCode !=13" or selecting each number individually with the == operator but it doesn't work, should I create a condition or could I use javascript to intercept the charCode 13 when used?

答:
I found a solution with :

```<code><input type="number" name="quantity" value="<?php echo $this->request-
>quantity; ?>" size="3" onkeydown='return (event.which >= 48 && event.which <=
57) || event.which == 8 || event.which == 46' required />
</code>```

Thanks to
Only allow numbers, backspace and delete keys on input text

Title: Excluding Keycode (android)

Body:
I want to exclude the "Enter"(keycode 13) key on Android when a user selects a quantity but I need to still have him able to remove a quantity(keycode 8).

<input type="number" name="quantity" value="<?php echo $this->request-
>quantity; ?>" size="3" onkeypress="return event.charCode <= 57"
maxlength="3"/>

I tried using "&& event.charCode !=13" or selecting each number individually with the == operator but it doesn't work, should I create a condition or could I use javascript to intercept the charCode 13 when used?

Body:
I found a solution with :

<input type="number" name="quantity" value="<?php echo $this->request-
>quantity; ?>" size="3" onkeydown='return (event.which >= 48 && event.which <=
57) || event.which == 8 || event.which == 46' required />

Thanks to
Only allow numbers, backspace and delete keys on input text


问:
page does not wait for another page to finish their tasks before continuing
So here's the code snippet:

```<code>    for (let item of items)
    {
        await page.waitFor(10000)
        await page.click("#item_"+item)
        await page.click("#i"+item)

        let pages = await browser.pages()
        let tempPage = pages[pages.length-1]

        await tempPage.waitFor("a.orange", {timeout: 60000, visible: true})
        await tempPage.click("a.orange")

        counter++
    }
</code>```

page and tempPage are two different pages.

What happens is that page waits for 10 seconds, then clicks some stuff, which opens a second page.

What's supposed to happen is that tempPage waits for an element, clicks it, then page should wait 10 seconds before doing it all over again.

However, what actually happens is that page waits for 10 seconds, clicks the stuff, then starts waiting for 10 seconds without waiting for tempPage to finish its tasks.

Is this a bug, or am I misunderstanding something? How should I fix this so that when the for loop loops again, it is only after tempPage has clicked.

答:
Generally, you cannot rely on await tempPage.click("a.orange") to pause execution until tempPage has "finish[ed] its tasks".  For super simple code that executes synchronously, it may work. But in general, you cannot rely on it.

If the click triggers an Ajax operation, or starts a CSS animation, or starts a computation that cannot be immediately computed, or opens a new page, etc., then the result you are waiting for is asynchronous, and the .click method will not wait for this asynchronous operation to complete.

What can you do? In some cases you may be able to hook into the code that is running on the page and wait for some event that matters to you. For instance, if you want to wait for an Ajax operation to be done and the code on the page uses jQuery, then you might use ajaxComplete to detect when the operation is complete. If you cannot hook into any event system to detect when the operation is done, then you may need to poll the page to wait for evidence that the operation is done.

Here is an example that shows the issue:

```<code>const puppeteer = require('puppeteer');

function getResults(page) {
    return page.evaluate(() => ({
        clicked: window.clicked,
        asynchronousResponse: window.asynchronousResponse,
    }));
}

puppeteer.launch().then(async browser => {
    const page = await browser.newPage();
    await page.goto("https://example.com");
    // We add a button to the page that will click later.
    await page.evaluate(() => {
        const button = document.createElement("button");
        button.id = "myButton";
        button.textContent = "My Button";
        document.body.appendChild(button);
        window.clicked = 0;
        window.asynchronousResponse = 0;
        button.addEventListener("click", () => {
            // Synchronous operation
            window.clicked++;

            // Asynchronous operation.
            setTimeout(() => {
                window.asynchronousResponse++;
            }, 1000);
        });
    });

    console.log("before clicks", await getResults(page));

    const button = await page.$("#myButton");
    await button.click();
    await button.click();
    console.log("after clicks", await getResults(page));

    await page.waitForFunction(() => window.asynchronousResponse === 2);
    console.log("after wait", await getResults(page));

    await browser.close();
});
</code>```

The setTimeout code simulates any kind of asynchronous operation started by the click.

When you run this code, you'll see on the console:

```<code>before click { clicked: 0, asynchronousResponse: 0 }
after click { clicked: 2, asynchronousResponse: 0 }
after wait { clicked: 2, asynchronousResponse: 2 }
</code>```

You see that clicked is immediately incremented twice by the two clicks. However, it takes a while before asynchronousResponse is incremented. The statement await page.waitForFunction(() => window.asynchronousResponse === 2) polls the page until the condition we are waiting for is realized.

You mentioned in a comment that the button is closing the tab. Opening and closing tabs are asynchronous operations. Here's an example:

```<code>puppeteer.launch().then(async browser => {
    let pages = await browser.pages();
    console.log("number of pages", pages.length);
    const page = pages[0];
    await page.goto("https://example.com");
    await page.evaluate(() => {
        window.open("https://example.com");
    });

    do {
        pages = await browser.pages();
        // For whatever reason, I need to have this here otherwise
        // browser.pages() always returns the same value. And the loop
        // never terminates.
        await page.evaluate(() => {});
        console.log("number of pages after evaluating open", pages.length);
    } while (pages.length === 1);

    let tempPage = pages[pages.length - 1];

    // Add a button that will close the page when we click it.
    tempPage.evaluate(() => {
        const button = document.createElement("button");
        button.id = "myButton";
        button.textContent = "My Button";
        document.body.appendChild(button);
        window.clicked = 0;
        window.asynchronousResponse = 0;
        button.addEventListener("click", () => {
            window.close();
        });
    });

    const button = await tempPage.$("#myButton");
    await button.click();

    do {
        pages = await browser.pages();
        // For whatever reason, I need to have this here otherwise
        // browser.pages() always returns the same value. And the loop
        // never terminates.
        await page.evaluate(() => {});
        console.log("number of pages after click", pages.length);
    } while (pages.length > 1);

    await browser.close();
});
</code>```

When I run the above, I get:

```<code>number of pages 1
number of pages after evaluating open 1
number of pages after evaluating open 1
number of pages after evaluating open 2
number of pages after click 2
number of pages after click 1
</code>```

You can see it takes a bit before window.open() and window.close() have detectable effects.

In your comment you also wrote:

I thought await was basically what turned an asynchronous function into a synchronous one

I would not say it turns asynchronous functions into synchronous ones. It makes the current code wait for an asynchronous operation's promise to be resolved or rejected. However, more importantly for the issue at hand here, the problem is that you have two virtual machines executing JavaScript code: there's Node which runs puppeteer and the script that controls the browser, and there's the browser itself which has its own JavaScript virtual machine. Any await that you use on the Node side affects only the Node code: it has no bearing on the code that runs in the browser.

It can get confusing when you see things like await page.evaluate(() => { some code; }). It looks like it is all of one piece, and all executing in the same virtual machine, but it is not. puppeteer takes the parameter passed to .evaluate, serializes it, and sends it over to the browser, where it executes. Try adding something like await page.evaluate(() => { button.click(); }); in the script above, after const button = .... Something like this:

```<code>const button = await tempPage.$("#myButton");
await button.click();
await page.evaluate(() => { button.click(); });
</code>```

In the script, button is defined before page.evaluate, but you'll get a ReferenceError when page.evaluate runs because button is not defined on the browser side!

Body:
So here's the code snippet:

    for (let item of items)
    {
        await page.waitFor(10000)
        await page.click("#item_"+item)
        await page.click("#i"+item)

        let pages = await browser.pages()
        let tempPage = pages[pages.length-1]

        await tempPage.waitFor("a.orange", {timeout: 60000, visible: true})
        await tempPage.click("a.orange")

        counter++
    }

page and tempPage are two different pages.

What happens is that page waits for 10 seconds, then clicks some stuff, which opens a second page.

What's supposed to happen is that tempPage waits for an element, clicks it, then page should wait 10 seconds before doing it all over again.

However, what actually happens is that page waits for 10 seconds, clicks the stuff, then starts waiting for 10 seconds without waiting for tempPage to finish its tasks.

Is this a bug, or am I misunderstanding something? How should I fix this so that when the for loop loops again, it is only after tempPage has clicked.

Body:
Generally, you cannot rely on await tempPage.click("a.orange") to pause execution until tempPage has "finish[ed] its tasks".  For super simple code that executes synchronously, it may work. But in general, you cannot rely on it.

If the click triggers an Ajax operation, or starts a CSS animation, or starts a computation that cannot be immediately computed, or opens a new page, etc., then the result you are waiting for is asynchronous, and the .click method will not wait for this asynchronous operation to complete.

What can you do? In some cases you may be able to hook into the code that is running on the page and wait for some event that matters to you. For instance, if you want to wait for an Ajax operation to be done and the code on the page uses jQuery, then you might use ajaxComplete to detect when the operation is complete. If you cannot hook into any event system to detect when the operation is done, then you may need to poll the page to wait for evidence that the operation is done.

Here is an example that shows the issue:

const puppeteer = require('puppeteer');

function getResults(page) {
    return page.evaluate(() => ({
        clicked: window.clicked,
        asynchronousResponse: window.asynchronousResponse,
    }));
}

puppeteer.launch().then(async browser => {
    const page = await browser.newPage();
    await page.goto("https://example.com");
    // We add a button to the page that will click later.
    await page.evaluate(() => {
        const button = document.createElement("button");
        button.id = "myButton";
        button.textContent = "My Button";
        document.body.appendChild(button);
        window.clicked = 0;
        window.asynchronousResponse = 0;
        button.addEventListener("click", () => {
            // Synchronous operation
            window.clicked++;

            // Asynchronous operation.
            setTimeout(() => {
                window.asynchronousResponse++;
            }, 1000);
        });
    });

    console.log("before clicks", await getResults(page));

    const button = await page.$("#myButton");
    await button.click();
    await button.click();
    console.log("after clicks", await getResults(page));

    await page.waitForFunction(() => window.asynchronousResponse === 2);
    console.log("after wait", await getResults(page));

    await browser.close();
});

The setTimeout code simulates any kind of asynchronous operation started by the click.

When you run this code, you'll see on the console:

before click { clicked: 0, asynchronousResponse: 0 }
after click { clicked: 2, asynchronousResponse: 0 }
after wait { clicked: 2, asynchronousResponse: 2 }

You see that clicked is immediately incremented twice by the two clicks. However, it takes a while before asynchronousResponse is incremented. The statement await page.waitForFunction(() => window.asynchronousResponse === 2) polls the page until the condition we are waiting for is realized.

You mentioned in a comment that the button is closing the tab. Opening and closing tabs are asynchronous operations. Here's an example:

puppeteer.launch().then(async browser => {
    let pages = await browser.pages();
    console.log("number of pages", pages.length);
    const page = pages[0];
    await page.goto("https://example.com");
    await page.evaluate(() => {
        window.open("https://example.com");
    });

    do {
        pages = await browser.pages();
        // For whatever reason, I need to have this here otherwise
        // browser.pages() always returns the same value. And the loop
        // never terminates.
        await page.evaluate(() => {});
        console.log("number of pages after evaluating open", pages.length);
    } while (pages.length === 1);

    let tempPage = pages[pages.length - 1];

    // Add a button that will close the page when we click it.
    tempPage.evaluate(() => {
        const button = document.createElement("button");
        button.id = "myButton";
        button.textContent = "My Button";
        document.body.appendChild(button);
        window.clicked = 0;
        window.asynchronousResponse = 0;
        button.addEventListener("click", () => {
            window.close();
        });
    });

    const button = await tempPage.$("#myButton");
    await button.click();

    do {
        pages = await browser.pages();
        // For whatever reason, I need to have this here otherwise
        // browser.pages() always returns the same value. And the loop
        // never terminates.
        await page.evaluate(() => {});
        console.log("number of pages after click", pages.length);
    } while (pages.length > 1);

    await browser.close();
});

When I run the above, I get:

number of pages 1
number of pages after evaluating open 1
number of pages after evaluating open 1
number of pages after evaluating open 2
number of pages after click 2
number of pages after click 1

You can see it takes a bit before window.open() and window.close() have detectable effects.

In your comment you also wrote:

I thought await was basically what turned an asynchronous function into a synchronous one

I would not say it turns asynchronous functions into synchronous ones. It makes the current code wait for an asynchronous operation's promise to be resolved or rejected. However, more importantly for the issue at hand here, the problem is that you have two virtual machines executing JavaScript code: there's Node which runs puppeteer and the script that controls the browser, and there's the browser itself which has its own JavaScript virtual machine. Any await that you use on the Node side affects only the Node code: it has no bearing on the code that runs in the browser.

It can get confusing when you see things like await page.evaluate(() => { some code; }). It looks like it is all of one piece, and all executing in the same virtual machine, but it is not. puppeteer takes the parameter passed to .evaluate, serializes it, and sends it over to the browser, where it executes. Try adding something like await page.evaluate(() => { button.click(); }); in the script above, after const button = .... Something like this:

const button = await tempPage.$("#myButton");
await button.click();
await page.evaluate(() => { button.click(); });

In the script, button is defined before page.evaluate, but you'll get a ReferenceError when page.evaluate runs because button is not defined on the browser side!


问:
Spring ModelAttribute correct parsing
I have Spring controller with endpoint like:

```<code>@RequestMapping("/provider")
public ResponseEntity<Something> load(@ModelAttribute PageRequest pageRequest)
{
    ... //do something
}
</code>```

where PageRequest is simple POJO:

```<code>class PageRequest
{
    String[] field;
    String[] value;
    ... // constructor getters settest
}
</code>```

When I GET request like:
.../provider?field=commanders&value=John%2CBill%2CAlex then pageRequestdata is mapped:

```<code>field[0] = commanders;

value[0] = John
value[1] = Bill
value[2] = Alex
</code>```

But when I GET request like:
.../provider?field=country&value=Australia&field=commanders&value=John%2CBill%2CAlex then pageRequestdata is mapped:

```<code>field[0] = country;
field[1] = commanders;

value[0] = Australia
value[1] = "John,Bill,Alex"
</code>```

My question is why mapping is different for these requests, and can it be done for first request same as for the second. (comma %2C separated data map to single value).

used: Spring 3.x

答:
I did some investigation and figured out that for first request value=John%2CBill%2CAlex Spring using org.springframework.format.supportDefaultFormattingConversionService class which under the hood has org.springframework.core.convert.support.StringToArrayConverter whose convert() method split your string by to array using comma as a separator.

You have 2 ways to resolve this issue:

Use ; instead of , as separator for you value (value=John;Bill;Alex)

Use different conversion service bean containing your own converter from String to String[]. For more details look at this answer

Title: Spring ModelAttribute correct parsing

Body:
I have Spring controller with endpoint like:

@RequestMapping("/provider")
public ResponseEntity<Something> load(@ModelAttribute PageRequest pageRequest)
{
    ... //do something
}

where PageRequest is simple POJO:

class PageRequest
{
    String[] field;
    String[] value;
    ... // constructor getters settest
}

When I GET request like:
.../provider?field=commanders&value=John%2CBill%2CAlex then pageRequestdata is mapped:

field[0] = commanders;

value[0] = John
value[1] = Bill
value[2] = Alex

But when I GET request like:
.../provider?field=country&value=Australia&field=commanders&value=John%2CBill%2CAlex then pageRequestdata is mapped:

field[0] = country;
field[1] = commanders;

value[0] = Australia
value[1] = "John,Bill,Alex"

My question is why mapping is different for these requests, and can it be done for first request same as for the second. (comma %2C separated data map to single value).

used: Spring 3.x


问:
Error when deploying Tizen App - Failed to get a device information
I am having a problem with deploying a Tizen app onto my Samsung smart tv. For some time it was working really good, but since updating tizen studio to 2.0 and the tv-extension to 4.0 it isn't working anymore. I always get a 'Failed to get a device information' error.

[2017.11.22 00:54:29][ERROR] ProfileInfo.java(426) - Failed to get a device information from '10.0.0.40:26101' (model: UJ5500, platform: Tizen, version: unknown, profile: unknown                      `-¶)
  java.lang.Exception: Failed to get a device's profile version
      at org.tizen.common.core.application.ProfileInfo.getProfileInfo(ProfileInfo.java:413)
      at org.tizen.common.util.LaunchUtil.checkProfile(LaunchUtil.java:158)
      at org.tizen.web.zimlaunch.deployer.ZimLaunchDelegate.preLaunchCheck(ZimLaunchDelegate.java:141)
      at org.eclipse.debug.internal.core.LaunchConfiguration.launch(LaunchConfiguration.java:840)
      at org.eclipse.debug.internal.core.LaunchConfiguration.launch(LaunchConfiguration.java:739)
      at org.eclipse.debug.internal.ui.DebugUIPlugin.buildAndLaunch(DebugUIPlugin.java:1039)
      at org.eclipse.debug.internal.ui.DebugUIPlugin$8.run(DebugUIPlugin.java:1256)
      at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55)

The required Tizen version is set to 2.3 and my model is a UJ5500 (2015).

On the dev website of samsung they say that this kind of error is only occuring on 2015 models and it can be ignored, but I can't deploy it. I also thought about downgrading tizen studio to 1.3 and the tv-extension to 3.0 as i had before, sadly I can't install the web-app dev of the package manager. For those of you who might think that this is caused by the certificate, I already created a public and partner one with my UDID of my Samsung device. And by the way it is also not working on an emulator (same error).

答:
You need to use an older Tizen Studio for this (I know, I know, its stupid - hopefully you kept the old one around).  As I'm sure you've noticed you can't install the TV-2.3.0 extension that your TV requires.  I have the same problem with mine.  The answer is buried here: http://developer.samsung.com/tv/develop/specifications/tv-model-groups
and I got the inspiration to figure it out from: https://developer.tizen.org/ko/forums/sdk-ide/device-manager-unknown-platform?langredirect=1

Would be nice if they'd just let you install the older TV extensions in the new IDE right?  Oh well... hope this helps you a little.  If you are ever unsure run the undocumented "./sdb capability" and it'll show you what version the TV needs.

```<code>~/tizen-studio-2/tools/sdb capability

secure_protocol:enabled
rootcmd_support:disabled
zone_support:disabled
multiuser_support:disabled
cpu_arch:armv7
profile_name:tv
vendor_name:Samsung
--->>> platform_version:2.3.0 <<<---
product_version:1.0
sdbd_version:2.2.17
</code>```

-Sebastian

Body:
You need to use an older Tizen Studio for this (I know, I know, its stupid - hopefully you kept the old one around).  As I'm sure you've noticed you can't install the TV-2.3.0 extension that your TV requires.  I have the same problem with mine.  The answer is buried here: http://developer.samsung.com/tv/develop/specifications/tv-model-groups
and I got the inspiration to figure it out from: https://developer.tizen.org/ko/forums/sdk-ide/device-manager-unknown-platform?langredirect=1

Would be nice if they'd just let you install the older TV extensions in the new IDE right?  Oh well... hope this helps you a little.  If you are ever unsure run the undocumented "./sdb capability" and it'll show you what version the TV needs.

~/tizen-studio-2/tools/sdb capability

secure_protocol:enabled
rootcmd_support:disabled
zone_support:disabled
multiuser_support:disabled
cpu_arch:armv7
profile_name:tv
vendor_name:Samsung
--->>> platform_version:2.3.0 <<<---
product_version:1.0
sdbd_version:2.2.17

-Sebastian


问:
multiple drive issue when receiving inputs from external source in verilog synthesis
The synthesis I'm trying to do is on a GCD algorithm Finite State Machine that works using the "subtract if bigger" method. I will attach the code and try and formulate a decent question.

```<code>module GCD_R (A,B,out,nrst,act,clk,fla_g);
  input [31:0] A, B;
  input clk, act, nrst;
  output reg fla_g;
  output reg [31:0] out;
  reg [3:0] state, next_state;
  reg [31:0] A_reg, B_reg, Aint_reg, Bint_reg, out_reg;//2 registers will keep intermediate numbers+out, and next numbers
  parameter IDLE = 3'b001;
  parameter ABIG = 3'b010;
  parameter BBIG = 3'b100;
  reg next_flag;

  always @(*)
    case (state)
      IDLE: begin
        $display("start");
        if(act == 0) begin
          A_reg = A; //A,B are wires that contain numbers from an external source
          B_reg = B; //first assign to A_reg and B_reg
          out_reg = 31'bx;
          next_flag = 1'b0;
          next_state = IDLE;
        end
        if(act == 1)
          if(A_reg==0) begin
            out_reg = B_reg;
            next_flag = 1'b1; //testbench will know when we stopped
            Aint_reg = A_reg; //taking care not to infer latches
            Bint_reg = B_reg;
            next_state = IDLE;
          end
          else if (B_reg==0) begin
            out_reg = A_reg;
            next_flag = 1'b1;
            Aint_reg = A_reg; //taking care not to infer latches
            Bint_reg = B_reg;
            next_state = IDLE;
          end
          else if (A_reg >= B_reg) begin
            out_reg = 31'bx;
            next_flag = 1'b0;
            Aint_reg = A_reg;
            Bint_reg = B_reg;
            next_state = ABIG;
          end
          else begin
            out_reg = 4'bxxx;
            next_flag = 1'b0;
            Aint_reg = A_reg;
            Bint_reg = B_reg;
            next_state = BBIG;
         end
       else
        begin
         Aint_reg = A_reg;
         Bint_reg = B_reg;
         out_reg = 4'bxxx;
         next_flag = 1'b0;
         next_state = 4'bx;
        end
     end

     ABIG: begin
       if (A_reg==0 | B_reg==0) begin
         out_reg = 31'bx;
         next_flag = 1'b0;
         next_state = IDLE;
         Aint_reg = A_reg;
         Bint_reg = B_reg;
       end
       else if (B_reg > A_reg) begin
         out_reg = 31'bx;
         next_flag = 1'b0;
         next_state = BBIG;
         Aint_reg = A_reg;
         Bint_reg = B_reg;
       end
       else begin
         out_reg = 31'bx;
         next_flag = 1'b0;
         next_state = ABIG;
         Aint_reg = A_reg - B_reg;
         Bint_reg = B_reg;
       end
     end

     BBIG: begin
       if (A_reg==0 | B_reg==0) begin
         out_reg = 31'bx;
         next_flag = 1'b0;
         next_state = IDLE;
         Aint_reg = A_reg;
         Bint_reg = B_reg;
       end
       else if (A_reg > B_reg) begin
         out_reg = 31'bx;
         next_flag = 1'b0;
         next_state = ABIG;
         Aint_reg = A_reg;
         Bint_reg = B_reg;
       end
       else begin
         out_reg = 31'bx;
         next_flag = 1'b0;
         next_state = BBIG;
         Aint_reg = A_reg;
         Bint_reg = B_reg - A_reg;
       end
     end

     default: begin
       out_reg = 31'bx;
       next_flag = 1'b0;
       next_state = 4'bx;
       Aint_reg = A_reg;
       Bint_reg = B_reg;
       $display("%t: State machine not initialized/n",$time);
     end
   endcase

 always @(posedge clk or negedge nrst)
   if (~nrst) begin
     state <=  IDLE;//we get the new values by resetting first
     out <= 4'bx;//we don't want anything there at the reset
     fla_g <= 1'b0;
   end
   else begin
     state <=  next_state;//otherwise, get the next state and the next registers to the intermediate ones
     A_reg <=  Aint_reg;// 2nd assign to A_reg and B_reg- that's the problem
     B_reg <=  Bint_reg;
     out <=  out_reg;
     fla_g <= next_flag;
   end

endmodule
</code>```

first, A and B are wires that will receive a list of numbers to compare via external source(some textfile in a testbench).

A_reg and B_reg are the intermediate registers that keep the numbers that we are checking the "if" statements on,

Aint_reg and Bint_reg are registers that keep the intermediate values of registers after the operations only to send them back to A_reg and B_reg when the clock is rising,

act decides whether the machine is on "on" mode and can perform the algorithm

nrst is the negative reset toggle

how was the problem formed:

you can see that at the beginning, there is an if(act == 0) condition. It was put there to ensure that the values at the A,B wires(received externally) will enter the registers there, instead of entering them in the sequential block while we were on the if(~nrst) condition since it made no sense entering a dynamic value while in reset.

This takes us to the current problem- I know that assigning a value to A and B both in the sequential and combinatoric blocks is what creates the problem, but I just can't find an alternative.

p.s. the fact that I'm using A_reg = A creates latches since I don't assign to A_reg anywhere else, and that's another problem since writing

Aint_reg = A_reg;
 A_reg = Aint_reg;

to satisfy latches doesn't sit right with me.

p.s.2. I tried looking into the similar questions on the site, but owing to my lack of enough knowledge on the subject I couldn't relate my problem to the ones out there

I'll be glad to receive any help, thanks

EDIT: I deleted the nonblocking assignments in the if(~nrst) sequential block so as to not to multiple assign A_reg <= 0 there and A_reg = A in the combinatoric block, but the multiple assignment problem still bugs it somehow

EDIT2: seems that I forgot a fundamental thing- don't assign to the same variable in two different "always" block, but I just can't think of a good enough solution to assign the wires A,B to a register and not assign to it again in the sequential block

答:
You are correct in identifying the major problem in your code is that you are not handling registers and combinational logic correctly. Whenever you have a register (register, not reg type, they are not the same and it is confusing for those new to Verilog), you need to define it in a particular way so synthesis and simulation tools can handle it. The safest practice is to create a clean separation between combinational logic and sequential storage (ie, actual registers). You started to do this with Aint_reg, Bint_reg, out_reg, etc; but you need to do it for all registered values whose values come from conbinational blocks. So, all these ideas together yields a struct for code like this (not completely your code but something similar):

```<code>input [31:0] A, B;
output reg [31:0] out;

reg [31:0] regA, regB;
reg [3:0] state, nextState;

always @(posedge clk or negedge rst) begin
  if (~rst) begin
    regA <= '0;
    regB <= '0;
    state <= IDLE;
  end
  else begin
    regA <= nextA;
    regB <= nextB;
    state <= nextState;
  end
end

always @(*) begin
  // Default; I always do this here to ensure there are no cases in which I dont assign a combinational value for this block
  // it always helps me keep track of which variables are assigned in which block
  nextA = regA;
  nextB = regB;
  nextState = state;

  out = '0;

  case (state)
    // In here is your case body, where you can reassign nextA, nextB, nextState and out
    // where the assignments are only dependent on A, B, regA, regB and state (ie, the values NOT assigned in this block)
  endcase
end
</code>```

With this in mind, you need to have only the Aint_reg, Bint_reg, etc in the combinational block; so you dont need to assign A_reg, Breg, etc in the combinational block. Note also that if this will mean the timing of out will be delayed, so you can always bypass the register if you need to push a value out from a combination block immediately. From what I understand, you might be having issues with loading during a reset, which is understandable as so long as reset (nrst) is asserted (ie, 0), nothing will load. That is the entire point of a reset, to hold the system in a known state until it is lifted. So until nrst is deasserted, your module shouldnt do anything. A few other points:

Formating your code correctly is very important, make sure your code is always clean as it helps spot bugs. I reformatted it and there seems to be a missing begin..end in the last block of the IDLE state

Always begin..end your blocks, it will avoid so many bugs

Watch out for the size of things, I see you declared your variables to be 32 bits reg [31:0] but are only assigning them using 31'd which is 31 bits. Use '0 syntax to zero fill for any size.

Setting registers to 'x is not ideal, you should have registers just retain their state (as you do thing for register values and next register values).

Hope this clarifies things for you.

Body:
The synthesis I'm trying to do is on a GCD algorithm Finite State Machine that works using the "subtract if bigger" method. I will attach the code and try and formulate a decent question.

module GCD_R (A,B,out,nrst,act,clk,fla_g);
  input [31:0] A, B;
  input clk, act, nrst;
  output reg fla_g;
  output reg [31:0] out;
  reg [3:0] state, next_state;
  reg [31:0] A_reg, B_reg, Aint_reg, Bint_reg, out_reg;//2 registers will keep intermediate numbers+out, and next numbers
  parameter IDLE = 3'b001;
  parameter ABIG = 3'b010;
  parameter BBIG = 3'b100;
  reg next_flag;

  always @(*)
    case (state)
      IDLE: begin
        $display("start");
        if(act == 0) begin
          A_reg = A; //A,B are wires that contain numbers from an external source
          B_reg = B; //first assign to A_reg and B_reg
          out_reg = 31'bx;
          next_flag = 1'b0;
          next_state = IDLE;
        end
        if(act == 1)
          if(A_reg==0) begin
            out_reg = B_reg;
            next_flag = 1'b1; //testbench will know when we stopped
            Aint_reg = A_reg; //taking care not to infer latches
            Bint_reg = B_reg;
            next_state = IDLE;
          end
          else if (B_reg==0) begin
            out_reg = A_reg;
            next_flag = 1'b1;
            Aint_reg = A_reg; //taking care not to infer latches
            Bint_reg = B_reg;
            next_state = IDLE;
          end
          else if (A_reg >= B_reg) begin
            out_reg = 31'bx;
            next_flag = 1'b0;
            Aint_reg = A_reg;
            Bint_reg = B_reg;
            next_state = ABIG;
          end
          else begin
            out_reg = 4'bxxx;
            next_flag = 1'b0;
            Aint_reg = A_reg;
            Bint_reg = B_reg;
            next_state = BBIG;
         end
       else
        begin
         Aint_reg = A_reg;
         Bint_reg = B_reg;
         out_reg = 4'bxxx;
         next_flag = 1'b0;
         next_state = 4'bx;
        end
     end

     ABIG: begin
       if (A_reg==0 | B_reg==0) begin
         out_reg = 31'bx;
         next_flag = 1'b0;
         next_state = IDLE;
         Aint_reg = A_reg;
         Bint_reg = B_reg;
       end
       else if (B_reg > A_reg) begin
         out_reg = 31'bx;
         next_flag = 1'b0;
         next_state = BBIG;
         Aint_reg = A_reg;
         Bint_reg = B_reg;
       end
       else begin
         out_reg = 31'bx;
         next_flag = 1'b0;
         next_state = ABIG;
         Aint_reg = A_reg - B_reg;
         Bint_reg = B_reg;
       end
     end

     BBIG: begin
       if (A_reg==0 | B_reg==0) begin
         out_reg = 31'bx;
         next_flag = 1'b0;
         next_state = IDLE;
         Aint_reg = A_reg;
         Bint_reg = B_reg;
       end
       else if (A_reg > B_reg) begin
         out_reg = 31'bx;
         next_flag = 1'b0;
         next_state = ABIG;
         Aint_reg = A_reg;
         Bint_reg = B_reg;
       end
       else begin
         out_reg = 31'bx;
         next_flag = 1'b0;
         next_state = BBIG;
         Aint_reg = A_reg;
         Bint_reg = B_reg - A_reg;
       end
     end

     default: begin
       out_reg = 31'bx;
       next_flag = 1'b0;
       next_state = 4'bx;
       Aint_reg = A_reg;
       Bint_reg = B_reg;
       $display("%t: State machine not initialized/n",$time);
     end
   endcase

 always @(posedge clk or negedge nrst)
   if (~nrst) begin
     state <=  IDLE;//we get the new values by resetting first
     out <= 4'bx;//we don't want anything there at the reset
     fla_g <= 1'b0;
   end
   else begin
     state <=  next_state;//otherwise, get the next state and the next registers to the intermediate ones
     A_reg <=  Aint_reg;// 2nd assign to A_reg and B_reg- that's the problem
     B_reg <=  Bint_reg;
     out <=  out_reg;
     fla_g <= next_flag;
   end

endmodule

first, A and B are wires that will receive a list of numbers to compare via external source(some textfile in a testbench).

A_reg and B_reg are the intermediate registers that keep the numbers that we are checking the "if" statements on,

Aint_reg and Bint_reg are registers that keep the intermediate values of registers after the operations only to send them back to A_reg and B_reg when the clock is rising,

act decides whether the machine is on "on" mode and can perform the algorithm

nrst is the negative reset toggle

how was the problem formed:

you can see that at the beginning, there is an if(act == 0) condition. It was put there to ensure that the values at the A,B wires(received externally) will enter the registers there, instead of entering them in the sequential block while we were on the if(~nrst) condition since it made no sense entering a dynamic value while in reset.

This takes us to the current problem- I know that assigning a value to A and B both in the sequential and combinatoric blocks is what creates the problem, but I just can't find an alternative.

p.s. the fact that I'm using A_reg = A creates latches since I don't assign to A_reg anywhere else, and that's another problem since writing

Aint_reg = A_reg;
 A_reg = Aint_reg;

to satisfy latches doesn't sit right with me.

p.s.2. I tried looking into the similar questions on the site, but owing to my lack of enough knowledge on the subject I couldn't relate my problem to the ones out there

I'll be glad to receive any help, thanks

EDIT: I deleted the nonblocking assignments in the if(~nrst) sequential block so as to not to multiple assign A_reg <= 0 there and A_reg = A in the combinatoric block, but the multiple assignment problem still bugs it somehow

EDIT2: seems that I forgot a fundamental thing- don't assign to the same variable in two different "always" block, but I just can't think of a good enough solution to assign the wires A,B to a register and not assign to it again in the sequential block

Body:
You are correct in identifying the major problem in your code is that you are not handling registers and combinational logic correctly. Whenever you have a register (register, not reg type, they are not the same and it is confusing for those new to Verilog), you need to define it in a particular way so synthesis and simulation tools can handle it. The safest practice is to create a clean separation between combinational logic and sequential storage (ie, actual registers). You started to do this with Aint_reg, Bint_reg, out_reg, etc; but you need to do it for all registered values whose values come from conbinational blocks. So, all these ideas together yields a struct for code like this (not completely your code but something similar):

input [31:0] A, B;
output reg [31:0] out;

reg [31:0] regA, regB;
reg [3:0] state, nextState;

always @(posedge clk or negedge rst) begin
  if (~rst) begin
    regA <= '0;
    regB <= '0;
    state <= IDLE;
  end
  else begin
    regA <= nextA;
    regB <= nextB;
    state <= nextState;
  end
end

always @(*) begin
  // Default; I always do this here to ensure there are no cases in which I dont assign a combinational value for this block
  // it always helps me keep track of which variables are assigned in which block
  nextA = regA;
  nextB = regB;
  nextState = state;

  out = '0;

  case (state)
    // In here is your case body, where you can reassign nextA, nextB, nextState and out
    // where the assignments are only dependent on A, B, regA, regB and state (ie, the values NOT assigned in this block)
  endcase
end

With this in mind, you need to have only the Aint_reg, Bint_reg, etc in the combinational block; so you dont need to assign A_reg, Breg, etc in the combinational block. Note also that if this will mean the timing of out will be delayed, so you can always bypass the register if you need to push a value out from a combination block immediately. From what I understand, you might be having issues with loading during a reset, which is understandable as so long as reset (nrst) is asserted (ie, 0), nothing will load. That is the entire point of a reset, to hold the system in a known state until it is lifted. So until nrst is deasserted, your module shouldnt do anything. A few other points:

Formating your code correctly is very important, make sure your code is always clean as it helps spot bugs. I reformatted it and there seems to be a missing begin..end in the last block of the IDLE state

Always begin..end your blocks, it will avoid so many bugs

Watch out for the size of things, I see you declared your variables to be 32 bits reg [31:0] but are only assigning them using 31'd which is 31 bits. Use '0 syntax to zero fill for any size.

Setting registers to 'x is not ideal, you should have registers just retain their state (as you do thing for register values and next register values).

Hope this clarifies things for you.


问:
batch - Why does successful dir statement print File Not Found?
Recently, I made a small batch file to list all of the files in a given directory.  When I run the file, it successfully makes a txt of all of the files.  However, if I run it from the command prompt, it also prints File Not Found.

```<code>dir ".\builds\dev-versions" /b /o:d *.jar > devFiles.txt
</code>```

What is causing this to happen?

答:
Your dir command should be running twice - once for each of the arguments ".\builds\dev-versions" and *.jar

. means "the current directory" so it should list both the nominated directory, and all of the .jar files in the current directory. If either list is empty, you'll get the file nor found error.

Since you don't tell us what the code is attempting to do, we are limited in suggesting a remedy. Appending 2>nul may assist by discarding the error report.

Body:
Recently, I made a small batch file to list all of the files in a given directory.  When I run the file, it successfully makes a txt of all of the files.  However, if I run it from the command prompt, it also prints File Not Found.

dir ".\builds\dev-versions" /b /o:d *.jar > devFiles.txt

What is causing this to happen?