问:
Unrecognized selector sent to instance with Timer
Im making a game with spritekit and would like to check for some updates in variables each second (instead of using the update method which checks too often).
I created a scheduledTimer that has a selector of the function that I want to run, but it gives me the error: Unrecognized selector sent to instance.

I understand that the function probably needs the correct sender, but what is it? Thank you

```<code>var timer = Timer.scheduledTimer(timeInterval: 1,
                                       target: self,
                                     selector: #selector(GameScene.updateEachSecond),
                                     userInfo: nil,
                                      repeats: true)

func updateEachSecond() {
   print("1 second has passed")
}
</code>```

答:
You need to declare your timer

```<code>var timer = Timer()
</code>```

as a property of your GameScene

and move your timer initialization to didMove(to: or any other method that runs after your scene has finished loading.

```<code>override func didMove(to view: SKView) {
    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateEachSecond), userInfo: nil, repeats: true)
}
</code>```

Another option as suggested in comments is to check in your update method if the second changed:

```<code>var timeInterval: TimeInterval = 0
var time = 0

override func update(_ currentTime: TimeInterval) {
    if timeInterval < currentTime.rounded(.down) {
        time += 1
        timeInterval = currentTime
        updateEachSecond()
    }
}

func updateEachSecond() {
    print("Time:", time, terminator: "s\n")
}
</code>```

Body:
Im making a game with spritekit and would like to check for some updates in variables each second (instead of using the update method which checks too often).
I created a scheduledTimer that has a selector of the function that I want to run, but it gives me the error: Unrecognized selector sent to instance.

I understand that the function probably needs the correct sender, but what is it? Thank you

var timer = Timer.scheduledTimer(timeInterval: 1,
                                       target: self,
                                     selector: #selector(GameScene.updateEachSecond),
                                     userInfo: nil,
                                      repeats: true)

func updateEachSecond() {
   print("1 second has passed")
}

Body:
You need to declare your timer

var timer = Timer()

as a property of your GameScene

and move your timer initialization to didMove(to: or any other method that runs after your scene has finished loading.

override func didMove(to view: SKView) {
    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateEachSecond), userInfo: nil, repeats: true)
}

Another option as suggested in comments is to check in your update method if the second changed:

var timeInterval: TimeInterval = 0
var time = 0

override func update(_ currentTime: TimeInterval) {
    if timeInterval < currentTime.rounded(.down) {
        time += 1
        timeInterval = currentTime
        updateEachSecond()
    }
}

func updateEachSecond() {
    print("Time:", time, terminator: "s\n")
}


来源: stackexchange

问:
Observable and Angular2
I have an issue with Observables in Angular 2

My component calls service function on Init like below:

```<code>delivery: IDeliveryCountry[];

ngOnInit() {
  this.checkoutService._getInfo().subscribe(dev => this.delivery = dev);
}
</code>```

This is how interface looks like IDeliveryCountry:

```<code>export interface IDeliveryCountry {
  iso: string;
  name: string;
}
</code>```

This is how Service looks like:

```<code>_getInfo(): Observable<IDeliveryCountry[]> {
    return this.http.get(this.deliveryCountryUrl)
    .map((response: Response) => <IDeliveryCountry[]>response.json())
}
</code>```

json file with data looks like this:

```<code>[
  {
    "iso":"se",
    "name":"Sweden"
  },
  {
    "iso":"dk",
    "name":"Denmark"
  }
]
</code>```

My html file is just a simple ngFor loop:

```<code><div *ngFor='let dev of delivery'>{{dev.iso}}</div>
</code>```

So far all things works perfect, as expected I get back "se" and "dk" in UI.

The problem appears when I change a structure of data in my json file to following:

```<code>{
  "country": {
    "iso":"se",
    "name":"Sweden"
  }
}
</code>```

I want data to only have one country with iso and name property for it. So my html file looks like following:

```<code><div>{{delivery.iso}}</div>
</code>```

But I am getting iso as undefined all the time

" Cannot read property 'iso' of undefined "

Thank you!

答:
Alternatively you could change your service to return the DeliveryCountry[]

```<code>getInfo(): Observable<IDeliveryCountry[]> {
  return this.http.get(this.deliveryCountryUrl)
  .map((response: Response) => response.json())
  .map(delivery => delivery.country);
}
</code>```

Then:

```<code>ngOnInit() {
  this.checkoutService.getInfo()
  .subscribe(deliveryCountries => this.deliveryCountries = deliveryCountries);
}
</code>```

Then:

```<code><div *ngFor="let deliveryCountry of deliveryCountries">{{deliveryCountry?.iso}}</div>
</code>```

ContentLicense: CC BY-SA 3.0

Title: Observable and Angular2

Body:
I have an issue with Observables in Angular 2

My component calls service function on Init like below:

delivery: IDeliveryCountry[];

ngOnInit() {
  this.checkoutService._getInfo().subscribe(dev => this.delivery = dev);
}

This is how interface looks like IDeliveryCountry:

export interface IDeliveryCountry {
  iso: string;
  name: string;
}

This is how Service looks like:

_getInfo(): Observable<IDeliveryCountry[]> {
    return this.http.get(this.deliveryCountryUrl)
    .map((response: Response) => <IDeliveryCountry[]>response.json())
}

json file with data looks like this:

[
  {
    "iso":"se",
    "name":"Sweden"
  },
  {
    "iso":"dk",
    "name":"Denmark"
  }
]

My html file is just a simple ngFor loop:

{{dev.iso}}

So far all things works perfect, as expected I get back "se" and "dk" in UI.

The problem appears when I change a structure of data in my json file to following:

{
  "country": {
    "iso":"se",
    "name":"Sweden"
  }
}

I want data to only have one country with iso and name property for it. So my html file looks like following:

{{delivery.iso}}

But I am getting iso as undefined all the time

" Cannot read property 'iso' of undefined "

Thank you!

Body:
Alternatively you could change your service to return the DeliveryCountry[]

getInfo(): Observable<IDeliveryCountry[]> {
  return this.http.get(this.deliveryCountryUrl)
  .map((response: Response) => response.json())
  .map(delivery => delivery.country);
}

Then:

ngOnInit() {
  this.checkoutService.getInfo()
  .subscribe(deliveryCountries => this.deliveryCountries = deliveryCountries);
}

Then:

<div *ngFor="let deliveryCountry of deliveryCountries">{{deliveryCountry?.iso}}</div>


问:
vim do not fold everything on first fold
When I close the first fold in a buffer (zc in normal mode), all the folds are automatically closed. Is there a way to just close the given fold without closing the rest?

I have foldmethod=syntax. Observed with python but probably this applies to other languages.

Example python file

zc on method a()

As you can see, all methods: a, b, c are folded. Desired behaviour is for only method a to be folded, as shown below:

This only happens on the first time a fold is closed in a buffer. After re-opening all the folds, zc will only close the proper fold.

EDIT: I believe this has to do with SimpylFold plugin. I have set nofoldenable by default. When I zc, it looks like SimpylFold sets foldenable, which automatically folds all the methods.

答:
The cause was a weird interaction with nofoldenable and the plugin SimpylFold. I set nofoldenable by default. If you have foldenable, unless you add additional commands all your folds are closed by default.

Now when using the SimpylFold plugin, zc on first use also sets foldenable, which will close all folds.

The solution is to add something like this to your ~/.vimrc

```<code>autocmd FileType python setlocal foldenable foldlevel=20
</code>```

This enables folding locally for python files while leaving the folds open on buffer open. Then zc behaves normally.

Body:
The cause was a weird interaction with nofoldenable and the plugin SimpylFold. I set nofoldenable by default. If you have foldenable, unless you add additional commands all your folds are closed by default.

Now when using the SimpylFold plugin, zc on first use also sets foldenable, which will close all folds.

The solution is to add something like this to your ~/.vimrc

autocmd FileType python setlocal foldenable foldlevel=20

This enables folding locally for python files while leaving the folds open on buffer open. Then zc behaves normally.


问:
Intent in Android developer
I have two "Intent" from different Activity?

```<code>protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_padres);

    TextView mTextViewNom = (TextView) findViewById(R.id.textNew2);
    TextView mTextViewAp = (TextView) findViewById(R.id.textNew3);
    Intent intent = getIntent();

    String usuario = intent.getStringExtra("Usuario");
    mTextViewNom.setText(usuario);
    String apellido = intent.getStringExtra("Apellidos");
    mTextViewAp.setText(apellido);

    TextView mTextViewMedia = (TextView) findViewById(R.id.textNew4);
    int mediaObtenida = 0;

    Intent intent2 = getIntent();
    int media = intent2.getIntExtra("Media", mediaObtenida);
    mTextViewMedia.setText(String.valueOf(media));

}
</code>```

How I can specify URI in getIntent();???

答:
Store your URI as a string
intent.putExtra("MyURI".toString());
Then just corvert it again
Uri testURI = Uri.parse(extras.getString("MyURI"));

Title: Intent in Android developer

Body:
I have two "Intent" from different Activity?

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_padres);

    TextView mTextViewNom = (TextView) findViewById(R.id.textNew2);
    TextView mTextViewAp = (TextView) findViewById(R.id.textNew3);
    Intent intent = getIntent();

    String usuario = intent.getStringExtra("Usuario");
    mTextViewNom.setText(usuario);
    String apellido = intent.getStringExtra("Apellidos");
    mTextViewAp.setText(apellido);

    TextView mTextViewMedia = (TextView) findViewById(R.id.textNew4);
    int mediaObtenida = 0;

    Intent intent2 = getIntent();
    int media = intent2.getIntExtra("Media", mediaObtenida);
    mTextViewMedia.setText(String.valueOf(media));

}

How I can specify URI in getIntent();???


问:
GIT clone branch to older commit in another directory
I have 2 directories of the same project, let call them directories A and B.

These two folder were cloned from a master git repo in another location, so they both started out with the same git repo commit.

Now A stayed with the original code and fixed a few minor bugs, and commited the changes, so A git branch looks like this:

```<code>A: (original)-(bug fix 1) - (bug fix 2) - (bug fix 3)
</code>```

While B, I decided to change the look of the application but I havent commited yet. so B git branch looks like this:

```<code>B: (original)
</code>```

What I would like to do is merge these 2 git repos from the original clone so I can have the following:

```<code>A: (original)-(bug fix 1) - (bug fix 2) - (bug fix 3)--------(merge both)

           \                                                    /
branch B:   \ -----------------(New version look) -------------
</code>```

答:
If you can push back to that repo, but you don't want to push B, you can:

go to your A local clone

add the B local clone as a remote:

