问:
I am not able to return object (Node in BST)
I am trying to return parent node and self in Binary Search tree. I am getting this error "cannot unpack non-iterable NoneType object". Please help.

```<code>class Node:
    def __init__(self,data=None):
        self.data=data
        self.left=None
        self.right=None

    def insert(self,data):
        if data<self.data:
            if self.left==None:
                self.left=Node(data)
            else:
                self.left.insert(data)
        elif data>self.data:
            if self.right==None:
                self.right=Node(data)
            else:
                self.right.insert(data)
        else:

            return

    def printtree(self):

        if self.left:
            self.left.printtree()
        print(self.data)
        if self.right:
            self.right.printtree()

    def findval(self,data,parent=None):
        if self.data==data:
            return self,parent
        elif data<self.data:
            if self.left==None:
                return None,None
            else:
                parent=self
                self=self.left
                self.findval(data,parent)

        elif data > self.data:
            if self.right == None:
                return None,None
            else:
                parent = self
                self = self.right
                self.findval(data,parent)
        else:
            print("data not found")
            return None,None

    def deletenode(self,data):
        self,parent=self.findval(data)
        #Error found here
        print(self.data,parent.data)
        #Code of deletion

root=Node(10)
root.insert(5)
root.insert(15)
root.insert(3)
root.insert(7)
root.insert(13)
root.insert(16)

root.deletenode(5)
</code>```

Trying to return parent node and self in findval function
Error found = "TypeError: cannot unpack non-iterable NoneType object"
How can we return an Object in Python?

答:
The issue is you are missing a return on the recursive findval call, change the code to:

```<code>def findval(self, data, parent=None):
    if self.data == data:
        return self, parent

    elif data < self.data:
        if self.left is None:
            return None, None
        else:
            return self.left.findval(data, self)

    elif data > self.data:
        if self.right is None:
            return None, None
        else:
            return self.right.findval(data, self)

    else:
        print("data not found")
        return None, None
</code>```

Body:
I am trying to return parent node and self in Binary Search tree. I am getting this error "cannot unpack non-iterable NoneType object". Please help.

class Node:
    def __init__(self,data=None):
        self.data=data
        self.left=None
        self.right=None

    def insert(self,data):
        if data<self.data:
            if self.left==None:
                self.left=Node(data)
            else:
                self.left.insert(data)
        elif data>self.data:
            if self.right==None:
                self.right=Node(data)
            else:
                self.right.insert(data)
        else:

            return

    def printtree(self):

        if self.left:
            self.left.printtree()
        print(self.data)
        if self.right:
            self.right.printtree()

    def findval(self,data,parent=None):
        if self.data==data:
            return self,parent
        elif data<self.data:
            if self.left==None:
                return None,None
            else:
                parent=self
                self=self.left
                self.findval(data,parent)

        elif data > self.data:
            if self.right == None:
                return None,None
            else:
                parent = self
                self = self.right
                self.findval(data,parent)
        else:
            print("data not found")
            return None,None

    def deletenode(self,data):
        self,parent=self.findval(data)
        #Error found here
        print(self.data,parent.data)
        #Code of deletion

root=Node(10)
root.insert(5)
root.insert(15)
root.insert(3)
root.insert(7)
root.insert(13)
root.insert(16)

root.deletenode(5)

Trying to return parent node and self in findval function
Error found = "TypeError: cannot unpack non-iterable NoneType object"
How can we return an Object in Python?

Body:
The issue is you are missing a return on the recursive findval call, change the code to:

def findval(self, data, parent=None):
    if self.data == data:
        return self, parent

    elif data < self.data:
        if self.left is None:
            return None, None
        else:
            return self.left.findval(data, self)

    elif data > self.data:
        if self.right is None:
            return None, None
        else:
            return self.right.findval(data, self)

    else:
        print("data not found")
        return None, None


来源: stackexchange

问:
Can't update HAXM: "Install Intel x86 Emulator Accelerator (HAXM installer) (revision: 6.2.1)" failed
I am using Android Studio 2.3.3 on Windows 10. I tried to update the Intel Emulator Accelerator (HAXM) using the SDK Manager but it does not work, I get the following message:

```
To install:
- Intel x86 Emulator Accelerator (HAXM installer) (extras;intel;Hardware_Accelerated_Execution_Manager)
Preparing "Install Intel x86 Emulator Accelerator (HAXM installer) (revision: 6.2.1)".
Downloading https://dl.google.com/android/repository/extras/intel/haxm-windows_r6_2_1.zip
An error occurred while preparing SDK package Intel x86 Emulator Accelerator (HAXM installer): C:\Users\[...]\AppData\Local\Temp\PackageOperation01\android\repository\extras\intel\haxm-windows_r6_2_1.zip (Le chemin d’accès spécifié est introuvable)
"Install Intel x86 Emulator Accelerator (HAXM installer) (revision: 6.2.1)" failed.
Preparing "Install Intel x86 Emulator Accelerator (HAXM installer) (revision: 6.2.1)".
Downloading https://dl.google.com/android/repository/extras/intel/haxm-windows_r6_2_1.zip
An error occurred while preparing SDK package Intel x86 Emulator Accelerator (HAXM installer): C:\Users\[...]\AppData\Local\Temp\PackageOperation01\haxm-windows_r6_2_1.zip (Le chemin d’accès spécifié est introuvable).
"Install Intel x86 Emulator Accelerator (HAXM installer) (revision: 6.2.1)" failed.
Failed packages:
- Intel x86 Emulator Accelerator (HAXM installer) (extras;intel;Hardware_Accelerated_Execution_Manager)
```

I even manually downloaded the file https://dl.google.com/android/repository/extras/intel/haxm-windows_r6_2_1.zip then unzipped it and executed the file silent_install.bat as administrator. But Android Studio is still displaying 6.2.0 as the installed version. Is there a way to update HAXM?

答:
In order to successfully install or update HAXM on Windows 10 to run Android Emulator, you need to enable Intel VT-x.
To enable Intel VT-x, go to Windows BIOS to enable it.

This is not only for running the Android emulator. This problem is faced when running a virtual machine in your Windows as well.

ContentLicense: CC BY-SA 3.0

Body:
I am using Android Studio 2.3.3 on Windows 10. I tried to update the Intel Emulator Accelerator (HAXM) using the SDK Manager but it does not work, I get the following message:

To install:
- Intel x86 Emulator Accelerator (HAXM installer) (extras;intel;Hardware_Accelerated_Execution_Manager)
Preparing "Install Intel x86 Emulator Accelerator (HAXM installer) (revision: 6.2.1)".
Downloading https://dl.google.com/android/repository/extras/intel/haxm-windows_r6_2_1.zip
An error occurred while preparing SDK package Intel x86 Emulator Accelerator (HAXM installer): C:\Users\[...]\AppData\Local\Temp\PackageOperation01\android\repository\extras\intel\haxm-windows_r6_2_1.zip (Le chemin d’accès spécifié est introuvable)
"Install Intel x86 Emulator Accelerator (HAXM installer) (revision: 6.2.1)" failed.
Preparing "Install Intel x86 Emulator Accelerator (HAXM installer) (revision: 6.2.1)".
Downloading https://dl.google.com/android/repository/extras/intel/haxm-windows_r6_2_1.zip
An error occurred while preparing SDK package Intel x86 Emulator Accelerator (HAXM installer): C:\Users\[...]\AppData\Local\Temp\PackageOperation01\haxm-windows_r6_2_1.zip (Le chemin d’accès spécifié est introuvable).
"Install Intel x86 Emulator Accelerator (HAXM installer) (revision: 6.2.1)" failed.
Failed packages:
- Intel x86 Emulator Accelerator (HAXM installer) (extras;intel;Hardware_Accelerated_Execution_Manager)

I even manually downloaded the file https://dl.google.com/android/repository/extras/intel/haxm-windows_r6_2_1.zip then unzipped it and executed the file silent_install.bat as administrator. But Android Studio is still displaying 6.2.0 as the installed version. Is there a way to update HAXM?

ContentLicense: CC BY-SA 4.0


问:
hyperledger : error creating a Channel Configuration Transaction
I have been following this link : http://hyperledger-fabric.readthedocs.io/en/latest/build_network.html#troubleshoot for starting my first network, using byfn.sh file, and have executed all steps till

```<code>export CHANNEL_NAME=mychannel  && ../bin/configtxgen -profile TwoOrgsChannel -outputCreateChannelTx ./channel-artifacts/channel.tx -channelID $CHANNEL_NAME
</code>```

The error that I am getting is:

```<code>himani@himani-HP-Notebook:~/fabric-samples/first-network$ export CHANNEL_NAME=mychannelthis  && ../bin/configtxgen -profile TwoOrgsChannel -outputCreateChannelTx ./channel-artifacts/channel.tx -channelID $CHANNEL_NAME2018-06-07 11:42:00.552 IST [common/tools/configtxgen] main -> INFO 001 Loading configuration
2018-06-07 11:42:00.560 IST [common/tools/configtxgen] doOutputChannelCreateTx -> INFO 002 Generating new channel configtx
2018-06-07 11:42:00.560 IST [msp] getMspConfig -> INFO 003 Loading NodeOUs
2018-06-07 11:42:00.561 IST [msp] getMspConfig -> INFO 004 Loading NodeOUs
2018-06-07 11:42:00.579 IST [common/tools/configtxgen] main -> CRIT 005 Error on outputChannelCreateTx: config update generation failure: could not parse application to application group: setting up the MSP manager failed: the supplied identity is not valid: x509: certificate signed by unknown authority (possibly because of "x509: ECDSA verification failure" while trying to verify candidate authority certificate "ca.org1.example.com")
</code>```

I have tried variations of the command,

```<code>export CHANNEL_NAME=mychannelanother  && ../bin/configtxgen -profile TwoOrgsChannel -outputCreateChannelTx ./channel-artifacts/channel.tx -channelID $CHANNEL_NAME

export CHANNEL_NAME=mychannelanother  && ../bin/configtxgen -profile TwoOrgsChannel -outputCreateChannelTx ./channel-artifacts/channel.tx -channelID $mychannelanother

export CHANNEL_NAME=mychannel  && ../bin/configtxgen -profile TwoOrgsChannel -outputCreateChannelTx ./channel-artifacts/channel.tx -channelID $mychannel
</code>```

I even tried creating a channel without using byfn.sh file, but got a different error

```<code>himani@himani-HP-Notebook:~/fabric-samples/first-network$ peer channel create -o orderer.example.com:7050 -c mychannel -f ./channel-artifacts/channel.tx --tls --cafile /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem
No command 'peer' found, did you mean:
 Command 'pear' from package 'php-pear' (main)
 Command 'pee' from package 'moreutils' (universe)
 Command 'peet' from package 'pipexec' (universe)
 Command 'beer' from package 'gerstensaft' (universe)
peer: command not found
himani@himani-HP-Notebook:~/fabric-samples/first-network$ peer channel create -o orderer.example.com:7050 -c mychannelthis -f ./channel-artifacts/channel.tx --tls --cafile /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem
No command 'peer' found, did you mean:
 Command 'pear' from package 'php-pear' (main)
 Command 'pee' from package 'moreutils' (universe)
 Command 'beer' from package 'gerstensaft' (universe)
 Command 'peet' from package 'pipexec' (universe)
peer: command not found
</code>```

