问:
Turn swift object into a JSON string
I have classes like these:

```<code>class MyDate
  {
    var year : String = ""
    var month : String = ""
    var day : String = ""

    init(year : String , month : String , day : String) {
        self.year = year
        self.month = month
        self.day = day
    }

}
</code>```

```<code>class Lad
{
    var firstName : String = ""
    var lastName : String = ""
    var dateOfBirth : MyDate?

    init(firstname : String , lastname : String , dateofbirth : MyDate) {
        self.firstName = firstname
        self.lastName = lastname
        self.dateOfBirth = dateofbirth
    }
}
</code>```

```<code>class MainCon {

    func sendData()  {

        let myDate = MyDate(year: "1901", month: "4", day: "30")
        let obj = Lad(firstname: "Markoff", lastname: "Chaney", dateofbirth: myDate)

        let api = ApiService()
        api.postDataToTheServer(led: obj)

    }

}
</code>```

```<code>class ApiService {

    func postDataToTheServer(led : Lad)  {
        // here i need to json
    }
}
</code>```

And I would like to turn a Lad object into a JSON string like this:

{
      "firstName":"Markoff",
      "lastName":"Chaney",
      "dateOfBirth":
      {
          "year":"1901",
          "month":"4",
          "day":"30"
      }
  }

答:
EDIT - 10/31/2017: This answer mostly applies to Swift 3 and possibly earlier versions. As of late 2017, we now have Swift 4 and you should be using the Encodable and Decodable protocols to convert data between representations including JSON and file encodings. (You can add the Codable protocol to use both encoding and decoding)

The usual solution for working with JSON in Swift is to use dictionaries. So you could do:

```<code>extension Date {
  var dataDictionary {
    return [
      "year": self.year,
      "month": self.month,
      "day": self.day
    ];
  }
}

extension Lad {
  var dataDictionary {
    return [
      "firstName": self.firstName,
      "lastName": self.lastName,
      "dateOfBirth": self.dateOfBirth.dataDictionary
    ];
  }
}
</code>```

and then serialize the dictionary-formatted data using JSONSerialization.

```<code>//someLad is a Lad object

do {
  // encoding dictionary data to JSON
  let jsonData = try JSONSerialization.data(withJSONObject: someLad.dataDictionary,
                                                   options: .prettyPrinted)

  // decoding JSON to Swift object
  let decoded = try JSONSerialization.jsonObject(with: jsonData, options: [])
  // after decoding, "decoded" is of type `Any?`, so it can't be used
  // we must check for nil and cast it to the right type
  if let dataFromJSON = decoded as? [String: Any] {
      // use dataFromJSON
  }
} catch {
    // handle conversion errors
}
</code>```

If you just need to do this for few classes, providing methods to turn them into dictionaries is the most readable option and won't make your app noticeably larger.

However, if you need to turn a lot of different classes into JSON it would be tedious to write out how to turn each class into a dictionary. So it would be useful to use some sort of reflection API in order to be able to list out the properties of an object. The most stable option seems to be EVReflection. Using EVReflection, for each class we want to turn into json we can do:

```<code>extension SomeClass: EVReflectable { }

let someObject: SomeClass = SomeClass();
let someObjectDictionary = someObject.toDictionary();
</code>```

and then, just like before, we can serialize the dictionary we just obtained to JSON using JSONSerialization. We'll just need to use object.toDictionary() instead of object.dataDictionary.

If you don't want to use EVReflection, you can implement reflection (the ability to see which fields an object has and iterate over them) yourself by using the Mirror class. There's an explanation of how to use Mirror for this purpose here.

So, having defined either a .dataDictionary computed variable or using EVReflection's .toDictionary() method, we can do

```<code>class ApiService {

  func postDataToTheServer(lad: Lad)  {
    //if using a custom method
    let dict = lad.dataDictionary

    //if using EVReflection
    let dict = lad.toDictionary()

    //now, we turn it into JSON
    do {
      let jsonData = try JSONSerialization.data(withJSONObject: dict,
                                                       options: .prettyPrinted)
      // send jsonData to server
    } catch {
      // handle errors
    }
  }
}
</code>```

Title: Turn swift object into a JSON string

Body:
I have classes like these:

class MyDate
  {
    var year : String = ""
    var month : String = ""
    var day : String = ""

    init(year : String , month : String , day : String) {
        self.year = year
        self.month = month
        self.day = day
    }

}

class Lad
{
    var firstName : String = ""
    var lastName : String = ""
    var dateOfBirth : MyDate?

    init(firstname : String , lastname : String , dateofbirth : MyDate) {
        self.firstName = firstname
        self.lastName = lastname
        self.dateOfBirth = dateofbirth
    }
}

class MainCon {

    func sendData()  {

        let myDate = MyDate(year: "1901", month: "4", day: "30")
        let obj = Lad(firstname: "Markoff", lastname: "Chaney", dateofbirth: myDate)

        let api = ApiService()
        api.postDataToTheServer(led: obj)

    }

}

class ApiService {

    func postDataToTheServer(led : Lad)  {
        // here i need to json
    }
}

And I would like to turn a Lad object into a JSON string like this:

{
      "firstName":"Markoff",
      "lastName":"Chaney",
      "dateOfBirth":
      {
          "year":"1901",
          "month":"4",
          "day":"30"
      }
  }

Body:
EDIT - 10/31/2017: This answer mostly applies to Swift 3 and possibly earlier versions. As of late 2017, we now have Swift 4 and you should be using the Encodable and Decodable protocols to convert data between representations including JSON and file encodings. (You can add the Codable protocol to use both encoding and decoding)

The usual solution for working with JSON in Swift is to use dictionaries. So you could do:

extension Date {
  var dataDictionary {
    return [
      "year": self.year,
      "month": self.month,
      "day": self.day
    ];
  }
}

extension Lad {
  var dataDictionary {
    return [
      "firstName": self.firstName,
      "lastName": self.lastName,
      "dateOfBirth": self.dateOfBirth.dataDictionary
    ];
  }
}

and then serialize the dictionary-formatted data using JSONSerialization.

//someLad is a Lad object

do {
  // encoding dictionary data to JSON
  let jsonData = try JSONSerialization.data(withJSONObject: someLad.dataDictionary,
                                                   options: .prettyPrinted)

  // decoding JSON to Swift object
  let decoded = try JSONSerialization.jsonObject(with: jsonData, options: [])
  // after decoding, "decoded" is of type `Any?`, so it can't be used
  // we must check for nil and cast it to the right type
  if let dataFromJSON = decoded as? [String: Any] {
      // use dataFromJSON
  }
} catch {
    // handle conversion errors
}

If you just need to do this for few classes, providing methods to turn them into dictionaries is the most readable option and won't make your app noticeably larger.

However, if you need to turn a lot of different classes into JSON it would be tedious to write out how to turn each class into a dictionary. So it would be useful to use some sort of reflection API in order to be able to list out the properties of an object. The most stable option seems to be EVReflection. Using EVReflection, for each class we want to turn into json we can do:

extension SomeClass: EVReflectable { }

let someObject: SomeClass = SomeClass();
let someObjectDictionary = someObject.toDictionary();

and then, just like before, we can serialize the dictionary we just obtained to JSON using JSONSerialization. We'll just need to use object.toDictionary() instead of object.dataDictionary.

If you don't want to use EVReflection, you can implement reflection (the ability to see which fields an object has and iterate over them) yourself by using the Mirror class. There's an explanation of how to use Mirror for this purpose here.

So, having defined either a .dataDictionary computed variable or using EVReflection's .toDictionary() method, we can do

class ApiService {

  func postDataToTheServer(lad: Lad)  {
    //if using a custom method
    let dict = lad.dataDictionary

    //if using EVReflection
    let dict = lad.toDictionary()

    //now, we turn it into JSON
    do {
      let jsonData = try JSONSerialization.data(withJSONObject: dict,
                                                       options: .prettyPrinted)
      // send jsonData to server
    } catch {
      // handle errors
    }
  }
}


来源: stackexchange

问:
Start WSO2 Enterprise Integrator as a service in windows not work
I followed the instructions in Installing EI as Windows service, but I am unable to start the service.
Below the output of runConsole.bat of YAJSW (both with yajsw-stable-11.11 and with yajsw-stable-12.08)

```<code>C:\yajsw-stable-12.08\bat>runConsole.bat

C:\yajsw-stable-12.08\bat>pushd C:\yajsw-stable-12.08\bat\

C:\yajsw-stable-12.08\bat>call setenv.bat
"java" -Xmx30m -Djna_tmpdir="C:\yajsw-stable-12.08\bat\/../tmp" -Djava.net.preferIPv4Stack=true -jar "C:\yajsw-stable-12.08\bat\/../wrapper.jar" -c "C:\yajsw-st
able-12.08\bat\/../conf/wrapper.conf"
YAJSW: yajsw-stable-12.08
OS   : Windows 7/6.1/amd64
JVM  : Oracle Corporation/1.8.0_121/C:\Program Files\Java\jre1.8.0_121/64
mar 30, 2017 3:54:18 PM org.apache.commons.vfs2.VfsLog info
INFORMAZIONI: Using "C:\Users\Sexxa\AppData\Local\Temp\vfs_cache" as temporary files store.
WARNING|wrapper|"WSO2 Carbon"|17-03-30 15:54:18|YAJSW: yajsw-stable-12.08
WARNING|wrapper|"WSO2 Carbon"|17-03-30 15:54:18|OS   : Windows 7/6.1/amd64
WARNING|wrapper|"WSO2 Carbon"|17-03-30 15:54:18|JVM  : Oracle Corporation/1.8.0_121/C:\Program Files\Java\jre1.8.0_121/64
system.env 61
INFO|wrapper|"WSO2 Carbon"|17-03-30 15:54:19|started process with pid 18140
INFO|wrapper|"WSO2 Carbon"|17-03-30 15:54:19|restart process due to default exit code rule
INFO|wrapper|"WSO2 Carbon"|17-03-30 15:54:19|restart internal RUNNING
INFO|wrapper|"WSO2 Carbon"|17-03-30 15:54:19|stopping process with pid/timeout 18140 45000
INFO|wrapper|"WSO2 Carbon"|17-03-30 15:54:20|process exit code: 1
system.env 61
INFO|wrapper|"WSO2 Carbon"|17-03-30 15:54:25|started process with pid 4508
INFO|wrapper|"WSO2 Carbon"|17-03-30 15:54:25|restart process due to default exit code rule
INFO|wrapper|"WSO2 Carbon"|17-03-30 15:54:25|restart internal RUNNING
INFO|wrapper|"WSO2 Carbon"|17-03-30 15:54:25|stopping process with pid/timeout 4508 45000
INFO|wrapper|"WSO2 Carbon"|17-03-30 15:54:26|process exit code: 1
system.env 61
INFO|wrapper|"WSO2 Carbon"|17-03-30 15:54:31|started process with pid 14232
INFO|wrapper|"WSO2 Carbon"|17-03-30 15:54:31|restart process due to default exit code rule
INFO|wrapper|"WSO2 Carbon"|17-03-30 15:54:31|restart internal RUNNING
INFO|wrapper|"WSO2 Carbon"|17-03-30 15:54:31|stopping process with pid/timeout 14232 45000
INFO|wrapper|"WSO2 Carbon"|17-03-30 15:54:32|process exit code: 1
system.env 61
INFO|wrapper|"WSO2 Carbon"|17-03-30 15:54:37|started process with pid 17972
INFO|wrapper|"WSO2 Carbon"|17-03-30 15:54:37|restart process due to default exit code rule
INFO|wrapper|"WSO2 Carbon"|17-03-30 15:54:37|restart internal RUNNING
INFO|wrapper|"WSO2 Carbon"|17-03-30 15:54:37|stopping process with pid/timeout 17972 45000
INFO|wrapper|"WSO2 Carbon"|17-03-30 15:54:38|process exit code: 1
system.env 61
INFO|wrapper|"WSO2 Carbon"|17-03-30 15:54:43|started process with pid 14460
INFO|wrapper|"WSO2 Carbon"|17-03-30 15:54:43|restart process due to default exit code rule
INFO|wrapper|"WSO2 Carbon"|17-03-30 15:54:43|restart internal RUNNING
INFO|wrapper|"WSO2 Carbon"|17-03-30 15:54:43|stopping process with pid/timeout 14460 45000
INFO|wrapper|"WSO2 Carbon"|17-03-30 15:54:44|process exit code: 1
system.env 61
INFO|wrapper|"WSO2 Carbon"|17-03-30 15:54:49|started process with pid 7148
INFO|wrapper|"WSO2 Carbon"|17-03-30 15:54:49|too many restarts
INFO|wrapper|"WSO2 Carbon"|17-03-30 15:54:49|Shutting down Wrapper
</code>```

