问:
Script required
Suppose we have a table #temp1, what we required here is, we want an additional column ABC and in that, we want to print the output as (10-10 = 0), (20-10) = 10, (30-10 = 20), (40-10 = 30) and (50-10 = 40)

So, we have created a table and insert script below.

```<code>Create table #temp1 (ID Int Identity(1,1),Name varchar(10),Series bigint)

insert into #temp1 values('A',10)
insert into #temp1 values('B',20)
insert into #temp1 values('C',30)
insert into #temp1 values('D',40)
insert into #temp1 values('E',50)
</code>```

I tried as below, where its incrementing the values rows by rows.

```<code>select ID,Name,Series, SUM(series) over(order by series asc Rows Between Unbounded Preceding and Current Row) ranking from #temp1
</code>```

Output should be:

```<code>ID|Name|Series|ABC
1 |  A |  10  | 0
2 |  B |  20  | 10
3 |  C |  30  | 20
4 |  D |  40  | 30
5 |  E |  50  | 40
</code>```

Can anyone here me, how to do that.

答: select ID,Name,Series,(series - 10) as abc from #temp1</p>

Title: Script required

Body:
Suppose we have a table #temp1, what we required here is, we want an additional column ABC and in that, we want to print the output as (10-10 = 0), (20-10) = 10, (30-10 = 20), (40-10 = 30) and (50-10 = 40)

So, we have created a table and insert script below.

Create table #temp1 (ID Int Identity(1,1),Name varchar(10),Series bigint)

insert into #temp1 values('A',10)
insert into #temp1 values('B',20)
insert into #temp1 values('C',30)
insert into #temp1 values('D',40)
insert into #temp1 values('E',50)

I tried as below, where its incrementing the values rows by rows.

select ID,Name,Series, SUM(series) over(order by series asc Rows Between Unbounded Preceding and Current Row) ranking from #temp1

Output should be:

ID|Name|Series|ABC
1 |  A |  10  | 0
2 |  B |  20  | 10
3 |  C |  30  | 20
4 |  D |  40  | 30
5 |  E |  50  | 40

Can anyone here me, how to do that.


来源: stackexchange

问:
When I use #define two scanf("%d",&two) I get an output 1 after entering 4
This program tries to get input from user and store it in a macro named two but when I print the macro I get 1 as output....
Why is That?</p>

```<code>#include <stdio.h>
//declares two
int two;
//Takes input to store it in two
#define two scanf("%d",&two)
int main()
{

      printf("%d\n",two);

 return 0;
}
</code>```

答: What you're seeing is the value returned by scanf. The return value is the number of items scanf successfully filled (1 item in this case). See this reference: http://www.cplusplus.com/reference/cstdio/scanf/</p>

ContentLicense: CC BY-SA 3.0

Body:
This program tries to get input from user and store it in a macro named two but when I print the macro I get 1 as output....
Why is That?

#include <stdio.h>
//declares two
int two;
//Takes input to store it in two
#define two scanf("%d",&two)
int main()
{

      printf("%d\n",two);

 return 0;
}


问:
how to add hashmap in google maps android?
how to add hastmap to passing data from infowindow?

I want to display data from markers to new activity with the name of the mysql database

i want to replace it with hstmap, so that i can give more information when user press infowindow on markers

```<code> private void addMarker(LatLng latlng, final String title, final String keterangan) {
    markerOptions.position(latlng);
    markerOptions.title(title);
    markerOptions.snippet(keterangan);
    gMap.addMarker(markerOptions);
    gMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
        @Override
        public void onInfoWindowClick(Marker marker) {
            Intent i = new Intent(Navigator.this, ScrollingActivity.class);
            i.putExtra("title", marker.getTitle());
            i.putExtra("keterangan", marker.getSnippet());
            startActivity(i);
        }
    });
}
</code>```

答:
```<code>//Define hashmap
private HashMap<Marker, MyMarker>  markerHashMap=new HashMap<>();

//put all markers
markerHashMap.put(marker,mymaker);

gMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener()
{
@Override
public void onInfoWindowClick(Marker marker){
     if(markerHashMap!=null){
        MyMarker myMarker=markerHashMap.get(marker);
        Intent i=new Intent(Navigator.this,ScrollingActivity.class);
        i.putExtra("title",myMarker.getTitle());
        i.putExtra("keterangan",myMarker.getSnippt());
        startActivity(i);
        }
      }
    });
}

//put your data according your requirement
public class MyMarker {
    private String title, snippt;
    private double lat, lng;

    public MyMarker(String title, String snippt, double lat, double lng) {
        this.title = title;
        this.snippt = snippt;
        this.lat = lat;
        this.lng = lng;
       }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getSnippt() {
        return snippt;
    }

    public void setSnippt(String snippt) {
        this.snippt = snippt;
    }

    public double getLat() {
        return lat;
    }

    public void setLat(double lat) {
        this.lat = lat;
    }

    public double getLng() {
       return lng;
    }

    public void setLng(double lng) {
      this.lng = lng;
    }
}
</code>```

Body:
how to add hastmap to passing data from infowindow?

I want to display data from markers to new activity with the name of the mysql database

i want to replace it with hstmap, so that i can give more information when user press infowindow on markers

 private void addMarker(LatLng latlng, final String title, final String keterangan) {
    markerOptions.position(latlng);
    markerOptions.title(title);
    markerOptions.snippet(keterangan);
    gMap.addMarker(markerOptions);
    gMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
        @Override
        public void onInfoWindowClick(Marker marker) {
            Intent i = new Intent(Navigator.this, ScrollingActivity.class);
            i.putExtra("title", marker.getTitle());
            i.putExtra("keterangan", marker.getSnippet());
            startActivity(i);
        }
    });
}


问:
Scikitlearn LinearSVC Bad input shape
I'm trying to use LinearSVC on my data! My code below:

```<code>from sklearn import svm

clf2 = svm.LinearSVC()
clf2.fit(X_train, y_train)
</code>```

Results in the following error:

```<code>ValueError: bad input shape (2190, 9)
</code>```

I've used one-hot encoding on my y value before splitting into y_test and y_train, and believe this to be the issue. I've tried implementing similar fixes (sklearn (Bad Input Shape) ValueError) but still get errors when I try and re-shape.

After one hot-encoding, I have a target variable (y) that has 9 classes, and there are a total of 2190 samples i'm running. It seems I need to reduce these 9 classes to 1 class in order to fit the SVM.

Any suggestions would be greatly appreciated!

答:
LinearSVC dont accept 2-d values for y. As documented:

Parameters:

```<code>y : array-like, shape = [n_samples]

    Target vector relative to X
</code>```

So you don't need to convert into one-hot encoded matrix. Just supply them as is, even if its strings. They will be internally handled correctly.

Title: Scikitlearn LinearSVC Bad input shape

Body:
I'm trying to use LinearSVC on my data! My code below:

from sklearn import svm

clf2 = svm.LinearSVC()
clf2.fit(X_train, y_train)

Results in the following error:

ValueError: bad input shape (2190, 9)

I've used one-hot encoding on my y value before splitting into y_test and y_train, and believe this to be the issue. I've tried implementing similar fixes (sklearn (Bad Input Shape) ValueError) but still get errors when I try and re-shape.

After one hot-encoding, I have a target variable (y) that has 9 classes, and there are a total of 2190 samples i'm running. It seems I need to reduce these 9 classes to 1 class in order to fit the SVM.

Any suggestions would be greatly appreciated!

Body:
LinearSVC dont accept 2-d values for y. As documented:

Parameters:

y : array-like, shape = [n_samples]

    Target vector relative to X

So you don't need to convert into one-hot encoded matrix. Just supply them as is, even if its strings. They will be internally handled correctly.


问:
How to convert image to string data in ionic 3
Currently I am developing Ionic3 project.
Now I tried to store image data from UI to sqlite.
But I am not sure about the appropriate way to do it.
If you have already done, Please help me
How can I to do it?</p>

答:
First of all you need to learn how to take a picture, and for that you should refer this link. https://devdactic.com/ionic-2-images/

after that the image is come in the path of image is like this file:///image_path, So you have to pass this path to the base64 plugin like this.

for that you have to install the plugin.

$ ionic cordova plugin add com-badrit-base64
 $ npm install --save @ionic-native/base64