I modified the /home/himani/fabric-samples/first-network/crypto-config/ordererOrganizations/example.com/tlsca/tlsca.example.com-cert.pem doc by referring to this link : https://gerrit.hyperledger.org/r/#/c/18177/ , and executed the command again, but to no avail.

Are my certificates outdated? Where can I find the right ones? Is the issue something else?

UPDATE:
After referring to a solution provided to a similar problem, Hyperledger Fabric v1.1.0 byfn tutorial on Ubuntu 16.04, I brought down my network and tried to clean up artifacts but I couldn't execute those commands. Channel artifacts folder is empty.

I couldn't execute those commands

答:
I don't know if you have solved it or not, but there are some mistakes there.

```<code>himani@himani-HP-Notebook:~/fabric-samples/first-network$ export CHANNEL_NAME=mychannelthis  && ../bin/configtxgen -profile TwoOrgsChannel -outputCreateChannelTx ./channel-artifacts/channel.tx -channelID $CHANNEL_NAME2018-06-07 11:42:00.552 IST [common/tools/configtxgen] main -> INFO 001 Loading configuration
2018-06-07 11:42:00.560 IST [common/tools/configtxgen] doOutputChannelCreateTx -> INFO 002 Generating new channel configtx
2018-06-07 11:42:00.560 IST [msp] getMspConfig -> INFO 003 Loading NodeOUs
2018-06-07 11:42:00.561 IST [msp] getMspConfig -> INFO 004 Loading NodeOUs
2018-06-07 11:42:00.579 IST [common/tools/configtxgen] main -> CRIT 005 Error on outputChannelCreateTx: config update generation failure: could not parse application to application group: setting up the MSP manager failed: the supplied identity is not valid: x509: certificate signed by unknown authority (possibly because of "x509: ECDSA verification failure" while trying to verify candidate authority certificate "ca.org1.example.com")
</code>```

if you are following the tutorial, CHANNEL_NAME should be mychannel.

for the 3rd variations, it should be like this

```<code>export CHANNEL_NAME=mychannel  && ../bin/configtxgen -profile TwoOrgsChannel -outputCreateChannelTx ./channel-artifacts/channel.tx -channelID $CHANNEL_NAME
</code>```

for creating channel, peer channel create can only be send inside docker container.
If you are sending directly from command line, try this

```<code>docker exec -it yourCliContainerName peer channel create -o orderer.example.com:7050 -c mychannelthis -f ./channel-artifacts/channel.tx --tls --cafile /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem
</code>```

but remember to start the container first.

hope this helps

Body:
I have been following this link : http://hyperledger-fabric.readthedocs.io/en/latest/build_network.html#troubleshoot for starting my first network, using byfn.sh file, and have executed all steps till

export CHANNEL_NAME=mychannel  && ../bin/configtxgen -profile TwoOrgsChannel -outputCreateChannelTx ./channel-artifacts/channel.tx -channelID $CHANNEL_NAME

The error that I am getting is:

himani@himani-HP-Notebook:~/fabric-samples/first-network$ export CHANNEL_NAME=mychannelthis  && ../bin/configtxgen -profile TwoOrgsChannel -outputCreateChannelTx ./channel-artifacts/channel.tx -channelID $CHANNEL_NAME2018-06-07 11:42:00.552 IST [common/tools/configtxgen] main -> INFO 001 Loading configuration
2018-06-07 11:42:00.560 IST [common/tools/configtxgen] doOutputChannelCreateTx -> INFO 002 Generating new channel configtx
2018-06-07 11:42:00.560 IST [msp] getMspConfig -> INFO 003 Loading NodeOUs
2018-06-07 11:42:00.561 IST [msp] getMspConfig -> INFO 004 Loading NodeOUs
2018-06-07 11:42:00.579 IST [common/tools/configtxgen] main -> CRIT 005 Error on outputChannelCreateTx: config update generation failure: could not parse application to application group: setting up the MSP manager failed: the supplied identity is not valid: x509: certificate signed by unknown authority (possibly because of "x509: ECDSA verification failure" while trying to verify candidate authority certificate "ca.org1.example.com")

I have tried variations of the command,

export CHANNEL_NAME=mychannelanother  && ../bin/configtxgen -profile TwoOrgsChannel -outputCreateChannelTx ./channel-artifacts/channel.tx -channelID $CHANNEL_NAME

export CHANNEL_NAME=mychannelanother  && ../bin/configtxgen -profile TwoOrgsChannel -outputCreateChannelTx ./channel-artifacts/channel.tx -channelID $mychannelanother

export CHANNEL_NAME=mychannel  && ../bin/configtxgen -profile TwoOrgsChannel -outputCreateChannelTx ./channel-artifacts/channel.tx -channelID $mychannel

I even tried creating a channel without using byfn.sh file, but got a different error

himani@himani-HP-Notebook:~/fabric-samples/first-network$ peer channel create -o orderer.example.com:7050 -c mychannel -f ./channel-artifacts/channel.tx --tls --cafile /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem
No command 'peer' found, did you mean:
 Command 'pear' from package 'php-pear' (main)
 Command 'pee' from package 'moreutils' (universe)
 Command 'peet' from package 'pipexec' (universe)
 Command 'beer' from package 'gerstensaft' (universe)
peer: command not found
himani@himani-HP-Notebook:~/fabric-samples/first-network$ peer channel create -o orderer.example.com:7050 -c mychannelthis -f ./channel-artifacts/channel.tx --tls --cafile /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem
No command 'peer' found, did you mean:
 Command 'pear' from package 'php-pear' (main)
 Command 'pee' from package 'moreutils' (universe)
 Command 'beer' from package 'gerstensaft' (universe)
 Command 'peet' from package 'pipexec' (universe)
peer: command not found

I modified the /home/himani/fabric-samples/first-network/crypto-config/ordererOrganizations/example.com/tlsca/tlsca.example.com-cert.pem doc by referring to this link : https://gerrit.hyperledger.org/r/#/c/18177/ , and executed the command again, but to no avail.

Are my certificates outdated? Where can I find the right ones? Is the issue something else?

UPDATE:
After referring to a solution provided to a similar problem, Hyperledger Fabric v1.1.0 byfn tutorial on Ubuntu 16.04, I brought down my network and tried to clean up artifacts but I couldn't execute those commands. Channel artifacts folder is empty.

I couldn't execute those commands

Body:
I don't know if you have solved it or not, but there are some mistakes there.

himani@himani-HP-Notebook:~/fabric-samples/first-network$ export CHANNEL_NAME=mychannelthis  && ../bin/configtxgen -profile TwoOrgsChannel -outputCreateChannelTx ./channel-artifacts/channel.tx -channelID $CHANNEL_NAME2018-06-07 11:42:00.552 IST [common/tools/configtxgen] main -> INFO 001 Loading configuration
2018-06-07 11:42:00.560 IST [common/tools/configtxgen] doOutputChannelCreateTx -> INFO 002 Generating new channel configtx
2018-06-07 11:42:00.560 IST [msp] getMspConfig -> INFO 003 Loading NodeOUs
2018-06-07 11:42:00.561 IST [msp] getMspConfig -> INFO 004 Loading NodeOUs
2018-06-07 11:42:00.579 IST [common/tools/configtxgen] main -> CRIT 005 Error on outputChannelCreateTx: config update generation failure: could not parse application to application group: setting up the MSP manager failed: the supplied identity is not valid: x509: certificate signed by unknown authority (possibly because of "x509: ECDSA verification failure" while trying to verify candidate authority certificate "ca.org1.example.com")

if you are following the tutorial, CHANNEL_NAME should be mychannel.

for the 3rd variations, it should be like this

export CHANNEL_NAME=mychannel  && ../bin/configtxgen -profile TwoOrgsChannel -outputCreateChannelTx ./channel-artifacts/channel.tx -channelID $CHANNEL_NAME

for creating channel, peer channel create can only be send inside docker container.
If you are sending directly from command line, try this

docker exec -it yourCliContainerName peer channel create -o orderer.example.com:7050 -c mychannelthis -f ./channel-artifacts/channel.tx --tls --cafile /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem

but remember to start the container first.

hope this helps


问:
WPF Noob Seeking Guidance
So, most of the time I live in ASP.NET MVC Land - however, right now I'm trying to make some analysis tools for our solution using WPF (aka, it would count lines of code, which files have tests, extracting meta data from attributes, etc). Everything is mostly going well (the reflection code I have works fine). What I'm having trouble with is the WPF ItemsControl. Compared to a tradition <asp:Repeater />, ItemsControl is completely boggling me.

My XAML:

```<code><ItemsControl x:Name="repeaterRecentProjects">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Border Background="#094563" Margin="5" Padding="3">
                <DockPanel>
                    <Image Source="/Content/Black-Internal-icon.png" Height="16" Width="16"></Image>
                    <TextBlock Margin="5,0" Text="{Binding}"></TextBlock>
                </DockPanel>
            </Border>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
    <ItemsPanelTemplate>
        <StackPanel Orientation="Vertical"></StackPanel>
    </ItemsPanelTemplate>
</ItemsControl>
</code>```

The idea is that the DataTemplate contains my template, as I understand it. Then, in code I can do something like this (EDIT: Full code behind of the page):

```<code>public partial class HomeScreen : Page
{
    protected bool _isProjectChosen = false;

    public HomeScreen()
    {
        InitializeComponent();
    }

    protected ObservableCollection<string> someFiles = new ObservableCollection<string>();

    protected override void OnInitialized(EventArgs e)
    {
        base.OnInitialized(e);

        someFiles.Add("SomeFile.aspx");
        someFiles.Add("SomeFile2.aspx");
        someFiles.Add("SomeFile3.aspx");

        repeaterRecentProjects.ItemsSource = someFiles;
    }

    private void buttonSelectProject_Click(object sender, RoutedEventArgs e)
    {
        OpenFileDialog dialogSelectProject = new OpenFileDialog();

        dialogSelectProject.DefaultExt = ".sln";
        dialogSelectProject.Filter = "Visual Studio Solution (.sln)|*.sln";

        if (dialogSelectProject.ShowDialog() == true)
        {
            textBlockProjectName.Text = dialogSelectProject.FileName;
            _isProjectChosen = true;
            buttonAnalyzeProject.IsEnabled = true;
        }

        someFiles.Add("AnotherString.aspx");
    }

    private void buttonAnalyzeProject_Click(object sender, RoutedEventArgs e)
    {
        MessageBox.Show("Click");
    }
}
</code>```

However, whenever I run my application, I don't see three items in my items control, only one item. Why is this? Also, would my binding expression be correct? Since I'm not binding to a property of string, simply {Binding} should be acceptable right?

答:
Try setting the ItemsSource on your items control</p>

```<code>repeaterRecentProjects.ItemsSource = someFiles;
...snipped...
</code>```

Title: WPF Noob Seeking Guidance