Any ideas?

答:
Try to use wrapper.conf that is located in your WSO2 EI folder.

Path: ...\wso2-ei\bin\yajsw\wrapper.conf. And what version of WSO2 EI are you using?

ContentLicense: CC BY-SA 3.0

Body:
I followed the instructions in Installing EI as Windows service, but I am unable to start the service.
Below the output of runConsole.bat of YAJSW (both with yajsw-stable-11.11 and with yajsw-stable-12.08)

C:\yajsw-stable-12.08\bat>runConsole.bat

C:\yajsw-stable-12.08\bat>pushd C:\yajsw-stable-12.08\bat\

C:\yajsw-stable-12.08\bat>call setenv.bat
"java" -Xmx30m -Djna_tmpdir="C:\yajsw-stable-12.08\bat\/../tmp" -Djava.net.preferIPv4Stack=true -jar "C:\yajsw-stable-12.08\bat\/../wrapper.jar" -c "C:\yajsw-st
able-12.08\bat\/../conf/wrapper.conf"
YAJSW: yajsw-stable-12.08
OS   : Windows 7/6.1/amd64
JVM  : Oracle Corporation/1.8.0_121/C:\Program Files\Java\jre1.8.0_121/64
mar 30, 2017 3:54:18 PM org.apache.commons.vfs2.VfsLog info
INFORMAZIONI: Using "C:\Users\Sexxa\AppData\Local\Temp\vfs_cache" as temporary files store.
WARNING|wrapper|"WSO2 Carbon"|17-03-30 15:54:18|YAJSW: yajsw-stable-12.08
WARNING|wrapper|"WSO2 Carbon"|17-03-30 15:54:18|OS   : Windows 7/6.1/amd64
WARNING|wrapper|"WSO2 Carbon"|17-03-30 15:54:18|JVM  : Oracle Corporation/1.8.0_121/C:\Program Files\Java\jre1.8.0_121/64
system.env 61
INFO|wrapper|"WSO2 Carbon"|17-03-30 15:54:19|started process with pid 18140
INFO|wrapper|"WSO2 Carbon"|17-03-30 15:54:19|restart process due to default exit code rule
INFO|wrapper|"WSO2 Carbon"|17-03-30 15:54:19|restart internal RUNNING
INFO|wrapper|"WSO2 Carbon"|17-03-30 15:54:19|stopping process with pid/timeout 18140 45000
INFO|wrapper|"WSO2 Carbon"|17-03-30 15:54:20|process exit code: 1
system.env 61
INFO|wrapper|"WSO2 Carbon"|17-03-30 15:54:25|started process with pid 4508
INFO|wrapper|"WSO2 Carbon"|17-03-30 15:54:25|restart process due to default exit code rule
INFO|wrapper|"WSO2 Carbon"|17-03-30 15:54:25|restart internal RUNNING
INFO|wrapper|"WSO2 Carbon"|17-03-30 15:54:25|stopping process with pid/timeout 4508 45000
INFO|wrapper|"WSO2 Carbon"|17-03-30 15:54:26|process exit code: 1
system.env 61
INFO|wrapper|"WSO2 Carbon"|17-03-30 15:54:31|started process with pid 14232
INFO|wrapper|"WSO2 Carbon"|17-03-30 15:54:31|restart process due to default exit code rule
INFO|wrapper|"WSO2 Carbon"|17-03-30 15:54:31|restart internal RUNNING
INFO|wrapper|"WSO2 Carbon"|17-03-30 15:54:31|stopping process with pid/timeout 14232 45000
INFO|wrapper|"WSO2 Carbon"|17-03-30 15:54:32|process exit code: 1
system.env 61
INFO|wrapper|"WSO2 Carbon"|17-03-30 15:54:37|started process with pid 17972
INFO|wrapper|"WSO2 Carbon"|17-03-30 15:54:37|restart process due to default exit code rule
INFO|wrapper|"WSO2 Carbon"|17-03-30 15:54:37|restart internal RUNNING
INFO|wrapper|"WSO2 Carbon"|17-03-30 15:54:37|stopping process with pid/timeout 17972 45000
INFO|wrapper|"WSO2 Carbon"|17-03-30 15:54:38|process exit code: 1
system.env 61
INFO|wrapper|"WSO2 Carbon"|17-03-30 15:54:43|started process with pid 14460
INFO|wrapper|"WSO2 Carbon"|17-03-30 15:54:43|restart process due to default exit code rule
INFO|wrapper|"WSO2 Carbon"|17-03-30 15:54:43|restart internal RUNNING
INFO|wrapper|"WSO2 Carbon"|17-03-30 15:54:43|stopping process with pid/timeout 14460 45000
INFO|wrapper|"WSO2 Carbon"|17-03-30 15:54:44|process exit code: 1
system.env 61
INFO|wrapper|"WSO2 Carbon"|17-03-30 15:54:49|started process with pid 7148
INFO|wrapper|"WSO2 Carbon"|17-03-30 15:54:49|too many restarts
INFO|wrapper|"WSO2 Carbon"|17-03-30 15:54:49|Shutting down Wrapper

Any ideas?


问:
datagrid sorting is being undone each time itemsource receives an update
I have a DataGrid in a WPF application that binds an ItemSource. Every three seconds when this ItemSource receives an update the sorting on the DataGrid gets thrown out of whack. It is as close to a live feed I can get from our call system so the update every three seconds is needed. Question is how do I get the sorting to stay and or reapply before the update hits the DataGrid so the user does not see it sorted incorrectly. I've posted some code below but have no idea what information you may need to help resolve this. I've been fighting with it all day.

GOAL: Currently the code programmically sorts this list. It works for three seconds as stated above but sorting it programmically is not the goal. I'm here because I need help figuring out why it doesn't stay sorted on the data grid. I want the users to be able to sort it anyway they want in the long run. I need the sort to stop going away each time the item source is updated.

Code Behind:

```<code>private void textBlock_Loaded(object sender, RoutedEventArgs e)
        {
            FeedServiceAgent data = new FeedServiceAgent();

            data.MessageReceived += OnMessageReceived;
            data.Subscribe("92", 3);
        }

        private void OnMessageReceived(object sender, MessageReceivedEventArgs e)
        {
            try
            {
                List<NewAgent> newAgentList = new List<NewAgent>();
                if (e == null)
                    return;

                if (e.CmsData != null)
                {

                    Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() =>
                    {
                        foreach (var item in e.CmsData.Agents)
                        {
                            NewAgent newAgents = new ScoreBoardClientTest.NewAgent();

                            newAgents.AgentName = item.AgName;

                            newAgents.AgentExtension = item.Extension;

                            newAgents.AgentDateTimeChange = ConvertedDateTimeUpdated;

                            newAgents.AuxReasons = item.AuxReasonDescription;

                            newAgents.LoginIdentifier = item.LoginId;

                            newAgents.AgentState = item.WorkModeDirectionDescription;

                            var timeSpanSince = DateTime.Now - item.DateTimeUpdated;
                            newAgents.AgentDateTimeStateChange = timeSpanSince;

                            newAgentList.Add(newAgents);

                            ListCollectionView myListCollectionView = new ListCollectionView(newAgentList);

                            myListCollectionView.SortDescriptions.Add(new SortDescription("AgentState", ListSortDirection.Ascending));
                            myListCollectionView.SortDescriptions.Add(new SortDescription("AuxReasons", ListSortDirection.Descending));
                            myListCollectionView.SortDescriptions.Add(new SortDescription("AgentDateTimeStateChange", ListSortDirection.Descending));

                            DataGrid.ItemsSource = myListCollectionView;
                        }
                    }));
                }
            }
</code>```

XAML:

```<code><DataGrid Name="DataGrid" AutoGenerateColumns="False" IsReadOnly="True" HorizontalAlignment="Stretch" HorizontalContentAlignment="Stretch" ColumnWidth="*"  Foreground="Green" FontSize="10"   Loaded="textBlock_Loaded" Margin="0,10" RenderTransformOrigin="0.127,0.275" Background="{x:Null}" IsSynchronizedWithCurrentItem="False" GridLinesVisibility="Horizontal">
                <DataGrid.Columns>
                    <DataGridTextColumn Header="Name" Binding="{Binding AgentName}"  />
                    <DataGridTextColumn Header="State" Binding="{Binding AgentState}"  />
                    <DataGridTextColumn Header="Aux" Binding="{Binding AuxReasons}" />
                    <DataGridTextColumn Header="Time" Binding="{Binding AgentDateTimeStateChange, StringFormat={}{0:hh}:{0:mm}:{0:ss}}"/>
                </DataGrid.Columns>
            </DataGrid>
</code>```

CS for List Objects:

```<code>class NewAgent
    {
        public string AgentName { get; set; }
        public int AgentExtension { get; set; }
        public TimeSpan AgentDateTimeChange { get; set; }
        public TimeSpan AgentDateTimeStateChange { get; set; }
        public String AuxReasons { get; set; }
        public string LoginIdentifier { get; set; }
        public string AgentState { get; set; }

    }
</code>```

答:
My solution (not elegant but should work) - save dataGrid.Items.SortDescriptions before setting new ItemSource.

Remove lines in your code where you doing myListCollectionView.SortDescriptions.Add and try following