```<code>git remote add repoB ../B
</code>```

fetch and merge:

```<code>git fetch repoB
git checkout A
git merge repoB/B
</code>```

Body:
I have 2 directories of the same project, let call them directories A and B.

These two folder were cloned from a master git repo in another location, so they both started out with the same git repo commit.

Now A stayed with the original code and fixed a few minor bugs, and commited the changes, so A git branch looks like this:

A: (original)-(bug fix 1) - (bug fix 2) - (bug fix 3)

While B, I decided to change the look of the application but I havent commited yet. so B git branch looks like this:

B: (original)

What I would like to do is merge these 2 git repos from the original clone so I can have the following:

A: (original)-(bug fix 1) - (bug fix 2) - (bug fix 3)--------(merge both)

           \                                                    /
branch B:   \ -----------------(New version look) -------------

Body:
If you can push back to that repo, but you don't want to push B, you can:

go to your A local clone

add the B local clone as a remote:

git remote add repoB ../B

fetch and merge:

git fetch repoB
git checkout A
git merge repoB/B


问:
Desynchonization between realm collection notification and collection view count
I'm using Realm in my project to write realtime data coming from an API and populating a UICollectionView in the same time. To achieve that I've been using Realm's Collection Notification (https://realm.io/docs/swift/latest/#collection-notifications) to observe insertions. The problem I'm having is that I always get the following error when I'm using more than one section in the collection view:

Terminating app due to uncaught exception
  'NSInternalInconsistencyException', reason: 'Invalid update: invalid
  number of items in section 2.  The number of items contained in an
  existing section after the update (4) must be equal to the number of
  items contained in that section before the update (3), plus or minus
  the number of items inserted or deleted from that section (0 inserted,
  0 deleted) and plus or minus the number of items moved into or out of
  that section (0 moved in, 0 moved out).'

I have 3 sections in the collection view that I need to refresh each time I receive a new item from the API. It works perfectly when I have 1 section but result in a crash when I have 3 sections. To do so, I have an array of NotificationToken and I observe new insertions as such:

 internal func observeResults(results: Results<SJResult>, section: Int) {
      notificationTokens.append(results.addNotificationBlock { [weak self] (changes: RealmCollectionChange) in
        switch changes {
          case .initial:
            collectionView.reloadData()
            break
          case .update(_, let deletions, let insertions, let modifications):
            collectionView.performBatchUpdates({
              collectionView.insertItems(at: insertions.map { IndexPath(row: $0, section: section) })
              collectionView.deleteItems(at: deletions.map { IndexPath(row: $0, section: section) })
              collectionView.reloadItems(at: modifications.map { IndexPath(row: $0, section: section) })
            })
            break
          case .error(let error):
            fatalError("\(error)")
            break
        }
      })
    }
```

<p>I'm writing the result in a background queue like that:</p>

<pre class="lang-c prettyprint-override"><code>DispatchQueue.global(qos: .background).async { [weak self] in
  for (index, group) in groups.enumerated() {
    let result = Item(group: group)

    if let realm = try? Realm() {
      do {
        try realm.write {
          realm.add(result)
        }
      } catch let exception {
        print("Can't write result: \(exception)")
      }
    }
  }
}
</code>```

And that's how I specify the number of items in each section:

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return results(leg: section).count // Query the table to get the results I want to display
}
```

It seems that when the collection view is inserting new elements (in collectionView.performBatchUpdates), there is new item that are sometimes written on the database realm.add(result) in the same time, which result in a crash as the total number of items has changed between the start and the end of the update. I managed to avoid the crash by writing synchronously DispatchQueue.global(qos: .background).sync, which lead to some performance issues. I really would like to write any new item asynchronously but I can't figure out why it crashes. Does anyone has an idea of what's going on and how I can improve that please?

答:
I'm struggling with the same problem right now. My latest theory to explain why it works perfectly fine with one section and starts crashing with more then one section is as follows:
The collection view checks for the number of items in the sections at the beginning of the animations and again at the end to catch consistency errors. As long as you have one section, changes to the results will generate sequences of notifications, each starting a new performBatchUpdates that will keep everything perfectly synced.
When you have more than one section, with their own notifications attached to different results, you start having interleaved sequences of notifications that start their own performBatchUpdates, and more importantly check the counts of all the sections at the end of each animation.
That is probably why you and me are having these problems. We have individual notifications per section, but their work affects the whole collection view sections, including previously started in flight animations and their end-of-flight checks. I do not have a solution for this problem yet.</p>

Body:
I'm using Realm in my project to write realtime data coming from an API and populating a UICollectionView in the same time. To achieve that I've been using Realm's Collection Notification (https://realm.io/docs/swift/latest/#collection-notifications) to observe insertions. The problem I'm having is that I always get the following error when I'm using more than one section in the collection view:

Terminating app due to uncaught exception
  'NSInternalInconsistencyException', reason: 'Invalid update: invalid
  number of items in section 2.  The number of items contained in an
  existing section after the update (4) must be equal to the number of
  items contained in that section before the update (3), plus or minus
  the number of items inserted or deleted from that section (0 inserted,
  0 deleted) and plus or minus the number of items moved into or out of
  that section (0 moved in, 0 moved out).'

I have 3 sections in the collection view that I need to refresh each time I receive a new item from the API. It works perfectly when I have 1 section but result in a crash when I have 3 sections. To do so, I have an array of NotificationToken and I observe new insertions as such:

 internal func observeResults(results: Results<SJResult>, section: Int) {
      notificationTokens.append(results.addNotificationBlock { [weak self] (changes: RealmCollectionChange) in
        switch changes {
          case .initial:
            collectionView.reloadData()
            break
          case .update(_, let deletions, let insertions, let modifications):
            collectionView.performBatchUpdates({
              collectionView.insertItems(at: insertions.map { IndexPath(row: $0, section: section) })
              collectionView.deleteItems(at: deletions.map { IndexPath(row: $0, section: section) })
              collectionView.reloadItems(at: modifications.map { IndexPath(row: $0, section: section) })
            })
            break
          case .error(let error):
            fatalError("\(error)")
            break
        }
      })
    }

I'm writing the result in a background queue like that:

DispatchQueue.global(qos: .background).async { [weak self] in
  for (index, group) in groups.enumerated() {
    let result = Item(group: group)

    if let realm = try? Realm() {
      do {
        try realm.write {
          realm.add(result)
        }
      } catch let exception {
        print("Can't write result: \(exception)")
      }
    }
  }
}

And that's how I specify the number of items in each section:

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return results(leg: section).count // Query the table to get the results I want to display
}

It seems that when the collection view is inserting new elements (in collectionView.performBatchUpdates), there is new item that are sometimes written on the database realm.add(result) in the same time, which result in a crash as the total number of items has changed between the start and the end of the update. I managed to avoid the crash by writing synchronously DispatchQueue.global(qos: .background).sync, which lead to some performance issues. I really would like to write any new item asynchronously but I can't figure out why it crashes. Does anyone has an idea of what's going on and how I can improve that please?


问:
HTML5 - vertical layout: flexible height + fill the rest
I have a dreaded height problem in html, IE9 and above, avoiding flex-box:

I have header of one to three lines heigth (highly depends)

the vertical rest of the page shall be filled a section. With scrollbars to that section, in case it's contents grow to long.

In simplied stylus syntax, or as a full codepen:

```<code>html, body, header, section
  padding 0
  margin 0
  font-size 40px
  box-sizing border-box

html
  background #f99
  height 100%

body
  background #9f9
  border 4px solid green
  height 100%

header
  border 4px solid darkred

section
  background #99f
  overflow auto
</code>```

If the header height was known, life would be easy. I could easily resort to „corner pinning“:

```<code>  position absolute
  top 100px
  bottom 0
</code>```

(Or have a fat top padding, and place the header above that, etc, etc...)

But sadly: its height varies. Any suggestions other than a vertical flexbox?

— looks like I need a corner pin with a little help from javascript regarding the top attribute?

答:
As IE9 support viewport units vh, you could do like this, without script, and an extra wrapper.

With this you get a dynamic header and a section that fills the remain viewport, and scroll when there is much content.

Fiddle demo

Stack snippet

html, body, .container {
  margin: 0;
  height: 100%;
}
* {
  box-sizing: border-box;
}
.container {
  border: 4px solid green;
}
.wrapper {
  position: relative;
}
header {
  font-size: 40px;
  background: lightgray;
  border: 4px solid darkred;
}
section {
  position: absolute;
  left: 0; right: 0;
  top: 100%;
  height: calc(100vh - 100% - 8px);  /* the 8px (2 * 4px) is for the container's border */
  background: lightblue;
  font-size: 40px;
  overflow: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="wrapper">
    <header>
      A fancy header
      <br> line two
    </header>
    <section>
      could be a lot of text
      <br> could be a lot of text
      <br> could be a lot of text
      <br> could be a lot of text
      <br> could be a lot of text
      <br> could be a lot of text
      <br> could be a lot of text
      <br> could be a lot of text
      <br> could be a lot of text
      <br> could be a lot of text
      <br> could be a lot of text
      <br> could be a lot of text
      <br> could be a lot of text
      <br> could be a lot of text
      <br> could be a lot of text
      <br> could be a lot of text
      <br> could be a lot of text
      <br> could be a lot of text
      <br> could be a lot of text
      <br> could be a lot of text
      <br> could be a lot of text
    </section>
  </div>
</div></code>```

Body:
I have a dreaded height problem in html, IE9 and above, avoiding flex-box:

I have header of one to three lines heigth (highly depends)

the vertical rest of the page shall be filled a section. With scrollbars to that section, in case it's contents grow to long.

In simplied stylus syntax, or as a full codepen:

html, body, header, section
  padding 0
  margin 0
  font-size 40px
  box-sizing border-box

html
  background #f99
  height 100%

body
  background #9f9
  border 4px solid green
  height 100%

header
  border 4px solid darkred

section
  background #99f
  overflow auto

If the header height was known, life would be easy. I could easily resort to „corner pinning“:

  position absolute
  top 100px
  bottom 0

(Or have a fat top padding, and place the header above that, etc, etc...)

But sadly: its height varies. Any suggestions other than a vertical flexbox?

— looks like I need a corner pin with a little help from javascript regarding the top attribute?

Body:
As IE9 support viewport units vh, you could do like this, without script, and an extra wrapper.

With this you get a dynamic header and a section that fills the remain viewport, and scroll when there is much content.

Fiddle demo

Stack snippet

