问:
Oracle PL/SQL : to_date() format not considered
When I execute this in PL/SQL Developer :

```<code>SELECT to_date('29/03/17 14:05','DD/MM/RR HH24:MI')  FROM dual;
</code>```

Here's what I get :

```<code>3/29/2017 2:05:00 PM
</code>```

How is this possible ? I use HH24 but it seems like it's HH that's being used instead. The day and month are also not in the format I entered.

答:
Ok, conceptual excercise coming up

Which of these dates represents the 1st January 2017?

```<code>01/01/2017
2017-01-01
01-JAN-2017
</code>```

That's right, all of them. The date datatype is not a format, it stores the value of the date, not how it appears.

If using Oracle, adjust your NLS_DATE_FORMAT to match your expectation, but again, this is just how the system will display the date, not how it stores it.

Body:
When I execute this in PL/SQL Developer :

SELECT to_date('29/03/17 14:05','DD/MM/RR HH24:MI')  FROM dual;

Here's what I get :

3/29/2017 2:05:00 PM

How is this possible ? I use HH24 but it seems like it's HH that's being used instead. The day and month are also not in the format I entered.

Body:
Ok, conceptual excercise coming up

Which of these dates represents the 1st January 2017?

01/01/2017
2017-01-01
01-JAN-2017

That's right, all of them. The date datatype is not a format, it stores the value of the date, not how it appears.

If using Oracle, adjust your NLS_DATE_FORMAT to match your expectation, but again, this is just how the system will display the date, not how it stores it.


来源: stackexchange

问:
Re indexing array-object in jquery
I have an array with object like this

```<code>var arr = [
  {'key1':'A','key2':1,'key3':0.04,'key4':10},
  {'key1':'B','key2':1,'key3':0.03,'key4':20},
  {'key1':'B','key2':2,'key3':0.05,'key4':30},
  {'key1':'A','key2':1,'key3':0.03,'key4':40},
  ...
];
</code>```

Inside array there can be unlimited objects. I need to create new array where every key1 and key2 must save unique and if same key1 and key2,then key3 must be added. My result for above array look like this

```<code>//Can be array or object
var a = [
  ['A'][1] => {'key3':0.07,'key4':50},
  ['B'][1] => {'key3':0.07,'key4':20},
  ['B'][2] => {'key3':0.05,'key4':30}
];
</code>```

My result can be array or object. What I have tried is

```<code>var a = {};
arr.forEach(function(obj){
  if(a[obj.key1]){
    if(a[obj.key1][obj.key2]){
      a[obj.key1][obj.key2] += obj.key3;
    }else{
      a[obj.key1][obj.key2] = obj.key3;
    }
  }else{
    a[obj.key1] = obj.key1;
  }
});
console.log(a);
</code>```

And I am getting only depth of result. Please suggest me how can I get my result output from given array object.
Thanks in advance.

答:
For more nested objects, you could use an array for grouping the keys and one for the keys with the value to add. Then build a new object, if necessary and assign the values.

var array = [{ key1: 'A', key2: 1, key3: 0.04, key4: 10 }, { key1: 'B', key2: 1, key3: 0.03, key4: 20 }, { key1: 'B', key2: 2, key3: 0.05, key4: 30 }, { key1: 'A', key2: 1, key3: 0.03, key4: 40 }],
    groupKeys = ['key1', 'key2'],
    valueKeys = ['key3', 'key4'],
    result = Object.create(null);

array.forEach(function (a) {
    var object = groupKeys.reduce(function (r, k) {
        return r[a[k]] = r[a[k]] || {};
    }, result);
    valueKeys.forEach(function (k) {
        object[k] = (object[k] || 0) + a[k];
    });
});

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

ContentLicense: CC BY-SA 3.0

Title: Re indexing array-object in jquery

Body:
I have an array with object like this

var arr = [
  {'key1':'A','key2':1,'key3':0.04,'key4':10},
  {'key1':'B','key2':1,'key3':0.03,'key4':20},
  {'key1':'B','key2':2,'key3':0.05,'key4':30},
  {'key1':'A','key2':1,'key3':0.03,'key4':40},
  ...
];

Inside array there can be unlimited objects. I need to create new array where every key1 and key2 must save unique and if same key1 and key2,then key3 must be added. My result for above array look like this

//Can be array or object
var a = [
  ['A'][1] => {'key3':0.07,'key4':50},
  ['B'][1] => {'key3':0.07,'key4':20},
  ['B'][2] => {'key3':0.05,'key4':30}
];

My result can be array or object. What I have tried is

var a = {};
arr.forEach(function(obj){
  if(a[obj.key1]){
    if(a[obj.key1][obj.key2]){
      a[obj.key1][obj.key2] += obj.key3;
    }else{
      a[obj.key1][obj.key2] = obj.key3;
    }
  }else{
    a[obj.key1] = obj.key1;
  }
});
console.log(a);

And I am getting only depth of result. Please suggest me how can I get my result output from given array object.
Thanks in advance.

Body:
For more nested objects, you could use an array for grouping the keys and one for the keys with the value to add. Then build a new object, if necessary and assign the values.

var array = [{ key1: 'A', key2: 1, key3: 0.04, key4: 10 }, { key1: 'B', key2: 1, key3: 0.03, key4: 20 }, { key1: 'B', key2: 2, key3: 0.05, key4: 30 }, { key1: 'A', key2: 1, key3: 0.03, key4: 40 }],
    groupKeys = ['key1', 'key2'],
    valueKeys = ['key3', 'key4'],
    result = Object.create(null);

array.forEach(function (a) {
    var object = groupKeys.reduce(function (r, k) {
        return r[a[k]] = r[a[k]] || {};
    }, result);
    valueKeys.forEach(function (k) {
        object[k] = (object[k] || 0) + a[k];
    });
});

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
How to fix - 41: non-static variable cannot be referenced from a static context -> What is the reason for this?
I'm trying to write this code to get the first initialCapacity prime numbers and then print them in sequence using java. It isn't working for two reasons, firstly I get the error

41: non-static variable listOfPrimeNumbers cannot be referenced from a static context

when I try to run the program, but even when I change the variable to static and run the program, it will only print out "1". So it is only iterating the while loop in the constructor Primes once, and then stopping and I simply cannot find the problem there no matter how hard I look ! Would anyone be able to help me out please, even if you could just give a very quick look and tell me what could be wrong, I'd really appreciate it.

Also, what is the story with relation to non-static and static variables and methods ? What is the best practice when using these ? If anyone could link me to a page describing this (I have googled to no avail!) I would love to read up :)

Thank you all so much !

```<code>import java.util.*;
public class Primes {
  private ArrayList<Integer> listOfPrimeNumbers;

  public static void main(String[] args) {
    ArrayList<Integer> listOfPrimeNumbers;
    Primes generator=new Primes(50);
    print();
  }

  public Primes( int initialCapacity) {
    listOfPrimeNumbers = new ArrayList<Integer>(initialCapacity);
    int index=0;
    int counter=0;
    while (counter != initialCapacity  ) {
      if (isPrime(index)) {
        listOfPrimeNumbers.add(index);
        counter++;
        System.out.println(counter);
        index++;
      }
      else {
        index++;
      }
    }
  }
  public boolean isPrime(int candidateNo) {
    Iterator<Integer> iter = listOfPrimeNumbers.iterator( );
    //in here ! ?
    int i=2;
    while ( iter.hasNext( ) ) {
      int next = iter.next( );
      if (next%i==0 && i!=1) {
        return false;
      }
    }
    return true;
  }

  public static void print( ) {
    int n = listOfPrimeNumbers.size();
    for(int i = 0; i <= n ; i++)
      System.out.println( listOfPrimeNumbers.get( i ) );

  }
}
</code>```

I have edited my code now so that everything is static (meaning I can have multiple instances?). I now have this, the problem being it just prints out the first 51 numbers, and then gets a stack overflow, can anyone help ? Thank you :) :

```<code>import java.util.*;
public class Primes {
  private static ArrayList<Integer> listOfPrimeNumbers;

  public static void main(String[] args) {
    ArrayList<Integer> listOfPrimeNumbers;
    Primes generator=new Primes(50);
    print();
  }

  public Primes( int initialCapacity) {
    listOfPrimeNumbers = new ArrayList<Integer>(initialCapacity);
    int index=2;
    int counter=0;
    while (counter != initialCapacity  ) {
      if (isPrime(index)) {
        listOfPrimeNumbers.add(index);
        counter++;
        System.out.println(counter);
        index++;
      }
      else {
        index++;
      }
    }
  }
  public boolean isPrime(int candidateNo) {
    Iterator<Integer> iter = listOfPrimeNumbers.iterator( );
    while ( iter.hasNext( ) ) {
      int next = iter.next( );
      if (next%candidateNo==0 && candidateNo!=1) {
        return false;
      }
    }
    return true;
  }

  public static void print( ) {
    int n = listOfPrimeNumbers.size();
    for(int i = 0; i <= n ; i++)
      System.out.println( listOfPrimeNumbers.get( i ) );

  }
}
</code>```

答:
listOfPrimeNumbers is a member of your class, which means that each instance of Primes has its own copy of listOfPrimeNumbers.

print is a static function, which means that it is not related to an instance of Primes, and as such, it doesn't have access to any of the listOfPrimeNumbers variables there are (one per instance of your class).

So listOfPrimeNumbers would have to be static (i.e. there is only one copy in the whole wide world), or print can't be static.

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to write this code to get the first initialCapacity prime numbers and then print them in sequence using java. It isn't working for two reasons, firstly I get the error

41: non-static variable listOfPrimeNumbers cannot be referenced from a static context

when I try to run the program, but even when I change the variable to static and run the program, it will only print out "1". So it is only iterating the while loop in the constructor Primes once, and then stopping and I simply cannot find the problem there no matter how hard I look ! Would anyone be able to help me out please, even if you could just give a very quick look and tell me what could be wrong, I'd really appreciate it.

Also, what is the story with relation to non-static and static variables and methods ? What is the best practice when using these ? If anyone could link me to a page describing this (I have googled to no avail!) I would love to read up :)

Thank you all so much !

import java.util.*;
public class Primes {
  private ArrayList<Integer> listOfPrimeNumbers;

  public static void main(String[] args) {
    ArrayList<Integer> listOfPrimeNumbers;
    Primes generator=new Primes(50);
    print();
  }

  public Primes( int initialCapacity) {
    listOfPrimeNumbers = new ArrayList<Integer>(initialCapacity);
    int index=0;
    int counter=0;
    while (counter != initialCapacity  ) {
      if (isPrime(index)) {
        listOfPrimeNumbers.add(index);
        counter++;
        System.out.println(counter);
        index++;
      }
      else {
        index++;
      }
    }
  }
  public boolean isPrime(int candidateNo) {
    Iterator<Integer> iter = listOfPrimeNumbers.iterator( );
    //in here ! ?
    int i=2;
    while ( iter.hasNext( ) ) {
      int next = iter.next( );
      if (next%i==0 && i!=1) {
        return false;
      }
    }
    return true;
  }