```<code>var sorting = DataGrid.Items.SortDescriptions
       .Select(x => new {x.PropertyName, x.Direction}).ToList();

DataGrid.ItemsSource = myListCollectionView;

foreach (var item in sorting)
{
   var col = DataGrid.Columns
               .First(x => x.SortMemberPath == item.PropertyName);
   col.SortDirection = item.Direction;
   DataGrid.Items.SortDescriptions.Add(
         new SortDescription(item.PropertyName, item.Direction));
 };
</code>```

Body:
I have a DataGrid in a WPF application that binds an ItemSource. Every three seconds when this ItemSource receives an update the sorting on the DataGrid gets thrown out of whack. It is as close to a live feed I can get from our call system so the update every three seconds is needed. Question is how do I get the sorting to stay and or reapply before the update hits the DataGrid so the user does not see it sorted incorrectly. I've posted some code below but have no idea what information you may need to help resolve this. I've been fighting with it all day.

GOAL: Currently the code programmically sorts this list. It works for three seconds as stated above but sorting it programmically is not the goal. I'm here because I need help figuring out why it doesn't stay sorted on the data grid. I want the users to be able to sort it anyway they want in the long run. I need the sort to stop going away each time the item source is updated.

Code Behind:

private void textBlock_Loaded(object sender, RoutedEventArgs e)
        {
            FeedServiceAgent data = new FeedServiceAgent();

            data.MessageReceived += OnMessageReceived;
            data.Subscribe("92", 3);
        }

        private void OnMessageReceived(object sender, MessageReceivedEventArgs e)
        {
            try
            {
                List<NewAgent> newAgentList = new List<NewAgent>();
                if (e == null)
                    return;

                if (e.CmsData != null)
                {

                    Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() =>
                    {
                        foreach (var item in e.CmsData.Agents)
                        {
                            NewAgent newAgents = new ScoreBoardClientTest.NewAgent();

                            newAgents.AgentName = item.AgName;

                            newAgents.AgentExtension = item.Extension;

                            newAgents.AgentDateTimeChange = ConvertedDateTimeUpdated;

                            newAgents.AuxReasons = item.AuxReasonDescription;

                            newAgents.LoginIdentifier = item.LoginId;

                            newAgents.AgentState = item.WorkModeDirectionDescription;

                            var timeSpanSince = DateTime.Now - item.DateTimeUpdated;
                            newAgents.AgentDateTimeStateChange = timeSpanSince;

                            newAgentList.Add(newAgents);

                            ListCollectionView myListCollectionView = new ListCollectionView(newAgentList);

                            myListCollectionView.SortDescriptions.Add(new SortDescription("AgentState", ListSortDirection.Ascending));
                            myListCollectionView.SortDescriptions.Add(new SortDescription("AuxReasons", ListSortDirection.Descending));
                            myListCollectionView.SortDescriptions.Add(new SortDescription("AgentDateTimeStateChange", ListSortDirection.Descending));

                            DataGrid.ItemsSource = myListCollectionView;
                        }
                    }));
                }
            }

XAML:

<DataGrid Name="DataGrid" AutoGenerateColumns="False" IsReadOnly="True" HorizontalAlignment="Stretch" HorizontalContentAlignment="Stretch" ColumnWidth="*"  Foreground="Green" FontSize="10"   Loaded="textBlock_Loaded" Margin="0,10" RenderTransformOrigin="0.127,0.275" Background="{x:Null}" IsSynchronizedWithCurrentItem="False" GridLinesVisibility="Horizontal">
                <DataGrid.Columns>
                    <DataGridTextColumn Header="Name" Binding="{Binding AgentName}"  />
                    <DataGridTextColumn Header="State" Binding="{Binding AgentState}"  />
                    <DataGridTextColumn Header="Aux" Binding="{Binding AuxReasons}" />
                    <DataGridTextColumn Header="Time" Binding="{Binding AgentDateTimeStateChange, StringFormat={}{0:hh}:{0:mm}:{0:ss}}"/>
                </DataGrid.Columns>
            </DataGrid>

CS for List Objects:

class NewAgent
    {
        public string AgentName { get; set; }
        public int AgentExtension { get; set; }
        public TimeSpan AgentDateTimeChange { get; set; }
        public TimeSpan AgentDateTimeStateChange { get; set; }
        public String AuxReasons { get; set; }
        public string LoginIdentifier { get; set; }
        public string AgentState { get; set; }

    }

Body:
My solution (not elegant but should work) - save dataGrid.Items.SortDescriptions before setting new ItemSource.

Remove lines in your code where you doing myListCollectionView.SortDescriptions.Add and try following

var sorting = DataGrid.Items.SortDescriptions
       .Select(x => new {x.PropertyName, x.Direction}).ToList();

DataGrid.ItemsSource = myListCollectionView;

foreach (var item in sorting)
{
   var col = DataGrid.Columns
               .First(x => x.SortMemberPath == item.PropertyName);
   col.SortDirection = item.Direction;
   DataGrid.Items.SortDescriptions.Add(
         new SortDescription(item.PropertyName, item.Direction));
 };


问:
Does HTML5 audio stream, or download and then play
I intend to put together a web based player for myself. Is it possible to stream audio files using the html5  tag? or will they fully download and then play. Is any special server configuration required to play these files

Also what if the audio is not a file on the server but being dynamically generated on the server side with the raw bytes being written to the response stream

答:
http://www.w3.org/TR/2010/WD-html5-20101019/video.html#audio

edit:

What's up with all that downloading?

Opera, Chrome and Safari will automatically download the whole video file even if it hasn't started to play yet. Firefox 3.6 only loads enough to render a frame and determine duration, unless the autobuffer attribute is present. Note that the spec changed from autobuffer to preload, which hasn't been implemented anywhere yet. Opera plans to change to the Firefox behavior of only loading enough to render a frame and determine duration by default, unless the preload attribute says otherwise.

source: http://dev.opera.com/articles/view/everything-you-need-to-know-about-html5-video-and-audio/

ContentLicense: CC BY-SA 2.5


问:
Using Javascript to set maxlength of a form text field, not working
So, I have this in my javascript file:

```<code>function yeahbaby() {
document.getElementByName("surname").maxLength = "40";
}
</code>```

which is loaded in this line of code in my htm file

```<code><form action="blah blah blah"
method="post" name="medicalform" onsubmit="return unrelated validation function();"
onload="yeahbaby();">
</code>```

With the final result being that this input field

```<code>Surname: <input type="text" name="surname">
</code>```

is limited to a maximum of 40 characters.

However, it doesn't actually put the limit on the input field, as I can type many more than 40 characters (or whatever I try changing it to).

I know I can change it in the htm file directly but I need to actually change it using javascript. I've literally been trying to fix this for the past two hours. Have I missed something?

Edit: I've tried getElementsbyName (adding the S) and it's still not working.

Edit 2: document.getElementsByName("surname")[0].setAttribute('maxLength', '40'); doesn't work either

Edit 3: https://pastebin.com/7SNmmcSN a link to both my HTML and javascript files.

答:
The problem in your code is that you put the JavaScript as a funciton but not invoking the function.

Also note that it is getElementsByName not getElementByName and it will return an HTML collection not a single element.

So, you have to specify the index [0].

Check the below snippet.

function yeahbaby() {
document.getElementsByName("surname")[0].setAttribute("maxLength", "40");
}
yeahbaby();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form action="blah blah blah"
method="post" name="medicalform" onsubmit="return unrelated validation function();"
onload="yeahbaby();">

Surname: <input type="text" name="surname"></code>```

Body:
So, I have this in my javascript file:

function yeahbaby() {
document.getElementByName("surname").maxLength = "40";
}

which is loaded in this line of code in my htm file

<form action="blah blah blah"
method="post" name="medicalform" onsubmit="return unrelated validation function();"
onload="yeahbaby();">

With the final result being that this input field

Surname: <input type="text" name="surname">

is limited to a maximum of 40 characters.

However, it doesn't actually put the limit on the input field, as I can type many more than 40 characters (or whatever I try changing it to).

I know I can change it in the htm file directly but I need to actually change it using javascript. I've literally been trying to fix this for the past two hours. Have I missed something?

Edit: I've tried getElementsbyName (adding the S) and it's still not working.

Edit 2: document.getElementsByName("surname")[0].setAttribute('maxLength', '40'); doesn't work either

Edit 3: https://pastebin.com/7SNmmcSN a link to both my HTML and javascript files.

Body:
The problem in your code is that you put the JavaScript as a funciton but not invoking the function.

Also note that it is getElementsByName not getElementByName and it will return an HTML collection not a single element.

So, you have to specify the index [0].

Check the below snippet.

function yeahbaby() {
document.getElementsByName("surname")[0].setAttribute("maxLength", "40");
}
yeahbaby();

<form action="blah blah blah"
method="post" name="medicalform" onsubmit="return unrelated validation function();"
onload="yeahbaby();">

Surname: <input type="text" name="surname">


问:
mysql Database lookup using wso2esb or wso2-am
Just as the title suggests.
I want to wrap a database call in an API or REST API whichever is easiest preferable API Manager API.

How can i do this and return the data from the database in json?

答:
You can use DSS to access the database, and then a payload factory mediator or Data Mapper to transform the response in a json.
Alternatively, you can use DSS to expose your data as a set of REST style resource.Take a look at this link for an example on how to achieve this.</p>


问:
How to save text file as variable in IOS
I am sending some images via socket and I would like to create text file with information about the images to send over the network as well.  I right now I can send the images no problem by creating a variable for the image data like so

```<code>let imageData = UIImageJPEGRepresentation(someUIImage, 1.0)
</code>```

How do create a variable with the data of the text file?

```<code>let textData = someTextFileAsData.....
</code>```

答:
You should use write(to: URL, atomically: Bool) or write(toFile: String, atomically: Bool) of NSData method to write your data in a file.

In your case it would be :

```<code>let imageData = UIImageJPEGRepresentation(someUIImage, 1.0)
imageData.writeToFile("imageData.txt", atomically:true)
</code>```

You can then restore it like that :

```<code>var imageData = NSData(contentsOfFile: "imageData.txt")
</code>```

And to get back the image from data :

```<code>let image : UIImage = UIImage(data: imageData)
</code>```

Body:
I am sending some images via socket and I would like to create text file with information about the images to send over the network as well.  I right now I can send the images no problem by creating a variable for the image data like so

let imageData = UIImageJPEGRepresentation(someUIImage, 1.0)

How do create a variable with the data of the text file?

let textData = someTextFileAsData.....

Body:
You should use write(to: URL, atomically: Bool) or write(toFile: String, atomically: Bool) of NSData method to write your data in a file.

In your case it would be :

let imageData = UIImageJPEGRepresentation(someUIImage, 1.0)
imageData.writeToFile("imageData.txt", atomically:true)

You can then restore it like that :

var imageData = NSData(contentsOfFile: "imageData.txt")

And to get back the image from data :

let image : UIImage = UIImage(data: imageData)


问:
Destructor causes corruption of the heap.
I'm playing around with destructors and I don't understand why I get an error for this code when the main function terminates.

```<code>#include <iostream>
#include <math.h>
#include <string>
#include <cstdint>
#include <cassert>
using namespace std;

