问:
WPF usercontrol Twoway binding Dependency Property
I created a Dependency Property in the usercontrol, but however changes in the usercontrol was NOT notified to the Viewmodel

Usercontrol

```<code><UserControl x:Class="DPsample.UserControl1"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         mc:Ignorable="d"
         d:DesignHeight="300" d:DesignWidth="300">
<Grid>
    <TextBox x:Name="txtName"></TextBox>
</Grid>
</code>```

UserControl.cs

```<code>/// <summary>
/// Interaction logic for UserControl1.xaml
/// </summary>
public partial class UserControl1 : UserControl
{
    public UserControl1()
    {
        InitializeComponent();
    }

    #region SampleProperty

    public static readonly DependencyProperty SamplePropertyProperty
                                            = DependencyProperty.Register("SampleProperty",
                                            typeof(string),
                                            typeof(UserControl1),
                                            new PropertyMetadata(OnSamplePropertyChanged));

    public string SampleProperty
    {
        get { return (string)GetValue(SamplePropertyProperty); }
        set { SetValue(SamplePropertyProperty, value); }
    }

    static void OnSamplePropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
    {
        (obj as UserControl1).OnSamplePropertyChanged(e);
    }
    private void OnSamplePropertyChanged(DependencyPropertyChangedEventArgs e)
    {
        string SamplePropertyNewValue = (string)e.NewValue;

        txtName.Text = SamplePropertyNewValue;
    }

    #endregion
}
</code>```

MainWindow

```<code><Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:DPsample" x:Class="DPsample.MainWindow"
    Title="MainWindow" Height="350" Width="525">
<Grid>

    <local:UserControl1 SampleProperty="{Binding SampleText,Mode=TwoWay}" HorizontalAlignment="Left" Margin="76,89,0,0" VerticalAlignment="Top" Width="99"/>
    <Button Content="Show" HorizontalAlignment="Left" Margin="76,125,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>

</Grid>
</code>```

MainWindow.cs

```<code> public MainWindow()
    {
        InitializeComponent();
        this.DataContext = new MainViewModel();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        var item = this.DataContext as MainViewModel;
        MessageBox.Show(item.SampleText.ToString());
    }
</code>```

MainViewModel.cs

```<code>public class MainViewModel : NotifyViewModelBase
{
    public MainViewModel()
    {
        this.SampleText = "test";
    }

    private string _sampleText;
    public string SampleText
    {
        get { return _sampleText; }
        set { _sampleText = value; OnPropertyChanged("SampleText"); }
    }
}
</code>```

答:
An alternative way to do this is an ElementName Binding. First assign the x:Name attribute to the UserControl (for example x:Name="MyUC"), then change the binding to:

```<code><TextBox Text="{Binding ElementName=MyUC, Path=SampleProperty}"/>
</code>```

Body:
I created a Dependency Property in the usercontrol, but however changes in the usercontrol was NOT notified to the Viewmodel

Usercontrol

<UserControl x:Class="DPsample.UserControl1"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         mc:Ignorable="d"
         d:DesignHeight="300" d:DesignWidth="300">
<Grid>
    <TextBox x:Name="txtName"></TextBox>
</Grid>

UserControl.cs

///
/// Interaction logic for UserControl1.xaml
///
public partial class UserControl1 : UserControl
{
    public UserControl1()
    {
        InitializeComponent();
    }

    #region SampleProperty

    public static readonly DependencyProperty SamplePropertyProperty
                                            = DependencyProperty.Register("SampleProperty",
                                            typeof(string),
                                            typeof(UserControl1),
                                            new PropertyMetadata(OnSamplePropertyChanged));

    public string SampleProperty
    {
        get { return (string)GetValue(SamplePropertyProperty); }
        set { SetValue(SamplePropertyProperty, value); }
    }

    static void OnSamplePropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
    {
        (obj as UserControl1).OnSamplePropertyChanged(e);
    }
    private void OnSamplePropertyChanged(DependencyPropertyChangedEventArgs e)
    {
        string SamplePropertyNewValue = (string)e.NewValue;

        txtName.Text = SamplePropertyNewValue;
    }

    #endregion
}

MainWindow

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:DPsample" x:Class="DPsample.MainWindow"
    Title="MainWindow" Height="350" Width="525">
<Grid>

    <local:UserControl1 SampleProperty="{Binding SampleText,Mode=TwoWay}" HorizontalAlignment="Left" Margin="76,89,0,0" VerticalAlignment="Top" Width="99"/>
    <Button Content="Show" HorizontalAlignment="Left" Margin="76,125,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>

</Grid>

MainWindow.cs

 public MainWindow()
    {
        InitializeComponent();
        this.DataContext = new MainViewModel();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        var item = this.DataContext as MainViewModel;
        MessageBox.Show(item.SampleText.ToString());
    }

MainViewModel.cs

public class MainViewModel : NotifyViewModelBase
{
    public MainViewModel()
    {
        this.SampleText = "test";
    }

    private string _sampleText;
    public string SampleText
    {
        get { return _sampleText; }
        set { _sampleText = value; OnPropertyChanged("SampleText"); }
    }
}

Body:
An alternative way to do this is an ElementName Binding. First assign the x:Name attribute to the UserControl (for example x:Name="MyUC"), then change the binding to:

<TextBox Text="{Binding ElementName=MyUC, Path=SampleProperty}"/>

ContentLicense: CC BY-SA 4.0


来源: stackexchange

问:
Issue with jQuery setting checkboxes as checked in IE6 (not showing as checked?)
The Code:

```<code>var lstInstanceIds = getData.lstInstanceIds.split(',');
    for(var i=0; i<lstInstanceIds.length; i++) {
        var value = lstInstanceIds[i];
        $('input[value=' + value + ']').attr('checked','checked');
    }
</code>```

So all i'm doing is looping a list and setting the attribute checked as checked where the values meet.

This works fine in Chrome, Firefox, IE7/8, Safari.
But not in IE6...

答: IETester is not an accurate representation of a true IE6 environment.  Mainly due to using the javascript engine that is in the local machine rather than the IE6 one.  I have come across many pages that work and look great in IE6 using IETester but fail horribly when brought up on a real IE6 on Windows XP environment.  My suggestion there is to get the free Virtual PC image of IE6 on WinXP SP3.  It is very useful in finding real errors using jQuery (though it is still a pain to debug).</p>

ContentLicense: CC BY-SA 2.5

Body:
The Code:

var lstInstanceIds = getData.lstInstanceIds.split(',');
    for(var i=0; i<lstInstanceIds.length; i++) {
        var value = lstInstanceIds[i];
        $('input[value=' + value + ']').attr('checked','checked');
    }

So all i'm doing is looping a list and setting the attribute checked as checked where the values meet.

This works fine in Chrome, Firefox, IE7/8, Safari.
But not in IE6...


问:
Why do you have to cast objects when calling particular methods of a subclass?
So, for example,

```<code>Person p = New Person()

Person z = New Adult()
</code>```

Let's say the Adult Class had it's own method called drive(), why couldn't I do:

z.drive()

I know this won't work, but what is the logic behind this not working? When you say: Person z = New Adult(), aren't you specifying it is an Adult instance?

答:
When you say: Person z = New Adult(), aren't you specifying it is an Adult instance?

You're creating an Adult object, but the declaration Person z says that the variable z is allowed to refer to any kind of person, not just an adult.  You could write z = new Child() on the very next line.

When you call a method on z, Java checks that it's valid for all objects that the variable could refer to.  It doesn't analyze the preceding code to try to figure out what specific type it actually does refer to, because in most cases that isn't possible.  (The variable could've been passed in as a method argument, for example, or it could've been set to either an Adult or Child based on an if statement.)  There may be specific cases where it's guaranteed that the variable will refer to a specific class, but the Java language doesn't treat those cases specially.  If the variable was declared with type Person, you can only call Person methods on it.

If you write Adult z = new Adult(), then you can call z.drive(), because the variable is guaranteed to refer only to adults, never children.

ContentLicense: CC BY-SA 3.0

Body:
So, for example,

Person p = New Person()

Person z = New Adult()

Let's say the Adult Class had it's own method called drive(), why couldn't I do:

z.drive()

I know this won't work, but what is the logic behind this not working? When you say: Person z = New Adult(), aren't you specifying it is an Adult instance?


问:
Bootstrap: centering content in Nav and changing default beavior on smaller screens
I have tried adding floats and using some Bootstrap classes to try and get it to work to no avail. Not sure what I'm missing. I would like to make the ul or all the items centered. Below is the nav markup:

http://jsfiddle.net/bdd9U/1489/

```<code><div class="container">
    <nav class="navbar navbar-default" role="navigation">
        <ul class="nav navbar-nav">
          <li><a href="#">Link</a></li>
          <li><a href="#">Link</a></li>
          <li><a href="#">Link</a></li>
          <li><a href="#">Link</a></li>
        </ul>
    </nav>
    <h1>Home</h1>
</div>
</code>```

Also, on smaller screens, the nav's default behavior is to stack on top of each other. I wanted to make it so that the active link is the only one shown (or maybe with another link), but it can be scrolled horizontally for the other links. I am planning on using Scrollspy so active links are updated automatically if that makes a difference. Not sure how to approach that - any ideas would be appreciated.

答:
Because the li elements are block-level (display :block is applied through Bootstrap's CSS), all you need to do is add text-align: center on the ul:

```<code>.navbar-nav {
  text-align: center;
}
</code>```

I've created an updated fiddle showcasing this here.

Not sure about the ScrollSpy effect, but I'd assume that you can simply pass through the collection of links as an argument into the parameters.

Hope this helps! :)

Body:
I have tried adding floats and using some Bootstrap classes to try and get it to work to no avail. Not sure what I'm missing. I would like to make the ul or all the items centered. Below is the nav markup:

http://jsfiddle.net/bdd9U/1489/

Link

Link

Link

Link

Home

Also, on smaller screens, the nav's default behavior is to stack on top of each other. I wanted to make it so that the active link is the only one shown (or maybe with another link), but it can be scrolled horizontally for the other links. I am planning on using Scrollspy so active links are updated automatically if that makes a difference. Not sure how to approach that - any ideas would be appreciated.

Body:
Because the li elements are block-level (display :block is applied through Bootstrap's CSS), all you need to do is add text-align: center on the ul:

.navbar-nav {
  text-align: center;
}

I've created an updated fiddle showcasing this here.

Not sure about the ScrollSpy effect, but I'd assume that you can simply pass through the collection of links as an argument into the parameters.

Hope this helps! :)


问:
avoiding nested for loops python
I have a function which takes in expressions and replaces the variables with all the permutations of the values that I am using as inputs. This is my code that I have tested and works, however after looking through SO, people have said that nested for loops are a bad idea however I am unsure as to how to make this more efficient. Could somebody help? Thanks. </p>