Body:
So, most of the time I live in ASP.NET MVC Land - however, right now I'm trying to make some analysis tools for our solution using WPF (aka, it would count lines of code, which files have tests, extracting meta data from attributes, etc). Everything is mostly going well (the reflection code I have works fine). What I'm having trouble with is the WPF ItemsControl. Compared to a tradition <asp:Repeater />, ItemsControl is completely boggling me.

My XAML:

<ItemsControl x:Name="repeaterRecentProjects">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Border Background="#094563" Margin="5" Padding="3">
                <DockPanel>
                    <Image Source="/Content/Black-Internal-icon.png" Height="16" Width="16"></Image>
                    <TextBlock Margin="5,0" Text="{Binding}"></TextBlock>
                </DockPanel>
            </Border>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
    <ItemsPanelTemplate>
        <StackPanel Orientation="Vertical"></StackPanel>
    </ItemsPanelTemplate>
</ItemsControl>

The idea is that the DataTemplate contains my template, as I understand it. Then, in code I can do something like this (EDIT: Full code behind of the page):

public partial class HomeScreen : Page
{
    protected bool _isProjectChosen = false;

    public HomeScreen()
    {
        InitializeComponent();
    }

    protected ObservableCollection<string> someFiles = new ObservableCollection<string>();

    protected override void OnInitialized(EventArgs e)
    {
        base.OnInitialized(e);

        someFiles.Add("SomeFile.aspx");
        someFiles.Add("SomeFile2.aspx");
        someFiles.Add("SomeFile3.aspx");

        repeaterRecentProjects.ItemsSource = someFiles;
    }

    private void buttonSelectProject_Click(object sender, RoutedEventArgs e)
    {
        OpenFileDialog dialogSelectProject = new OpenFileDialog();

        dialogSelectProject.DefaultExt = ".sln";
        dialogSelectProject.Filter = "Visual Studio Solution (.sln)|*.sln";

        if (dialogSelectProject.ShowDialog() == true)
        {
            textBlockProjectName.Text = dialogSelectProject.FileName;
            _isProjectChosen = true;
            buttonAnalyzeProject.IsEnabled = true;
        }

        someFiles.Add("AnotherString.aspx");
    }

    private void buttonAnalyzeProject_Click(object sender, RoutedEventArgs e)
    {
        MessageBox.Show("Click");
    }
}

However, whenever I run my application, I don't see three items in my items control, only one item. Why is this? Also, would my binding expression be correct? Since I'm not binding to a property of string, simply {Binding} should be acceptable right?

Body:
Try setting the ItemsSource on your items control

repeaterRecentProjects.ItemsSource = someFiles;
...snipped...


问:
OkHttp3 java.lang.IllegalArgumentException: Unexpected char 0x2019
Why OKHttp prohibit some printable characters to be sent as header? I am writing an apps that publishes a http header. The apps crashed because a right single quoted character.

This is the stack trace:

```<code>Fatal Exception: java.lang.IllegalArgumentException: Unexpected char 0x2019 at 358 in my-header value: test’s
       at okhttp3.Headers.checkValue(Headers.java:272)
       at okhttp3.Headers$Builder.add(Headers.java:312)
       at okhttp3.Request$Builder.addHeader(Request.java:196)
...
</code>```

This is the OkHttp source code that throws the exception:

```<code>internal fun checkValue(value: String, name: String) {
      for (i in 0 until value.length) {
        val c = value[i]
        require(c == '\t' || c in '\u0020'..'\u007e') {
          format("Unexpected char %#04x at %d in %s value: %s", c.toInt(), i, name, value)
      }
   }
}
</code>```

Seeing that source code, is that a standard to allow only character in this range require(c == '\t' || c in '\u0020'..'\u007e') for http header?

答:
Please check this.

Because of the exist of checkValue method in Okhttp, your header can't contains invalid data.

So you need to encode your my-header 's value.

Body:
Why OKHttp prohibit some printable characters to be sent as header? I am writing an apps that publishes a http header. The apps crashed because a right single quoted character.

This is the stack trace:

Fatal Exception: java.lang.IllegalArgumentException: Unexpected char 0x2019 at 358 in my-header value: test’s
       at okhttp3.Headers.checkValue(Headers.java:272)
       at okhttp3.Headers$Builder.add(Headers.java:312)
       at okhttp3.Request$Builder.addHeader(Request.java:196)
...

This is the OkHttp source code that throws the exception:

internal fun checkValue(value: String, name: String) {
      for (i in 0 until value.length) {
        val c = value[i]
        require(c == '\t' || c in '\u0020'..'\u007e') {
          format("Unexpected char %#04x at %d in %s value: %s", c.toInt(), i, name, value)
      }
   }
}

Seeing that source code, is that a standard to allow only character in this range require(c == '\t' || c in '\u0020'..'\u007e') for http header?


问:
How to convert an integer in a base to a string
Sometimes I have integers like these 021 or 011.

If I try to convert them to a string, the result will be:

```<code>p 021.to_s # "17" instead "021"
p 011.to_s # "9" instead "011"
</code>```

Why does this happen and how can I convert the integers to strings?

答:
Numeric literals with a leading zero are considered to be octal (base 8) numbers.

The to_s method converts the numbers to the default decimal (base 10).

21 octal is 17 decimal

11 octal is 9 decimal

For the expected results, remove the leading zeroes.

Body:
Sometimes I have integers like these 021 or 011.

If I try to convert them to a string, the result will be:

p 021.to_s # "17" instead "021"
p 011.to_s # "9" instead "011"

Why does this happen and how can I convert the integers to strings?


问:
merge same keys data into one map with unique keys elixir
I have this json

```<code>[
  %{
    "159.69.136.31" => [
      %{"2015" => ["4"]},
      %{"2016" => []},
      %{"2017" => ["9"]},
      %{"2018" => []},
      %{"2019" => ["05"]}
    ]
  },
  %{
    "94.130.139.38" => [
      %{"2015" => []},
      %{"2016" => []},
      %{"2017" => []},
      %{"2018" => ["5", "8"]},
      %{"2019" => []}
    ]
  },
  %{
    "94.130.217.56" => [
      %{"2015" => []},
      %{"2016" => []},
      %{"2017" => []},
      %{"2018" => []},
      %{"2019" => []}
    ]
  }
]
</code>```

and I want to make it something like

```<code>[
  %{"2015" => ["4"]},
  %{"2016" => []},
  %{"2017" => ["9"]},
  %{"2018" => ["5", "8"]},
  %{"2019" => ["05"]}
]
</code>```

Basically, it's merging the same year's keys and the data available on the map. I have tried this solution with different approaches but it didn't work Elixir: Merge list with same map keys to one map

Update: years and IPs are constant
Update little bit more info about this..

```<code>years = ["2015", "2016", "2017", "2018", "2019"]
servers = [@seaweedfs_new, @seaweedfs_old, @seaweedfs_oldest]

  Enum.map(servers, fn server ->
    type = seaweefs_type(server)
    attribute = seaweedfs_attribute(server)
    url = "http://" <> server <> ":8888" <> "/#{camera.exid}/snapshots/recordings/"
    year_values =
      Enum.map(years, fn year ->
        final_url = url <> year <> "/"
        %{
          "#{year}" => request_from_seaweedfs(final_url, type, attribute)
        }
      end)
    %{
      "#{server}" => year_values
    }
  end)
</code>```

This is how I am getting year values and making them to the server object. If there is a possibility to break it down while even getting year values?

"#{year}" => request_from_seaweedfs(final_url, type, attribute) this request basically returns such as "2015"  => ["1", "2", "3"], is there any possiblity to merge years a head before going to into servers?

答:
Why are you doing:

```<code>"#{server}" => year_values
</code>```

when you don't care about the server name in the final result?  Doing that makes it harder to access the relevant data.

You can use a for loop (which is also called a list comprehension) coupled with the :reduce option (elixir 1.8+) to create a results map:

```<code>defmodule My do

  @years ["2015", "2016", "2017", "2018", "2019"]
  @servers ["new", "old", "oldest"]

  def request_from_seaweedfs(url, _type, _attribute) do
    IO.puts url
    "#{:random.uniform(20)}"  #Returns a random string
  end

  def get_data do
    for server <- @servers, year <- @years, reduce: %{} do
      map -> #This is the map specified here --------^
        url = "http://#{server}:8888/camera.exid/snapshots/recordings/#{year}/"
        result = request_from_seaweedfs(url, "x", "y")
        IO.puts "#{year}: #{result}"
        Map.update(map, year, [result], &([result|&1]))
    end
  end

end
</code>```

Output:

```<code>~/elixir_programs$ iex my.ex
Erlang/OTP 20 [erts-9.3] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:10] [hipe] [kernel-poll:false]
Interactive Elixir (1.8.2) - press Ctrl+C to exit (type h() ENTER for help)

iex(1)> My.get_data
http://new:8888/camera.exid/snapshots/recordings/2015/
2015: 9
http://new:8888/camera.exid/snapshots/recordings/2016/
2016: 15
http://new:8888/camera.exid/snapshots/recordings/2017/
2017: 19
http://new:8888/camera.exid/snapshots/recordings/2018/
2018: 11
http://new:8888/camera.exid/snapshots/recordings/2019/
2019: 7
http://old:8888/camera.exid/snapshots/recordings/2015/
2015: 12
http://old:8888/camera.exid/snapshots/recordings/2016/
2016: 19
http://old:8888/camera.exid/snapshots/recordings/2017/
2017: 14
http://old:8888/camera.exid/snapshots/recordings/2018/
2018: 10
http://old:8888/camera.exid/snapshots/recordings/2019/
2019: 12
http://oldest:8888/camera.exid/snapshots/recordings/2015/
2015: 3
http://oldest:8888/camera.exid/snapshots/recordings/2016/
2016: 5
http://oldest:8888/camera.exid/snapshots/recordings/2017/
2017: 14
http://oldest:8888/camera.exid/snapshots/recordings/2018/
2018: 4
http://oldest:8888/camera.exid/snapshots/recordings/2019/
2019: 12

%{
  "2015" => ["3", "12", "9"],
  "2016" => ["5", "19", "15"],
  "2017" => ["14", "14", "19"],
  "2018" => ["4", "10", "11"],
  "2019" => ["12", "12", "7"]
}
</code>```

To get your list, you can do:

```<code>My.get_data |> Enum.map(fn {key,val} -> %{key => val} end)
</code>```

which produces:

```<code>[
  %{"2015" => ["3", "12", "9"]},
  %{"2016" => ["5", "19", "15"]},
  %{"2017" => ["14", "14", "19"]},
  %{"2018" => ["4", "10", "11"]},
  %{"2019" => ["12", "12", "7"]}
]
</code>```

And, if the data's order needs to be maintained then you can do:

```<code>My.get_data |> Enum.map(fn {key,val} -> %{key => Enum.reverse(val)} end)
</code>```

Body:
I have this json