class RGBA {
    uint8_t _red, _blue, _green, _alpha;
    int *_arr;
    int _length;
public:
    RGBA(int *arr, int length, uint8_t r = 0, uint8_t b = 0, uint8_t g = 0, uint8_t a = 255):
      _red (r), _blue (b), _green (g), _alpha (a) {
      _arr = arr;
      _length = length;
      }
      ~RGBA() {
          cout << "Destroying object" << endl;
          delete[] _arr;
      }

    void print() {
        for (int i = 0; i < _length; ++i) {
            cout << _arr[i] << endl;
        }
        cout << static_cast<int>(_red) << " " << static_cast<int>(_blue) << " " << static_cast<int>(_green) << " " << static_cast<int>(_alpha) << endl;
    }
};

int main() {
    int arr[3] = {1,2,3};
    RGBA rgba(arr, 3);
    rgba.print();

    cin.get();
    return 0;
}
</code>```

It outputs, but then when I press Enter, it prints 'Destroying object' with the following error "This may be due to a corruption of the heap, which indicates a bug in testcpp.exe or any of the DLLs it has loaded.".

```<code>1
2
3
0 0 0 255
</code>```

I use VS2010 on Win7.

答:
That's because you aren't supposed to delete the array.

The implementation of your destructor is correct, but the array is not allocated with new[], so you must not de-allocating with delete[].

If you'd replace your array in your main with it's modernized cousin, std::array, and the pointer in your class by std::vector, you would see that assigning a array to a vector would require an allocation on the heap and a copy of each element in your array.

A quick way to fix the code would be to allocate the array using new[]:

```<code>int* arr = new int[3]{1, 2, 3};
RGBA rgba(arr, 3);
rgba.print();
</code>```

Now that the array is allocated using new[], it can be safely deleted using delete[].

However, please note that in most modern code, you either use std::array<T, N>, std::vector<T> or std::unique_ptr<T[]> to manage arrays.

The resulting code that use arrays and vectors would be like this:

```<code>#include <iostream>
#include <vector>
#include <array>

struct RGBA {
    std::uint8_t red = 0, green = 0, blue = 0, alpha = 255;
    std::vector<int> arr;

    RGBA(std::vector<int> _arr) : arr{std::move(_arr)} {}

    // No destructor needed. vector manages it's own resources.

    void print() {
        for (auto&& number : arr) {
            std::cout << number << std::endl;
        }

        std::cout << static_cast<int>(red) << " "
                  << static_cast<int>(blue) << " "
                  << static_cast<int>(green) << " "
                  << static_cast<int>(alpha) << std::endl;
    }
};

int main() {
    // Create a constant array on the stack the modern way
    constexpr std::array<int, 3> arr{1, 2, 3};

    // Copy array elements in the vector
    RGBA rgba{std::vector<int>{arr.begin(), arr.end()}};

    rgba.print();

    cin.get();
}
</code>```

Body:
I'm playing around with destructors and I don't understand why I get an error for this code when the main function terminates.

#include <iostream>
#include <math.h>
#include <string>
#include <cstdint>
#include <cassert>
using namespace std;

class RGBA {
    uint8_t _red, _blue, _green, _alpha;
    int *_arr;
    int _length;
public:
    RGBA(int *arr, int length, uint8_t r = 0, uint8_t b = 0, uint8_t g = 0, uint8_t a = 255):
      _red (r), _blue (b), _green (g), _alpha (a) {
      _arr = arr;
      _length = length;
      }
      ~RGBA() {
          cout << "Destroying object" << endl;
          delete[] _arr;
      }

    void print() {
        for (int i = 0; i < _length; ++i) {
            cout << _arr[i] << endl;
        }
        cout << static_cast<int>(_red) << " " << static_cast<int>(_blue) << " " << static_cast<int>(_green) << " " << static_cast<int>(_alpha) << endl;
    }
};

int main() {
    int arr[3] = {1,2,3};
    RGBA rgba(arr, 3);
    rgba.print();

    cin.get();
    return 0;
}

It outputs, but then when I press Enter, it prints 'Destroying object' with the following error "This may be due to a corruption of the heap, which indicates a bug in testcpp.exe or any of the DLLs it has loaded.".

1
2
3
0 0 0 255

I use VS2010 on Win7.

Body:
That's because you aren't supposed to delete the array.

The implementation of your destructor is correct, but the array is not allocated with new[], so you must not de-allocating with delete[].

If you'd replace your array in your main with it's modernized cousin, std::array, and the pointer in your class by std::vector, you would see that assigning a array to a vector would require an allocation on the heap and a copy of each element in your array.

A quick way to fix the code would be to allocate the array using new[]:

int* arr = new int[3]{1, 2, 3};
RGBA rgba(arr, 3);
rgba.print();

Now that the array is allocated using new[], it can be safely deleted using delete[].

However, please note that in most modern code, you either use std::array<T, N>, std::vector<T> or std::unique_ptr<T[]> to manage arrays.

The resulting code that use arrays and vectors would be like this:

#include <iostream>
#include <vector>
#include <array>

struct RGBA {
    std::uint8_t red = 0, green = 0, blue = 0, alpha = 255;
    std::vector<int> arr;

    RGBA(std::vector<int> _arr) : arr{std::move(_arr)} {}

    // No destructor needed. vector manages it's own resources.

    void print() {
        for (auto&& number : arr) {
            std::cout << number << std::endl;
        }

        std::cout << static_cast<int>(red) << " "
                  << static_cast<int>(blue) << " "
                  << static_cast<int>(green) << " "
                  << static_cast<int>(alpha) << std::endl;
    }
};

int main() {
    // Create a constant array on the stack the modern way
    constexpr std::array<int, 3> arr{1, 2, 3};

    // Copy array elements in the vector
    RGBA rgba{std::vector<int>{arr.begin(), arr.end()}};

    rgba.print();

    cin.get();
}


问:
Take first N keys by max value from dict {key:list}
is there have easy way to take first N keys which have max value from they list in dict {key:list}
    is there have easy way to take first N keys which have max value from they list in dict {key:list}

```<code>def main():

    for x in range(len(sale10k)):
        timelist.append(sale10k[x][3])
        pricesList.append(sale10k[x][4])
        if sale10k[x][0] in salesByCategory.keys():
            salesByCategory[sale10k[x][0]].append(float(sale10k[x][4]))
        else:
            salesByCategory[sale10k[x][0]]=[]
            salesByCategory[sale10k[x][0]].append(float(sale10k[x][4]))

    salesByCategory1={}
    for key,value in salesByCategory.items():
        salesByCategory1[key]=sum(salesByCategory.get(key))

    #fiveLarges=heapq.nlargest(5,salesByCategory1,key=salesByCategory1.get)
    salesBycatalog={}
    for y in range(len(catalog)):
       salesBycatalog[catalog[y][0]]=catalog[y][5]
    totalByGroup={}
    for key, value in salesBycatalog.items():
        if value in totalByGroup.keys():
            totalByGroup[value].append(salesByCategory1.get(key))
        else:
            totalByGroup[value]=[]
            totalByGroup[value].append(salesByCategory1.get(key))

    print(totalByGroup)

if __name__ == "__main__":
    main()

 i have 2 files excel.cvs

my output from now is this :

{'POLO SHIRTS': [2609.76, 13339.109999999991, 15622.410000000007], 'APPAREL ACCESSORIES': [22596.24999999999, 20901.099999999995, 31007.8], 'PANTS': [8031.729999999998, 11179.949999999999, 5405.839999999997, 9023.949999999999, 21523.819999999996, 26030.800000000017], 'FOOTWEAR ACCESSORIES': [8686.369999999999], 'GLIDING SP.EQUIPMENT': [22136.399999999987, 27678.920000000006, 14222.21999999999, 30013.37000000001], 'SHOES': [1903.66, 25443.21999999999, 22152.530000000006, 11585.410000000002, 38504.679999999986, 7787.670000000004, 10256.860000000002, 1377.1199999999997, 15459.799999999992, 20919.56000000001, 6299.769999999996, 1555.4499999999998, 17470.460000000006, 29361.220000000034, 4070.9000000000033, 27045.450000000004, 20721.829999999994, 780.55, 24671.590000000015, 13189.570000000002, 6442.700000000001, 6105.390000000005, 12701.659999999998, 29418.89000000001, 7295.620000000001, 26344.420000000002, 3262.12, 11710.460000000006, 3272.2999999999993, 17055.989999999994, 9019.77, 12722.570000000003, 20020.150000000005, 30164.860000000026, 17513.14, 3168.6200000000003, 27008.24, 14585.679999999988, 15273.48, 24172.329999999998, 33968.96000000003, 35480.790000000015, 25150.459999999992, 24207.679999999997, 26909.090000000007, 17692.079999999998, 27844.97999999999, 33847.389999999985, 13266.239999999994, 11757.349999999997, 24469.410000000018, 8214.879999999997, 3966.6899999999964, 5336.910000000003, 27766.659999999978, 24636.97000000002, 21330.829999999994, 10331.680000000004, 19769.529999999995, 20764.439999999984, 2873.509999999999, 23263.23, 15127.240000000003, 13282.320000000003, 32917.03000000001, 17657.12, 9959.55, 21052.779999999995, 16015.79, 2667.2699999999995, 16041.830000000004, 2309.9000000000005, 8095.450000000001, 23628.889999999985, 3846.259999999999, 6795.61, 14608.109999999995, 6422.360000000001, 3241.279999999999, 19220.27999999999, 20836.899999999994, 28446.07000000001, 13984.979999999992, 10006.460000000003, 14417.309999999998, 9069.470000000001, 8081.38, 1766.8899999999999, 19041.750000000004, 3310.279999999999, 3649.49, 11089.069999999994, 10946.420000000002, 16297.91, 3788.1000000000004, 27356.640000000007, 14024.480000000001, 29409.03], 'SUITS': [28587.990000000016, 14337.800000000001], 'BALLS': [25855.07, 15207.729999999992, 25567.809999999987, 8428.509999999998, 15119.609999999995, 26069.969999999983, 29843.490000000023], 'TOPS': [1673.2000000000005, 8673.400000000001, 23610.79999999999, 2090.380000000001], 'HEADWEAR': [2075.3000000000015, 18891.799999999996, 39717.93, 33657.65, 9965.720000000005, 12030.020000000006, 670.9999999999999, 12694.720000000007, 24846.22000000001, 1606.1799999999994, 9993.330000000002, 10154.900000000005], 'HARDWARE ACCESSORIES': [14619.109999999997], 'OTHER SHIRTS': [18013.450000000004], 'PROTECTION GEAR': [26454.929999999997], 'JERSEYS': [23741.06, 38425.269999999975], 'SANDALS/SLIPPERS': [9103.83, 21025.040000000005, 12702.349999999999, 26766.439999999984, 29818.339999999993], 'SHORTS': [14817.77, 29540.92999999998, 9415.059999999996, 14582.480000000001], 'JACKETS': [30096.11000000001, 13372.469999999998, 31145.73000000001, 6011.17, 12225.300000000003, 23485.399999999998, 13889.96], 'SWIMWEAR': [14035.140000000001, 20232.629999999997, 5142.340000000001, 2945.349999999998, 23495.320000000003, 8207.920000000004, 11972.729999999994], 'T-SHIRTS': [11130.700000000004, 8315.83, 8346.719999999998, 27847.550000000007, 22704.759999999995, 7828.200000000002, 17823.379999999997, 2248.46, 9012.14, 7774.72, 12030.049999999996, 4207.649999999999, 21293.16, 3159.4700000000007, 13385.12, 30507.87], 'UNDERWEAR': [10419.31, 31017.909999999993, 2794.590000000002, 18625.990000000005, 21829.879999999994], 'SWEATSHIRTS': [4317.6799999999985, 23453.049999999985, 28176.49000000001], 'TIGHTS': [23823.43999999999, 11180.129999999996], 'BAGS': [13980.240000000007, 18509.50999999999, 20064.309999999998, 22317.360000000004, 17641.04]}