```<code>    public presentActionSheet() {
    let actionSheet = this.actionSheetCtrl.create({
    title: 'Select Image Source',
    buttons: [
    {
      text: 'Load from Library',
      handler: () => {
        this.takePicture(this.camera.PictureSourceType.PHOTOLIBRARY);
    }
    },
    {
      text: 'Use Camera',
      handler: () => {
        this.takePicture(this.camera.PictureSourceType.CAMERA);
      }
    },
    {
      text: 'Cancel',
      role: 'cancel'
    }
    ]
    });
    actionSheet.present();
}

public takePicture(sourceType) {

    let resUser: string = "res.users";

    // Create options for the Camera Dialog
    var options = {
        quality: 100,
        sourceType: sourceType,
        saveToPhotoAlbum: true,
        correctOrientation: true
    };

    // Get the data of an image
    this.camera.getPicture(options).then((imagePath) => {
    // Special handling for Android library

    if (this.platform.is('android') && sourceType === this.camera.PictureSourceType.PHOTOLIBRARY) {

    this.base64.encodeFile(imagePath).then((base64String: string) => {
      // console.log("-----base64String-----" + base64String);
      let imageSrc = base64String.split(",");
      console.log("---Splitted image string----" + imageSrc[1]);
      this.src = imageSrc[1]

      let args = {
        image: imageSrc[1]
      }

      this.odooRpc.updateRecord(resUser, this.data[0].id, args).then((res: any) => {
        console.log("----res of updation---" + res);
      }).catch((err: any) => {
        this.presentToast("There is some problem in uploading image")
      })

    })

    this.filePath.resolveNativePath(imagePath)
      .then(filePath => {
        let correctPath = filePath.substr(0, filePath.lastIndexOf('/') + 1);
        let currentName = imagePath.substring(imagePath.lastIndexOf('/') + 1, imagePath.lastIndexOf('?'));
        this.copyFileToLocalDir(correctPath, currentName, this.createFileName());
      });

    } else {

    this.base64.encodeFile(imagePath).then((base64String: string) => {
      // console.log("-----base64String-----" + base64String);
      let imageSrc = base64String.split(",");
      console.log("---Splitted image string----" + imageSrc[1]);
      this.src = imageSrc[1]

      let args = {
        image: imageSrc[1]
      }

      this.odooRpc.updateRecord(resUser, this.data[0].id, args).then((res: any) => {
        console.log("----res of updation---" + res);
      }).catch((err: any) => {
        this.presentToast("There is some problem in uploading image")
      })
    })

    console.log("-------inside else IMage Path------" + imagePath);

    var currentName = imagePath.substr(imagePath.lastIndexOf('/') + 1);
    var correctPath = imagePath.substr(0, imagePath.lastIndexOf('/') + 1);
    this.copyFileToLocalDir(correctPath, currentName, this.createFileName());
    }
    }, (err) => {
      this.presentToast('Error while selecting image.');
    });
    }

private createFileName() {
    var d = new Date(),
    n = d.getTime(),
    newFileName = n + ".jpg";
    return newFileName;
}

// Copy the image to a local folder
private copyFileToLocalDir(namePath, currentName, newFileName) {
    this.file.copyFile(namePath, currentName, cordova.file.dataDirectory, newFileName).then(success => {
    this.lastImage = newFileName;
    }, error => {
    this.presentToast('Error while storing file.');
    });
}
</code>```

Body:
First of all you need to learn how to take a picture, and for that you should refer this link. https://devdactic.com/ionic-2-images/

after that the image is come in the path of image is like this file:///image_path, So you have to pass this path to the base64 plugin like this.

for that you have to install the plugin.

$ ionic cordova plugin add com-badrit-base64
 $ npm install --save @ionic-native/base64

    public presentActionSheet() {
    let actionSheet = this.actionSheetCtrl.create({
    title: 'Select Image Source',
    buttons: [
    {
      text: 'Load from Library',
      handler: () => {
        this.takePicture(this.camera.PictureSourceType.PHOTOLIBRARY);
    }
    },
    {
      text: 'Use Camera',
      handler: () => {
        this.takePicture(this.camera.PictureSourceType.CAMERA);
      }
    },
    {
      text: 'Cancel',
      role: 'cancel'
    }
    ]
    });
    actionSheet.present();
}

public takePicture(sourceType) {

    let resUser: string = "res.users";

    // Create options for the Camera Dialog
    var options = {
        quality: 100,
        sourceType: sourceType,
        saveToPhotoAlbum: true,
        correctOrientation: true
    };

    // Get the data of an image
    this.camera.getPicture(options).then((imagePath) => {
    // Special handling for Android library

    if (this.platform.is('android') && sourceType === this.camera.PictureSourceType.PHOTOLIBRARY) {

    this.base64.encodeFile(imagePath).then((base64String: string) => {
      // console.log("-----base64String-----" + base64String);
      let imageSrc = base64String.split(",");
      console.log("---Splitted image string----" + imageSrc[1]);
      this.src = imageSrc[1]

      let args = {
        image: imageSrc[1]
      }

      this.odooRpc.updateRecord(resUser, this.data[0].id, args).then((res: any) => {
        console.log("----res of updation---" + res);
      }).catch((err: any) => {
        this.presentToast("There is some problem in uploading image")
      })

    })

    this.filePath.resolveNativePath(imagePath)
      .then(filePath => {
        let correctPath = filePath.substr(0, filePath.lastIndexOf('/') + 1);
        let currentName = imagePath.substring(imagePath.lastIndexOf('/') + 1, imagePath.lastIndexOf('?'));
        this.copyFileToLocalDir(correctPath, currentName, this.createFileName());
      });

    } else {

    this.base64.encodeFile(imagePath).then((base64String: string) => {
      // console.log("-----base64String-----" + base64String);
      let imageSrc = base64String.split(",");
      console.log("---Splitted image string----" + imageSrc[1]);
      this.src = imageSrc[1]

      let args = {
        image: imageSrc[1]
      }

      this.odooRpc.updateRecord(resUser, this.data[0].id, args).then((res: any) => {
        console.log("----res of updation---" + res);
      }).catch((err: any) => {
        this.presentToast("There is some problem in uploading image")
      })
    })

    console.log("-------inside else IMage Path------" + imagePath);

    var currentName = imagePath.substr(imagePath.lastIndexOf('/') + 1);
    var correctPath = imagePath.substr(0, imagePath.lastIndexOf('/') + 1);
    this.copyFileToLocalDir(correctPath, currentName, this.createFileName());
    }
    }, (err) => {
      this.presentToast('Error while selecting image.');
    });
    }

private createFileName() {
    var d = new Date(),
    n = d.getTime(),
    newFileName = n + ".jpg";
    return newFileName;
}

// Copy the image to a local folder
private copyFileToLocalDir(namePath, currentName, newFileName) {
    this.file.copyFile(namePath, currentName, cordova.file.dataDirectory, newFileName).then(success => {
    this.lastImage = newFileName;
    }, error => {
    this.presentToast('Error while storing file.');
    });
}


问:
Implementing Snapshot in AXON 3.0 : Aggregate Type is unknown in this snapShotter
I'm still new to the axon frame work.

I'm trying to implement snapshotting using  mongodb in my application and I keep on getting an error saying

"AbstractSnapshotter                : An attempt to create and store a snapshot resulted in an exception. Exception summary: Aggregate Type is unknown in this snapshotter: com.myworklife.contacts.domain.contact.Contact"

This is a part of my java config file.

```<code>@Bean
public AggregateSnapshotter snapShotter(EventStore eventStore, AggregateFactory<Contact> contactAggregateFactory) {
    return new AggregateSnapshotter(eventStore);
}

@Bean
public SnapshotTriggerDefinition snapshotTriggerDefinition(Snapshotter snapShotter) throws Exception {
    return new EventCountSnapshotTriggerDefinition(snapShotter, 1);
}

@Bean
public EventStore eventStore(EventStorageEngine eventStorageEngine)  {
    return new EmbeddedEventStore(eventStorageEngine);
}

@Bean
public Repository<Contact> contactAggregateRepository(EventStore eventStore, SnapshotTriggerDefinition snapshotTriggerDefinition) {
    return new ContactRepository(eventStore, snapshotTriggerDefinition);
}
</code>```

And my repository.

```<code>    @Repository("ContactRepository")
public class ContactRepository extends EventSourcingRepository<Contact> {

    @Autowired
    public ContactRepository(EventStore eventStore, SnapshotTriggerDefinition snapshotTriggerDefinition) {
        super(Contact.class, eventStore, snapshotTriggerDefinition);
    }

    public Contact findContact(ContactId contactId) {
        return load(contactId.toString()).getWrappedAggregate().getAggregateRoot();
    }
}
</code>```

My aggregate.

```<code>@Aggregate(repository="contactAggregateRepository")
public class Contact {

    @AggregateIdentifier
    private ContactId id;
    private String name;
    private String mobileNumber;

    public Contact() {
        // do nothing, Axon requires default constructor
    }

    @CommandHandler
    public Contact(CreateContactCommand createContactCommand) {
        apply(new ContactHasBeenCreatedEvent(createContactCommand.getContactId(), createContactCommand.getName(),
                createContactCommand.getMobileNumber()));
    }
}
</code>```

Is there something I'm doing wrong?

since I'm getting an error saying "An attempt to create and store a snapshot resulted in an exception. Exception summary: Aggregate Type is unknown in this snapshotter: com.myworklife.contacts.domain.contact.Contact"

Any help will be highly appreciated.

Thanks,
Pat

答:
1.depencity jar

```<code> <dependency>
    <groupId>org.axonframework</groupId>
    <artifactId>axon-spring-boot-autoconfigure</artifactId>
    <version>${axon.version}</version>
</dependency>
</code>```

2.At first,you should config your application.ymp or bootstrap.yml,like this:spring:
  data:
    mongodb:
      host: localhost
      port: 27017
      database: axonframework
      events: domainevents
      snapshots: snapshotevents

3.config your mongoDB:

```<code>    @Bean(name = "axonMongoTemplate")
public MongoTemplate axonMongoTemplate() {
    MongoTemplate template = new DefaultMongoTemplate(mongoClient(), mongoDbName, eventsCollectionName, snapshotCollectionName);
    return template;
}

@Bean
public MongoClient mongoClient(){
    MongoFactory mongoFactory = new MongoFactory();
    mongoFactory.setMongoAddresses(Arrays.asList(new ServerAddress(mongoHost)));
    return mongoFactory.createMongo();
}

@Bean
public EventStorageEngine eventStorageEngine(Serializer serializer){
    return new MongoEventStorageEngine(
            serializer,null, axonMongoTemplate(), new DocumentPerEventStorageStrategy());
</code>```

4.config repository for your aggregate,for example,i config a Element Aggreaget's repository