[
  %{
    "159.69.136.31" => [
      %{"2015" => ["4"]},
      %{"2016" => []},
      %{"2017" => ["9"]},
      %{"2018" => []},
      %{"2019" => ["05"]}
    ]
  },
  %{
    "94.130.139.38" => [
      %{"2015" => []},
      %{"2016" => []},
      %{"2017" => []},
      %{"2018" => ["5", "8"]},
      %{"2019" => []}
    ]
  },
  %{
    "94.130.217.56" => [
      %{"2015" => []},
      %{"2016" => []},
      %{"2017" => []},
      %{"2018" => []},
      %{"2019" => []}
    ]
  }
]

and I want to make it something like

[
  %{"2015" => ["4"]},
  %{"2016" => []},
  %{"2017" => ["9"]},
  %{"2018" => ["5", "8"]},
  %{"2019" => ["05"]}
]

Basically, it's merging the same year's keys and the data available on the map. I have tried this solution with different approaches but it didn't work Elixir: Merge list with same map keys to one map

Update: years and IPs are constant
Update little bit more info about this..

years = ["2015", "2016", "2017", "2018", "2019"]
servers = [@seaweedfs_new, @seaweedfs_old, @seaweedfs_oldest]

  Enum.map(servers, fn server ->
    type = seaweefs_type(server)
    attribute = seaweedfs_attribute(server)
    url = "http://" <> server <> ":8888" <> "/#{camera.exid}/snapshots/recordings/"
    year_values =
      Enum.map(years, fn year ->
        final_url = url <> year <> "/"
        %{
          "#{year}" => request_from_seaweedfs(final_url, type, attribute)
        }
      end)
    %{
      "#{server}" => year_values
    }
  end)

This is how I am getting year values and making them to the server object. If there is a possibility to break it down while even getting year values?

"#{year}" => request_from_seaweedfs(final_url, type, attribute) this request basically returns such as "2015"  => ["1", "2", "3"], is there any possiblity to merge years a head before going to into servers?

Body:
Why are you doing:

"#{server}" => year_values

when you don't care about the server name in the final result?  Doing that makes it harder to access the relevant data.

You can use a for loop (which is also called a list comprehension) coupled with the :reduce option (elixir 1.8+) to create a results map:

defmodule My do

  @years ["2015", "2016", "2017", "2018", "2019"]
  @servers ["new", "old", "oldest"]

  def request_from_seaweedfs(url, _type, _attribute) do
    IO.puts url
    "#{:random.uniform(20)}"  #Returns a random string
  end

  def get_data do
    for server <- @servers, year <- @years, reduce: %{} do
      map -> #This is the map specified here --------^
        url = "http://#{server}:8888/camera.exid/snapshots/recordings/#{year}/"
        result = request_from_seaweedfs(url, "x", "y")
        IO.puts "#{year}: #{result}"
        Map.update(map, year, [result], &([result|&1]))
    end
  end

end

Output:

~/elixir_programs$ iex my.ex
Erlang/OTP 20 [erts-9.3] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:10] [hipe] [kernel-poll:false]
Interactive Elixir (1.8.2) - press Ctrl+C to exit (type h() ENTER for help)

iex(1)> My.get_data
http://new:8888/camera.exid/snapshots/recordings/2015/
2015: 9
http://new:8888/camera.exid/snapshots/recordings/2016/
2016: 15
http://new:8888/camera.exid/snapshots/recordings/2017/
2017: 19
http://new:8888/camera.exid/snapshots/recordings/2018/
2018: 11
http://new:8888/camera.exid/snapshots/recordings/2019/
2019: 7
http://old:8888/camera.exid/snapshots/recordings/2015/
2015: 12
http://old:8888/camera.exid/snapshots/recordings/2016/
2016: 19
http://old:8888/camera.exid/snapshots/recordings/2017/
2017: 14
http://old:8888/camera.exid/snapshots/recordings/2018/
2018: 10
http://old:8888/camera.exid/snapshots/recordings/2019/
2019: 12
http://oldest:8888/camera.exid/snapshots/recordings/2015/
2015: 3
http://oldest:8888/camera.exid/snapshots/recordings/2016/
2016: 5
http://oldest:8888/camera.exid/snapshots/recordings/2017/
2017: 14
http://oldest:8888/camera.exid/snapshots/recordings/2018/
2018: 4
http://oldest:8888/camera.exid/snapshots/recordings/2019/
2019: 12

%{
  "2015" => ["3", "12", "9"],
  "2016" => ["5", "19", "15"],
  "2017" => ["14", "14", "19"],
  "2018" => ["4", "10", "11"],
  "2019" => ["12", "12", "7"]
}

To get your list, you can do:

My.get_data |> Enum.map(fn {key,val} -> %{key => val} end)

which produces:

[
  %{"2015" => ["3", "12", "9"]},
  %{"2016" => ["5", "19", "15"]},
  %{"2017" => ["14", "14", "19"]},
  %{"2018" => ["4", "10", "11"]},
  %{"2019" => ["12", "12", "7"]}
]

And, if the data's order needs to be maintained then you can do:

My.get_data |> Enum.map(fn {key,val} -> %{key => Enum.reverse(val)} end)


问:
How to find controls in a repeater header or footer
I was wondering how one would find the controls in the HeaderTemplate or FooterTemplate of an Asp.Net Repeater control.

I can access them on the ItemDataBound event, but I was wondering how to get them after (for example to retrieve a value of an input in the header/footer).

Note: I posted this question here after finding the answer just so that I remember it (and maybe other people might find this useful).

答:
Find control into Repeater (Header, Item, Footer)</p>

```<code>public static class FindControlInRepeater
{
    public static Control FindControl(this Repeater repeater, string controlName)
    {
        for (int i = 0; i < repeater.Controls.Count; i++)
            if (repeater.Controls[i].Controls[0].FindControl(controlName) != null)
                return repeater.Controls[i].Controls[0].FindControl(controlName);
        return null;
    }
}
</code>```

OwnerDisplayName: Crossbrowser

ContentLicense: CC BY-SA 2.5

Body:
Find control into Repeater (Header, Item, Footer)

public static class FindControlInRepeater
{
    public static Control FindControl(this Repeater repeater, string controlName)
    {
        for (int i = 0; i < repeater.Controls.Count; i++)
            if (repeater.Controls[i].Controls[0].FindControl(controlName) != null)
                return repeater.Controls[i].Controls[0].FindControl(controlName);
        return null;
    }
}


问:
Hiding a highchart series is very slow
I have a highchart displaying multiple series, each contains 100+ data points
I have a UI containing a checkbox for each series that when clicked calls the series.hide() or series.show() to toggle the hide/show of each line
My problem is that the hide and show are extremely slow such that I cant check one checkbox whilst processing from a previous is taking place
Does anyone know how to handle this?
Thanks</p>

答:
How about adding visible: false for the series that are hidden before calling Highcharts.chart()?
Please see references: 1. Highcharts API and 2. Demo

In my case, above approach showed the best performance comparing to the followings:

series.hide()

setVisible(false, false)

setVisible(false, true) or setVisible(false, false); redraw();

Title: Hiding a highchart series is very slow


问:
How to pass arguments as CLOB in mybatis while using oracle functions?
I'm trying to put a lengthy WKT (a long string about geographical info) into an oracle spatial function SDO_GEOMETRY to transform WKT into oracle geometry type using mybatis. There are no column in the database that stores the WKT, it is only used as a parameter in the said function. The java type of the item is String, when I try to put it in it would return error, saying String too long. This indicates that the string is not being turned into a CLOB. How do I do that?

I tried using this at the start of mybatis .xml file:

```<code><resultMap type="example.Building" id="BaseResultMap">
        <result property="geom" column="geom" jdbcType="CLOB"
                javaType = "java.lang.String"  typeHandler ="example.Utils.OracleClobTypeHandler"/>
    </resultMap>
</code>```

and I have an OracleClobTypeHandler class set up.

I also tried using #{wkt,jdbcType=CLOB} but that went nowhere.

EDIT: This is the SetParameter method in the OracleClobTypeHandler:

```<code>    @Override
    public void setParameter(PreparedStatement arg0, int arg1, Object arg2, JdbcType arg3) throws SQLException {
        CLOB clob = CLOB.getEmptyCLOB();
        clob.setString(1, (String) arg2);
        arg0.setClob(arg1, clob);
    }
</code>```

答:
<resultMap /> is irrelevant as it is used when mapping query result to Java object.

Try specifying typeHandler in the parameter reference. e.g.

#{wkt,typeHandler=example.Utils.OracleClobTypeHandler}

Note that if the type handler is an inner class of Utils, it has to be referenced as example.Utils$OracleClobTypeHandler instead.

Body:
I'm trying to put a lengthy WKT (a long string about geographical info) into an oracle spatial function SDO_GEOMETRY to transform WKT into oracle geometry type using mybatis. There are no column in the database that stores the WKT, it is only used as a parameter in the said function. The java type of the item is String, when I try to put it in it would return error, saying String too long. This indicates that the string is not being turned into a CLOB. How do I do that?

I tried using this at the start of mybatis .xml file:

<resultMap type="example.Building" id="BaseResultMap">
        <result property="geom" column="geom" jdbcType="CLOB"
                javaType = "java.lang.String"  typeHandler ="example.Utils.OracleClobTypeHandler"/>
    </resultMap>

and I have an OracleClobTypeHandler class set up.

I also tried using #{wkt,jdbcType=CLOB} but that went nowhere.

EDIT: This is the SetParameter method in the OracleClobTypeHandler:

    @Override
    public void setParameter(PreparedStatement arg0, int arg1, Object arg2, JdbcType arg3) throws SQLException {
        CLOB clob = CLOB.getEmptyCLOB();
        clob.setString(1, (String) arg2);
        arg0.setClob(arg1, clob);
    }


问:
LSTM. Calculating RMSE using inverse_transform
I'm having some trouble calculating the RMSE (root-mean-squared-error) in my LSTM model. The model fits fine and I'm getting a good loss reduction, however when trying to inverse_transform my yhat results I get the following error:

```<code>non-broadcastable output operand with shape (399,1) doesn't match the broadcast shape (399,4)
</code>```

Here's my code:

Preprocessing:

```<code>btc = pd.read_csv('live_bitcoin.csv')
twitter_sent = pd.read_csv('live_tweet.csv')
reddit_sent = pd.read_csv('live_reddit.csv')

btc.columns = ["price_usd","24h_volume_usd","market_cap_usd","available_supply","total_supply","percent_change_1h","percent_change_24h","percent_change_7d", "Sell", "Buy", "15m", "Stamp"]
twitter_sent.columns = ["Sentiment", "Stamp"]
reddit_sent.columns = ["Sentiment", "Stamp"]

merged = pd.merge(twitter_sent, btc,  on='Stamp', how='inner').merge(reddit_sent, on='Stamp', how='inner')
data = merged[["Sentiment_x", "Sentiment_y","24h_volume_usd", "market_cap_usd", "available_supply","price_usd"]].groupby(merged['Stamp']).mean()
datag = data[["24h_volume_usd", "market_cap_usd", "available_supply","price_usd"]]
tw_sentiment = data["Sentiment_x"]
rdt_sentiment = data["Sentiment_y"]

print "Dataset size: " + str(len(datag))
print "Timespan: " + str(len(datag)/60) + " hours"

from sklearn.preprocessing import MinMaxScaler

scaler = MinMaxScaler(feature_range=(0, 1))
values = datag.values.reshape(-1, datag.shape[1])
tw_sentiment = tw_sentiment.values.reshape(-1, 1)
rdt_sentiment = rdt_sentiment.values.reshape(-1, 1)
tw_sentiment = tw_sentiment.astype('float32')
rdt_sentiment = rdt_sentiment.astype('float32')
values = values.astype('float32')
scaled = scaler.fit_transform(values)
</code>```