html, body, .container {
  margin: 0;
  height: 100%;
}
* {
  box-sizing: border-box;
}
.container {
  border: 4px solid green;
}
.wrapper {
  position: relative;
}
header {
  font-size: 40px;
  background: lightgray;
  border: 4px solid darkred;
}
section {
  position: absolute;
  left: 0; right: 0;
  top: 100%;
  height: calc(100vh - 100% - 8px);  /* the 8px (2 * 4px) is for the container's border */
  background: lightblue;
  font-size: 40px;
  overflow: auto;
}

<div class="container">
  <div class="wrapper">
    <header>
      A fancy header
      <br> line two
    </header>
    <section>
      could be a lot of text
      <br> could be a lot of text
      <br> could be a lot of text
      <br> could be a lot of text
      <br> could be a lot of text
      <br> could be a lot of text
      <br> could be a lot of text
      <br> could be a lot of text
      <br> could be a lot of text
      <br> could be a lot of text
      <br> could be a lot of text
      <br> could be a lot of text
      <br> could be a lot of text
      <br> could be a lot of text
      <br> could be a lot of text
      <br> could be a lot of text
      <br> could be a lot of text
      <br> could be a lot of text
      <br> could be a lot of text
      <br> could be a lot of text
      <br> could be a lot of text
    </section>
  </div>
</div>


问:
how to prevent overlapping sounds on multiple notifications
In my android app is a very common scenario to receive multiple notifications at the same time.
Each notification can have a custom sound (set by the user) to recognize what type of notification is without looking at the status bar.
The problem is that when multiple notifications are sent at the same time, the sounds overlap themselves and the result is an unpleasant noise besides to completely break the feature to recognize the type of notifications just hearing the sound.

Is there a way to queue the notification sounds? Alternatively, can I send a notification only when another one finished to play his sound?

答:
If you are you using the SoundPool class you can setMaxStreams() to 1 to avoid multiple sounds from playing. Additionally, the Soundpool class allows you to set a priority for each notification sound, so it can know which sound to play when there are multiple sounds trying to play at the same time. Unfortunately, Soundpool does not support queues of any kind.

Alternatively, if you are using MediaPlayer to play sounds, you can use the onCompletionListener. However, it's not recommended to use the MediaPlayer for notification sounds as MediaPlayer was meant to be used for longer audio files.


问:
Filename ending with period and using FileInfo C#
I'm having an issue where a file containing a period at the end of its name cannot be seen by FileInfo. I know that Windows prevents naming files this way, but this data came from a different operating system.

I am able to create a problem file in Windows by using command line:

```<code>echo "test" > "\\?\C:\Test\BadFileName."
</code>```

and this is the code I was using to test the file:

```<code>DateTime origAccessDate;
DateTime OrigCreateDate;
long sizeBytes;

string path = @"\\?\C:\Test\BadFileName.";
FileInfo fi = new FileInfo(path);

try
{
     origAccessDate = fi.LastAccessTime;
     OrigCreateDate = fi.CreationTime;
     sizeBytes = fi.Length;
}
catch (Exception ex)
{
     MessageBox.Show(ex.Message);
}
</code>```

The problem occurs when FileInfo is called on the path. The Exists property is false, even though you can copy/paste the path to confirm it is valid. The goal is not to rename the file in order to read, but to read it in place (as-is).

答:
Method calls:

```<code>        string path = @"C:\Test\BadFileName.";

        DateTime createDate = cmdGetCreateDate(path);
        DateTime accessDate = cmdGetAccessDate(path);
        long bytes = cmdGetSizeBytes(path);
</code>```

Methods:

```<code>    private DateTime cmdGetCreateDate(string path)
    {
        DateTime createDate = new DateTime();
        int lastSlash = path.LastIndexOf(Convert.ToChar("\\"));
        string file = path.Substring(lastSlash + 1);
        string folder = path.Substring(0, lastSlash);

        string cmdexe = @"C:\Windows\System32\cmd.exe";
        string args = @"/c dir /T:C /A:-D """ + folder + "\"";

        Process procCreateDate = new Process
        {
            StartInfo = new ProcessStartInfo
            {
                FileName = cmdexe,
                Arguments = args,
                UseShellExecute = false,
                RedirectStandardOutput = true,
                CreateNoWindow = true
            }
        };

        procCreateDate.Start();
        string output = procCreateDate.StandardOutput.ReadToEnd();

        if (!output.Contains(file))
        {
            return createDate; //File not found
        }

        string p = @"\b\d{2}/\d{2}/\d{4}\b\s+\d{2}:\d{2} ..";
        Regex rx = new Regex(p);
        Match m = rx.Match(output);

        if (m.Success)
        {
            DateTime.TryParse(m.Value, out createDate);
        }

        return createDate;
    }

private DateTime cmdGetAccessDate(string path)
    {
        DateTime accessDate = new DateTime();
        int lastSlash = path.LastIndexOf(Convert.ToChar("\\"));
        string file = path.Substring(lastSlash + 1);
        string folder = path.Substring(0, lastSlash);

        string cmdexe = @"C:\Windows\System32\cmd.exe";
        string args = @"/c dir /T:A /A:-D """ + folder + "\"";

        Process procCreateDate = new Process
        {
            StartInfo = new ProcessStartInfo
            {
                FileName = cmdexe,
                Arguments = args,
                UseShellExecute = false,
                RedirectStandardOutput = true,
                CreateNoWindow = true
            }
        };

        procCreateDate.Start();
        string output = procCreateDate.StandardOutput.ReadToEnd();

        if (!output.Contains(file))
        {
            return accessDate; //File not found
        }

        string p = @"\b\d{2}/\d{2}/\d{4}\b\s+\d{2}:\d{2} ..";
        Regex rx = new Regex(p);
        Match m = rx.Match(output);

        if (m.Success)
        {
            DateTime.TryParse(m.Value, out accessDate);
        }

        return accessDate;
    }

    private long cmdGetSizeBytes(string path)
    {
        long bytes = -1;
        int lastSlash = path.LastIndexOf(Convert.ToChar("\\"));
        string file = path.Substring(lastSlash + 1);
        string folder = path.Substring(0, lastSlash);

        string cmdexe = @"C:\Windows\System32\cmd.exe";
        string args = @"/c dir /A:-D """ + folder + "\"";

        Process procCreateDate = new Process
        {
            StartInfo = new ProcessStartInfo
            {
                FileName = cmdexe,
                Arguments = args,
                UseShellExecute = false,
                RedirectStandardOutput = true,
                CreateNoWindow = true
            }
        };

        procCreateDate.Start();
        string output = procCreateDate.StandardOutput.ReadToEnd();

        if (!output.Contains(file))
        {
            return bytes; //File not found
        }

        string p = @"\d+ " + file;
        Regex rx = new Regex(p);
        Match m = rx.Match(output);

        if (m.Success)
        {
            string[] splitVal = m.Value.Split(Convert.ToChar(" "));
            bytes = Convert.ToInt64(splitVal[0]);
        }

        return bytes;
    }
</code>```

Body:
I'm having an issue where a file containing a period at the end of its name cannot be seen by FileInfo. I know that Windows prevents naming files this way, but this data came from a different operating system.

I am able to create a problem file in Windows by using command line:

echo "test" > "\\?\C:\Test\BadFileName."

and this is the code I was using to test the file:

DateTime origAccessDate;
DateTime OrigCreateDate;
long sizeBytes;

string path = @"\\?\C:\Test\BadFileName.";
FileInfo fi = new FileInfo(path);

try
{
     origAccessDate = fi.LastAccessTime;
     OrigCreateDate = fi.CreationTime;
     sizeBytes = fi.Length;
}
catch (Exception ex)
{
     MessageBox.Show(ex.Message);
}

The problem occurs when FileInfo is called on the path. The Exists property is false, even though you can copy/paste the path to confirm it is valid. The goal is not to rename the file in order to read, but to read it in place (as-is).

Body:
Method calls:

        string path = @"C:\Test\BadFileName.";

        DateTime createDate = cmdGetCreateDate(path);
        DateTime accessDate = cmdGetAccessDate(path);
        long bytes = cmdGetSizeBytes(path);

Methods:

    private DateTime cmdGetCreateDate(string path)
    {
        DateTime createDate = new DateTime();
        int lastSlash = path.LastIndexOf(Convert.ToChar("\\"));
        string file = path.Substring(lastSlash + 1);
        string folder = path.Substring(0, lastSlash);

        string cmdexe = @"C:\Windows\System32\cmd.exe";
        string args = @"/c dir /T:C /A:-D """ + folder + "\"";

        Process procCreateDate = new Process
        {
            StartInfo = new ProcessStartInfo
            {
                FileName = cmdexe,
                Arguments = args,
                UseShellExecute = false,
                RedirectStandardOutput = true,
                CreateNoWindow = true
            }
        };

        procCreateDate.Start();
        string output = procCreateDate.StandardOutput.ReadToEnd();

        if (!output.Contains(file))
        {
            return createDate; //File not found
        }

        string p = @"\b\d{2}/\d{2}/\d{4}\b\s+\d{2}:\d{2} ..";
        Regex rx = new Regex(p);
        Match m = rx.Match(output);

        if (m.Success)
        {
            DateTime.TryParse(m.Value, out createDate);
        }

        return createDate;
    }

private DateTime cmdGetAccessDate(string path)
    {
        DateTime accessDate = new DateTime();
        int lastSlash = path.LastIndexOf(Convert.ToChar("\\"));
        string file = path.Substring(lastSlash + 1);
        string folder = path.Substring(0, lastSlash);

        string cmdexe = @"C:\Windows\System32\cmd.exe";
        string args = @"/c dir /T:A /A:-D """ + folder + "\"";

        Process procCreateDate = new Process
        {
            StartInfo = new ProcessStartInfo
            {
                FileName = cmdexe,
                Arguments = args,
                UseShellExecute = false,
                RedirectStandardOutput = true,
                CreateNoWindow = true
            }
        };

        procCreateDate.Start();
        string output = procCreateDate.StandardOutput.ReadToEnd();

        if (!output.Contains(file))
        {
            return accessDate; //File not found
        }

        string p = @"\b\d{2}/\d{2}/\d{4}\b\s+\d{2}:\d{2} ..";
        Regex rx = new Regex(p);
        Match m = rx.Match(output);

        if (m.Success)
        {
            DateTime.TryParse(m.Value, out accessDate);
        }

        return accessDate;
    }

    private long cmdGetSizeBytes(string path)
    {
        long bytes = -1;
        int lastSlash = path.LastIndexOf(Convert.ToChar("\\"));
        string file = path.Substring(lastSlash + 1);
        string folder = path.Substring(0, lastSlash);

        string cmdexe = @"C:\Windows\System32\cmd.exe";
        string args = @"/c dir /A:-D """ + folder + "\"";

        Process procCreateDate = new Process
        {
            StartInfo = new ProcessStartInfo
            {
                FileName = cmdexe,
                Arguments = args,
                UseShellExecute = false,
                RedirectStandardOutput = true,
                CreateNoWindow = true
            }
        };

        procCreateDate.Start();
        string output = procCreateDate.StandardOutput.ReadToEnd();

        if (!output.Contains(file))
        {
            return bytes; //File not found
        }

        string p = @"\d+ " + file;
        Regex rx = new Regex(p);
        Match m = rx.Match(output);

        if (m.Success)
        {
            string[] splitVal = m.Value.Split(Convert.ToChar(" "));
            bytes = Convert.ToInt64(splitVal[0]);
        }

        return bytes;
    }