i need this :

SHOES: 1519077.15 €
    T-SHIRTS: 207615.78 €
    HEADWEAR: 176304.77 €
    BALLS: 146092.19 €
    JACKETS: 130226.14 €

I have data stored in dict orderBygroup {key-list(of float values)} and need to take first 5 keys with max value.
My second question is - dict salesByCategory1 is make with loping to salesByCategory and sum of all values to receive the total for article number.
</code>```

Can i get that totals with some smartes way ?
    is there have easy way to make that output ?

答:
```<code>   totalByGroup1={}
    for key,value in totalByGroup.items():
        totalByGroup1[key]=sum(totalByGroup.get(key))
</code>```

Create a new dictionary with summed elements. More resources.

```<code>    sorted5=sorted(totalByGroup1, key=totalByGroup1.get, reverse=True)[:5]
    print(sorted5)
</code>```

sorting and taking the first 5 elements
output is : ['SHOES', 'T-SHIRTS', 'HEADWEAR', 'BALLS', 'JACKETS']
more time, more resurses

```<code>    for key in sorted5:
        print(key,': ','{0:.2f}'.format(totalByGroup1.get(key)))
</code>```

and now result :
SHOES :  1519077.15
T-SHIRTS :  207615.78
HEADWEAR :  176304.77
BALLS :  146092.19
JACKETS :  130226.14

now lets ask again if we have 4 record in dict wit that data:
a:[1,2,3],b:[6,7,8],c:[4,5,6],d:[9,10,11]
how to get first 2 key,value sorted by max value -->>
d:30,b:21

if we have 1000 record in dict - ?? how to get first N key sorted by max value of list
example go:1563,do:1560,bo:1490,ro:1480 .. etc

Body:
is there have easy way to take first N keys which have max value from they list in dict {key:list}
    is there have easy way to take first N keys which have max value from they list in dict {key:list}

def main():

    for x in range(len(sale10k)):
        timelist.append(sale10k[x][3])
        pricesList.append(sale10k[x][4])
        if sale10k[x][0] in salesByCategory.keys():
            salesByCategory[sale10k[x][0]].append(float(sale10k[x][4]))
        else:
            salesByCategory[sale10k[x][0]]=[]
            salesByCategory[sale10k[x][0]].append(float(sale10k[x][4]))

    salesByCategory1={}
    for key,value in salesByCategory.items():
        salesByCategory1[key]=sum(salesByCategory.get(key))

    #fiveLarges=heapq.nlargest(5,salesByCategory1,key=salesByCategory1.get)
    salesBycatalog={}
    for y in range(len(catalog)):
       salesBycatalog[catalog[y][0]]=catalog[y][5]
    totalByGroup={}
    for key, value in salesBycatalog.items():
        if value in totalByGroup.keys():
            totalByGroup[value].append(salesByCategory1.get(key))
        else:
            totalByGroup[value]=[]
            totalByGroup[value].append(salesByCategory1.get(key))

    print(totalByGroup)

if __name__ == "__main__":
    main()

 i have 2 files excel.cvs

my output from now is this :

{'POLO SHIRTS': [2609.76, 13339.109999999991, 15622.410000000007], 'APPAREL ACCESSORIES': [22596.24999999999, 20901.099999999995, 31007.8], 'PANTS': [8031.729999999998, 11179.949999999999, 5405.839999999997, 9023.949999999999, 21523.819999999996, 26030.800000000017], 'FOOTWEAR ACCESSORIES': [8686.369999999999], 'GLIDING SP.EQUIPMENT': [22136.399999999987, 27678.920000000006, 14222.21999999999, 30013.37000000001], 'SHOES': [1903.66, 25443.21999999999, 22152.530000000006, 11585.410000000002, 38504.679999999986, 7787.670000000004, 10256.860000000002, 1377.1199999999997, 15459.799999999992, 20919.56000000001, 6299.769999999996, 1555.4499999999998, 17470.460000000006, 29361.220000000034, 4070.9000000000033, 27045.450000000004, 20721.829999999994, 780.55, 24671.590000000015, 13189.570000000002, 6442.700000000001, 6105.390000000005, 12701.659999999998, 29418.89000000001, 7295.620000000001, 26344.420000000002, 3262.12, 11710.460000000006, 3272.2999999999993, 17055.989999999994, 9019.77, 12722.570000000003, 20020.150000000005, 30164.860000000026, 17513.14, 3168.6200000000003, 27008.24, 14585.679999999988, 15273.48, 24172.329999999998, 33968.96000000003, 35480.790000000015, 25150.459999999992, 24207.679999999997, 26909.090000000007, 17692.079999999998, 27844.97999999999, 33847.389999999985, 13266.239999999994, 11757.349999999997, 24469.410000000018, 8214.879999999997, 3966.6899999999964, 5336.910000000003, 27766.659999999978, 24636.97000000002, 21330.829999999994, 10331.680000000004, 19769.529999999995, 20764.439999999984, 2873.509999999999, 23263.23, 15127.240000000003, 13282.320000000003, 32917.03000000001, 17657.12, 9959.55, 21052.779999999995, 16015.79, 2667.2699999999995, 16041.830000000004, 2309.9000000000005, 8095.450000000001, 23628.889999999985, 3846.259999999999, 6795.61, 14608.109999999995, 6422.360000000001, 3241.279999999999, 19220.27999999999, 20836.899999999994, 28446.07000000001, 13984.979999999992, 10006.460000000003, 14417.309999999998, 9069.470000000001, 8081.38, 1766.8899999999999, 19041.750000000004, 3310.279999999999, 3649.49, 11089.069999999994, 10946.420000000002, 16297.91, 3788.1000000000004, 27356.640000000007, 14024.480000000001, 29409.03], 'SUITS': [28587.990000000016, 14337.800000000001], 'BALLS': [25855.07, 15207.729999999992, 25567.809999999987, 8428.509999999998, 15119.609999999995, 26069.969999999983, 29843.490000000023], 'TOPS': [1673.2000000000005, 8673.400000000001, 23610.79999999999, 2090.380000000001], 'HEADWEAR': [2075.3000000000015, 18891.799999999996, 39717.93, 33657.65, 9965.720000000005, 12030.020000000006, 670.9999999999999, 12694.720000000007, 24846.22000000001, 1606.1799999999994, 9993.330000000002, 10154.900000000005], 'HARDWARE ACCESSORIES': [14619.109999999997], 'OTHER SHIRTS': [18013.450000000004], 'PROTECTION GEAR': [26454.929999999997], 'JERSEYS': [23741.06, 38425.269999999975], 'SANDALS/SLIPPERS': [9103.83, 21025.040000000005, 12702.349999999999, 26766.439999999984, 29818.339999999993], 'SHORTS': [14817.77, 29540.92999999998, 9415.059999999996, 14582.480000000001], 'JACKETS': [30096.11000000001, 13372.469999999998, 31145.73000000001, 6011.17, 12225.300000000003, 23485.399999999998, 13889.96], 'SWIMWEAR': [14035.140000000001, 20232.629999999997, 5142.340000000001, 2945.349999999998, 23495.320000000003, 8207.920000000004, 11972.729999999994], 'T-SHIRTS': [11130.700000000004, 8315.83, 8346.719999999998, 27847.550000000007, 22704.759999999995, 7828.200000000002, 17823.379999999997, 2248.46, 9012.14, 7774.72, 12030.049999999996, 4207.649999999999, 21293.16, 3159.4700000000007, 13385.12, 30507.87], 'UNDERWEAR': [10419.31, 31017.909999999993, 2794.590000000002, 18625.990000000005, 21829.879999999994], 'SWEATSHIRTS': [4317.6799999999985, 23453.049999999985, 28176.49000000001], 'TIGHTS': [23823.43999999999, 11180.129999999996], 'BAGS': [13980.240000000007, 18509.50999999999, 20064.309999999998, 22317.360000000004, 17641.04]}

i need this :

SHOES: 1519077.15 €
    T-SHIRTS: 207615.78 €
    HEADWEAR: 176304.77 €
    BALLS: 146092.19 €
    JACKETS: 130226.14 €

I have data stored in dict orderBygroup {key-list(of float values)} and need to take first 5 keys with max value.
My second question is - dict salesByCategory1 is make with loping to salesByCategory and sum of all values to receive the total for article number.

Can i get that totals with some smartes way ?
    is there have easy way to make that output ?

Body:
   totalByGroup1={}
    for key,value in totalByGroup.items():
        totalByGroup1[key]=sum(totalByGroup.get(key))

Create a new dictionary with summed elements. More resources.

    sorted5=sorted(totalByGroup1, key=totalByGroup1.get, reverse=True)[:5]
    print(sorted5)

sorting and taking the first 5 elements
output is : ['SHOES', 'T-SHIRTS', 'HEADWEAR', 'BALLS', 'JACKETS']
more time, more resurses

    for key in sorted5:
        print(key,': ','{0:.2f}'.format(totalByGroup1.get(key)))

and now result :
SHOES :  1519077.15
T-SHIRTS :  207615.78
HEADWEAR :  176304.77
BALLS :  146092.19
JACKETS :  130226.14

now lets ask again if we have 4 record in dict wit that data:
a:[1,2,3],b:[6,7,8],c:[4,5,6],d:[9,10,11]
how to get first 2 key,value sorted by max value -->>
d:30,b:21

if we have 1000 record in dict - ?? how to get first N key sorted by max value of list
example go:1563,do:1560,bo:1490,ro:1480 .. etc


问:
Unit Testing No provider for ChangeDetectorRef
version: Angular 4.

I am injecting a parent component into child component to access parent method through child component.

In parent-component I had to use ChangeDetectorRef because it has a property which will update runtime.

Now code is working fine but child-component spec is throwing error for "ChangeDetectorRef" which is injected in parent component.

Error: No provider for ChangeDetectorRef!

Parent Component

```<code>import { Component, AfterViewChecked, ChangeDetectorRef, ChangeDetectionStrategy } from '@angular/core';