Training:

```<code>train_size = int(len(scaled) * 0.7)
test_size = len(scaled) - train_size
train, test = scaled[0:train_size,:], scaled[train_size:len(scaled),:]
split = train_size

def create_dataset(dataset, look_back, tw_sentiment, rdt_sentiment, sent=False):
    dataX, dataY = [], []
    for i in range(len(dataset) - look_back):
        if i >= look_back:
            a = dataset[i-look_back:i+1, 0]
            a = a.tolist()
            if(sent==True):
                current_tw_sentiment = tw_sentiment[i].tolist()[0]
                current_rdt_sentiment = rdt_sentiment[i].tolist()[0]
                a.append(current_tw_sentiment)
                a.append(current_rdt_sentiment)
            dataX.append(a)
            dataY.append(dataset[i + look_back, 0])
    print(len(dataY))
    return np.array(dataX), np.array(dataY)

look_back = 2
trainX, trainY = create_dataset(train, look_back, tw_sentiment[0:train_size], rdt_sentiment[0:train_size], sent=True)
testX, testY = create_dataset(test, look_back, tw_sentiment[train_size:len(scaled)], rdt_sentiment[train_size:len(scaled)], sent=True)

trainX = np.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))
testX = np.reshape(testX, (testX.shape[0], 1, testX.shape[1]))

# Creating new model
model = Sequential()
model.add(LSTM(100, input_shape=(trainX.shape[1], trainX.shape[2]), return_sequences=True))
model.add(LSTM(100))
model.add(Dense(1))
model.compile(loss='mae', optimizer='adam')
model.save('LSTM_14-03-2018.h5')

# Loading model
# model = load_model('models/LSTM_12-03-2018_GOOD.h5')

history = model.fit(trainX, trainY, epochs=300, batch_size=100, validation_data=(testX, testY), verbose=0, shuffle=False)
yhat = model.predict(testX)
yhat_inverse = scaler.inverse_transform(yhat.reshape(-1, 1))
testY_inverse = scaler.inverse_transform(testY.reshape(-1, 1))
rmse_sent = sqrt(mean_squared_error(testY_inverse, yhat_inverse))
print "Done"
print 'Test RMSE: %.3f' % rmse_sent
</code>```

The main problem lies here:

```<code>  yhat_inverse = scaler.inverse_transform(yhat.reshape(-1,1))
  testY_inverse = scaler.inverse_transform(testY.reshape(-1,1))
</code>```

For what I understand (still a beginner in ML), my yhat variable has a shape of (399, 1) as I'm trying to make a prediction based on several features. I'm only looking to revert my data to its previous transform so the RMSE error returns in an appropriate scale. I'm basically trying to reconvert prices to their normal scale. I'm also never re_transforming the data after the MinMaxScaler does it in the preprocessing stage.

Any clues on what might be wrong?

答:
the following works for me.

scaler2 = MinMaxScaler()
scaler2.min_, scaler2.scale_ = scaler.min_[0], scaler.scale_[0]

yhat_inverse = scaler2.inverse_transform(yhat)
testY_inverse = scaler2.inverse_transform(testY)

Body:
I'm having some trouble calculating the RMSE (root-mean-squared-error) in my LSTM model. The model fits fine and I'm getting a good loss reduction, however when trying to inverse_transform my yhat results I get the following error:

non-broadcastable output operand with shape (399,1) doesn't match the broadcast shape (399,4)

Here's my code:

Preprocessing:

btc = pd.read_csv('live_bitcoin.csv')
twitter_sent = pd.read_csv('live_tweet.csv')
reddit_sent = pd.read_csv('live_reddit.csv')

btc.columns = ["price_usd","24h_volume_usd","market_cap_usd","available_supply","total_supply","percent_change_1h","percent_change_24h","percent_change_7d", "Sell", "Buy", "15m", "Stamp"]
twitter_sent.columns = ["Sentiment", "Stamp"]
reddit_sent.columns = ["Sentiment", "Stamp"]

merged = pd.merge(twitter_sent, btc,  on='Stamp', how='inner').merge(reddit_sent, on='Stamp', how='inner')
data = merged[["Sentiment_x", "Sentiment_y","24h_volume_usd", "market_cap_usd", "available_supply","price_usd"]].groupby(merged['Stamp']).mean()
datag = data[["24h_volume_usd", "market_cap_usd", "available_supply","price_usd"]]
tw_sentiment = data["Sentiment_x"]
rdt_sentiment = data["Sentiment_y"]

print "Dataset size: " + str(len(datag))
print "Timespan: " + str(len(datag)/60) + " hours"

from sklearn.preprocessing import MinMaxScaler

scaler = MinMaxScaler(feature_range=(0, 1))
values = datag.values.reshape(-1, datag.shape[1])
tw_sentiment = tw_sentiment.values.reshape(-1, 1)
rdt_sentiment = rdt_sentiment.values.reshape(-1, 1)
tw_sentiment = tw_sentiment.astype('float32')
rdt_sentiment = rdt_sentiment.astype('float32')
values = values.astype('float32')
scaled = scaler.fit_transform(values)

Training:

train_size = int(len(scaled) * 0.7)
test_size = len(scaled) - train_size
train, test = scaled[0:train_size,:], scaled[train_size:len(scaled),:]
split = train_size

def create_dataset(dataset, look_back, tw_sentiment, rdt_sentiment, sent=False):
    dataX, dataY = [], []
    for i in range(len(dataset) - look_back):
        if i >= look_back:
            a = dataset[i-look_back:i+1, 0]
            a = a.tolist()
            if(sent==True):
                current_tw_sentiment = tw_sentiment[i].tolist()[0]
                current_rdt_sentiment = rdt_sentiment[i].tolist()[0]
                a.append(current_tw_sentiment)
                a.append(current_rdt_sentiment)
            dataX.append(a)
            dataY.append(dataset[i + look_back, 0])
    print(len(dataY))
    return np.array(dataX), np.array(dataY)

look_back = 2
trainX, trainY = create_dataset(train, look_back, tw_sentiment[0:train_size], rdt_sentiment[0:train_size], sent=True)
testX, testY = create_dataset(test, look_back, tw_sentiment[train_size:len(scaled)], rdt_sentiment[train_size:len(scaled)], sent=True)

trainX = np.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))
testX = np.reshape(testX, (testX.shape[0], 1, testX.shape[1]))

# Creating new model
model = Sequential()
model.add(LSTM(100, input_shape=(trainX.shape[1], trainX.shape[2]), return_sequences=True))
model.add(LSTM(100))
model.add(Dense(1))
model.compile(loss='mae', optimizer='adam')
model.save('LSTM_14-03-2018.h5')

# Loading model
# model = load_model('models/LSTM_12-03-2018_GOOD.h5')

history = model.fit(trainX, trainY, epochs=300, batch_size=100, validation_data=(testX, testY), verbose=0, shuffle=False)
yhat = model.predict(testX)
yhat_inverse = scaler.inverse_transform(yhat.reshape(-1, 1))
testY_inverse = scaler.inverse_transform(testY.reshape(-1, 1))
rmse_sent = sqrt(mean_squared_error(testY_inverse, yhat_inverse))
print "Done"
print 'Test RMSE: %.3f' % rmse_sent

The main problem lies here:

  yhat_inverse = scaler.inverse_transform(yhat.reshape(-1,1))
  testY_inverse = scaler.inverse_transform(testY.reshape(-1,1))

For what I understand (still a beginner in ML), my yhat variable has a shape of (399, 1) as I'm trying to make a prediction based on several features. I'm only looking to revert my data to its previous transform so the RMSE error returns in an appropriate scale. I'm basically trying to reconvert prices to their normal scale. I'm also never re_transforming the data after the MinMaxScaler does it in the preprocessing stage.

Any clues on what might be wrong?


问:
Dict comprehension not working like I thought it does. What am I doing wrong?
Dict comprehension with if-else condition does not seem to be using the if block at all. It always goes to the else block even when it should not.

I am trying to use dict comprehension with if condition in python to determine the number of occurrences of characters in a string. However, the if condition never seems to be satisfied (when it really should be). Only the else condition seems to be satisfied

def letter_count(input_str):
    letter_count_map = {}

    letter_count_map = {letter: letter_count_map[letter]+1 if letter in
                        letter_count_map.keys() else 1
                        for letter in input_str}
    print(letter_count_map)

letter_count("serendipity")
```

<p>Expected result:</p>

```{'s': 1, 'e': 2, 'r': 1, 'n': 1, 'd': 1, 'i': 2, 'p': 1, 't': 1, 'y': 1}
```

<p>Actual result:</p>

```{'s': 1, 'e': 1, 'r': 1, 'n': 1, 'd': 1, 'i': 1, 'p': 1, 't': 1, 'y': 1}
```

What am I doing wrong?

答:
You also can take defaultdict to simplify your code.

```<code>from collections import defaultdict

def letter_count(input_str):
    letter_count_map = defaultdict(lambda: 0)

    for c in input_str:
        letter_count_map[c] += 1
    print(letter_count_map)

letter_count("serendipity")
</code>```

Body:
Dict comprehension with if-else condition does not seem to be using the if block at all. It always goes to the else block even when it should not.

I am trying to use dict comprehension with if condition in python to determine the number of occurrences of characters in a string. However, the if condition never seems to be satisfied (when it really should be). Only the else condition seems to be satisfied

def letter_count(input_str):
    letter_count_map = {}

    letter_count_map = {letter: letter_count_map[letter]+1 if letter in
                        letter_count_map.keys() else 1
                        for letter in input_str}
    print(letter_count_map)

letter_count("serendipity")

Expected result:

{'s': 1, 'e': 2, 'r': 1, 'n': 1, 'd': 1, 'i': 2, 'p': 1, 't': 1, 'y': 1}

Actual result:

{'s': 1, 'e': 1, 'r': 1, 'n': 1, 'd': 1, 'i': 1, 'p': 1, 't': 1, 'y': 1}

What am I doing wrong?

Body:
You also can take defaultdict to simplify your code.

from collections import defaultdict

def letter_count(input_str):
    letter_count_map = defaultdict(lambda: 0)

    for c in input_str:
        letter_count_map[c] += 1
    print(letter_count_map)

letter_count("serendipity")


问:
How to check if html tag contains a class
I'm trying to use JS to check if an html tag contains a specific class

What I have so far (doesn't work)

```<code>if (html.classList.contains('test')) {

}
</code>```

```<code><html class="test">
</code>```

答:
You can determine the class within the classList of the element.

let el = document.querySelector('html');
var classList = el.classList;
console.log(classList.contains('test')); // gives true```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html class="test"></code>```

You can also grab the className (which is a string of all applied classes and use .indexOf();

let el = document.querySelector('html');
var className = el.className;
console.log(className); // gives 'test test2'
console.log(className.indexOf('test') > -1); // gives true```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html class="test test2"></code>```

If you have access to jQuery, the .hasClass() method is what you want

let test = $('html').hasClass('test');
console.log(test); // gives true```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html class="test"></code>```

Body:
I'm trying to use JS to check if an html tag contains a specific class

What I have so far (doesn't work)

if (html.classList.contains('test')) {

}

Body:
You can determine the class within the classList of the element.

let el = document.querySelector('html');
var classList = el.classList;
console.log(classList.contains('test')); // gives true

<html class="test">

You can also grab the className (which is a string of all applied classes and use .indexOf();

let el = document.querySelector('html');
var className = el.className;
console.log(className); // gives 'test test2'
console.log(className.indexOf('test') > -1); // gives true

<html class="test test2">

If you have access to jQuery, the .hasClass() method is what you want

let test = $('html').hasClass('test');
console.log(test); // gives true

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html class="test">


问:
How to divide each element in a row by corresponding row value?
(I want to divide each element in a row by corresponding row value. Denominator should the value of "Ac" when row element is present.</p>

```<code>Ac    V1  V2  V3   V4  V5  V6  V7
6.6  NA  NA  NA   NA   0  5.6  5.2
8.4  NA  0   82.5 31   0  0    1.1