```<code>@Configuration
public class ElementConfiguration {

    @Autowired
    private EventStore eventStore;
    @Bean
    @Scope("prototype")
    public Element elementAggregate() {
        return new Element();
    }

    @Bean
    public AggregateFactory<Element> elementAggregateAggregateFactory() {

        SpringPrototypeAggregateFactory<Element> aggregateFactory = new SpringPrototypeAggregateFactory<>();
        aggregateFactory.setPrototypeBeanName("elementAggregate");
        return aggregateFactory;
    }
    @Bean
    public SpringAggregateSnapshotterFactoryBean springAggregateSnapshotterFactoryBean(){

        SpringAggregateSnapshotterFactoryBean factory = new SpringAggregateSnapshotterFactoryBean();
        return factory;
    }
     @Bean
    public Repository<Element> elementAggregateRepository(Snapshotter snapshotter) {

        EventCountSnapshotTriggerDefinition eventCountSnapshotTriggerDefinition = new EventCountSnapshotTriggerDefinition(snapshotter, 3);

        EventSourcingRepository<Element> repository = new EventSourcingRepository<Element>(
            elementAggregateAggregateFactory(),
            eventStore,
            eventCountSnapshotTriggerDefinition
        );
        return repository;
    }
</code>```

5.enjoy

Body:
I'm still new to the axon frame work.

I'm trying to implement snapshotting using  mongodb in my application and I keep on getting an error saying

"AbstractSnapshotter                : An attempt to create and store a snapshot resulted in an exception. Exception summary: Aggregate Type is unknown in this snapshotter: com.myworklife.contacts.domain.contact.Contact"

This is a part of my java config file.

@Bean
public AggregateSnapshotter snapShotter(EventStore eventStore, AggregateFactory<Contact> contactAggregateFactory) {
    return new AggregateSnapshotter(eventStore);
}

@Bean
public SnapshotTriggerDefinition snapshotTriggerDefinition(Snapshotter snapShotter) throws Exception {
    return new EventCountSnapshotTriggerDefinition(snapShotter, 1);
}

@Bean
public EventStore eventStore(EventStorageEngine eventStorageEngine)  {
    return new EmbeddedEventStore(eventStorageEngine);
}

@Bean
public Repository<Contact> contactAggregateRepository(EventStore eventStore, SnapshotTriggerDefinition snapshotTriggerDefinition) {
    return new ContactRepository(eventStore, snapshotTriggerDefinition);
}

And my repository.

    @Repository("ContactRepository")
public class ContactRepository extends EventSourcingRepository<Contact> {

    @Autowired
    public ContactRepository(EventStore eventStore, SnapshotTriggerDefinition snapshotTriggerDefinition) {
        super(Contact.class, eventStore, snapshotTriggerDefinition);
    }

    public Contact findContact(ContactId contactId) {
        return load(contactId.toString()).getWrappedAggregate().getAggregateRoot();
    }
}

My aggregate.

@Aggregate(repository="contactAggregateRepository")
public class Contact {

    @AggregateIdentifier
    private ContactId id;
    private String name;
    private String mobileNumber;

    public Contact() {
        // do nothing, Axon requires default constructor
    }

    @CommandHandler
    public Contact(CreateContactCommand createContactCommand) {
        apply(new ContactHasBeenCreatedEvent(createContactCommand.getContactId(), createContactCommand.getName(),
                createContactCommand.getMobileNumber()));
    }
}

Is there something I'm doing wrong?

since I'm getting an error saying "An attempt to create and store a snapshot resulted in an exception. Exception summary: Aggregate Type is unknown in this snapshotter: com.myworklife.contacts.domain.contact.Contact"

Any help will be highly appreciated.

Thanks,
Pat

Body:
1.depencity jar

 <dependency>
    <groupId>org.axonframework</groupId>
    <artifactId>axon-spring-boot-autoconfigure</artifactId>
    <version>${axon.version}</version>
</dependency>

2.At first,you should config your application.ymp or bootstrap.yml,like this:spring:
  data:
    mongodb:
      host: localhost
      port: 27017
      database: axonframework
      events: domainevents
      snapshots: snapshotevents

3.config your mongoDB:

    @Bean(name = "axonMongoTemplate")
public MongoTemplate axonMongoTemplate() {
    MongoTemplate template = new DefaultMongoTemplate(mongoClient(), mongoDbName, eventsCollectionName, snapshotCollectionName);
    return template;
}

@Bean
public MongoClient mongoClient(){
    MongoFactory mongoFactory = new MongoFactory();
    mongoFactory.setMongoAddresses(Arrays.asList(new ServerAddress(mongoHost)));
    return mongoFactory.createMongo();
}