@Component({
  selector: 'parent-component',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ParentComponent implements AfterViewChecked {

  stageWidth: number;

  constructor(private ref: ChangeDetectorRef) {
    this.ref = ref;
  }

  //call this function as many times as number of child components within parent-component.
  parentMethod(childInterface: ChildInterface) {
    this.childInterfaces.push(childInterface);
  }

  ngAfterViewChecked() {
    this.elementWidth = this.updateElementWidthRuntime();
    this.ref.detectChanges();
  }
}
</code>```

Child Component

```<code>import { Component, AfterViewInit } from '@angular/core';
import { ParentComponent } from '../carousel.component';

@Component({
  selector: 'child-component',
  templateUrl: './carousel-slide.component.html',
  styleUrls: ['./carousel-slide.component.scss'],
})
export class ChildComponent implements AfterViewInit {

  constructor(private parentComponent: ParentComponent) {
  }

  ngAfterViewInit() {
    this.parentComponent.parentMethod(this);
  }
}
</code>```

app.html

```<code><parent-component>
    <child-component>
      <div class="box">Content of any height and width</div>
    </child-component>
    <child-component>
      <div class="box">Content of any height and width</div>
    </child-component>
    <child-component>
      <div class="box">Content of any height and width</div>
    </child-component>
</parent-component>
</code>```

Unit test for Child Component

```<code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { ParentComponent } from '../parent.component';
import { ChildComponent } from './child.component';

describe('ChildComponent', () => {
  let component: ChildComponent;
  let fixture: ComponentFixture<ChildComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ChildComponent],
      providers: [ParentComponent]
    })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ChildComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create \'ChildComponent\'', () => {
    expect(component).toBeTruthy();
  });
});
</code>```

When I am trying to add ChangeDetectorRef in providers in child spec, I am getting following error.

Failed: Encountered undefined provider! Usually this means you have a
  circular dependencies (might be caused by using 'barrel' index.ts
  files.)

After googling and trying many things I am unable to find solution. Any help appreciated.

答:
I am able to get rid of this error by making "ChangeDetectorRef" as @Optional dependency in my Parent Component.

```<code>constructor(@Optional() private ref: ChangeDetectorRef) {
    this.ref = ref;
}
</code>```

This way my child component's configureTestingModule will ignore ParentComponent provider.

Body:
version: Angular 4.

I am injecting a parent component into child component to access parent method through child component.

In parent-component I had to use ChangeDetectorRef because it has a property which will update runtime.

Now code is working fine but child-component spec is throwing error for "ChangeDetectorRef" which is injected in parent component.

Error: No provider for ChangeDetectorRef!

Parent Component

import { Component, AfterViewChecked, ChangeDetectorRef, ChangeDetectionStrategy } from '@angular/core';

@Component({
  selector: 'parent-component',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ParentComponent implements AfterViewChecked {

  stageWidth: number;

  constructor(private ref: ChangeDetectorRef) {
    this.ref = ref;
  }

  //call this function as many times as number of child components within parent-component.
  parentMethod(childInterface: ChildInterface) {
    this.childInterfaces.push(childInterface);
  }

  ngAfterViewChecked() {
    this.elementWidth = this.updateElementWidthRuntime();
    this.ref.detectChanges();
  }
}

Child Component

import { Component, AfterViewInit } from '@angular/core';
import { ParentComponent } from '../carousel.component';

@Component({
  selector: 'child-component',
  templateUrl: './carousel-slide.component.html',
  styleUrls: ['./carousel-slide.component.scss'],
})
export class ChildComponent implements AfterViewInit {

  constructor(private parentComponent: ParentComponent) {
  }

  ngAfterViewInit() {
    this.parentComponent.parentMethod(this);
  }
}

app.html

<parent-component>
    <child-component>

Content of any height and width

    </child-component>
    <child-component>

Content of any height and width

    </child-component>
    <child-component>

Content of any height and width

    </child-component>
</parent-component>

Unit test for Child Component

import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { ParentComponent } from '../parent.component';
import { ChildComponent } from './child.component';

describe('ChildComponent', () => {
  let component: ChildComponent;
  let fixture: ComponentFixture<ChildComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ChildComponent],
      providers: [ParentComponent]
    })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ChildComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create \'ChildComponent\'', () => {
    expect(component).toBeTruthy();
  });
});

When I am trying to add ChangeDetectorRef in providers in child spec, I am getting following error.

Failed: Encountered undefined provider! Usually this means you have a
  circular dependencies (might be caused by using 'barrel' index.ts
  files.)

After googling and trying many things I am unable to find solution. Any help appreciated.

Body:
I am able to get rid of this error by making "ChangeDetectorRef" as @Optional dependency in my Parent Component.

constructor(@Optional() private ref: ChangeDetectorRef) {
    this.ref = ref;
}

This way my child component's configureTestingModule will ignore ParentComponent provider.


问:
How to play in line headphones and bluetooth simultaneously iOS?
Xcode Swift! How to play sound in line headphones and bluetooth simultaneously?</p>

答:
I don't actually think there's a way to do it. Since the signal of the headphone-jack is analog, it kind of deactivates the audio signal for the speakers and or bluetooth.

Not sure though.


问:
Linking combo box (JQuery preferrably)
I am wondering if anyone has any experience using a JQuery plugin that converts a html

```<code><select>
  <option> Blah </option>
</select>
</code>```

combo box into something (probably a div) where selecting an item acts the same as clicking a link.

I guess you could probably use javascript to handle a selection event (my javascript knowledge is a little in disrepair at the moment) and 'switch' on the value of the combo box but this seems like more of a hack.

Your advice, experience and recommendations are appreciated.

答:
If you're going to have a lot of select boxes that you want to allow to use as redirects, without having to define them independently, try something similar to:

```<code>$("[id*='COMMON_NAME']").change(function() {
    document.location = this.value;
});
</code>```

And have your select boxes be named accordingly:

```<code><select id="COMMON_NAME_001">...</select>
<select id="COMMON_NAME_002">...</select>
</code>```

This creates a onchange event for all IDs containing "COMMON_NAME" to do a redirect of the <option> value.

OwnerDisplayName: Graphain

Title: Linking combo box (JQuery preferrably)

Body:
I am wondering if anyone has any experience using a JQuery plugin that converts a html

<select>
  <option> Blah </option>
</select>

combo box into something (probably a div) where selecting an item acts the same as clicking a link.

I guess you could probably use javascript to handle a selection event (my javascript knowledge is a little in disrepair at the moment) and 'switch' on the value of the combo box but this seems like more of a hack.

Your advice, experience and recommendations are appreciated.

Body:
If you're going to have a lot of select boxes that you want to allow to use as redirects, without having to define them independently, try something similar to:

$("[id*='COMMON_NAME']").change(function() {
    document.location = this.value;
});

And have your select boxes be named accordingly:

<select id="COMMON_NAME_001">...</select>
<select id="COMMON_NAME_002">...</select>

This creates a onchange event for all IDs containing "COMMON_NAME" to do a redirect of the <option> value.

OwnerDisplayName: Drew J


问:
unset all environment variables starting with a leading string while in a script (without closing or restarting bash)
I'd like to:

unset myvarname*

where myvarname is a string and * is... well, you got it.

Tried

env | grep string | unset

but doesn't work.

I'm into a script and I don't want to start a new shell so no env -i or source something or leaving the reentering the shell

Please help a poor noob

Thanks in advance

答:
If it's the bash shell, do:

```<code>unset $(compgen -v myvarname)
</code>```

For example, show all variables in my current environment beginning with the letter 'S':

```<code>unset $(compgen -v  S)
</code>```

Output:

```<code>SAL_USE_VCLPLUGIN
SCREEN_NO
SECONDS
SESSION
SESSIONTYPE
SHELL
SHELLOPTS
SHLVL
SSH_AUTH_SOCK
</code>```

If it's a POSIX shell, try something more generic:

```<code>unset $(env | sed -n 's/^\(S.*\)=.*/\1/p')
</code>```

Or if GNU grep is available:

```<code>unset $(env | grep -o '^S[^=]*')
</code>```

Body:
If it's the bash shell, do:

unset $(compgen -v myvarname)

For example, show all variables in my current environment beginning with the letter 'S':

unset $(compgen -v  S)

Output:

SAL_USE_VCLPLUGIN
SCREEN_NO
SECONDS
SESSION
SESSIONTYPE
SHELL
SHELLOPTS
SHLVL
SSH_AUTH_SOCK

If it's a POSIX shell, try something more generic:

unset $(env | sed -n 's/^\(S.*\)=.*/\1/p')

Or if GNU grep is available:

unset $(env | grep -o '^S[^=]*')


问:
Using Redirect in Spring Boot
Im having trouble using redirect functionality within my spring boot application. As shown in my code below im returning "redirect:/aucConfirm/" but when i initiate this i get a "This application has no explicit mapping" error.

```<code>@Controller
@RequestMapping("/")
public class WelcomeController {

    @Autowired
    AuctionItemRepository aucRepository;

// inject via application.properties
@Value("${welcome.message:test}")
private String message = "Hello World";

@RequestMapping(value = "/")
public String welcome(Map<String, Object> model) {
    model.put("message", this.message);
    return "welcome";
}

    @RequestMapping(value = "/sell", method = RequestMethod.GET)
    public String addAuction(Model model, HttpServletRequest request) {

        model.addAttribute("newAuction", new AuctionItem());

        return "NewAuction";
    }

    @RequestMapping(value = "/sell", method = RequestMethod.POST)
    public String saveAuction(@ModelAttribute AuctionItem newAuction, RedirectAttributes attributes){

        return "redirect:/aucConfirm";
    }

    @RequestMapping(value = "/aucConfirm", method = RequestMethod.GET)
    public String confirmNewAuction(Model model, HttpServletRequest request) {

        return "aucConfirm";
    }
}
</code>```

This is my current configuration class -

```<code>@SpringBootApplication
@ComponentScan
@EnableJpaRepositories("All")
@EntityScan("All")
public class AuctionWebApplication extends SpringBootServletInitializer  {

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
    return application.sources(AuctionWebApplication.class);
}

public static void main(String[] args) throws Exception {
    SpringApplication.run(AuctionWebApplication.class, args);
}

    @Bean
    DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/auctiondb?zeroDateTimeBehavior=convertToNull");
        dataSource.setUsername("root");
        dataSource.setPassword("toor");

        return dataSource;
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) {
        LocalContainerEntityManagerFactoryBean entityManager = new LocalContainerEntityManagerFactoryBean();
        entityManager.setDataSource(dataSource);
        entityManager.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
        entityManager.setPackagesToScan("All");

        Properties jpaProperties = new Properties();
        jpaProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
        jpaProperties.setProperty("hibernate.hbm2ddl.auto", "update");
        jpaProperties.setProperty("hibernate.id.new_generator_mappings", "false");
        entityManager.setJpaProperties(jpaProperties);

        return entityManager;
    }