问:
how to create a device specific app in objective c
I want to create an app which is specific to the device type.Say my app should work only on  iPhone but not on iPad or iPod even if it (the app) has common features.</p>

答: If your application is for App Store distribution you may be able to use the UIRequiredDeviceCapabilities key of Info.plist to produce a sufficiently restrictive set of requirements. Make this entry a dictionary and then for example setting a telephony=false value would exclude phone devices, still-camera=false value would exclude (current) iPads etc.  The iTunes/App Store will then not allow a user to install the app on an unsupported device

ContentLicense: CC BY-SA 2.5


问:
MYSQL delete all records except first and last for a given date
This gives me all the records for a particular switch and port. I would like to delete all except the first and last one for each day.</p>

```<code>/mysql -sN --user=root --password=notmypassword -e
"SELECT * FROM collector.fibre
WHERE fabric_switch_name = 'switch-1'
  AND port = '0'
  AND datatype = 'TxElements'
  AND (time > '2016-05-31 00:00:00' AND time < '2016-05-31 23:59:59') "
</code>```

答:
by "first and last" I will assume you mean earliest and latest, so:

Select criteria in the given date and then deselect the minimum date and maximum date values.

It is assumed your time is stored in a DATETIME column.

```<code>    DELETE FROM collector.fibre
         WHERE fabric_switch_name = 'switch-1'
         AND port = '0'
         AND datatype = 'TxElements'
         AND (TIME(time) !=
             (
             SELECT MAX(TIME(time))
             FROM `collector`.`fibre` WHERE fabric_switch_name = 'switch-1'
             AND port = '0'
             AND datatype = 'TxElements'
             AND DATE(time) = '2016-05-30'
             )
             AND
             TIME(time) != (
             SELECT MIN(TIME(time))
             FROM `collector`.`fibre` WHERE fabric_switch_name = 'switch-1'
             AND port = '0'
             AND datatype = 'TxElements'
             AND DATE(time) = '2016-05-30'
             )
         )
         AND DATE(time) = '2016-05-30'
</code>```

This is probably poorly written and does unfortunately use criteria repetition for the subqueries but the concept works as:

SubSelect by criteria and Not rows where the time column is MAX or MIN time values fitting said criteria

Reference : https://stackoverflow.com/a/7836444/3536236

So you can then input each day and remove non-earliest and non-latest values. If you want to cycle through the whole table in one fell swoop I would figure you want to create a Procedure but I don't know enough to help you much here. However your title says MYSQL delete all records except first and last for a given date which implies you will manually run it one date at a time as needed.

Example:

Example Set:

```<code>   fabric_switch_name |   datatype  |  port  |        time
 -------------------------------------------------------------------
       switch-1       |  TxElements |    2   |  2016-05-31 15:00:00
       switch-1       |  TxElements |    1   |  2016-05-30 22:10:00
       switch-2       |  TxElements |    0   |  2016-05-30 15:00:00
       switch-1       |  TxElements |    0   |  2016-05-29 10:20:10
       switch-1       |  TxElements |    0   |  2016-05-29 05:50:00
       switch-1       |  TxElements |    0   |  2016-05-29 19:50:00
       switch-1       |  TxElements |    5   |  2016-05-29 21:50:00
       switch-1       |  TxElements |    0   |  2016-05-29 20:11:40
</code>```

Result Set:

```<code>   fabric_switch_name |   datatype  |  port  |        time
 -------------------------------------------------------------------
       switch-1       |  TxElements |    2   |  2016-05-31 15:00:00
       switch-1       |  TxElements |    1   |  2016-05-30 22:10:00
       switch-1       |  TxElements |    0   |  2016-05-29 05:50:00
       switch-2       |  TxElements |    0   |  2016-05-30 15:00:00
       switch-1       |  TxElements |    5   |  2016-05-29 21:50:00
       switch-1       |  TxElements |    0   |  2016-05-29 20:11:40
</code>```

Body:
This gives me all the records for a particular switch and port. I would like to delete all except the first and last one for each day.

/mysql -sN --user=root --password=notmypassword -e
"SELECT * FROM collector.fibre
WHERE fabric_switch_name = 'switch-1'
  AND port = '0'
  AND datatype = 'TxElements'
  AND (time > '2016-05-31 00:00:00' AND time < '2016-05-31 23:59:59') "

Body:
by "first and last" I will assume you mean earliest and latest, so:

Select criteria in the given date and then deselect the minimum date and maximum date values.

It is assumed your time is stored in a DATETIME column.

    DELETE FROM collector.fibre
         WHERE fabric_switch_name = 'switch-1'
         AND port = '0'
         AND datatype = 'TxElements'
         AND (TIME(time) !=
             (
             SELECT MAX(TIME(time))
             FROM `collector`.`fibre` WHERE fabric_switch_name = 'switch-1'
             AND port = '0'
             AND datatype = 'TxElements'
             AND DATE(time) = '2016-05-30'
             )
             AND
             TIME(time) != (
             SELECT MIN(TIME(time))
             FROM `collector`.`fibre` WHERE fabric_switch_name = 'switch-1'
             AND port = '0'
             AND datatype = 'TxElements'
             AND DATE(time) = '2016-05-30'
             )
         )
         AND DATE(time) = '2016-05-30'

This is probably poorly written and does unfortunately use criteria repetition for the subqueries but the concept works as:

SubSelect by criteria and Not rows where the time column is MAX or MIN time values fitting said criteria

Reference : https://stackoverflow.com/a/7836444/3536236

So you can then input each day and remove non-earliest and non-latest values. If you want to cycle through the whole table in one fell swoop I would figure you want to create a Procedure but I don't know enough to help you much here. However your title says MYSQL delete all records except first and last for a given date which implies you will manually run it one date at a time as needed.

Example:

Example Set:

   fabric_switch_name |   datatype  |  port  |        time
 -------------------------------------------------------------------
       switch-1       |  TxElements |    2   |  2016-05-31 15:00:00
       switch-1       |  TxElements |    1   |  2016-05-30 22:10:00
       switch-2       |  TxElements |    0   |  2016-05-30 15:00:00
       switch-1       |  TxElements |    0   |  2016-05-29 10:20:10
       switch-1       |  TxElements |    0   |  2016-05-29 05:50:00
       switch-1       |  TxElements |    0   |  2016-05-29 19:50:00
       switch-1       |  TxElements |    5   |  2016-05-29 21:50:00
       switch-1       |  TxElements |    0   |  2016-05-29 20:11:40

Result Set:

   fabric_switch_name |   datatype  |  port  |        time
 -------------------------------------------------------------------
       switch-1       |  TxElements |    2   |  2016-05-31 15:00:00
       switch-1       |  TxElements |    1   |  2016-05-30 22:10:00
       switch-1       |  TxElements |    0   |  2016-05-29 05:50:00
       switch-2       |  TxElements |    0   |  2016-05-30 15:00:00
       switch-1       |  TxElements |    5   |  2016-05-29 21:50:00
       switch-1       |  TxElements |    0   |  2016-05-29 20:11:40


问:
The Decorator Design Pattern: What is meant by adding functionality?
I have just gone into studying the Decorator Design Pattern using C#.

I have made an example which kinda functions as I think it is intended except for one thing.

I kinda understood that the whole point of the pattern is to add functionality to an object dynamically.

So when I create an object like this:

```<code>Inventory a = new Ashbringer(new TravelersBagpack());
a.Execute();
</code>```

Then I kinda expected that the point was that the a object would now be able to call the Execute() method which only exists in the Ashbringer class. Thus adding functionality to the a object.

Though this I can't do without adding the Execute() method to the Inventory interface which would ultimately mean I would have to implement the Execute() method to all the classes implementing Inventory Interface or the abstract Decorator.

Perhaps there is a thing or two I don't know about interfaces or perhaps I misunderstand the point of the Decorator Design Pattern?

答:
The idea in the decorator pattern is that you extend the functionality of a method. It is for cases when inheritance becomes to complex and the functionality needs to be in seperated classes.

A good example is calculating prices. Imagine you want to add fees for special services like a nicer package, faster shipping, insurance.

Now you have your Product class with a CalculatePrice method.

```<code>public class Product
{
    public double CalculatePrice()
    {
        // 10 is the products price
        return 10.0D;
    }
}
</code>```

As next you can create a ProductDecorator which doesn't call his base classes method but the one of the product it was given.

```<code>public abstract class ProductDecorator : Product
{
    private readonly Product _product;

    public ProductDecorator(Product product)
    {
        _product = product;
    }

    public override double CalculatePrice()
    {
        return _product.CalculatePrice();
    }
}
</code>```

Now this price has to change when you want extra services like the metioned above. So you can create decorator classes for them.

```<code>public class ShippingDecorator : ProductDecorator
{
    public ShippingDecorator(Product product)
        : base(product)
    { }

    public override double CalculatePrice()
    {
        // shipping coasts 5
        return base.CalculatePrice() + 5;
    }
}

public class InsuranceDecorator : ProductDecorator
{
...
</code>```

If you wanted to use inheritance for this it would not be usefull as it would be to complex. (To many classes)

Now you can use it like this.

```<code>var product = new Product();
product = new ShippingDecorator(product);
product = new InsuranceDecorator(product);
...
</code>```

Typicly you also have a factory which creates your object or you can use the builder patten.

ContentLicense: CC BY-SA 4.0

Body:
I have just gone into studying the Decorator Design Pattern using C#.

I have made an example which kinda functions as I think it is intended except for one thing.

I kinda understood that the whole point of the pattern is to add functionality to an object dynamically.

So when I create an object like this:

Inventory a = new Ashbringer(new TravelersBagpack());
a.Execute();

Then I kinda expected that the point was that the a object would now be able to call the Execute() method which only exists in the Ashbringer class. Thus adding functionality to the a object.