@Bean
public EventStorageEngine eventStorageEngine(Serializer serializer){
    return new MongoEventStorageEngine(
            serializer,null, axonMongoTemplate(), new DocumentPerEventStorageStrategy());

4.config repository for your aggregate,for example,i config a Element Aggreaget's repository

@Configuration
public class ElementConfiguration {

    @Autowired
    private EventStore eventStore;
    @Bean
    @Scope("prototype")
    public Element elementAggregate() {
        return new Element();
    }

    @Bean
    public AggregateFactory<Element> elementAggregateAggregateFactory() {

        SpringPrototypeAggregateFactory<Element> aggregateFactory = new SpringPrototypeAggregateFactory<>();
        aggregateFactory.setPrototypeBeanName("elementAggregate");
        return aggregateFactory;
    }
    @Bean
    public SpringAggregateSnapshotterFactoryBean springAggregateSnapshotterFactoryBean(){

        SpringAggregateSnapshotterFactoryBean factory = new SpringAggregateSnapshotterFactoryBean();
        return factory;
    }
     @Bean
    public Repository<Element> elementAggregateRepository(Snapshotter snapshotter) {

        EventCountSnapshotTriggerDefinition eventCountSnapshotTriggerDefinition = new EventCountSnapshotTriggerDefinition(snapshotter, 3);

        EventSourcingRepository<Element> repository = new EventSourcingRepository<Element>(
            elementAggregateAggregateFactory(),
            eventStore,
            eventCountSnapshotTriggerDefinition
        );
        return repository;
    }

5.enjoy


问:
Optimization Algorithm in C#
I have an optimization issue that I'm not sure where to go from here. I have a program that tries to find the best combination of inputs that return the highest predicted r squared value. The problem is that I have 21 total inputs (List) and I need them in a set of 15 inputs. The formula for total combinations is:

n! / r!(n - r)! = 21! / 15!(21 - 15)! = 54,264 possible combinations

So obviously running through each combination and calculating the predicted rsquared is not an ideal solution so is there an better way/algorithm/method I can use to try to skip or narrow down the bad combinations so that I'm only processing the fewest amount of combinations? Here is my current psuedo code for this issue:

```<code>public BestCombo GetBestCombo(List<List<MultipleRegressionInfo>> combosList)
{
   BestCombo bestCombo = new BestCombo();

   foreach (var combo in combosList)
   {
      var predRsquared = CalculatePredictedRSquared(combo);

      if (predRsquared > bestCombo.predRSquared)
      {
         bestCombo.predRSquared = predRsquared;
         bestCombo.BestRSquaredCombo = combo;
      }
   }

   return bestCombo;
}

public class BestCombo
    {
        public double predRSquared { get; set; }
        public IEnumerable<MultipleRegressionInfo> BestRSquaredCombo { get; set; }
    }

public class MultipleRegressionInfo
{
    public List<double> input { get; set; }
    public List<double> output { get; set; }
}

public double CalculatePredictedRSquared(List<MultipleRegressionInfo> combo)
{
    Matrix<double> matrix = BuildMatrix(combo.Select(i => i.input).ToArray());
    Vector<double> vector = BuildVector(combo.ElementAt(0).output);
    var coefficients = CalculateWithQR(matrix, vector);
    var y = CalculateYIntercept(coefficients, input, output);
    var estimateList = CalculateEstimates(coefficients, y, input, output);
    return GetPredRsquared(estimateList, output);
}
</code>```

答:
54,264 is not enormous for a computer - it might be worth timing a few calls to compute R^2 and multiplying up to see just how long this would take.

There is a branch and bound algorithm for this sort of problem, which relies on the fact that R^2(A,B,C) >= R^2(A,B) - that the R^2 can only decrease when you drop a variable. Recursively search the space of all sets of variables of size at least 15. After computing the R^2 for a set of variables, make recursive calls with sets produced by dropping a single variable from the set, where any such drop must be to the right of any existing gap (so A.CDE produces A..DE, A.C.E, and A.CD. but not ..CDE, which will be produced by .BCDE). You can terminate the recursion when you get down to the desired size of set, or when you find an R^2 that is no better than the best answer so far.

If it happens that you often find R^2 values no better than the best answer so far, this will save time - but this is not guaranteed. You can attempt to improve the efficiency by chosing to investigate the sets with highest R^2 first, hoping that you find a new best answer good enough to rule out their siblings by the time you come to them, and by using a procedure to calculate R^2 for A.CDE that makes use of the calculations you have already done for ABCDE.

Title: Optimization Algorithm in C#

Body:
I have an optimization issue that I'm not sure where to go from here. I have a program that tries to find the best combination of inputs that return the highest predicted r squared value. The problem is that I have 21 total inputs (List) and I need them in a set of 15 inputs. The formula for total combinations is:

n! / r!(n - r)! = 21! / 15!(21 - 15)! = 54,264 possible combinations

So obviously running through each combination and calculating the predicted rsquared is not an ideal solution so is there an better way/algorithm/method I can use to try to skip or narrow down the bad combinations so that I'm only processing the fewest amount of combinations? Here is my current psuedo code for this issue:

public BestCombo GetBestCombo(List<List<MultipleRegressionInfo>> combosList)
{
   BestCombo bestCombo = new BestCombo();

   foreach (var combo in combosList)
   {
      var predRsquared = CalculatePredictedRSquared(combo);

      if (predRsquared > bestCombo.predRSquared)
      {
         bestCombo.predRSquared = predRsquared;
         bestCombo.BestRSquaredCombo = combo;
      }
   }

   return bestCombo;
}

public class BestCombo
    {
        public double predRSquared { get; set; }
        public IEnumerable<MultipleRegressionInfo> BestRSquaredCombo { get; set; }
    }

public class MultipleRegressionInfo
{
    public List<double> input { get; set; }
    public List<double> output { get; set; }
}

public double CalculatePredictedRSquared(List<MultipleRegressionInfo> combo)
{
    Matrix<double> matrix = BuildMatrix(combo.Select(i => i.input).ToArray());
    Vector<double> vector = BuildVector(combo.ElementAt(0).output);
    var coefficients = CalculateWithQR(matrix, vector);
    var y = CalculateYIntercept(coefficients, input, output);
    var estimateList = CalculateEstimates(coefficients, y, input, output);
    return GetPredRsquared(estimateList, output);
}


问:
Adding column names to dataframe while reading a csv in r
I have multiple .csv files in my directory which don't have a column name. So while reading them without header gives error

Error in match.names(clabs, names(xi)) :
    names do not match previous names.

So for that reason, I want to append column names to those csv files and combine them all to one single dataframe, but I'm not able to add a column name to those multiple csv file while reading them. File names are like test_abc.csv , test_pqr.csv, test_xyz.csv etc.
here is what I tried

```<code>temp = list.files(pattern="*.csv")
read_csv_filename <- function(filename){
  ret <- read.csv(filename,header = F)
  ret$city <- gsub(".*[_]([^.]+)[.].*", "\\1", filename)
  ret
}

df_all <- do.call(rbind,lapply(temp,read_csv_filename))
</code>```

How do I add header here to every file while reading?

This is a names that I want to add while reading

```<code>colnames = c("Age","Gender","height","weight")
</code>```

Any suggestion?

答:
Using tidyverse packages, you can do this nicely with purrr::map_dfr function, which iterates of a list, performing some function on each elements that returns a dataframe each time, and the row-binds all those data frames together.

library(readr)
library(purrr)
library(dplyr) # only used in example set up

# Setting up some example csv files to work with

mtcars_slim <- select(mtcars, 1:3)

write_csv(slice(mtcars_slim, 1:4), "mtcars_1.csv", col_names = FALSE)
write_csv(slice(mtcars_slim, 5:10), "mtcars_2.csv", col_names = FALSE)
write_csv(slice(mtcars_slim, 11:1), "mtcars_3.csv", col_names = FALSE)

# get file paths, read them all, and row-bind them all

dir(pattern = "mtcars_\\d+\\.csv") %>%
  map_dfr(read_csv, col_names = c("mpg", "cyl", "disp"))

#> Parsed with column specification:
#> cols(
#>   mpg = col_double(),
#>   cyl = col_integer(),
#>   disp = col_integer()
#> )

#> # A tibble: 21 x 3
#>      mpg   cyl  disp
#>    <dbl> <int> <dbl>
#>  1  21.0     6 160.0
#>  2  21.0     6 160.0
#>  3  22.8     4 108.0
#>  4  21.4     6 258.0
#>  5  18.7     8 360.0
#>  6  18.1     6 225.0
#>  7  14.3     8 360.0
#>  8  24.4     4 146.7
#>  9  22.8     4 140.8
#> 10  19.2     6 167.6
#> # ... with 11 more rows
```

Body:
I have multiple .csv files in my directory which don't have a column name. So while reading them without header gives error

Error in match.names(clabs, names(xi)) :
    names do not match previous names.

So for that reason, I want to append column names to those csv files and combine them all to one single dataframe, but I'm not able to add a column name to those multiple csv file while reading them. File names are like test_abc.csv , test_pqr.csv, test_xyz.csv etc.
here is what I tried

temp = list.files(pattern="*.csv")
read_csv_filename <- function(filename){
  ret <- read.csv(filename,header = F)
  ret$city <- gsub(".*[_]([^.]+)[.].*", "\\1", filename)
  ret
}

df_all <- do.call(rbind,lapply(temp,read_csv_filename))

How do I add header here to every file while reading?

This is a names that I want to add while reading

colnames = c("Age","Gender","height","weight")

Any suggestion?


问:
Search in array with relevance
I am doing a very small online store application in PHP. So I have an array of maps in PHP. I want to search for a string (a product) in the array. I looked at array_search in PHP and it seems that it only looks for exact match. Do you guys know a better way to do this functionality? Since this is a very small part of what I am actually doing, I was hoping that there was something built in. Any ideas?

Thanks!

EDIT: The array contains "products" in this format:

```<code>[6] => SimpleXMLElement Object
    (
        [@attributes] => Array
            (
                [id] => 2000-YM
            )

        [Name] => Team Swim School T-Shirt
        [size] => YM
        [price] => 15
        [group] => Team Clothing
        [id] => 2000-YM
    )

[7] => SimpleXMLElement Object
    (
        [@attributes] => Array
            (
                [id] => 3000-YS
            )

        [Name] => Youth Track Jacket
        [size] => YS
        [price] => 55
        [group] => Team Clothing
        [id] => 3000-YS
    )
</code>```

So I was wondering I can do a search such as "Team" and it would return me first item seen here. I am basing the search on the Name (again this is just something small). I understand that I can find the exact string, I am just stuck on the "best results" if it cannot find the exact item. Efficiency is nice but not required since I only have about 50 items so even if I use a "slow" algorithm it won't take much time.

答:
I have same Issue but i have created i function to search in array by passing the array, key and value.</p>

```<code>public function searchinarr($array, $key, $value)
{
       $results = array();
            for($i=0;$i<count($array);$i++)
            {
                foreach($array[$i] as $k=>$val)
                {
                    if($k==$key)
                    {
                        if(strpos($val,$value)!== false)
                        {
                            $results[] = $array[$i];
                        }
                    }
                }

            }
            return $results;
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Search in array with relevance

Body:
I am doing a very small online store application in PHP. So I have an array of maps in PHP. I want to search for a string (a product) in the array. I looked at array_search in PHP and it seems that it only looks for exact match. Do you guys know a better way to do this functionality? Since this is a very small part of what I am actually doing, I was hoping that there was something built in. Any ideas?

Thanks!

EDIT: The array contains "products" in this format:

[6] => SimpleXMLElement Object
    (
        [@attributes] => Array
            (
                [id] => 2000-YM
            )

        [Name] => Team Swim School T-Shirt
        [size] => YM
        [price] => 15
        [group] => Team Clothing
        [id] => 2000-YM
    )

[7] => SimpleXMLElement Object
    (
        [@attributes] => Array
            (
                [id] => 3000-YS
            )

        [Name] => Youth Track Jacket
        [size] => YS
        [price] => 55
        [group] => Team Clothing
        [id] => 3000-YS
    )

So I was wondering I can do a search such as "Team" and it would return me first item seen here. I am basing the search on the Name (again this is just something small). I understand that I can find the exact string, I am just stuck on the "best results" if it cannot find the exact item. Efficiency is nice but not required since I only have about 50 items so even if I use a "slow" algorithm it won't take much time.

Body:
I have same Issue but i have created i function to search in array by passing the array, key and value.

public function searchinarr($array, $key, $value)
{
       $results = array();
            for($i=0;$i<count($array);$i++)
            {
                foreach($array[$i] as $k=>$val)
                {
                    if($k==$key)
                    {
                        if(strpos($val,$value)!== false)
                        {
                            $results[] = $array[$i];
                        }
                    }
                }

            }
            return $results;
}


问:
Java: variable from parent class in child one isn't initialized and holds null
```<code>Parent class(*ch.qos.logback.core.FileAppender*):

     ...

   protected String fileName = null;

   public FileAppender() {
      }

          public void setFile(String file) {
            if (file == null) {
              fileName = file;
            } else {
              // Trim spaces from both ends. The users probably does not want
              // trailing spaces in file names.
              String val = file.trim();
              fileName = val;
            }
          }
    ...
</code>```

Child class:

```<code>    ...
   public class FileAppender<E> extends ch.qos.logback.core.FileAppender<E> {

     private FileResourceManager frm  = new FileResourceManager(fileName, tempDir, false, loggerFacade);

     public void writeOut(E event) throws IOException {
      Object txId = null;
      try {
       frm.start();
       txId = frm.generatedUniqueTxId();
       frm.startTransaction(txId);
       outputStream = frm.writeResource(txId, fileName, true);
       outputStream.write(event.toString().getBytes());
       frm.commitTransaction(txId);

      }

      catch (Exception e) {
    ...
      }
     }
</code>```

The problem is that fileName is passed as null to frm in this line:

```<code>private FileResourceManager frm  = new FileResourceManager(fileName, tempDir, false, loggerFacade);
</code>```

How can i create frm instance,with not-null fileName,e.g. already initialized in parent?

答:
Is setFile an override that you are calling from the parent class constructor? In that case: The parent class constructor runs before the useful part fo the child constructor. So setFile is called from the parent class constructor, and then control is returned to the child class constructor which you have nulling out that variable.

The instance field initialisers and instance initialisers are actually part of constructors, after the possibly implicit call to super (but not if they call this()). I believe C sharp inserts instance initialisers before the call to super (but they can't reference this).

What to do: Avoiding inheritance is always good. In particular avoid protected variables and calling overridable methods from constructors. Keep constructors simple. And don't add = null to instance fields.

ContentLicense: CC BY-SA 2.5

Body:
Parent class(*ch.qos.logback.core.FileAppender*):

     ...

   protected String fileName = null;

   public FileAppender() {
      }

          public void setFile(String file) {
            if (file == null) {
              fileName = file;
            } else {
              // Trim spaces from both ends. The users probably does not want
              // trailing spaces in file names.
              String val = file.trim();
              fileName = val;
            }
          }
    ...

Child class:

    ...
   public class FileAppender<E> extends ch.qos.logback.core.FileAppender<E> {

     private FileResourceManager frm  = new FileResourceManager(fileName, tempDir, false, loggerFacade);

     public void writeOut(E event) throws IOException {
      Object txId = null;
      try {
       frm.start();
       txId = frm.generatedUniqueTxId();
       frm.startTransaction(txId);
       outputStream = frm.writeResource(txId, fileName, true);
       outputStream.write(event.toString().getBytes());
       frm.commitTransaction(txId);

      }

      catch (Exception e) {
    ...
      }
     }

The problem is that fileName is passed as null to frm in this line:

private FileResourceManager frm  = new FileResourceManager(fileName, tempDir, false, loggerFacade);

How can i create frm instance,with not-null fileName,e.g. already initialized in parent?


问:
How to do this Firebase Cloud Function I cant get this to work
In the Cloud Firestore I try to create a Function trigger but I have some problems.

I want the Cloud Firestore Function to respond to writes at this Firebase Realtime databas location:

```<code>"VISITORS_PRESENCE" : {
    "8PICNP6JBTJDFGiBZYsT" : { // House for sale
      "3b1874ec-02f8-4004-817d-a3c44877473c" : { // The user Id
        "applicationId" : "3b1874ec-02f8-4004-817d-a3c44877473c",
        "last_changed" : 1510859721293,
        "state" : "online",
        "userId" : "testtest@test,com"
      }
    }
  },
</code>```

and simply copy this values/writes into Cloud Firestore Using this functions:
(note this is based on the Cloud Firestore docs functions get-started

```<code>exports.onvisitorPresence = functions.database
    .ref("/VISITORS_PRESENCE/{uid1}/{uid2}").onWrite((event) => {
        // Get the data written to Realtime Database
        const eventStatus = event.data.val();

        // Then use other event data to create a reference to the
        // corresponding Firestore document.
        const userStatusFirestoreRef = firestore
        .doc(`VISITORS_PRESENCE/${event.params.uid1}/USERS/{event.params.uid2}`);

        // It is likely that the Realtime Database change that triggered
        // this event has already been overwritten by a fast change in
        // online / offline status, so we'll re-read the current data
        // and compare the timestamps.
        return event.data.ref.once("value").then((statusSnapshot) => {
            return statusSnapshot.val();
        }).then((status) => {
            console.log(status, eventStatus);
            // If the current timestamp for this data is newer than
            // the data that triggered this event, we exit this function.
            if (status.last_changed > eventStatus.last_changed) return;

            // Otherwise, we convert the last_changed field to a Date
            eventStatus.last_changed = new Date(eventStatus.last_changed);

            // ... and write it to Firestore.
            return userStatusFirestoreRef.set(eventStatus);
        });
    });
</code>```

In the Cloud Firestore what this produces is this:

VISITORS_PRESENCE/8PICNP6JBTJDFGiBZYsT/USERS/{event.params.uid2}/

applicationId "3b1874ec-02f8-4004-817d-a3c44877473c"

last_changed November 16, 2017 at 8:15:21 PM UTC+1

state "online"

userId "testtest@test,com"

Here´s a pic:

I want the event.params.uid2in the above to be the "3b1874ec-02f8-4004-817d-a3c44877473c" which is a userId.

How can I do this?

答:
Your function is triggered by write operation to the Firebase Realtime Database:

```<code>exports.onvisitorPresence = functions.database
    .ref("/VISITORS_PRESENCE/{uid1}/{uid2}").onWrite((event) => {
</code>```

To trigger a function by a write to Cloud Firestore you'd use:

```<code>exports.myFunctionName = functions.firestore
  .document('users/marie').onWrite((event) => {
</code>```

For a longer example, have a look at the documentation for triggering Cloud Functions from Firebase.

Body:
In the Cloud Firestore I try to create a Function trigger but I have some problems.

I want the Cloud Firestore Function to respond to writes at this Firebase Realtime databas location:

"VISITORS_PRESENCE" : {
    "8PICNP6JBTJDFGiBZYsT" : { // House for sale
      "3b1874ec-02f8-4004-817d-a3c44877473c" : { // The user Id
        "applicationId" : "3b1874ec-02f8-4004-817d-a3c44877473c",
        "last_changed" : 1510859721293,
        "state" : "online",
        "userId" : "testtest@test,com"
      }
    }
  },

and simply copy this values/writes into Cloud Firestore Using this functions:
(note this is based on the Cloud Firestore docs functions get-started

exports.onvisitorPresence = functions.database
    .ref("/VISITORS_PRESENCE/{uid1}/{uid2}").onWrite((event) => {
        // Get the data written to Realtime Database
        const eventStatus = event.data.val();

        // Then use other event data to create a reference to the
        // corresponding Firestore document.
        const userStatusFirestoreRef = firestore
        .doc(`VISITORS_PRESENCE/${event.params.uid1}/USERS/{event.params.uid2}`);

        // It is likely that the Realtime Database change that triggered
        // this event has already been overwritten by a fast change in
        // online / offline status, so we'll re-read the current data
        // and compare the timestamps.
        return event.data.ref.once("value").then((statusSnapshot) => {
            return statusSnapshot.val();
        }).then((status) => {
            console.log(status, eventStatus);
            // If the current timestamp for this data is newer than
            // the data that triggered this event, we exit this function.
            if (status.last_changed > eventStatus.last_changed) return;

            // Otherwise, we convert the last_changed field to a Date
            eventStatus.last_changed = new Date(eventStatus.last_changed);

            // ... and write it to Firestore.
            return userStatusFirestoreRef.set(eventStatus);
        });
    });

In the Cloud Firestore what this produces is this:

VISITORS_PRESENCE/8PICNP6JBTJDFGiBZYsT/USERS/{event.params.uid2}/

applicationId "3b1874ec-02f8-4004-817d-a3c44877473c"

last_changed November 16, 2017 at 8:15:21 PM UTC+1

state "online"

userId "testtest@test,com"

Here´s a pic:

I want the event.params.uid2in the above to be the "3b1874ec-02f8-4004-817d-a3c44877473c" which is a userId.

How can I do this?

Body:
Your function is triggered by write operation to the Firebase Realtime Database:

exports.onvisitorPresence = functions.database
    .ref("/VISITORS_PRESENCE/{uid1}/{uid2}").onWrite((event) => {

To trigger a function by a write to Cloud Firestore you'd use:

exports.myFunctionName = functions.firestore
  .document('users/marie').onWrite((event) => {

For a longer example, have a look at the documentation for triggering Cloud Functions from Firebase.


问:
No speedup using XGBClassifier with GPU support
In the following code, I try to search over different hyper-parameters of xgboost.

```<code>param_test1 = {
 'max_depth':list(range(3,10,2)),
 'min_child_weight':list(range(1,6,2))
}
predictors = [x for x in train_data.columns if x not in ['target', 'id']]
gsearch1 = GridSearchCV(estimator=XGBClassifier(learning_rate =0.1, n_estimators=100, max_depth=5,
                                                min_child_weight=1, gamma=0, subsample=0.8, colsample_bytree=0.8,
                                                objective= 'binary:logistic', n_jobs=4, scale_pos_weight=1, seed=27,
                                                kvargs={'tree_method':'gpu_hist'}),
                    param_grid=param_test1, scoring='roc_auc', n_jobs=4, iid=False, cv=5, verbose=2)
gsearch1.fit(train_data[predictors], train_data['target'])
</code>```

Even though I use kvargs={tree_method':'gpu_hist'}, I get no speedup in the implementation. According to the nvidia-smi, the GPU is not much involved in the computation:

```<code>+-----------------------------------------------------------------------------+
| NVIDIA-SMI 375.66                 Driver Version: 375.66                    |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  GeForce GTX 1080    Off  | 0000:01:00.0      On |                  N/A |
|  0%   39C    P8    10W / 200W |    338MiB /  8112MiB |      1%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID  Type  Process name                               Usage      |
|=============================================================================|
|    0       961    G   /usr/lib/xorg/Xorg                             210MiB |
|    0      1675    G   compiz                                         124MiB |
|    0      2359    G   /usr/lib/firefox/firefox                         2MiB |
+-----------------------------------------------------------------------------+
</code>```

I have installed the GPU supported xgboost using the following commands in Ubuntu:

```<code>$ git clone --recursive https://github.com/dmlc/xgboost
$ mkdir build
$ cd build
$ cmake .. -DUSE_CUDA=ON
$ make -j
</code>```

What is the possible reason?

答:
I'd like to revise two things. The installation of xgboost in Ubuntu,

make -j4

And as for Vivek's opinion, I'd like you to check the 'tree_method' parameter withe respect to the below.

http://xgboost.readthedocs.io/en/latest/parameter.html

Body:
In the following code, I try to search over different hyper-parameters of xgboost.

param_test1 = {
 'max_depth':list(range(3,10,2)),
 'min_child_weight':list(range(1,6,2))
}
predictors = [x for x in train_data.columns if x not in ['target', 'id']]
gsearch1 = GridSearchCV(estimator=XGBClassifier(learning_rate =0.1, n_estimators=100, max_depth=5,
                                                min_child_weight=1, gamma=0, subsample=0.8, colsample_bytree=0.8,
                                                objective= 'binary:logistic', n_jobs=4, scale_pos_weight=1, seed=27,
                                                kvargs={'tree_method':'gpu_hist'}),
                    param_grid=param_test1, scoring='roc_auc', n_jobs=4, iid=False, cv=5, verbose=2)
gsearch1.fit(train_data[predictors], train_data['target'])

Even though I use kvargs={tree_method':'gpu_hist'}, I get no speedup in the implementation. According to the nvidia-smi, the GPU is not much involved in the computation:

+-----------------------------------------------------------------------------+
| NVIDIA-SMI 375.66                 Driver Version: 375.66                    |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  GeForce GTX 1080    Off  | 0000:01:00.0      On |                  N/A |
|  0%   39C    P8    10W / 200W |    338MiB /  8112MiB |      1%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID  Type  Process name                               Usage      |
|=============================================================================|
|    0       961    G   /usr/lib/xorg/Xorg                             210MiB |
|    0      1675    G   compiz                                         124MiB |
|    0      2359    G   /usr/lib/firefox/firefox                         2MiB |
+-----------------------------------------------------------------------------+

I have installed the GPU supported xgboost using the following commands in Ubuntu:

$ git clone --recursive https://github.com/dmlc/xgboost
$ mkdir build
$ cd build
$ cmake .. -DUSE_CUDA=ON
$ make -j

What is the possible reason?


问:
Datagrid vs Gridview

Possible Duplicate:

  The Difference Between a DataGrid and a GridView in ASP.NET?

What is main difference between Data grid and Grid View in asp.net?

答: Basically if you use GridView you have a lot of options which is useful and you don't have to write code for that functions.</p>

Title: Datagrid vs Gridview


问:
Installing an SQL Server Sample Database in SQL Server 2017 using SSMS
I am brand new to SQL. I have not written SQL and do not have any prior experience. I am following an SQL tutorial on Udemy and to follow along I need to restore a database and retrieve both the mdf and ldf files.

I tried using the Northwind sample database which I downloaded from this website: http://northwinddatabase.codeplex.com/

I then click on create new Query in SSMS

and ran the following query which executed successfully:

I then ran this query which resulted in an error:

I naviagted to the my D drive on my file system and there is no folder there named MSSQLDataFiles. My C drive has only 45 GB left of space and I'm wondering if that may be an issue although I don't think that should be an issue at all, at least for what I am trying to achieve.

All I'm interested in is restoring the database file so that I can follow along with the Udemy tutorial.

Any suggestions would be greatly appreciated.

Thank you for your help

答:
The database will be created once you restored the ".bak" file. System itself created the ".ldf" and ".mdf" files in respective root folder.
refer the below site then you can achieve what you requested.

https://www.mssqltips.com/sqlservertip/4933/sql-server-2017-restore-database-error-in-ssms/


问:
Rails and JSON data, only override if has been updated or new
I have a whatever cronjob that gets JSON data from an external URL and saves to my database. I'm looking for an option to only add or update records that are new or have been changed since the last rake task. At the moment it just creates over the old data.

Rake Task

```<code>namespace :properties do
  desc "Save Properties from API to database"
  task upload: :environment do

    json = JSON.parse('{"Property":[{"id":"1","street":"123 Fake Street","town":"Someplace","postcode":"000000"}]}')

    json['Property'].each do |data|
      property = Property.create
      property.id = data['id']
      property.street = data['street']
      property.town = data['town']
      property.postcode = data['postcode']
      property.save
    end

  end
end
</code>```

答:
To achieve this I did:

```<code>json['Property'].each do |data|
 property = Property.find_or_create_by(id: data['id'])
 property.id = data['id']
 property.street = data['street']
 property.town = data['town']
 property.postcode = data['postcode']
 property.save
end
</code>```

Thanks to @Sajin.

Body:
I have a whatever cronjob that gets JSON data from an external URL and saves to my database. I'm looking for an option to only add or update records that are new or have been changed since the last rake task. At the moment it just creates over the old data.

Rake Task

namespace :properties do
  desc "Save Properties from API to database"
  task upload: :environment do

    json = JSON.parse('{"Property":[{"id":"1","street":"123 Fake Street","town":"Someplace","postcode":"000000"}]}')

    json['Property'].each do |data|
      property = Property.create
      property.id = data['id']
      property.street = data['street']
      property.town = data['town']
      property.postcode = data['postcode']
      property.save
    end

  end
end

Body:
To achieve this I did:

json['Property'].each do |data|
 property = Property.find_or_create_by(id: data['id'])
 property.id = data['id']
 property.street = data['street']
 property.town = data['town']
 property.postcode = data['postcode']
 property.save
end

Thanks to @Sajin.


问:
Cognitive Services via CLI in Azure Government
The docs mention that it can be accessed via CLI, but there are no samples for CLI in the docs, only PowerShell.

Any advice on where to get started?

答:
You can find the details on how to manage Cognitive Services in the Cognitive Services Azure CLI documentation.

As usual with Azure Government:

Set your CLI to Azure Government via the az cloud set --name=AzureUSGovernment

Use the Azure Government regions.

Use the subset of APIs available in Azure Government (see this doc for the literal values to use with --kind).

Use the subset of SKUs available in Azure Government

Here's a quick sample on how to get going:

```<code>az cloud set --name AzureUSGovernment
az login

az group create -n cogstestrg -l usgovvirginia

az cognitiveservices account create -n cogstestcv -g cogstestrg --sku S0 --kind ComputerVision -l usgovvirginia

az cognitiveservices account show -g cogstestrg -n cogstestcv

az cognitiveservices account keys list -g cogstestrg -n cogstestcv

#Make sure you REPLACE_WITH_YOUR_KEY in the curl command below using the key from the previous command
curl -v -X POST "https://virginia.api.cognitive.microsoft.us/vision/v1.0/analyze?visualFeatures=Categories,Description,Color&details=&language=en" -H "Content-Type: application/json" -H "Ocp-Apim-Subscription-Key: REPLACE_WITH_YOUR_KEY" --data-ascii "{'url' : 'http://upload.wikimedia.org/wikipedia/commons/3/3c/Shaki_waterfall.jpg'}"
</code>```

Body:
You can find the details on how to manage Cognitive Services in the Cognitive Services Azure CLI documentation.

As usual with Azure Government:

Set your CLI to Azure Government via the az cloud set --name=AzureUSGovernment

Use the Azure Government regions.

Use the subset of APIs available in Azure Government (see this doc for the literal values to use with --kind).

Use the subset of SKUs available in Azure Government

Here's a quick sample on how to get going:

az cloud set --name AzureUSGovernment
az login

az group create -n cogstestrg -l usgovvirginia

az cognitiveservices account create -n cogstestcv -g cogstestrg --sku S0 --kind ComputerVision -l usgovvirginia

az cognitiveservices account show -g cogstestrg -n cogstestcv

az cognitiveservices account keys list -g cogstestrg -n cogstestcv

#Make sure you REPLACE_WITH_YOUR_KEY in the curl command below using the key from the previous command
curl -v -X POST "https://virginia.api.cognitive.microsoft.us/vision/v1.0/analyze?visualFeatures=Categories,Description,Color&details=&language=en" -H "Content-Type: application/json" -H "Ocp-Apim-Subscription-Key: REPLACE_WITH_YOUR_KEY" --data-ascii "{'url' : 'http://upload.wikimedia.org/wikipedia/commons/3/3c/Shaki_waterfall.jpg'}"


问:
Count down timer show wrong values : Android
I'm using CountDownTimer in my Application and it's showing wrong hours.
this is what i tried.

```<code>long miliSecsDate = milliseconds ("2017-11-18 12:35");
</code>```

Convert date and time in to miliseconds

```<code>public long milliseconds(String date)
            {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                try
                {
                    Date mDate = sdf.parse(date);
                    long timeInMilliseconds = mDate.getTime();
                    return timeInMilliseconds;
                }
                catch (ParseException e)
                {
                    e.printStackTrace();
                }
                return 0;
            }
</code>```

Countdown timer

```<code>public void showCountdown(long miliSecsDate){
        new CountDownTimer(miliSecsDate, 1000) {
            public void onTick(long millisUntilFinished) {
                long seconds= TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished);

                int minutes = (int)(seconds % 3600) / 60;
                int hours = (int)seconds / 3600;
                seconds = seconds % 60;
                Log.d("time",""+hours+" : "+minutes+" : "+seconds);
          }
            public void onFinish() {
                txtRemainingTime.setText("done!");
            }

        }.start();
    }
</code>```

my Log cat showing like below

D/time: 419719 : 3 : 43

答:
Try using:

```<code>    String myDate = "2017-11-18 12:35";
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    Date date = sdf.parse(myDate);
    long millis = date.getTime();

    long seconds = millis/1000;
    long sec = seconds % 60;
    long min = (seconds / 60) % 60;
    long hrs = (seconds / (60 * 60)) % 24;

    Log.d("time",""+hrs+" : "+min+" : "+sec);
</code>```

If you want to use TimeUnit class Refer link

Body:
I'm using CountDownTimer in my Application and it's showing wrong hours.
this is what i tried.

long miliSecsDate = milliseconds ("2017-11-18 12:35");

Convert date and time in to miliseconds

public long milliseconds(String date)
            {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                try
                {
                    Date mDate = sdf.parse(date);
                    long timeInMilliseconds = mDate.getTime();
                    return timeInMilliseconds;
                }
                catch (ParseException e)
                {
                    e.printStackTrace();
                }
                return 0;
            }

Countdown timer

public void showCountdown(long miliSecsDate){
        new CountDownTimer(miliSecsDate, 1000) {
            public void onTick(long millisUntilFinished) {
                long seconds= TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished);

                int minutes = (int)(seconds % 3600) / 60;
                int hours = (int)seconds / 3600;
                seconds = seconds % 60;
                Log.d("time",""+hours+" : "+minutes+" : "+seconds);
          }
            public void onFinish() {
                txtRemainingTime.setText("done!");
            }

        }.start();
    }

my Log cat showing like below

D/time: 419719 : 3 : 43

Body:
Try using:

    String myDate = "2017-11-18 12:35";
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    Date date = sdf.parse(myDate);
    long millis = date.getTime();

    long seconds = millis/1000;
    long sec = seconds % 60;
    long min = (seconds / 60) % 60;
    long hrs = (seconds / (60 * 60)) % 24;

    Log.d("time",""+hrs+" : "+min+" : "+sec);

If you want to use TimeUnit class Refer link


问:
How to align  value to center vertically?
I need to align td cell value to center, both horizontally and vertically.  has a rowspan attribute.

The output right now is like:

```<code>A  |  B  |  C  |  D
1  |  2  |  3  |  4
1  |  2  |  3  |
1  |  2  |  3  |
</code>```

Desired:

```<code>A  |  B  |  C  |  D
1  |  2  |  3  |
1  |  2  |  3  |  4
1  |  2  |  3  |
1  |  2  |  3  |
</code>```

答:
use 4	 its work

table td {
  padding: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table border="1">
  <tr>
    <td>A</td>
    <td>B</td>
    <td>C</td>
    <td>D</td>
  </tr>
  <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
    <td rowspan="4" align="center">4</td>
  </tr>
  <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
  </tr>
  <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>

  </tr>
  <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
  </tr>

</table></code>```

Title: How to align <td rowspan ="value"> value to center vertically?

Body:
I need to align td cell value to center, both horizontally and vertically.  has a rowspan attribute.

The output right now is like:

A  |  B  |  C  |  D
1  |  2  |  3  |  4
1  |  2  |  3  |
1  |  2  |  3  |

Desired:

A  |  B  |  C  |  D
1  |  2  |  3  |
1  |  2  |  3  |  4
1  |  2  |  3  |
1  |  2  |  3  |

Body:
use <td rowspan="4" align="center">4</td> its work

table td {
  padding: 5px;
}

<table border="1">
  <tr>
    <td>A</td>
    <td>B</td>
    <td>C</td>
    <td>D</td>
  </tr>
  <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
    <td rowspan="4" align="center">4</td>
  </tr>
  <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
  </tr>
  <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>

  </tr>
  <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
  </tr>

</table>


问:
Wanting to return data to front end,not view - Spring Framework
I have set up an endpoint using Spring Framework.  My controller is being hit when I visit my URL, it grabs the JSON data that is sent and I can persist stuff to the database.  On either success or fail, I would like to return data to the front end instead of resolve the returned String as a view.  If I return a string then it trys to go to that page as I see ../WEB-INF/views/.html as where it wants to go and I get a 404.  All help is appreciated!

cc-servlet.xml

```<code><beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.1.xsd">

<context:component-scan base-package="
        com.classycartridges.controllers,
        com.classycartridges.mappers,
        com.classycartridges.objects,
        com.classycartridges.services" />

<mvc:annotation-driven />

<bean id="viewResolver"
    class="org.springframework.web.servlet.view.UrlBasedViewResolver">
    <property name="viewClass"
        value="org.springframework.web.servlet.view.JstlView" />
    <property name="prefix" value="/WEB-INF/views/" />
    <property name="suffix" value=".html" />
</bean>

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  <property name="driverClassName" value="com.mysql.jdbc.Driver" />
  <property name="url" value="xxxx" />
  <property name="username" value="xxxx" />
  <property name="password" value="xxxx" />
</bean>

<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  <property name="dataSource" ref="dataSource" />
</bean>

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  <property name="dataSource" ref="dataSource" />
  <property name="typeAliasesPackage" value="com.classycartridges.objects"/>
  <!--<property name="mapperLocations" value="classpath*:com/github/elizabetht/mappers/*.xml" />-->
</bean>

<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
  <constructor-arg index="0" ref="sqlSessionFactory" />
</bean>

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  <property name="basePackage" value="com.classycartridges.mappers" />
</bean>
</code>```

web.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <display-name>cc</display-name>
  <servlet>
    <servlet-name>cc</servlet-name>
    <servlet-class>
        org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
<load-on-startup>1</load-on-startup>
    </servlet>
  <servlet-mapping>
    <servlet-name>cc</servlet-name>
    <url-pattern>/create</url-pattern>
  </servlet-mapping>
</web-app>
</code>```

AccountController

```<code>package com.classycartridges.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.classycartridges.objects.Status;
import com.classycartridges.objects.UserAccount;
import com.classycartridges.services.AccountService;

@Controller
public class AccountController {

    @Autowired
    private AccountService accountService;

    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public Status createNewUserAccount(UserAccount userAccount) {
        //System.out.println("username: " + userAccount.getUsername() + " email: " + userAccount.getEmail() + " password: " + userAccount.getPassword());
        String check = accountService.checkForExistingAccount(userAccount);
        Status status = new Status();
        //if the user email or username already exists, do not persist data
        if (("exists").equals(check)) {
            status.setStatusText("Error: Account already exists with the specified email or username.");
            return status;
        } else {
            accountService.createAccount(userAccount);
            status.setStatusText("Success, your account has been created.");
            return status;
        }

    }

}
</code>```

答:
Add @ResponseBody annotation to the method</p>

```<code>@ResponseBody
@RequestMapping(value = "/create", method = RequestMethod.POST)
    public Status createNewUserAccount(UserAccount userAccount) {
...
...
}
</code>```

Body:
I have set up an endpoint using Spring Framework.  My controller is being hit when I visit my URL, it grabs the JSON data that is sent and I can persist stuff to the database.  On either success or fail, I would like to return data to the front end instead of resolve the returned String as a view.  If I return a string then it trys to go to that page as I see ../WEB-INF/views/.html as where it wants to go and I get a 404.  All help is appreciated!

cc-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.1.xsd">

<context:component-scan base-package="
        com.classycartridges.controllers,
        com.classycartridges.mappers,
        com.classycartridges.objects,
        com.classycartridges.services" />

<mvc:annotation-driven />

<bean id="viewResolver"
    class="org.springframework.web.servlet.view.UrlBasedViewResolver">
    <property name="viewClass"
        value="org.springframework.web.servlet.view.JstlView" />
    <property name="prefix" value="/WEB-INF/views/" />
    <property name="suffix" value=".html" />
</bean>

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  <property name="driverClassName" value="com.mysql.jdbc.Driver" />
  <property name="url" value="xxxx" />
  <property name="username" value="xxxx" />
  <property name="password" value="xxxx" />
</bean>

<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  <property name="dataSource" ref="dataSource" />
</bean>

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  <property name="dataSource" ref="dataSource" />
  <property name="typeAliasesPackage" value="com.classycartridges.objects"/>

</bean>

<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
  <constructor-arg index="0" ref="sqlSessionFactory" />
</bean>

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  <property name="basePackage" value="com.classycartridges.mappers" />
</bean>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <display-name>cc</display-name>
  <servlet>
    <servlet-name>cc</servlet-name>
    <servlet-class>
        org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
<load-on-startup>1</load-on-startup>
    </servlet>
  <servlet-mapping>
    <servlet-name>cc</servlet-name>
    <url-pattern>/create</url-pattern>
  </servlet-mapping>
</web-app>

AccountController

package com.classycartridges.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.classycartridges.objects.Status;
import com.classycartridges.objects.UserAccount;
import com.classycartridges.services.AccountService;

@Controller
public class AccountController {

    @Autowired
    private AccountService accountService;

    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public Status createNewUserAccount(UserAccount userAccount) {
        //System.out.println("username: " + userAccount.getUsername() + " email: " + userAccount.getEmail() + " password: " + userAccount.getPassword());
        String check = accountService.checkForExistingAccount(userAccount);
        Status status = new Status();
        //if the user email or username already exists, do not persist data
        if (("exists").equals(check)) {
            status.setStatusText("Error: Account already exists with the specified email or username.");
            return status;
        } else {
            accountService.createAccount(userAccount);
            status.setStatusText("Success, your account has been created.");
            return status;
        }

    }

}

Body:
Add @ResponseBody annotation to the method

@ResponseBody
@RequestMapping(value = "/create", method = RequestMethod.POST)
    public Status createNewUserAccount(UserAccount userAccount) {
...
...
}


问:
can we use sql compact edition data base for multiple system network access
Hi now we are using sql compact edition database for windows forms in .net..and i am using data base for multiple systems by sharing but while using it....it is showing an error that already another process is using it...so can u please fix the problem and tell me there is any solution to solve this problem....thaks in advance</p>

答: SQL Server Compact only supports connections from a single machine, so no network access allowed, for this requirement you should use SQL Server Express.</p>


问:
Why Either value is not discarded?
Have the following in ghci:

```<code>:m + Control.Monad.Error
let f x = Right x

Left 1.0 >> Right 1 >>= f
</code>```

gives

```<code>Left 1.0
</code>```

As I understand >> operator discards monadic result of the first argument,
but I see that here it is preserved. Could you please explain?

http://hackage.haskell.org/package/base-4.10.0.0/docs/src/Data.Either.html#Either

strangely, that link doesn't show how Either is implementing methods of Monad typeclass.

答:
The "result" which is being discarded refers only to the a values contained in (not always literally) an m a value, not the rest of it. In case of Either it means that the value of a Right will be ignored, but not whether it's Left or Right, or the value of a Left.

If you combine the definition of >>= for Either and the default definition of >>, you'll see that >> here is effectively

```<code>Left  l >> x = Left  l >>= \_ -> x = Left l
Right r >> x = Right r >>= \_ -> x = x
</code>```

and the result in the second clause indeed doesn't depend on r.

Title: Why Either value is not discarded?

Body:
Have the following in ghci:

:m + Control.Monad.Error
let f x = Right x

Left 1.0 >> Right 1 >>= f

gives

Left 1.0

As I understand >> operator discards monadic result of the first argument,
but I see that here it is preserved. Could you please explain?

http://hackage.haskell.org/package/base-4.10.0.0/docs/src/Data.Either.html#Either

strangely, that link doesn't show how Either is implementing methods of Monad typeclass.

Body:
The "result" which is being discarded refers only to the a values contained in (not always literally) an m a value, not the rest of it. In case of Either it means that the value of a Right will be ignored, but not whether it's Left or Right, or the value of a Left.

If you combine the definition of >>= for Either and the default definition of >>, you'll see that >> here is effectively

Left  l >> x = Left  l >>= \_ -> x = Left l
Right r >> x = Right r >>= \_ -> x = x

and the result in the second clause indeed doesn't depend on r.


问:
How to choose Cassandra version?
I'm sql coder and new in Cassandra, which version should I choose, Cassandra 3.X or Cassandra 2.X?

We already have cassandra-2.1.17 but it could not support any aggregate function at all, I want to upgrade to cassandra 3.X but I don't know much about the difference, just want to get some advice, appreciate.

答: The latest stable release of Cassandra is 3.11.1. It would be good to upgrade yourself with it. I have tested and used 3.11.0 with satisfaction. You can check the latest release and changelog here - http://cassandra.apache.org/</p>

Title: How to choose Cassandra version?


答:
Use the align attribute

```<code><td align="center">Name</td>
</code>```

Body:
Use the align attribute

<td align="center">Name</td>


问:
Why one of the two object instances pointing to the same object behaves differently upon assigning NULL to any of them?
Consider below code snippet :

```<code><?php
  class SimpleClass {
    // property declaration
    public $var = 'a default value';

    // method declaration
    public function displayVar() {
      echo $this->var;
    }
  }

  $instance = new SimpleClass();

  $assigned   =  $instance;

  $instance->var = '$assigned will have this value';
  var_dump($instance);
  echo "<br>";
  var_dump($assigned);
?>
</code>```

The output of above code is as below :

```<code>object(SimpleClass)#1 (1) { ["var"]=> string(30) "$assigned will have this value" }
object(SimpleClass)#1 (1) { ["var"]=> string(30) "$assigned will have this value" }
</code>```

I understood the above program well. I understood the fact that any changes to either $instance or $assigned will be reflected in the other, because they are pointing to the same object instance.

But this principle is failing in below code upon assigning NULL to any of the two object instances. It is expected that both of the object instances should become NULL but one of the two contains NULL and other doesn't contain NULL. Why so?

```<code><?php
  class SimpleClass {
    // property declaration
    public $var = 'a default value';

    // method declaration
    public function displayVar() {
      echo $this->var;
    }
  }

  $instance = new SimpleClass();

  $assigned   =  $instance;

  $instance = NULL;
  var_dump($instance);
  echo "<br>";
  var_dump($assigned);
?>
</code>```

Output of above code is as below :

```<code>NULL
object(SimpleClass)#1 (1) { ["var"]=> string(15) "a default value" }
</code>```

Also, in the above code no where the class method displayVar() is being called which echoes the text 'a default value' nor there is any constructor method present then how the var property of an object instance $assigned is getting set instead of having NULL in it?

As both of the object instances are pointing to the same object why they behave in one way when NULLis assigned to one of them and other(the expected) way when string or some meaningful value is assigned to one of them?

答:
$assigned = $instance means that you're copying a pointer because whenever you assign a new object to a variable, you're basically making a pointer reference to the object.

So when you do $instance = NULL you're assigning null to the $instance variable while $assigned still pointing to the object that you created previously

Have a look at this link http://php.net/manual/en/language.oop5.references.php

Body:
Consider below code snippet :

<?php
  class SimpleClass {
    // property declaration
    public $var = 'a default value';

    // method declaration
    public function displayVar() {
      echo $this->var;
    }
  }

  $instance = new SimpleClass();

  $assigned   =  $instance;

  $instance->var = '$assigned will have this value';
  var_dump($instance);
  echo "
";
  var_dump($assigned);
?>

The output of above code is as below :

object(SimpleClass)#1 (1) { ["var"]=> string(30) "$assigned will have this value" }
object(SimpleClass)#1 (1) { ["var"]=> string(30) "$assigned will have this value" }

I understood the above program well. I understood the fact that any changes to either $instance or $assigned will be reflected in the other, because they are pointing to the same object instance.

But this principle is failing in below code upon assigning NULL to any of the two object instances. It is expected that both of the object instances should become NULL but one of the two contains NULL and other doesn't contain NULL. Why so?

<?php
  class SimpleClass {
    // property declaration
    public $var = 'a default value';

    // method declaration
    public function displayVar() {
      echo $this->var;
    }
  }

  $instance = new SimpleClass();

  $assigned   =  $instance;

  $instance = NULL;
  var_dump($instance);
  echo "
";
  var_dump($assigned);
?>

Output of above code is as below :

NULL
object(SimpleClass)#1 (1) { ["var"]=> string(15) "a default value" }

Also, in the above code no where the class method displayVar() is being called which echoes the text 'a default value' nor there is any constructor method present then how the var property of an object instance $assigned is getting set instead of having NULL in it?

As both of the object instances are pointing to the same object why they behave in one way when NULLis assigned to one of them and other(the expected) way when string or some meaningful value is assigned to one of them?


问:
Problems with through associations
I'm looking to loop through an association and include a through association as well. I'm getting an undefined method `name' for nil:NilClass error on the below.

I have an account model which has_many sales, which works fine. But sales is linked via previousAgents through previous_agent_id and this is where i'm having the problem.

Account Model

```<code>has_many :sales, primary_key: 'account_id'
</code>```

Sales Model

```<code>belongs_to :previousAgent, primary_key: 'previous_agent_id'
</code>```

Account View

```<code><% @account.sales.each do |p| %>
 <p>Previous Agent <%= p.previousAgent.name %></p>
 <p>Date: <%= p.date.strftime("%d %B, %Y") %></p>
 <p>Comments: <%= p.comment %></p>
<% end %>
</code>```

答:
Use

```<code><%= p.previousAgents.first.name %>
</code>```

Account has_many previousAgents

So, p.previousAgents will return Array of the previousAgent if you want to show all the previous agents do following.

```<code><% @account.sales.each do |p| %>
 <% for agent in p.previousAgents %>
   <p>Previous Agent <%= agent.name %></p>
 <% end %>
 <p>Date: <%= p.date.strftime("%d %B, %Y") %></p>
 <p>Comments: <%= p.comment %></p>
<% end %>
</code>```

EDITED, as Question is get edited.

```<code><%= p.previousAgent.try(:name) %>
</code>```

So, if p.previousAgent is nil it will not throw an error & if p.previousAgent returns the object of PreviousAgent then above code will return the values of the name attribute.

Check try method here

Title: Problems with through associations

Body:
I'm looking to loop through an association and include a through association as well. I'm getting an undefined method `name' for nil:NilClass error on the below.

I have an account model which has_many sales, which works fine. But sales is linked via previousAgents through previous_agent_id and this is where i'm having the problem.

Account Model

has_many :sales, primary_key: 'account_id'

Sales Model

belongs_to :previousAgent, primary_key: 'previous_agent_id'

Account View

<% @account.sales.each do |p| %>

Previous Agent <%= p.previousAgent.name %>

Date: <%= p.date.strftime("%d %B, %Y") %>

Comments: <%= p.comment %>

<% end %>

Body:
Use

<%= p.previousAgents.first.name %>

Account has_many previousAgents

So, p.previousAgents will return Array of the previousAgent if you want to show all the previous agents do following.

<% @account.sales.each do |p| %>
 <% for agent in p.previousAgents %>
   <p>Previous Agent <%= agent.name %></p>
 <% end %>
 <p>Date: <%= p.date.strftime("%d %B, %Y") %></p>
 <p>Comments: <%= p.comment %></p>
<% end %>

EDITED, as Question is get edited.

<%= p.previousAgent.try(:name) %>

So, if p.previousAgent is nil it will not throw an error & if p.previousAgent returns the object of PreviousAgent then above code will return the values of the name attribute.

Check try method here


问:
Node / Express: EADDRINUSE, Address already in use - Kill server
I have a simple server running in node.js using connect:

```<code>var server = require('connect').createServer();
//actions...
server.listen(3000);
</code>```

In my code I have actual handlers, but thats the basic idea. The problem I keep getting is

```<code>EADDRINUSE, Address already in use
</code>```

I receive this error when running my application again after it previously crashed or errors. Since I am not opening a new instance of terminal I close out the process with ctr + z.

I am fairly certain all I have to do is close out the server or connection. I tried calling server.close() in process.on('exit', ...); with no luck.

答:
Check the PID i.e. id of process running on port 3000 with below command :

```<code>lsof -i tcp:3000
</code>```

It would output something like following:

```<code>COMMAND  PID   USER   FD   TYPE  DEVICE  SIZE/OFF NODE NAME
node     5805  xyz    12u  IPv6  63135    0t0     TCP  *:3000 (LISTEN)
</code>```

Now kill the process using :

```<code>kill -9 5805
</code>```

Body:
I have a simple server running in node.js using connect:

var server = require('connect').createServer();
//actions...
server.listen(3000);

In my code I have actual handlers, but thats the basic idea. The problem I keep getting is

EADDRINUSE, Address already in use

I receive this error when running my application again after it previously crashed or errors. Since I am not opening a new instance of terminal I close out the process with ctr + z.

I am fairly certain all I have to do is close out the server or connection. I tried calling server.close() in process.on('exit', ...); with no luck.

Body:
Check the PID i.e. id of process running on port 3000 with below command :

lsof -i tcp:3000

It would output something like following:

COMMAND  PID   USER   FD   TYPE  DEVICE  SIZE/OFF NODE NAME
node     5805  xyz    12u  IPv6  63135    0t0     TCP  *:3000 (LISTEN)

Now kill the process using :

kill -9 5805