```<code>def replaceVar(expression):

    eval_list = list()

    a = [1, 8, 12, 13]
    b = [1, 2, 3, 4]
    c = [5, 9, 2, 7]

    for i in expression:
        first_eval = [i.replace("a", str(j)) for j in a]
        tmp = list()
        for k in first_eval:
            snd_eval = [k.replace("b", str(l)) for l in b]
            tmp2 = list()
            for m in snd_eval:
                trd_eval = [m.replace("c", str(n)) for n in c]
                tmp2.append(trd_eval)
            tmp.append(tmp2)
        eval_list.append(tmp)
    print(eval_list)
    return eval_list

print(replaceVar(['b-16+(c-(a+11))', 'a-(c-5)+a-b-10']))
</code>```

答:
here are some ideas:

as yours list a, b and c are hardcoded, harcode them as strings, therefore you don't have to cast every element to string at each step

use list comprehension, they are a little more faster than a normal for-loop with append

instead of .replace, use .format, it does all the replace for you in a single step

use itertools.product to combine a, b and c

with all that, I arrive to this

```<code>import itertools

def replaceVar(expression):

    a = ['1', '8', '12', '13' ]
    b = ['1', '2', '3', '4' ]
    c = ['5', '9', '2', '7' ]
    expression = [exp.replace('a','{0}').replace('b','{1}').replace('c','{2}')
                  for exp in expression] #prepare the expresion so they can be used with format

    return [ exp.format(*arg) for exp in expression  for arg in itertools.product(a,b,c) ]
</code>```

the speed gain is marginal, but is something, in my machine it goes from 148 milliseconds to 125

Functionality is the same to the version of R.Q.

Title: avoiding nested for loops python

Body:
I have a function which takes in expressions and replaces the variables with all the permutations of the values that I am using as inputs. This is my code that I have tested and works, however after looking through SO, people have said that nested for loops are a bad idea however I am unsure as to how to make this more efficient. Could somebody help? Thanks.

def replaceVar(expression):

    eval_list = list()

    a = [1, 8, 12, 13]
    b = [1, 2, 3, 4]
    c = [5, 9, 2, 7]

    for i in expression:
        first_eval = [i.replace("a", str(j)) for j in a]
        tmp = list()
        for k in first_eval:
            snd_eval = [k.replace("b", str(l)) for l in b]
            tmp2 = list()
            for m in snd_eval:
                trd_eval = [m.replace("c", str(n)) for n in c]
                tmp2.append(trd_eval)
            tmp.append(tmp2)
        eval_list.append(tmp)
    print(eval_list)
    return eval_list

print(replaceVar(['b-16+(c-(a+11))', 'a-(c-5)+a-b-10']))

Body:
here are some ideas:

as yours list a, b and c are hardcoded, harcode them as strings, therefore you don't have to cast every element to string at each step

use list comprehension, they are a little more faster than a normal for-loop with append

instead of .replace, use .format, it does all the replace for you in a single step

use itertools.product to combine a, b and c

with all that, I arrive to this

import itertools

def replaceVar(expression):

    a = ['1', '8', '12', '13' ]
    b = ['1', '2', '3', '4' ]
    c = ['5', '9', '2', '7' ]
    expression = [exp.replace('a','{0}').replace('b','{1}').replace('c','{2}')
                  for exp in expression] #prepare the expresion so they can be used with format

    return [ exp.format(*arg) for exp in expression  for arg in itertools.product(a,b,c) ]

the speed gain is marginal, but is something, in my machine it goes from 148 milliseconds to 125

Functionality is the same to the version of R.Q.


问:
limit std::vector for given min and max values
I've a std::vector of double values and I'm searching for a way to limit the sorted result to certain min and max values. Let me provide an example -

```<code>std::vector<double> v;
v.push_back(2.5);
v.push_back(3.5);
v.push_back(4.5);
v.push_back(5.5);
v.push_back(6.5);
</code>```

In above example, if I execute limit(v, 4.0, 7.0); it should provide me indexes eg [2] to [4] or end or whatever. I tried searching for <algorithm> header but couldn't find one :/ I can use additional library too if the need arises.

答:
You are looking for std::lower_bound and std::upper_bound:

```<code>auto it1 = std::lower_bound(v.begin(), v.end(), 4.0);
auto it2 = std::upper_bound(it1, v.end(), 7.0);

for (auto it = it1; it != it2; ++it)
    std::cout << *it << "\n";
</code>```

Body:
I've a std::vector of double values and I'm searching for a way to limit the sorted result to certain min and max values. Let me provide an example -

std::vector<double> v;
v.push_back(2.5);
v.push_back(3.5);
v.push_back(4.5);
v.push_back(5.5);
v.push_back(6.5);

In above example, if I execute limit(v, 4.0, 7.0); it should provide me indexes eg [2] to [4] or end or whatever. I tried searching for <algorithm> header but couldn't find one :/ I can use additional library too if the need arises.

Body:
You are looking for std::lower_bound and std::upper_bound:

auto it1 = std::lower_bound(v.begin(), v.end(), 4.0);
auto it2 = std::upper_bound(it1, v.end(), 7.0);

for (auto it = it1; it != it2; ++it)
    std::cout << *it << "\n";


问:
Testing state in S#arp Architecture - Best practice
How do I test for state in a S#arp Architecture project?

For example, I have a custom RoleProvider. I want to test the method provider.AddUsersToRoles(string[], string[]).

So I start with:

```<code>// Arrange
const string ficticiousRole = "Management";
var userToExpect = UserInstanceFactory.CreateValidTransientUser();
var roleToExpect = RoleInstanceFactory.CreateValidTransientRole();

userRepository.Expect(r => r.GetByUsername(userToExpect.Username))
              .Return(userToExpect);
roleRepository.Expect(r => r.GetByName(ficticiousRole))
              .Return(roleToExpect);

var userNames = new List<string>();
var roleNames = new List<string>();
userNames.Add(userToExpect.Username);
roleNames.Add(ficticiousRole);
</code>```

Then I add the user to a role. Then I check if the user is in this role.

```<code>// Act
roleProvider.AddUsersToRoles(userNames.ToArray(), roleNames.ToArray());
var isNewUserInRole = roleProvider.IsUserInRole(userToExpect.Username, ficticiousRole);

// Assert
Assert.IsTrue(isNewUserInRole);
</code>```

The problem is that I'm using Rhino Mocks. I have limited knowledge of Rhino Mocks, but from what I understand (according to Ayende Rahien) you use Rhino Mocks to test for operations, not state.

So I guess an in-memory SqlLite db would be more suitable? What's the best way to do this in S#arp Arch?

答: Without seeing the rest of your code, it would be difficult to answer this. </p>

Body:
How do I test for state in a S#arp Architecture project?

For example, I have a custom RoleProvider. I want to test the method provider.AddUsersToRoles(string[], string[]).

So I start with:

// Arrange
const string ficticiousRole = "Management";
var userToExpect = UserInstanceFactory.CreateValidTransientUser();
var roleToExpect = RoleInstanceFactory.CreateValidTransientRole();

userRepository.Expect(r => r.GetByUsername(userToExpect.Username))
              .Return(userToExpect);
roleRepository.Expect(r => r.GetByName(ficticiousRole))
              .Return(roleToExpect);

var userNames = new List<string>();
var roleNames = new List<string>();
userNames.Add(userToExpect.Username);
roleNames.Add(ficticiousRole);

Then I add the user to a role. Then I check if the user is in this role.

// Act
roleProvider.AddUsersToRoles(userNames.ToArray(), roleNames.ToArray());
var isNewUserInRole = roleProvider.IsUserInRole(userToExpect.Username, ficticiousRole);

// Assert
Assert.IsTrue(isNewUserInRole);

The problem is that I'm using Rhino Mocks. I have limited knowledge of Rhino Mocks, but from what I understand (according to Ayende Rahien) you use Rhino Mocks to test for operations, not state.

So I guess an in-memory SqlLite db would be more suitable? What's the best way to do this in S#arp Arch?


问:
How can two tabs communicate inside a browser?
How can prepare a communication channel to communicate between multiple opened tabs in same browser without any server side support?</p>

答: You can also leverage Web-Sockets to achieve real-time event based commincation across tab's and browsers. Libraries such as Socket.io make the entire process very straightforward.</p>


问:
Swift 3: Handle Errors in URLSession Delegates
I need to know how to catch errors (interruptions, primarily) in a URLsession with delegates.

I have the following Swift function within a custom class, which downloads a small file to test download speeds:

```<code>func testSpeed() {

    Globals.shared.dlStartTime = Date()
    Globals.shared.DownComplete = false

    let session = URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: nil)

    let task = session.downloadTask(with: url!)

    if Globals.shared.currentSSID == "" {
        Globals.shared.bandwidth = 0
        Globals.shared.DownComplete = true

        session.invalidateAndCancel()

        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "ProcessFinished"), object: nil, userInfo: nil)

    } else {
        print("Running Task")
        task.resume()

    }
}
</code>```

This class uses URLSessionDelegate and URLSessionDownloadDelegate. Here are the current delegates it calls:

```<code>public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
    Globals.shared.dlFileSize = (Double(totalBytesExpectedToWrite) * 8) / 1000
    let progress = (Double(totalBytesWritten) / Double(totalBytesExpectedToWrite)) * 100.0
    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "ProcessUpdating"), object: nil, userInfo: ["progress" : progress])
}
</code>```

^ That one monitors download progress and uses NotificationCenter to send the progress back to the view controller.

```<code>public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
    print("Done")
    if Globals.shared.DownComplete == false {
        let elapsed = Double( Date().timeIntervalSince(Globals.shared.dlStartTime))
        Globals.shared.bandwidth = Int(Globals.shared.dlFileSize / elapsed)
        Globals.shared.DownComplete = true
        Globals.shared.dataUse! += (Globals.shared.dlFileSize! / 8000)
    }
    session.invalidateAndCancel()

    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "ProcessFinished"), object: nil, userInfo: nil)
}
</code>```

^ That one just calculates the speed once the download is finished, and sends the result to a global variable in another class. Unimportant.

As of now, when I test my application, interrupting the download just hangs the app, because it keeps waiting for the processFinished NC call, which obviously never comes.

Is there another delegate I should add to catch that interruption, or am I missing something more obvious?

答: You can use urlSession:task:didCompleteWithError delegate method

Body:
I need to know how to catch errors (interruptions, primarily) in a URLsession with delegates.

I have the following Swift function within a custom class, which downloads a small file to test download speeds:

func testSpeed() {

    Globals.shared.dlStartTime = Date()
    Globals.shared.DownComplete = false

    let session = URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: nil)

    let task = session.downloadTask(with: url!)

    if Globals.shared.currentSSID == "" {
        Globals.shared.bandwidth = 0
        Globals.shared.DownComplete = true

        session.invalidateAndCancel()

        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "ProcessFinished"), object: nil, userInfo: nil)

    } else {
        print("Running Task")
        task.resume()

    }
}

This class uses URLSessionDelegate and URLSessionDownloadDelegate. Here are the current delegates it calls:

public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
    Globals.shared.dlFileSize = (Double(totalBytesExpectedToWrite) * 8) / 1000
    let progress = (Double(totalBytesWritten) / Double(totalBytesExpectedToWrite)) * 100.0
    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "ProcessUpdating"), object: nil, userInfo: ["progress" : progress])
}

^ That one monitors download progress and uses NotificationCenter to send the progress back to the view controller.

public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
    print("Done")
    if Globals.shared.DownComplete == false {
        let elapsed = Double( Date().timeIntervalSince(Globals.shared.dlStartTime))
        Globals.shared.bandwidth = Int(Globals.shared.dlFileSize / elapsed)
        Globals.shared.DownComplete = true
        Globals.shared.dataUse! += (Globals.shared.dlFileSize! / 8000)
    }
    session.invalidateAndCancel()

    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "ProcessFinished"), object: nil, userInfo: nil)
}

^ That one just calculates the speed once the download is finished, and sends the result to a global variable in another class. Unimportant.

As of now, when I test my application, interrupting the download just hangs the app, because it keeps waiting for the processFinished NC call, which obviously never comes.

Is there another delegate I should add to catch that interruption, or am I missing something more obvious?


问:
State Space and circuit simulator
As far as I know there is no state-space based general purpose circuit simulator around. Though there are certain algorithm to figure out how to find state-spaces (unique?) in a circuit (represented by graphs). Has anyone tried writing a program to simulate some basic circuit elements? </p>