  public static void print( ) {
    int n = listOfPrimeNumbers.size();
    for(int i = 0; i <= n ; i++)
      System.out.println( listOfPrimeNumbers.get( i ) );

  }
}

I have edited my code now so that everything is static (meaning I can have multiple instances?). I now have this, the problem being it just prints out the first 51 numbers, and then gets a stack overflow, can anyone help ? Thank you :) :

import java.util.*;
public class Primes {
  private static ArrayList<Integer> listOfPrimeNumbers;

  public static void main(String[] args) {
    ArrayList<Integer> listOfPrimeNumbers;
    Primes generator=new Primes(50);
    print();
  }

  public Primes( int initialCapacity) {
    listOfPrimeNumbers = new ArrayList<Integer>(initialCapacity);
    int index=2;
    int counter=0;
    while (counter != initialCapacity  ) {
      if (isPrime(index)) {
        listOfPrimeNumbers.add(index);
        counter++;
        System.out.println(counter);
        index++;
      }
      else {
        index++;
      }
    }
  }
  public boolean isPrime(int candidateNo) {
    Iterator<Integer> iter = listOfPrimeNumbers.iterator( );
    while ( iter.hasNext( ) ) {
      int next = iter.next( );
      if (next%candidateNo==0 && candidateNo!=1) {
        return false;
      }
    }
    return true;
  }

  public static void print( ) {
    int n = listOfPrimeNumbers.size();
    for(int i = 0; i <= n ; i++)
      System.out.println( listOfPrimeNumbers.get( i ) );

  }
}


问:
Several ways of preventing a form to submit the normal way?
I have a little php experience and would like to learn ajax jQuery. I've been watching several tutorials on submitting a form without refreshing the page. I notice people use different ways to prevent a form from submitting the normal way (with a page refresh):

with the event.preventDefault() function

using return false

In a script I'm trying to understand the JS script starts with:

$("#submitBrandForm").unbind('submit').bind('submit', function() {

Does this also have the same functionality? This same script ends with 'return false', which confuses me (and makes me think the unbind - bind code has another purpose).

Thanks

答:
No, the third one doesn't do the same thing. unbind only removes any previously attached event handlers (via bind), it does not prevent the form from being submitted.

In your example unbind and bind are just used to replace the existing event handler(s). If you don't unbind first, bind will add a handler to the ones that are already attached. You'll also often see unbind('submit', ...) inside the handler for a submit event that programmatically submits the form, to prevent the function from calling itself endlessly, like in this answer.

By the way, bind and unbind have been deprecated, you should be using on and off.


问:
How can i change the date format for "list-month view" in full calendar?
I just want to change the date format for list month view('fc-list-heading-main') in full calendar. I tried all different way but i was not successful. Please let me know how can i change date format.

Any help would be appreciated.

答:
Right now i didn't find any solution for this. I didn't find any full calendar api for this. I have fixed this with jQuery.

```<code>jQuery('.fc-list-table .fc-list-heading').each(function () {
       jQuery(this).find(".fc-list-heading-main").html(jQuery(this).find(".fc-list-heading-main").text().split(',')[0].split(' ')[1]);
     });
     jQuery('.fc-list-table .fc-list-heading').each(function () {
       jQuery(this).find(".fc-list-heading-alt").html(jQuery(this).find(".fc-list-heading-alt").text().slice(0, 3));
     });
</code>```

Placed the above code after calendar rendered. Also added this code for next and previous events.

Body:
Right now i didn't find any solution for this. I didn't find any full calendar api for this. I have fixed this with jQuery.

jQuery('.fc-list-table .fc-list-heading').each(function () {
       jQuery(this).find(".fc-list-heading-main").html(jQuery(this).find(".fc-list-heading-main").text().split(',')[0].split(' ')[1]);
     });
     jQuery('.fc-list-table .fc-list-heading').each(function () {
       jQuery(this).find(".fc-list-heading-alt").html(jQuery(this).find(".fc-list-heading-alt").text().slice(0, 3));
     });

Placed the above code after calendar rendered. Also added this code for next and previous events.


问:
Adding annotations to MKMapview - found nil error
ok, I'm getting a bit frustrated with this.

I have a ViewController, which has two containers controlled by a segment controller.  One is for a table view of data, the other is for a map view of data.

The tableview loads perfectly.  The data is stored on a Firebase DB, and I have a struct set up that reads the Firebase DB, and the relevant cell code to populate the table.

My problem is with the MapView.  I am trying to set up the view so that it reads the data from the Struct and populates the map with various pins to show the location of each item.  All items in the data have lat and long coords.

When I run the app, It fails with unexpectedly found nil error,

The code of my mapView container is:

```<code>import UIKit
import MapKit

class TrackMapView: UIViewController, MKMapViewDelegate {

@IBOutlet weak var mapView: MKMapView!
var tr: newTracks!

override func viewDidLoad() {
    super.viewDidLoad()

    self.mapView.delegate = self

    let coordinate = CLLocationCoordinate2DMake(tr.lat,tr.lon)
    let mapItem = MKMapItem(placemark: MKPlacemark(coordinate: coordinate,addressDictionary:nil))
    mapItem.name = tr.name

}

}
</code>```

newTracks is my struct.

Can somebody help me build the code that allows me to get the data from the struct and place the pins on the map.  I am finding mapView code a bit frustrating.

my TableView container is as follows and has a number of functions to pull the data.

```<code>import UIKit
import GoogleMobileAds
import FirebaseDatabase
import CoreLocation
import MapKit

class TrackTableView: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate {

@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var searchBar: UISearchBar!

var TR: newTracks!
var track = [newTracks]()
var items: [newTracks] = []
var filteredTrack = [newTracks]()
var inSearchMode = false

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.dataSource = self
    tableView.delegate = self
    searchBar.delegate = self
    searchBar.returnKeyType = UIReturnKeyType.done

    getTrackData()

}
func getTrackData() {

    let result = FIRDatabase.database().reference(withPath: "tracks")
    result.observe(.value, with: { snapshot in
        var newItems: [newTracks] = []
        for item in snapshot.children {
            let trackDetails = newTracks(snapshot: item as! FIRDataSnapshot)
            newItems.append(trackDetails)
        }
        self.items = newItems
        self.items.sort(by: {$0.distance < $1.distance})
        self.tableView.reloadData()
    })
}

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if inSearchMode {
        return filteredTrack.count
    } else {
        return items.count
    }
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if let cell = tableView.dequeueReusableCell(withIdentifier: "TrackCell", for: indexPath) as? TrackCell {

        let tr: newTracks!
        if inSearchMode {
            tr = filteredTrack[indexPath.row]
            cell.configureCell(track: tr)
        } else {
            tr = items[indexPath.row]
            cell.configureCell(track: tr)
        }
        cell.configureCell(track: tr)

        cell.completion = {
            let coordinate = CLLocationCoordinate2DMake(tr.lat,tr.lon)
            let mapItem = MKMapItem(placemark: MKPlacemark(coordinate: coordinate,addressDictionary:nil))
            mapItem.name = tr.name
            mapItem.openInMaps(launchOptions: [MKLaunchOptionsDirectionsModeKey :MKLaunchOptionsDirectionsModeDriving])
            return()
        }

        return cell
    } else {
        return UITableViewCell()
    }

}

func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
    view.endEditing(true)
}

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    if searchBar.text == nil || searchBar.text == "" {
        inSearchMode = false
        tableView.reloadData()
        view.endEditing(true)
    } else {
        inSearchMode = true
        let lower = searchBar.text!
        filteredTrack =  items.filter({$0.name.range(of: lower) != nil})
        tableView.reloadData()

    }
}
}
</code>```

my storyboard, the top container works as a table view, the bottom one just displays an empty map, I need to get it showing the same data that is on the table view, but as pins on the map.

答:
I actually managed to resolve this by rethinking my MapViewController.  I added the following code, and it works perfectly now.</p>

```<code> func getTrackData() {

    let result = FIRDatabase.database().reference(withPath: "tracks")
    result.observe(.value, with: { snapshot in
        for item in snapshot.children {
            let objects = newTracks (snapshot: item as! FIRDataSnapshot)
            let lat = objects.lat
            let lon = objects.lon
            let name = objects.name
            let annotation = mapPoint(title: name!, locationName: name!, coordinate: CLLocationCoordinate2D(latitude: lat!, longitude: lon!))
            self.mapView.addAnnotation(annotation as MKAnnotation)
        }
    })
}

func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
    let location = view.annotation as! mapPoint
    let launchOptions = [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving]
    location.mapItem().openInMaps(launchOptions: launchOptions)
}
</code>```

Body:
ok, I'm getting a bit frustrated with this.

I have a ViewController, which has two containers controlled by a segment controller.  One is for a table view of data, the other is for a map view of data.

The tableview loads perfectly.  The data is stored on a Firebase DB, and I have a struct set up that reads the Firebase DB, and the relevant cell code to populate the table.

My problem is with the MapView.  I am trying to set up the view so that it reads the data from the Struct and populates the map with various pins to show the location of each item.  All items in the data have lat and long coords.

When I run the app, It fails with unexpectedly found nil error,

The code of my mapView container is:

import UIKit
import MapKit

class TrackMapView: UIViewController, MKMapViewDelegate {

@IBOutlet weak var mapView: MKMapView!
var tr: newTracks!

override func viewDidLoad() {
    super.viewDidLoad()

    self.mapView.delegate = self

    let coordinate = CLLocationCoordinate2DMake(tr.lat,tr.lon)
    let mapItem = MKMapItem(placemark: MKPlacemark(coordinate: coordinate,addressDictionary:nil))
    mapItem.name = tr.name

}

}

newTracks is my struct.

Can somebody help me build the code that allows me to get the data from the struct and place the pins on the map.  I am finding mapView code a bit frustrating.

my TableView container is as follows and has a number of functions to pull the data.

import UIKit
import GoogleMobileAds
import FirebaseDatabase
import CoreLocation
import MapKit

class TrackTableView: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate {

@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var searchBar: UISearchBar!

var TR: newTracks!
var track = [newTracks]()
var items: [newTracks] = []
var filteredTrack = [newTracks]()
var inSearchMode = false

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.dataSource = self
    tableView.delegate = self
    searchBar.delegate = self
    searchBar.returnKeyType = UIReturnKeyType.done

    getTrackData()

}
func getTrackData() {

    let result = FIRDatabase.database().reference(withPath: "tracks")
    result.observe(.value, with: { snapshot in
        var newItems: [newTracks] = []
        for item in snapshot.children {
            let trackDetails = newTracks(snapshot: item as! FIRDataSnapshot)
            newItems.append(trackDetails)
        }
        self.items = newItems
        self.items.sort(by: {$0.distance < $1.distance})
        self.tableView.reloadData()
    })
}

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if inSearchMode {
        return filteredTrack.count
    } else {
        return items.count
    }
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if let cell = tableView.dequeueReusableCell(withIdentifier: "TrackCell", for: indexPath) as? TrackCell {

        let tr: newTracks!
        if inSearchMode {
            tr = filteredTrack[indexPath.row]
            cell.configureCell(track: tr)
        } else {
            tr = items[indexPath.row]
            cell.configureCell(track: tr)
        }
        cell.configureCell(track: tr)

        cell.completion = {
            let coordinate = CLLocationCoordinate2DMake(tr.lat,tr.lon)
            let mapItem = MKMapItem(placemark: MKPlacemark(coordinate: coordinate,addressDictionary:nil))
            mapItem.name = tr.name
            mapItem.openInMaps(launchOptions: [MKLaunchOptionsDirectionsModeKey :MKLaunchOptionsDirectionsModeDriving])
            return()
        }

        return cell
    } else {
        return UITableViewCell()
    }

}

func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
    view.endEditing(true)
}

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    if searchBar.text == nil || searchBar.text == "" {
        inSearchMode = false
        tableView.reloadData()
        view.endEditing(true)
    } else {
        inSearchMode = true
        let lower = searchBar.text!
        filteredTrack =  items.filter({$0.name.range(of: lower) != nil})
        tableView.reloadData()

    }
}
}