</code>```

}

Update

Could it possibly have something to do with my jsp page that im trying to establish the recommit? I have a mvc form here -

```<code><mvc:form class="form-inline" action="${action}" method="post" modelAttribute="newAuction" id="addNewAuc">
</code>```

and when the user hits the next button it should hit the "redirect:/aucConfirm" -

```<code><button type="submit" name="submit" class="btn btn-success" form="addNewAuc">Next</button>
</code>```

Is there anything wrong with this code? Im running out of ideas at this point. Do i need to add anything to my spring boot configuration class to get it working? - Please help!

Update 2

http://localhost:8080/AuctionWebsite/sell

When i enter details int this form and select next i want it to redirect to-
http://localhost:8080/AuctionWebsite/aucConfirm

However this is what appears-

not redirecting at all and remaining with link http://localhost:8080/AuctionWebsite/sell

http://localhost:8080/AuctionWebsite/aucConfirm works when entered manually

Im getting a little bit desperate at this point, would really appreciate any help.

答:
Use this code

```<code>redirect:aucConfirm
</code>```

Instead of

```<code>redirect:/aucConfirm
</code>```

As per your updated question. it seems that

"This application has no explicit mapping" error

Is for /error url;

The actual error is

Validation failed for object 'auctionItem'

So problem is not with redirection , it is something else related to validation. You may find specific error on console log.

Title: Using Redirect in Spring Boot

Body:
Im having trouble using redirect functionality within my spring boot application. As shown in my code below im returning "redirect:/aucConfirm/" but when i initiate this i get a "This application has no explicit mapping" error.

@Controller
@RequestMapping("/")
public class WelcomeController {

    @Autowired
    AuctionItemRepository aucRepository;

// inject via application.properties
@Value("${welcome.message:test}")
private String message = "Hello World";

@RequestMapping(value = "/")
public String welcome(Map<String, Object> model) {
    model.put("message", this.message);
    return "welcome";
}

    @RequestMapping(value = "/sell", method = RequestMethod.GET)
    public String addAuction(Model model, HttpServletRequest request) {

        model.addAttribute("newAuction", new AuctionItem());

        return "NewAuction";
    }

    @RequestMapping(value = "/sell", method = RequestMethod.POST)
    public String saveAuction(@ModelAttribute AuctionItem newAuction, RedirectAttributes attributes){

        return "redirect:/aucConfirm";
    }

    @RequestMapping(value = "/aucConfirm", method = RequestMethod.GET)
    public String confirmNewAuction(Model model, HttpServletRequest request) {

        return "aucConfirm";
    }
}

This is my current configuration class -

@SpringBootApplication
@ComponentScan
@EnableJpaRepositories("All")
@EntityScan("All")
public class AuctionWebApplication extends SpringBootServletInitializer  {

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
    return application.sources(AuctionWebApplication.class);
}

public static void main(String[] args) throws Exception {
    SpringApplication.run(AuctionWebApplication.class, args);
}

    @Bean
    DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/auctiondb?zeroDateTimeBehavior=convertToNull");
        dataSource.setUsername("root");
        dataSource.setPassword("toor");

        return dataSource;
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) {
        LocalContainerEntityManagerFactoryBean entityManager = new LocalContainerEntityManagerFactoryBean();
        entityManager.setDataSource(dataSource);
        entityManager.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
        entityManager.setPackagesToScan("All");

        Properties jpaProperties = new Properties();
        jpaProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
        jpaProperties.setProperty("hibernate.hbm2ddl.auto", "update");
        jpaProperties.setProperty("hibernate.id.new_generator_mappings", "false");
        entityManager.setJpaProperties(jpaProperties);

        return entityManager;
    }

}

Update

Could it possibly have something to do with my jsp page that im trying to establish the recommit? I have a mvc form here -

<mvc:form class="form-inline" action="${action}" method="post" modelAttribute="newAuction" id="addNewAuc">

and when the user hits the next button it should hit the "redirect:/aucConfirm" -

<button type="submit" name="submit" class="btn btn-success" form="addNewAuc">Next</button>

Is there anything wrong with this code? Im running out of ideas at this point. Do i need to add anything to my spring boot configuration class to get it working? - Please help!

Update 2

http://localhost:8080/AuctionWebsite/sell

When i enter details int this form and select next i want it to redirect to-
http://localhost:8080/AuctionWebsite/aucConfirm

However this is what appears-

not redirecting at all and remaining with link http://localhost:8080/AuctionWebsite/sell

http://localhost:8080/AuctionWebsite/aucConfirm works when entered manually

Im getting a little bit desperate at this point, would really appreciate any help.

Body:
Use this code

redirect:aucConfirm

Instead of

redirect:/aucConfirm

As per your updated question. it seems that

"This application has no explicit mapping" error

Is for /error url;

The actual error is

Validation failed for object 'auctionItem'

So problem is not with redirection , it is something else related to validation. You may find specific error on console log.


问:
Determining the history of a built in MATLAB function between different versions?
Is there a complete list of changes made for each given built in function between versions and a record of a functions first incorporation into the MATLAB environment?

Essentially I am writing documents to accompany my work and I rely on some functions only available in newer versions (e.g. polarhistogram).

This is not a duplicate of previously asked questions as I am looking for changes listed for a specific function not MATLAB as a whole. It should be also noted that the suggested duplicates were asked 3 years ago, and as such a list could have been compiled subsequently.

Related topics:

How can I check since which Matlab version a function exists?

View Release Notes across multiple versions of MATLAB

答:
Unfortunately there is no comprehensive list of the functions that were introduced and the changes. The Release Notes for each new release are likely the best place to find that detailed information. The Online Release Notes site is actually fully searchable and filterable by release number as well as filtering for incompatibilities.

In general though, in order to determine when a function was introduced, you can look at the lower left hand corner of the online documentation and it will indicate the first release in which that function was available.

If you want to automate this, there is a FEX submission called when which will programmatically go and fetch this information.


问:
angularjs - passing objects between components
I am working on an AngularJS/Ui-router project. I have two states:

state1

state2 (a sub-state of state1)

States code:

```<code>app.config(function($stateProvider){
  $stateProvider.state('state1', {
    url : '/state1',
    component : 'state1cpt',
    resolve : {
      state1data : function(){
        return {'x':1, 'y':2, 'z':3};
      }
    }
  });
  $stateProvider.state('state1.state2', {
    url : '/state2',
    component : 'state2cpt'
  });
});
</code>```

Each state has a component:

```<code>app.component('state1cpt', {
  bindings : {
    state1data : '<'
  },
  templateUrl : 'state1.html'
});

app.component('state2cpt', {
   templateUrl : 'state2.html'
});
</code>```

And the views:

index.html

```<code><a ui-sref="state1">State1</a>
<ui-view></ui-view>
</code>```

state1.html

```<code><h2>State1 x: {{$ctrl.state1data.x}}</h2>
<a ui-sref="state1.state2">State2</a>
<ui-view></ui-view>
</code>```

state2.html

```<code><h2>State2</h2>
</code>```

How can I pass the state1data object to the state2? And what is the better way to do it? (In resolve of state2, or in controller of state2?)

A running plunker: http://plnkr.co/edit/HDt0f4wzjyUVQ7lEI9YB?p=preview

答:
I would use parameters in the url, after all you use the ui-router to have states defined by your url.

html

```<code><a ui-sref="state1({x:1,y:2,z:3})">State1</a>

<a ui-sref="state1.state2({x:3,y:4,z:3})">State2</a>
</code>```

js

```<code>app.config(function($stateProvider){
  $stateProvider.state('state1', {
    url : '/state1/{x:int}/{y:int}/{z:int}',
    component : 'state1cpt'
  });
  $stateProvider.state('state1.state2', {
    url : '/state2/{x:int}/{y:int}/{z:int}',
    component : 'state2cpt'
  });
});

app.component('state1cpt', {
  templateUrl : 'state1.html',
  controller: function($stateParams){
    this.x = $stateParams.x;
    this.y = $stateParams.y;
    this.z = $stateParams.z;
  }
});

app.component('state2cpt', {
  templateUrl : 'state2.html'
});
</code>```

plunker:
http://plnkr.co/edit/37e38xokN3bMrF64VZQ6?p=preview

Body:
I am working on an AngularJS/Ui-router project. I have two states:

state1

state2 (a sub-state of state1)

States code:

app.config(function($stateProvider){
  $stateProvider.state('state1', {
    url : '/state1',
    component : 'state1cpt',
    resolve : {
      state1data : function(){
        return {'x':1, 'y':2, 'z':3};
      }
    }
  });
  $stateProvider.state('state1.state2', {
    url : '/state2',
    component : 'state2cpt'
  });
});

Each state has a component:

app.component('state1cpt', {
  bindings : {
    state1data : '<'
  },
  templateUrl : 'state1.html'
});

app.component('state2cpt', {
   templateUrl : 'state2.html'
});

And the views:

index.html

State1
<ui-view></ui-view>

state1.html

State1 x: {{$ctrl.state1data.x}}

State2
<ui-view></ui-view>

state2.html

State2

How can I pass the state1data object to the state2? And what is the better way to do it? (In resolve of state2, or in controller of state2?)

A running plunker: http://plnkr.co/edit/HDt0f4wzjyUVQ7lEI9YB?p=preview

Body:
I would use parameters in the url, after all you use the ui-router to have states defined by your url.

html

<a ui-sref="state1({x:1,y:2,z:3})">State1</a>

<a ui-sref="state1.state2({x:3,y:4,z:3})">State2</a>

js

app.config(function($stateProvider){
  $stateProvider.state('state1', {
    url : '/state1/{x:int}/{y:int}/{z:int}',
    component : 'state1cpt'
  });
  $stateProvider.state('state1.state2', {
    url : '/state2/{x:int}/{y:int}/{z:int}',
    component : 'state2cpt'
  });
});

app.component('state1cpt', {
  templateUrl : 'state1.html',
  controller: function($stateParams){
    this.x = $stateParams.x;
    this.y = $stateParams.y;
    this.z = $stateParams.z;
  }
});

app.component('state2cpt', {
  templateUrl : 'state2.html'
});

plunker:
http://plnkr.co/edit/37e38xokN3bMrF64VZQ6?p=preview


问:
Integrate HornetQ in Websphere Application Server
I have been working on Websphere Application Server for a project, I want to integrate HornetQ in my Websphere Application Server.

The main objective is that I want to read/write messages from my java code running in WebSphere Application Server to the Queues that would be in HornetQ.

Please help in this regard, I was looking for support regarding this integration but couldn't find enough documentation regarding this.

How can I implement it ?

答:
I cannot give a full solution as the resources vary widely between systems and they can be very hard to find as well, but I can provide you pointers, find them below.

JMS between two different systems needs adapter or JCA configuration to be in place for it to work.

For consuming HornetQ, you need Hornet Q resource adapter deployed into Websphere. If HornetQ did not provide the resource adapter(usuall .rar file) for websphere then you are out of luck, you have to find a more generic resource adapter for Websphere and tweak it. (there is this site where you can download the code and build rar out of it here  )

After deploying the resource adapter, you need to configure the resource adapter, meaning you need to let the resource adapter know the url of the HornetQ, connection factories, connection Pool size etc.

Write the MDB for consuming the messages from the resource adapter.


问:
Angular2: Adding components dynamically
I am planning to add dynamic components at certain location in my Angular 2 app. I tried adding anchor points but it didn't work.</p>

答:
Use an anchor Point  in html

In ts file

```<code>constructor(private componentFactoryResolver: ComponentFactoryResolver,
    private viewContainerRef: ViewContainerRef) {}