<p>[ref] 1. Sheshu and Reed, Electrical networks and graph theory.
[ref] 2. H Narayanan, Submodular Functions and Electrical Networks ( http://www.ee.iitb.ac.in/~hn )</p>

答:
Old post..

Once you have derived the state-space representation of your electrical circuit, you can use any suitable ODE solver to run the time-domain simulation.

The harder part is the derivation of the state-space equations from a netlist via MNA or a tree approach.

See
ANALOG CIRCUIT SIMULATION BY STATE VARIABLE METHOD by Rodica VOICULESCU1 and Mihai IORDACHE

Title: State Space and circuit simulator

Body:
As far as I know there is no state-space based general purpose circuit simulator around. Though there are certain algorithm to figure out how to find state-spaces (unique?) in a circuit (represented by graphs). Has anyone tried writing a program to simulate some basic circuit elements?

[ref] 1. Sheshu and Reed, Electrical networks and graph theory.
[ref] 2. H Narayanan, Submodular Functions and Electrical Networks ( http://www.ee.iitb.ac.in/~hn )


问:
click function after postback
Hello I am working on a simple project using javascript, and I am trying to have a click event fired after the page posts back from the server, and I cant seem to figure out how to do it.  Here is my code below

```<code><asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
    <style type="text/css">
        .SignUp
        {
            padding-right: 450px;
            padding-left: 25px;
            margin-top: 100px;
        }
        .auto-style1
        {
            color: #FFFFFF;
        }
        .auto-style2
        {
            text-align: left;
        }
        .auto-style3
        {
            color: #FFFFFF;
            width: 158px;
        }
        .Message
        {
            margin-left: 100px;
            margin-top: 75px;
        }
        </style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <h1>Sign Up for an Account:</h1>
    <div class="SignUp">
        <table class="auto-style1">
            <tr>
                <td class="auto-style3">First Name</td>
                <td class="auto-style2">
                    <asp:TextBox ID="FirstName" Class="FirstName" runat="server" style="margin-left: 0px"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="Firstname" ErrorMessage="Please Enter First Name" ForeColor="Red">*</asp:RequiredFieldValidator>
                </td>
            </tr>
            <tr>
                <td class="auto-style3">Last Name</td>
                <td class="auto-style2">
                    <asp:TextBox ID="LastName" class="LastName" runat="server"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Please Enter Last Name" ForeColor="Red" ControlToValidate="LastName">*</asp:RequiredFieldValidator>
                </td>
            </tr>
            <tr>
                <td class="auto-style3">Password</td>
                <td class="auto-style2">
                    <asp:TextBox ID="Password" class="Password" runat="server" ></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="Please Create a Password" ForeColor="Red" ControlToValidate="Password">*</asp:RequiredFieldValidator>
                </td>
            </tr>
            <tr>
                <td class="auto-style3">Confirm Password</td>
                <td class="auto-style2">
                    <asp:TextBox ID="ConfirmPassword" class="ConfirmPassword" runat="server"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ErrorMessage="Please Confirm Password" ForeColor="Red" ControlToValidate="ConfirmPassword">*</asp:RequiredFieldValidator>
                    <asp:CompareValidator ID="CompareValidator2" runat="server" ControlToCompare="Password" ControlToValidate="ConfirmPassword" ErrorMessage="Passwords must Match" ForeColor="Red">*</asp:CompareValidator>
                </td>
            </tr>
            <tr>
                <td class="auto-style3">Email</td>
                <td class="auto-style2">
                    <asp:TextBox ID="Email" class="Email" runat="server"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ControlToValidate="Email" ErrorMessage="Please enter an Email" ForeColor="Red">*</asp:RequiredFieldValidator>
                     <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="Email" ErrorMessage="Please Enter a valid Email" ForeColor="Red" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">*</asp:RegularExpressionValidator>
                </td>
            </tr>
            <tr>
                <td class="auto-style3">ConfirmEmail</td>
                <td class="auto-style2">
                    <asp:TextBox ID="ConfirmEmail" class="ConfirmEmail" runat="server"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server" ControlToValidate="ConfirmEmail" ErrorMessage="Please confirm Email" ForeColor="Red">*</asp:RequiredFieldValidator>
                    <asp:CompareValidator ID="CompareValidator1" runat="server" ControlToCompare="Email" ControlToValidate="ConfirmEmail" ErrorMessage="Emails must Match" ForeColor="Red">*</asp:CompareValidator>
                </td>
            </tr>
        </table>
   </div>
    <br />

    <asp:Button ID="CreateAccount" Class="CreateAccount" runat="server" Text="Create Account" OnClick="SignUp_Click" />
    <br />
    <asp:Label  ID="Message" class="Message" runat="server" BackColor="Black" Font-Bold="True" Font-Size="30px" ForeColor="Red" Text="You have successfully created an Account" Height="30px" Visible="false"></asp:Label>
    <br />
    <br />
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:portfoliobrownConnectionString2 %>" SelectCommand="SELECT [id], [FirstName], [LastName], [Password], [ConfirmPassword], [ConfirmEmail], [Email] FROM [SignUP]"></asp:SqlDataSource>
    <br />
    <asp:ValidationSummary ID="ValidationSummary1" runat="server" ForeColor="Red" />
   <script type="text/javascript">
       $(".CreateAccount").click(function () {
           var first = document.getElementsByClassName("FirstName")
           var last = document.getElementsByClassName("LastName")
           var pass = document.getElementsByClassName("Password")
           var ConPass = document.getElementsByClassName("ConrirmPassword")
           var Email = document.getElementsByClassName("Email")
           var conEmail = document.getElementsByClassName("ConfirmEmail")
               if(first.length > 0 && last.length > 0 && pass.length > 0 && conPass.length > 0 &&
                   Email.length > 0 && conEnail.length > 0)
               {
                    alert("ehb");
               }

           });
</code>```

So basically I want the alert method to fire after the button is clicked on to create the account, but only when the page posts back from the server.

Thanks, any help would be appreciated

答:
You must check if input is empty or not. Give your input elements id tags like this:

```<code><input id="username" ...
<input id="password" ...
</code>```

Then check them logically in JS.

```<code><script>
    function button_onclick(){
         var name = document.getElementById('<%= username.ClientID %>').value;
         var passw = document.getElementById('<%= password.ClientID %>').value;
         if(name.length > 0 && passw.length > 0){
            alert("Fields are not empty!");
         }
    }
</script>
</code>```

Title: click function after postback

Body:
Hello I am working on a simple project using javascript, and I am trying to have a click event fired after the page posts back from the server, and I cant seem to figure out how to do it.  Here is my code below

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">

</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">

Sign Up for an Account:

                First Name

                    <asp:TextBox ID="FirstName" Class="FirstName" runat="server" style="margin-left: 0px"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="Firstname" ErrorMessage="Please Enter First Name" ForeColor="Red">*</asp:RequiredFieldValidator>

                Last Name

                    <asp:TextBox ID="LastName" class="LastName" runat="server"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Please Enter Last Name" ForeColor="Red" ControlToValidate="LastName">*</asp:RequiredFieldValidator>

                Password

                    <asp:TextBox ID="Password" class="Password" runat="server" ></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="Please Create a Password" ForeColor="Red" ControlToValidate="Password">*</asp:RequiredFieldValidator>

                Confirm Password

                    <asp:TextBox ID="ConfirmPassword" class="ConfirmPassword" runat="server"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ErrorMessage="Please Confirm Password" ForeColor="Red" ControlToValidate="ConfirmPassword">*</asp:RequiredFieldValidator>
                    <asp:CompareValidator ID="CompareValidator2" runat="server" ControlToCompare="Password" ControlToValidate="ConfirmPassword" ErrorMessage="Passwords must Match" ForeColor="Red">*</asp:CompareValidator>

                Email

                    <asp:TextBox ID="Email" class="Email" runat="server"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ControlToValidate="Email" ErrorMessage="Please enter an Email" ForeColor="Red">*</asp:RequiredFieldValidator>
                     <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="Email" ErrorMessage="Please Enter a valid Email" ForeColor="Red" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">*</asp:RegularExpressionValidator>

                ConfirmEmail

                    <asp:TextBox ID="ConfirmEmail" class="ConfirmEmail" runat="server"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server" ControlToValidate="ConfirmEmail" ErrorMessage="Please confirm Email" ForeColor="Red">*</asp:RequiredFieldValidator>
                    <asp:CompareValidator ID="CompareValidator1" runat="server" ControlToCompare="Email" ControlToValidate="ConfirmEmail" ErrorMessage="Emails must Match" ForeColor="Red">*</asp:CompareValidator>

    <asp:Button ID="CreateAccount" Class="CreateAccount" runat="server" Text="Create Account" OnClick="SignUp_Click" />

    <asp:Label  ID="Message" class="Message" runat="server" BackColor="Black" Font-Bold="True" Font-Size="30px" ForeColor="Red" Text="You have successfully created an Account" Height="30px" Visible="false"></asp:Label>

    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:portfoliobrownConnectionString2 %>" SelectCommand="SELECT [id], [FirstName], [LastName], [Password], [ConfirmPassword], [ConfirmEmail], [Email] FROM [SignUP]"></asp:SqlDataSource>

    <asp:ValidationSummary ID="ValidationSummary1" runat="server" ForeColor="Red" />

Body:
You must check if input is empty or not. Give your input elements id tags like this:

<input id="username" ...
<input id="password" ...

Then check them logically in JS.

<script>
    function button_onclick(){
         var name = document.getElementById('<%= username.ClientID %>').value;
         var passw = document.getElementById('<%= password.ClientID %>').value;
         if(name.length > 0 && passw.length > 0){
            alert("Fields are not empty!");
         }
    }
</script>


问:
MATLAB genetic algorithm constraint (all variables can't be zero at the same time in a binary environment)
I'm using MATLAB ga function for my optimization problem. In my problem, I have some decision variables which are integer (0 and 1: I specified lower bound, upper bound, and IntCon for it) plus two continues varibales. Otherwise, all integer variables can't be zero at same time, so at least, we need a single "one" variable among integers. How can I implement mentioned constraint in MATLAB?

答:
This is a Mixed-Integer optimization problem and it can be solved using ga in MATLAB. As mentioned in the documentations: ga can solve problems when certain variables are integer-valued. Not all the variables but certain variables. So you should have at least one real variable among the other integers.

Whit IntCon options, you can specify which variables are integer, for instance IntCon=[1 3] means that your first and third variables are integer. To avoid both integer variables to be 0 at the same time, I think you can add some inequality constraints.

For instance look at the following example:

Let's say we want to find the optimum value for the Ackley function with 5 variables (e.g. in 5 dimensions), [x(1)...x(5)] and let's assume that the first and third variables, x(1) and x(3), are integers. We can write the following script:

```<code>nVar = 5;
lb = -5*ones(1,nVar);   % define the upper bound
ub = 5*ones(1,nVar);    % define the lower bound
rng(1,'twister')        % for reproducibility
opts = optimoptions('ga','MaxStallGenerations',50,'FunctionTolerance',1e-3,'MaxGenerations',300);
[x,~,~] = ga(@ackleyfcn,nVar,[],[],[],[],lb,ub,[],[1 3],opts);
disp('solution:');disp(x)
</code>```

On my machine, I get this solution:

```<code>solution:
                   0  -0.000000278963321                   0   0.979067345808285  -0.000000280775000
</code>```

It can be seen that x(1) and x(3) are integers and both 0. Now let's say as you mentioned, they both cannot be 0 at the same time and if one is 0 the other should be 1. Here the boundaries of the Ackley's problem allows the variables to be in the range defined by lower and upper bounds. However, in your case the lower and upper bounds should be defined as [0] and [1] for both integer variables.

Now I want to avoid both variables to be 0, so I can write the following linear inequality constraint:

```<code>% x(1) + x(3) >= 1
% x(1) >= 0
% x(3) > 0
</code>```

These inequalities should be written in form Ax <= b:

```<code>A = [-1 0 -1 0 0
    -1 0 0 0 0
    0 0 -1 0 0];
b = [-1
    0
    0];
</code>```

Now if we run the optimization problem again we see the effect of the constraints on the output:

```<code>[x,~,~] = ga(@ackleyfcn,nVar,A,b,[],[],lb,ub,[],[1 3],opts);
disp('solution');disp(x)

solution
   1.000000000000000  -0.000005031565831                   0  -0.000011740569861   0.000008060759466
</code>```

Body:
This is a Mixed-Integer optimization problem and it can be solved using ga in MATLAB. As mentioned in the documentations: ga can solve problems when certain variables are integer-valued. Not all the variables but certain variables. So you should have at least one real variable among the other integers.

Whit IntCon options, you can specify which variables are integer, for instance IntCon=[1 3] means that your first and third variables are integer. To avoid both integer variables to be 0 at the same time, I think you can add some inequality constraints.

For instance look at the following example:

Let's say we want to find the optimum value for the Ackley function with 5 variables (e.g. in 5 dimensions), [x(1)...x(5)] and let's assume that the first and third variables, x(1) and x(3), are integers. We can write the following script:

nVar = 5;
lb = -5*ones(1,nVar);   % define the upper bound
ub = 5*ones(1,nVar);    % define the lower bound
rng(1,'twister')        % for reproducibility
opts = optimoptions('ga','MaxStallGenerations',50,'FunctionTolerance',1e-3,'MaxGenerations',300);
[x,~,~] = ga(@ackleyfcn,nVar,[],[],[],[],lb,ub,[],[1 3],opts);
disp('solution:');disp(x)

On my machine, I get this solution:

solution:
                   0  -0.000000278963321                   0   0.979067345808285  -0.000000280775000

It can be seen that x(1) and x(3) are integers and both 0. Now let's say as you mentioned, they both cannot be 0 at the same time and if one is 0 the other should be 1. Here the boundaries of the Ackley's problem allows the variables to be in the range defined by lower and upper bounds. However, in your case the lower and upper bounds should be defined as [0] and [1] for both integer variables.

Now I want to avoid both variables to be 0, so I can write the following linear inequality constraint:

% x(1) + x(3) >= 1
% x(1) >= 0
% x(3) > 0

These inequalities should be written in form Ax <= b:

A = [-1 0 -1 0 0
    -1 0 0 0 0
    0 0 -1 0 0];
b = [-1
    0
    0];

Now if we run the optimization problem again we see the effect of the constraints on the output:

[x,~,~] = ga(@ackleyfcn,nVar,A,b,[],[],lb,ub,[],[1 3],opts);
disp('solution');disp(x)

solution
   1.000000000000000  -0.000005031565831                   0  -0.000011740569861   0.000008060759466


问:
X11 problems when compiling openjdk 9 on centos 7
I find problems when I started to compile openjdk for my first time.

Below is what I did

hg clone http://hg.openjdk.java.net/jdk9/dev 9dev

cd 9dev

bash ./get_source.sh

bash ./configure

Then, I got this error message

configure: error: Could not find X11 libraries. You might be able to fix this by running 'sudo yum install libXtst-devel libXt-devel libXrender-devel libXi-devel'.

Then, I did what it told me to do.

After the installation, the same error still exists.

So I checked where the files lies on my machine

rpm -qa | grep X11

libX11-1.6.3-3.el7.x86_64
libX11-common-1.6.3-3.el7.noarch
libX11-devel-1.6.3-3.el7.x86_64

rpm -ql libX11-1.6.3-3.el7.x86_64

/usr/lib64/libX11-xcb.so.1
/usr/lib64/libX11-xcb.so.1.0.0
/usr/lib64/libX11.so.6
/usr/lib64/libX11.so.6.3.0

so i tried the way of specifying the X11 path

bash ./configure --x-libraries=/usr/lib64

Unfortunately, the same error still stays.

Can someone help me out of here, please?

thx

update

Thank @omajid for directing me to the log file config.log, where I found that the configure is using the gcc in my linuxbrew installation.

configure:56234: /data/alex/git/brew/bin/g++ -o conftest    conftest.cpp -lX11  >&5
  /data/alex/git/brew/bin/ld: cannot find -lX11
  collect2: error: ld returned 1 exit status
  configure:56234: $? = 1

So after I exported my c compiler to the system one, the problem was fixed.

export CC=/usr/bin/gcc
export CXX=/usr/bin/g++
```

答:
Here is the relevant packages needed at build time and the configure flags I use in my spec file for building unofficial OpenJDK 9 packages for Fedora/EPEL:

```<code>autoconf
automake
alsa-lib-devel
binutils
cups-devel
desktop-file-utils
fontconfig
freetype-devel
elfutils
giflib-devel
gcc-c++
gdb
gtk2-devel
lcms2-devel
libjpeg-devel
libpng-devel
libxslt
libX11-devel
libXi-devel
libXinerama-devel
libXt-devel
libXtst-devel
nss-devel
pkgconfig
xorg-x11-proto-devel
zip
java-1.8.0-openjdk-devel

bash ../configure \
--with-boot-jdk=/usr/lib/jvm/java-1.8.0-openjdk/ \
--with-native-debug-symbols=internal \
--enable-unlimited-crypto \
--with-zlib=system \
--with-libjpeg=system \
--with-giflib=system \
--with-libpng=system \
--with-lcms=system \
--with-stdc++lib=dynamic \
--disable-javac-server \
--disable-warnings-as-errors
</code>```

In any case, the error messages produce by configure are a best guess. You should take a look at config.log to see what test actually failed and what the error messages are. In this case, it looks like you are probably missing one of several X11 libraries. Possibly libXinerama-devel.

If this still doesn't fix your error, please paste the error messages from your autoconf log file (should be named config.log or configure.log, I forget).

Body:
Here is the relevant packages needed at build time and the configure flags I use in my spec file for building unofficial OpenJDK 9 packages for Fedora/EPEL:

autoconf
automake
alsa-lib-devel
binutils
cups-devel
desktop-file-utils
fontconfig
freetype-devel
elfutils
giflib-devel
gcc-c++
gdb
gtk2-devel
lcms2-devel
libjpeg-devel
libpng-devel
libxslt
libX11-devel
libXi-devel
libXinerama-devel
libXt-devel
libXtst-devel
nss-devel
pkgconfig
xorg-x11-proto-devel
zip
java-1.8.0-openjdk-devel

bash ../configure \
--with-boot-jdk=/usr/lib/jvm/java-1.8.0-openjdk/ \
--with-native-debug-symbols=internal \
--enable-unlimited-crypto \
--with-zlib=system \
--with-libjpeg=system \
--with-giflib=system \
--with-libpng=system \
--with-lcms=system \
--with-stdc++lib=dynamic \
--disable-javac-server \
--disable-warnings-as-errors

In any case, the error messages produce by configure are a best guess. You should take a look at config.log to see what test actually failed and what the error messages are. In this case, it looks like you are probably missing one of several X11 libraries. Possibly libXinerama-devel.

If this still doesn't fix your error, please paste the error messages from your autoconf log file (should be named config.log or configure.log, I forget).


问:
Trying to get an average using the contents of two files
So I have two files in my directory that contain a number in each of them. I want to make a script that calculates the average of these two numbers. How would I write it? Would this be correct?</p>

```<code>avg=$((${<file1.txt}-${<file2.txt})/2)
</code>```

答:
You'll want to use a command substitution:

```<code>avg=$(($(cat file1.txt)-$(cat file2.txt)/2))
</code>```

However, Bash is a pretty bad language for doing maths (at least unless it's completely integer maths). You might want to look into bc or a "real" language like Python.

Body:
So I have two files in my directory that contain a number in each of them. I want to make a script that calculates the average of these two numbers. How would I write it? Would this be correct?

avg=$((${<file1.txt}-${<file2.txt})/2)

Body:
You'll want to use a command substitution:

avg=$(($(cat file1.txt)-$(cat file2.txt)/2))

However, Bash is a pretty bad language for doing maths (at least unless it's completely integer maths). You might want to look into bc or a "real" language like Python.


问:
Button sound effect only works 28 times
I have set a gunshot sound to play every time I press a button (It is a fire button so it needs to be clicked many times).
When I run the program, the gunshot sound plays every time I press it, but after the 28th time the button is pressed, the sound is no longer played. However, the Toast I added still works. Any idea why this is?

activity_main.xml:

```<code> <Button
        android:id="@+id/fire"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="fire"
        android:onClick="fire"
        android:textSize="35sp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />
</code>```

Main.java:

```<code>package com.example.brans.zoombie;

import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class Main extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

public void fire(View v){
    MediaPlayer mp = MediaPlayer.create(Main.this, R.raw.pistol);
    mp.start();
    Toast.makeText(this, "shot fired", Toast.LENGTH_SHORT).show();
}
}
</code>```

After the 29th Time, the logcat says this.

```<code>04-02 16:07:56.371 23703-23717/com.example.brans.zoombie       V/MediaPlayer:message received msg=100, ext1=1, ext2=-19
04-02 16:07:56.371 23703-23717/com.example.brans.zoombie E/MediaPlayer: error (1, -19)
04-02 16:07:56.371 23703-23717/com.example.brans.zoombie V/MediaPlayer: callback application
04-02 16:07:56.371 23703-23717/com.example.brans.zoombie V/MediaPlayer: back from callback
</code>```

答: i think you should have to release the Media Player to release from the completed sound then reset it to play it another time. so it will no longer in the memory. </p>

Title: Button sound effect only works 28 times

Body:
I have set a gunshot sound to play every time I press a button (It is a fire button so it needs to be clicked many times).
When I run the program, the gunshot sound plays every time I press it, but after the 28th time the button is pressed, the sound is no longer played. However, the Toast I added still works. Any idea why this is?

activity_main.xml:

 <Button
        android:id="@+id/fire"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="fire"
        android:onClick="fire"
        android:textSize="35sp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

Main.java:

package com.example.brans.zoombie;

import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class Main extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

public void fire(View v){
    MediaPlayer mp = MediaPlayer.create(Main.this, R.raw.pistol);
    mp.start();
    Toast.makeText(this, "shot fired", Toast.LENGTH_SHORT).show();
}
}

After the 29th Time, the logcat says this.

04-02 16:07:56.371 23703-23717/com.example.brans.zoombie       V/MediaPlayer:message received msg=100, ext1=1, ext2=-19
04-02 16:07:56.371 23703-23717/com.example.brans.zoombie E/MediaPlayer: error (1, -19)
04-02 16:07:56.371 23703-23717/com.example.brans.zoombie V/MediaPlayer: callback application
04-02 16:07:56.371 23703-23717/com.example.brans.zoombie V/MediaPlayer: back from callback


问:
Getting the value and text from a datalist in jquery
I am trying to get the value in the #place input and keep it in that input but have the fax number go into the #fax input?  Is it possible to get both values and drop them into the respective locations.</p>

```<code>input type="text" id="place" list="places">
<datalist id="places">
    <option value="WVC">503-882-1212</option>
    <option value="HAM">612-883-1414</option>
    <option value="WON">317-445-8585</option>
</datalist>
<br>
<input type="text" id="fax">
</code>```

答:
There are two things you need to do to achieve this effect given the starting code you gave us. First, you need to capture any change to your input element by adding an event listener.

Second, using javascript you just need to select the correct option element from all of the ones present, and extract the fax number, which is the tags innerHTML.

```<code><input type="text" id="place" list="places">
<datalist id="places">
    <option value="WVC">503-882-1212</option>
    <option value="HAM">612-883-1414</option>
    <option value="WON">317-445-8585</option>
</datalist>
<br>
<input type="text" id="fax">
<script>
    document.querySelector('input').addEventListener('input', function () {
        var val = document.querySelector('input').value;
        faxNum = document.querySelectorAll('option[value="' + val + '"]')[0].innerHTML;
        document.querySelector('#fax').value = faxNum;
    });
</script>
</code>```

Body:
I am trying to get the value in the #place input and keep it in that input but have the fax number go into the #fax input?  Is it possible to get both values and drop them into the respective locations.

input type="text" id="place" list="places">
<datalist id="places">
    <option value="WVC">503-882-1212</option>
    <option value="HAM">612-883-1414</option>
    <option value="WON">317-445-8585</option>
</datalist>

<input type="text" id="fax">

Body:
There are two things you need to do to achieve this effect given the starting code you gave us. First, you need to capture any change to your input element by adding an event listener.

Second, using javascript you just need to select the correct option element from all of the ones present, and extract the fax number, which is the tags innerHTML.

<input type="text" id="place" list="places">
<datalist id="places">
    <option value="WVC">503-882-1212</option>
    <option value="HAM">612-883-1414</option>
    <option value="WON">317-445-8585</option>
</datalist>
<br>
<input type="text" id="fax">
<script>
    document.querySelector('input').addEventListener('input', function () {
        var val = document.querySelector('input').value;
        faxNum = document.querySelectorAll('option[value="' + val + '"]')[0].innerHTML;
        document.querySelector('#fax').value = faxNum;
    });
</script>


问:
Get YouTube channel name and link by using Oauth- JS
I was wondering if there was a way to get a user's Channel name and the link to the Channel, by through the JS Oauth from Google.

I don't really understand how that all works.

答:
No.

All you will get is

```<code>Array
  (
    [access_token] => ya29.Glv5AyS0dOSbwvb3beSkQrkNoiBBT******************
    [expires_in] => 3600
    [refresh_token] => 1/wg516U0JybrW0uw*****************
    [token_type] => Bearer
  )
</code>```

However, once you do have an access_token, you can make a call like this

```<code>https://www.googleapis.com/youtube/v3/channels?access_token=[access_token]&part=snippet&mine=true
</code>```

That should work for you.

Body:
No.

All you will get is

Array
  (
    [access_token] => ya29.Glv5AyS0dOSbwvb3beSkQrkNoiBBT******************
    [expires_in] => 3600
    [refresh_token] => 1/wg516U0JybrW0uw*****************
    [token_type] => Bearer
  )

However, once you do have an access_token, you can make a call like this

https://www.googleapis.com/youtube/v3/channels?access_token=[access_token]&part=snippet&mine=true

That should work for you.


问:
Conditional call to second async function, based on data collected before the first async function
I have some data in a array.

```<code>let data = ['firstData', 'secondData'];
</code>```

The first object (firstData) always exists, secondData could be null. So I always use that to call my async function like:

```<code>myAsyncFunction(data[0]).then(result => {
    //do something here
});
</code>```

If data[1] exists, I wanna call myAsyncFunction with data[1].

My current solution is with nested promises. Like this:

```<code>myAsyncFunction(data[0]).then(result => {
    return result;
}).then(result => {
    if(data[1] !== null){
        myAsyncFunction(data[1].then(resultTwo => {
        //dostuff with data
      });
    }
});
</code>```

I don't really like this solution, but it does work. It must be a better way tho. result is always a object. I tried Promise.all but it does not work. I think it's a problem with "race condition" of some sort (I am on thin ice here).

Is my current solution the only one?

Here is what myAsuncFunction looks like:

```<code>myAsyncFunction(personData){
    return new Promise<any> ((resolve, reject) => {

        //Assingen private variables

    secondAsyncFunction(somePersonData).then(result =>
     {

                    //Do some sync stuff

          return someNewData; //not a promise
     })
         .then(thirdAsyncFunction)
         .then(data => {
              resolve(data);
         })
         .catch(error => {
          reject(error);
     });
});
</code>```

答:
Given that data is known statically before the promise result, you don't need to put the condition inside the then callback - you can make the whole chaining conditional:

```<code>var promise = myAsyncFunction(data[0]);
if(data[1] !== null){
    promise.then(result =>
        myAsyncFunction(data[1])
    ).then(resultTwo => {
        //dostuff with data
    });
}
</code>```

In general, notice that nesting is not a bad thing, it is required when you want to branch control flow. Just don't forget to always return your promises from all (callback) functions.

Body:
I have some data in a array.

let data = ['firstData', 'secondData'];

The first object (firstData) always exists, secondData could be null. So I always use that to call my async function like:

myAsyncFunction(data[0]).then(result => {
    //do something here
});

If data[1] exists, I wanna call myAsyncFunction with data[1].

My current solution is with nested promises. Like this:

myAsyncFunction(data[0]).then(result => {
    return result;
}).then(result => {
    if(data[1] !== null){
        myAsyncFunction(data[1].then(resultTwo => {
        //dostuff with data
      });
    }
});

I don't really like this solution, but it does work. It must be a better way tho. result is always a object. I tried Promise.all but it does not work. I think it's a problem with "race condition" of some sort (I am on thin ice here).

Is my current solution the only one?

Here is what myAsuncFunction looks like:

myAsyncFunction(personData){
    return new Promise<any> ((resolve, reject) => {

        //Assingen private variables

    secondAsyncFunction(somePersonData).then(result =>
     {

                    //Do some sync stuff

          return someNewData; //not a promise
     })
         .then(thirdAsyncFunction)
         .then(data => {
              resolve(data);
         })
         .catch(error => {
          reject(error);
     });
});

Body:
Given that data is known statically before the promise result, you don't need to put the condition inside the then callback - you can make the whole chaining conditional:

var promise = myAsyncFunction(data[0]);
if(data[1] !== null){
    promise.then(result =>
        myAsyncFunction(data[1])
    ).then(resultTwo => {
        //dostuff with data
    });
}

In general, notice that nesting is not a bad thing, it is required when you want to branch control flow. Just don't forget to always return your promises from all (callback) functions.


问:
How to place 4 selectors in a row to fill exactly one col-sm-4 grid?
I'm using Bootstrap and making a simple form with col-sm-4 grid. Now it looks as:

Also when I resize browser width to 507px, C1 and C2 elements slide down to the next line:

And by some reason my dropdown lists look as plain HTML without any styles, despite I add class="selectpicker" to them. I expect them to be like:

I want to get something like this:

This is my fiddle: https://jsfiddle.net/j96vaokc/

What Bootstrap classes should I use?

Thank you in advance.

答:
You have a couple simple problems. First off, the selectpicker class is part of this Bootstrap jQuery plugin, bootstrap-select. You would have to download and include that script and stylesheet. Before that, you would also need to include the jQuery script.

Here's a working fiddle to demonstrate what it'll look like with your code and the included scripts. Go to the 'External Resources' tab on the left to see which scripts/stylesheets I included and in which order:

https://jsfiddle.net/j96vaokc/5/

I added

```<code>.dropdown-toggle {
  width:60px !important
}
</code>```

just to make the presentation neater on jsfiddle.

In regards to the wonky placement during window resize, that has a lot to do with your use of the bootstrap grid classes. In my fiddle you'll see that I removed alot of column classes since they weren't necessary. What I'm doing with the CSS is important because I have to override the default bootstrap-select styling for width in order to properly center. Also, in case you missed it I explicitly added a line break between the labels and select options.

Body:
You have a couple simple problems. First off, the selectpicker class is part of this Bootstrap jQuery plugin, bootstrap-select. You would have to download and include that script and stylesheet. Before that, you would also need to include the jQuery script.

Here's a working fiddle to demonstrate what it'll look like with your code and the included scripts. Go to the 'External Resources' tab on the left to see which scripts/stylesheets I included and in which order:

https://jsfiddle.net/j96vaokc/5/

I added

.dropdown-toggle {
  width:60px !important
}

just to make the presentation neater on jsfiddle.

In regards to the wonky placement during window resize, that has a lot to do with your use of the bootstrap grid classes. In my fiddle you'll see that I removed alot of column classes since they weren't necessary. What I'm doing with the CSS is important because I have to override the default bootstrap-select styling for width in order to properly center. Also, in case you missed it I explicitly added a line break between the labels and select options.


问:
Flatten nested JSON (Dict, List) into List to prepare to write into DB
I am still working on a problem to flatten a nested JSON file. The nested items are either List or Dict:

Here is the file I want to flatten (Unlike in my previous post, I kept it at good length, but it only contains input[0] not any subsequent items as it will be very long):

```<code>input = [{'states': ['USED'], 'niceName': '1-series', 'id': 'BMW_1_Series',
            'years': [{'styles':
                       [{'trim': '128i', 'states': ['USED'], 'submodel': {'body': 'Convertible', 'niceName': 'convertible', 'modelName': '1 Series Convertible'},
                         'name': '128i 2dr Convertible (3.0L 6cyl 6M)', 'id': 100994560},
                        {'trim': '128i', 'states': ['USED'], 'submodel': {'body': 'Coupe', 'niceName': 'coupe', 'modelName': '1 Series Coupe'},
                          'name': '128i 2dr Coupe (3.0L 6cyl 6M)', 'id': 100974974},
                        {'trim': '135i', 'states': ['USED'], 'submodel': {'body': 'Coupe', 'niceName': 'coupe', 'modelName': '1 Series Coupe'},
                         'name': '135i 2dr Coupe (3.0L 6cyl Turbo 6M)', 'id': 100974975},
                        {'trim': '135i', 'states': ['USED'], 'submodel': {'body': 'Convertible', 'niceName': 'convertible', 'modelName': '1 Series Convertible'},
                         'name': '135i 2dr Convertible (3.0L 6cyl Turbo 6M)', 'id': 100994561}
                        ],
                       'states': ['USED'], 'id': 100524709, 'year': 2008},
                      {'styles':
                       [{'trim': '135i', 'states': ['USED'], 'submodel': {'body': 'Coupe', 'niceName': 'coupe', 'modelName': '1 Series Coupe'},
                         'name': '135i 2dr Coupe (3.0L 6cyl Turbo 6M)', 'id': 101082656},
                        {'trim': '128i', 'states': ['USED'], 'submodel': {'body': 'Coupe', 'niceName': 'coupe', 'modelName': '1 Series Coupe'},
                         'name': '128i 2dr Coupe (3.0L 6cyl 6M)', 'id': 101082655},
                        {'trim': '135i', 'states': ['USED'], 'submodel': {'body': 'Convertible', 'niceName': 'convertible', 'modelName': '1 Series Convertible'},
                         'name': '135i 2dr Convertible (3.0L 6cyl Turbo 6M)', 'id': 101082663},
                        {'trim': '128i', 'states': ['USED'], 'submodel': {'body': 'Convertible', 'niceName': 'convertible', 'modelName': '1 Series Convertible'},
                         'name': '128i 2dr Convertible (3.0L 6cyl 6M)', 'id': 101082662}
                        ],
                       'states': ['USED'], 'id': 100503222, 'year': 2009},
                      {'styles':
                       [{'trim': '128i', 'states': ['USED'], 'submodel': {'body': 'Coupe', 'niceName': 'coupe', 'modelName': '1 Series Coupe'},
                         'name': '128i 2dr Coupe (3.0L 6cyl 6M)', 'id': 101200599},
                        {'trim': '135i', 'states': ['USED'], 'submodel': {'body': 'Coupe', 'niceName': 'coupe', 'modelName': '1 Series Coupe'},
                         'name': '135i 2dr Coupe (3.0L 6cyl Turbo 6M)', 'id': 101200600},
                        {'trim': '135i', 'states': ['USED'], 'submodel': {'body': 'Convertible', 'niceName': 'convertible', 'modelName': '1 Series Convertible'},
                         'name': '135i 2dr Convertible (3.0L 6cyl Turbo 6M)', 'id': 101200607},
                        {'trim': '128i', 'states': ['USED'], 'submodel': {'body': 'Convertible', 'niceName': 'convertible', 'modelName': '1 Series Convertible'},
                         'name': '128i 2dr Convertible (3.0L 6cyl 6M)', 'id': 101200601}
                        ],
                       'states': ['USED'], 'id': 100529091, 'year': 2010},
                      {'styles':
                       [{'trim': '128i', 'states': ['USED'], 'submodel': {'body': 'Coupe', 'niceName': 'coupe', 'modelName': '1 Series Coupe'},
                         'name': '128i 2dr Coupe (3.0L 6cyl 6M)', 'id': 101288165},
                        {'trim': '135i', 'states': ['USED'], 'submodel': {'body': 'Coupe', 'niceName': 'coupe', 'modelName': '1 Series Coupe'},
                         'name': '135i 2dr Coupe (3.0L 6cyl Turbo 6M)', 'id': 101288166},
                        {'trim': '135i', 'states': ['USED'], 'submodel': {'body': 'Convertible', 'niceName': 'convertible', 'modelName': '1 Series Convertible'},
                         'name': '135i 2dr Convertible (3.0L 6cyl Turbo 6M)', 'id': 101288298},
                        {'trim': '128i', 'states': ['USED'], 'submodel': {'body': 'Convertible', 'niceName': 'convertible', 'modelName': '1 Series Convertible'},
                         'name': '128i 2dr Convertible (3.0L 6cyl 6M)', 'id': 101288297}
                        ],
                       'states': ['USED'], 'id': 100531309, 'year': 2011},
                      {'styles':
                       [{'trim': '128i', 'states': ['USED'], 'submodel': {'body': 'Convertible', 'niceName': 'convertible', 'modelName': '1 Series Convertible'},
                         'name': '128i 2dr Convertible (3.0L 6cyl 6M)', 'id': 101381667},
                        {'trim': '135i', 'states': ['USED'], 'submodel': {'body': 'Convertible', 'niceName': 'convertible', 'modelName': '1 Series Convertible'},
                         'name': '135i 2dr Convertible (3.0L 6cyl Turbo 6M)', 'id': 101381668},
                        {'trim': '128i', 'states': ['USED'], 'submodel': {'body': 'Coupe', 'niceName': 'coupe', 'modelName': '1 Series Coupe'},
                         'name': '128i 2dr Coupe (3.0L 6cyl 6M)', 'id': 101381665},
                        {'trim': '135i', 'states': ['USED'], 'submodel': {'body': 'Coupe', 'niceName': 'coupe', 'modelName': '1 Series Coupe'},
                         'name': '135i 2dr Coupe (3.0L 6cyl Turbo 6M)', 'id': 101381666}
                        ],
                       'states': ['USED'], 'id': 100534729, 'year': 2012},
                      {'styles':
                       [{'trim': '128i', 'states': ['USED'], 'submodel': {'body': 'Coupe', 'niceName': 'coupe', 'modelName': '1 Series Coupe'},
                        'name': '128i 2dr Coupe (3.0L 6cyl 6M)', 'id': 200428722},
                        {'trim': '128i', 'states': ['USED'], 'submodel': {'body': 'Convertible', 'niceName': 'convertible', 'modelName': '1 Series Convertible'},
                         'name': '128i 2dr Convertible (3.0L 6cyl 6M)', 'id': 200428721},
                        {'trim': '135is', 'states': ['USED'], 'submodel': {'body': 'Coupe', 'niceName': 'coupe', 'modelName': '1 Series Coupe'},
                         'name': '135is 2dr Coupe (3.0L 6cyl Turbo 6M)', 'id': 200421701},
                        {'trim': '135i', 'states': ['USED'], 'submodel': {'body': 'Coupe', 'niceName': 'coupe', 'modelName': '1 Series Coupe'},
                         'name': '135i 2dr Coupe (3.0L 6cyl Turbo 6M)', 'id': 200428724},
                        {'trim': '135i', 'states': ['USED'], 'submodel': {'body': 'Convertible', 'niceName': 'convertible', 'modelName': '1 Series Convertible'},
                         'name': '135i 2dr Convertible (3.0L 6cyl Turbo 6M)', 'id': 200428723},
                        {'trim': '128i SULEV', 'states': ['USED'], 'submodel': {'body': 'Coupe', 'niceName': 'coupe', 'modelName': '1 Series Coupe'},
                         'name': '128i SULEV 2dr Coupe (3.0L 6cyl 6M)', 'id': 200428726},
                        {'trim': '128i SULEV', 'states': ['USED'], 'submodel': {'body': 'Convertible', 'niceName': 'convertible', 'modelName': '1 Series Convertible'},
                         'name': '128i SULEV 2dr Convertible (3.0L 6cyl 6M)', 'id': 200428725},
                        {'trim': '135is', 'states': ['USED'], 'submodel': {'body': 'Convertible', 'niceName': 'convertible', 'modelName': '1 Series Convertible'},
                         'name': '135is 2dr Convertible (3.0L 6cyl Turbo 6M)', 'id': 200428727}
                        ],
                       'states': ['USED'], 'id': 200421700, 'year': 2013}
                      ],
          'name': '1 Series', 'make': {'niceName': 'bmw', 'name': 'BMW', 'id': 200000081}
          }, #here is more to come, but I needed to crop it
          ]
</code>```

The code I used so far after failing with my aproach was written by @poke from: Flattening Generic JSON List of Dicts or Lists in Python

```<code>def splitObj (obj, prefix = None):
    '''
    Split the object, returning a 3-tuple with the flat object, optionally
    followed by the key for the subobjects and a list of those subobjects.
    '''
    # copy the object, optionally add the prefix before each key
    new = obj.copy() if prefix is None else { '{}_{}'.format(prefix, k): v for k, v in obj.items() }

    # try to find the key holding the subobject or a list of subobjects
    for k, v in new.items():
        # list of subobjects
        if isinstance(v, list):
            del new[k]
            return new, k, v
        # or just one subobject
        elif isinstance(v, dict):
            del new[k]
            return new, k, [v]
    return new, None, None

def flatten (data, prefix = None):
    '''
    Flatten the data, optionally with each key prefixed.
    '''
    # iterate all items
    for item in data:
        # split the object
        flat, key, subs = splitObj(item, prefix)

        # just return fully flat objects
        if key is None:
            yield flat
            continue

        # otherwise recursively flatten the subobjects
        for sub in flatten(subs, key):
            sub.update(flat)
            yield sub
</code>```

I receive the following error:

```<code>AttributeError: 'str' object has no attribute 'items'
</code>```

Which results from 'states': ['USED']

I do not know how to handle that. The key 'states' can be kept as a list.

I hope that somebody can help me out on that.

Ps: This is a follow up post from Python: Write Nested JSON as multiple elements in List

答:
Rethinking the problem

It is often easier to find a solution for a more general problem. So, let's look closer at the problem first.

The input is some JSON file describing a set of objects.

An object is recusively defined as either an atom (strings or numbers) or a dict with object values. Lists are used to represent alternatives (i.e. any element of the list can take the place of the list).
For example {a:[1,2]} means that a can be either 1 or 2.

The output should be a list of objects that do not contain any options. Additionally, the objects should be flattened, i.e. should be be dicts whose values are atoms and whose keys are describing the path to the value in the original object.

My solution handles alternatives and flattening separately.

Normalising

The function normalise below takes the input of json.dumps and yields a sequence of dicts. Note that the input and output of normalise have the same semantics and describe the same set of objects. The output is just normalised in the sense that it does contain alternatives only at the top level. Database people would call that denormalised because it is undesirable for relational databases.

normalise always returns a sequence of objects. normalise is implemented as generator to keep memory usage low.

The following cases are distinguished in normalise.

An atom input means there is only one possibility. So, the atom is yielded (this is like returning a list containing the atom).

A list means alternatives of alternatives. It yields all elements of its normalised input (this is like concatenating lists).

A dict means that we have to consider all combinations of alternatives for the individual keys. So, we return a cartesian product of the alternatives.

Here is the code:

```<code>import itertools

def normalise(x):
    if isinstance(x, dict):
        keys = x.keys()
        values = (normalise(i) for i in x.values())
        for i in itertools.product(*values):
            yield (dict(zip(keys, i)))
    elif isinstance(x, list):
        #if not x:           # uncomment for "LEFT JOIN" behaviour
        #    yield None
        for i in x:
            yield from normalise(i)
    else:
        yield x
</code>```

This code does not return an object if it contains any empty lists. This is because there is no possible value. This is like SQL "INNER JOIN". From Bert's answer it looks like he wants "LEFT JOIN" behaviour (i.e. some default value). To achieve that just uncomment the two lines.

Pseudo-flattening

The objects yielded by normalise still have the original (nested) dict structure. They could be flattened using code found in other discussions.

However, the OP wants to insert the objects in a database. So, he will most likely not need a list of keys of the flattened dictionary. He will only need a function returning the value for a given path.

This can be achieved by creating a wrapper object to the dict that has a __getitem__ method. This wrapper can also be used to return a default value for non-existing paths.

```<code>class DictWrapper:
    def __init__(self, d, sep='.'):
        self.d = d
        self.sep = sep

    def __getitem__(self, key):
        ret = self.d
        try:
            for k in key.split(self.sep):
                ret = ret[k]
            return ret
        except KeyError:
            return None
</code>```

The sql insert can than look like the following (tested with psycopg2)

```<code>for i in normalise(input):
    cur.execute('insert into mytable (year) VALUES (%(years.year)s)', DictWrapper(i))
</code>```

Implementation details

This implemenation clearly sacrifices some runtime performance for clarity.

Abstract base classes could be used instead of list and dict. However, this might be problematic because str is a sequence but should be treated as atom.

DictWrapper only works properly if sep is not contained in any of the dict keys.

normalise does not filter out duplicates. This could be done by using sets and named tuples instead of lists and dicts. However, this would imply that the whole result has to be in memory. It might be better to filter out duplicates at the database level.

To keep memory usage at a minimum the JSON should be read lazily.

Body:
I am still working on a problem to flatten a nested JSON file. The nested items are either List or Dict:

Here is the file I want to flatten (Unlike in my previous post, I kept it at good length, but it only contains input[0] not any subsequent items as it will be very long):

input = [{'states': ['USED'], 'niceName': '1-series', 'id': 'BMW_1_Series',
            'years': [{'styles':
                       [{'trim': '128i', 'states': ['USED'], 'submodel': {'body': 'Convertible', 'niceName': 'convertible', 'modelName': '1 Series Convertible'},
                         'name': '128i 2dr Convertible (3.0L 6cyl 6M)', 'id': 100994560},
                        {'trim': '128i', 'states': ['USED'], 'submodel': {'body': 'Coupe', 'niceName': 'coupe', 'modelName': '1 Series Coupe'},
                          'name': '128i 2dr Coupe (3.0L 6cyl 6M)', 'id': 100974974},
                        {'trim': '135i', 'states': ['USED'], 'submodel': {'body': 'Coupe', 'niceName': 'coupe', 'modelName': '1 Series Coupe'},
                         'name': '135i 2dr Coupe (3.0L 6cyl Turbo 6M)', 'id': 100974975},
                        {'trim': '135i', 'states': ['USED'], 'submodel': {'body': 'Convertible', 'niceName': 'convertible', 'modelName': '1 Series Convertible'},
                         'name': '135i 2dr Convertible (3.0L 6cyl Turbo 6M)', 'id': 100994561}
                        ],
                       'states': ['USED'], 'id': 100524709, 'year': 2008},
                      {'styles':
                       [{'trim': '135i', 'states': ['USED'], 'submodel': {'body': 'Coupe', 'niceName': 'coupe', 'modelName': '1 Series Coupe'},
                         'name': '135i 2dr Coupe (3.0L 6cyl Turbo 6M)', 'id': 101082656},
                        {'trim': '128i', 'states': ['USED'], 'submodel': {'body': 'Coupe', 'niceName': 'coupe', 'modelName': '1 Series Coupe'},
                         'name': '128i 2dr Coupe (3.0L 6cyl 6M)', 'id': 101082655},
                        {'trim': '135i', 'states': ['USED'], 'submodel': {'body': 'Convertible', 'niceName': 'convertible', 'modelName': '1 Series Convertible'},
                         'name': '135i 2dr Convertible (3.0L 6cyl Turbo 6M)', 'id': 101082663},
                        {'trim': '128i', 'states': ['USED'], 'submodel': {'body': 'Convertible', 'niceName': 'convertible', 'modelName': '1 Series Convertible'},
                         'name': '128i 2dr Convertible (3.0L 6cyl 6M)', 'id': 101082662}
                        ],
                       'states': ['USED'], 'id': 100503222, 'year': 2009},
                      {'styles':
                       [{'trim': '128i', 'states': ['USED'], 'submodel': {'body': 'Coupe', 'niceName': 'coupe', 'modelName': '1 Series Coupe'},
                         'name': '128i 2dr Coupe (3.0L 6cyl 6M)', 'id': 101200599},
                        {'trim': '135i', 'states': ['USED'], 'submodel': {'body': 'Coupe', 'niceName': 'coupe', 'modelName': '1 Series Coupe'},
                         'name': '135i 2dr Coupe (3.0L 6cyl Turbo 6M)', 'id': 101200600},
                        {'trim': '135i', 'states': ['USED'], 'submodel': {'body': 'Convertible', 'niceName': 'convertible', 'modelName': '1 Series Convertible'},
                         'name': '135i 2dr Convertible (3.0L 6cyl Turbo 6M)', 'id': 101200607},
                        {'trim': '128i', 'states': ['USED'], 'submodel': {'body': 'Convertible', 'niceName': 'convertible', 'modelName': '1 Series Convertible'},
                         'name': '128i 2dr Convertible (3.0L 6cyl 6M)', 'id': 101200601}
                        ],
                       'states': ['USED'], 'id': 100529091, 'year': 2010},
                      {'styles':
                       [{'trim': '128i', 'states': ['USED'], 'submodel': {'body': 'Coupe', 'niceName': 'coupe', 'modelName': '1 Series Coupe'},
                         'name': '128i 2dr Coupe (3.0L 6cyl 6M)', 'id': 101288165},
                        {'trim': '135i', 'states': ['USED'], 'submodel': {'body': 'Coupe', 'niceName': 'coupe', 'modelName': '1 Series Coupe'},
                         'name': '135i 2dr Coupe (3.0L 6cyl Turbo 6M)', 'id': 101288166},
                        {'trim': '135i', 'states': ['USED'], 'submodel': {'body': 'Convertible', 'niceName': 'convertible', 'modelName': '1 Series Convertible'},
                         'name': '135i 2dr Convertible (3.0L 6cyl Turbo 6M)', 'id': 101288298},
                        {'trim': '128i', 'states': ['USED'], 'submodel': {'body': 'Convertible', 'niceName': 'convertible', 'modelName': '1 Series Convertible'},
                         'name': '128i 2dr Convertible (3.0L 6cyl 6M)', 'id': 101288297}
                        ],
                       'states': ['USED'], 'id': 100531309, 'year': 2011},
                      {'styles':
                       [{'trim': '128i', 'states': ['USED'], 'submodel': {'body': 'Convertible', 'niceName': 'convertible', 'modelName': '1 Series Convertible'},
                         'name': '128i 2dr Convertible (3.0L 6cyl 6M)', 'id': 101381667},
                        {'trim': '135i', 'states': ['USED'], 'submodel': {'body': 'Convertible', 'niceName': 'convertible', 'modelName': '1 Series Convertible'},
                         'name': '135i 2dr Convertible (3.0L 6cyl Turbo 6M)', 'id': 101381668},
                        {'trim': '128i', 'states': ['USED'], 'submodel': {'body': 'Coupe', 'niceName': 'coupe', 'modelName': '1 Series Coupe'},
                         'name': '128i 2dr Coupe (3.0L 6cyl 6M)', 'id': 101381665},
                        {'trim': '135i', 'states': ['USED'], 'submodel': {'body': 'Coupe', 'niceName': 'coupe', 'modelName': '1 Series Coupe'},
                         'name': '135i 2dr Coupe (3.0L 6cyl Turbo 6M)', 'id': 101381666}
                        ],
                       'states': ['USED'], 'id': 100534729, 'year': 2012},
                      {'styles':
                       [{'trim': '128i', 'states': ['USED'], 'submodel': {'body': 'Coupe', 'niceName': 'coupe', 'modelName': '1 Series Coupe'},
                        'name': '128i 2dr Coupe (3.0L 6cyl 6M)', 'id': 200428722},
                        {'trim': '128i', 'states': ['USED'], 'submodel': {'body': 'Convertible', 'niceName': 'convertible', 'modelName': '1 Series Convertible'},
                         'name': '128i 2dr Convertible (3.0L 6cyl 6M)', 'id': 200428721},
                        {'trim': '135is', 'states': ['USED'], 'submodel': {'body': 'Coupe', 'niceName': 'coupe', 'modelName': '1 Series Coupe'},
                         'name': '135is 2dr Coupe (3.0L 6cyl Turbo 6M)', 'id': 200421701},
                        {'trim': '135i', 'states': ['USED'], 'submodel': {'body': 'Coupe', 'niceName': 'coupe', 'modelName': '1 Series Coupe'},
                         'name': '135i 2dr Coupe (3.0L 6cyl Turbo 6M)', 'id': 200428724},
                        {'trim': '135i', 'states': ['USED'], 'submodel': {'body': 'Convertible', 'niceName': 'convertible', 'modelName': '1 Series Convertible'},
                         'name': '135i 2dr Convertible (3.0L 6cyl Turbo 6M)', 'id': 200428723},
                        {'trim': '128i SULEV', 'states': ['USED'], 'submodel': {'body': 'Coupe', 'niceName': 'coupe', 'modelName': '1 Series Coupe'},
                         'name': '128i SULEV 2dr Coupe (3.0L 6cyl 6M)', 'id': 200428726},
                        {'trim': '128i SULEV', 'states': ['USED'], 'submodel': {'body': 'Convertible', 'niceName': 'convertible', 'modelName': '1 Series Convertible'},
                         'name': '128i SULEV 2dr Convertible (3.0L 6cyl 6M)', 'id': 200428725},
                        {'trim': '135is', 'states': ['USED'], 'submodel': {'body': 'Convertible', 'niceName': 'convertible', 'modelName': '1 Series Convertible'},
                         'name': '135is 2dr Convertible (3.0L 6cyl Turbo 6M)', 'id': 200428727}
                        ],
                       'states': ['USED'], 'id': 200421700, 'year': 2013}
                      ],
          'name': '1 Series', 'make': {'niceName': 'bmw', 'name': 'BMW', 'id': 200000081}
          }, #here is more to come, but I needed to crop it
          ]

The code I used so far after failing with my aproach was written by @poke from: Flattening Generic JSON List of Dicts or Lists in Python

def splitObj (obj, prefix = None):
    '''
    Split the object, returning a 3-tuple with the flat object, optionally
    followed by the key for the subobjects and a list of those subobjects.
    '''
    # copy the object, optionally add the prefix before each key
    new = obj.copy() if prefix is None else { '{}_{}'.format(prefix, k): v for k, v in obj.items() }

    # try to find the key holding the subobject or a list of subobjects
    for k, v in new.items():
        # list of subobjects
        if isinstance(v, list):
            del new[k]
            return new, k, v
        # or just one subobject
        elif isinstance(v, dict):
            del new[k]
            return new, k, [v]
    return new, None, None

def flatten (data, prefix = None):
    '''
    Flatten the data, optionally with each key prefixed.
    '''
    # iterate all items
    for item in data:
        # split the object
        flat, key, subs = splitObj(item, prefix)

        # just return fully flat objects
        if key is None:
            yield flat
            continue

        # otherwise recursively flatten the subobjects
        for sub in flatten(subs, key):
            sub.update(flat)
            yield sub

I receive the following error:

AttributeError: 'str' object has no attribute 'items'

Which results from 'states': ['USED']

I do not know how to handle that. The key 'states' can be kept as a list.

I hope that somebody can help me out on that.

Ps: This is a follow up post from Python: Write Nested JSON as multiple elements in List

Body:
Rethinking the problem

It is often easier to find a solution for a more general problem. So, let's look closer at the problem first.

The input is some JSON file describing a set of objects.

An object is recusively defined as either an atom (strings or numbers) or a dict with object values. Lists are used to represent alternatives (i.e. any element of the list can take the place of the list).
For example {a:[1,2]} means that a can be either 1 or 2.

The output should be a list of objects that do not contain any options. Additionally, the objects should be flattened, i.e. should be be dicts whose values are atoms and whose keys are describing the path to the value in the original object.

My solution handles alternatives and flattening separately.

Normalising

The function normalise below takes the input of json.dumps and yields a sequence of dicts. Note that the input and output of normalise have the same semantics and describe the same set of objects. The output is just normalised in the sense that it does contain alternatives only at the top level. Database people would call that denormalised because it is undesirable for relational databases.

normalise always returns a sequence of objects. normalise is implemented as generator to keep memory usage low.

The following cases are distinguished in normalise.

An atom input means there is only one possibility. So, the atom is yielded (this is like returning a list containing the atom).

A list means alternatives of alternatives. It yields all elements of its normalised input (this is like concatenating lists).

A dict means that we have to consider all combinations of alternatives for the individual keys. So, we return a cartesian product of the alternatives.

Here is the code:

import itertools

def normalise(x):
    if isinstance(x, dict):
        keys = x.keys()
        values = (normalise(i) for i in x.values())
        for i in itertools.product(*values):
            yield (dict(zip(keys, i)))
    elif isinstance(x, list):
        #if not x:           # uncomment for "LEFT JOIN" behaviour
        #    yield None
        for i in x:
            yield from normalise(i)
    else:
        yield x

This code does not return an object if it contains any empty lists. This is because there is no possible value. This is like SQL "INNER JOIN". From Bert's answer it looks like he wants "LEFT JOIN" behaviour (i.e. some default value). To achieve that just uncomment the two lines.

Pseudo-flattening

The objects yielded by normalise still have the original (nested) dict structure. They could be flattened using code found in other discussions.

However, the OP wants to insert the objects in a database. So, he will most likely not need a list of keys of the flattened dictionary. He will only need a function returning the value for a given path.

This can be achieved by creating a wrapper object to the dict that has a __getitem__ method. This wrapper can also be used to return a default value for non-existing paths.

class DictWrapper:
    def __init__(self, d, sep='.'):
        self.d = d
        self.sep = sep

    def __getitem__(self, key):
        ret = self.d
        try:
            for k in key.split(self.sep):
                ret = ret[k]
            return ret
        except KeyError:
            return None

The sql insert can than look like the following (tested with psycopg2)

for i in normalise(input):
    cur.execute('insert into mytable (year) VALUES (%(years.year)s)', DictWrapper(i))

Implementation details

This implemenation clearly sacrifices some runtime performance for clarity.

Abstract base classes could be used instead of list and dict. However, this might be problematic because str is a sequence but should be treated as atom.

DictWrapper only works properly if sep is not contained in any of the dict keys.

normalise does not filter out duplicates. This could be done by using sets and named tuples instead of lists and dicts. However, this would imply that the whole result has to be in memory. It might be better to filter out duplicates at the database level.

To keep memory usage at a minimum the JSON should be read lazily.


问:
How Do I Cancel and Restart a Timed Event in Swift?
I have a sliderValueChange function which updates a UILabel's text.  I want for it to have a time limit until it clears the label's text, but I also want this "timed clear" action to be cancelled & restarted or delayed whenever the UISlider is moved within the time limit before the "timed clear" action takes place.

So far this is what I have:

```<code>let task = DispatchWorkItem {
  consoleLabel.text = ""
}
func volumeSliderValueChange(sender: UISlider) {

  task.cancel()

  let senderValue = String(format: "%.2f", sender.value)
  consoleLabel.text = "Volume: \(senderValue)"

  DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 3, execute: task)
}
</code>```

Obviously, this approach does not work, since cancel() apparently cannot be reversed.. (or at least I don't know how).  I also don't know how to start a new task at the end of this function which will be cancelled if the function is recalled..

Am I going about this the wrong way?  Is there something I am overlooking to make this work?

答:
Use a timer:

```<code>weak var clearTimer: Timer?
</code>```

And:

```<code>override func viewDidLoad() {
  super.viewDidLoad()
  startClearTimer()
}

func startClearTimer() {
  clearTimer = Timer.scheduledTimer(
    timeInterval: 3.0,
    target: self,
    selector: #selector(clearLabel(_:)),
    userInfo: nil,
    repeats: false)
}

func clearLabel(_ timer: Timer) {
   label.text = ""
}

func volumeSliderValueChange(sender: UISlider) {
   clearTimer?.invalidate()  //Kill the timer
   //do whatever you need to do with the slider value
   startClearTimer()  //Start a new timer
}
</code>```

Body:
I have a sliderValueChange function which updates a UILabel's text.  I want for it to have a time limit until it clears the label's text, but I also want this "timed clear" action to be cancelled & restarted or delayed whenever the UISlider is moved within the time limit before the "timed clear" action takes place.

So far this is what I have:

let task = DispatchWorkItem {
  consoleLabel.text = ""
}
func volumeSliderValueChange(sender: UISlider) {

  task.cancel()

  let senderValue = String(format: "%.2f", sender.value)
  consoleLabel.text = "Volume: \(senderValue)"

  DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 3, execute: task)
}

Obviously, this approach does not work, since cancel() apparently cannot be reversed.. (or at least I don't know how).  I also don't know how to start a new task at the end of this function which will be cancelled if the function is recalled..

Am I going about this the wrong way?  Is there something I am overlooking to make this work?

Body:
Use a timer:

weak var clearTimer: Timer?

And:

override func viewDidLoad() {
  super.viewDidLoad()
  startClearTimer()
}

func startClearTimer() {
  clearTimer = Timer.scheduledTimer(
    timeInterval: 3.0,
    target: self,
    selector: #selector(clearLabel(_:)),
    userInfo: nil,
    repeats: false)
}

func clearLabel(_ timer: Timer) {
   label.text = ""
}

func volumeSliderValueChange(sender: UISlider) {
   clearTimer?.invalidate()  //Kill the timer
   //do whatever you need to do with the slider value
   startClearTimer()  //Start a new timer
}


问:
Does Resharper support RowTest?
Resharper doesn't recognise Rowtests, is this normal? Is there anyway to fix it? (other than splitting rowtest manually)

答:
Install Gallio www.gallio.org

it has a ReSharper plugin that lets you run NUnit/MbUnit row tests

OwnerDisplayName: Slough

Title: Does Resharper support RowTest?

OwnerDisplayName: Krzysztof Koźmic