my storyboard, the top container works as a table view, the bottom one just displays an empty map, I need to get it showing the same data that is on the table view, but as pins on the map.

Body:
I actually managed to resolve this by rethinking my MapViewController.  I added the following code, and it works perfectly now.

 func getTrackData() {

    let result = FIRDatabase.database().reference(withPath: "tracks")
    result.observe(.value, with: { snapshot in
        for item in snapshot.children {
            let objects = newTracks (snapshot: item as! FIRDataSnapshot)
            let lat = objects.lat
            let lon = objects.lon
            let name = objects.name
            let annotation = mapPoint(title: name!, locationName: name!, coordinate: CLLocationCoordinate2D(latitude: lat!, longitude: lon!))
            self.mapView.addAnnotation(annotation as MKAnnotation)
        }
    })
}

func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
    let location = view.annotation as! mapPoint
    let launchOptions = [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving]
    location.mapItem().openInMaps(launchOptions: launchOptions)
}


问:
How to delete last character from a string using jQuery?
How to delete last character from a string for instance in 123-4- when I delete 4 it should display 123- using jQuery.

答:
Why use jQuery for this?

```<code>str = "123-4";
alert(str.substring(0,str.length - 1));
</code>```

Of course if you must:

Substr w/ jQuery:

```<code>//example test element
 $(document.createElement('div'))
    .addClass('test')
    .text('123-4')
    .appendTo('body');

//using substring with the jQuery function html
alert($('.test').html().substring(0,$('.test').html().length - 1));
</code>```

Body:
Why use jQuery for this?

str = "123-4";
alert(str.substring(0,str.length - 1));

Of course if you must:

Substr w/ jQuery:

//example test element
 $(document.createElement('div'))
    .addClass('test')
    .text('123-4')
    .appendTo('body');

//using substring with the jQuery function html
alert($('.test').html().substring(0,$('.test').html().length - 1));


问:
Does fl parameter makes search faster in solr?
I am using solr for search and want to know if I should use fl means field parameter. By using it, will search be fater?

答:
Search itself won't be faster, but you could see gains for very large result sets. The data returned over the wire will be smaller and Solr / Lucene won't have to retrieve the content of the fields that aren't returned.

How much it'll actually change improve your application's performance in a measurable way depends on too many factors to give a definitive answer. It won't affect the response time negatively, but you'll have to spend more time maintaining which data to return from your queries for each type of query you're making.

Usually if you're not using the data (if none of your queries require the actual data) you can ask Solr to not store the actual data for the field instead.


问:
pandas read_csv incorrectly reading number of columns with sep=None
I have the following single column CSV file:

```<code>id
1
2
3
</code>```

When I read the csv with pandas.read_csv('path/to/csv') it can correctly read it.

However, requirements dictate that I must accept multiple delimiters so my existing code uses sep=None.

When reading the above CSV, pandas.read_csv('path/to/csv', sep=None) produces ValueError: Expected 2 fields in line 2, saw 1. Obviously it is incorrectly identifying a delimiter and expecting two columns.

Can anyone suggest a way around this that would allow me to continue accepting multiple delimiters but also correctly process the CSV above? Using a regex delimiter e.g. sep=';|,' is not acceptable due to it causing pandas to ignore quotations.

答:
This is the best solution we could find in the end:

```<code>data = csv_file.decode(chardet.detect(csv_file)['encoding'])
dialect = csv.Sniffer().sniff(StringIO(data).readline())
if dialect.delimiter.isalnum():
    dialect.delimiter = ','
pd.read_csv(StringIO(data), dialect=dialect)
</code>```

Reasoning that if the Sniffer cannot detect a delimiter, it is a single row CSV and setting the delimiter to , allows it to be read.

Body:
I have the following single column CSV file:

id
1
2
3

When I read the csv with pandas.read_csv('path/to/csv') it can correctly read it.

However, requirements dictate that I must accept multiple delimiters so my existing code uses sep=None.

When reading the above CSV, pandas.read_csv('path/to/csv', sep=None) produces ValueError: Expected 2 fields in line 2, saw 1. Obviously it is incorrectly identifying a delimiter and expecting two columns.

Can anyone suggest a way around this that would allow me to continue accepting multiple delimiters but also correctly process the CSV above? Using a regex delimiter e.g. sep=';|,' is not acceptable due to it causing pandas to ignore quotations.

Body:
This is the best solution we could find in the end:

data = csv_file.decode(chardet.detect(csv_file)['encoding'])
dialect = csv.Sniffer().sniff(StringIO(data).readline())
if dialect.delimiter.isalnum():
    dialect.delimiter = ','
pd.read_csv(StringIO(data), dialect=dialect)

Reasoning that if the Sniffer cannot detect a delimiter, it is a single row CSV and setting the delimiter to , allows it to be read.


问:
Controller action called twice
I am developing an web app with Laravel and I encountered this "strange" behavior. Some controller actions are called twice. I know so because on my logs I see (for one page refresh) two full sets of entries. My controller action starts like this:

```<code>public function action_edit($rid=-1) {
    // Calc Input
    $id  = Input::get('id', $rid);
    Log::TWICE("?? {$id} - {$rid}");
</code>```

where $rid is the object id to edit as requested by the url, however if I get an id in my Input, then I use this id instead. So when I call my controller via a url like:

.../mycontroller/edit/1

I get TWO entries  in my log file:

```<code>2013-02-07 00:49:15 TWICE - ?? 1 - 1
2013-02-07 00:49:16 TWICE - ?? img - img
</code>```

The first one is the normal that I should see, however the second one I don't understand where it is coming from. I checked using the Chrome's developer tools (both network tab and console tab) but there is no sign of the second request!! I initially thought that I might try to use some resource with a relative url of img or ../img but I found no clue. Of course img is the name of my images folder on my template but there is nowhere in my code a relative url img by itself...

Do you have any suggestions regarding this issue? Where else in my code should I examine/check? What else could trigger the second call?

NOTE: I am using the following call at some point on my code but the referenced action is 'show' not 'edit'!!