Output:

V1 V2    V3        V4       V5                            V6               V7
NA 0/8.4 82.5/8.4 31/8.4  (0*6.6+0*6.6)/(6.6+8.4) (5.6*6.6+0*8.4)/(6.6+8.4) (5.2*6.6+1.1*8.4)/(6.6+8.4)
</code>```

Body:
(I want to divide each element in a row by corresponding row value. Denominator should the value of "Ac" when row element is present.

Ac    V1  V2  V3   V4  V5  V6  V7
6.6  NA  NA  NA   NA   0  5.6  5.2
8.4  NA  0   82.5 31   0  0    1.1

Output:

V1 V2    V3        V4       V5                            V6               V7
NA 0/8.4 82.5/8.4 31/8.4  (0*6.6+0*6.6)/(6.6+8.4) (5.6*6.6+0*8.4)/(6.6+8.4) (5.2*6.6+1.1*8.4)/(6.6+8.4)

Body:
Your data:

library(dplyr)

df <- data.frame(V1 = c(rep(NA,4), 0, 5.6, 5.2),
                 V2 = c(NA, 0 , 82.5, 31, 0, 0, 1.1))

df <- df %>%
  t %>% as.data.frame() %>%
  dplyr::mutate(Ac = c(6.6, 8.4)) %>%
  dplyr::select(Ac, V1:V7)
df

> df
   Ac V1 V2   V3 V4 V5  V6  V7
1 6.6 NA NA   NA NA  0 5.6 5.2
2 8.4 NA  0 82.5 31  0 0.0 1.1

The answer:

resp <- df %>%
  dplyr::select(-Ac) %>%
  t %>% as.data.frame() %>%
  dplyr::mutate(V1_1 = V1/df[1,1],
                V2_2 = V2/df[2,1]) %>%
  dplyr::rowwise() %>%
  dplyr::mutate(resp = ifelse(is.na(V1_1) & is.na(V2_2), NA,
                              sum(V1_1, V2_2, na.rm = T))) %>%
  dplyr::select(resp) %>% t %>% as.data.frame()
resp

> resp
     V1 V2       V3       V4 V5        V6        V7
resp NA  0 9.821429 3.690476  0 0.8484848 0.9188312


问:
Left align in fortran format
Is it possible to left align a printed out value in Fortran, instead of the default right alignment ?

For example, I have formatters like this

"(A3,10A12)"

and

"(A1, I12, 9F12.6)"

I would like the strings and numbers printed with these formatters to be left aligned, instead of right aligned.

答:
Isn't right-justified the default?

If you first write a number to a string, you could use the intrinsics adjustL or adjustR to get either adjustment, then output the string.

Title: Left align in fortran format


问:
Javascript Redirect Based On Radio Selection
I have devised this script to redirect to the specific page based on the radio selection but it keeps going to the old link that was setup. Are there any recommendations you can suggest to get this working?

```<code>            <div class="col-12" style="margin-top">
            <label><strong>What Is Your Business Currently Generating?</strong></label>
            <div class="d-flex m-t--20">
                <div class="p--relative check">
                    <input type="radio" id="o5kradio" name="income" value="o5k" checked required/>
                    <label for="diy">Over $5k Per Month</label>
                </div>
                <div class="p--relative check">
                    <input type="radio" id="u5kradio" name="income" value="u5k" required/>
                    <label for="hands-on">Under $5k Per Month</label>
                </div>
            </div>
        </div>

        <script>
        var o5kradio = document.getElementById("o5kradio"),
        u5kradio = document.getElementById("u5kradio"),
        submitButton = document.getElementById("SubmitButton");

         submitButton.addEventListener("click", function () {
         if (o5kradio.checked) {
         alert('o5k');
         window.location = "https://vincedelmonte7figuremastermind.com/sit-in/schedule-now/";
         } else {
         alert('u5k');
         window.location = "https://vincedelmonte7figuremastermind.com/sit-in/schedule-now-2/";
    }
    }, false);
    </script>

        <!--ERROR/SUCCESS MESSAGE-->
        <div class="message js-message"></div>
        <button type="submit" value="submit" id="SubmitButton" class="btn txt--shadow-smaller">Click TO SUBMIT APPLICATION</button>
    </form>
</code>```

Sends users here no matter the selection: https://vincedelmonte7figuremastermind.com/sit-in/schedule-now/

答:
Okay, so this works and while it's a bit of overkill, it's very thorough overkill that you can use for any future radio button forms, even ones with dozens of options:

```<code>      <div class="col-12" style="margin-top">
        <label><strong>What Is Your Business Currently Generating?</strong></label>
        <div class="d-flex m-t--20">
            <div class="p--relative check">
                <input type="radio" id="o5kradio" name="income" value="o5k" checked required/>
                <label for="diy">Over $5k Per Month</label>
            </div>
            <div class="p--relative check">
                <input type="radio" id="u5kradio" name="income" value="u5k" required/>
                <label for="hands-on">Under $5k Per Month</label>
            </div>
        </div>
    </div>

  <script>
    // No need for declaring global variables here
    function submit(source,options){
    // First, this segment finds the checked element in the array:
      for (var i = 0; i < options.length; i++){
        if (options[i].checked){
          break;
        }
      }
    // Next, the source switch determines which button element called the function:
    switch(source.id){
   case 'submitButton':
    // The options switch then determines what happens when the checked option is submitted:
      switch(options[i].id){
        case 'o5kradio':
          alert('over5k');
          window.location = "https://vincedelmonte7figuremastermind.com/sit-in/schedule-now/";
          break;
        case 'u5kradio':
          alert('under5k');
          window.location = "https://vincedelmonte7figuremastermind.com/sit-in/schedule-now-2/";
          break;
          //  The default option for the options switch
        default:
          window.location = "https://vincedelmonte7figuremastermind.com/sit-in/schedule-now/";
          }
        break;
        // The default option for the source switch
        default:
       }
    }
</script>

    <!--ERROR/SUCCESS MESSAGE-->
    <div class="message js-message"></div>
    <button type="submit" value="submit" id="submitButton" onclick="submit(this,options=[o5kradio,u5kradio])" class="btn txt--shadow-smaller">Click TO SUBMIT APPLICATION</button>