Though this I can't do without adding the Execute() method to the Inventory interface which would ultimately mean I would have to implement the Execute() method to all the classes implementing Inventory Interface or the abstract Decorator.

Perhaps there is a thing or two I don't know about interfaces or perhaps I misunderstand the point of the Decorator Design Pattern?

Body:
The idea in the decorator pattern is that you extend the functionality of a method. It is for cases when inheritance becomes to complex and the functionality needs to be in seperated classes.

A good example is calculating prices. Imagine you want to add fees for special services like a nicer package, faster shipping, insurance.

Now you have your Product class with a CalculatePrice method.

public class Product
{
    public double CalculatePrice()
    {
        // 10 is the products price
        return 10.0D;
    }
}

As next you can create a ProductDecorator which doesn't call his base classes method but the one of the product it was given.

public abstract class ProductDecorator : Product
{
    private readonly Product _product;

    public ProductDecorator(Product product)
    {
        _product = product;
    }

    public override double CalculatePrice()
    {
        return _product.CalculatePrice();
    }
}

Now this price has to change when you want extra services like the metioned above. So you can create decorator classes for them.

public class ShippingDecorator : ProductDecorator
{
    public ShippingDecorator(Product product)
        : base(product)
    { }

    public override double CalculatePrice()
    {
        // shipping coasts 5
        return base.CalculatePrice() + 5;
    }
}