Laravel\Routing\Controller::call($controller.'@show',  ...

Thank you in advance!

Pan

答:
This is an old question, but I still see this at the top of the Google result when I search for solution, so I decided to add this answer after I finally find the problem.

The current answer that marked as correct is only partially correct: it is related to image, but it is not limited to Favicon.

Somehow all major browser (at least for IE, Firefox and Chrome) decide that when there is an empty link provided to whatever place that is supposed to be an image, they will make it the current URL. Some example of places that may cause problem:

```<code><img src="">
<div class="background-image:url()"></div>
<link rel="icon" type="image/x-icon" href="">
</code>```

Provide a link or simply remove the line will solve the problem.

Title: Controller action called twice

Body:
I am developing an web app with Laravel and I encountered this "strange" behavior. Some controller actions are called twice. I know so because on my logs I see (for one page refresh) two full sets of entries. My controller action starts like this:

public function action_edit($rid=-1) {
    // Calc Input
    $id  = Input::get('id', $rid);
    Log::TWICE("?? {$id} - {$rid}");

where $rid is the object id to edit as requested by the url, however if I get an id in my Input, then I use this id instead. So when I call my controller via a url like:

.../mycontroller/edit/1

I get TWO entries  in my log file:

2013-02-07 00:49:15 TWICE - ?? 1 - 1
2013-02-07 00:49:16 TWICE - ?? img - img

The first one is the normal that I should see, however the second one I don't understand where it is coming from. I checked using the Chrome's developer tools (both network tab and console tab) but there is no sign of the second request!! I initially thought that I might try to use some resource with a relative url of img or ../img but I found no clue. Of course img is the name of my images folder on my template but there is nowhere in my code a relative url img by itself...

Do you have any suggestions regarding this issue? Where else in my code should I examine/check? What else could trigger the second call?

NOTE: I am using the following call at some point on my code but the referenced action is 'show' not 'edit'!!

Laravel\Routing\Controller::call($controller.'@show',  ...

Thank you in advance!

Pan

Body:
This is an old question, but I still see this at the top of the Google result when I search for solution, so I decided to add this answer after I finally find the problem.

The current answer that marked as correct is only partially correct: it is related to image, but it is not limited to Favicon.

Somehow all major browser (at least for IE, Firefox and Chrome) decide that when there is an empty link provided to whatever place that is supposed to be an image, they will make it the current URL. Some example of places that may cause problem:

<img src="">
<div class="background-image:url()"></div>
<link rel="icon" type="image/x-icon" href="">

Provide a link or simply remove the line will solve the problem.


问:
Apache .htaccess, subfolder
I have website on Phalcon and everything works fine (I have SSL) but now I would like to have an access to the forum (https://www.example.com/forum/) but I have a problem with the .htaccess configuration.

Phalcon have the specific config:

```<code><IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteCond %{HTTP_HOST} !^www.example.com [NC]
    RewriteRule ^(.*)$ http://www.example.com%{REQUEST_URI} [R=301,L]
    RewriteCond %{HTTPS} !=on
    RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]
    RewriteRule  ^$ public/    [L]
    RewriteRule  (.*) public/$1 [L]
</IfModule>
</code>```

What is the correct configuration for home domain and /forum/ folder?

答:
Phalcon's root .htaccess file redirects all traffic to /public folder.
What you need to do is add one more condition to your final rewrite rule. Here is portion of my .htaccess file:

```<code><IfModule mod_rewrite.c>
    RewriteEngine On

    # Force www
    RewriteCond %{HTTP_HOST} !^$
    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteCond %{HTTPS}s ^on(s)|
    RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

    # Remove trailing slash
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [R=301,L]

    # Forward to public/
    RewriteRule ^(forum)($|/) - [L]
    RewriteRule ^(.*)$ public/$1 [L]
</IfModule>
</code>```

This RewriteRule ^(forum)($|/) - [L] is the important condition you need to add before RewriteRule ^.*$ public/$0 [L]

Also you can add as much as rules you want to allow multiple folders.

```<code>RewriteRule ^(forum)($|/) - [L]
RewriteRule ^(some-other-folder)($|/) - [L]
...
</code>```

Title: Apache .htaccess, subfolder

Body:
I have website on Phalcon and everything works fine (I have SSL) but now I would like to have an access to the forum (https://www.example.com/forum/) but I have a problem with the .htaccess configuration.

Phalcon have the specific config:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteCond %{HTTP_HOST} !^www.example.com [NC]
    RewriteRule ^(.*)$ http://www.example.com%{REQUEST_URI} [R=301,L]
    RewriteCond %{HTTPS} !=on
    RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]
    RewriteRule  ^$ public/    [L]
    RewriteRule  (.*) public/$1 [L]
</IfModule>

What is the correct configuration for home domain and /forum/ folder?

Body:
Phalcon's root .htaccess file redirects all traffic to /public folder.
What you need to do is add one more condition to your final rewrite rule. Here is portion of my .htaccess file:

<IfModule mod_rewrite.c>
    RewriteEngine On

    # Force www
    RewriteCond %{HTTP_HOST} !^$
    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteCond %{HTTPS}s ^on(s)|
    RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

    # Remove trailing slash
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [R=301,L]

    # Forward to public/
    RewriteRule ^(forum)($|/) - [L]
    RewriteRule ^(.*)$ public/$1 [L]
</IfModule>

This RewriteRule ^(forum)($|/) - [L] is the important condition you need to add before RewriteRule ^.*$ public/$0 [L]

Also you can add as much as rules you want to allow multiple folders.

RewriteRule ^(forum)($|/) - [L]
RewriteRule ^(some-other-folder)($|/) - [L]
...


问:
PHP & PDO: Can connect to DB; can't seem to query
It appears I can connect to my database using PDO, but can't execute any queries with it. Example:

```<code> private function connect() {
      try {
           $link = new PDO("mysql:host=$this->sHost;dbname=$this->sName", $this->sUser, $this->sPass);
      }
           catch (PDOException $e) {
           die ($e);
      }
      print_r($link);
      $result = $link->query("select * from mt3_users");
      var_dump($result);
      $row = $result->fetch($result);
      die("Your id is: ".$row["id"]);
      //$link = mysql_connect($this->sHost, $this->sUser, $this->sPass);
      if (!$link) {
          echo "Failed to connect to $this->sHost!";
          return false;
      }
      return $link;
 }
</code>```

This returns the following:

PDO Object ( ) bool(false)
  Fatal error: Call to a member function fetch() on a non-object in Database.php on line 32

So basically, $link is coming back as a PDO object (I changed my username and password to see if an exception was caught; it was) and PDOConnection::Query is returning null for some reason. This is my first time dealing with PDOs -- am I doing something funny?

答:
Most likely the query fails, are you sure of the name of the table mt3_users and that you have selected the right database? That error message shows that $result is not an object and that's due to an error in the query.

Also:

```<code>$row = $result->fetch($result);
</code>```

should be

```<code>$row = $result->fetch();
</code>```

unless you want to specify options to fetch(), but you don't pass the object as argument.

Body:
It appears I can connect to my database using PDO, but can't execute any queries with it. Example:

 private function connect() {
      try {
           $link = new PDO("mysql:host=$this->sHost;dbname=$this->sName", $this->sUser, $this->sPass);
      }
           catch (PDOException $e) {
           die ($e);
      }
      print_r($link);
      $result = $link->query("select * from mt3_users");
      var_dump($result);
      $row = $result->fetch($result);
      die("Your id is: ".$row["id"]);
      //$link = mysql_connect($this->sHost, $this->sUser, $this->sPass);
      if (!$link) {
          echo "Failed to connect to $this->sHost!";
          return false;
      }
      return $link;
 }

This returns the following:

PDO Object ( ) bool(false)
  Fatal error: Call to a member function fetch() on a non-object in Database.php on line 32

So basically, $link is coming back as a PDO object (I changed my username and password to see if an exception was caught; it was) and PDOConnection::Query is returning null for some reason. This is my first time dealing with PDOs -- am I doing something funny?

Body:
Most likely the query fails, are you sure of the name of the table mt3_users and that you have selected the right database? That error message shows that $result is not an object and that's due to an error in the query.

Also:

$row = $result->fetch($result);

should be

$row = $result->fetch();

unless you want to specify options to fetch(), but you don't pass the object as argument.


问:
Entity Framework 6 - Field conditional mapping
I am using Entity Framework for mapping our company software' and what i would like create a sort of conditional field mapping based on some field attributes i have created. Trying to better explain:
I have created the attribute ModelPersistentAttribute that I use in the following way:

```<code>    [ModelPersistent("WORKORDER", persistentSchema: "mySchema", fromVersion:       "0.0", toVersion: "2.0")]
    public class WorkOrderDTO : AMOSEntityDTO
    {
     public WorkOrderDTO()
     { }

     public WorkOrderDTO(decimal WORKORDERID, string WONO, DateTime    LASTUPDATED)
     {
       this.WORKORDERID = WORKORDERID;
       this.WONO = WONO;
       this.LASTUPDATED = LASTUPDATED;
     }

     [Key]
     public decimal WORKORDERID { get; set; }

     public string WONO { get; set; }

     [ModelPersistentAttribute(persistentName: "TITLE", fromVersion:"0.0")]
     public string myTITLE { get; set; }
   }
</code>```

Then I created a mapping class that has an automap method which is the following

```<code>    /// <summary>
    /// Automapping
    /// </summary>
    /// <param name="configurationOptions"></param>
    protected void AutoMap(EntityTypeMapCondigurationOptionsEFNet<TEntity> entityConfigurationOptions)
    {
        IEnumerable<ModelPersistentAttribute> persistentAttributes = typeof(TEntity).GetCustomAttributes<ModelPersistentAttribute>();
        if (persistentAttributes.Count() == 0 || persistentAttributes.Any(mpa => mpa.IsInRange(entityConfigurationOptions.Version, entityConfigurationOptions.DBMSType)))
        {
            if (persistentAttributes.Count() != 0) MapEntity(entityConfigurationOptions, persistentAttributes);
            foreach (var prop in typeof(TEntity).GetProperties())
            {
                NotMappedAttribute notMapped = prop.GetCustomAttribute<NotMappedAttribute>();
                if (notMapped == null)
                {
                    IEnumerable<ModelPersistentAttribute> modelAttributes = prop.GetCustomAttributes<ModelPersistentAttribute>();
                    if (modelAttributes.Count() == 0 || (modelAttributes.Any(ma => ma.IsInRange(entityConfigurationOptions.Version))))
                        MapProperty(prop, entityConfigurationOptions, modelAttributes);
                    else
                        IgnoreProperty(prop, entityConfigurationOptions);
                }
            }
        }
        else
            IgnoreEntity(entityConfigurationOptions);
    }
</code>```

Everything seems to work properly for mapping

```<code>    protected virtual void MapProperty(PropertyInfo propertyInfo, EntityTypeMapCondigurationOptionsEFNet<TEntity> entityConfigurationOptions, IEnumerable<ModelPersistentAttribute> modelAttributes)
    {
        ModelPersistentAttribute modelVersionAttribute = modelAttributes.FirstOrDefault<ModelPersistentAttribute>(mpa => mpa.IsInRange(entityConfigurationOptions.Version, entityConfigurationOptions.DBMSType));
        string persistentName = string.Empty;
        if (modelVersionAttribute != null)
            persistentName = modelVersionAttribute.PersistentName;
        else
            persistentName = propertyInfo.Name;
        entityConfigurationOptions.ModelBuilder.Properties().Where(p => p.Equals(propertyInfo)).Configure(c=> c.HasColumnName(persistentName));
    }
</code>```

but I am not able to run it when i want to ignore a property:

```<code>    /// <summary>
    /// Ignore property
    /// </summary>
    /// <param name="propertyInfo"></param>
    protected virtual void IgnoreProperty(PropertyInfo propertyInfo, EntityTypeMapCondigurationOptionsEFNet<TEntity> entityConfigurationOptions)
    {
        entityConfigurationOptions.ModelBuilder.Types<TEntity>().Configure(ctc => ctc.Ignore(p => propertyInfo));

 // The following as well doesn't work
 //entityConfigurationOptions.ModelBuilder.Types<TEntity>//().Configure(ctc =>    ctc.Ignore(p => propertyInfo.Name));

    }
</code>```

The meaning of the error I get is something that I understand but I don't know how to solve:

The expression 'p => value(DTO.Service.EFCore.EntityTypeVersionMap`1+<>c__DisplayClass4_0[TestDTO.Shared.WorkOrderDTO]).propertyInfo' is not a valid property expression. The expression should represent a property: C#: 't => t.MyProperty'  VB.Net: 'Function(t) t.MyProperty'.'

Any help on this will be VERY appreciated!
Thanks in advance
Luigi

答:
You can use the non generic Types method with Where, which Configure -> Ignore method has overloads for string propertyName and PropertyInfo propertyInfo (the one that you need):

```<code>entityConfigurationOptions.ModelBuilder
    .Types().Where(type => type == typeof(TEntity))
    .Configure(ctc => ctc.Ignore(propertyInfo));
</code>```

Body:
I am using Entity Framework for mapping our company software' and what i would like create a sort of conditional field mapping based on some field attributes i have created. Trying to better explain:
I have created the attribute ModelPersistentAttribute that I use in the following way:

    [ModelPersistent("WORKORDER", persistentSchema: "mySchema", fromVersion:       "0.0", toVersion: "2.0")]
    public class WorkOrderDTO : AMOSEntityDTO
    {
     public WorkOrderDTO()
     { }

     public WorkOrderDTO(decimal WORKORDERID, string WONO, DateTime    LASTUPDATED)
     {
       this.WORKORDERID = WORKORDERID;
       this.WONO = WONO;
       this.LASTUPDATED = LASTUPDATED;
     }

     [Key]
     public decimal WORKORDERID { get; set; }

     public string WONO { get; set; }

     [ModelPersistentAttribute(persistentName: "TITLE", fromVersion:"0.0")]
     public string myTITLE { get; set; }
   }

Then I created a mapping class that has an automap method which is the following

    ///
    /// Automapping
    ///
    /// <param name="configurationOptions"></param>
    protected void AutoMap(EntityTypeMapCondigurationOptionsEFNet<TEntity> entityConfigurationOptions)
    {
        IEnumerable<ModelPersistentAttribute> persistentAttributes = typeof(TEntity).GetCustomAttributes<ModelPersistentAttribute>();
        if (persistentAttributes.Count() == 0 || persistentAttributes.Any(mpa => mpa.IsInRange(entityConfigurationOptions.Version, entityConfigurationOptions.DBMSType)))
        {
            if (persistentAttributes.Count() != 0) MapEntity(entityConfigurationOptions, persistentAttributes);
            foreach (var prop in typeof(TEntity).GetProperties())
            {
                NotMappedAttribute notMapped = prop.GetCustomAttribute<NotMappedAttribute>();
                if (notMapped == null)
                {
                    IEnumerable<ModelPersistentAttribute> modelAttributes = prop.GetCustomAttributes<ModelPersistentAttribute>();
                    if (modelAttributes.Count() == 0 || (modelAttributes.Any(ma => ma.IsInRange(entityConfigurationOptions.Version))))
                        MapProperty(prop, entityConfigurationOptions, modelAttributes);
                    else
                        IgnoreProperty(prop, entityConfigurationOptions);
                }
            }
        }
        else
            IgnoreEntity(entityConfigurationOptions);
    }

Everything seems to work properly for mapping

    protected virtual void MapProperty(PropertyInfo propertyInfo, EntityTypeMapCondigurationOptionsEFNet<TEntity> entityConfigurationOptions, IEnumerable<ModelPersistentAttribute> modelAttributes)
    {
        ModelPersistentAttribute modelVersionAttribute = modelAttributes.FirstOrDefault<ModelPersistentAttribute>(mpa => mpa.IsInRange(entityConfigurationOptions.Version, entityConfigurationOptions.DBMSType));
        string persistentName = string.Empty;
        if (modelVersionAttribute != null)
            persistentName = modelVersionAttribute.PersistentName;
        else
            persistentName = propertyInfo.Name;
        entityConfigurationOptions.ModelBuilder.Properties().Where(p => p.Equals(propertyInfo)).Configure(c=> c.HasColumnName(persistentName));
    }

but I am not able to run it when i want to ignore a property:

    ///
    /// Ignore property
    ///
    /// <param name="propertyInfo"></param>
    protected virtual void IgnoreProperty(PropertyInfo propertyInfo, EntityTypeMapCondigurationOptionsEFNet<TEntity> entityConfigurationOptions)
    {
        entityConfigurationOptions.ModelBuilder.Types<TEntity>().Configure(ctc => ctc.Ignore(p => propertyInfo));

 // The following as well doesn't work
 //entityConfigurationOptions.ModelBuilder.Types<TEntity>//().Configure(ctc =>    ctc.Ignore(p => propertyInfo.Name));

    }

The meaning of the error I get is something that I understand but I don't know how to solve:

The expression 'p => value(DTO.Service.EFCore.EntityTypeVersionMap`1+<>c__DisplayClass4_0[TestDTO.Shared.WorkOrderDTO]).propertyInfo' is not a valid property expression. The expression should represent a property: C#: 't => t.MyProperty'  VB.Net: 'Function(t) t.MyProperty'.'

Any help on this will be VERY appreciated!
Thanks in advance
Luigi

Body:
You can use the non generic Types method with Where, which Configure -> Ignore method has overloads for string propertyName and PropertyInfo propertyInfo (the one that you need):

entityConfigurationOptions.ModelBuilder
    .Types().Where(type => type == typeof(TEntity))
    .Configure(ctc => ctc.Ignore(propertyInfo));


问:
KnockoutJS, Binding View
I'm struggling with issues from KnockoutJS, I have block code below

```<code>var viewModel = function (value){
    this.name = ko.observable(value);
}
var model = {}; model.firstName = "ABC";
var AppViewModel = new viewModel(model.firstName);
ko.applyBindings(AppViewModel);
</code>```

And in HTML i have a view with binding

```<code>data-bind="textInput: name".
</code>```

It's good work. TextView display with text: "ABC".
I have a question. when I change value in TextView. Whether if that model (special firstName) update new value from textView ?

答:
The problem is that model.firstName is an object property but it isn't an observable, instead you're using that object property to set the observable, the observable is the two way binding, if you want firstName to be an observable/two way binding you can do it like so:

```<code>var viewModel = function (){
    VM = this;
    VM.firstName = ko.observable("ABC");
    return VM;
}

var AppViewModel = new viewModel();
ko.applyBindings(AppViewModel);
</code>```

Here we're creating a function viewModel() that returns an object with the property firstName which is a knockout observable containing "ABC". Then we're creating an instance of that view model and applying it to the page. Now if you make any changes in the input it should update the value of AppViewModel.firstName.

Or to keep it more similar to your code you can do it like this:

```<code>var viewModel = function (){
    this.firstName = ko.observable("ABC");
}

var AppViewModel = new viewModel();
ko.applyBindings(AppViewModel);
</code>```

Note that there is no need to create the model object with the property firstName, you can just initialise the observable with a string and it will pick up any changes made in the textInput binding.

Title: KnockoutJS, Binding View

Body:
I'm struggling with issues from KnockoutJS, I have block code below

var viewModel = function (value){
    this.name = ko.observable(value);
}
var model = {}; model.firstName = "ABC";
var AppViewModel = new viewModel(model.firstName);
ko.applyBindings(AppViewModel);

And in HTML i have a view with binding

data-bind="textInput: name".

It's good work. TextView display with text: "ABC".
I have a question. when I change value in TextView. Whether if that model (special firstName) update new value from textView ?

Body:
The problem is that model.firstName is an object property but it isn't an observable, instead you're using that object property to set the observable, the observable is the two way binding, if you want firstName to be an observable/two way binding you can do it like so:

var viewModel = function (){
    VM = this;
    VM.firstName = ko.observable("ABC");
    return VM;
}

var AppViewModel = new viewModel();
ko.applyBindings(AppViewModel);

Here we're creating a function viewModel() that returns an object with the property firstName which is a knockout observable containing "ABC". Then we're creating an instance of that view model and applying it to the page. Now if you make any changes in the input it should update the value of AppViewModel.firstName.

Or to keep it more similar to your code you can do it like this:

var viewModel = function (){
    this.firstName = ko.observable("ABC");
}

var AppViewModel = new viewModel();
ko.applyBindings(AppViewModel);

Note that there is no need to create the model object with the property firstName, you can just initialise the observable with a string and it will pick up any changes made in the textInput binding.


问:
When does a C# Task actually start?
When does a Task actually start?

```<code>public void DoSomething() {
    Task myTask = DoSomethingAsync();

    Task.WaitAll(new[] { myTask }, 2000);
}

public async Task DoSomethingAsync() {
    await SomethingElse();
}
</code>```

Does it start immediately when initializing it in Task myTask = DoSomethingAsync(); or does it start when you say to wait for it in Task.WaitAll(new[] { myTask }, 2000); ?

答:
Calling an async method returns a hot task, a task that has already been started. So there is no actual code necessary to force it to run.

According MSDN (thanks to Stephen Cleary) the Task-based Asynchronous Pattern (TAP) pattern requires returned tasks to be hot. That means that all tasks, except those created with new Task will be hot.

From the referenced article:

Tasks that are created by the public Task constructors are referred to as cold tasks... All other tasks begin their life cycle in a hot state.

Title: When does a C# Task actually start?

Body:
When does a Task actually start?

public void DoSomething() {
    Task myTask = DoSomethingAsync();

    Task.WaitAll(new[] { myTask }, 2000);
}

public async Task DoSomethingAsync() {
    await SomethingElse();
}

Does it start immediately when initializing it in Task myTask = DoSomethingAsync(); or does it start when you say to wait for it in Task.WaitAll(new[] { myTask }, 2000); ?


问:
Inserting data via C# is inaccessible when queried
I am having a very annoying issue with a program I am currently making. In the program a teacher with admin status can add a user to a students_tbl Table in an SQL database by adding in relevant information. The following code adds a Student to the student_tbl in C#.

```<code>string studentAdd = "Insert Into student_tbl(Forename, Surname, SchlYear, InOrOut, Block1, Block2, Block3, Block4, Pword) Values (@forename, @surname, '" + SchlYear + "', '" + inOrOut + "' , '" + Blocks[0] + "', '" + Blocks[1] + "', '" + Blocks[2] + "', '" + Blocks[3] + "', @password)";
SqlCommand studentAddCommand = new SqlCommand(studentAdd, con);
studentAddCommand.Parameters.Add(new SqlParameter("@forename", Forename));
studentAddCommand.Parameters.Add(new SqlParameter("@surname", Surname));
studentAddCommand.Parameters.Add(new SqlParameter("@password", hashedPassword));
studentAddCommand.ExecuteNonQuery();
MessageBox.Show("Student Added Successfully");
con.Close();
</code>```

The variables added in to the table come from results and are simply just names, integers and bools, nothing complex.

The issue I am having is that this data is inaccessible when trying to log in as a student added via this system. If a user is added manually through SSMS then it works fine. Is this something ridiculously basic I am missing, as if I was to add a user ie. 'Joe Bloggs', and search

```<code>Select UserID from student_tbl Where Forename = 'Joe'
</code>```

It simply finds nothing.
Does anybody have any glaring issues I am missing, or not declaring etc? I am able to provide any more information if it could lead to a solution. Thanks.

答:
According to @Jeroen van Langen  comment, try to trim values:</p>

```<code>studentAddCommand.Parameters.Add(new SqlParameter("@forename", Forename.Trim()));
studentAddCommand.Parameters.Add(new SqlParameter("@surname", Surname.Trim()));
</code>```

Body:
I am having a very annoying issue with a program I am currently making. In the program a teacher with admin status can add a user to a students_tbl Table in an SQL database by adding in relevant information. The following code adds a Student to the student_tbl in C#.

string studentAdd = "Insert Into student_tbl(Forename, Surname, SchlYear, InOrOut, Block1, Block2, Block3, Block4, Pword) Values (@forename, @surname, '" + SchlYear + "', '" + inOrOut + "' , '" + Blocks[0] + "', '" + Blocks[1] + "', '" + Blocks[2] + "', '" + Blocks[3] + "', @password)";
SqlCommand studentAddCommand = new SqlCommand(studentAdd, con);
studentAddCommand.Parameters.Add(new SqlParameter("@forename", Forename));
studentAddCommand.Parameters.Add(new SqlParameter("@surname", Surname));
studentAddCommand.Parameters.Add(new SqlParameter("@password", hashedPassword));
studentAddCommand.ExecuteNonQuery();
MessageBox.Show("Student Added Successfully");
con.Close();

The variables added in to the table come from results and are simply just names, integers and bools, nothing complex.

The issue I am having is that this data is inaccessible when trying to log in as a student added via this system. If a user is added manually through SSMS then it works fine. Is this something ridiculously basic I am missing, as if I was to add a user ie. 'Joe Bloggs', and search

Select UserID from student_tbl Where Forename = 'Joe'

It simply finds nothing.
Does anybody have any glaring issues I am missing, or not declaring etc? I am able to provide any more information if it could lead to a solution. Thanks.

Body:
According to @Jeroen van Langen  comment, try to trim values:

studentAddCommand.Parameters.Add(new SqlParameter("@forename", Forename.Trim()));
studentAddCommand.Parameters.Add(new SqlParameter("@surname", Surname.Trim()));


问:
Gerrit will not push. Error: No common ancestry
Trying to push to gerrit. Brings up no common ancestry. </p>

```<code>nolan@nolan-pc:~/pac-man$ git push ssh://1KX2@review.pac-rom.com:29418/android_vendor_pac HEAD:refs/for/pac-6.0
Counting objects: 8, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (8/8), done.
Writing objects: 100% (8/8), 6.63 KiB | 0 bytes/s, done.
Total 8 (delta 0), reused 0 (delta 0)
remote: Processing changes: refs: 1, done
To ssh://1KX2@review.pac-rom.com:29418/android_vendor_pac
 ! [remote rejected] HEAD -> refs/for/pac-6.0 (no common ancestry)
error: failed to push some refs to 'ssh://1KX2@review.pac-rom.com:29418/android_vendor_pac'
</code>```

答:
One case where this is solved "easily" is if you pushed to an entirely new repo and have no interest in any possibly old git history that brought your project code to the state it has now.

Then a solution is to start in a new folder, then clone the (empty) project from gerrit. This folder then have a common ancestry with this gerrit project. Then you could work to add your source files into this new folder using git add until satisfied,(that mundane work is the non-easy part) leaving out any old .git folder and finally try a push. This pushes your project onto gerrit with git history beginning from this point on.

Body:
Trying to push to gerrit. Brings up no common ancestry.

nolan@nolan-pc:~/pac-man$ git push ssh://1KX2@review.pac-rom.com:29418/android_vendor_pac HEAD:refs/for/pac-6.0
Counting objects: 8, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (8/8), done.
Writing objects: 100% (8/8), 6.63 KiB | 0 bytes/s, done.
Total 8 (delta 0), reused 0 (delta 0)
remote: Processing changes: refs: 1, done
To ssh://1KX2@review.pac-rom.com:29418/android_vendor_pac
 ! [remote rejected] HEAD -> refs/for/pac-6.0 (no common ancestry)
error: failed to push some refs to 'ssh://1KX2@review.pac-rom.com:29418/android_vendor_pac'


问:
check how many arrays have length greater than 0 in javascript and angularjs
I am trying to create a validation in my app.

What I have, is multiple lists with a toggle (true/false).

If the item is selected, it populates an array.

And I have a different array for each group.

Pretty much something like this:

```<code>$scope.selected = {
  group1: {
    values: []
  },
  group2: {
    values: []
  },
  group3: {
    values: []
  }
}
</code>```

When I select something, let's say, from the list in group 1, $scope.selected changes to this:

```<code>$scope.selected = {
   group1: {
     values: [{cat: 1, id: 1},{cat:1, id:3}]
   }
}
</code>```

The problem I've got is that I am trying to validate this.

What I need is to be able to display a message if multiple values arrays are greater than 0.

For instance if:

```<code>$scope.selected = {
   group1: {
     values: [{cat: 1, id: 1},{cat:1, id:3}]
   },
   group2: {
     values: [{cat: 2, id: 5},{cat:2, id:2}]
   }
}
</code>```

a message should appear as I can't allow to submit multiple groups at once.

I know that I can have some sort of function that checks on the specific name for the groups, but I need something a bit more dynamic, as groups may (and will) increase at some point (ie. I will have more groups that the ones I have now).

Is there any way I can check that only one out of all my group arrays is not empty, and if multiple are not empty, I show something?

thanks and I hope it's clear enough

答:
You can use Array#filter and Object.keys(o)

const selected = {
   group1: {
     values: [{cat: 1, id: 1},{cat:1, id:3}]
   },
   group2: {
     values: [{cat: 2, id: 5},{cat:2, id:2}]
   }
};
const validSelected = {
   group1: {
     values: [{cat: 1, id: 1},{cat:1, id:3}]
   },
   group2: {
     values: []
   }
};

function validate(obj){
  return Object.keys(obj).filter(k=>obj[k].values.length>0).length === 1;
}

console.log(validate(selected)); //false
console.log(validate(validSelected)); //true```
</div>
</div>
</p>

<p>Without <strong>ES6</strong> arrow :</p>

```Object.keys(obj).filter(function(k){return obj[k].values.length>0).length === 1});
```

Body:
I am trying to create a validation in my app.

What I have, is multiple lists with a toggle (true/false).

If the item is selected, it populates an array.

And I have a different array for each group.

Pretty much something like this:

$scope.selected = {
  group1: {
    values: []
  },
  group2: {
    values: []
  },
  group3: {
    values: []
  }
}

When I select something, let's say, from the list in group 1, $scope.selected changes to this:

$scope.selected = {
   group1: {
     values: [{cat: 1, id: 1},{cat:1, id:3}]
   }
}

The problem I've got is that I am trying to validate this.

What I need is to be able to display a message if multiple values arrays are greater than 0.

For instance if:

$scope.selected = {
   group1: {
     values: [{cat: 1, id: 1},{cat:1, id:3}]
   },
   group2: {
     values: [{cat: 2, id: 5},{cat:2, id:2}]
   }
}

a message should appear as I can't allow to submit multiple groups at once.

I know that I can have some sort of function that checks on the specific name for the groups, but I need something a bit more dynamic, as groups may (and will) increase at some point (ie. I will have more groups that the ones I have now).

Is there any way I can check that only one out of all my group arrays is not empty, and if multiple are not empty, I show something?

thanks and I hope it's clear enough

Body:
You can use Array#filter and Object.keys(o)

const selected = {
   group1: {
     values: [{cat: 1, id: 1},{cat:1, id:3}]
   },
   group2: {
     values: [{cat: 2, id: 5},{cat:2, id:2}]
   }
};
const validSelected = {
   group1: {
     values: [{cat: 1, id: 1},{cat:1, id:3}]
   },
   group2: {
     values: []
   }
};

function validate(obj){
  return Object.keys(obj).filter(k=>obj[k].values.length>0).length === 1;
}

console.log(validate(selected)); //false
console.log(validate(validSelected)); //true

Without ES6 arrow :

Object.keys(obj).filter(function(k){return obj[k].values.length>0).length === 1});


问:
How to get Chirpy working with JS and mash.config
I just downloaded and installed the most recent version of Chirpy [Nude Chirpy v1.0.0.5.3]
I created a "mash.less.chirp.config" file in my CSS directory, and it's compressing/minifying very spectacularly!!!

```<code><root>
    <FileGroup Name="site.css">
        <File Path="elements.css" />
        <File Path="jquery-ui-1.8.4.custom.css" />
        <File Path="site.less" />
        <File Path="wmd.css" />
    </FileGroup>
</root>
</code>```

I also created a "mash.chirp.config" file in my Script directory, unfortunately it's not doing anything at all.

```<code><root>
    <FileGroup Name="site.js">
        <File path="jquery-ui-1.8.4.custom.min.js" Minify="false" />
        <File path="un-master.js" />
        <File path="jquery-ui-timepicker-addon.min.js" Minify="false" />
        <File path="jquery-nmcFormHelper.js" />
        <File path="jquery.textarearesizer.min.js" Minify="false" />
        <File path="jquery-openid.js" />
        <File path="jquery.timeago.js" />
    </FileGroup>
</root>
</code>```

any help/direction on this will be greatly appreciated.

[ADDED INFO]

I'm using Visual Studio 2010 Professional

I've got an ASP.NET MVC3 Project

Folder Structure...

ROOT/Assets/Scripts/mash.chirp.config

     ROOT/Assets/Scripts/[all_my_js_files].js

答:
I changed my config to the following, and it seems to be working

```<code><?xml version="1.0" encoding="utf-8" ?>
<root xmlns="urn:ChirpyConfig"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="urn:ChirpyConfig http://www.weirdlover.com/chirpy/chirp.xsd">
    <FileGroup Name="site.js">
        <File Path="jquery-ui-1.8.4.custom.min.js" Minify="false" />
        <File Path="un-master.js" />
        <File Path="jquery-ui-timepicker-addon.min.js" Minify="false" />
        <File Path="jquery-nmcFormHelper.js" />
        <File Path="jquery.textarearesizer.min.js" Minify="false" />
        <File Path="jquery-openid.js" />
        <File Path="jquery.timeago.js" />
    </FileGroup>
</root>
</code>```

Evidently it's case sensitive Path instead of path.

Body:
I just downloaded and installed the most recent version of Chirpy [Nude Chirpy v1.0.0.5.3]
I created a "mash.less.chirp.config" file in my CSS directory, and it's compressing/minifying very spectacularly!!!

<root>
    <FileGroup Name="site.css">
        <File Path="elements.css" />
        <File Path="jquery-ui-1.8.4.custom.css" />
        <File Path="site.less" />
        <File Path="wmd.css" />
    </FileGroup>
</root>

I also created a "mash.chirp.config" file in my Script directory, unfortunately it's not doing anything at all.

<root>
    <FileGroup Name="site.js">
        <File path="jquery-ui-1.8.4.custom.min.js" Minify="false" />
        <File path="un-master.js" />
        <File path="jquery-ui-timepicker-addon.min.js" Minify="false" />
        <File path="jquery-nmcFormHelper.js" />
        <File path="jquery.textarearesizer.min.js" Minify="false" />
        <File path="jquery-openid.js" />
        <File path="jquery.timeago.js" />
    </FileGroup>
</root>

any help/direction on this will be greatly appreciated.

[ADDED INFO]

I'm using Visual Studio 2010 Professional

I've got an ASP.NET MVC3 Project

Folder Structure...

ROOT/Assets/Scripts/mash.chirp.config

     ROOT/Assets/Scripts/[all_my_js_files].js

Body:
I changed my config to the following, and it seems to be working

<?xml version="1.0" encoding="utf-8" ?>
<root xmlns="urn:ChirpyConfig"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="urn:ChirpyConfig http://www.weirdlover.com/chirpy/chirp.xsd">
    <FileGroup Name="site.js">
        <File Path="jquery-ui-1.8.4.custom.min.js" Minify="false" />
        <File Path="un-master.js" />
        <File Path="jquery-ui-timepicker-addon.min.js" Minify="false" />
        <File Path="jquery-nmcFormHelper.js" />
        <File Path="jquery.textarearesizer.min.js" Minify="false" />
        <File Path="jquery-openid.js" />
        <File Path="jquery.timeago.js" />
    </FileGroup>
</root>

Evidently it's case sensitive Path instead of path.


问:
Disable button until checkbox ticked
Apologies if this has already been asked, i have found it difficult to use the answers I have found to use in my code.

Basically, I have a "receive" button, that when the user clicks, will receive an email. But, I want a tick box checked in order for the button to become clickable. I have a code that kind of works, but when the page first loads, the "Receive" button is already clickable. However, when I click the tick box then unclick it, it disables the button.

```<code><td>
    <input type="checkbox"  id="tick" onchange="document.getElementById('terms').disabled = !this.checked;" />
    <td>
    <p> I agree to the <a href="terms.html" target="_blank">Terms & Conditions</a></p>
    </td>
</td>
</tr>
<td class="label1"></td>
<td align="right">
    <button type="submit" class="btn btn1" name="terms" id="terms">Receive</i></button>
</td>
</code>```

答:
please add attrbute disabled to the button

 I agree to the Terms & Conditions

                                Receive

Title: Disable button until checkbox ticked

Body:
Apologies if this has already been asked, i have found it difficult to use the answers I have found to use in my code.

Basically, I have a "receive" button, that when the user clicks, will receive an email. But, I want a tick box checked in order for the button to become clickable. I have a code that kind of works, but when the page first loads, the "Receive" button is already clickable. However, when I click the tick box then unclick it, it disables the button.

    <input type="checkbox"  id="tick" onchange="document.getElementById('terms').disabled = !this.checked;" />

 I agree to the Terms & Conditions

    <button type="submit" class="btn btn1" name="terms" id="terms">Receive</button>


问:
Admin-LTE theme integration in yii2 & changing its default theme
I have integrated the AdminLTE theme in my web app now I want to change the theme of the AdminLTE from its default blue black to red color, How can I do this? In which files I need to make the required changes..?</p>

答:
In My case I just change body class to

in layouts/main.php

Body:
In My case I just change body class to

    <body class="skin-red">

in layouts/main.php


问:
Fahrenheit to Celsius table C
I am working on a code that displays a conversion table from Fahrenheit to Celsius.How can I change it so that it will start from negative value and go towards positive something like this

```<code>Fahrenhite  Celcius
-10   -23.3333
-20   -28.8889
 ..
 ..
 ..
 ..
 100   37.7778
</code>```

my code:

```<code>#include <stdio.h>
int main()
{
      float fahrenheit, celsius;
      int lower, upper, step;

      lower = 10;
      upper = 100;
      step = 10;
      printf("F       C\n\n");
      fahrenheit = lower;
      while(fahrenheit <= upper)
             {
            celsius = (5.0 / 9.0) * (fahrenheit - 32.0);
            printf("%3.0f %6.1f\n", fahrenheit, celsius);
            fahrenheit = fahrenheit + step;
             }

                  return 0;
}
</code>```

答:
Firstly you must learn how to work this code it is so simply an clear.
Your code works for lower=10 and upper=100 you can change these values what are you want you can reach table. If you want 4 digits after the conviction

```<code> printf("%3.0f %6.4f\n", fahrenheit, celsius);
</code>```

you must chage %6.1f like above

Title: Fahrenheit to Celsius table C

Body:
I am working on a code that displays a conversion table from Fahrenheit to Celsius.How can I change it so that it will start from negative value and go towards positive something like this

Fahrenhite  Celcius
-10   -23.3333
-20   -28.8889
 ..
 ..
 ..
 ..
 100   37.7778

my code:

#include <stdio.h>
int main()
{
      float fahrenheit, celsius;
      int lower, upper, step;

      lower = 10;
      upper = 100;
      step = 10;
      printf("F       C\n\n");
      fahrenheit = lower;
      while(fahrenheit <= upper)
             {
            celsius = (5.0 / 9.0) * (fahrenheit - 32.0);
            printf("%3.0f %6.1f\n", fahrenheit, celsius);
            fahrenheit = fahrenheit + step;
             }

                  return 0;
}

Body:
Firstly you must learn how to work this code it is so simply an clear.
Your code works for lower=10 and upper=100 you can change these values what are you want you can reach table. If you want 4 digits after the conviction

 printf("%3.0f %6.4f\n", fahrenheit, celsius);

you must chage %6.1f like above


问:
How to send multiple paramters in perform selector in swift3?
I have to implement perform selector with multiple parameters (two strings parameters). I have created a function.
How to implement this function with perform selector after delay method.

```<code>func addBorderLayer(textField: UITextField , placeHolder: String) {
    textField.layer.borderColor =  UIColor.init(colorLiteralRed: 254/255, green: 93/255, blue: 49/255, alpha: 1.0).cgColor
    textField.layer.borderWidth = 1.0
    textField.placeholder = placeHolder
}`
</code>```

I have call this method like this

```<code> self.perform(#selector(SecurityQuestionViewController.clearBorderLayer(textField:placeHolder:)), with:(textField,"Test") , afterDelay: 0.5)
</code>```

When I pass parameter like this show me segmentation error in xcode,but my problem is how to pass parameters in it.What is correct way to pass parameters?

答:
Use (G)rand (C)entral (D)ispatch, it's block based and easier to use than performSelector, you don't need to call an extra method, change the text field properties directly for example:

```<code>func addBorderLayer(textField: UITextField , placeHolder: String) {
    textField.layer.borderColor =  UIColor.init(colorLiteralRed: 254/255, green: 93/255, blue: 49/255, alpha: 1.0).cgColor
    textField.layer.borderWidth = 1.0
    textField.placeholder = placeHolder
    DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(500)) {
        textField.placeholder = "Test"
    }
}
</code>```

Body:
I have to implement perform selector with multiple parameters (two strings parameters). I have created a function.
How to implement this function with perform selector after delay method.

func addBorderLayer(textField: UITextField , placeHolder: String) {
    textField.layer.borderColor =  UIColor.init(colorLiteralRed: 254/255, green: 93/255, blue: 49/255, alpha: 1.0).cgColor
    textField.layer.borderWidth = 1.0
    textField.placeholder = placeHolder
}`

I have call this method like this

 self.perform(#selector(SecurityQuestionViewController.clearBorderLayer(textField:placeHolder:)), with:(textField,"Test") , afterDelay: 0.5)

When I pass parameter like this show me segmentation error in xcode,but my problem is how to pass parameters in it.What is correct way to pass parameters?

Body:
Use (G)rand (C)entral (D)ispatch, it's block based and easier to use than performSelector, you don't need to call an extra method, change the text field properties directly for example:

func addBorderLayer(textField: UITextField , placeHolder: String) {
    textField.layer.borderColor =  UIColor.init(colorLiteralRed: 254/255, green: 93/255, blue: 49/255, alpha: 1.0).cgColor
    textField.layer.borderWidth = 1.0
    textField.placeholder = placeHolder
    DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(500)) {
        textField.placeholder = "Test"
    }
}


问:
C++ array pointer
I came across a C++ program like this

```<code>#include<iostream>
using namespace std;

int main() {
    int N = 10;
    int M = 2;
    int a[] = { 2,1,4,3,6,5,8,7,10,9 };
    int(*b)[5] = (int(*)[5]) a;
    for (int i = 0; i<M; i++) {
        for (int j = 0; j<N / M; j++) {
            cout << b[i][j] << endl;
        }
    }

    system("pause");
    return 0;
}
</code>```

The above program's output is 2,1,4,3,6,5,8,7,10,9. It looks like b is an array point. So what does (int(*)[5]) a mean? Can someone help me to explain it?

答:
The statement

```<code>int a[] = { 2,1,4,3,6,5,8,7,10,9 };
</code>```

Looks like this in memory

```<code>     +---+---+---+---+---+---+---+---+---+---+
a -> | 2 | 1 | 4 | 3 | 6 | 5 | 8 | 7 | 10| 9 |;
     +---+---+---+---+---+---+---+---+---+---+
      +0  +1 ...
</code>```

When you access elements in the array you typically use [] but since a is an address. you can access
elements also using a pointer style offset

```<code>a + 2   // address to third int, *(a+2) the actual value `3`
</code>```

Now by declaring another way to access the 10 integers you can access the memory of a in a different way, the type determines the way you access the memory

```<code>int(*b)[5] = (int(*)[5]) a; // compiler, pretend a is of same type
</code>```

In the above statement b and a refer to the same memory but b is of type pointer to int array of five.

since b is a pointer:

b points to where a starts. doing b++, b now points to middle of a array since declaration of b says it holds only five integers

so

```<code>b[0] points to address a + 0
b[0][0] is the value of a + 0 or a[0] alt. *(a + 0)

b[1] points to address a + 5
b[1][0] is the value of a + 5 or a[5] alt. *(a + 5)
</code>```

Since C normally has no check whether you are going out of bounds the above works.

Title: C++ array pointer

Body:
I came across a C++ program like this

#include<iostream>
using namespace std;

int main() {
    int N = 10;
    int M = 2;
    int a[] = { 2,1,4,3,6,5,8,7,10,9 };
    int(*b)[5] = (int(*)[5]) a;
    for (int i = 0; i<M; i++) {
        for (int j = 0; j<N / M; j++) {
            cout << b[i][j] << endl;
        }
    }

    system("pause");
    return 0;
}

The above program's output is 2,1,4,3,6,5,8,7,10,9. It looks like b is an array point. So what does (int(*)[5]) a mean? Can someone help me to explain it?

Body:
The statement

int a[] = { 2,1,4,3,6,5,8,7,10,9 };

Looks like this in memory

     +---+---+---+---+---+---+---+---+---+---+
a -> | 2 | 1 | 4 | 3 | 6 | 5 | 8 | 7 | 10| 9 |;
     +---+---+---+---+---+---+---+---+---+---+
      +0  +1 ...

When you access elements in the array you typically use [] but since a is an address. you can access
elements also using a pointer style offset

a + 2   // address to third int, *(a+2) the actual value `3`

Now by declaring another way to access the 10 integers you can access the memory of a in a different way, the type determines the way you access the memory

int(*b)[5] = (int(*)[5]) a; // compiler, pretend a is of same type

In the above statement b and a refer to the same memory but b is of type pointer to int array of five.

since b is a pointer:

b points to where a starts. doing b++, b now points to middle of a array since declaration of b says it holds only five integers

so

b[0] points to address a + 0
b[0][0] is the value of a + 0 or a[0] alt. *(a + 0)

b[1] points to address a + 5
b[1][0] is the value of a + 5 or a[5] alt. *(a + 5)

Since C normally has no check whether you are going out of bounds the above works.


问:
Dependecy injection for HttpConfiguration in Simple Injector
I am getting an error in my HelpController:

The constructor of type HelpController contains the parameter with
  name 'config' and type HttpConfiguration that is not registered.
  Please ensure HttpConfiguration is registered, or change the
  constructor of HelpController.

Is there any alternative to resolve this issue because I use Configuration to get Configuration.GetModelDescriptionGenerator();

public class HelpController : Controller
{
    private const string ErrorViewName = "Error";

    public HelpController(HttpConfiguration config)
    {
        Configuration = config;
    }

    public HttpConfiguration Configuration { get; private set; }

    ...

    public ActionResult ResourceModel(string modelName)
    {
        if (!String.IsNullOrEmpty(modelName))
        {
            ModelDescriptionGenerator modelDescriptionGenerator = Configuration.GetModelDescriptionGenerator();
            ModelDescription modelDescription;
            if (modelDescriptionGenerator.GeneratedModels.TryGetValue(modelName, out modelDescription))
            {
                return View(modelDescription);
            }
        }

        return View(ErrorViewName);
    }
}
```

答:
Change your constructor to private and put back in the parameterless constructor as generated by VS. Your HelpController should look like this.

```<code>public class HelpController : Controller
{
    private const string ErrorViewName = "Error";

    public HelpController()
        : this(GlobalConfiguration.Configuration)
    {
    }

    private HelpController(HttpConfiguration config)
    {
        Configuration = config;
    }

    public HttpConfiguration Configuration { get; private set; }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Change your constructor to private and put back in the parameterless constructor as generated by VS. Your HelpController should look like this.

public class HelpController : Controller
{
    private const string ErrorViewName = "Error";

    public HelpController()
        : this(GlobalConfiguration.Configuration)
    {
    }

    private HelpController(HttpConfiguration config)
    {
        Configuration = config;
    }

    public HttpConfiguration Configuration { get; private set; }
}


问:
Custom Exception in scala
how can i create custom exceptions in Scala extending Exception class and throw them when exception occurs as well as catch them.

example in java :

```<code>class CustomException extends Exception {

  public final static String _FAIL_TO_INSERT = "FAIL_TO_INSERT";

}
</code>```

答:
In order to reflect all the original constructors from Exception I'd implement a custom exception with the following pattern:

```<code>class CustomException(msg: String) extends Exception(msg) {
  def this(msg: String, cause: Throwable) = {
    this(msg)
    initCause(cause)
  }

  def this(cause: Throwable) = {
    this(Option(cause).map(_.toString).orNull)
    initCause(cause)
  }

  def this() = {
    this(null: String)
  }
}
</code>```

This can be also achieved with a trait as mentioned in previous answer. I'd just not create individual classes in this case:

```<code>trait SomeException { self: Throwable =>
  def someDetail: SomeDetail
}
</code>```

then, when throwing:

```<code>throw new Exception(...) with SomeException {
  override val someDetail = ...
}
</code>```

and when matching:

```<code>try {
  ...
} catch {
  case ex: Throwable with SomeException =>
    ex.getCause
    ex.getMessage
    ex.someDetail
}
</code>```

The advantage here is that you are not sticking to any particular constructor of the parent exception.

something more or less like that.

Title: Custom Exception in scala

Body:
how can i create custom exceptions in Scala extending Exception class and throw them when exception occurs as well as catch them.

example in java :

class CustomException extends Exception {

  public final static String _FAIL_TO_INSERT = "FAIL_TO_INSERT";

}

Body:
In order to reflect all the original constructors from Exception I'd implement a custom exception with the following pattern:

class CustomException(msg: String) extends Exception(msg) {
  def this(msg: String, cause: Throwable) = {
    this(msg)
    initCause(cause)
  }

  def this(cause: Throwable) = {
    this(Option(cause).map(_.toString).orNull)
    initCause(cause)
  }

  def this() = {
    this(null: String)
  }
}

This can be also achieved with a trait as mentioned in previous answer. I'd just not create individual classes in this case:

trait SomeException { self: Throwable =>
  def someDetail: SomeDetail
}

then, when throwing:

throw new Exception(...) with SomeException {
  override val someDetail = ...
}

and when matching:

try {
  ...
} catch {
  case ex: Throwable with SomeException =>
    ex.getCause
    ex.getMessage
    ex.someDetail
}

The advantage here is that you are not sticking to any particular constructor of the parent exception.

something more or less like that.


答:
Since b  is a pointer to array of 5 integers so :

b[0] will point to an array of 5 integers stored from location pointed to by b.

b[1] will point to an array of 5 integers stored from location pointed to by b + (5*sizeof(int)).

Since b has been assigned address of a via typecasting int(*b)[5] = (int(*)[5]) a;, therefore:

b[0] will point to first 5 integers of array a i.e, a[0..4]

b[1] will point to next 5 integers of array a i.e, a[5..9]

Now,

b[0][0] will give value of 1st element indexed at 0 of array pointed to by b[0] i.e, a[0]

b[0][1] will give value of 2nd element indexed at 1 of array pointed to by b[0] i.e, a[1]

..

..

b[1][0] will give value of 1st element indexed at 0 of array pointed to by b[1] i.e, a[5]

b[1][1] will give value of 2nd element indexed at 1 of array pointed to by b[1] i.e, a[6]

Title: C++ array pointer


问:
App fails to compile and run in Android Studio
I have made a basic application with one Splash Screen Activity and one Main Screen Activity(with Navigation Drawer). When I click "Run" Button, one error is shown in the Messages Box.

Android Studio Version: 2.2.3.

The code in build.gradle:

```<code>    buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.3'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

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

The error goes as this:

Error:Execution failed for task ':app:compileDebugJavaWithJavac'.

Could not expand ZIP 'C:\Users\vijtech\AndroidStudioProjects\Deadline\app\build\intermediates\exploded-aar\com.android.support\design\25.3.1\jars\classes.jar'.

Please help. Thanks in advance.

答:
Try to update your dependencies in your build.gradle (app).

Go to File -> Project Structure -> Messages -> Check for Updates

Then it will show you, and you just need to upgrade it in your file.

Body:
I have made a basic application with one Splash Screen Activity and one Main Screen Activity(with Navigation Drawer). When I click "Run" Button, one error is shown in the Messages Box.

Android Studio Version: 2.2.3.

The code in build.gradle:

    buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.3'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

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

The error goes as this:

Error:Execution failed for task ':app:compileDebugJavaWithJavac'.

Could not expand ZIP 'C:\Users\vijtech\AndroidStudioProjects\Deadline\app\build\intermediates\exploded-aar\com.android.support\design\25.3.1\jars\classes.jar'.

Please help. Thanks in advance.


问:
Best cheap GUI for converting to f4v
I need to give one client the ability to convert some videos to f4v h264 before loading it up to an AIR app.

I normally doing with the Adobe Media Encoder CS4 but that only ships with adobe products (you can't download it as a free standalone app - which, start rant is odd, you'd think they would push the format - Microsoft's competing expresssion encoder is free end rant)

Anyway, I need to get a (hopefully not too expensive, but willing to pay for it) good 3rd part app that can take any video and convert it to an f4v.

Can you suggest any? Everything i've found is horrible or jammed with ads and crap.

What would you use? Any suggestion?

(please don't just say ffmpeg - I know it can do it but we need to good simple GUI)

Thanks!

答: Have you checked http://handbrake.fr/ </p>

Title: Best cheap GUI for converting to f4v

Body: Have you checked http://handbrake.fr/


问:
Show field_dict.items() of django-reversion in template
I am tring to use django reversion app in my project. I am little bit comfused. How to show list of changes (field_dict.items()) in template?

models.py:

```<code>@reversion.register()
class Function(models.Model):
    ***FIELDS***
</code>```

views.py:

```<code>def function_revisions(request, function_code):
    function = get_object_or_404(Function, pk=function_code)
    versions = Version.objects.get_for_object(Function)
    context = {
        'function': function,
        'versions': versions,
    }
    return render(request, 'project/function_revisions.html', context)
</code>```

function_revisions.html:

```<code>{% for version in versions %}
     <p>Version: {{ forloop.counter }}.</p>
     <p>Revision by {{ version.revision.user }}.</p>
     <p>Date of revision : {{ version.revision.date_created }}.</p>

     {% for field_name, field_value in version.field_dict.items() %} <-- ???
         <p>Field </p>{{ field_name }} had the value {{ field_value }}<p>
     {% endfor %}
{% endfor %}
</code>```

ERROR:

```<code>Traceback (most recent call last):
  File "C:\Users\Nurzhan\PycharmProjects\RMS\project\views.py", line 231, in function_revisions
    versions = Version.objects.get_for_object(Function)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\reversion\models.py", line 118, in get_for_object
    return self.get_for_object_reference(obj.__class__, obj.pk, model_db=model_db)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\reversion\models.py", line 113, in get_for_object_reference
    return self.get_for_model(model, model_db=model_db).filter(
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\reversion\models.py", line 106, in get_for_model
    content_type = _get_content_type(model, self.db)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\reversion\revisions.py", line 402, in _get_content_type
    version_options = _get_options(model)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\reversion\revisions.py", line 388, in _get_options
    _assert_registered(model)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\reversion\revisions.py", line 381, in _assert_registered
    if not is_registered(model):
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\reversion\revisions.py", line 319, in is_registered
    return _get_registration_key(model) in _registered_models
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\reversion\revisions.py", line 312, in _get_registration_key
    return (model._meta.app_label, model._meta.model_name)
AttributeError: type object 'ModelBase' has no attribute '_meta'
</code>```

答: You're passing the wrong thing into get_for_object - you need to pass the instance, function, not the model, Function.

Body:
I am tring to use django reversion app in my project. I am little bit comfused. How to show list of changes (field_dict.items()) in template?

models.py:

@reversion.register()
class Function(models.Model):
    ***FIELDS***

views.py:

def function_revisions(request, function_code):
    function = get_object_or_404(Function, pk=function_code)
    versions = Version.objects.get_for_object(Function)
    context = {
        'function': function,
        'versions': versions,
    }
    return render(request, 'project/function_revisions.html', context)

function_revisions.html:

{% for version in versions %}

Version: {{ forloop.counter }}.

Revision by {{ version.revision.user }}.

Date of revision : {{ version.revision.date_created }}.

     {% for field_name, field_value in version.field_dict.items() %} <-- ???

Field
{{ field_name }} had the value {{ field_value }}

     {% endfor %}
{% endfor %}

ERROR:

Traceback (most recent call last):
  File "C:\Users\Nurzhan\PycharmProjects\RMS\project\views.py", line 231, in function_revisions
    versions = Version.objects.get_for_object(Function)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\reversion\models.py", line 118, in get_for_object
    return self.get_for_object_reference(obj.__class__, obj.pk, model_db=model_db)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\reversion\models.py", line 113, in get_for_object_reference
    return self.get_for_model(model, model_db=model_db).filter(
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\reversion\models.py", line 106, in get_for_model
    content_type = _get_content_type(model, self.db)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\reversion\revisions.py", line 402, in _get_content_type
    version_options = _get_options(model)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\reversion\revisions.py", line 388, in _get_options
    _assert_registered(model)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\reversion\revisions.py", line 381, in _assert_registered
    if not is_registered(model):
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\reversion\revisions.py", line 319, in is_registered
    return _get_registration_key(model) in _registered_models
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\reversion\revisions.py", line 312, in _get_registration_key
    return (model._meta.app_label, model._meta.model_name)
AttributeError: type object 'ModelBase' has no attribute '_meta'