</form>
</code>```

So to clarify, here's what I'm doing...

For starters, I prefer "onclick" functions in buttons because it gives more freedom. I created a function called "submit" and it passes two values from the HTML: 1. "this", which will be its own Id so the function can identify the source and 2. an array called "options" which contains the Ids of all of the radio buttons it will need to evaluate to find the checked one:

```<code><button type="submit" value="submit" id="submitButton" onclick="submit(this,options=[o5kradio,u5kradio])" class="btn txt--shadow-smaller">Click TO SUBMIT APPLICATION</button>
</code>```

Next, the first part of the function finds the checked radio button by cycling through the array. Since there can only ever be one checked button, this is easy to do:

```<code>function submit(source,options){
  for (var i = 0; i < options.length; i++){
    if (options[i].checked){
      break;
    }
  } ...etc.
</code>```

Next, I used a nested switch to decide how to handle the results. Note that adding ".id" after "source" and "options" bypasses the need to use "getElementById":

```<code> // The source switch
    switch(source.id){
   case 'submitButton':
      // The options switch, currently the first "case" of the source switch, but you can add as many cases as needed
      switch(options[i].id){
        case 'o5kradio':
          alert('over5k');
          window.location = "https://vincedelmonte7figuremastermind.com/sit-in/schedule-now/";
          break;
        case 'u5kradio':
          alert('under5k');
          window.location = "https://vincedelmonte7figuremastermind.com/sit-in/schedule-now-2/";
          break;
          //  The default option for the options switch
        default:
          window.location = "https://vincedelmonte7figuremastermind.com/sit-in/schedule-now/";
          }
        break;
        // The default option for the source switch
        default:
       }
</code>```

Once again, this is overkill, and I wouldn't be surprised if I've made at least one faux pas here, but the beauty of this setup is that every radio button form you have can utilize the same function, and you can have as many options as you want.

All you need to do is add another "case" to the "source.id" switch for each time a user will click the "submit" button (on additional pages, I assume) and you can control however many pages, redirections, and options you may have with one function. This means each click will only ever make three calculations (for statement, source switch, and option switch) so as to avoid multiple "else if" statements in a row for more than two radio buttons.

PS. The Id for "submitButton" starts with a capital "S", though fixing that didn't get it to work for me.

Body:
I have devised this script to redirect to the specific page based on the radio selection but it keeps going to the old link that was setup. Are there any recommendations you can suggest to get this working?

            What Is Your Business Currently Generating?

                    <input type="radio" id="o5kradio" name="income" value="o5k" checked required/>
                    Over $5k Per Month

                    <input type="radio" id="u5kradio" name="income" value="u5k" required/>
                    Under $5k Per Month

        <button type="submit" value="submit" id="SubmitButton" class="btn txt--shadow-smaller">Click TO SUBMIT APPLICATION</button>
    </form>

Sends users here no matter the selection: https://vincedelmonte7figuremastermind.com/sit-in/schedule-now/

Body:
Okay, so this works and while it's a bit of overkill, it's very thorough overkill that you can use for any future radio button forms, even ones with dozens of options:

      <div class="col-12" style="margin-top">
        <label><strong>What Is Your Business Currently Generating?</strong></label>
        <div class="d-flex m-t--20">
            <div class="p--relative check">
                <input type="radio" id="o5kradio" name="income" value="o5k" checked required/>
                <label for="diy">Over $5k Per Month</label>
            </div>
            <div class="p--relative check">
                <input type="radio" id="u5kradio" name="income" value="u5k" required/>
                <label for="hands-on">Under $5k Per Month</label>
            </div>
        </div>
    </div>

  <script>
    // No need for declaring global variables here
    function submit(source,options){
    // First, this segment finds the checked element in the array:
      for (var i = 0; i < options.length; i++){
        if (options[i].checked){
          break;
        }
      }
    // Next, the source switch determines which button element called the function:
    switch(source.id){
   case 'submitButton':
    // The options switch then determines what happens when the checked option is submitted:
      switch(options[i].id){
        case 'o5kradio':
          alert('over5k');
          window.location = "https://vincedelmonte7figuremastermind.com/sit-in/schedule-now/";
          break;
        case 'u5kradio':
          alert('under5k');
          window.location = "https://vincedelmonte7figuremastermind.com/sit-in/schedule-now-2/";
          break;
          //  The default option for the options switch
        default:
          window.location = "https://vincedelmonte7figuremastermind.com/sit-in/schedule-now/";
          }
        break;
        // The default option for the source switch
        default:
       }
    }
</script>

    <!--ERROR/SUCCESS MESSAGE-->
    <div class="message js-message"></div>
    <button type="submit" value="submit" id="submitButton" onclick="submit(this,options=[o5kradio,u5kradio])" class="btn txt--shadow-smaller">Click TO SUBMIT APPLICATION</button>
</form>

So to clarify, here's what I'm doing...

For starters, I prefer "onclick" functions in buttons because it gives more freedom. I created a function called "submit" and it passes two values from the HTML: 1. "this", which will be its own Id so the function can identify the source and 2. an array called "options" which contains the Ids of all of the radio buttons it will need to evaluate to find the checked one:

<button type="submit" value="submit" id="submitButton" onclick="submit(this,options=[o5kradio,u5kradio])" class="btn txt--shadow-smaller">Click TO SUBMIT APPLICATION</button>

Next, the first part of the function finds the checked radio button by cycling through the array. Since there can only ever be one checked button, this is easy to do:

function submit(source,options){
  for (var i = 0; i < options.length; i++){
    if (options[i].checked){
      break;
    }
  } ...etc.

Next, I used a nested switch to decide how to handle the results. Note that adding ".id" after "source" and "options" bypasses the need to use "getElementById":

 // The source switch
    switch(source.id){
   case 'submitButton':
      // The options switch, currently the first "case" of the source switch, but you can add as many cases as needed
      switch(options[i].id){
        case 'o5kradio':
          alert('over5k');
          window.location = "https://vincedelmonte7figuremastermind.com/sit-in/schedule-now/";
          break;
        case 'u5kradio':
          alert('under5k');
          window.location = "https://vincedelmonte7figuremastermind.com/sit-in/schedule-now-2/";
          break;
          //  The default option for the options switch
        default:
          window.location = "https://vincedelmonte7figuremastermind.com/sit-in/schedule-now/";
          }
        break;
        // The default option for the source switch
        default:
       }

Once again, this is overkill, and I wouldn't be surprised if I've made at least one faux pas here, but the beauty of this setup is that every radio button form you have can utilize the same function, and you can have as many options as you want.

All you need to do is add another "case" to the "source.id" switch for each time a user will click the "submit" button (on additional pages, I assume) and you can control however many pages, redirections, and options you may have with one function. This means each click will only ever make three calculations (for statement, source switch, and option switch) so as to avoid multiple "else if" statements in a row for more than two radio buttons.

PS. The Id for "submitButton" starts with a capital "S", though fixing that didn't get it to work for me.


问:
Setting legend entries manually
I am using openpyxl to create charts. For some reason, I do not want to insert row names when adding data. So, I want to edit the legend entries manually. I am wondering if anyone know how to do this.
More specifically
class openpyxl.chart.legend.Legend(legendPos='r', legendEntry=(),
     layout=None, overlay=None, spPr=None, txPr=None, extLst=None). I want to edit the legendEntry field

答: You cannot do that. You need to set the rows when creating the plots. That will create the titles for your charts</p>

Title: Setting legend entries manually


问:
How do I store my data in a custom Vue component instead of the root Vue instance?
I am creating a custom checkbox component in Vue, and it is working fine with the data being stored in the root instance. I plan to reuse this component (along with many other components I'm building) in a wide variety of cases. I do not want to have to update or edit the root Vue instance every time I use the component, and want to store the data ONLY in the component itself. The boolean value of checked/unchecked needs to be reactive.

I played around with using a computed value, but could not get that to work either. I am open to using this though if I need to.

(THIS VERSION DOES NOT WORK)

    <checkbox-item v-model="checkData">Active</checkbox-item>
    {{ checkData }}

```
</div>
</div>
</p>
<p>(THIS VERSION WORKS, BUT AGAIN I NEED THE DATA TO NOT BE IN THE ROOT INSTANCE)</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <script src="https://unpkg.com/vue@2.6.10"></script>
  <div id="app">
    <checkbox-item v-model="checkData">Active</checkbox-item>
    {{ checkData }}
  </div>
</body>

<script>
  Vue.component('checkbox-item', {
    template: `
          <label class="checkbox-item">
            <input type="checkbox" :checked="value"
                   @change="$emit('input', $event.target.checked)"
                   class="checkbox-input">
            <span class="checkbox-label">
              <slot></slot>
            </span>
          </label>
        `,
    props: ['value']
  })
  new Vue({
    el: '#app',
    data: {
      checkData: null
    }
  })
</script></code>```

The error I get is:

[Vue warn]: Property or method "checkData" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

And checkData is not reactive like it was in the working example.

EDIT: Okay, here's what works! I am definitely going to look into using SFC's and other code organization methods, but for now it's still in one html file. Does anyone see a reason this wouldn't work in the long run?

        <checkbox-item></checkbox-item>

```

答:
The reason the first example one doesn't work is because your root Vue component doesn't have access to the checkbox's data.

    <checkbox-item v-model="checkData">Active</checkbox-item>
    {{ checkData }}

```

<h3>What's going on in the non-functional example?</h3>

<p>When you say <code>v-model="checkData"</code> in the nonfunctional example, that's telling the Parent (Root) Vue component to find <code>checkData</code> in its local scope and <code>v-bind:value="checkData"</code> and <code>v-on:input="checkData = $event.target.value"</code></p>

<h3>Making your checkbox-item reusable</h3>

<p>Your component is wonderfully reusable as-is.</p>

<p>The only change I would make to your <code>checkbox-item</code> is to pass <code>v-on="$listeners"</code> and <code>v-bind="$attrs"</code> through on the <code>input</code> element, and remove the explicit "value" in the prop.</p>

<p>For any low-level, reusable UI component, you'll want to get the data in and out. Using a v-model and storing the data in a parent component is actually what you want to do. Storing the data in the root component feels clumsy, so often times there are mid-level components.</p>

<p>To demonstrate this, I made a list of nerds that can either be happy or sad and use your checkbox to update their state.</p>

Usage in Root Vue component

<pre class="lang-html prettyprint-override"><code><body>
  <script src="https://unpkg.com/vue@2.6.10"></script>
  <div id="app">
    <!-- If you wanted to take in data,
        you would pass in the nerds array as a Prop
        into nerd-list _from_ the root Vue instance -->
    <nerd-list/>
  </div>
</body>

<script>
  Vue.component('nerd-list', {
   template: '<div>
     <h1>List of nerds and if they are happy</h1>
     <div v-for="nerd in nerds" :key="nerd.id">
       {{ nerd.name }}
       <checkbox-item v-model="nerd.happy">Happy</checkbox-item>
     </div>
   </div>',
  data() {
    return {
      nerds: [
        { name: 'Jess', happy: true, id: 1 },
        { name: 'Tiffany', happy: true, id: 2 },
      ]
    };
  },
});

  Vue.component('checkbox-item', {
    template: `
          <label class="checkbox-item">
            <input type="checkbox" :checked="value"
                   @change="$emit('input', $event.target.checked)"
                   class="checkbox-input">
            <span class="checkbox-label">
              <slot></slot>
            </span>
          </label>
        `,
    props: ['value']
  })
  new Vue({
    el: '#app',
    data: {}, // any data in here could be used to pass props into the nerd-list.
  })
</script>
</code>```

Lastly, as you can tell, writing all of this in Javascript files might seem a bit cumbersome. I highly recommend using Vue CLI and Vue SFC components for a nicer experience.

Body:
I am creating a custom checkbox component in Vue, and it is working fine with the data being stored in the root instance. I plan to reuse this component (along with many other components I'm building) in a wide variety of cases. I do not want to have to update or edit the root Vue instance every time I use the component, and want to store the data ONLY in the component itself. The boolean value of checked/unchecked needs to be reactive.

I played around with using a computed value, but could not get that to work either. I am open to using this though if I need to.

(THIS VERSION DOES NOT WORK)

    <checkbox-item v-model="checkData">Active</checkbox-item>
    {{ checkData }}

(THIS VERSION WORKS, BUT AGAIN I NEED THE DATA TO NOT BE IN THE ROOT INSTANCE)

    <checkbox-item v-model="checkData">Active</checkbox-item>
    {{ checkData }}

The error I get is:

[Vue warn]: Property or method "checkData" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

And checkData is not reactive like it was in the working example.

EDIT: Okay, here's what works! I am definitely going to look into using SFC's and other code organization methods, but for now it's still in one html file. Does anyone see a reason this wouldn't work in the long run?

        <checkbox-item></checkbox-item>

Body:
The reason the first example one doesn't work is because your root Vue component doesn't have access to the checkbox's data.

<html>
<!-- Your existing nonfunctional example -->
<body>
  <script src="https://unpkg.com/vue@2.6.10"></script>
  <div id="app">
    <!-- Both v-model and {{ checkData }}
      are asking about the root vue's checkData,
      but you took that off. This is why you have an error -->
    <checkbox-item v-model="checkData">Active</checkbox-item>
    {{ checkData }}
  </div>
</body>

</html>

What's going on in the non-functional example?

When you say v-model="checkData" in the nonfunctional example, that's telling the Parent (Root) Vue component to find checkData in its local scope and v-bind:value="checkData" and v-on:input="checkData = $event.target.value"

Making your checkbox-item reusable

Your component is wonderfully reusable as-is.

The only change I would make to your checkbox-item is to pass v-on="$listeners" and v-bind="$attrs" through on the input element, and remove the explicit "value" in the prop.

For any low-level, reusable UI component, you'll want to get the data in and out. Using a v-model and storing the data in a parent component is actually what you want to do. Storing the data in the root component feels clumsy, so often times there are mid-level components.

To demonstrate this, I made a list of nerds that can either be happy or sad and use your checkbox to update their state.

Usage in Root Vue component

<body>
  <script src="https://unpkg.com/vue@2.6.10"></script>
  <div id="app">
    <!-- If you wanted to take in data,
        you would pass in the nerds array as a Prop
        into nerd-list _from_ the root Vue instance -->
    <nerd-list/>
  </div>
</body>

<script>
  Vue.component('nerd-list', {
   template: '<div>
     <h1>List of nerds and if they are happy</h1>
     <div v-for="nerd in nerds" :key="nerd.id">
       {{ nerd.name }}
       <checkbox-item v-model="nerd.happy">Happy</checkbox-item>
     </div>
   </div>',
  data() {
    return {
      nerds: [
        { name: 'Jess', happy: true, id: 1 },
        { name: 'Tiffany', happy: true, id: 2 },
      ]
    };
  },
});

  Vue.component('checkbox-item', {
    template: `
          <label class="checkbox-item">
            <input type="checkbox" :checked="value"
                   @change="$emit('input', $event.target.checked)"
                   class="checkbox-input">
            <span class="checkbox-label">
              <slot></slot>
            </span>
          </label>
        `,
    props: ['value']
  })
  new Vue({
    el: '#app',
    data: {}, // any data in here could be used to pass props into the nerd-list.
  })
</script>

Lastly, as you can tell, writing all of this in Javascript files might seem a bit cumbersome. I highly recommend using Vue CLI and Vue SFC components for a nicer experience.


问:
Can I build and compile an app built for jail broken iOS and run as a development app on my device?
Just a quick q about iOS development..

I'd love to be able to run a certain game emulator on my iPad..

If it's released under open source is there any thing stopping me from compiling it and running it in an emulator or getting a provisioning profile and running it on my device?

Do jailbroken apps tend to use libraries that wont run on a vanilla copy of iOS?

I.e. Do they patch the kernel to get full control of the video controller etc..

Thanks

Daniel

答:
I think the jailbroken apps can utilize eglibc or glibc, as when I jailbroke me iPod Touch, I remember looking over the installed packages, and remember seeing something along the lines of glibc.

In short, I think if the app is self-sufficient, you probably could package it with XCode, but if it requires some low-level APIs and libraries, you're out of luck.


问:
How to clone different rows of table with an unique event
Making an ordering app. There is a div with a table containing all products with for each the price and a button to select it. There is a second div which containing selected products. So, i clone the selected product to put it in the second div. It runs but i had to make an event for each products and i would like to create an unique function using button class name to do this.

I tried to create a for() with no results but i'm a js beginner and i'va issues with my syntax

HTML

```<code><h1>CHOOSE</h1>

<table id="starters">
          <tr>
            <th>PRODUCT</th>
            <th>PRICE</th>
            <th>ADD TO CART</th>
          </tr>
          <tr>
            <td>Cherry</td>
            <td>6</td>
            <td><button id="s1" class="item_button"></button></td>
          </tr>
          <tr>
            <td>Peach</td>
            <td>8</td>
            <td><button id="s2" class="item_button"></button></td>
          </tr>
          <tr>
            <td>Strawberry</td>
            <td>12</td>
            <td><button id="s3" class="item_button"></button></td>
          </tr>
          <tr>
            <td>Banana</td>
            <td>7</td>
            <td><button id="s4" class="item_button"></button></td>
          </tr>
          <tr>
            <td>Apple</td>
            <td>7</td>
            <td><button id="s5" class="item_button"></button></td>
        </tr>
</table>

<h1>YOUR CHOICE</h1>

<table id="products_cart">

</table>
</code>```

JAVASCRIPT

```<code>var s0ne = document.getElementById('s1');
var sTwo = document.getElementById('s2');
var sThree = document.getElementById('s3');
var sFour = document.getElementById('s4');
var sFive = document.getElementById('s5');
let boxes = document.getElementById("starters")
let basket = document.getElementById("products_cart")

s0ne.onclick = function() {
  let clone = boxes.getElementsByTagName("tr")[1].cloneNode(true);
  basket.appendChild(clone);
}

sTwo.onclick = function() {
  let clone = boxes.getElementsByTagName("tr")[2].cloneNode(true);
  basket.appendChild(clone);
}

sThree.onclick = function() {
  let clone = boxes.getElementsByTagName("tr")[3].cloneNode(true);
  basket.appendChild(clone);
}

sFour.onclick = function() {
  let clone = boxes.getElementsByTagName("tr")[4].cloneNode(true);
  basket.appendChild(clone);
}

sFive.onclick = function() {
  let clone = boxes.getElementsByTagName("tr")[5].cloneNode(true);
  basket.appendChild(clone);
}
</code>```

答:
Use this javascript code :      </p>

```<code>add = function(e)
      {
        choices = document.getElementById('products_cart');
        choices.innerHTML=choices.innerHTML+e.target.parentNode.parentNode.innerHTML;

      }
      products = document.querySelectorAll('.item_button');

      for(i=0;i<products.length;i++)
         products[i].addEventListener('click',add,false);
</code>```

Body:
Making an ordering app. There is a div with a table containing all products with for each the price and a button to select it. There is a second div which containing selected products. So, i clone the selected product to put it in the second div. It runs but i had to make an event for each products and i would like to create an unique function using button class name to do this.

I tried to create a for() with no results but i'm a js beginner and i'va issues with my syntax

HTML

CHOOSE

            PRODUCT
            PRICE
            ADD TO CART

            Cherry
            6
            <button id="s1" class="item_button"></button>

            Peach
            8
            <button id="s2" class="item_button"></button>

            Strawberry
            12
            <button id="s3" class="item_button"></button>

            Banana
            7
            <button id="s4" class="item_button"></button>

            Apple
            7
            <button id="s5" class="item_button"></button>

YOUR CHOICE

JAVASCRIPT

var s0ne = document.getElementById('s1');
var sTwo = document.getElementById('s2');
var sThree = document.getElementById('s3');
var sFour = document.getElementById('s4');
var sFive = document.getElementById('s5');
let boxes = document.getElementById("starters")
let basket = document.getElementById("products_cart")

s0ne.onclick = function() {
  let clone = boxes.getElementsByTagName("tr")[1].cloneNode(true);
  basket.appendChild(clone);
}

sTwo.onclick = function() {
  let clone = boxes.getElementsByTagName("tr")[2].cloneNode(true);
  basket.appendChild(clone);
}

sThree.onclick = function() {
  let clone = boxes.getElementsByTagName("tr")[3].cloneNode(true);
  basket.appendChild(clone);
}

sFour.onclick = function() {
  let clone = boxes.getElementsByTagName("tr")[4].cloneNode(true);
  basket.appendChild(clone);
}

sFive.onclick = function() {
  let clone = boxes.getElementsByTagName("tr")[5].cloneNode(true);
  basket.appendChild(clone);
}

Body:
Use this javascript code :

add = function(e)
      {
        choices = document.getElementById('products_cart');
        choices.innerHTML=choices.innerHTML+e.target.parentNode.parentNode.innerHTML;

      }
      products = document.querySelectorAll('.item_button');

      for(i=0;i<products.length;i++)
         products[i].addEventListener('click',add,false);


答:
Considering you can use jQuery:

let basket = document.getElementById("products_cart")

$('.item_button').on('click', function(e) {
 let target = $(e.currentTarget);
 let clone = target.parents('tr')[0].cloneNode(true);
 basket.appendChild(clone);
})
```

<p>Using pure JS, you could do something like this:</p>

<pre class="lang-js prettyprint-override"><code>let basket = document.getElementById("products_cart")

let buttons = document.querySelectorAll('.item_button');

for (button of buttons) {
 button.addEventListener('click', cloneLine);
}

function cloneLine(e) {
 let td = e.target.parentNode;
 let tr = td.parentNode;
 let clone = tr.cloneNode(true);
 basket.appendChild(clone);
}
</code>```

Title: How to clone different rows of table with an unique event

Body:
Considering you can use jQuery:

let basket = document.getElementById("products_cart")

$('.item_button').on('click', function(e) {
 let target = $(e.currentTarget);
 let clone = target.parents('tr')[0].cloneNode(true);
 basket.appendChild(clone);
})

Using pure JS, you could do something like this:

let basket = document.getElementById("products_cart")

let buttons = document.querySelectorAll('.item_button');

for (button of buttons) {
 button.addEventListener('click', cloneLine);
}

function cloneLine(e) {
 let td = e.target.parentNode;
 let tr = td.parentNode;
 let clone = tr.cloneNode(true);
 basket.appendChild(clone);
}


问:
PostgreSQL jsonb, `?` and JDBC
I am using PostgreSQL 9.4 and the awesome JSONB field type.  I am trying to query against a field in a document.  The following works in the psql CLI

SELECT id FROM program WHERE document -> 'dept' ? 'CS'
```

<p>When I try to run the same query via my Scala app, I'm getting the error below.  I'm using Play framework and Anorm, so the query looks like this</p>

<pre class="lang-scala prettyprint-override"><code>SQL(s"SELECT id FROM program WHERE document -> 'dept' ? {dept}")
.on('dept -> "CS")
....
</code>```

SQLException: : No value specified for parameter 5.
  (SimpleParameterList.java:223)

(in my actual queries there are more parameters)

I can get around this by casting my parameter to type jsonb and using the @> operator to check containment.

```<code>SQL(s"SELECT id FROM program WHERE document -> 'dept' @> {dept}::jsonb")
.on('dept -> "CS")
....
</code>```

I'm not too keen on the work around.   I don't know if there are performance penalties for the cast, but it's extra typing, and non-obvious.

Is there anything else I can do?

答:
As bob said just use ?? instead of ?

```<code>SQL(s"SELECT id FROM program WHERE document -> 'dept' ?? {dept}")
.on('dept -> "CS")
</code>```

Title: PostgreSQL jsonb, `?` and JDBC

Body:
I am using PostgreSQL 9.4 and the awesome JSONB field type.  I am trying to query against a field in a document.  The following works in the psql CLI

SELECT id FROM program WHERE document -> 'dept' ? 'CS'

When I try to run the same query via my Scala app, I'm getting the error below.  I'm using Play framework and Anorm, so the query looks like this

SQL(s"SELECT id FROM program WHERE document -> 'dept' ? {dept}")
.on('dept -> "CS")
....

SQLException: : No value specified for parameter 5.
  (SimpleParameterList.java:223)

(in my actual queries there are more parameters)

I can get around this by casting my parameter to type jsonb and using the @> operator to check containment.

SQL(s"SELECT id FROM program WHERE document -> 'dept' @> {dept}::jsonb")
.on('dept -> "CS")
....

I'm not too keen on the work around.   I don't know if there are performance penalties for the cast, but it's extra typing, and non-obvious.

Is there anything else I can do?

Body:
As bob said just use ?? instead of ?

SQL(s"SELECT id FROM program WHERE document -> 'dept' ?? {dept}")
.on('dept -> "CS")


问:
KWIC with lucene 3.1
I study Lucene and there's somtehing i still don't understand.
First, I use the last version of lucene, 3.1.

Then everything works fine but I keep failing to use the Highlighter and the Fragments.

Is anybody know how to use it in the last version?

Thank you and sorry for my english...

答:
We are using a FastVectorHighlighter to do the highlighting. You can have a look at the implementation on GitHub:
https://github.com/Letractively/gtxcontentconnector/blob/ad4c49d250f4ce22db000426f4cf195c1b773452/contentconnector/contentconnector-lucene/src/main/java/com/gentics/cr/lucene/search/highlight/WhitespaceVectorBolder.java</p>

Title: KWIC with lucene 3.1