问:
Angular 2 - Observe result of firebase database
I'm new in angular, so be kind :)

Angular 2 ( 1.0.4 )
Angular Cli
NodeJs 7.9

i've try to make a centralized service that check if user is logged-in and, if it is retrive and send back data of User... i just try for 2 days to make this method works without success... any help will be appreciated :

```<code>    import { Injectable } from '@angular/core';
    import { Component, OnInit } from '@angular/core';
    import { AngularFireAuth } from 'angularfire2/auth';
    import { AngularFireDatabaseModule, AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database';
    import { Observable } from 'rxjs/Rx';
    import { TipoUtente } from './tipidati' ;
    import {Resolve, ActivatedRouteSnapshot, RouterStateSnapshot, Router} from '@angular/router';

    import * as firebase from 'firebase';

    import 'rxjs/add/operator/toPromise' ;

    @Injectable()
    export class StatoutenteService implements OnInit {

constructor(private db: AngularFireDatabase, private afAuth: AngularFireAuth, private router: Router) {}

public getUserData() : Observable<any> {

  this.afAuth.authState.map( auth => {

        if (auth == null) {
          this.Logged = false ;
          this.Utente = new TipoUtente() ;
          this.UId = '' ;
          return undefined ;

        } else {
          this.Logged = true  ;
          this.UId = auth.uid ;

          return this.dbUserData().then(data => {
              console.log('leggo promessa') ;
              console.log(data) ;
              if (data.Livello != undefined) this.Utente = data ; else this.Utente = undefined ;
              console.log(this.Utente) ;
              if ( this.Utente == undefined ) { this.createNewUser() }
            } ) ;
        }
      } ) ;

} ;

private dbUserData() : Promise<TipoUtente> {

  // Controllo Utente
  console.log('Recupero dati utente!') ;
  console.log('UID :' + this.UId ) ;
  console.log(this.Logged) ;

  let utenteX = this.db.object('users/' + this.UId)
  return new Promise((resolve, reject) => {
    // must import 'rxjs/add/operator/first'; before using it here
    utenteX.subscribe( data  => {
      if ( data.$value == null ) resolve(undefined); else resolve(data) ;
    }, reject);
  });

}
</code>```

答:
The main issue is that your getUserData() does not returning anything. You need to return the ovservable.

```<code>return this.afAuth.authState.map( auth => { ....
</code>```

then you should be able to access the userData by subscribing the getUserData() like so:

```<code>this.statoutenteService.getUserData().subscribe(promisedUserData => {...})
</code>```

but actually mixing promises and observables is not a good practice. try to restructe it like so:

```<code>export class StatoutenteService implements OnInit {
    Logged: boolean;
    UId: string;
    Utente: TipoUtente;

    constructor(private db: AngularFireDatabase, private afAuth: AngularFireAuth, private router: Router) {
         this.Logged = false;
         this.UId = '';
         this.Utente = new TipoUtente();
    }

    public getUserData() : Observable<any> {

      return this.afAuth.authState
         .filter(auth => !!auth)  //filters out events where auth is not truthy
         .flatMap( auth => {      //flatMap will resolve the returned observable (chaining observables)
             this.Logged = true;
             this.UId = auth.uid;

             return this.db.object('users/' + this.UId);
        }).map(data => {
             if (data.Livello != undefined)
                 this.Utente = data;
             else
                 this.Utente = undefined;
             console.log(this.Utente) ;
             if (this.Utente == undefined)
                 return this.createNewUser();
             return null;
        });
    }
}
</code>```

then you don't have the overhead of the promise. when you then subscribe to the getUserData() observable, you will get whatever the last maping function returns. so right now you would get the return value of this.createNewUser(); if this.Utente was undefined before. otherwise null.

you would access it the same way, by subscribing to it:

```<code>this.statoutenteService.getUserData().subscribe(user => {...})
</code>```

Hope that will help you.

Body:
I'm new in angular, so be kind :)

Angular 2 ( 1.0.4 )
Angular Cli
NodeJs 7.9