</code>```

Create a component factory
Get the reference of the anchor point
Bind any data if required
Run detect changes for updating it

Title: Angular2: Adding components dynamically

Body:
Use an anchor Point  in html

In ts file

constructor(private componentFactoryResolver: ComponentFactoryResolver,
    private viewContainerRef: ViewContainerRef) {}

Create a component factory
Get the reference of the anchor point
Bind any data if required
Run detect changes for updating it


问:
Splitting values and assigning keys
I have a json array with long and lat values combined, and fields are empty. I am trying to figure out a python script to loop through the array and separate them into long and lat keys.

```<code>[
  {
    "Shape": "(47.630880207000075, -122.37391463199998)"
  },
  {
    "Shape": ""
  },
  {
    "Shape": "(47.70118823100006, -122.38447021399998)"
  }
]
</code>```

output desired:

```<code>[
  {
    "Long": "47.630880207000075",
    "Lat": "-122.37391463199998"

  },
  {
     "Long": "",
    "Lat": ""
  },
  {
   "Long": "47.70118823100006",
    "Lat": "-122.38447021399998"
  }
]
</code>```

So far I have converted the CSV into JSON and in the process of figuring out the regex to loop through it.. code so far:

import csv

```<code>import json

csvfile = open('geoloc.csv', 'r')
jsonfile = open('file.json', 'w')

# fieldnames = ("S")
reader = csv.DictReader( csvfile)
out = json.dumps( [ row for row in reader ], sort_keys=True, indent=4 )
jsonfile.write(out)
</code>```

答:
It's probably easy to use ast.literal_eval to turn this into a tuple vs. re, e.g.:

```<code>In [1]:
import ast
def tuple_convert(t):
    return ast.literal_eval(t) if t else ('', '')

keys = ['Long', 'Lat']
[dict(zip(keys, tuple_convert(d['Shape']))) for d in data]

Out[1]:
[{'Lat': -122.37391463199998, 'Long': 47.630880207000075},
 {'Lat': '', 'Long': ''},
 {'Lat': -122.38447021399998, 'Long': 47.70118823100006}]
</code>```

Title: Splitting values and assigning keys

Body:
I have a json array with long and lat values combined, and fields are empty. I am trying to figure out a python script to loop through the array and separate them into long and lat keys.

[
  {
    "Shape": "(47.630880207000075, -122.37391463199998)"
  },
  {
    "Shape": ""
  },
  {
    "Shape": "(47.70118823100006, -122.38447021399998)"
  }
]

output desired:

[
  {
    "Long": "47.630880207000075",
    "Lat": "-122.37391463199998"

  },
  {
     "Long": "",
    "Lat": ""
  },
  {
   "Long": "47.70118823100006",
    "Lat": "-122.38447021399998"
  }
]

So far I have converted the CSV into JSON and in the process of figuring out the regex to loop through it.. code so far:

import csv

import json

csvfile = open('geoloc.csv', 'r')
jsonfile = open('file.json', 'w')

# fieldnames = ("S")
reader = csv.DictReader( csvfile)
out = json.dumps( [ row for row in reader ], sort_keys=True, indent=4 )
jsonfile.write(out)

Body:
It's probably easy to use ast.literal_eval to turn this into a tuple vs. re, e.g.:

In [1]:
import ast
def tuple_convert(t):
    return ast.literal_eval(t) if t else ('', '')

keys = ['Long', 'Lat']
[dict(zip(keys, tuple_convert(d['Shape']))) for d in data]

Out[1]:
[{'Lat': -122.37391463199998, 'Long': 47.630880207000075},
 {'Lat': '', 'Long': ''},
 {'Lat': -122.38447021399998, 'Long': 47.70118823100006}]


问:
What causes WriteFile to return ERROR_ACCESS_DENIED?
We currently face the problem of a call to WriteFile (or, rather CFile::Write - but that just calls WriteFile internally) causing the Win32 error 5 ERROR_ACCESS_DENIED.

(EDIT: Note that we can't repro the behavior. All we have at the moment is a logfile indicating the source line where the CFile::Write was and containing as error ERROR_ACCESS_DENIED!)

(EDIT: The file is on a local drive and it is in fact a file and not a directory.)

Now, WriteFiles's documentation doesn't really help, and experimenting with a simple test-app yields the following results:

WriteFile will cause ERROR_ACCESS_DENIED if it is called for a file handle that is not opened for writing (i.e. is opened for reading only).

It will not cause ERROR_ACCESS_DENIED if

The handle is not valid or the file isn't open at all

The access rights, or the write protected flag for the file are modified after the file has been opened by the process. (If these are modified before the file is opened, then we never get to WriteFile because opening the file will fail.)

The file is somehow locked by another process/handle (This will at best result in error 32 ERROR_SHARING_VIOLATION).

That leaves us with the situation, that apparently the only possibility for this call to fail if the file was actually opened with the read flag instead of the write flag. However, looking at our code, this seems extremely unlikely. (Due to our tracing, we can be sure that WriteFile failed and  we can be sure that the error is ERROR_ACCESS_DENIED, we cannot be 100.1% sure of the opening flags, because these are not traced out.)

Are there any other known circumstances where WriteFile (CFile::Write) would cause an ERROR_ACCESS_DENIED?

Note: To additionally clarify the context of this question:

The file was open, therefore it can't be a directory or somesuch

All tests I performed indicate that while the file is open it cannot be deleted, so the file should still have been there on the call to WriteFile

The file is located on a local drive and not on a network drive.

I should add that we're running on WIndows XP sp3 and the app is compiled with Visual Studio 2005.

答:
if you can debug it, you should. it could be a million things:

msdn is wrong (it happens a lot)

some app (virus?) is hooking WriteFile and causing different behavior

filesystem problem?

something wrong in your logging, or observations


问:
Is it possible to get data of two files like so using then function using bluebird promise?
Is it possible to get data of two files like so using then function using bluebird promise?</p>

```<code>fs.readFileAsync('directory/file1.txt')
        .then(function(fileData1){
            return fs.readFileAsync('directory/file2.txt');
        })
        .then(function(fileData2){
            return console.log(fileData1+fileData2);
        })
</code>```

答:
You can just wrap the first fs.readFileAsync('directory/file1.txt') call in Bluebird.resolve to convert to Bluebird promises, but you won't have the result of the first file in the handler of your second 'then' function.

In your case you can do them both in parallel using Bluebird.all.

```<code>Bluebird.all([
  fs.readFileAsync('directory/file1.txt')
, fs.readFileAsync('directory/file2.txt')
])
  .spread(function(file1, file2) {
    console.log(file1 + file2);
  })
</code>```

If you use Bluebird.all remember that it takes an Array.

Body:
Is it possible to get data of two files like so using then function using bluebird promise?

fs.readFileAsync('directory/file1.txt')
        .then(function(fileData1){
            return fs.readFileAsync('directory/file2.txt');
        })
        .then(function(fileData2){
            return console.log(fileData1+fileData2);
        })

Body:
You can just wrap the first fs.readFileAsync('directory/file1.txt') call in Bluebird.resolve to convert to Bluebird promises, but you won't have the result of the first file in the handler of your second 'then' function.

In your case you can do them both in parallel using Bluebird.all.

Bluebird.all([
  fs.readFileAsync('directory/file1.txt')
, fs.readFileAsync('directory/file2.txt')
])
  .spread(function(file1, file2) {
    console.log(file1 + file2);
  })

If you use Bluebird.all remember that it takes an Array.


问:
TextInputLayout hint overlap issue
I'm using TextInputLayout from Android Design Library to show label on EditText.

The problem is when I start activity with that EditText hint (label) text overlaps the actual text (for a second) and only then returns to its own place (at the top of the EditText).

To illustrate this issue I recorded a short sample video: https://youtu.be/gy0CzcYggxU

Here is my activity.xml:

```<code><LinearLayout
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_margin="16dp"
  android:orientation="vertical">

<android.support.design.widget.TextInputLayout
    android:id="@+id/firstNameTextInputLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="8dp">

  <EditText
      android:id="@+id/firstNameEditText"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:hint="@string/first_name"
      android:inputType="textCapWords"
      android:textColor="@color/textPrimary"
      android:textColorHint="@color/textSecondary"
      android:textSize="16sp"
      android:theme="@style/CustomEditText"/>
</android.support.design.widget.TextInputLayout>

<android.support.design.widget.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="24dp">

  <EditText
      android:id="@+id/lastNameEditText"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:hint="@string/last_name"
      android:inputType="textCapWords"
      android:textColor="@color/textPrimary"
      android:textColorHint="@color/textSecondary"
      android:textSize="16sp"
      android:theme="@style/CustomEditText"/>
</android.support.design.widget.TextInputLayout>
</code>```

答:
The workaround that worked for me was to update activity like this:</p>

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    ...
    textInputLayout.setHintAnimationEnabled(false);
    textInput.setText("sample");
    textInputLayout.setHintAnimationEnabled(true);
    ...
}
</code>```

Title: TextInputLayout hint overlap issue

Body:
I'm using TextInputLayout from Android Design Library to show label on EditText.

The problem is when I start activity with that EditText hint (label) text overlaps the actual text (for a second) and only then returns to its own place (at the top of the EditText).

To illustrate this issue I recorded a short sample video: https://youtu.be/gy0CzcYggxU

Here is my activity.xml:

<LinearLayout
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_margin="16dp"
  android:orientation="vertical">

<android.support.design.widget.TextInputLayout
    android:id="@+id/firstNameTextInputLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="8dp">

  <EditText
      android:id="@+id/firstNameEditText"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:hint="@string/first_name"
      android:inputType="textCapWords"
      android:textColor="@color/textPrimary"
      android:textColorHint="@color/textSecondary"
      android:textSize="16sp"
      android:theme="@style/CustomEditText"/>
</android.support.design.widget.TextInputLayout>

<android.support.design.widget.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="24dp">

  <EditText
      android:id="@+id/lastNameEditText"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:hint="@string/last_name"
      android:inputType="textCapWords"
      android:textColor="@color/textPrimary"
      android:textColorHint="@color/textSecondary"
      android:textSize="16sp"
      android:theme="@style/CustomEditText"/>
</android.support.design.widget.TextInputLayout>

Body:
The workaround that worked for me was to update activity like this:

@Override
protected void onCreate(Bundle savedInstanceState) {
    ...
    textInputLayout.setHintAnimationEnabled(false);
    textInput.setText("sample");
    textInputLayout.setHintAnimationEnabled(true);
    ...
}