public class InsuranceDecorator : ProductDecorator
{
...

If you wanted to use inheritance for this it would not be usefull as it would be to complex. (To many classes)

Now you can use it like this.

var product = new Product();
product = new ShippingDecorator(product);
product = new InsuranceDecorator(product);
...

Typicly you also have a factory which creates your object or you can use the builder patten.


问:
My Javascript Timer Speeds Up Every Time I Press the "Start" button
Every time I click the "start" button the timer speed up. And in reverse if you press the "stop" button it starts to slow down and eventually stops. Any way to stop this and just make it where when you press "start" it starts but doesn't speed up?</p>

```<code>function timeKeeper() {
  var h1 = $('#headTime')[0],
    start = $('#start'),
    stop = $('#stop'),
    clear = $('#clear'),
    seconds = 0,
    minutes = 0,
    hours = 0,
    t;

  function add() {
    seconds++;
    if (seconds >= 60) {
      seconds = 0;
      minutes++;
      if (minutes >= 60) {
        minutes = 0;
        hours++;
      }
    }

    h1.textContent = (hours ? (hours > 9 ? hours : "0" + hours) :
      "00") + "." + (minutes ? (minutes > 9 ? minutes : "0" + minutes) :
      "00") + "." + (seconds > 9 ? seconds : "0" + seconds);

    timer();
  }

  function timer() {
    t = setTimeout(add, 1000);
  }

  /* Start button */
  $('#start').on('click', function() {
    timer();
  });

  /* Stop button */
  $('#stop').on('click', function() {
    clearTimeout(t);
  });

  /* Clear button */
  $('#clear').on('click', function() {
    h1.textContent = "00.00.00";
    seconds = 0;
    minutes = 0;
    hours = 0;
  });
</code>```

答:
You need to cancel the old timer when you start a new one.</p>

```<code>$('#start').on('click', function() {
    clearTimeout(t);
    timer();
});
</code>```

Body:
Every time I click the "start" button the timer speed up. And in reverse if you press the "stop" button it starts to slow down and eventually stops. Any way to stop this and just make it where when you press "start" it starts but doesn't speed up?

function timeKeeper() {
  var h1 = $('#headTime')[0],
    start = $('#start'),
    stop = $('#stop'),
    clear = $('#clear'),
    seconds = 0,
    minutes = 0,
    hours = 0,
    t;

  function add() {
    seconds++;
    if (seconds >= 60) {
      seconds = 0;
      minutes++;
      if (minutes >= 60) {
        minutes = 0;
        hours++;
      }
    }

    h1.textContent = (hours ? (hours > 9 ? hours : "0" + hours) :
      "00") + "." + (minutes ? (minutes > 9 ? minutes : "0" + minutes) :
      "00") + "." + (seconds > 9 ? seconds : "0" + seconds);

    timer();
  }

  function timer() {
    t = setTimeout(add, 1000);
  }

  /* Start button */
  $('#start').on('click', function() {
    timer();
  });

  /* Stop button */
  $('#stop').on('click', function() {
    clearTimeout(t);
  });

  /* Clear button */
  $('#clear').on('click', function() {
    h1.textContent = "00.00.00";
    seconds = 0;
    minutes = 0;
    hours = 0;
  });

Body:
You need to cancel the old timer when you start a new one.

$('#start').on('click', function() {
    clearTimeout(t);
    timer();
});


问:
MDS LastChgUserName
We have been using MDS for a couple of years now and we have noticed that the LastChgUserName field isn't always populated (i.e. its NULL) anyone else notice this or have any idea why this is happening? This is a field that is supposed to be auto populated by MDS and is needed for troubleshooting/tracking. Note: the LastChgDateTime is always populated. I checked if the Excel addin was causing the issue and it doesn't seem to be. Also the issue isn't doesn't seem to be occurring when the record is created. Thoughts?</p>

答: Well I dug through the stored procs and the stored proc that is used to load data programmatically into MDS hard codes the user ID to a 0 and there aren't any users with and ID of zero (select * from mdm.tblUser) and that is what is causing the LastChgUserName to be a NULL. I verified this by modifying the stored proc to take a user ID as a param and sure enough the LastChgUserName gets populated....</p>

Title: MDS LastChgUserName


问:
How to configure on-behalf-of authentication in multi-tenant environment?
I have a native client that calls a service I wrote-- that in turn calls the Graph API (using the original caller's credentials).

This is exactly like the 'onbehalfof' sample found here (my code fails the same way as the sample):

https://github.com/Azure-Samples/active-directory-dotnet-webapi-onbehalfof

When logging in as a user from the same tenant as the service (tenant A), everything works fine (just like the onbehalf of sample).  When logging in as a user from a different tenant (tenant B), I get an exception on this line in the service:

```<code>result = await authContext.AcquireTokenAsync(GraphResourceId, clientCred, userAssertion);
</code>```

(this is line 153 from TodoListController.cs in the onbehalfof sample).

The exception is this:

AADSTS65001: The user or administrator has not consented to use the
  application with ID 'de2fb28b-83f8-419d-9b00-3fbce0a60bf4'. Send an
  interactive authorization request for this user and resource.\r\nTrace
  ID: 6865c420-674a-4adf-a070-3d9b9c500200\r\nCorrelation ID:
  7e088563-d7fe-4131-a05c-cbe04dbb2bbd\r\nTimestamp: 2017-03-29
  22:56:58Z

The application id above refers to the service I wrote (which is the same line in the TodoListService in the onbehalfofsample).

I configured everything for multi-tenant authentication. But it's the additional call that my service is making to another service (Graph API) that's causing the problem.  What additional configuration do I need to do in the Azure portal to make this work?

答:
It's working now.  I had to make two changes to get it working.

First, on the service side switch to using "common" as the tenant.  I had switched to common on the client but didn't realize you had to do this on the service side as well:

```<code><add key="ida:Tenant" value="common" />
</code>```

Second, change the GraphUserUrl on the service to the following URL:

```<code><add key="ida:GraphUserUrl" value="https://graph.windows.net/me?api-version=1.6" />
</code>```

The original URL in the sample didn't work (at least for users in another tenant).

Body:
I have a native client that calls a service I wrote-- that in turn calls the Graph API (using the original caller's credentials).

This is exactly like the 'onbehalfof' sample found here (my code fails the same way as the sample):

https://github.com/Azure-Samples/active-directory-dotnet-webapi-onbehalfof

When logging in as a user from the same tenant as the service (tenant A), everything works fine (just like the onbehalf of sample).  When logging in as a user from a different tenant (tenant B), I get an exception on this line in the service:

result = await authContext.AcquireTokenAsync(GraphResourceId, clientCred, userAssertion);

(this is line 153 from TodoListController.cs in the onbehalfof sample).

The exception is this:

AADSTS65001: The user or administrator has not consented to use the
  application with ID 'de2fb28b-83f8-419d-9b00-3fbce0a60bf4'. Send an
  interactive authorization request for this user and resource.\r\nTrace
  ID: 6865c420-674a-4adf-a070-3d9b9c500200\r\nCorrelation ID:
  7e088563-d7fe-4131-a05c-cbe04dbb2bbd\r\nTimestamp: 2017-03-29
  22:56:58Z

The application id above refers to the service I wrote (which is the same line in the TodoListService in the onbehalfofsample).

I configured everything for multi-tenant authentication. But it's the additional call that my service is making to another service (Graph API) that's causing the problem.  What additional configuration do I need to do in the Azure portal to make this work?

Body:
It's working now.  I had to make two changes to get it working.

First, on the service side switch to using "common" as the tenant.  I had switched to common on the client but didn't realize you had to do this on the service side as well:

<add key="ida:Tenant" value="common" />

Second, change the GraphUserUrl on the service to the following URL:

<add key="ida:GraphUserUrl" value="https://graph.windows.net/me?api-version=1.6" />

The original URL in the sample didn't work (at least for users in another tenant).


问:
How add authentication in MQTT transport WSO2 Message broker
I have created a sample Publish and subscribe model project using the WSO2 Message Broker.

```<code>import threading
import paho.mqtt.client as mqtt

def publish_1(client,topic):
    message="on"
    print("publish data")
    client.publish(topic,message)
    publish_1(client,topic)

broker="localhost"
topic_pub='/temperature123'
topic_sub='$SYS/#'

def on_connect(client, userdata, rc):
    print("Connected with result code "+str(rc))
    client.subscribe(topic_sub)

def on_message(client, userdata, msg):
    print(msg.topic+" "+str(msg.payload))

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

client.connect(broker, 1883, 60)
thread1=threading.Thread(target=publish_1,args=(client,topic_pub))
thread1.start()
</code>```

But there is no security in this implementation.

Can someone help me to setup a authentication in MQTT subscription in the WSO2 Message Broker?
And i dont see any subscribed node information also in the WSO2 Message broker application https://localhost:9443/carbon

答:
My experience is with Mosquitto not with WSO2 MB, but from a quick look at the WSO2 MB documentation it seems to support SSL which is the standard way of securing MQTT (https://docs.wso2.com/display/MB310/Enabling+SSL+Support). The process of doing this is quite simple, just distribute the proper keys and certificates then use tsl_set() to configure them in your script.

If you require subtler user / topic level controls it looks like they are provided through the larger WSO2 framework (https://docs.wso2.com/pages/viewpage.action?pageId=30540550#SecurityinWSO2MessageBroker/ApacheQpid-Auth). But I will leave it someone with more experience with WSO2 to explain your options there.

Edit: As an aside, it is seen as a bad practice to start a topic with a / because it creates a confusing / layer. I would just write the topic as "temperature123"

Body:
I have created a sample Publish and subscribe model project using the WSO2 Message Broker.

import threading
import paho.mqtt.client as mqtt

def publish_1(client,topic):
    message="on"
    print("publish data")
    client.publish(topic,message)
    publish_1(client,topic)

broker="localhost"
topic_pub='/temperature123'
topic_sub='$SYS/#'

def on_connect(client, userdata, rc):
    print("Connected with result code "+str(rc))
    client.subscribe(topic_sub)

def on_message(client, userdata, msg):
    print(msg.topic+" "+str(msg.payload))

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

client.connect(broker, 1883, 60)
thread1=threading.Thread(target=publish_1,args=(client,topic_pub))
thread1.start()

But there is no security in this implementation.

Can someone help me to setup a authentication in MQTT subscription in the WSO2 Message Broker?
And i dont see any subscribed node information also in the WSO2 Message broker application https://localhost:9443/carbon


问:
Resize CKEditor
I am using CKEditor and would like to resize the editor.  I am doing the following:

```<code><head runat="server">

    <script src="../../../../../js/jquery-1.10.2.min.js" type="text/javascript"></script>
    <script src="../../../../../ckeditor/ckeditor.js" type="text/javascript"></script>
    <script src="../../../../../js/ckeditor_initialize.js" type="text/javascript"></script>

    <script type="text/javascript">
        function ResizeEditor() {
            var editor = CKEDITOR.replace('tbEditor');
            editor.resize('100', '800');
        }
    </script>
</head>
<body onload="ResizeEditor();">
    <form id="form1" runat="server">
        <asp:TextBox class="ckeditor" ID="tbEditor" runat="server" ClientIDMode="Static" TextMode="MultiLine"></asp:TextBox>
    </form>
</body>
</code>```

But it does not seem to work.  I think I may be getting the CKEditor Instance incorrectly.  Can someone explain what I am doing wrong?

I am using CKEditor 4 with .net 4.5.

答:
here don't work with replace, because I need destroy before and I understand you do not have to do this.

You can resize this way:

```<code>var editor = CKEDITOR.instances['tbEditor'];
if (editor) {
     editor.resize(100, 800);
}
</code>```

Title: Resize CKEditor

Body:
I am using CKEditor and would like to resize the editor.  I am doing the following:

    <form id="form1" runat="server">
        <asp:TextBox class="ckeditor" ID="tbEditor" runat="server" ClientIDMode="Static" TextMode="MultiLine"></asp:TextBox>
    </form>

But it does not seem to work.  I think I may be getting the CKEditor Instance incorrectly.  Can someone explain what I am doing wrong?

I am using CKEditor 4 with .net 4.5.

Body:
here don't work with replace, because I need destroy before and I understand you do not have to do this.

You can resize this way:

var editor = CKEDITOR.instances['tbEditor'];
if (editor) {
     editor.resize(100, 800);
}


问:
How to scroll tablayout programmatically - Android
I have created 30 scrollable tabs using tablayout.

So first three tabs are visible on screen and rest of them are invisible which can be scroll using swipe gesture.

The problem is when I am selecting last tab programmatically but it is not get visible (tab layout not get scrolled to last tab).

How can I make tablayout to scroll to last tab?

答:
If your TabLayout is used in conjunction with a ViewPager, which is common, simply add the following in the onCreate() method in your Activity:

```<code>tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout);
</code>```

That some of your tabs are not being shown indicates the tabMode attribute is set to app:tabMode="scrollable".

Body:
If your TabLayout is used in conjunction with a ViewPager, which is common, simply add the following in the onCreate() method in your Activity:

tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout);

That some of your tabs are not being shown indicates the tabMode attribute is set to app:tabMode="scrollable".


问:
Time in milliseconds in Python
In this logging that I built part of it is to time the entire process from start to finish. In this script we are unzipping, pulling data and merging and rezipping these files. Imported default_timer from timeit as shown below. All of the processes are timed as is the entire time it takes to run the script. The out put in the log is this -1.207415584403293e-06 for the time it takes to rezip and I cannot figure out how to get it out of scientific notation and display it as either milliseconds or microseconds. Any ideas? The coding is as below:

```<code>from timeit import default_timer as timer
start = timer()
fullstart = start
</code>```

this is the import and call for the timer at the beginning and the coding at the end is as follows:

```<code>end = timer()
logger.info("Total time in sec "+str(end - fullstart))
</code>```

答:
This is output formatting.  Below, I've used the oldest version; I suggest that you read the documentation and pick the form you like best.
I multiplied by a million to get microseconds, and then used a simple float format specification to print something more readable.  I'll let you replace the print with a logging command.

```<code>from timeit import default_timer as timer
start = timer()
fullstart = start

for i in range(100000):
    pass

end = timer()
print("Total time : %.1f ms" % (1000 * (end - fullstart)))
</code>```

Output:

```<code>Total time : 7.3 ms
</code>```

Title: Time in milliseconds in Python

Body:
In this logging that I built part of it is to time the entire process from start to finish. In this script we are unzipping, pulling data and merging and rezipping these files. Imported default_timer from timeit as shown below. All of the processes are timed as is the entire time it takes to run the script. The out put in the log is this -1.207415584403293e-06 for the time it takes to rezip and I cannot figure out how to get it out of scientific notation and display it as either milliseconds or microseconds. Any ideas? The coding is as below:

from timeit import default_timer as timer
start = timer()
fullstart = start

this is the import and call for the timer at the beginning and the coding at the end is as follows:

end = timer()
logger.info("Total time in sec "+str(end - fullstart))

Body:
This is output formatting.  Below, I've used the oldest version; I suggest that you read the documentation and pick the form you like best.
I multiplied by a million to get microseconds, and then used a simple float format specification to print something more readable.  I'll let you replace the print with a logging command.

from timeit import default_timer as timer
start = timer()
fullstart = start

for i in range(100000):
    pass

end = timer()
print("Total time : %.1f ms" % (1000 * (end - fullstart)))

Output:

Total time : 7.3 ms


问:
c# commandline no error line number
If there is an exception in .NET code and and PDB file is available you normally get the errors with source code line numbers shown in the exception message. This seems to be different in command line executables, where I do not get any line number although a PDB file is available:

Anwendung: MNX.CommandLine.EpkFtpEventhandler.exe Frameworkversion: v4.0.30319 Beschreibung: Der Prozess wurde aufgrund eines Ausnahmefehlers beendet. Ausnahmeinformationen: System.Data.SqlClient.SqlException Stapel: bei System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(System.String, Boolean, Int32, Boolean) bei System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(System.Threading.Tasks.TaskCompletionSource`1, System.String, Boolean, Int32, Boolean) bei System.Data.SqlClient.SqlCommand.ExecuteNonQuery() bei MNX.DB.WriteLocal(System.String) bei MNX.DB.Write(System.String) bei MNX.CommandLine.EpkFtpEventHandler.Main(System.String[])

Does anyone know why?

答:
Use Stack Frames and surround you code with a try catch:

```<code>try
{
     throw new Exception();
}
catch (Exception ex)
{
    // Get stack trace for the exception with source file information
    var st = new StackTrace(ex, true);
    // Get the top stack frame
    var frame = st.GetFrame(0);
    // Get the line number from the stack frame
    var line = frame.GetFileLineNumber();
    // Print the line number
    Console.WriteLine($"An Error ({ex.Message}) occurred in line {line}");
}
</code>```

To avoid plagiarism: I got the idea from this question.

I don't know why it isn't normally displayed in your console application though, but this should do it as well.

Title: c# commandline no error line number

Body:
Use Stack Frames and surround you code with a try catch:

try
{
     throw new Exception();
}
catch (Exception ex)
{
    // Get stack trace for the exception with source file information
    var st = new StackTrace(ex, true);
    // Get the top stack frame
    var frame = st.GetFrame(0);
    // Get the line number from the stack frame
    var line = frame.GetFileLineNumber();
    // Print the line number
    Console.WriteLine($"An Error ({ex.Message}) occurred in line {line}");
}

To avoid plagiarism: I got the idea from this question.

I don't know why it isn't normally displayed in your console application though, but this should do it as well.


问:
videojs show double caption (it may be already posted but didnt found similair issue)
im facing a weird problem and i dont know how to resolve it,
videojs show me double caption for arabic subtitles but show correctly other languages like french english even chinese. so im just wondering what should be the issue. I checked the file vtt but it seems correct.

here a picture how it looks like see image here

答:
well heres the minimal informations that i can provide:
the config is :
i put the real of the second subtitle to verify that is not doubled but in videojs shows double captions only for arabic</p>

```<code><video id="example_video_1" class="video-js" controls preload="auto" width="640" height="264" data-setup='{"example_option":true}'><source src="http://vjs.zencdn.net/v/oceans.mp4" type="video/mp4" /><track kind="captions" src="http://example.com/path/to/captions.vtt" srclang="en" label="English" default><track kind="captions"src="https://www.osnmovies.com/subtitles/tt0918940_ar/0000.vtt"srclang="ar" label="Arabic" default> </video>
</code>```

Body:
well heres the minimal informations that i can provide:
the config is :
i put the real of the second subtitle to verify that is not doubled but in videojs shows double captions only for arabic

<video id="example_video_1" class="video-js" controls preload="auto" width="640" height="264" data-setup='{"example_option":true}'><source src="http://vjs.zencdn.net/v/oceans.mp4" type="video/mp4" /><track kind="captions" src="http://example.com/path/to/captions.vtt" srclang="en" label="English" default><track kind="captions"src="https://www.osnmovies.com/subtitles/tt0918940_ar/0000.vtt"srclang="ar" label="Arabic" default> </video>


问:
Unable to get Dynamic xfa form fields using pdf.js after Enabling Usage rights in adobe reader
I have created a Dynamic XFA form  using Livecycle designer.I'm using pdf.js to get the form fields.But after enabling  "enable usage rights" to the form it shows the form field length is 0. I'm using page.getAnnotations() of pdf.js to get it.</p>

答: If the form is static XFA, the PDF contains an AcroForm dictionary in addition to the XFA dictionary which is how non-Adobe viewers can handle static XFA. They don't handle the XFA, they read the AcroForm as though the XFA didn't exist. However, with Dynamic XFA, it is very likely that there are no form fields in the AcroForm dictionary until the viewer renders the XFA into a PDF... Acrobat does this automatically but other libraries that can't create a PDF DOM from the XFA DOM won't be able to. I doubt your issue has anything to do with usage rights other than the fact that saving the file caused Acrobat to wipe the PDF counterpart to the XFA.</p>


问:
How to retrieve the value of an input on keyup?
What I am trying to achieve is to output the actual value/text so that I can save it into a variable, but the console gives me a number indicator and it keeps adding to it each time I keyup.

```<code><input id="usp-custom-3" type="text">
</code>```

var country1 = $("#usp-custom-3").html();
$("#usp-custom-3").on("keyup", function() {
    console.log(country1);
});
```

答:
There's two issues with your code. Firstly you need to get the val() of the input, not it's html(). Secondly, you need to retrieve the value every time the event happens, so place it within the event handler, like this:

$("#usp-custom-3").on("keyup", function() {
  var country1 = $("#usp-custom-3").val();
  console.log(country1);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="usp-custom-3" type="text"></code>```

Body:
What I am trying to achieve is to output the actual value/text so that I can save it into a variable, but the console gives me a number indicator and it keeps adding to it each time I keyup.

<input id="usp-custom-3" type="text">

var country1 = $("#usp-custom-3").html();
$("#usp-custom-3").on("keyup", function() {
    console.log(country1);
});

Body:
There's two issues with your code. Firstly you need to get the val() of the input, not it's html(). Secondly, you need to retrieve the value every time the event happens, so place it within the event handler, like this:

$("#usp-custom-3").on("keyup", function() {
  var country1 = $("#usp-custom-3").val();
  console.log(country1);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="usp-custom-3" type="text">


问:
Upgrading to Laravel 5.4.0 from 5.1
I am using Laravel 5.1 and I would like to know how to upgrade to the latest version of Laravel which is 5.4.

Can we directly upgrade to Laravel 5.4 From 5.1 ?

答:
The best way to upgrade is to follow the steps for each version. So upgrade to 5.2 then 5.3 then finally 5.4. The upgrade guides look lengthy but it most cases it wont take to much time because the guide covers all potential changes but they won't all apply to your application.

Alternatively you could install a fresh version of 5.4 then copy your application code into the new Laravel. Since the upgrade for each version is relatively straight forward and this method would lose your git history I wouldn't recommend it.

Another paid method would be to use Laravel Shift which will automate the upgrade process for you.

Edit: As @Scott mentioned you should make sure your server meets the server requirements for your target Laravel version. Specifically make sure you have PHP >= 5.6.4 installed

Title: Upgrading to Laravel 5.4.0 from 5.1


问:
How to remove file with invalid name (Ubuntu)?
By mistake I have createad file with name:

```<code>0);          if (count($keys->toArray())  0) {              $this->obj->api(messages.send, [                 access_token > $this->group->getAccessToken(),                 user_id > $this->userId,                 message > Я
</code>```

I'm not able to remove it via ssh or sftp.

Is there any way?

答:
Remove the file by its inode number.

Every filesystem entry has a number, called the inode number.  With this you can remove a file without referencing the file's name

```<code>ls -il
</code>```

Will list inode numbers along with the long entry.  For example:

```<code>> ls -il example
8460278 -rw-r--r-- 1 edwbuck edwbuck 0 Mar 30 21:13 example
</code>```

which can be removed by

```<code>> find . -inum 8460278 -exec rm -i {} +
</code>```

which will use the find command to locate the file and then pass the difficult to type name (properly escaped) to the rm command.  If you don't like the "prompt me if I really want to do it" behavior in rm remove the -i option.

Body:
By mistake I have createad file with name:

0);          if (count($keys->toArray())  0) {              $this->obj->api(messages.send, [                 access_token > $this->group->getAccessToken(),                 user_id > $this->userId,                 message > Я

I'm not able to remove it via ssh or sftp.

Is there any way?

Body:
Remove the file by its inode number.

Every filesystem entry has a number, called the inode number.  With this you can remove a file without referencing the file's name

ls -il

Will list inode numbers along with the long entry.  For example:

> ls -il example
8460278 -rw-r--r-- 1 edwbuck edwbuck 0 Mar 30 21:13 example

which can be removed by

> find . -inum 8460278 -exec rm -i {} +

which will use the find command to locate the file and then pass the difficult to type name (properly escaped) to the rm command.  If you don't like the "prompt me if I really want to do it" behavior in rm remove the -i option.


问:
JavaFX - Update Table Row From Task
I'm trying to update the text in my table from inside my JavaFx Task. I've done this before with basic labels, but I'm completely lost when it comes to properly binding to the table and updating the rows. Here is the code I have so far.

My main class

```<code>public class AnotherClass extends Application {
static List<Listing> listings = Collections.synchronizedList(new ArrayList<Listing>());
@Override
    public void start(Stage stage) throws Exception {
        // calls init function about 200 lines of code for adding Listing objects to the listings list.

        Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));

        Scene scene = new Scene(root);

        stage.setScene(scene);
        stage.show();

    }
}
</code>```

My controller class:

```<code>public class TestController implements Initializable {

UpdateTableTask updateTableTask = new UpdateTableTask();

@FXML
public TableView<Listing> allListings;
@FXML
public TableColumn<Listing, String> nameCol;
public TableColumn<Listing, String> idCol;
public TableColumn<Listing, String> skuCol;
@FXML
public final ObservableList<Listing> allListingsData = FXCollections.observableArrayList();

public void initialize(URL url, ResourceBundle rb) {

    for(int i = 0; i < AnotherClass.listings.size(); i++){

        allListingsData.add(AnotherClass.listings.get(i));
    }
    nameCol.setCellValueFactory(new PropertyValueFactory<Listing, String>("name"));
    idCol.setCellValueFactory(new PropertyValueFactory<Listing, String>("id"));
    skuCol.setCellValueFactory(new PropertyValueFactory<Listing, String>("SKU"));
    allListings.setItems(allListingsData);

    updateTableTask.launch();

}

}
</code>```

My Listing class:

```<code>public class Listing {
private String name;
private String id;
private String sku;
private double maxPrice;
private double minPrice;
private double currentPrice;
private int quantity;
private boolean isFBA;
private boolean active;
private boolean needsUpdate = false;
private double newPrice;
private double shipping;
private boolean isCompetitive = true;
private String buyBoxName = "unknown";
//private String productId;
private String asin;
public Listing(String name, String id, String sku, double minPrice, double maxPrice, double currentPrice, int quantity, String asin, boolean isFBA, boolean active, double shipping){
    this.name = name;
    this.id = id;
    this.sku = sku;
    this.maxPrice = maxPrice;
    this.minPrice = minPrice;
    this.currentPrice = currentPrice;
    this.quantity = quantity;
    this.isFBA = isFBA;
    this.active = active;
    this.shipping = shipping;
    //this.productId = productId;
    this.asin = asin;
  }
  public String getShippingLabel(){
     String result;
      if(Double.compare(this.shipping, 0.0) == 0){
            result = "Standard Free Shipping";
       }else{
            result = "Default Amazon Template";
       }
       return result;
   }
   public String getASIN(){
        return this.asin;
   }
    public String getName(){
       return this.name;
    }

    public String getId(){
        return this.id;
    }

    public int getQuantity(){
       return this.quantity;
    }
    public boolean getNeedsUpdate(){
        return this.needsUpdate;
    }

    public void setNeedsUpdate(boolean b){
        this.needsUpdate = b;
    }

    public void setNewPrice(double price){
        this.newPrice = price;
    }

    public double getNewPrice(){
        return this.newPrice;
    }

    public String getSKU(){
        return this.sku;
    }

    public double getCurrentPrice(){
        return this.currentPrice;
    }

   public void setCurrentPrice(double price){
        this.currentPrice = price;
    }

    public boolean getIsFBA(){
       return this.isFBA;
   }

    public void setIsFBA(boolean isFBA){
        this.isFBA = isFBA;
    }

    public double getMinPrice(){
        return this.minPrice;
    }

    public double getMaxPrice(){
        return this.maxPrice;
    }

    public double getShipping(){
        return this.shipping;
    }

    public void setIsCompetitive(boolean isCompetitive){
        this.isCompetitive = isCompetitive;
    }

    public boolean getIsCompetitive(){
        return this.isCompetitive;
    }

    public void setNewPriceToMin(){
        this.newPrice = this.minPrice;
    }

    public void setNewPriceToMax(){
        this.newPrice = this.maxPrice;
    }

    public void setBuyBoxName(String name){
        this.buyBoxName = name;
    }

    public String getBuyBoxName(){
        return this.buyBoxName;
    }
}
</code>```

Then I have a task that I need to update the table with.

```<code>public class UpdateTableTask extends Service<Void>{

@Override
protected Task<Void> createTask() {
        return new Task<Void>() {
            @Override
            protected Void call() throws Exception {
                  while(true){
                       synchronized(AnotherClass.listings){
                          for(int i = 0; i < AnotherClass.listings.size(); i++){
                              // multiple threads access the list.
                               Response response = makeAPICall();
                              listings.get(i).isCompetitive(response); //true or false
                              Thread.sleep(1000);
                          }

                       }
                  }

            }
        }
    }
}
</code>```

(manually typed in the code)

Any help would be appreciated. Thanks

答:
It's a little bit hard as your code as presented is a bit incomplete and wouldn't actually compile, so I will modify things a little bit and make some assumptions (which may not match your actual use case).

Let's assume you want have a column:

```<code>@FXML
TableColumn<Listing, String> isCompetitiveCol;
</code>```

For which you have a propertyValueFactory:

```<code>isCompetitiveCol.setCellValueFactory(new PropertyValueFactory<Listing, String>("isCompetitive"));
</code>```

Change your Listing class to use full JavaFX properties, rather than just basic types.  For example, instead of:

```<code>private boolean isCompetitive = true;
. . .
public void setIsCompetitive(boolean isCompetitive){
    this.isCompetitive = isCompetitive;
}
public boolean getIsCompetitive(){
    return this.isCompetitive;
}
</code>```

Write:

```<code>private BooleanProperty isCompetitive = new SimpleBooleanProperty(true);
public void setIsCompetitive(boolean isCompetitive){
    this.isCompetitive.set(isCompetitive);
}
public boolean getIsCompetitive(){
    return this.isCompetitive.get();
}
public BooleanProperty isCompetitiveProperty() {
    return isCompetitive;
}
</code>```

This turns the competitive property into a listenable property that can fire change and invalidation listeners when its value is updated.  The PropertyValueFactory implementation will trigger the update notification (and subsequent update to a value in a cell in the table), whenever the property is changed.

As you using threads, you need to make sure that you don't update the isCompetitive property value off of the JavaFX application thread (as updates to the scene graph triggered from the property update can only occur on the JavaFX application thread).  You can do that by running any updates using Platform.runLater().

So your task can be something like this:

```<code>@FXML
public TableView<Listing> allListings;
...
for(int i = 0; i < AnotherClass.listings.size(); i++){
    allListingsData.add(new Listing(AnotherClass.listings.get(i)));
}
...
return new Task<Void>() {
    @Override
    protected Void call() throws Exception {
         while(true){
              synchronized(AnotherClass.listings) {
                  for(int i = 0; i < AnotherClass.listings.size(); i++){
                      Response response = makeAPICall();
                      Platform.runLater(() -> {
                          allListings.getItems().get(i).setIsCompetitive(
                              response.isCompetitive()
                          );
                      };
                      Thread.sleep(1000);
                  }
              }
         }
    }
}
</code>```

Note, I am keeping the listing objects in the TableView items separate from the listing objects in the AnotherClass.listings class (by creating the list using allListingsData.add(new Listing(AnotherClass.listings.get(i)));).  This is to ensure that when if you have other threads updating AnotherClass.listings values, it doesn't have a side effect of trying to update your table through the linkage established via the PropertyValueFactory.  Instead updates are transferred from AnotherClass.listings to the TableView in the platform.runLater call to make sure the table only changes when you need to have it change.

Note the above solution is assuming a fixed list of listings where the values of the properties of the listings change, but the number and order of listings themselves don't change (e.g. listings are not added to, removed from or reordered in the list during the process).  If that assumption is does not hold, then you will need additional logic to update the list values themselves, and not just the properties inside list elements (and to be careful to do so without violating threading rules).  To understand how to achieve that you can look the Task documentation sections about tasks which return ObservableLists, Partial Results Tasks and Tasks which modify the Scene Graph and will likely need to use some combination of the idioms described in those samples to achieve the result you require.

Also note, because you are just doing while(true) in your Task, you probably don't even need a Task (as you are not using any of it's features, such as the return value, updateMessage and updateProgress systems).  Instead you can just launch a thread with a runnable (either new Thread() or using Executors) and update values back via Platform.runLater as needed.

Title: JavaFX - Update Table Row From Task

Body:
I'm trying to update the text in my table from inside my JavaFx Task. I've done this before with basic labels, but I'm completely lost when it comes to properly binding to the table and updating the rows. Here is the code I have so far.

My main class

public class AnotherClass extends Application {
static List<Listing> listings = Collections.synchronizedList(new ArrayList<Listing>());
@Override
    public void start(Stage stage) throws Exception {
        // calls init function about 200 lines of code for adding Listing objects to the listings list.

        Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));

        Scene scene = new Scene(root);

        stage.setScene(scene);
        stage.show();

    }
}

My controller class:

public class TestController implements Initializable {

UpdateTableTask updateTableTask = new UpdateTableTask();

@FXML
public TableView<Listing> allListings;
@FXML
public TableColumn<Listing, String> nameCol;
public TableColumn<Listing, String> idCol;
public TableColumn<Listing, String> skuCol;
@FXML
public final ObservableList<Listing> allListingsData = FXCollections.observableArrayList();

public void initialize(URL url, ResourceBundle rb) {

    for(int i = 0; i < AnotherClass.listings.size(); i++){

        allListingsData.add(AnotherClass.listings.get(i));
    }
    nameCol.setCellValueFactory(new PropertyValueFactory<Listing, String>("name"));
    idCol.setCellValueFactory(new PropertyValueFactory<Listing, String>("id"));
    skuCol.setCellValueFactory(new PropertyValueFactory<Listing, String>("SKU"));
    allListings.setItems(allListingsData);

    updateTableTask.launch();

}

}

My Listing class:

public class Listing {
private String name;
private String id;
private String sku;
private double maxPrice;
private double minPrice;
private double currentPrice;
private int quantity;
private boolean isFBA;
private boolean active;
private boolean needsUpdate = false;
private double newPrice;
private double shipping;
private boolean isCompetitive = true;
private String buyBoxName = "unknown";
//private String productId;
private String asin;
public Listing(String name, String id, String sku, double minPrice, double maxPrice, double currentPrice, int quantity, String asin, boolean isFBA, boolean active, double shipping){
    this.name = name;
    this.id = id;
    this.sku = sku;
    this.maxPrice = maxPrice;
    this.minPrice = minPrice;
    this.currentPrice = currentPrice;
    this.quantity = quantity;
    this.isFBA = isFBA;
    this.active = active;
    this.shipping = shipping;
    //this.productId = productId;
    this.asin = asin;
  }
  public String getShippingLabel(){
     String result;
      if(Double.compare(this.shipping, 0.0) == 0){
            result = "Standard Free Shipping";
       }else{
            result = "Default Amazon Template";
       }
       return result;
   }
   public String getASIN(){
        return this.asin;
   }
    public String getName(){
       return this.name;
    }

    public String getId(){
        return this.id;
    }

    public int getQuantity(){
       return this.quantity;
    }
    public boolean getNeedsUpdate(){
        return this.needsUpdate;
    }

    public void setNeedsUpdate(boolean b){
        this.needsUpdate = b;
    }

    public void setNewPrice(double price){
        this.newPrice = price;
    }

    public double getNewPrice(){
        return this.newPrice;
    }

    public String getSKU(){
        return this.sku;
    }

    public double getCurrentPrice(){
        return this.currentPrice;
    }

   public void setCurrentPrice(double price){
        this.currentPrice = price;
    }

    public boolean getIsFBA(){
       return this.isFBA;
   }

    public void setIsFBA(boolean isFBA){
        this.isFBA = isFBA;
    }

    public double getMinPrice(){
        return this.minPrice;
    }

    public double getMaxPrice(){
        return this.maxPrice;
    }

    public double getShipping(){
        return this.shipping;
    }

    public void setIsCompetitive(boolean isCompetitive){
        this.isCompetitive = isCompetitive;
    }

    public boolean getIsCompetitive(){
        return this.isCompetitive;
    }

    public void setNewPriceToMin(){
        this.newPrice = this.minPrice;
    }

    public void setNewPriceToMax(){
        this.newPrice = this.maxPrice;
    }

    public void setBuyBoxName(String name){
        this.buyBoxName = name;
    }

    public String getBuyBoxName(){
        return this.buyBoxName;
    }
}

Then I have a task that I need to update the table with.

public class UpdateTableTask extends Service<Void>{

@Override
protected Task<Void> createTask() {
        return new Task<Void>() {
            @Override
            protected Void call() throws Exception {
                  while(true){
                       synchronized(AnotherClass.listings){
                          for(int i = 0; i < AnotherClass.listings.size(); i++){
                              // multiple threads access the list.
                               Response response = makeAPICall();
                              listings.get(i).isCompetitive(response); //true or false
                              Thread.sleep(1000);
                          }

                       }
                  }

            }
        }
    }
}

(manually typed in the code)

Any help would be appreciated. Thanks

Body:
It's a little bit hard as your code as presented is a bit incomplete and wouldn't actually compile, so I will modify things a little bit and make some assumptions (which may not match your actual use case).

Let's assume you want have a column:

@FXML
TableColumn<Listing, String> isCompetitiveCol;

For which you have a propertyValueFactory:

isCompetitiveCol.setCellValueFactory(new PropertyValueFactory<Listing, String>("isCompetitive"));

Change your Listing class to use full JavaFX properties, rather than just basic types.  For example, instead of:

private boolean isCompetitive = true;
. . .
public void setIsCompetitive(boolean isCompetitive){
    this.isCompetitive = isCompetitive;
}
public boolean getIsCompetitive(){
    return this.isCompetitive;
}

Write:

private BooleanProperty isCompetitive = new SimpleBooleanProperty(true);
public void setIsCompetitive(boolean isCompetitive){
    this.isCompetitive.set(isCompetitive);
}
public boolean getIsCompetitive(){
    return this.isCompetitive.get();
}
public BooleanProperty isCompetitiveProperty() {
    return isCompetitive;
}

This turns the competitive property into a listenable property that can fire change and invalidation listeners when its value is updated.  The PropertyValueFactory implementation will trigger the update notification (and subsequent update to a value in a cell in the table), whenever the property is changed.

As you using threads, you need to make sure that you don't update the isCompetitive property value off of the JavaFX application thread (as updates to the scene graph triggered from the property update can only occur on the JavaFX application thread).  You can do that by running any updates using Platform.runLater().

So your task can be something like this:

@FXML
public TableView<Listing> allListings;
...
for(int i = 0; i < AnotherClass.listings.size(); i++){
    allListingsData.add(new Listing(AnotherClass.listings.get(i)));
}
...
return new Task<Void>() {
    @Override
    protected Void call() throws Exception {
         while(true){
              synchronized(AnotherClass.listings) {
                  for(int i = 0; i < AnotherClass.listings.size(); i++){
                      Response response = makeAPICall();
                      Platform.runLater(() -> {
                          allListings.getItems().get(i).setIsCompetitive(
                              response.isCompetitive()
                          );
                      };
                      Thread.sleep(1000);
                  }
              }
         }
    }
}

Note, I am keeping the listing objects in the TableView items separate from the listing objects in the AnotherClass.listings class (by creating the list using allListingsData.add(new Listing(AnotherClass.listings.get(i)));).  This is to ensure that when if you have other threads updating AnotherClass.listings values, it doesn't have a side effect of trying to update your table through the linkage established via the PropertyValueFactory.  Instead updates are transferred from AnotherClass.listings to the TableView in the platform.runLater call to make sure the table only changes when you need to have it change.

Note the above solution is assuming a fixed list of listings where the values of the properties of the listings change, but the number and order of listings themselves don't change (e.g. listings are not added to, removed from or reordered in the list during the process).  If that assumption is does not hold, then you will need additional logic to update the list values themselves, and not just the properties inside list elements (and to be careful to do so without violating threading rules).  To understand how to achieve that you can look the Task documentation sections about tasks which return ObservableLists, Partial Results Tasks and Tasks which modify the Scene Graph and will likely need to use some combination of the idioms described in those samples to achieve the result you require.

Also note, because you are just doing while(true) in your Task, you probably don't even need a Task (as you are not using any of it's features, such as the return value, updateMessage and updateProgress systems).  Instead you can just launch a thread with a runnable (either new Thread() or using Executors) and update values back via Platform.runLater as needed.