i've try to make a centralized service that check if user is logged-in and, if it is retrive and send back data of User... i just try for 2 days to make this method works without success... any help will be appreciated :

    import { Injectable } from '@angular/core';
    import { Component, OnInit } from '@angular/core';
    import { AngularFireAuth } from 'angularfire2/auth';
    import { AngularFireDatabaseModule, AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database';
    import { Observable } from 'rxjs/Rx';
    import { TipoUtente } from './tipidati' ;
    import {Resolve, ActivatedRouteSnapshot, RouterStateSnapshot, Router} from '@angular/router';

    import * as firebase from 'firebase';

    import 'rxjs/add/operator/toPromise' ;

    @Injectable()
    export class StatoutenteService implements OnInit {

constructor(private db: AngularFireDatabase, private afAuth: AngularFireAuth, private router: Router) {}

public getUserData() : Observable<any> {

  this.afAuth.authState.map( auth => {

        if (auth == null) {
          this.Logged = false ;
          this.Utente = new TipoUtente() ;
          this.UId = '' ;
          return undefined ;

        } else {
          this.Logged = true  ;
          this.UId = auth.uid ;

          return this.dbUserData().then(data => {
              console.log('leggo promessa') ;
              console.log(data) ;
              if (data.Livello != undefined) this.Utente = data ; else this.Utente = undefined ;
              console.log(this.Utente) ;
              if ( this.Utente == undefined ) { this.createNewUser() }
            } ) ;
        }
      } ) ;

} ;

private dbUserData() : Promise<TipoUtente> {

  // Controllo Utente
  console.log('Recupero dati utente!') ;
  console.log('UID :' + this.UId ) ;
  console.log(this.Logged) ;

  let utenteX = this.db.object('users/' + this.UId)
  return new Promise((resolve, reject) => {
    // must import 'rxjs/add/operator/first'; before using it here
    utenteX.subscribe( data  => {
      if ( data.$value == null ) resolve(undefined); else resolve(data) ;
    }, reject);
  });

}

Body:
The main issue is that your getUserData() does not returning anything. You need to return the ovservable.

return this.afAuth.authState.map( auth => { ....

then you should be able to access the userData by subscribing the getUserData() like so:

this.statoutenteService.getUserData().subscribe(promisedUserData => {...})

but actually mixing promises and observables is not a good practice. try to restructe it like so:

export class StatoutenteService implements OnInit {
    Logged: boolean;
    UId: string;
    Utente: TipoUtente;

    constructor(private db: AngularFireDatabase, private afAuth: AngularFireAuth, private router: Router) {
         this.Logged = false;
         this.UId = '';
         this.Utente = new TipoUtente();
    }

    public getUserData() : Observable<any> {

      return this.afAuth.authState
         .filter(auth => !!auth)  //filters out events where auth is not truthy
         .flatMap( auth => {      //flatMap will resolve the returned observable (chaining observables)
             this.Logged = true;
             this.UId = auth.uid;

             return this.db.object('users/' + this.UId);
        }).map(data => {
             if (data.Livello != undefined)
                 this.Utente = data;
             else
                 this.Utente = undefined;
             console.log(this.Utente) ;
             if (this.Utente == undefined)
                 return this.createNewUser();
             return null;
        });
    }
}

then you don't have the overhead of the promise. when you then subscribe to the getUserData() observable, you will get whatever the last maping function returns. so right now you would get the return value of this.createNewUser(); if this.Utente was undefined before. otherwise null.

you would access it the same way, by subscribing to it:

this.statoutenteService.getUserData().subscribe(user => {...})

Hope that will help you.


来源: stackexchange

问:
Python gives me "None" when trying to print a function
I am quite new to python, having only toyed with it for a few days now. I am trying to cobble together a program to show off a battle system I had in mind. My issue is that I keep getting "None" produced when I try to print

```<code>import os
class Player():
    def __init__(self, name, hp, maxhp, strength, intel, charm, level):
        self.name = name
        self.hp = hp
        self.maxhp = maxhp
        self.strength = 10
        self.intel = intel
        self.charm = charm
    self.level = level
    def attack(self, Enemy):
        Enemy.hp -= self.strength

class Steve():
    def __init__(self, name, hp, maxhp, strength, intel, charm, level):
        self.name = name
        self.hp = hp
        self.maxhp = maxhp
        self.strength = strength
        self.intel = intel
    self.charm = charm
    self.level = level

class Barry():
    def __init__(self, name, hp, maxhp, strength, intel, charm, level):
        self.name = name
        self.hp = hp
        self.maxhp = maxhp
        self.strength = strength
        self.intel = intel
        self.charm = charm
        self.level = level
def Start():
    Player.hp = 100
    Player.maxhp = 200
    Player.strength = 30
    Player.intel = 10
    Player.charm = 43
    Player.level = 23
   nameSelection()

def nameSelection():
    os.system('cls')
    Player.name = input("Please enter your name\n==>")
    print("==>")
    gameStart()

def gameStart():
    os.system('cls')
    global Enemy
    print ("Player Name:",Player.name)
    print ("Who would you like to fight?")
    print ("1.)Steve")
    print ("2.)Barry")
    print ("3.)Change your name")
    option = input("==>")
    if option == "1":
        Enemy = Steve("Steve", 100, 200, 10, 20, 30, 50)
        fight()
    elif option == "2":
        Enemy = Barry("Barry", 100, 200, 10, 20, 30, 50)
        fight()
    elif option == "3":
        nameSelection()

def attack():
    Enemy.hp -= Player.strength

def fight():
    os.system('cls')
    while Enemy.hp > 0:
        os.system('cls')
        print(CharacterStats())
        print ("1.) Attack")
        print ("2.) Run")
        option = input("==>")
        if option == "1":
            attack()
            print (Enemy.hp)
    print ("You did it! You have defeated", Enemy.name,"!")
    gameStart()

def CharacterStats():
    print ("You now face", Enemy.name)
    print ("His current health is", Enemy.hp,"/",Enemy.maxhp)
    print ("His strength is", Enemy.strength)
    print ("His intelligence is", Enemy.intel)
    print ("His charm is", Enemy.charm)
    print ("He is level", Enemy.level)
Start()
</code>```

When I get to a fight encoutner with one of the two options, I get

```<code>You now face Steve
His current health is 100 / 200
His strength is 10
His intelligence is 20
His charm is 30
He is level 50
None
1.) Attack
2.) Run
==>
</code>```

I have read that return could fix it, but I can't seem to get return to give me the desired results I was looking for, both how it looks different went printed in to the player, and it only returns one of these lines of stats. I may be getting some of my terms wrong, I hope I am being clear on what my issue is.

答:
You are getting None because you are printing the function, where you should just call the function, your function doesn't return anything and that is why you are getting None.
Change this line:

```<code>print(CharacterStats())
</code>```

to:

```<code>CharacterStats()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am quite new to python, having only toyed with it for a few days now. I am trying to cobble together a program to show off a battle system I had in mind. My issue is that I keep getting "None" produced when I try to print

import os
class Player():
    def __init__(self, name, hp, maxhp, strength, intel, charm, level):
        self.name = name
        self.hp = hp
        self.maxhp = maxhp
        self.strength = 10
        self.intel = intel
        self.charm = charm
    self.level = level
    def attack(self, Enemy):
        Enemy.hp -= self.strength

class Steve():
    def __init__(self, name, hp, maxhp, strength, intel, charm, level):
        self.name = name
        self.hp = hp
        self.maxhp = maxhp
        self.strength = strength
        self.intel = intel
    self.charm = charm
    self.level = level

class Barry():
    def __init__(self, name, hp, maxhp, strength, intel, charm, level):
        self.name = name
        self.hp = hp
        self.maxhp = maxhp
        self.strength = strength
        self.intel = intel
        self.charm = charm
        self.level = level
def Start():
    Player.hp = 100
    Player.maxhp = 200
    Player.strength = 30
    Player.intel = 10
    Player.charm = 43
    Player.level = 23
   nameSelection()

def nameSelection():
    os.system('cls')
    Player.name = input("Please enter your name\n==>")
    print("==>")
    gameStart()

def gameStart():
    os.system('cls')
    global Enemy
    print ("Player Name:",Player.name)
    print ("Who would you like to fight?")
    print ("1.)Steve")
    print ("2.)Barry")
    print ("3.)Change your name")
    option = input("==>")
    if option == "1":
        Enemy = Steve("Steve", 100, 200, 10, 20, 30, 50)
        fight()
    elif option == "2":
        Enemy = Barry("Barry", 100, 200, 10, 20, 30, 50)
        fight()
    elif option == "3":
        nameSelection()

def attack():
    Enemy.hp -= Player.strength

def fight():
    os.system('cls')
    while Enemy.hp > 0:
        os.system('cls')
        print(CharacterStats())
        print ("1.) Attack")
        print ("2.) Run")
        option = input("==>")
        if option == "1":
            attack()
            print (Enemy.hp)
    print ("You did it! You have defeated", Enemy.name,"!")
    gameStart()

def CharacterStats():
    print ("You now face", Enemy.name)
    print ("His current health is", Enemy.hp,"/",Enemy.maxhp)
    print ("His strength is", Enemy.strength)
    print ("His intelligence is", Enemy.intel)
    print ("His charm is", Enemy.charm)
    print ("He is level", Enemy.level)
Start()

When I get to a fight encoutner with one of the two options, I get

You now face Steve
His current health is 100 / 200
His strength is 10
His intelligence is 20
His charm is 30
He is level 50
None
1.) Attack
2.) Run
==>

I have read that return could fix it, but I can't seem to get return to give me the desired results I was looking for, both how it looks different went printed in to the player, and it only returns one of these lines of stats. I may be getting some of my terms wrong, I hope I am being clear on what my issue is.

Body:
You are getting None because you are printing the function, where you should just call the function, your function doesn't return anything and that is why you are getting None.
Change this line:

print(CharacterStats())

to:

CharacterStats()


问:
MacOS - how to get process user/owner with PID using C/C++?
I have been using proc_info.h and similar files to get information about my processes like paths, ppids, names, etc. Now I need to get the user's who own those processes using C/C++. How can I do this? in proc_info.h I see the struct called proc_regioninfo which has a member pri_user_tag which might be what I am looking for but I'm cant figure out how to populate a struct of ````proc_regioninfo```. I've looked everywhere online and can't find an answer.

I've been digging around in this part of my file system trying to find stuff: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift-migrator/sdks/MacOSX.sdk/usr/include so maybe that will help you find things.

this question How to programatically get uid from pid in osx using c++? has an answer but I can't figure out how to install libproc-dev like the person suggests, nor can my system figure out what to do with #include <proc/readproc.h>.

If you have any idea I would greatly appreciate it!

答: If you are using XCode (to what your digging in the file systems hints at) and if it is an option to write a mixed Objective-C / C++ - app, you could use Objective-C's NSProcessInfo-object, which provides features like userName of fullUserName . A way how to use NSProcessInfo is described in this SO answer. Hope it helps.


问:
What is the difference between Azure ACS and Azure AD B2C?
I need to add a custom identity provider to Azure B2C and unsure how to do this.

I know this is possible in Azure ACS, but not sure if B2C is just a "prettier" layer on top of ACS.

Can anyone clarify the difference, and perhaps tell me how I can create a custom IDP for a social network not listed in B2C?

答:
The ability to add custom identity providers is now in public preview with "Identity Experience Framework" feature.
You can add custom policies to integrate with any SAML, OIDC or OAuth based providers, so you can effectively replace ACS with AAD B2C.

B2C Custom Policies Overview


问:
Add affiliate URL query parameter to all links of a domain on a single page in Wordpress
I am preparing a page on my wordpress site where I will post coupons and product urls for a website I am an affiliate of.

Instead of creating affiliate links by hand on every URL, I would like to automatically add the affiliate query parameter on every URL of this particular domain.

The urls might be:

```<code>example.com
example.com/
example.com/cell-phones-c_11293/
example.com/cell-phones/pp_617010.html?wid=4
</code>```

The query parameter I want to add is ?lkid=12345678 (the same for every URL).

```<code>example.com?lkid=12345678
example.com/?lkid=12345678
example.com/cell-phones-c_11293/?lkid=12345678
example.com/cell-phones/pp_617010.html?wid=4&lkid=10823628
</code>```

I want this functionality only for this particular page, not for every post on Wordpress, so I wouldn't like to add the code to the functions.php, or install a plugin just for this single page.

Is it possible to add it as a header or body script to the page through the "Scripts" screen option at the editor?

I have found the following code from this answer,

```<code><script>
var $links = $('a'); // get all anchor tags

// loop through each anchor tag
$.each($links, function(index, item){
    var url = $(this).attr('href'); // var for value of href attribute
            // use regex to match your domain
            var pattern = new RegExp(/(example.com\/)(.*)/i);
            if(pattern.test(url))
                $(this).attr('href', url + '?lkid=12345678');
                // append ?lkid=12345678 if url contains example
});
</script>
</code>```

And the following code from this answer

```<code><script>
function updateQueryStringParameter(uri, key, value) {
  var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
  var separator = uri.indexOf('?') !== -1 ? "&" : "?";
  if (uri.match(re)) {
    return uri.replace(re, '$1' + key + "=" + value + '$2');
  }
  else {
    return uri + separator + key + "=" + value;
  }
}
</script>
</code>```

...but I unfortunately I don't know enough programming to make them work for my case.

答:
First answer looks to work except if the href already has some parameters (?x=y). Also, it's advisable to put jQuery code inside .ready function. And last, in wordpress by default you need to use jQuery instead of $ alias, or pass $ into the function, which I'm doing here:

```<code><script>
jQuery(document).ready(function( $ ){
    var $links = $('a'); // get all anchor tags

    // loop through each anchor tag
    $.each($links, function(index, item){
        var url = $(this).attr('href'); // var for value of href attribute
            // use regex to match your domain
            var pattern = new RegExp(/(example.com\/)(.*)/i);
            if(pattern.test(url))
                var chr = url.indexOf("?") == -1 ? "?" : "&"; // will be "&" if "?" in url
                $(this).attr('href', url + chr + 'lkid=12345678');
                // append ?lkid=12345678 if url contains example
    });
});
</script>
</code>```

Give it a shot and if it works for you I'll make some improvements for the parameters.

Body:
I am preparing a page on my wordpress site where I will post coupons and product urls for a website I am an affiliate of.

Instead of creating affiliate links by hand on every URL, I would like to automatically add the affiliate query parameter on every URL of this particular domain.

The urls might be:

example.com
example.com/
example.com/cell-phones-c_11293/
example.com/cell-phones/pp_617010.html?wid=4

The query parameter I want to add is ?lkid=12345678 (the same for every URL).

example.com?lkid=12345678
example.com/?lkid=12345678
example.com/cell-phones-c_11293/?lkid=12345678
example.com/cell-phones/pp_617010.html?wid=4&lkid=10823628

I want this functionality only for this particular page, not for every post on Wordpress, so I wouldn't like to add the code to the functions.php, or install a plugin just for this single page.

Is it possible to add it as a header or body script to the page through the "Scripts" screen option at the editor?

I have found the following code from this answer,

And the following code from this answer

...but I unfortunately I don't know enough programming to make them work for my case.

Body:
First answer looks to work except if the href already has some parameters (?x=y). Also, it's advisable to put jQuery code inside .ready function. And last, in wordpress by default you need to use jQuery instead of $ alias, or pass $ into the function, which I'm doing here:

<script>
jQuery(document).ready(function( $ ){
    var $links = $('a'); // get all anchor tags

    // loop through each anchor tag
    $.each($links, function(index, item){
        var url = $(this).attr('href'); // var for value of href attribute
            // use regex to match your domain
            var pattern = new RegExp(/(example.com\/)(.*)/i);
            if(pattern.test(url))
                var chr = url.indexOf("?") == -1 ? "?" : "&"; // will be "&" if "?" in url
                $(this).attr('href', url + chr + 'lkid=12345678');
                // append ?lkid=12345678 if url contains example
    });
});
</script>

Give it a shot and if it works for you I'll make some improvements for the parameters.


问:
How to make value in a column to look back at previous values?
I'm a beginner, so I probably don't use the correct terms when explaining my problem. Hope you can help me anyway.

I have a table consisting of EP.Detect (Movement in entrance), LP.Detect (movement in room), R.Detect (the door can etiher be "open" or "closed" or "moved") and presence is 0 (false) or 1 (true).

The purpose with this is to know when a person is present. And I have done that by making some conditions. My code works fine, except when it come to "closed".

My problem is that it doesn't understand that when R.Detect is closed and EP.Detect and LP.Detect is TimeOut, it doesn't mean that Presence is 0. Because the door haven't been open or moved, therefore the person is still present.

```<code>  occupied=FALSE
        j<-1
        i<-1
        startRow=1
        endRow=1
        n=1
        for (n in 1:length(dft1$Time)){
          endRow=n
        if(dft1$R.Detect[n]=="moved" |dft1$R.Detect[n]=="open" | dft1$R.Detect[n]=="closed"){

            if(n>1){
              for(i in startRow:endRow){
                if(dft1$R.Detect[n]=="moved" | dft1$R.Detect[n]=="open" ){occupied=TRUE}
                if(dft1$EP.Detect[i]=="Movement" & dft1$LP.Detect[i]=="Movement"){occupied=TRUE}
                if(dft1$EP.Detect[i]=="TimeOut" & dft1$LP.Detect[i]=="Movement"){occupied=TRUE}
                if(dft1$EP.Detect[i]=="Movement" & dft1$LP.Detect[i]=="TimeOut"){occupied=TRUE}
              }
            }
            for(j in startRow:endRow){dft1$Presence[j]<-occupied}
          }
          startRow=endRow
          n=n+1
          occupied=FALSE
        }
</code>```

Tried to upload it as a .txt

It is easier to understand when you look in the picture

```<code>structure(list(EP.Detect = c("TimeOut", "TimeOut", "TimeOut",
"Movement", "Movement", "Movement", "TimeOut", "TimeOut", "Movement",
"Movement", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "Movement",
"Movement", "Movement", "Movement", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "Movement", "Movement", "Movement",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "Movement", "Movement",
"TimeOut", "TimeOut", "TimeOut", "Movement", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "Movement", "Movement",
"Movement", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "Movement",
"Movement", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "Movement", "Movement", "Movement",
"Movement", "Movement", "TimeOut", "Movement", "TimeOut", "TimeOut",
"TimeOut"), LP.Detect = c("TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "Movement",
"Movement", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "Movement", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "Movement", "Movement", "Movement",
"Movement", "Movement", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "Movement", "Movement", "Movement", "Movement", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "Movement",
"Movement", "Movement", "Movement", "TimeOut", "Movement", "Movement",
"Movement", "Movement", "Movement", "TimeOut", "TimeOut", "TimeOut"
), R.Detect = c("closed", "closed", "open", "moved", "moved",
"closed", "closed", "closed", "moved", "moved", "closed", "closed",
"closed", "closed", "closed", "closed", "moved", "moved", "closed",
"closed", "closed", "closed", "closed", "closed", "closed", "moved",
"moved", "closed", "closed", "closed", "closed", "closed", "closed",
"closed", "closed", "closed", "closed", "closed", "closed", "closed",
"closed", "closed", "closed", "closed", "closed", "closed", "closed",
"closed", "closed", "moved", "moved", "closed", "closed", "closed",
"closed", "closed", "closed", "closed", "closed", "closed", "closed",
"closed", "closed", "closed", "closed", "closed", "closed", "closed",
"moved", "moved", "closed", "closed", "closed", "closed", "closed",
"closed", "closed", "closed", "closed", "closed", "closed", "closed",
"closed", "closed", "closed", "closed", "closed", "closed", "closed",
"closed", "closed", "closed", "closed", "closed", "closed", "closed",
"closed", "closed", "closed", "closed", "closed", "closed", "closed",
"closed", "closed", "closed", "closed", "closed", "closed", "closed",
"closed", "closed", "closed", "closed", "closed", "closed", "closed",
"closed", "closed", "closed", "closed", "closed", "closed", "closed",
"closed", "closed", "closed", "closed", "closed", "closed", "closed",
"closed", "closed", "closed", "closed", "closed", "closed", "closed",
"closed", "closed", "closed", "closed", "closed", "closed", "closed",
"closed", "closed", "closed", "closed", "closed", "closed", "closed",
"closed", "moved", "closed", "closed", "closed", "closed", "closed",
"closed", "closed", "closed", "closed", "closed", "closed", "closed",
"closed", "closed", "closed", "open", "closed", "closed", "closed",
"closed", "moved", "closed", "closed", "closed"), Presence = c(0,
0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0,
0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 0, 0, 0)), .Names = c("EP.Detect", "LP.Detect",
"R.Detect", "Presence"), row.names = 25550:25727, class = "data.frame")
</code>```

答:
You may be able to accomplish this much more cleanly with a dplyr case statement without having to use any for loops.

```<code>library(dplyr)

dft1 <- dft1 %>%
        mutate(Presence = case_when(# If R.Detect is "moved" or "open" or "closed"
                                    # AND (   (EP.Detect on previous row is "Movement" AND LP.Detect on previous row is "Movement" or "TimeOut)
                                    #      OR (EP.Detect on previous row is "TimeOut" AND LP.Detect on previous row is "Movement")
                                    #     )
                                    # THEN set Presence to 1
                                    .$R.Detect %in% c("moved","open", "closed")
                                    & (  (lag(.$EP.Detect) == "Movement" & lag(.$LP.Detect) %in% c("Movement","TimeOut"))
                                       | (lag(.$EP.Detect) == "TimeOut" & lag(.$LP.Detect) == "Movement")
                                      ) ~ 1,
                                    # All other cases, set Presence to 0
                                    TRUE ~ 0
                                   )
              )
</code>```

If you do have to process this through a for loop for a particular reason, then this simplified loop should get you what you need

```<code># Loop through all rows in the dataframe starting at row 2
for(i in 2:nrow(dft1)){
  # If R.Detect is either "moved", "open", or "closed"
  # AND (   (EP.Detect on the previous row is "Movement" AND LP.Detect on the previous row is either "Movement" or "Timeout")
  #      OR (EP.Detect on the previous row is "TimeOut" AND LP.Detect on the previous row is "Movement")
  #     )
  # Then set Presence to 1
  # Else set Presence to 0
  if(dft1$R.Detect[i] %in% c("moved","open","closed")
     & (  (dft1$EP.Detect[i - 1] == "Movement" & dft1$LP.Detect[i - 1] %in% c("Movement","TimeOut") )
        | (dft1$EP.Detect[i - 1] == "TimeOut" & dft1$LP.Detect[i - 1] == "Movement")
       )
  ){
    dft1$Presence[i] <- 1
  } else{
    dft1$Presence[i] <- 0
  }
}
</code>```

Body:
I'm a beginner, so I probably don't use the correct terms when explaining my problem. Hope you can help me anyway.

I have a table consisting of EP.Detect (Movement in entrance), LP.Detect (movement in room), R.Detect (the door can etiher be "open" or "closed" or "moved") and presence is 0 (false) or 1 (true).

The purpose with this is to know when a person is present. And I have done that by making some conditions. My code works fine, except when it come to "closed".

My problem is that it doesn't understand that when R.Detect is closed and EP.Detect and LP.Detect is TimeOut, it doesn't mean that Presence is 0. Because the door haven't been open or moved, therefore the person is still present.

  occupied=FALSE
        j<-1
        i<-1
        startRow=1
        endRow=1
        n=1
        for (n in 1:length(dft1$Time)){
          endRow=n
        if(dft1$R.Detect[n]=="moved" |dft1$R.Detect[n]=="open" | dft1$R.Detect[n]=="closed"){

            if(n>1){
              for(i in startRow:endRow){
                if(dft1$R.Detect[n]=="moved" | dft1$R.Detect[n]=="open" ){occupied=TRUE}
                if(dft1$EP.Detect[i]=="Movement" & dft1$LP.Detect[i]=="Movement"){occupied=TRUE}
                if(dft1$EP.Detect[i]=="TimeOut" & dft1$LP.Detect[i]=="Movement"){occupied=TRUE}
                if(dft1$EP.Detect[i]=="Movement" & dft1$LP.Detect[i]=="TimeOut"){occupied=TRUE}
              }
            }
            for(j in startRow:endRow){dft1$Presence[j]<-occupied}
          }
          startRow=endRow
          n=n+1
          occupied=FALSE
        }

Tried to upload it as a .txt

It is easier to understand when you look in the picture

structure(list(EP.Detect = c("TimeOut", "TimeOut", "TimeOut",
"Movement", "Movement", "Movement", "TimeOut", "TimeOut", "Movement",
"Movement", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "Movement",
"Movement", "Movement", "Movement", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "Movement", "Movement", "Movement",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "Movement", "Movement",
"TimeOut", "TimeOut", "TimeOut", "Movement", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "Movement", "Movement",
"Movement", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "Movement",
"Movement", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "Movement", "Movement", "Movement",
"Movement", "Movement", "TimeOut", "Movement", "TimeOut", "TimeOut",
"TimeOut"), LP.Detect = c("TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "Movement",
"Movement", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "Movement", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "Movement", "Movement", "Movement",
"Movement", "Movement", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "Movement", "Movement", "Movement", "Movement", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut",
"TimeOut", "TimeOut", "TimeOut", "TimeOut", "TimeOut", "Movement",
"Movement", "Movement", "Movement", "TimeOut", "Movement", "Movement",
"Movement", "Movement", "Movement", "TimeOut", "TimeOut", "TimeOut"
), R.Detect = c("closed", "closed", "open", "moved", "moved",
"closed", "closed", "closed", "moved", "moved", "closed", "closed",
"closed", "closed", "closed", "closed", "moved", "moved", "closed",
"closed", "closed", "closed", "closed", "closed", "closed", "moved",
"moved", "closed", "closed", "closed", "closed", "closed", "closed",
"closed", "closed", "closed", "closed", "closed", "closed", "closed",
"closed", "closed", "closed", "closed", "closed", "closed", "closed",
"closed", "closed", "moved", "moved", "closed", "closed", "closed",
"closed", "closed", "closed", "closed", "closed", "closed", "closed",
"closed", "closed", "closed", "closed", "closed", "closed", "closed",
"moved", "moved", "closed", "closed", "closed", "closed", "closed",
"closed", "closed", "closed", "closed", "closed", "closed", "closed",
"closed", "closed", "closed", "closed", "closed", "closed", "closed",
"closed", "closed", "closed", "closed", "closed", "closed", "closed",
"closed", "closed", "closed", "closed", "closed", "closed", "closed",
"closed", "closed", "closed", "closed", "closed", "closed", "closed",
"closed", "closed", "closed", "closed", "closed", "closed", "closed",
"closed", "closed", "closed", "closed", "closed", "closed", "closed",
"closed", "closed", "closed", "closed", "closed", "closed", "closed",
"closed", "closed", "closed", "closed", "closed", "closed", "closed",
"closed", "closed", "closed", "closed", "closed", "closed", "closed",
"closed", "closed", "closed", "closed", "closed", "closed", "closed",
"closed", "moved", "closed", "closed", "closed", "closed", "closed",
"closed", "closed", "closed", "closed", "closed", "closed", "closed",
"closed", "closed", "closed", "open", "closed", "closed", "closed",
"closed", "moved", "closed", "closed", "closed"), Presence = c(0,
0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0,
0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 0, 0, 0)), .Names = c("EP.Detect", "LP.Detect",
"R.Detect", "Presence"), row.names = 25550:25727, class = "data.frame")

Body:
You may be able to accomplish this much more cleanly with a dplyr case statement without having to use any for loops.

library(dplyr)

dft1 <- dft1 %>%
        mutate(Presence = case_when(# If R.Detect is "moved" or "open" or "closed"
                                    # AND (   (EP.Detect on previous row is "Movement" AND LP.Detect on previous row is "Movement" or "TimeOut)
                                    #      OR (EP.Detect on previous row is "TimeOut" AND LP.Detect on previous row is "Movement")
                                    #     )
                                    # THEN set Presence to 1
                                    .$R.Detect %in% c("moved","open", "closed")
                                    & (  (lag(.$EP.Detect) == "Movement" & lag(.$LP.Detect) %in% c("Movement","TimeOut"))
                                       | (lag(.$EP.Detect) == "TimeOut" & lag(.$LP.Detect) == "Movement")
                                      ) ~ 1,
                                    # All other cases, set Presence to 0
                                    TRUE ~ 0
                                   )
              )

If you do have to process this through a for loop for a particular reason, then this simplified loop should get you what you need

# Loop through all rows in the dataframe starting at row 2
for(i in 2:nrow(dft1)){
  # If R.Detect is either "moved", "open", or "closed"
  # AND (   (EP.Detect on the previous row is "Movement" AND LP.Detect on the previous row is either "Movement" or "Timeout")
  #      OR (EP.Detect on the previous row is "TimeOut" AND LP.Detect on the previous row is "Movement")
  #     )
  # Then set Presence to 1
  # Else set Presence to 0
  if(dft1$R.Detect[i] %in% c("moved","open","closed")
     & (  (dft1$EP.Detect[i - 1] == "Movement" & dft1$LP.Detect[i - 1] %in% c("Movement","TimeOut") )
        | (dft1$EP.Detect[i - 1] == "TimeOut" & dft1$LP.Detect[i - 1] == "Movement")
       )
  ){
    dft1$Presence[i] <- 1
  } else{
    dft1$Presence[i] <- 0
  }
}


问:
List Of String not inserting data
Running into an issue where i am trying to Insert() data into a list Of String but for some reason it is not inserting the data.

```<code>Private Sub Build(param 1, param 2, param 3,)
  Dim dataList As New List(Of String)
  Dim charcode as String = ""
  Dim index As Integer = 0

  For i As Integer = 0 To rowCount - 1
    dataList.Add("data" & i)
  Next

  'dataNum is of int value (zero based) from 0 - whatever number
  For Each Item As String In root.Subfields
    charcode = GetChar(Item, 2)
    If Not charCodes.Contains(charcode) Then
      dataList(dataNum).Insert(index, Item)
      index += 1
    End If
  Next
End Sub
</code>```

Using Visual Studio debugger i can see that the dataList is being populated

But when we get down to the For Each the data is not being populated into the list under the appropriate collection (data1, data2)

What's going on here? Surely this should work (right?).

thank you.

EDIT:

Here is an image of what i am trying to accomplish:

as you can see i have a main collection with collections or sub fields inside that one.

答:
It sounds from the question text like you're trying to insert a whole new string as a new entry in your list. Look carefully at this line:

```<code>dataList(dataNum).Insert(index, Item)
</code>```

When this code executes, it first retrieves the List(Of String) object referred to by the dataList variable, and then looks up the specific string object at index dataNum. Now you have a single string (not a List anymore) and you call the string's Insert() method. It's not the Insert() method for the list.

To fix this, I'd need to know more about how you're using the index variable that's not referred to or declared anywhere else in the code or the question text. It's not clear how you expect this to be used.

Or maybe you really wanted just a string. If so, that's not what your question text is asking for. But if you're really trying to insert additional text into that specific string, you still have a problem. String objects in .Net don't change (we say they are "immutable"). When you use a method like Insert(), rather than changing that string instance, it produces and returns a new string object. With that in mind, you need to assign that new string somewhere. That would look like this:

```<code>dataList(dataNum) = dataList(dataNum).Insert(index, Item)
</code>```

But, again, that's not what the text of your question is asking for. I'm including it here because it better matches the code sample.

Title: List Of String not inserting data

Body:
Running into an issue where i am trying to Insert() data into a list Of String but for some reason it is not inserting the data.

Private Sub Build(param 1, param 2, param 3,)
  Dim dataList As New List(Of String)
  Dim charcode as String = ""
  Dim index As Integer = 0

  For i As Integer = 0 To rowCount - 1
    dataList.Add("data" & i)
  Next

  'dataNum is of int value (zero based) from 0 - whatever number
  For Each Item As String In root.Subfields
    charcode = GetChar(Item, 2)
    If Not charCodes.Contains(charcode) Then
      dataList(dataNum).Insert(index, Item)
      index += 1
    End If
  Next
End Sub

Using Visual Studio debugger i can see that the dataList is being populated

But when we get down to the For Each the data is not being populated into the list under the appropriate collection (data1, data2)

What's going on here? Surely this should work (right?).

thank you.

EDIT:

Here is an image of what i am trying to accomplish:

as you can see i have a main collection with collections or sub fields inside that one.

Body:
It sounds from the question text like you're trying to insert a whole new string as a new entry in your list. Look carefully at this line:

dataList(dataNum).Insert(index, Item)

When this code executes, it first retrieves the List(Of String) object referred to by the dataList variable, and then looks up the specific string object at index dataNum. Now you have a single string (not a List anymore) and you call the string's Insert() method. It's not the Insert() method for the list.

To fix this, I'd need to know more about how you're using the index variable that's not referred to or declared anywhere else in the code or the question text. It's not clear how you expect this to be used.

Or maybe you really wanted just a string. If so, that's not what your question text is asking for. But if you're really trying to insert additional text into that specific string, you still have a problem. String objects in .Net don't change (we say they are "immutable"). When you use a method like Insert(), rather than changing that string instance, it produces and returns a new string object. With that in mind, you need to assign that new string somewhere. That would look like this:

dataList(dataNum) = dataList(dataNum).Insert(index, Item)

But, again, that's not what the text of your question is asking for. I'm including it here because it better matches the code sample.


问:
How do I swap this link out with Rails?
I am trying to take this link..

```<code>http://www.youtube.com/watch?v=4lzi_3SM9-o
</code>```

And turn it into this:

```<code>http://www.youtube.com/v/4lzi_3SM9-o
</code>```

To do this I need some way to capture watch?v= and switch it with v/

And I would like to accomplish this in my model with def tube_link

Any ideas?

答:
No need for regex, just use string replacement:

```<code>url["watch?v="] = "v/"
</code>```

But be warned that you might get an index error if you index on something that isn't in the string. (See here for more information.)

Edit: Something like this might be more readable (and more reliable):

```<code>newUrl = oldUrl.gsub("watch?v=", "v/")
</code>```

ContentLicense: CC BY-SA 2.5

Title: How do I swap this link out with Rails?

Body:
I am trying to take this link..

http://www.youtube.com/watch?v=4lzi_3SM9-o

And turn it into this:

http://www.youtube.com/v/4lzi_3SM9-o

To do this I need some way to capture watch?v= and switch it with v/

And I would like to accomplish this in my model with def tube_link

Any ideas?

Body:
No need for regex, just use string replacement:

url["watch?v="] = "v/"

But be warned that you might get an index error if you index on something that isn't in the string. (See here for more information.)

Edit: Something like this might be more readable (and more reliable):

newUrl = oldUrl.gsub("watch?v=", "v/")


问:
How can I render html in validation message in ASP.NET MVC?
I am currently developing a registration page. When user already exists I want to provide login and reset password links for user in error message for email field. In controller I have:

```<code>[HttpPost]
public ActionResult Register(RegistrationModel registration)
{
  ...

  if(userExists)
  {
      const string errorMessage = "User already exist. You can <a href="/account/login">login</a> ...";
      ModelState.AddModelError("Email", errorMessage);
      return View("Register", registration);
  }
}
</code>```

But when I try to output this message in view I do not get what I expect. I get html markup like plain text. I've already tried:

```<code>@using(Html.BeginForm())
{
<div>@Html.TextBoxFor(m => m.Email)
@{
   @Html.ValidationMessageFor(m => m.Email)

   ...

   @Html.Raw(Html.ValidationMessageFor(m => m.Email))

   ...

   string validationMessage = Html.ValidationMessageFor(m => m.Email).ToString();
   @Html.Raw(validationMessage)

   ...

   string validationMessage = Html.ValidationMessageFor(m => m.Email).ToHtmlString();
   @Html.Raw(validationMessage)

   ...

   string validationMessage = Html.ValidationMessageFor(m => m.Email).ToString();
   @(new HtmlString(validationMessage))

   ...

   string validationMessage = Html.ValidationMessageFor(m => m.Email).ToHtmlString();
   @(new HtmlString(validationMessage))

   ...

   string validationMessage = Html.ValidationMessageFor(m => m.Email).ToString();
   @(new MvcHtmlString(validationMessage))

   ...

   string validationMessage = Html.ValidationMessageFor(m => m.Email).ToHtmlString();
   @(new MvcHtmlString(validationMessage))

}
</div>
}
</code>```

答:
Found this post while figuring this out myself using ASP.NET Core.

What I ended up doing was adding my part of my validation message in modelstate.AddError(), and separately adding to ViewData the bit that had the Html I wanted to render, like so:

ViewData["myKey"]= "My html";

It feels pretty ugly and there's probably better ways of doing it, but for my very limited needs, this fit the bill nicely.

Body:
I am currently developing a registration page. When user already exists I want to provide login and reset password links for user in error message for email field. In controller I have:

[HttpPost]
public ActionResult Register(RegistrationModel registration)
{
  ...

  if(userExists)
  {
      const string errorMessage = "User already exist. You can login ...";
      ModelState.AddModelError("Email", errorMessage);
      return View("Register", registration);
  }
}

But when I try to output this message in view I do not get what I expect. I get html markup like plain text. I've already tried:

@using(Html.BeginForm())
{

@Html.TextBoxFor(m => m.Email)
@{
   @Html.ValidationMessageFor(m => m.Email)

   ...

   @Html.Raw(Html.ValidationMessageFor(m => m.Email))

   ...

   string validationMessage = Html.ValidationMessageFor(m => m.Email).ToString();
   @Html.Raw(validationMessage)

   ...

   string validationMessage = Html.ValidationMessageFor(m => m.Email).ToHtmlString();
   @Html.Raw(validationMessage)

   ...

   string validationMessage = Html.ValidationMessageFor(m => m.Email).ToString();
   @(new HtmlString(validationMessage))

   ...

   string validationMessage = Html.ValidationMessageFor(m => m.Email).ToHtmlString();
   @(new HtmlString(validationMessage))

   ...

   string validationMessage = Html.ValidationMessageFor(m => m.Email).ToString();
   @(new MvcHtmlString(validationMessage))

   ...

   string validationMessage = Html.ValidationMessageFor(m => m.Email).ToHtmlString();
   @(new MvcHtmlString(validationMessage))

}

}


问:
How to extract values of a dataframe based on a vector containing the row names of the dataframe?
I have a data frame df, which is as follows. The left-hand side is the row names and the first column is the corresponding values.

```<code>              v1
 a177:a1297  0.1
 a177:a842   0.2
 a177:a796   0.4
 a24:a1437   0.3
 a24:a1256   0.6
 a24:a762    0.7
</code>```

I have a vector of characters which are the row names of df. The vector is dfnames

```<code>  str(dfnames)
  chr [1:5] "a177:a1297" "a177:a842" "a177:a796" "a24:a1437" "a24:a1256" "a24:a762"
</code>```

If I extract one value based on a specific row name, it would be:

```<code>    df["a177:a1297",]
   [1]  0.1
</code>```

Now I want to extract all the values of df based on dfnames

```<code>  df[dfnames,]
  [1] NA NA NA NA NA NA
</code>```

Could anyone tell me how to extract the values of df based on a vector that contains the row names of df?

答:
You can do:</p>

```<code>df[which(row.names(df) %in% dfnames),]
</code>```

Body:
I have a data frame df, which is as follows. The left-hand side is the row names and the first column is the corresponding values.

              v1
 a177:a1297  0.1
 a177:a842   0.2
 a177:a796   0.4
 a24:a1437   0.3
 a24:a1256   0.6
 a24:a762    0.7

I have a vector of characters which are the row names of df. The vector is dfnames

  str(dfnames)
  chr [1:5] "a177:a1297" "a177:a842" "a177:a796" "a24:a1437" "a24:a1256" "a24:a762"

If I extract one value based on a specific row name, it would be:

    df["a177:a1297",]
   [1]  0.1

Now I want to extract all the values of df based on dfnames

  df[dfnames,]
  [1] NA NA NA NA NA NA

Could anyone tell me how to extract the values of df based on a vector that contains the row names of df?

Body:
You can do:

df[which(row.names(df) %in% dfnames),]


答:
Strings are immutable. If you call Insert on a string you need to catch the return value of the insert where the change is returned. The original string is not changed. By the way, do you realize that you are Inserting into a string and not into the list?

If you want to insert a string inside the current list you need something like this (It is not very clear from the code above if you need to use the variable datanum or the variable index to choose the appropriate position in the list)

```<code>For Each Item As String In root.Subfields
  charcode = GetChar(Item, 2)
  If Not charCodes.Contains(charcode) Then
    dataList.Insert(index, Item)
    index += 1
  End If
Next
</code>```

From your comment below it seems that you want only replace an element of the list with a new value. In this case you can treat the list like it was an array and write something like

```<code>dataList(0) = newItem;
</code>```

Title: List Of String not inserting data

Body:
Strings are immutable. If you call Insert on a string you need to catch the return value of the insert where the change is returned. The original string is not changed. By the way, do you realize that you are Inserting into a string and not into the list?

If you want to insert a string inside the current list you need something like this (It is not very clear from the code above if you need to use the variable datanum or the variable index to choose the appropriate position in the list)

For Each Item As String In root.Subfields
  charcode = GetChar(Item, 2)
  If Not charCodes.Contains(charcode) Then
    dataList.Insert(index, Item)
    index += 1
  End If
Next

From your comment below it seems that you want only replace an element of the list with a new value. In this case you can treat the list like it was an array and write something like

dataList(0) = newItem;


问:
Getting raw binary from mixed Buffer
Having following nodeJS Buffer().toString('utf8'):

```<code>Content-Type: audio/x-ms-wma
Content-Disposition: form-data; name=recordedAudio
\r\n\r\n0&�u�f�\u0011��\u0000�
</code>```

I need to remove headers (Content-Type/Disposition) and get the raw audio data. If I simply replace headers with replace method I am not able to convert UTF-8 audio back to Buffer properly.

How can it be done?

答:
I made it working using buffer-split package:</p>

```<code>var bsplit = require('buffer-split');
var rawData = bsplit(rawDataWithHeaders, new Buffer('\r\n\r\n'))[1];
rawData = bsplit(rawData, new Buffer('\r\n'))[0];
</code>```

Title: Getting raw binary from mixed Buffer

Body:
Having following nodeJS Buffer().toString('utf8'):

Content-Type: audio/x-ms-wma
Content-Disposition: form-data; name=recordedAudio
\r\n\r\n0&�u�f�\u0011��\u0000�

I need to remove headers (Content-Type/Disposition) and get the raw audio data. If I simply replace headers with replace method I am not able to convert UTF-8 audio back to Buffer properly.

How can it be done?

Body:
I made it working using buffer-split package:

var bsplit = require('buffer-split');
var rawData = bsplit(rawDataWithHeaders, new Buffer('\r\n\r\n'))[1];
rawData = bsplit(rawData, new Buffer('\r\n'))[0];


问:
How to tell if a string contains a certain character in JavaScript?
I have a page with a textbox where a user is supposed to enter a 24 character (letters and numbers, case insensitive) registration code.  I used maxlength to limit the user to entering 24 characters.

The registration codes are typically given as groups of characters separated by dashes, but I would like for the user to enter the codes without the dashes.

How can I write my JavaScript code without jQuery to check that a given string that the user inputs does not contain dashes, or better yet, only contains alphanumeric characters?

答:
Use a regular expression to accomplish this.</p>

```<code>function isAlphanumeric( str ) {
 return /^[0-9a-zA-Z]+$/.test(str);
}
</code>```

Body:
Use a regular expression to accomplish this.

function isAlphanumeric( str ) {
 return /^[0-9a-zA-Z]+$/.test(str);
}


问:
MVVM binding many properties
Is there a simpeler way to bind many properties?

So if you have a Person class with properties: lastname, firstname, birthday, gender, title, ...

Now I do this for every property on the ViewModel:

```<code> public string _LastName;
 public string LastName
 {
    get { return _LastName; }
    set { _LastName = value;
          RaisePropertyChanged("LastName"); }
 }
</code>```

And on the XAML page this binding:

```<code> <TextBlock Text="{Binding FirstName}" />
</code>```

Now image if Person object has like 20 properties..
So my question is can I do this in a simpeler way?

答:
You only need to raise the PropertyChanged event from the setter of a data-bound property if you actually intend to update the property dynamically at runtime. Otherwise you could use auto-implemented properties without any custom logic:

```<code>public FirstName { get; set; }
</code>```

There is also a NuGet package called Fody that can turn simple public properties into full INotifyPropertyChanged implementations for you automatically: https://github.com/Fody/PropertyChanged

Title: MVVM binding many properties

Body:
Is there a simpeler way to bind many properties?

So if you have a Person class with properties: lastname, firstname, birthday, gender, title, ...

Now I do this for every property on the ViewModel:

 public string _LastName;
 public string LastName
 {
    get { return _LastName; }
    set { _LastName = value;
          RaisePropertyChanged("LastName"); }
 }

And on the XAML page this binding:

 <TextBlock Text="{Binding FirstName}" />

Now image if Person object has like 20 properties..
So my question is can I do this in a simpeler way?

Body:
You only need to raise the PropertyChanged event from the setter of a data-bound property if you actually intend to update the property dynamically at runtime. Otherwise you could use auto-implemented properties without any custom logic:

public FirstName { get; set; }

There is also a NuGet package called Fody that can turn simple public properties into full INotifyPropertyChanged implementations for you automatically: https://github.com/Fody/PropertyChanged


问:
Access-Control-Allow-Origin is not working in PHP file hosted in Godaddy domain
I am running an angularjs application in my local system apache(http://localhost:8080). Here am trying to hit an API with post method. My API(http://php.mpect.com/demo/login.php) is hosted in godaddy server domain. Its a PHP file. I included

```<code>header('Access-Control-Allow-Origin: *');
</code>```

in my php file, but still am getting

XMLHttpRequest cannot load http://php.mpect.com/demo/login.php.
  Response to preflight request doesn't pass access control check:
  No 'Access-Control-Allow-Origin' header is present on the requested resource.
  Origin 'http://localhost:8080' is therefore not allowed access.

I am new to php and godaddy server. How can I solve this? Is there any way to include headers in godaddy domain? sorry for my english. Can anyone please provide me solution code to acheive this CORS problem. Thanks in advance.

答:
Add the configuration into your .htaccess file and you will be fine. This will ensure that the important CORS headers will set on any request. Ensure you have enabled mod_headers on apache2.

```<code># Always set these headers.
Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Header always set Access-Control-Max-Age "1000"
Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"
</code>```

Body:
I am running an angularjs application in my local system apache(http://localhost:8080). Here am trying to hit an API with post method. My API(http://php.mpect.com/demo/login.php) is hosted in godaddy server domain. Its a PHP file. I included

header('Access-Control-Allow-Origin: *');

in my php file, but still am getting

XMLHttpRequest cannot load http://php.mpect.com/demo/login.php.
  Response to preflight request doesn't pass access control check:
  No 'Access-Control-Allow-Origin' header is present on the requested resource.
  Origin 'http://localhost:8080' is therefore not allowed access.

I am new to php and godaddy server. How can I solve this? Is there any way to include headers in godaddy domain? sorry for my english. Can anyone please provide me solution code to acheive this CORS problem. Thanks in advance.

Body:
Add the configuration into your .htaccess file and you will be fine. This will ensure that the important CORS headers will set on any request. Ensure you have enabled mod_headers on apache2.

# Always set these headers.
Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Header always set Access-Control-Max-Age "1000"
Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"


问:
What's the quickest way to assign a variables based on an array?
What's the quickest way, from a readability/typing standpoint, to assign a value to a specific variable based on a related variable?

```<code>var abbrev;

if(state=='Pennsylvania'){
    abbrev='PA';
}else if(state=='New Jersey'){
    abbrev='NJ';
}else if(state=='Delaware'){
    abbrev='DE';
}
//and so on...
</code>```

I'm trying to avoid making one array for the state name and a another array for the abbreviation because the relationship is lost with separate declarations.

答:
You could use an object for the abbreviation, like

```<code>var abbreviations = {
        'Pennsylvania': 'PA',
        'New Jersey': 'NJ',
        'Delaware': 'DE'
    };
</code>```

Usage:

```<code>abbrev = abbreviations[state];
</code>```

Body:
What's the quickest way, from a readability/typing standpoint, to assign a value to a specific variable based on a related variable?

var abbrev;

if(state=='Pennsylvania'){
    abbrev='PA';
}else if(state=='New Jersey'){
    abbrev='NJ';
}else if(state=='Delaware'){
    abbrev='DE';
}
//and so on...

I'm trying to avoid making one array for the state name and a another array for the abbreviation because the relationship is lost with separate declarations.

Body:
You could use an object for the abbreviation, like

var abbreviations = {
        'Pennsylvania': 'PA',
        'New Jersey': 'NJ',
        'Delaware': 'DE'
    };

Usage:

abbrev = abbreviations[state];


问:
Shortcut for copying Ctrl-C not working in Android Studio
I am able to copy text from other programs and paste it to Android Studio. I am able to right click and copy selected text. I am able to cut text and paste it using shortcut. But while using shortcut Ctrl + C to copy text I am often unable to copy. This is very annoying problem. Does anyone here knows how to solve it?</p>

答: Go to Settings -> Keymap -> And then select Eclipse for Keymaps dropdown view. Generally it is set to MAC OS 10 by default</p>


问:
Overload resolution for multiply inherited operator()
First, consider this C++ code:

```<code>#include <stdio.h>

struct foo_int {
    void print(int x) {
        printf("int %d\n", x);
    }
};

struct foo_str {
    void print(const char* x) {
        printf("str %s\n", x);
    }
};

struct foo : foo_int, foo_str {
    //using foo_int::print;
    //using foo_str::print;
};

int main() {
    foo f;
    f.print(123);
    f.print("abc");
}
</code>```

As expected according to the Standard, this fails to compile, because print is considered separately in each base class for the purpose of overload resolution, and thus the calls are ambiguous. This is the case on Clang (4.0), gcc (6.3) and MSVC (17.0) - see godbolt results here.

Now consider the following snippet, the sole difference of which is that we use operator() instead of print:

```<code>#include <stdio.h>

struct foo_int {
    void operator() (int x) {
        printf("int %d\n", x);
    }
};

struct foo_str {
    void operator() (const char* x) {
        printf("str %s\n", x);
    }
};

struct foo : foo_int, foo_str {
    //using foo_int::operator();
    //using foo_str::operator();
};

int main() {
    foo f;
    f(123);
    f("abc");
}
</code>```

I would expect the results to be identical to the previous case, but it is not the case - while gcc still complains, Clang and MSVC can compile this fine!

Question #1: who is correct in this case? I expect it to be gcc, but the fact that two other unrelated compilers give a consistently different result here makes me wonder whether I'm missing something in the Standard, and things are different for operators when they're not invoked using function syntax.

Also note that if you only uncomment one of the using declarations, but not the other, then all three compilers will fail to compile, because they will only consider the function brought in by using during overload resolution, and thus one of the calls will fail due to type mismatch. Remember this; we'll get back to it later.

Now consider the following code:

```<code>#include <stdio.h>

auto print_int = [](int x) {
    printf("int %d\n", x);
};
typedef decltype(print_int) foo_int;

auto print_str = [](const char* x) {
    printf("str %s\n", x);
};
typedef decltype(print_str) foo_str;

struct foo : foo_int, foo_str {
    //using foo_int::operator();
    //using foo_str::operator();
    foo(): foo_int(print_int), foo_str(print_str) {}
};

int main() {
    foo f;
    f(123);
    f("foo");
}
</code>```

Again, same as before, except now we don't define operator() explicitly, but instead get it from a lambda type. Again, you'd expect the results to be consistent with the previous snippet; and this is true for the case where both using declarations are commented out, or if both are uncommented. But if you only comment out one but not the other, things are suddenly different again: now only MSVC complains as I would expect it to, while Clang and gcc both think it's fine - and use both inherited members for overload resolution, despite only one being brought in by using!

Question #2: who is correct in this case? Again, I'd expect it to be MSVC, but then why do both Clang and gcc disagree? And, more importantly, why this is different from the previous snippet? I would expect the lambda type to behave exactly the same as a manually defined type with overloaded operator()...

答:
Barry got #1 right. Your #2 hit a corner case: captureless nongeneric lambdas have an implicit conversion to function pointer, which got used in the mismatch case. That is, given

```<code>struct foo : foo_int, foo_str {
    using foo_int::operator();
    //using foo_str::operator();
    foo(): foo_int(print_int), foo_str(print_str) {}
} f;

using fptr_str = void(*)(const char*);
</code>```

f("hello") is equivalent to f.operator fptr_str()("hello"), converting the foo to an pointer-to-function and calling that. If you compile at -O0 you can actually see the call to the conversion function in the assembly before it gets optimized away. Put an init-capture in print_str, and you'll see an error since the implicit conversion goes away.

For more, see [over.call.object].

Body:
First, consider this C++ code:

#include <stdio.h>

struct foo_int {
    void print(int x) {
        printf("int %d\n", x);
    }
};

struct foo_str {
    void print(const char* x) {
        printf("str %s\n", x);
    }
};

struct foo : foo_int, foo_str {
    //using foo_int::print;
    //using foo_str::print;
};

int main() {
    foo f;
    f.print(123);
    f.print("abc");
}

As expected according to the Standard, this fails to compile, because print is considered separately in each base class for the purpose of overload resolution, and thus the calls are ambiguous. This is the case on Clang (4.0), gcc (6.3) and MSVC (17.0) - see godbolt results here.

Now consider the following snippet, the sole difference of which is that we use operator() instead of print:

#include <stdio.h>

struct foo_int {
    void operator() (int x) {
        printf("int %d\n", x);
    }
};

struct foo_str {
    void operator() (const char* x) {
        printf("str %s\n", x);
    }
};

struct foo : foo_int, foo_str {
    //using foo_int::operator();
    //using foo_str::operator();
};

int main() {
    foo f;
    f(123);
    f("abc");
}

I would expect the results to be identical to the previous case, but it is not the case - while gcc still complains, Clang and MSVC can compile this fine!

Question #1: who is correct in this case? I expect it to be gcc, but the fact that two other unrelated compilers give a consistently different result here makes me wonder whether I'm missing something in the Standard, and things are different for operators when they're not invoked using function syntax.

Also note that if you only uncomment one of the using declarations, but not the other, then all three compilers will fail to compile, because they will only consider the function brought in by using during overload resolution, and thus one of the calls will fail due to type mismatch. Remember this; we'll get back to it later.

Now consider the following code:

#include <stdio.h>

auto print_int = [](int x) {
    printf("int %d\n", x);
};
typedef decltype(print_int) foo_int;

auto print_str = [](const char* x) {
    printf("str %s\n", x);
};
typedef decltype(print_str) foo_str;

struct foo : foo_int, foo_str {
    //using foo_int::operator();
    //using foo_str::operator();
    foo(): foo_int(print_int), foo_str(print_str) {}
};

int main() {
    foo f;
    f(123);
    f("foo");
}

Again, same as before, except now we don't define operator() explicitly, but instead get it from a lambda type. Again, you'd expect the results to be consistent with the previous snippet; and this is true for the case where both using declarations are commented out, or if both are uncommented. But if you only comment out one but not the other, things are suddenly different again: now only MSVC complains as I would expect it to, while Clang and gcc both think it's fine - and use both inherited members for overload resolution, despite only one being brought in by using!

Question #2: who is correct in this case? Again, I'd expect it to be MSVC, but then why do both Clang and gcc disagree? And, more importantly, why this is different from the previous snippet? I would expect the lambda type to behave exactly the same as a manually defined type with overloaded operator()...

Body:
Barry got #1 right. Your #2 hit a corner case: captureless nongeneric lambdas have an implicit conversion to function pointer, which got used in the mismatch case. That is, given

struct foo : foo_int, foo_str {
    using foo_int::operator();
    //using foo_str::operator();
    foo(): foo_int(print_int), foo_str(print_str) {}
} f;

using fptr_str = void(*)(const char*);

f("hello") is equivalent to f.operator fptr_str()("hello"), converting the foo to an pointer-to-function and calling that. If you compile at -O0 you can actually see the call to the conversion function in the assembly before it gets optimized away. Put an init-capture in print_str, and you'll see an error since the implicit conversion goes away.

For more, see [over.call.object].


问:
Spark : SQL Context : Creating a data frame from Scala object
I am using Spark 1.5.2 to create a data frame from scala object using of of the following syntax. My purpose is to create a data for for unit testing.

class Address (first:String = null, second: String = null, zip: String = null){}
class Person (id: String = null, name: String = null, address: Seq[Address] = null){}
```

<hr>

<pre class="lang-scala prettyprint-override"><code>def test () = {

  val sqlContext = new SQLContext(sc)

  import sqlContext.implicits._

  val persons = Seq(
    new Person(id = "1", name = "Salim",
      address = Seq(new Address(first = "1st street"))),
    new Person(name = "Sana",
      address = Seq(new Address(zip = "60088")))
  )

  // The code can't infer schema automatically
  val claimDF = sqlContext.createDataFrame(sc.parallelize(persons, 2),classOf[Person])

  claimDF.printSchema() // This prints "root" not the schema of Person.
}
</code>```

Instead if I convert the Person and Address to case class then Spark can inherit schema automatically using the above syntax or using sc.parallelize(persons, 2).toDF or using sqlContext.createDataFrame(sc.parallelize(persons, 2),StructType)

I can't use case class because it can't hold more than 20 fields and I have a lot of fields in the class. And using StructType causes a lot of inconvenience. Case class is most convenient but can't hold too many properties.

Please help, thanks in advance.

答:
Thanks a lot for the input.

We ultimately migrated to Spark 2.1 with Scala 2.11 which supported a larger case class so this issue got resolved.

For Spark 1.6 and Scala 2.10 I ended up building Row object and Struct type to build a Dataframe.

```<code>val rows = Seq(Row("data"))
val aRDD = sc.parallelize(rows)
val aDF = sqlContext.createDataFrame(aRDD,getSchema())

def getSchema(): StructType= {
    StructType(
        Array(
            StructField("jobNumber", StringType, nullable = true))
    )
}
</code>```

Body:
I am using Spark 1.5.2 to create a data frame from scala object using of of the following syntax. My purpose is to create a data for for unit testing.

class Address (first:String = null, second: String = null, zip: String = null){}
class Person (id: String = null, name: String = null, address: Seq[Address] = null){}

def test () = {

  val sqlContext = new SQLContext(sc)

  import sqlContext.implicits._

  val persons = Seq(
    new Person(id = "1", name = "Salim",
      address = Seq(new Address(first = "1st street"))),
    new Person(name = "Sana",
      address = Seq(new Address(zip = "60088")))
  )

  // The code can't infer schema automatically
  val claimDF = sqlContext.createDataFrame(sc.parallelize(persons, 2),classOf[Person])

  claimDF.printSchema() // This prints "root" not the schema of Person.
}

Instead if I convert the Person and Address to case class then Spark can inherit schema automatically using the above syntax or using sc.parallelize(persons, 2).toDF or using sqlContext.createDataFrame(sc.parallelize(persons, 2),StructType)

I can't use case class because it can't hold more than 20 fields and I have a lot of fields in the class. And using StructType causes a lot of inconvenience. Case class is most convenient but can't hold too many properties.

Please help, thanks in advance.

Body:
Thanks a lot for the input.

We ultimately migrated to Spark 2.1 with Scala 2.11 which supported a larger case class so this issue got resolved.

For Spark 1.6 and Scala 2.10 I ended up building Row object and Struct type to build a Dataframe.

val rows = Seq(Row("data"))
val aRDD = sc.parallelize(rows)
val aDF = sqlContext.createDataFrame(aRDD,getSchema())

def getSchema(): StructType= {
    StructType(
        Array(
            StructField("jobNumber", StringType, nullable = true))
    )
}


问:
javascript force update on ng-model value on inputbox
```<code><form>
      Low: <input type="number" name="lowRange"
            ng-model="weight" ng-model-options = "{updateOn:'submit'}">
      <button type="submit">Assign</button>
      <button type="button" ng-click="resetValue()">Discard</button>
</form>
<p>$scope.weight: {{weight}}</p>
</code>```

weight is binded with ng-model. By using ng-model-options="{updateOn:'submit'}", the ng-model value is only updated after clicking on submit button.

When user modified the value in the input, and click discard, I want to reset the value inside the inputbox to be the current ng-model value.

I'm doing it by having a ng-click="resetValue()"

```<code>$scope.resetValue = function(){
    $scope.weight = $scope.weight; //if +1 here will update ng-model
  }
</code>```

But the assignment does not work when the variables are the same. Possibly because it is assigning by reference.

The value in the inputbox is not changed. Does anyone have any idea on how to force the ng-model on the inputbox to update the value?

Here is a demo: http://plnkr.co/edit/NQTieUmdEbxZeBsjk8Jw?%2F=preview&p=preview

答:
You need to tell the input field to reset.</p>

```<code><form name="myForm">
  Low: <input type="number" name="lowRange" ng-model="weight" ng-model-options = "{updateOn:'submit'}">
  <br>
  <button type="submit">Assign</button>
  <button type="button" ng-click="myForm.lowRange.$rollbackViewValue();">Discard</button>
</form>
</code>```

Body:
<form>
      Low: <input type="number" name="lowRange"
            ng-model="weight" ng-model-options = "{updateOn:'submit'}">
      <button type="submit">Assign</button>
      <button type="button" ng-click="resetValue()">Discard</button>
</form>

$scope.weight: {{weight}}

weight is binded with ng-model. By using ng-model-options="{updateOn:'submit'}", the ng-model value is only updated after clicking on submit button.

When user modified the value in the input, and click discard, I want to reset the value inside the inputbox to be the current ng-model value.

I'm doing it by having a ng-click="resetValue()"

$scope.resetValue = function(){
    $scope.weight = $scope.weight; //if +1 here will update ng-model
  }

But the assignment does not work when the variables are the same. Possibly because it is assigning by reference.

The value in the inputbox is not changed. Does anyone have any idea on how to force the ng-model on the inputbox to update the value?

Here is a demo: http://plnkr.co/edit/NQTieUmdEbxZeBsjk8Jw?%2F=preview&p=preview

Body:
You need to tell the input field to reset.

<form name="myForm">
  Low: <input type="number" name="lowRange" ng-model="weight" ng-model-options = "{updateOn:'submit'}">
  <br>
  <button type="submit">Assign</button>
  <button type="button" ng-click="myForm.lowRange.$rollbackViewValue();">Discard</button>
</form>


问:
Postgres UndefinedTable: ERROR: relation
I'm using postgres and rails to develop an app. When I run rake db:migrate I got the following error:

```<code>PG::UndefinedTable: ERROR:  relation "recipients" does not exist
: ALTER TABLE "chat_rooms" ADD CONSTRAINT "fk_rails_564b3640ba"
FOREIGN KEY ("recipient_id")
  REFERENCES "recipients" ("id")
</code>```

My migration file is:

```<code>class AddRecipientToChatRooms < ActiveRecord::Migration[5.0]
  def change
    add_reference :chat_rooms, :recipient, index: true, foreign_key: true
  end

  def drop
    remove_reference :chat_rooms, :recipient, index: true, foreign_key: true
  end
end
</code>```

My schema is:

```<code>ActiveRecord::Schema.define(version: 20170430135119) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "chat_rooms", force: :cascade do |t|
    t.string   "title"
    t.integer  "sender_id"
    t.datetime "created_at",   null: false
    t.datetime "updated_at",   null: false
    t.integer  "recipient_id"
    t.integer  "created_id"
    t.index ["created_id"], name: "index_chat_rooms_on_created_id", using: :btree
    t.index ["recipient_id"], name: "index_chat_rooms_on_recipient_id", using: :btree
    t.index ["sender_id"], name: "index_chat_rooms_on_sender_id", using: :btree
    t.index ["title"], name: "index_chat_rooms_on_title", unique: true, using: :btree
  end

  create_table "messages", force: :cascade do |t|
    t.text     "body"
    t.integer  "user_id"
    t.integer  "chat_room_id"
    t.datetime "created_at",   null: false
    t.datetime "updated_at",   null: false
    t.index ["chat_room_id"], name: "index_messages_on_chat_room_id", using: :btree
    t.index ["user_id"], name: "index_messages_on_user_id", using: :btree
  end

  create_table "users", force: :cascade do |t|
    t.string   "name"
    t.string   "email"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["email"], name: "index_users_on_email", unique: true, using: :btree
    t.index ["name"], name: "index_users_on_name", unique: true, using: :btree
  end

end
</code>```

I have read about this issue and I understand that postgresql is looking for a recipients table but in fact recipients are taken from users table, in other words recipients is an alias of users. I have specified that in my model with:

```<code>belongs_to :recipient, foreign_key: :recipient_id, class_name: 'User'
</code>```

I have some an idea on how to fix the issue but not sure if it's going to maintain referencial integrity:

Create an integer field named recipients_id and then add a foreign key with: add_foreign_key :chat_rooms, :users, column: :recipients_id, primary_key: :user_id

Any suggestion is welcome. :)

答:
You have to change your migration then to this. You can also skip the def drop part.

```<code>def change
  add_column :chat_rooms, :recipient_id, :integer, index: true
  add_foreign_key :chat_rooms, :users, column: :recipient_id
end
</code>```

Body:
I'm using postgres and rails to develop an app. When I run rake db:migrate I got the following error:

PG::UndefinedTable: ERROR:  relation "recipients" does not exist
: ALTER TABLE "chat_rooms" ADD CONSTRAINT "fk_rails_564b3640ba"
FOREIGN KEY ("recipient_id")
  REFERENCES "recipients" ("id")

My migration file is:

class AddRecipientToChatRooms < ActiveRecord::Migration[5.0]
  def change
    add_reference :chat_rooms, :recipient, index: true, foreign_key: true
  end

  def drop
    remove_reference :chat_rooms, :recipient, index: true, foreign_key: true
  end
end

My schema is:

ActiveRecord::Schema.define(version: 20170430135119) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "chat_rooms", force: :cascade do |t|
    t.string   "title"
    t.integer  "sender_id"
    t.datetime "created_at",   null: false
    t.datetime "updated_at",   null: false
    t.integer  "recipient_id"
    t.integer  "created_id"
    t.index ["created_id"], name: "index_chat_rooms_on_created_id", using: :btree
    t.index ["recipient_id"], name: "index_chat_rooms_on_recipient_id", using: :btree
    t.index ["sender_id"], name: "index_chat_rooms_on_sender_id", using: :btree
    t.index ["title"], name: "index_chat_rooms_on_title", unique: true, using: :btree
  end

  create_table "messages", force: :cascade do |t|
    t.text     "body"
    t.integer  "user_id"
    t.integer  "chat_room_id"
    t.datetime "created_at",   null: false
    t.datetime "updated_at",   null: false
    t.index ["chat_room_id"], name: "index_messages_on_chat_room_id", using: :btree
    t.index ["user_id"], name: "index_messages_on_user_id", using: :btree
  end

  create_table "users", force: :cascade do |t|
    t.string   "name"
    t.string   "email"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["email"], name: "index_users_on_email", unique: true, using: :btree
    t.index ["name"], name: "index_users_on_name", unique: true, using: :btree
  end

end

I have read about this issue and I understand that postgresql is looking for a recipients table but in fact recipients are taken from users table, in other words recipients is an alias of users. I have specified that in my model with:

belongs_to :recipient, foreign_key: :recipient_id, class_name: 'User'

I have some an idea on how to fix the issue but not sure if it's going to maintain referencial integrity:

Create an integer field named recipients_id and then add a foreign key with: add_foreign_key :chat_rooms, :users, column: :recipients_id, primary_key: :user_id

Any suggestion is welcome. :)

Body:
You have to change your migration then to this. You can also skip the def drop part.

def change
  add_column :chat_rooms, :recipient_id, :integer, index: true
  add_foreign_key :chat_rooms, :users, column: :recipient_id
end


问:
Will upgrading to Server 2008 R2 increase performance?
We are deploying two server-based applications, one WCF, and one a Winform that processes a lot of network traffic (like a custom-made WCF).

Generally speaking, would upgrading from Server 2008 to Server 2008 R2 / IIS 7.5 offer these apps potential significant performance benefits?

I'm particularly interested, as I've heard great things about Windows 7 as compared to Vista, and wondering if we can expect similar benefits with Server 2008 R2 vs Server 2008.  I.e. perhaps better memory handling, etc.

As an added note, I've heard the RTM for Server 2008 R2 will be available on MSDN within about a week, and that Windows 7 RTM will be available on MSDN today.

答:
Windows Server 2008 R2 has numerous improvements including most of those that were made to Win7.

However, whether or not you'll see any perf improvement is highly dependent on your app and how it works. The only way to tell if you'll get better perf is to measure the perf on your existing setup and then measure your perf on the new setup.

Any other speculation is just that - speculation - and may not have any bearing on reality!


问:
Unable to merge two dataframes using pandas
Despite multiple attempts I am not succeeding in doing a simple merge operation on two dataframes. Below code returns

KeyError: 'CODE'

on the merge function.

Note 1: To make the post reproducible, StringIO is used here with only two lines within each CSV, but in real life I read from files with thousands of records.

Note 2: Notice the trailing ',' (separator) at the end of each line: my CSV files are badly formatted but this is how actual files are.
Note 3: I am using Python 2.7

```<code>from StringIO import StringIO
import pandas as pd

master = StringIO("""N-NUMBER,SERIAL NUMBER,MFR MDL CODE,ENG MFR MDL,YEAR MFR,TYPE REGISTRANT,NAME,STREET,STREET2,CITY,STATE,ZIP CODE,REGION,COUNTY,COUNTRY,LAST ACTION DATE,CERT ISSUE DATE,CERTIFICATION,TYPE AIRCRAFT,TYPE ENGINE,STATUS CODE,MODE S CODE,FRACT OWNER,AIR WORTH DATE,OTHER NAMES(1),OTHER NAMES(2),OTHER NAMES(3),OTHER NAMES(4),OTHER NAMES(5),EXPIRATION DATE,UNIQUE ID,KIT MFR, KIT MODEL,MODE S CODE HEX,
1    ,1071                          ,3980115,54556,1988,5,FEDERAL AVIATION ADMINISTRATION                   ,WASHINGTON REAGAN NATIONAL ARPT  ,3201 THOMAS AVE HANGAR 6         ,WASHINGTON        ,DC,20001     ,1,001,US,20160614,19900214,1T        ,5,5 ,V ,50000001, ,19880909,                                                  ,                                                  ,                                                  ,                                                  ,                                                  ,20191130,00524101,                              ,                    ,A00001    ,""")

mfr = StringIO("""CODE,MFR,MODEL,TYPE-ACFT,TYPE-ENG,AC-CAT,BUILD-CERT-IND,NO-ENG,NO-SEATS,AC-WEIGHT,SPEED,
3980115,EXLINE ACE-C                  ,ACE-C               ,4,1 ,1,1,01,001,CLASS 1,0082,""")

masterdf = pd.read_csv(master,sep=",",index_col=False)
mfrdf = pd.read_csv(mfr,sep=",",index_col=False)

masterdf.merge(mfrdataframe,left_on='MFR MDL CODE',right_on='CODE', how='inner')
</code>```

答: I think that the problem is the name of the dataframe you're passing to merge: mfrdataframe should instead be mfrdf.

Body:
Despite multiple attempts I am not succeeding in doing a simple merge operation on two dataframes. Below code returns

KeyError: 'CODE'

on the merge function.

Note 1: To make the post reproducible, StringIO is used here with only two lines within each CSV, but in real life I read from files with thousands of records.

Note 2: Notice the trailing ',' (separator) at the end of each line: my CSV files are badly formatted but this is how actual files are.
Note 3: I am using Python 2.7

from StringIO import StringIO
import pandas as pd

master = StringIO("""N-NUMBER,SERIAL NUMBER,MFR MDL CODE,ENG MFR MDL,YEAR MFR,TYPE REGISTRANT,NAME,STREET,STREET2,CITY,STATE,ZIP CODE,REGION,COUNTY,COUNTRY,LAST ACTION DATE,CERT ISSUE DATE,CERTIFICATION,TYPE AIRCRAFT,TYPE ENGINE,STATUS CODE,MODE S CODE,FRACT OWNER,AIR WORTH DATE,OTHER NAMES(1),OTHER NAMES(2),OTHER NAMES(3),OTHER NAMES(4),OTHER NAMES(5),EXPIRATION DATE,UNIQUE ID,KIT MFR, KIT MODEL,MODE S CODE HEX,
1    ,1071                          ,3980115,54556,1988,5,FEDERAL AVIATION ADMINISTRATION                   ,WASHINGTON REAGAN NATIONAL ARPT  ,3201 THOMAS AVE HANGAR 6         ,WASHINGTON        ,DC,20001     ,1,001,US,20160614,19900214,1T        ,5,5 ,V ,50000001, ,19880909,                                                  ,                                                  ,                                                  ,                                                  ,                                                  ,20191130,00524101,                              ,                    ,A00001    ,""")

mfr = StringIO("""CODE,MFR,MODEL,TYPE-ACFT,TYPE-ENG,AC-CAT,BUILD-CERT-IND,NO-ENG,NO-SEATS,AC-WEIGHT,SPEED,
3980115,EXLINE ACE-C                  ,ACE-C               ,4,1 ,1,1,01,001,CLASS 1,0082,""")

masterdf = pd.read_csv(master,sep=",",index_col=False)
mfrdf = pd.read_csv(mfr,sep=",",index_col=False)

masterdf.merge(mfrdataframe,left_on='MFR MDL CODE',right_on='CODE', how='inner')


问:
what is the used technology on 3dvas.com
I was wonder what is the technology that has been used to render the gallery on this 3d object

https://www.3dvas.com/galleries/gallery.php?r=1&ex=1489

thanks

答: While I wouldnt be able to tell the exact library they used to make their product (without seeing their source code), 3D Engines such as Away3D are used to render such items in Flash and AIR products.


问:
Laravel one-to-one relationship fails
I created two migrations, because I wanted to create a one-to-one relationship between Trend and TrendExplanation.

```<code>Schema::create('trend_explanations', function (Blueprint $table) {
    $table->increments('id');
    $table->text('demographical')->nullable();
    $table->text('economical')->nullable();
    $table->text('social')->nullable();
    $table->text('technological')->nullable();
    $table->text('ecological')->nullable();
    $table->text('political')->nullable();
    $table->timestamps();
});
</code>```

This is the migration for the Trend model:

```<code>Schema::create('trends', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('explanation_id')->unsigned();
    $table->foreign('explanation_id')->references('id')->on('trend_explanations');
    $table->string('name');
    $table->date('date');
    $table->text('description');
    $table->timestamps();
});
</code>```

So in the models I did the following additions:

```<code>class Trend extends Model
{
    public function explanation()
    {
        return $this->hasOne(TrendExplanation::class);
    }
}
</code>```

And of course I created a seeder to test it out:

```<code>$trend = new Trend();
$trend->name = "Something";
$trend->description = "Description";

$explanation = new TrendExplanation();
// ...
$trend->explanation()->save($explanation);
$trend->save();
</code>```

And when I run it, I receive the error: [Illuminate\Database\QueryException] SQLSTATE[42S22]: Column not found: 1054 Unknown column 'trend_id' in 'field list'.

How does this happen? I don't understand what I did wrong here.

答:
You can specify the foreign and local keys when specifying the relationship. It usually goes

```<code>$this->hasOne(Class, foreign, local);
</code>```

So your definition would be:

```<code>return $this->hasOne(TrendExplanation::class, 'id', 'explanation_id');
</code>```

Title: Laravel one-to-one relationship fails

Body:
I created two migrations, because I wanted to create a one-to-one relationship between Trend and TrendExplanation.

Schema::create('trend_explanations', function (Blueprint $table) {
    $table->increments('id');
    $table->text('demographical')->nullable();
    $table->text('economical')->nullable();
    $table->text('social')->nullable();
    $table->text('technological')->nullable();
    $table->text('ecological')->nullable();
    $table->text('political')->nullable();
    $table->timestamps();
});

This is the migration for the Trend model:

Schema::create('trends', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('explanation_id')->unsigned();
    $table->foreign('explanation_id')->references('id')->on('trend_explanations');
    $table->string('name');
    $table->date('date');
    $table->text('description');
    $table->timestamps();
});

So in the models I did the following additions:

class Trend extends Model
{
    public function explanation()
    {
        return $this->hasOne(TrendExplanation::class);
    }
}

And of course I created a seeder to test it out:

$trend = new Trend();
$trend->name = "Something";
$trend->description = "Description";

$explanation = new TrendExplanation();
// ...
$trend->explanation()->save($explanation);
$trend->save();

And when I run it, I receive the error: [Illuminate\Database\QueryException] SQLSTATE[42S22]: Column not found: 1054 Unknown column 'trend_id' in 'field list'.

How does this happen? I don't understand what I did wrong here.

Body:
You can specify the foreign and local keys when specifying the relationship. It usually goes

$this->hasOne(Class, foreign, local);

So your definition would be:

return $this->hasOne(TrendExplanation::class, 'id', 'explanation_id');