问:
Two different DataTemplate
I have two ListBoxs defined in my XAML and one Class MyListItem.
Now one ListBox should display the name as button and the second ListBox should display the name as a TextBlock.

Here a little example, both ListBoxs behave the same.

MyListItem

```<code>public class MyListItem
{
    private string _name;
    public string Name
    {
        get{return _name;}
        set{_name = value;}
    }
}
</code>```

XAML

```<code><Window xmlns="https://github.com/avaloniaui"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:DataTemplate.Views.MainWindow"
    xmlns:viewsmodels="clr-namespace:DataTemplate.ViewModels;assembly=DataTemplate"
    xmlns:dt="clr-namespace:DataTemplate;assembly=DataTemplate"
    Title="DataTemplate" Width="700">
<Window.DataContext>
  <viewsmodels:MainWindowViewModel />
</Window.DataContext>
<Grid ColumnDefinitions="250,250,250">
  <ItemsControl Grid.Column="1" Items="{Binding List2}">
    <ItemsControl.DataTemplates>
      <DataTemplate DataType="{x:Type dt:MyListItem}">
        <TextBlock Text="{Binding Name}"/>
      </DataTemplate>
    </ItemsControl.DataTemplates>
  </ItemsControl>
  <ItemsControl Grid.Column="2" Items="{Binding List3}">
    <ItemsControl.DataTemplates>
      <DataTemplate DataType="{x:Type dt:MyListItem}">
        <Button Content="{Binding Name}"/>
      </DataTemplate>
    </ItemsControl.DataTemplates>
  </ItemsControl>
</Grid>
</Window>
</code>```

ViewMode

```<code>public class MainWindowViewModel
{
            public ObservableCollection<MyListItem> List1 { get; set; }
    public ObservableCollection<MyListItem> List2 { get; set; }
    public ObservableCollection<MyListItem> List3 { get; set; }

    public MainWindowViewModel()
    {
        List1 = new ObservableCollection<MyListItem>();
        List2 = new ObservableCollection<MyListItem>();
        List3 = new ObservableCollection<MyListItem>();

        Random rand = new Random();

        for (int i = 0; i < rand.Next(1, 20); i++)
        {
            MyListItem mli = new MyListItem();
            mli.Name = "ListItem" + i;
            List1.Add(mli);
        }

        for (int i = 0; i < rand.Next(1, 20); i++)
        {
            MyListItem mli = new MyListItem();
            mli.Name = "ListItem" + i;
            List2.Add(mli);
        }

        for (int i = 0; i < rand.Next(1, 20); i++)
        {
            MyListItem mli = new MyListItem();
            mli.Name = "ListItem" + i;
            List3.Add(mli);
        }
    }
}
</code>```

答:
You need to use ItemsControl instead of ListBox and have ItemTemplate set differently for each of them.

One will point to DataTemplate(using x:Key, not DataType) with TextBlock, and the other to DataTemplate with Button.

Title: Two different DataTemplate

Body:
I have two ListBoxs defined in my XAML and one Class MyListItem.
Now one ListBox should display the name as button and the second ListBox should display the name as a TextBlock.

Here a little example, both ListBoxs behave the same.

MyListItem

public class MyListItem
{
    private string _name;
    public string Name
    {
        get{return _name;}
        set{_name = value;}
    }
}

XAML

<Window xmlns="https://github.com/avaloniaui"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:DataTemplate.Views.MainWindow"
    xmlns:viewsmodels="clr-namespace:DataTemplate.ViewModels;assembly=DataTemplate"
    xmlns:dt="clr-namespace:DataTemplate;assembly=DataTemplate"
    Title="DataTemplate" Width="700">
<Window.DataContext>
  <viewsmodels:MainWindowViewModel />
</Window.DataContext>
<Grid ColumnDefinitions="250,250,250">
  <ItemsControl Grid.Column="1" Items="{Binding List2}">
    <ItemsControl.DataTemplates>
      <DataTemplate DataType="{x:Type dt:MyListItem}">
        <TextBlock Text="{Binding Name}"/>
      </DataTemplate>
    </ItemsControl.DataTemplates>
  </ItemsControl>
  <ItemsControl Grid.Column="2" Items="{Binding List3}">
    <ItemsControl.DataTemplates>
      <DataTemplate DataType="{x:Type dt:MyListItem}">
        <Button Content="{Binding Name}"/>
      </DataTemplate>
    </ItemsControl.DataTemplates>
  </ItemsControl>
</Grid>
</Window>

ViewMode

public class MainWindowViewModel
{
            public ObservableCollection<MyListItem> List1 { get; set; }
    public ObservableCollection<MyListItem> List2 { get; set; }
    public ObservableCollection<MyListItem> List3 { get; set; }

    public MainWindowViewModel()
    {
        List1 = new ObservableCollection<MyListItem>();
        List2 = new ObservableCollection<MyListItem>();
        List3 = new ObservableCollection<MyListItem>();

        Random rand = new Random();

        for (int i = 0; i < rand.Next(1, 20); i++)
        {
            MyListItem mli = new MyListItem();
            mli.Name = "ListItem" + i;
            List1.Add(mli);
        }

        for (int i = 0; i < rand.Next(1, 20); i++)
        {
            MyListItem mli = new MyListItem();
            mli.Name = "ListItem" + i;
            List2.Add(mli);
        }

        for (int i = 0; i < rand.Next(1, 20); i++)
        {
            MyListItem mli = new MyListItem();
            mli.Name = "ListItem" + i;
            List3.Add(mli);
        }
    }
}


来源: stackexchange

问:
JUCE unable to insert button on audio plugin
I'm attempting to add a button in an audio plugin, but can't seem to get it to display when testing.

I'm using the plugin host to test, and view the GUI. pad1 is defined in PluginEditor.h:

```<code>private:
    // This reference is provided as a quick way for your editor to
    // access the processor object that created it.
    CPAudioProcessor& processor;

    TextButton pad1;
</code>```

I've placed the following code in PluginEditor.cpp:

```<code>CPAudioProcessorEditor::CPAudioProcessorEditor (CPAudioProcessor& p)
    : AudioProcessorEditor (&p), processor (p)
{
    pad1.setColour(TextButton::buttonColourId, Colours::lime);
    pad1.setButtonText("Press Me!");
    addAndMakeVisible(pad1);

    // Make sure that before the constructor has finished, you've set the
    // editor's size to whatever you need it to be.
    setSize (400, 300);
}
</code>```

I was following this tutorial as a guide on how to add the button: https://www.juce.com/doc/tutorial_rectangle_advanced

Is there anything I'm missing? It looks the same as the code in the guide.

答:
The problem was I forgot to set the width/height in the overridden resized method.

```<code>void CPAudioProcessorEditor::resized()
{
    // This is generally where you'll want to lay out the positions of any
    // subcomponents in your editor..
    pad1.setBounds(10, 10, 100, 100);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm attempting to add a button in an audio plugin, but can't seem to get it to display when testing.

I'm using the plugin host to test, and view the GUI. pad1 is defined in PluginEditor.h:

private:
    // This reference is provided as a quick way for your editor to
    // access the processor object that created it.
    CPAudioProcessor& processor;

    TextButton pad1;

I've placed the following code in PluginEditor.cpp:

CPAudioProcessorEditor::CPAudioProcessorEditor (CPAudioProcessor& p)
    : AudioProcessorEditor (&p), processor (p)
{
    pad1.setColour(TextButton::buttonColourId, Colours::lime);
    pad1.setButtonText("Press Me!");
    addAndMakeVisible(pad1);

    // Make sure that before the constructor has finished, you've set the
    // editor's size to whatever you need it to be.
    setSize (400, 300);
}

I was following this tutorial as a guide on how to add the button: https://www.juce.com/doc/tutorial_rectangle_advanced

Is there anything I'm missing? It looks the same as the code in the guide.

Body:
The problem was I forgot to set the width/height in the overridden resized method.

void CPAudioProcessorEditor::resized()
{
    // This is generally where you'll want to lay out the positions of any
    // subcomponents in your editor..
    pad1.setBounds(10, 10, 100, 100);
}


问:
Quick and dirty solution for communication between processes in different machines
I have two processes written in java in two machines within my network that should pass simple chunks of data to each other.

I'm looking for a quick and dirty way (without resorting to writing files and polling for changes on network share files)

答:
What you have described is the quick (and not really that quick) and dirty way. The only other ways of accomplishing the task are setting up the processes to listen and send data through sockets (be that implemented directly by you - in java it is very easy, just Google and you will find, or as part of an library - probably needed for anything more complex)

So each process would have a listener on a specific port and every so often would send data across that port.

OwnerDisplayName: Dani

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Jamie


问:
Find() Method MongoDB with Nodejs
I'm currently trying to find all the documents that have a certain value of 'bar' in the key 'foo'. Using mongodb and nodejs.

When I try to run this I get:
 "TypeError: Cannot read property 'find' of undefined" error return.

If I try using findOne() it'll just return the first document that has the document with the value "bar" for the key "foo", however there are 3.

```<code>module.exports = function(app, db) {

app.get('/foo', (req, res)=>{

db.collection('barCollection').find({foo: {$all: ['bar']}}
,(err, item)=>{
 if (err) {
            res.send({'error':'An error has occurred'});
        } else {
            res.send(item);
        }
    });
 });
};
</code>```

Thanks

答:
Paul is right, there is some issue in your code which is why it's returning null.

Here try this snippet. I'm using 2 files for demo.

model.js

```<code>const mongoose = require('mongoose');

mongoose.connect('mongo_url');
var barSchema = new mongoose.Schema({
  // your schema
});

module.exports = mongoose.model('Bar', barSchema);
</code>```

main.js

```<code>var BarCollection = require('./models'); // assuming both files are in same directory.

BarCollection.find({foo: {$all: ['bar']}}
,(err, item)=>{
 if (err) {
            res.send({'error':'An error has occurred'});
        } else {
            res.send(item);
        }
    });
 });
};
</code>```

Basically what I am trying here is:

separate MongoDB model code in separate files

Import mongo collection in API files for CRUD operations

Title: Find() Method MongoDB with Nodejs

Body:
I'm currently trying to find all the documents that have a certain value of 'bar' in the key 'foo'. Using mongodb and nodejs.

When I try to run this I get:
 "TypeError: Cannot read property 'find' of undefined" error return.

If I try using findOne() it'll just return the first document that has the document with the value "bar" for the key "foo", however there are 3.

module.exports = function(app, db) {

app.get('/foo', (req, res)=>{

db.collection('barCollection').find({foo: {$all: ['bar']}}
,(err, item)=>{
 if (err) {
            res.send({'error':'An error has occurred'});
        } else {
            res.send(item);
        }
    });
 });
};

Thanks

Body:
Paul is right, there is some issue in your code which is why it's returning null.

Here try this snippet. I'm using 2 files for demo.

model.js

const mongoose = require('mongoose');

mongoose.connect('mongo_url');
var barSchema = new mongoose.Schema({
  // your schema
});

module.exports = mongoose.model('Bar', barSchema);

main.js

var BarCollection = require('./models'); // assuming both files are in same directory.

BarCollection.find({foo: {$all: ['bar']}}
,(err, item)=>{
 if (err) {
            res.send({'error':'An error has occurred'});
        } else {
            res.send(item);
        }
    });
 });
};

Basically what I am trying here is:

separate MongoDB model code in separate files

Import mongo collection in API files for CRUD operations


问:
I want to use aggregate function in attribute having integer name in it
I am using following mysql query in relation review(70,60,30) that is having attribute name with integer value

```<code>SELECT AVG(70) FROM `review`;
</code>```

But problem is that I am getting 70.0000 as answer which is not a correct one as it recognize 70 as value not a attribute name..

Plz help...

答:
If 70 is the name of a column, I encourage you to change the name!

```<code>alter table review change column `70` `value_70` . . . ;
</code>```

But, if you are stuck with it, use backticks:

```<code>SELECT AVG(`70`)
FROM review;
</code>```

Body:
I am using following mysql query in relation review(70,60,30) that is having attribute name with integer value

SELECT AVG(70) FROM `review`;

But problem is that I am getting 70.0000 as answer which is not a correct one as it recognize 70 as value not a attribute name..

Plz help...

Body:
If 70 is the name of a column, I encourage you to change the name!

alter table review change column `70` `value_70` . . . ;

But, if you are stuck with it, use backticks:

SELECT AVG(`70`)
FROM review;


问:
Target div and previous titles with jQuery
I have an HTML structure like this, and would like to move all the image galleries together with their corresponding titles and subtitles to a different position .image_content

```<code><h2>Some section</h2>
<p></p>
<p></p>
<p></p>

<h2>Some other section</h2>
<h3>Some sub-section</h3>
<p></p>
<p></p>
<p></p>

<h2>Planos</h2>
<div id='gallery-4' class='gallery'>
    <dl class='gallery-item'></dl>
    <dl class='gallery-item'></dl>
    <dl class='gallery-item'></dl>
    <dl class='gallery-item'></dl>
</div>

<h2>Fotos</h2>
<h3>Fotos archivo</h3>
<div id='gallery-5' class='gallery'>
    <dl class='gallery-item'></dl>
    <dl class='gallery-item'></dl>
    <dl class='gallery-item'></dl>
    <dl class='gallery-item'></dl>
</div>
</code>```

So far I've got this code to move the galleries:

```<code>$('.gallery').appendTo('.image_content');
</code>```

But I'm failing to also get the corresponding H2 and H3 titles. I've tried this but it's not working:

```<code>$('.gallery').prev('h2').appendTo('.image_content');
$('.gallery').appendTo('.image_content');
</code>```

This is the expected result (image_content already exists in another part of the code):

```<code><div class="image_content">
    <h2>Planos</h2>
    <div id='gallery-4' class='gallery'>
        <dl class='gallery-item'></dl>
        <dl class='gallery-item'></dl>
        <dl class='gallery-item'></dl>
        <dl class='gallery-item'></dl>
    </div>

    <h2>Fotos</h2>
    <h3>Fotos archivo</h3>
    <div id='gallery-5' class='gallery'>
        <dl class='gallery-item'></dl>
        <dl class='gallery-item'></dl>
        <dl class='gallery-item'></dl>
        <dl class='gallery-item'></dl>
    </div>
</div>
</code>```

答:
If you can change the html structure you can also add an enclosing tag to the galleries:

```<code><h2>Some section</h2>
<p></p>
<p></p>
<p></p>

<h2>Some other section</h2>
<h3>Some sub-section</h3>
<p></p>
<p></p>
<p></p>
<div>
  <h2>Planos</h2>
  <div id='gallery-4' class='gallery'>
      <dl class='gallery-item'></dl>
      <dl class='gallery-item'></dl>
      <dl class='gallery-item'></dl>
      <dl class='gallery-item'></dl>
  </div>
</div>

<div>
  <h2>Fotos</h2>
  <h3>Fotos archivo</h3>
  <div id='gallery-5' class='gallery'>
      <dl class='gallery-item'></dl>
      <dl class='gallery-item'></dl>
      <dl class='gallery-item'></dl>
      <dl class='gallery-item'></dl>
  </div>
</div>
</code>```

Which simplifies your addition:

```<code>$(".gallery").parent().children().appendTo(".image_content");
</code>```

It's important to note that this solution works if you only have the titles between the enclosing tags and the galleries

Body:
I have an HTML structure like this, and would like to move all the image galleries together with their corresponding titles and subtitles to a different position .image_content

Some section

Some other section

Some sub-section

Planos

Fotos

Fotos archivo

So far I've got this code to move the galleries:

$('.gallery').appendTo('.image_content');

But I'm failing to also get the corresponding H2 and H3 titles. I've tried this but it's not working:

$('.gallery').prev('h2').appendTo('.image_content');
$('.gallery').appendTo('.image_content');

This is the expected result (image_content already exists in another part of the code):

Planos

Fotos

Fotos archivo

Body:
If you can change the html structure you can also add an enclosing tag to the galleries:

<h2>Some section</h2>
<p></p>
<p></p>
<p></p>

<h2>Some other section</h2>
<h3>Some sub-section</h3>
<p></p>
<p></p>
<p></p>
<div>
  <h2>Planos</h2>
  <div id='gallery-4' class='gallery'>
      <dl class='gallery-item'></dl>
      <dl class='gallery-item'></dl>
      <dl class='gallery-item'></dl>
      <dl class='gallery-item'></dl>
  </div>
</div>

<div>
  <h2>Fotos</h2>
  <h3>Fotos archivo</h3>
  <div id='gallery-5' class='gallery'>
      <dl class='gallery-item'></dl>
      <dl class='gallery-item'></dl>
      <dl class='gallery-item'></dl>
      <dl class='gallery-item'></dl>
  </div>
</div>

Which simplifies your addition:

$(".gallery").parent().children().appendTo(".image_content");

It's important to note that this solution works if you only have the titles between the enclosing tags and the galleries


问:
Why do different versions of Silverlight assemblies have the same version number?
Why do different versions of Silverlight assemblies have the same version number?

```<code>Location: ...\Silverlight\v3.0\System.Core.dll
Name: System.Core, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e

Location: ...\Silverlight\v4.0\System.Core.dll
Name: System.Core, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e

Location: ...\Silverlight\v4.0\Profile\WindowsPhone\System.Core.dll
Name: System.Core, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e
</code>```

While standard .net has different version numbers

```<code>Location: ...\Framework\v4.0.30319\System.dll
Name: System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

Location: ...\Framework\v2.0.50727\System.dll
Name: System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
</code>```

答: I think it's the development team forgetting to change the version numbers and not having a check list, but I'm not 100% sure.  There is no mechanism that automates this task b/c there is no central compiler.  Each user in this development group can compile this code assembly as long as they have the strong name with the public key token.  I am interested in the complete answer from an expert on this subject.</p>

Body:
Why do different versions of Silverlight assemblies have the same version number?

Location: ...\Silverlight\v3.0\System.Core.dll
Name: System.Core, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e

Location: ...\Silverlight\v4.0\System.Core.dll
Name: System.Core, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e

Location: ...\Silverlight\v4.0\Profile\WindowsPhone\System.Core.dll
Name: System.Core, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e

While standard .net has different version numbers

Location: ...\Framework\v4.0.30319\System.dll
Name: System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

Location: ...\Framework\v2.0.50727\System.dll
Name: System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089


问:
Webpack: How can we *conditionally* use a plugin?
In Webpack, I have the following plugins:

```<code>plugins: [
        new ExtractTextPlugin('styles.css'),
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            },
            drop_console: true,
        }),
    ]
</code>```

I would like to apply the UglifyJsPlugin only for a specific target, so I tried using my intended conditional:

```<code>plugins: [
        new ExtractTextPlugin('styles.css'),
        (TARGET === 'build') && new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            },
            drop_console: true,
        }),
    ]
</code>```

However, this fails, showing the following error message:

```<code>E:\myProject\node_modules\tapable\lib\Tapable.js:164
            arguments[i].apply(this);
                         ^

TypeError: arguments[i].apply is not a function
</code>```

Note that the above code is similar to having false at the end of the plugins array (which emits the same error):

```<code>plugins: [
        new ExtractTextPlugin('styles.css'),
        false
    ]
</code>```

So, the question is:
Is there a way to have conditional plugins on Webpack? (other than using variables?)

答:
I push onto the plugins array given a condition in my webpack.config.js

```<code>const webpack = require('webpack');
const ExtractTextPlugin = require("extract-text-webpack-plugin");

module.exports = {
    entry: {
        ...
    },
    output: {
        ...
    },
    module: {
        rules: [
            ...
        ]
    },
    plugins: [
        new ExtractTextPlugin('styles.css'),
    ]
};

if (TARGET === 'build') {
    module.exports.plugins.push(
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            },
            drop_console: true,
        }),
    );
}
</code>```

Body:
In Webpack, I have the following plugins:

plugins: [
        new ExtractTextPlugin('styles.css'),
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            },
            drop_console: true,
        }),
    ]

I would like to apply the UglifyJsPlugin only for a specific target, so I tried using my intended conditional:

plugins: [
        new ExtractTextPlugin('styles.css'),
        (TARGET === 'build') && new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            },
            drop_console: true,
        }),
    ]

However, this fails, showing the following error message:

E:\myProject\node_modules\tapable\lib\Tapable.js:164
            arguments[i].apply(this);
                         ^

TypeError: arguments[i].apply is not a function

Note that the above code is similar to having false at the end of the plugins array (which emits the same error):

plugins: [
        new ExtractTextPlugin('styles.css'),
        false
    ]

So, the question is:
Is there a way to have conditional plugins on Webpack? (other than using variables?)

Body:
I push onto the plugins array given a condition in my webpack.config.js

const webpack = require('webpack');
const ExtractTextPlugin = require("extract-text-webpack-plugin");

module.exports = {
    entry: {
        ...
    },
    output: {
        ...
    },
    module: {
        rules: [
            ...
        ]
    },
    plugins: [
        new ExtractTextPlugin('styles.css'),
    ]
};

if (TARGET === 'build') {
    module.exports.plugins.push(
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            },
            drop_console: true,
        }),
    );
}

ContentLicense: CC BY-SA 4.0


问:
How can I create a seaborn regression plot with multiindex dataframe?
I have time series data which are multi-indexed on (Year, Month) as seen here:

```<code>print(df.index)
print(df)
</code>```

```<code>MultiIndex(levels=[[2016, 2017], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]],
           labels=[[0, 0, 0, 0, 0, 0, 0, 0], [2, 3, 4, 5, 6, 7, 8, 9]],
           names=['Year', 'Month'])
            Value
Year Month
2016 3       65.018150
     4       63.130035
     5       71.071254
     6       72.127967
     7       67.357795
     8       66.639228
     9       64.815232
     10      68.387698
</code>```

I want to do very basic linear regression on these time series data. Because pandas.DataFrame.plot does not do any regression, I intend to use Seaborn to do my plotting.

I attempted to do this by using lmplot:

```<code>sns.lmplot(x=("Year", "Month"), y="Value", data=df, fit_reg=True)
</code>```

but I get an error:

```<code>TypeError: '>' not supported between instances of 'str' and 'tuple'
</code>```

This is particularly interesting to me because all elements in df.index.levels[:] are of type numpy.int64, all elements in df.index.labels[:] are of type numpy.int8.

Why am I receiving this error? How can I resolve it?

答:
You can use reset_index to turn the dataframe's index into columns. Plotting DataFrames columns is then straight forward with seaborn.

As I guess the reason to use lmplot would be to show different regressions for different years (otherwise a regplot may be better suited), the "Year"column can be used as hue.

```<code>import numpy as np
import pandas as pd
import seaborn.apionly as sns
import matplotlib.pyplot as plt

iterables = [[2016, 2017], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]]
index = pd.MultiIndex.from_product(iterables, names=['Year', 'Month'])
df = pd.DataFrame({"values":np.random.rand(24)}, index=index)

df2 = df.reset_index()  # or, df.reset_index(inplace=True) if df is not required otherwise

g = sns.lmplot(x="Month", y="values", data=df2, hue="Year")

plt.show()
</code>```

Body:
I have time series data which are multi-indexed on (Year, Month) as seen here:

print(df.index)
print(df)

MultiIndex(levels=[[2016, 2017], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]],
           labels=[[0, 0, 0, 0, 0, 0, 0, 0], [2, 3, 4, 5, 6, 7, 8, 9]],
           names=['Year', 'Month'])
            Value
Year Month
2016 3       65.018150
     4       63.130035
     5       71.071254
     6       72.127967
     7       67.357795
     8       66.639228
     9       64.815232
     10      68.387698

I want to do very basic linear regression on these time series data. Because pandas.DataFrame.plot does not do any regression, I intend to use Seaborn to do my plotting.

I attempted to do this by using lmplot:

sns.lmplot(x=("Year", "Month"), y="Value", data=df, fit_reg=True)

but I get an error:

TypeError: '>' not supported between instances of 'str' and 'tuple'

This is particularly interesting to me because all elements in df.index.levels[:] are of type numpy.int64, all elements in df.index.labels[:] are of type numpy.int8.

Why am I receiving this error? How can I resolve it?

Body:
You can use reset_index to turn the dataframe's index into columns. Plotting DataFrames columns is then straight forward with seaborn.

As I guess the reason to use lmplot would be to show different regressions for different years (otherwise a regplot may be better suited), the "Year"column can be used as hue.

import numpy as np
import pandas as pd
import seaborn.apionly as sns
import matplotlib.pyplot as plt

iterables = [[2016, 2017], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]]
index = pd.MultiIndex.from_product(iterables, names=['Year', 'Month'])
df = pd.DataFrame({"values":np.random.rand(24)}, index=index)

df2 = df.reset_index()  # or, df.reset_index(inplace=True) if df is not required otherwise

g = sns.lmplot(x="Month", y="values", data=df2, hue="Year")

plt.show()


问:
How can I eject the CD-ROM drive with Dragon NaturallySpeaking's advanced scripting?
Is there any way to eject  the CD-ROM drive with Dragon NaturallySpeaking's advanced scripting?</p>

答:
You can use the  Windows Multimedia API (also known as WinMM):

```<code>' From Larry Allen
' https://www.knowbrainer.com/forums/forum/messageview.cfm?catid=12&threadid=12153&highlight_key=y&keyword1=eject
' http://archive.is/Y2ouS
' Tested with Dragon NaturallySpeaking 12.5 with Windows 7 SP1 x64 Ultimate
Declare Sub mciSendStringA Lib "winmm.dll" (ByVal lpstrCommand As String, _
ByVal lpstrReturnString As String, ByVal uReturnLength As Long, _
ByVal hWndCallback As Long)

Sub Main
Dim dummy As String
    mciSendStringA "Set CDAudio Door Open", dummy, 0, 0
End Sub
</code>```

source (mirror)

Body:
You can use the  Windows Multimedia API (also known as WinMM):

' From Larry Allen
' https://www.knowbrainer.com/forums/forum/messageview.cfm?catid=12&threadid=12153&highlight_key=y&keyword1=eject
' http://archive.is/Y2ouS
' Tested with Dragon NaturallySpeaking 12.5 with Windows 7 SP1 x64 Ultimate
Declare Sub mciSendStringA Lib "winmm.dll" (ByVal lpstrCommand As String, _
ByVal lpstrReturnString As String, ByVal uReturnLength As Long, _
ByVal hWndCallback As Long)

Sub Main
Dim dummy As String
    mciSendStringA "Set CDAudio Door Open", dummy, 0, 0
End Sub

source (mirror)


问:
javascript date difference
I've looked at: Get difference between 2 dates in javascript?

And I still can't get this to work.

```<code>var difference = data.List[0].EndDate - Math.round(new Date().getTime()/1000.0) * 1000;
var daysRemaining = Math.floor(difference / 1000 / 60 / 60 / 24);
var hoursRemaining = Math.floor(difference / 1000 / 60 / 60 - (24 * daysRemaining));
var minutesRemaining = Math.floor(difference / 1000 / 60 - (24 * 60 * daysRemaining) - (60 * hoursRemaining));
var secondsRemaining = Math.floor(difference / 1000 - (24 * 60 * 60 * daysRemaining) - (60 * 60 * hoursRemaining) - (60 * minutesRemaining));
</code>```

data.List[0].EndDate is a UTC number (like: 1291427809310 (http://www.epochconverter.com/)) that will always be later than the current date.

答:
You say that UTC timestamp is "2004-09-16T23:59:58.75"?

So you are basically doing

```<code>var x = "2004-09-16T23:59:58.75" - 123456
</code>```

Now that you clarified that, than the above does not apply. You new issue is the number of milliseconds is in the past so when you do the difference calculation, you are getting a negative number. You probably want to swap the order around.

```<code>var difference = new Date().getTime()-data.List[0].EndDate;
</code>```

Title: javascript date difference

Body:
I've looked at: Get difference between 2 dates in javascript?

And I still can't get this to work.

var difference = data.List[0].EndDate - Math.round(new Date().getTime()/1000.0) * 1000;
var daysRemaining = Math.floor(difference / 1000 / 60 / 60 / 24);
var hoursRemaining = Math.floor(difference / 1000 / 60 / 60 - (24 * daysRemaining));
var minutesRemaining = Math.floor(difference / 1000 / 60 - (24 * 60 * daysRemaining) - (60 * hoursRemaining));
var secondsRemaining = Math.floor(difference / 1000 - (24 * 60 * 60 * daysRemaining) - (60 * 60 * hoursRemaining) - (60 * minutesRemaining));

data.List[0].EndDate is a UTC number (like: 1291427809310 (http://www.epochconverter.com/)) that will always be later than the current date.

Body:
You say that UTC timestamp is "2004-09-16T23:59:58.75"?

So you are basically doing

var x = "2004-09-16T23:59:58.75" - 123456

Now that you clarified that, than the above does not apply. You new issue is the number of milliseconds is in the past so when you do the difference calculation, you are getting a negative number. You probably want to swap the order around.

var difference = new Date().getTime()-data.List[0].EndDate;


问:
AWS paperclip Rails. Working but when I upload image it updated all objects in Heroku
I've update my Rails app to store uploaded images in an AWS bucket when in production mode. It's working fine and I can see the image getting uploaded to AWS when using (Heroku). One thing however, When I update or create a new course the image uploaded becomes the image across all courses in the application. How do I distinguish the view to locate the particular image for each course? When I see the url for each image there is a different identifier at the end of the url for each image. So it is not the same image but looks like it's just being copied across all images in AWS or something. Any pointers in the right direction will be much appreciated. Thanks lads.

production.rb

```<code>        config.paperclip_defaults = {
        storage: :s3,
        s3_credentials: {
            bucket: ENV.fetch('S3_BUCKET_NAME'),
            access_key_id: ENV.fetch('AWS_ACCESS_KEY_ID'),
            secret_access_key: ENV.fetch('AWS_SECRET_ACCESS_KEY')
        },
        s3_host_name: "s3-eu-west-1.amazonaws.com", # Added entry
        url: ":s3_host_name",
        s3_region: 'eu-west-1' # Added entry
    }
</code>```

Not sure what other code is relevant here in my application. I'll add as requested. Thanks.

答:
Add to config/production.rb file

```<code># config/environments/production.rb
    config.paperclip_defaults = {
        storage: :s3,
        s3_host_name: "s3-eu-west-1.amazonaws.com",
        url: ':s3_domain_url',
        path: "/:class/:attachment/:id_partition/:style/:filename",
        s3_region: 'eu-west-1',
        s3_credentials: {
            bucket: ENV.fetch('S3_BUCKET_NAME'),
            access_key_id: ENV.fetch('AWS_ACCESS_KEY_ID'),
            secret_access_key: ENV.fetch('AWS_SECRET_ACCESS_KEY')
        }
    }
</code>```

So notice the changes I've made. I now call the url: ':s3_domain_url'  and match that with the path: key. This allows each image to be stored uniquely. Whereas previously it was saving to s3_host_name and this was saving the image over the last saved and nothing being unique.

Anyways simple enough to sort once I understood it a bit better. Hope this helps somebody down the line.

Body:
I've update my Rails app to store uploaded images in an AWS bucket when in production mode. It's working fine and I can see the image getting uploaded to AWS when using (Heroku). One thing however, When I update or create a new course the image uploaded becomes the image across all courses in the application. How do I distinguish the view to locate the particular image for each course? When I see the url for each image there is a different identifier at the end of the url for each image. So it is not the same image but looks like it's just being copied across all images in AWS or something. Any pointers in the right direction will be much appreciated. Thanks lads.

production.rb

        config.paperclip_defaults = {
        storage: :s3,
        s3_credentials: {
            bucket: ENV.fetch('S3_BUCKET_NAME'),
            access_key_id: ENV.fetch('AWS_ACCESS_KEY_ID'),
            secret_access_key: ENV.fetch('AWS_SECRET_ACCESS_KEY')
        },
        s3_host_name: "s3-eu-west-1.amazonaws.com", # Added entry
        url: ":s3_host_name",
        s3_region: 'eu-west-1' # Added entry
    }

Not sure what other code is relevant here in my application. I'll add as requested. Thanks.

Body:
Add to config/production.rb file

# config/environments/production.rb
    config.paperclip_defaults = {
        storage: :s3,
        s3_host_name: "s3-eu-west-1.amazonaws.com",
        url: ':s3_domain_url',
        path: "/:class/:attachment/:id_partition/:style/:filename",
        s3_region: 'eu-west-1',
        s3_credentials: {
            bucket: ENV.fetch('S3_BUCKET_NAME'),
            access_key_id: ENV.fetch('AWS_ACCESS_KEY_ID'),
            secret_access_key: ENV.fetch('AWS_SECRET_ACCESS_KEY')
        }
    }

So notice the changes I've made. I now call the url: ':s3_domain_url'  and match that with the path: key. This allows each image to be stored uniquely. Whereas previously it was saving to s3_host_name and this was saving the image over the last saved and nothing being unique.

Anyways simple enough to sort once I understood it a bit better. Hope this helps somebody down the line.


问:
Why REST API method name important? Because I can use any of those method to perform CRUD operation
In REST full API has some method name like (GET, PUT, POST etc.) for some specific operation (CRUD)
But I can perform any operation using any of the methods

Example for DB operations:

I can create or insert a new document or delete or update using GET
 method.

I can post or update or delete using POST method.

I can delete or update or delete using PUT method.

the same way I can use any of this method to perform DB (CRUD) operation

So, Why need this method to specify when we call any rest full API?

答:
To expand on Matías's answer, you have to think about the consequences of allowing consumers to call your API using any verb they wanted.

Firstly, your implementation is going to be more complex if you never know what operation is going to be expected.  For example, if someone can update a resource using GET, how do you tell the difference between a query and an update?  The answer: extra (needless) complexity of the implementation.

Secondly, there are consequences from the point-of-view of performance and scalability.  GET allows easy caching of resource representations because of its idempotent nature - which is the expected convention.  By not making it clear which verbs do what, you're making it harder to utilise strategies such as caching, which makes your API harder to scale.

Thirdly, it makes things more complicated for consumers.  HTTP's convention-based approach is widely understood.  Working with an API that doesn't follow that convention - especially one that labels itself as using HTTP/REST - is going to increase integration costs.


问:
Loop over checkboxes in PHP
I have a checkbox in each table row, and I would like to press the "Save" which will loop over each checkbox:
(if checked)-> enter to database that this student has attended
else ->enter to database that this student has not attended.

My PHP code:

```<code><table border="1" cellpadding="1" width="550px" style="text-align:center;">
    <th> Student ID </th>
    <th> First Name </th>
    <th> Last Name </th>
    <th> Class ID </th>
    <th> Attended </th>
<?php
    $classid = $_GET['classid'];

    $mysql_host='localhost';
    $mysql_user='root';
    $mysql_password='';
    $con = @mysqli_connect($mysql_host,$mysql_user,$mysql_password);

    if(!$con){
        die('Failed to connect to the database');//if not successful
    }else{
        //echo "Successfully connected to MySQL!";//if successful
        if(@mysqli_select_db($con, 'application_database')){//selecting the database
            //echo '<br>'."Connected to the specified database!";
        }else{
            die('<br>'."Could not connect to the specified database!");
        }
    }

    $sql="SELECT * FROM `student` WHERE class = '$classid'";
    $records=mysqli_query($con,$sql);

    while($student=mysqli_fetch_assoc($records)){

        echo "<tr>";
        echo "<td>".$student['id']."</td>";
        echo "<td>".$student['first_name']."</td>";
        echo "<td>".$student['last_name']."</td>";
        echo "<td>".$student['class']."</td>";
        echo "<td>".'<input type="checkbox" name="attendedCB">'."</td>";
    }

    echo '<form>';
    echo 'Teacher ID: <input type="number" name=teacher_id>';
    echo '<button name="save" type="submit">Save Attendance</button>';
    echo '</form>';

?>
</table>
</code>```

I have a "student_attendance" table in the db, so I want to add each student along with his/her "attended" checkbox status. Cheers :D

答:
Use id as value of check box by clicking that get the id value.
Based on the id value you can do operations(update, delete, edit)</p>

```<code>echo "<td><input type='checkbox' name='attendedCB' value ='.$student["id"].'></td>";
</code>```

Title: Loop over checkboxes in PHP

Body:
I have a checkbox in each table row, and I would like to press the "Save" which will loop over each checkbox:
(if checked)-> enter to database that this student has attended
else ->enter to database that this student has not attended.

My PHP code:

     Student ID
     First Name
     Last Name
     Class ID
     Attended
<?php
    $classid = $_GET['classid'];

    $mysql_host='localhost';
    $mysql_user='root';
    $mysql_password='';
    $con = @mysqli_connect($mysql_host,$mysql_user,$mysql_password);

    if(!$con){
        die('Failed to connect to the database');//if not successful
    }else{
        //echo "Successfully connected to MySQL!";//if successful
        if(@mysqli_select_db($con, 'application_database')){//selecting the database
            //echo '
'."Connected to the specified database!";
        }else{
            die('
'."Could not connect to the specified database!");
        }
    }

    $sql="SELECT * FROM `student` WHERE class = '$classid'";
    $records=mysqli_query($con,$sql);

    while($student=mysqli_fetch_assoc($records)){

        echo "
";
        echo "".$student['id']."	";
        echo "".$student['first_name']."	";
        echo "".$student['last_name']."	";
        echo "".$student['class']."	";
        echo "".'<input type="checkbox" name="attendedCB">'."	";
    }

    echo '<form>';
    echo 'Teacher ID: <input type="number" name=teacher_id>';
    echo '<button name="save" type="submit">Save Attendance</button>';
    echo '</form>';

?>

I have a "student_attendance" table in the db, so I want to add each student along with his/her "attended" checkbox status. Cheers :D

Body:
Use id as value of check box by clicking that get the id value.
Based on the id value you can do operations(update, delete, edit)

echo "<td><input type='checkbox' name='attendedCB' value ='.$student["id"].'></td>";


问:
Websphere + Tomcat : CertificateException
I have 2 applications deployed on 2 different servers where my GUI
 application is on Tomcat and CAS(central authentication) on Websphere. I have created keystore file and updated the same in server.xml in tomcat conf.

Please find the entries below.

Tomcat:

```<code><Environment name="config/centralCasServerLoginURL"
type="java.lang.String" value="https://localhost:9443/my-sso-web/login?
method=POST"/>
Tomcat: <Environment name="config/applicationServiceURL"
type="java.lang.String" value="https://localhost:8443/bank-client-
web/j_spring_cas_security_check"/>*
</code>```

and

```<code><Connector SSLEnabled="true" clientAuth="false"
keystoreFile="C:\tmp\newKeystore1"
         keystorePass="password" maxThreads="200" port="8443"
         protocol="org.apache.coyote.http11.Http11NioProtocol" scheme="https"
secure="true" sslProtocol="TLS"/>*
</code>```

I am able to run both the application individually but when I configured CASAuthentication profile in that time I am able to login CAS but after it redirected to my GUI application URL (i.e. https://localhost:8443/bank-client-web/j_spring_cas_security_check) it is throwing below error.

Could you please help me with that?

```<code>SEVERE: Servlet.service() for servlet [default] in context with path [/bank-
client-web] threw exception
java.lang.RuntimeException: javax.net.ssl.SSLHandshakeException:
java.security.cert.CertificateException: No name matching localhost found
    at org.jasig.cas.client.util.CommonUtils.getResponseFromServer(CommonUtils.java:295)
    at org.jasig.cas.client.validation.AbstractCasProtocolUrlBasedTicketValidator.retrieveResponseFromServer(AbstractCasProtocolUrlBasedTicketValidator.java:33)
    at org.jasig.cas.client.validation.AbstractUrlBasedTicketValidator.validate(AbstractUrlBasedTicketValidator.java:178)
    at org.springframework.security.cas.authentication.CasAuthenticationProvider.authenticateNow(CasAuthenticationProvider.java:131)
    at org.springframework.security.cas.authentication.CasAuthenticationProvider.authenticate(CasAuthenticationProvider.java:117)
    at org.springframework.security.authentication.ProviderManager.doAuthentication(ProviderManager.java:130)
Caused by: javax.net.ssl.SSLHandshakeException:
java.security.cert.CertificateException: No name matching localhost found
    at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
    at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1949)
    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:302)
Caused by: java.security.cert.CertificateException: No name matching localhost found
    at sun.security.util.HostnameChecker.matchDNS(HostnameChecker.java:221)
    at sun.security.util.HostnameChecker.match(HostnameChecker.java:95)
    ... 55 more
</code>```

答:
This is simply your client-side library peforming strict hostname verification, comparing "localhost" in the URL to the hosts WebSphere's certificate is valid for.

Simplest fix is to address this server by it's actual hostname rather than localhost.

Body:
I have 2 applications deployed on 2 different servers where my GUI
 application is on Tomcat and CAS(central authentication) on Websphere. I have created keystore file and updated the same in server.xml in tomcat conf.

Please find the entries below.

Tomcat:

<Environment name="config/centralCasServerLoginURL"
type="java.lang.String" value="https://localhost:9443/my-sso-web/login?
method=POST"/>
Tomcat: <Environment name="config/applicationServiceURL"
type="java.lang.String" value="https://localhost:8443/bank-client-
web/j_spring_cas_security_check"/>*

and

<Connector SSLEnabled="true" clientAuth="false"
keystoreFile="C:\tmp\newKeystore1"
         keystorePass="password" maxThreads="200" port="8443"
         protocol="org.apache.coyote.http11.Http11NioProtocol" scheme="https"
secure="true" sslProtocol="TLS"/>*

I am able to run both the application individually but when I configured CASAuthentication profile in that time I am able to login CAS but after it redirected to my GUI application URL (i.e. https://localhost:8443/bank-client-web/j_spring_cas_security_check) it is throwing below error.

Could you please help me with that?

SEVERE: Servlet.service() for servlet [default] in context with path [/bank-
client-web] threw exception
java.lang.RuntimeException: javax.net.ssl.SSLHandshakeException:
java.security.cert.CertificateException: No name matching localhost found
    at org.jasig.cas.client.util.CommonUtils.getResponseFromServer(CommonUtils.java:295)
    at org.jasig.cas.client.validation.AbstractCasProtocolUrlBasedTicketValidator.retrieveResponseFromServer(AbstractCasProtocolUrlBasedTicketValidator.java:33)
    at org.jasig.cas.client.validation.AbstractUrlBasedTicketValidator.validate(AbstractUrlBasedTicketValidator.java:178)
    at org.springframework.security.cas.authentication.CasAuthenticationProvider.authenticateNow(CasAuthenticationProvider.java:131)
    at org.springframework.security.cas.authentication.CasAuthenticationProvider.authenticate(CasAuthenticationProvider.java:117)
    at org.springframework.security.authentication.ProviderManager.doAuthentication(ProviderManager.java:130)
Caused by: javax.net.ssl.SSLHandshakeException:
java.security.cert.CertificateException: No name matching localhost found
    at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
    at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1949)
    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:302)
Caused by: java.security.cert.CertificateException: No name matching localhost found
    at sun.security.util.HostnameChecker.matchDNS(HostnameChecker.java:221)
    at sun.security.util.HostnameChecker.match(HostnameChecker.java:95)
    ... 55 more


问:
Node.js clustering with socket.io and mysql sessionstore
I'm trying to cluster a node app that runs with mysql, mysql session store and massive usage of socket.io.
I was looking for a way to adapt the socket.io session storage in mysql but i only found some redis adapter (following this guidelines : https://github.com/elad/node-cluster-socket.io)

Is there a way to implement node clustering with socket.io and mysql without installing redis ?

答: Have you tried using this module? https://www.npmjs.com/package/socket.io-mysql-session If it does not satisfy you, you will have to make your own socket.io session manager.This will not take more than 2-3 hours. I believe mysql is not exactly what you want to use to store socket.io data as a user is lost in every refresh meaning that a caching mechanism like redis is a better choice to use overall </p>


问:
Objective C version of the unix "finger" command
I'm trying to check the time since last login in my Cocoa app. I would like to do it without having to do something like this:

```<code>NSTask *task;
task = [[NSTask alloc] init];
[task setLaunchPath: @"/usr/bin/finger"];

NSArray *arguments;
arguments = [NSArray arrayWithObject: NSUserName()];
[task setArguments: arguments];

NSPipe *pipe;
pipe = [NSPipe pipe];
[task setStandardOutput: pipe];

NSFileHandle *file;
file = [pipe fileHandleForReading];

[task launch];

NSData *data;
data = [file readDataToEndOfFile];

NSString *stringData = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog (@"%@", stringData);
</code>```

For example, the Unix whoami command has the NSUserName Objective C equivalent.

答:
This was a really interesting question! Thanks for asking. :)

As for the answer, I went and found the source to finger and with it came up with the following:

```<code>#import <utmpx.h>

struct utmpx *user;
setutxent();
while ((user = getutxent()) != NULL) {
    if (user->ut_type == USER_PROCESS) {
        time_t loggedIn = user->ut_tv.tv_sec;
        NSDate * d = [NSDate dateWithTimeIntervalSince1970:loggedIn];
        NSLog(@"%s logged in at %@", user->ut_user, d);
    }
}
endutxent();
</code>```

On my computer, this logs:

```<code>dave logged in at 2010-12-06 09:59:13 -0800
dave logged in at 2010-12-13 19:14:20 -0800
</code>```

This matches the output of finger dave in Terminal:

```<code>Login: dave                     Name: Dave DeLong
Directory: /Users/dave                  Shell: /bin/bash
On since Mon Dec  6 09:59 (PST) on console, idle 7 days 9:18 (messages off)
On since Mon Dec 13 19:14 (PST) on ttys000
On since Thu Dec  9 17:21 (PST) on ttys001 (messages off)
</code>```

Body:
I'm trying to check the time since last login in my Cocoa app. I would like to do it without having to do something like this:

NSTask *task;
task = [[NSTask alloc] init];
[task setLaunchPath: @"/usr/bin/finger"];

NSArray *arguments;
arguments = [NSArray arrayWithObject: NSUserName()];
[task setArguments: arguments];

NSPipe *pipe;
pipe = [NSPipe pipe];
[task setStandardOutput: pipe];

NSFileHandle *file;
file = [pipe fileHandleForReading];

[task launch];

NSData *data;
data = [file readDataToEndOfFile];

NSString *stringData = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog (@"%@", stringData);

For example, the Unix whoami command has the NSUserName Objective C equivalent.

Body:
This was a really interesting question! Thanks for asking. :)

As for the answer, I went and found the source to finger and with it came up with the following:

#import <utmpx.h>

struct utmpx *user;
setutxent();
while ((user = getutxent()) != NULL) {
    if (user->ut_type == USER_PROCESS) {
        time_t loggedIn = user->ut_tv.tv_sec;
        NSDate * d = [NSDate dateWithTimeIntervalSince1970:loggedIn];
        NSLog(@"%s logged in at %@", user->ut_user, d);
    }
}
endutxent();

On my computer, this logs:

dave logged in at 2010-12-06 09:59:13 -0800
dave logged in at 2010-12-13 19:14:20 -0800

This matches the output of finger dave in Terminal:

Login: dave                     Name: Dave DeLong
Directory: /Users/dave                  Shell: /bin/bash
On since Mon Dec  6 09:59 (PST) on console, idle 7 days 9:18 (messages off)
On since Mon Dec 13 19:14 (PST) on ttys000
On since Thu Dec  9 17:21 (PST) on ttys001 (messages off)


问:
Resetting generator object in Python
I have a generator object returned by multiple yield. Preparation to call this generator is rather time-consuming operation. That is why I want to reuse the generator several times.

```<code>y = FunctionWithYield()
for x in y: print(x)
#here must be something to reset 'y'
for x in y: print(x)
</code>```

Of course, I'm taking in mind copying content into simple list. Is there a way to reset my generator?

See also: How to look ahead one element (peek) in a Python generator?

答:
There is no option to reset iterators. Iterator usually pops out when it iterate through next() function. Only way is to take a backup before iterate on the iterator object. Check below.

Creating iterator object with items 0 to 9

```<code>i=iter(range(10))
</code>```

Iterating through next() function which will pop out

```<code>print(next(i))
</code>```

Converting the iterator object to list

```<code>L=list(i)
print(L)
output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
</code>```

so item 0 is already popped out. Also all the items are popped as we converted the iterator to list.

```<code>next(L)

Traceback (most recent call last):
  File "<pyshell#129>", line 1, in <module>
    next(L)
StopIteration
</code>```

So you need to convert the iterator to lists for backup before start iterating.
List could be converted to iterator with iter(<list-object>)

Title: Resetting generator object in Python

Body:
I have a generator object returned by multiple yield. Preparation to call this generator is rather time-consuming operation. That is why I want to reuse the generator several times.

y = FunctionWithYield()
for x in y: print(x)
#here must be something to reset 'y'
for x in y: print(x)

Of course, I'm taking in mind copying content into simple list. Is there a way to reset my generator?

See also: How to look ahead one element (peek) in a Python generator?

Body:
There is no option to reset iterators. Iterator usually pops out when it iterate through next() function. Only way is to take a backup before iterate on the iterator object. Check below.

Creating iterator object with items 0 to 9

i=iter(range(10))

Iterating through next() function which will pop out

print(next(i))

Converting the iterator object to list

L=list(i)
print(L)
output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

so item 0 is already popped out. Also all the items are popped as we converted the iterator to list.

next(L)

Traceback (most recent call last):
  File "<pyshell#129>", line 1, in <module>
    next(L)
StopIteration

So you need to convert the iterator to lists for backup before start iterating.
List could be converted to iterator with iter(<list-object>)


问:
Tilemap from Tiled not rendering in Phaser
I'm stuck in a rut with this game I'm trying to make. The tilemap I'm trying to use has an error stating as follows

```<code>Error 1: "Phaser.Tileset - image tile area is not an even multiple of tile size"
Error 2: "Uncaught TypeError: Cannot read property '2' of undefined"
Error 3: "Uncaught TypeError: Cannot read property 'type' of undefined"2
</code>```

Here is a link to the code I'm using. http://pastebin.com/Dv00KGii

答: Try embedding tileset in your tilemap. For me this fixed this eror: Uncaught TypeError: Cannot read property '2' of undefined"

Body:
I'm stuck in a rut with this game I'm trying to make. The tilemap I'm trying to use has an error stating as follows

Error 1: "Phaser.Tileset - image tile area is not an even multiple of tile size"
Error 2: "Uncaught TypeError: Cannot read property '2' of undefined"
Error 3: "Uncaught TypeError: Cannot read property 'type' of undefined"2

Here is a link to the code I'm using. http://pastebin.com/Dv00KGii


问:
md-no-focus-style does not work properly in my setup
I have a button to open my navbar:

And after I click it it get's some kind of hitmarker:

After clicking on some navbar item (thus switching to next state/view) the hitmarker should disappear. Unforunately the hitmarker is present till I click on a random element.

The html for the button:

```<code><div ng-controller="navbarCtrl" ng-cloak>
  <md-content>
    <md-toolbar>
      <div class="md-toolbar-tools">
        <md-button class="md-icon-button" ng-click="toggleMenu()" aria-label="Menu">
          <md-icon md-svg-icon="assets/img/menu.svg"></md-icon>
        </md-button>
        <h2>
          <span><a ui-sref="overview">Test</a></span>
        </h2>
        <span flex></span>
        <md-button class="md-icon-button" ui-sref="account" aria-label="Account">
          <md-icon md-svg-icon="assets/img/account.svg"></md-icon>
        </md-button>
      </div>
    </md-toolbar>

  </md-content>

  <section layout="row" flex>
    <md-sidenav class="md-sidenav-left md-whiteframe-z2" md-component-id="left">
      <md-toolbar class="md-theme-indigo" layout="row">
        <h1 class="md-toolbar-tools">Menu</h1>
        <span flex></span>
        <md-button class="md-icon-button" aria-label="close" ng-click="close()">
          <md-icon md-svg-icon="assets/img/closeNavbar.svg"></md-icon>
        </md-button>
      </md-toolbar>
      <div layout="column" layout-align=" center">
        <md-button ui-sref-active="active" ng-click="close()" layout-align=" center" style="text-align:left" ui-sref="overview">Overview</md-button>
      </div>
    </md-sidenav>

  </section>

</div>
<div ui-view></div>
</code>```

What do I have to change in order to fix this?

答:
You need this in your CSS:</p>

```<code>.md-focused {
    background: transparent !important;
}
</code>```

Body:
I have a button to open my navbar:

And after I click it it get's some kind of hitmarker:

After clicking on some navbar item (thus switching to next state/view) the hitmarker should disappear. Unforunately the hitmarker is present till I click on a random element.

The html for the button:

  <md-content>
    <md-toolbar>

        <md-button class="md-icon-button" ng-click="toggleMenu()" aria-label="Menu">
          <md-icon md-svg-icon="assets/img/menu.svg"></md-icon>
        </md-button>

          Test

        <md-button class="md-icon-button" ui-sref="account" aria-label="Account">
          <md-icon md-svg-icon="assets/img/account.svg"></md-icon>
        </md-button>

    </md-toolbar>

  </md-content>

    <md-sidenav class="md-sidenav-left md-whiteframe-z2" md-component-id="left">
      <md-toolbar class="md-theme-indigo" layout="row">

Menu

        <md-button class="md-icon-button" aria-label="close" ng-click="close()">
          <md-icon md-svg-icon="assets/img/closeNavbar.svg"></md-icon>
        </md-button>
      </md-toolbar>

        <md-button ui-sref-active="active" ng-click="close()" layout-align=" center" style="text-align:left" ui-sref="overview">Overview</md-button>

    </md-sidenav>

What do I have to change in order to fix this?

Body:
You need this in your CSS:

.md-focused {
    background: transparent !important;
}


问:
SVG - animate/move dots along path
I'm looking for a way to move dots along existing path in order to get animation that looks like this:

I was thinking about working with dasharray but wasn't able to get this exact behavior.

Here is an example of something I tried, but as you can see it doesn't really work:

path.link {
  stroke-width: 3px;
  stroke-dasharray: 5 5;
  stroke: black;
}
path.link-anim {
  stroke-width: 3px;
  animation: link-anim 5s linear infinite;
}
path.red {
  stroke: red;
}
path.blue {
  stroke: blue;
}
path.green {
  stroke: green;
}
path.pink {
  stroke: pink;
}
@keyframes link-anim {
    0% {
        stroke-dashoffset: 0;
        stroke-dasharray: 5 5 100%;
    }
    100% {
        stroke-dashoffset: 100%;
        stroke-dasharray: 100% 5 5;
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg width="450" height="450">
  <g>
    <path class="link" d="M10,10L100,10"></path>
    <path class="link-anim red" d="M10,10L100,10"></path>
  </g>
  <g>
    <path class="link" d="M50,50L200,50"></path>
    <path class="link-anim blue" d="M50,50L200,50"></path>
  </g>
  <g>
    <path class="link" d="M75,75L75,200"></path>
    <path class="link-anim green" d="M75,75L75,200"></path>
  </g>
  <g>
    <path class="link" d="M85,85L450,450"></path>
    <path class="link-anim pink" d="M85,85L450,450"></path>
  </g>
</svg></code>```

Note - the angle of the line is not something I care about. I should have written this from the start. What I need is the 3 dots to move forward (and only those 3 dots).

答:
I have made an Path animation with javascript (also running on IE) You can also
animate your points in this way.

  <!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Nürburgring Animation</title>
    <meta name="author" content="Frank Wisniewski">
    <meta name="publisher" content="Frank Wisniewski">
    <meta name="copyright" content="Frank Wisniewski">
    <meta name="description" content="Auf dieser Seite wird eine kleine Animation des Nürburgrings um Adenau dargestellt. Die Animation wurde komplett in Javascript und SVG erstellt.">
    <meta name="keywords" content="SVG, Animation, Webdesign, Adenau, Nürburgring, Eifel, Frank, Wisniewski, Programmierung, Grafik, Gestaltung, Kunst">
    <meta name="page-topic" content="Forschung Technik">
    <meta name="page-type" content="Karte Plan">
    <meta name="audience" content="Alle, Erwachsene, Fans"><meta http-equiv="content-language" content="de">
    <meta name="robots" content="index, follow">
    <meta name="DC.Creator" content="Frank Wisniewski">
    <meta name="DC.Publisher" content="Frank Wisniewski">
    <meta name="DC.Rights" content="Frank Wisniewski">
    <meta name="DC.Description" content="Auf dieser Seite wird eine kleine Animation des Nürburgrings um Adenau dargestellt. Die Animation wurde komplett in Javascript und SVG rtstellt.">
    <meta name="DC.Language" content="de">

(c) Frank Wisniewski
Lohmühlenstraße 2
53518 Adenau

  ```

Title: SVG - animate/move dots along path

Body:
I'm looking for a way to move dots along existing path in order to get animation that looks like this:

I was thinking about working with dasharray but wasn't able to get this exact behavior.

Here is an example of something I tried, but as you can see it doesn't really work:

path.link {
  stroke-width: 3px;
  stroke-dasharray: 5 5;
  stroke: black;
}
path.link-anim {
  stroke-width: 3px;
  animation: link-anim 5s linear infinite;
}
path.red {
  stroke: red;
}
path.blue {
  stroke: blue;
}
path.green {
  stroke: green;
}
path.pink {
  stroke: pink;
}
@keyframes link-anim {
    0% {
        stroke-dashoffset: 0;
        stroke-dasharray: 5 5 100%;
    }
    100% {
        stroke-dashoffset: 100%;
        stroke-dasharray: 100% 5 5;
    }
}

<svg width="450" height="450">
  <g>
    <path class="link" d="M10,10L100,10"></path>
    <path class="link-anim red" d="M10,10L100,10"></path>
  </g>
  <g>
    <path class="link" d="M50,50L200,50"></path>
    <path class="link-anim blue" d="M50,50L200,50"></path>
  </g>
  <g>
    <path class="link" d="M75,75L75,200"></path>
    <path class="link-anim green" d="M75,75L75,200"></path>
  </g>
  <g>
    <path class="link" d="M85,85L450,450"></path>
    <path class="link-anim pink" d="M85,85L450,450"></path>
  </g>
</svg>

Note - the angle of the line is not something I care about. I should have written this from the start. What I need is the 3 dots to move forward (and only those 3 dots).

Body:
I have made an Path animation with javascript (also running on IE) You can also
animate your points in this way.

  <!DOCTYPE html>
  <html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Nürburgring Animation</title>
    <meta name="author" content="Frank Wisniewski">
    <meta name="publisher" content="Frank Wisniewski">
    <meta name="copyright" content="Frank Wisniewski">
    <meta name="description" content="Auf dieser Seite wird eine kleine Animation des Nürburgrings um Adenau dargestellt. Die Animation wurde komplett in Javascript und SVG erstellt.">
    <meta name="keywords" content="SVG, Animation, Webdesign, Adenau, Nürburgring, Eifel, Frank, Wisniewski, Programmierung, Grafik, Gestaltung, Kunst">
    <meta name="page-topic" content="Forschung Technik">
    <meta name="page-type" content="Karte Plan">
    <meta name="audience" content="Alle, Erwachsene, Fans"><meta http-equiv="content-language" content="de">
    <meta name="robots" content="index, follow">
    <meta name="DC.Creator" content="Frank Wisniewski">
    <meta name="DC.Publisher" content="Frank Wisniewski">
    <meta name="DC.Rights" content="Frank Wisniewski">
    <meta name="DC.Description" content="Auf dieser Seite wird eine kleine Animation des Nürburgrings um Adenau dargestellt. Die Animation wurde komplett in Javascript und SVG rtstellt.">
    <meta name="DC.Language" content="de">

    <style>
      body{font-family:"Calibri", "Helvetica", sans-serif;}
      .content{width:300px;margin-left:auto;margin-right:auto;}
      #svgG{width:200px;margin-left:auto;margin-right:auto;}
      svg{width:200px;height:200px;overflow:hidden;}
      h1,p{text-align:center;}
      p{font-size:8px;}
      .p10{font-size:14px;font-weight:bold;}
    </style>
  </head>
  <body>
    <div class="content">
    <div id="svgG"></div>
    <hr>
    <p>(c) Frank Wisniewski<br>Lohmühlenstraße 2</br>53518 Adenau</p>

    </div>
  <script>
  /* Programm und Grafiken sind geistiges Eigentum von Frank Wisniewski, Lohmühlenstraße 2, 53518 Adenau und dürfen ohne Genehemigung nicht genutzt werden */

      var carCount = 8;
      var i;
      var colors = ["Black", "Navy", "Blue", "BlueViolet", "CornFlowerBlue","Red", "LimeGreen", "IndianRed", "Sienna"];
      var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
      var _create = function (type){return document.createElementNS("http://www.w3.org/2000/svg", type);}
      var _set = function (el,par){for (key in par) {el.setAttribute(key.replace('X','-'),par[key]);}svg.appendChild(el);}
      with(svg){
        setAttribute('width', '250');
        setAttribute('height', '250');
        setAttribute("viewBox", "0 0 250 250");
        setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink");
      }
      svg.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink");
      svgG.appendChild(svg);
      var adenaubullet = _create("circle");
      _set(adenaubullet,{r:7,fill:'#f00',stroke:'#f00',cx:110,cy:8,strokeXwidth:1});
      var pfad = _create("path");
      pfad.setAttribute("d","M23.748,97.732c-4.235-2.956-3.875-3.774,0.149-6.424c4.415-2.912,9.246-4.657,13.445-7.991c3.775-2.997,6.616-6.559,8.157-11.154c0.658-1.969,0.469-3.708,0.928-5.656c0.49-2.073,2.818-3.084,2.289-5.231c-1.943-7.859,12.718-12.905,15.122-20.157c3.09-9.145-16.734-9.687-5.879-15.675c3.809-2.103,3.375-6.84,6.656-9.057c4.651-3.144,8.367,1.576,11.515,4.158c3.215,2.642,3.816-0.669,7.024-1.456c3.189-0.786,10.073,3.112,11.988-0.465c1.826-3.412,1.65-7.33,6.191-8.478c4.341-1.098,8.877-0.364,12.739-3.081c1.894-1.331,6.225-6.532,8.439-2.986c2.437,3.904-0.348,10.177,0.854,14.706c2.772,10.454,17.172,9.7,25.21,10.781c9.04,1.215,17.95,12.277,26.751,6.006c3.794-2.695,4.927-5.525,10.095-6.125c1.264-0.15,7.907-1.917,7.61,0.729c-0.316,2.853-6.305,5.333-8.338,6.711c-4.479,3.022-0.753,6.298,1.884,2.81c3.211-4.251,8.561-3.146,12.597-5.729c3.836-2.448,4.706-5.857,5.413-9.774c1.985-10.859,17.365-0.166,21.786,3.753c4.462,3.959,0.835,6.313,1.039,10.839c0.191,3.879,3.526,1.893,5.27,4.377c1.404,1.99,0.811,7.445-1.462,8.753c-3.792,2.168-6.586-2.64-9.273,2.805c-1.183,2.4-3.285,4.19-3.92,6.858c-0.735,3.091,1.969,7.785-0.122,10.477c-1.086,0.723-2.258,1.257-3.517,1.6c-1.907,1.228-3.592,3.089-5.258,4.608c-2.656,2.422-4.04,5.798-6.476,8.439c-3.986,4.336-10.271,6.805-16.063,7.526c-1.563,0.396-3.123,0.396-4.681,0c-2.271-0.944-1.521-3.241-4.827-2.771c-2.364,0.319-6.657,3.103-4.31,5.873c3.164,3.744,14.496,4.718,10.232,11.852c-4.087,6.844-13.375,9.795-19.857,13.7c-7.564,4.557-15.104,9.15-22.606,13.8c-7.321,4.53-16.081,8.639-22.572,14.298c-4.59,4.036-7.287,12.104-12.4,15.145c-2.264,1.35-1.265,4.361-4.132,5.722c-2.816,1.335-5.621-0.041-7.605-2.184c-0.949-1.027-2.493-4.413-4.188-2.536c-2.399,2.652-5.102,5.234-8.833,5.743c-3.432,0.466-6.206-1.944-9.507-1.572c-3.674,0.413-5.729-0.104-7.561-3.373c-1.255-2.242-3.559-3.075-5.613-4.396c-3.346-2.152-5.549-4.272-8.34-7.002c-5.066-4.96-13.847-9.133-14.34-17.222c-0.215-3.656,2.038-7.426,2.341-11.079c0.397-4.697-0.287-9.311-1.945-13.715c-1.431-3.801-3.489-7.284-4.994-11.039C29.209,99.368,26.926,99.928,23.748,97.732");
      _set(pfad,{fill:'none',stroke:'#666',strokeXwidth:6});
      var bordstein=pfad.cloneNode(true);
      _set(bordstein,{stroke:'#ddd',strokeXwidth:4});
      var grandprix = _create("path");
      grandprix.setAttribute("d","M32.246,245.125c-2.99-2.644,4.779-6.693,6.57-8.077c3.212-2.479,6.842-4.163,5.87-8.961c-0.891-4.404,1.944-8.48,3.929-12.302c1.225-2.359,2.457-4.719,3.468-7.177c1.085-2.64,0.846-3.498-1.781-4.92c-2.916-1.579-8.019-3.264-4.406-7.271c3.643-4.035,7.452-7.957,11.752-11.297c3.277-2.547,7.475-2.651,11.457-3.249c1.722-0.26,13.399-0.733,13.39-2.918c-0.015-3.294,6.497-2.777,8.654-3.153c1.517-0.266,5.267-1.056,5.688,1.308c0.445,2.497-1.268,3.257-2.928,4.664c-7.362,6.223-15.047,12.292-22.803,18.019c-0.534,0.395-8.754,5.805-8.457,3.525c0.423-3.213,5.225-8.695,1.275-11.084c-2.188-1.332-4.133-0.486-6.367,0.376c-1.574,0.607-5.299,1.734-6.084,3.411c-0.74,1.58,0.625,3.774,2.29,3.882c1.022,0.069,3.515-1.991,3.427,0.323c-0.094,2.511,0.521,5.18-0.138,7.646c-0.792,2.955-2.661,5.646-4.08,8.322c-0.9,1.696-3.023,4.913-2.296,7.02c0.89,2.563,4.673,2.549,5.777,4.88c1.078,2.279-4.431,3.46-5.976,4.184c-2.971,1.387-5.743,2.851-8.27,4.98c-1.822,1.534-3.684,3.438-5.079,5.381C35.841,244.419,34.963,247.523,32.246,245.125");
      _set(grandprix,{fill:'none', stroke:'#000', strokeXwidth:4});
      var grandprixbordstein=grandprix.cloneNode(true);
      _set(grandprixbordstein,{stroke:'#f00',strokeXwidth:3});
      var myText=_create("text");
      with (myText){
        setAttribute("font-family", "Arial, sans-serif");
        setAttribute("font-weight", "bold");
        setAttribute("font-style", "italic");
        setAttribute("text-anchor", "middle");
      }
      var myTextNode = document.createTextNode("");
      myText.appendChild(myTextNode);
      var nordschleife=myText.cloneNode(true);
      _set(nordschleife,{x:120,y:77,fontXsize:16});
      nordschleife.textContent="NORDSCHLEIFE";
      var grandprixtext=nordschleife.cloneNode(true);
      _set(grandprixtext,{x:110,y:220,fontXsize:16});
      grandprixtext.textContent="GRAND-PRIX";
      var grandprixtext1=nordschleife.cloneNode(true);
      _set(grandprixtext1,{x:110,y:240,fontXsize:16});
       grandprixtext1.textContent="STRECKE";
      var adenautext=nordschleife.cloneNode(true);
      _set(adenautext,{x:165,y:14,fontXsize:16});
      adenautext.textContent="ADENAU";
      var roundSquare=[];
      var mySquare=_create("rect");
      var roundBullet=[];
      var roundBulletText=[];
      for (i=1;i <= carCount;i++){

        roundBullet[i]=adenaubullet.cloneNode(true);
        _set(roundBullet[i],{r:5,strokeXwidth:0,fill:colors[i],stroke:colors[i],cx:180,cy:120+i*5*3});

        roundSquare[i]=mySquare.cloneNode(true);
        _set(roundSquare[i],{x:203,y:113+i*5*3,fill:'#ddd',stroke:'none',height:13,width:30});

        roundBulletText[i]=adenautext.cloneNode(true);
        _set(roundBulletText[i],{x:210,y:125+i*5*3,fontXsize:14,fontXstyle:'normal'});
        roundBulletText[i].textContent="0";
      }
      var lapsText=nordschleife.cloneNode(true);
      _set(lapsText,{x:217,y:122,fontXsize:14,fontXstyle:'normal'});
      lapsText.textContent="LAPS";
      var cars = [];
      var step=[];
      var laps=[];
      var len = pfad.getTotalLength();
      var speed = 1.5;
      var pos = [];
      var pt;
      var repeater;
      var lapPos = [];
      var carProto = _create("circle");
      with (carProto){
        setAttribute("r", 3);
        setAttribute("stroke-width", "1");
      }
      for(i = 1; i <= carCount; i++){
        cars[i]=carProto.cloneNode(true);
        pos[i]=i*5+750;
        laps[i]=0;
        lapPos[i]=750;
        pt=pfad.getPointAtLength(len/1000*pos[i])
        _set(cars[i],{cx:pt.x,cy:pt.y,stroke:colors[i],fill:colors[i]});
        step[i]=speed+Math.random()/1;
      }
      var animate=function(){
        for(i = 1; i <= carCount; i++){
          pos[i]+=step[i];
          lapPos[i]+=step[i];
          if(pos[i]>1000){
            pos[i]=1;
            step[i]=speed+Math.random()/2;
          }
          if (lapPos[i]>1750){
            lapPos[i]=750;
            laps[i]++;
            roundBulletText[i].textContent=laps[i];
          }
          pt=pfad.getPointAtLength(len/1000*pos[i])
          cars[i].setAttribute("cx", pt.x);
          cars[i].setAttribute("cy", pt.y);
        }
        //repeater = requestAnimationFrame(animate);
        repeater = setTimeout(animate,1000/60);
      }
      animate();

  </script>
  </body>
  </html>


问:
Find number of higher values than the given value in BST
I'm trying to find number of higher values than the given value in a binary search tree just for fun and overlearning. I have written a resursive function so far by drawing on paper with its logic. However, when I run it, it doesn't give the expected result. For example, 30, 25, 98, 23, 28, 97, 99, 29 is contained in BST. I'm trying to get greater values than 28 should be 5, but output is 2. Where is the problem in the method? I'm traversing all nodes in the tree, is there a more efficient solution for it?

```<code>public int findMax(Node<E> localRoot, E target) {
        if (localRoot == null) return 0;

        int cmpResult = target.compareTo(localRoot.data);
        int valL = findMax(localRoot.left, target) + cmpResult < 0 ? 1 : 0;
        int valR = findMax(localRoot.right, target) + cmpResult < 0 ? 1 : 0;
        return valL + valR;
}
</code>```

答:
In the end, the first function call will always return at most 1 + 1 because of this logic:

```<code>int valL = findMax(localRoot.left, target) + cmpResult < 0 ? 1 : 0;
int valR = findMax(localRoot.right, target) + cmpResult < 0 ? 1 : 0;
</code>```

It doesn't matter how many levels it calls down because of the order of operations. valL and valR will always be either 0 or 1 because it is testing whether (findMax(localRoot.right, target) + cmpResult) is < 0, ten assigning a value  a of 0 or 1. Try it using parentheses so that you are adding to the results of findMax. Like this:

```<code>int valL = findMax(localRoot.left, target) + (cmpResult < 0 ? 1 : 0);
int valR = findMax(localRoot.right, target) + (cmpResult < 0 ? 1 : 0);
</code>```

--EDIT--

Okay, I realized that I missed another important issue: you are adding the local comparison result to the left and right calculations for each node. This will result in a value that is too high! You need to keep the local node comparison independent of the left and right node comparisons. Try this:

```<code>int cmpResult = target.compareTo(localRoot.data);
int localNodeVal = cmpResult < 0 ? 1 : 0; // This is the value for the current node by itself.
int valL = findMax(localRoot.left, target);
int valR = findMax(localRoot.right, target);
// Add the local node result with the evaluation of the left and right side.
return localNodeVal + valL + valR;
</code>```

Body:
I'm trying to find number of higher values than the given value in a binary search tree just for fun and overlearning. I have written a resursive function so far by drawing on paper with its logic. However, when I run it, it doesn't give the expected result. For example, 30, 25, 98, 23, 28, 97, 99, 29 is contained in BST. I'm trying to get greater values than 28 should be 5, but output is 2. Where is the problem in the method? I'm traversing all nodes in the tree, is there a more efficient solution for it?

public int findMax(Node<E> localRoot, E target) {
        if (localRoot == null) return 0;

        int cmpResult = target.compareTo(localRoot.data);
        int valL = findMax(localRoot.left, target) + cmpResult < 0 ? 1 : 0;
        int valR = findMax(localRoot.right, target) + cmpResult < 0 ? 1 : 0;
        return valL + valR;
}

Body:
In the end, the first function call will always return at most 1 + 1 because of this logic:

int valL = findMax(localRoot.left, target) + cmpResult < 0 ? 1 : 0;
int valR = findMax(localRoot.right, target) + cmpResult < 0 ? 1 : 0;

It doesn't matter how many levels it calls down because of the order of operations. valL and valR will always be either 0 or 1 because it is testing whether (findMax(localRoot.right, target) + cmpResult) is < 0, ten assigning a value  a of 0 or 1. Try it using parentheses so that you are adding to the results of findMax. Like this:

int valL = findMax(localRoot.left, target) + (cmpResult < 0 ? 1 : 0);
int valR = findMax(localRoot.right, target) + (cmpResult < 0 ? 1 : 0);

--EDIT--

Okay, I realized that I missed another important issue: you are adding the local comparison result to the left and right calculations for each node. This will result in a value that is too high! You need to keep the local node comparison independent of the left and right node comparisons. Try this:

int cmpResult = target.compareTo(localRoot.data);
int localNodeVal = cmpResult < 0 ? 1 : 0; // This is the value for the current node by itself.
int valL = findMax(localRoot.left, target);
int valR = findMax(localRoot.right, target);
// Add the local node result with the evaluation of the left and right side.
return localNodeVal + valL + valR;


问:
pvlib IV curve - TypeError: must be str, not int
I'm trying to make an IV curve from pvlib but am getting the error:

TypeError: must be str, not int.

Running on Spyder.
Could you advise please? This example taken from the web.

```<code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
rom pvlib.pvsystem import singlediode, v_from_i, i_from_v, retrieve_sam

def fivepoints_to_frame(pnt):
    """
    Converts a 1 dimensional, dict-like singlediode or sapm result
    to a 5 row DataFrame with columns current and voltage.
    Users can iterate over the rows of a multidimensional
    singlediode or sapm result, if necessary.
    """
    ivframe = {'i_sc': (pnt['i_sc'], 0),
               'p_mp': (pnt['i_mp'], pnt['v_mp']),
               'i_x': (pnt['i_x'], 0.5*pnt['v_oc']),
               'i_xx': (pnt['i_xx'], 0.5*(pnt['v_oc']+pnt['v_mp'])),
               'v_oc': (0, pnt['v_oc'])}
    ivframe = pd.DataFrame(ivframe, index=['current', 'voltage']).T
    ivframe = ivframe.sort_values(by='voltage')

    return ivframe

resistance_shunt = 16
resistance_series = 0.094
nNsVth = 0.473
saturation_current = 1.943e-09
photocurrent = 7
module_parameters = retrieve_sam('cecmod')['Example_Module']

v_oc = v_from_i(resistance_shunt, resistance_series, nNsVth, 0,
saturation_current, photocurrent)
voltage = np.linspace(0, v_oc, 100)

current = i_from_v(resistance_shunt, resistance_series, nNsVth,
voltage,saturation_current, photocurrent)

fivepnts = singlediode(
    module_parameters, photocurrent, saturation_current, resistance_series,
resistance_shunt, nNsVth)
ivframe = fivepoints_to_frame(fivepnts)

fig, ax = plt.subplots()
ax.plot(voltage, current)
ax.scatter(ivframe['voltage'], ivframe['current'], c='k', s=36, zorder=10)
ax.set_xlim(0, None)
ax.set_ylim(0, None)
ax.set_ylabel('current (A)')
ax.set_xlabel('voltage (V)')
</code>```

答:
From the (Docs)

```<code>pvlib.pvsystem.singlediode(photocurrent, saturation_current, resistance_series,
                           resistance_shunt, nNsVth, ivcurve_pnts=None)
</code>```

The first parameter   to singlediode() is incorrect.  If I remove it like:

```<code>fivepnts = singlediode(
    photocurrent, saturation_current, resistance_series,
    resistance_shunt, nNsVth)
</code>```

I get:

Body:
I'm trying to make an IV curve from pvlib but am getting the error:

TypeError: must be str, not int.

Running on Spyder.
Could you advise please? This example taken from the web.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
rom pvlib.pvsystem import singlediode, v_from_i, i_from_v, retrieve_sam

def fivepoints_to_frame(pnt):
    """
    Converts a 1 dimensional, dict-like singlediode or sapm result
    to a 5 row DataFrame with columns current and voltage.
    Users can iterate over the rows of a multidimensional
    singlediode or sapm result, if necessary.
    """
    ivframe = {'i_sc': (pnt['i_sc'], 0),
               'p_mp': (pnt['i_mp'], pnt['v_mp']),
               'i_x': (pnt['i_x'], 0.5*pnt['v_oc']),
               'i_xx': (pnt['i_xx'], 0.5*(pnt['v_oc']+pnt['v_mp'])),
               'v_oc': (0, pnt['v_oc'])}
    ivframe = pd.DataFrame(ivframe, index=['current', 'voltage']).T
    ivframe = ivframe.sort_values(by='voltage')

    return ivframe

resistance_shunt = 16
resistance_series = 0.094
nNsVth = 0.473
saturation_current = 1.943e-09
photocurrent = 7
module_parameters = retrieve_sam('cecmod')['Example_Module']

v_oc = v_from_i(resistance_shunt, resistance_series, nNsVth, 0,
saturation_current, photocurrent)
voltage = np.linspace(0, v_oc, 100)

current = i_from_v(resistance_shunt, resistance_series, nNsVth,
voltage,saturation_current, photocurrent)

fivepnts = singlediode(
    module_parameters, photocurrent, saturation_current, resistance_series,
resistance_shunt, nNsVth)
ivframe = fivepoints_to_frame(fivepnts)

fig, ax = plt.subplots()
ax.plot(voltage, current)
ax.scatter(ivframe['voltage'], ivframe['current'], c='k', s=36, zorder=10)
ax.set_xlim(0, None)
ax.set_ylim(0, None)
ax.set_ylabel('current (A)')
ax.set_xlabel('voltage (V)')

Body:
From the (Docs)

pvlib.pvsystem.singlediode(photocurrent, saturation_current, resistance_series,
                           resistance_shunt, nNsVth, ivcurve_pnts=None)

The first parameter   to singlediode() is incorrect.  If I remove it like:

fivepnts = singlediode(
    photocurrent, saturation_current, resistance_series,
    resistance_shunt, nNsVth)

I get:


问:
Why Chart.js v2 time based data not aligning with X axis correctly?
When displaying time based data using Chart.js, the data itself doesn't seem to be aligned with the X axis labels. For instance, when the data is for 2016-11-30, the bar is actually showing in December. The last date in a series of dates doesn't even show on the chart. How can I make them align correctly?

```<code>$(document).ready(function(){

    var config = {
        type: 'bar',
        data: {
            labels: [
        '2016-11-30', // Why showing in December?
        '2017-04-01', // Why not showing in beginning of April?
        '2017-06-30'], // Why not showing?
            datasets: [{
                label: 'Contacts',
                backgroundColor: 'red',
                data: [
          1,
          5,
          7
        ]
            }]
        },
        options: {
            scales: {
                yAxes: [{
                    ticks: {
                        beginAtZero:true,
                        stepSize:1
                    }
                }],
                xAxes: [{
                    type: 'time',
                    barThickness:2,
                    time: {
                        unit: 'month'
                    }
                }]
            }
        }
    };

    var Canvas = $("#Chart");
    var cc = new Chart(Canvas, config);

});
</code>```

Example on Codepen:
https://codepen.io/skunkbad/pen/EmBJMa

答:
Regarding the showing on the wrong date:

This is because of how you instantiate a date object and how it relates to timezones, your browser is likely resolving that to your timezone and you get a different value.

I am on GMT-3 and this is what happens for me for example:

```<code>$ new Date('2016-11-30')
- Tue Nov 29 2016 21:00:00 GMT-0300 (BRT)

$ new Date(2016, 11, 30)
- Fri Dec 30 2016 00:00:00 GMT-0300 (BRT)
</code>```

Regarding not showing last data:

The bar is plotted but it's not on visible location. It's possible to verify this on this JSFiddle (not sure why not on codepen), if you move your mouse to the very edge of the screen the label will appear.

This is a known issue and is being tracked here: #2415

If possible, I think that the easiest workaround would be to manually define a max property on your time scale

Body:
When displaying time based data using Chart.js, the data itself doesn't seem to be aligned with the X axis labels. For instance, when the data is for 2016-11-30, the bar is actually showing in December. The last date in a series of dates doesn't even show on the chart. How can I make them align correctly?

$(document).ready(function(){

    var config = {
        type: 'bar',
        data: {
            labels: [
        '2016-11-30', // Why showing in December?
        '2017-04-01', // Why not showing in beginning of April?
        '2017-06-30'], // Why not showing?
            datasets: [{
                label: 'Contacts',
                backgroundColor: 'red',
                data: [
          1,
          5,
          7
        ]
            }]
        },
        options: {
            scales: {
                yAxes: [{
                    ticks: {
                        beginAtZero:true,
                        stepSize:1
                    }
                }],
                xAxes: [{
                    type: 'time',
                    barThickness:2,
                    time: {
                        unit: 'month'
                    }
                }]
            }
        }
    };

    var Canvas = $("#Chart");
    var cc = new Chart(Canvas, config);

});

Example on Codepen:
https://codepen.io/skunkbad/pen/EmBJMa

Body:
Regarding the showing on the wrong date:

This is because of how you instantiate a date object and how it relates to timezones, your browser is likely resolving that to your timezone and you get a different value.

I am on GMT-3 and this is what happens for me for example:

$ new Date('2016-11-30')
- Tue Nov 29 2016 21:00:00 GMT-0300 (BRT)

$ new Date(2016, 11, 30)
- Fri Dec 30 2016 00:00:00 GMT-0300 (BRT)

Regarding not showing last data:

The bar is plotted but it's not on visible location. It's possible to verify this on this JSFiddle (not sure why not on codepen), if you move your mouse to the very edge of the screen the label will appear.

This is a known issue and is being tracked here: #2415

If possible, I think that the easiest workaround would be to manually define a max property on your time scale


问:
How is a object with local variables stored in the heap?
Suppose I have a class that has local variables, like this one:

```<code>class Object{
 private:
 int number1, number2, number3;

 public:
 Object(){
 number1=0;
 number2=0;
 number3=0;
 }

}
</code>```

Now let's suppose I use it in my main program:

```<code>int main (){
Object obj1();
}
</code>```

I created my object locally in main. Since I did not use "new" it does not use the heap. All the object's variables (and the object itself) are stored in the stack.

Now suppose I used new in main, like this:

```<code>int main (){
Object p= new obj1();
}
</code>```

Now I only have one variable in my main: a pointer that points to obj1 in the heap.

My class notes say this is possible and correct: that you can dynamically create an object that has local variables. But how exactly is the compiler able to create the object in the heap? My object's variables number1, number2 and number3 do not use new. They are local variables and local variables need a local scope. I get that the object "p" is on the heap because we used "new". But what about its members? They don't use new. Is there some kind of automatic cast so that these local variables are made dynamic?

答:
A class doesn't have local variables, it has member variables.

And the size of an object includes the member variables. If you print sizeof(Object) you will see it change as you add or remove member variables.

So the new invocation will allocate space for the full object including its member variables (as reported by sizeof(Object)), and the *construction of those variables will happen as part of the Object construction call.

Body:
Suppose I have a class that has local variables, like this one:

class Object{
 private:
 int number1, number2, number3;

 public:
 Object(){
 number1=0;
 number2=0;
 number3=0;
 }

}

Now let's suppose I use it in my main program:

int main (){
Object obj1();
}

I created my object locally in main. Since I did not use "new" it does not use the heap. All the object's variables (and the object itself) are stored in the stack.

Now suppose I used new in main, like this:

int main (){
Object p= new obj1();
}

Now I only have one variable in my main: a pointer that points to obj1 in the heap.

My class notes say this is possible and correct: that you can dynamically create an object that has local variables. But how exactly is the compiler able to create the object in the heap? My object's variables number1, number2 and number3 do not use new. They are local variables and local variables need a local scope. I get that the object "p" is on the heap because we used "new". But what about its members? They don't use new. Is there some kind of automatic cast so that these local variables are made dynamic?


问:
Laravel 5 - SQLSTATE[HY000][1045] Access denied for user 'root'@'localhost' (using password: NO)
I am trying to make CRUD operations in laravel and I alway have this error message. I already configured the .env and the config/database.php files to my local setting but it doesn't work.

I tried php artisan cache:clear,php artisan config:clear too...

My config/database.php:

```<code>'mysql' => [
    'driver' => 'mysql',
    'host' => env('DB_HOST', 'localhost'),
    'port' => env('DB_PORT', ''),
    'database' => env('DB_DATABASE', 'feki_test'),
    'username' => env('DB_USERNAME', 'root'),
    'password' => env('DB_PASSWORD', ''),
    'unix_socket' => env('DB_SOCKET', ''),
    'charset' => 'utf8mb4',
    'collation' => 'utf8mb4_unicode_ci',
    'prefix' => '',
    'strict' => true,
    'engine' => null,
],
</code>```

My .env:

```<code>DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=
DB_DATABASE=feki_test
DB_USERNAME=root
DB_PASSWORD=
</code>```

答:
Based on the comments, you're trying to access the local xampp mysql server from within Homestead. This won't work as the application is in an isolated virtual machine. You will need to use Homestead's mysql server for your application. Use the default connection information for this.

```<code>DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret
</code>```

To access Homestead's server on your local machine change the port to 33060. This can be helpful if you want to use a SQL tool to connect to the database.

Body:
I am trying to make CRUD operations in laravel and I alway have this error message. I already configured the .env and the config/database.php files to my local setting but it doesn't work.

I tried php artisan cache:clear,php artisan config:clear too...

My config/database.php:

'mysql' => [
    'driver' => 'mysql',
    'host' => env('DB_HOST', 'localhost'),
    'port' => env('DB_PORT', ''),
    'database' => env('DB_DATABASE', 'feki_test'),
    'username' => env('DB_USERNAME', 'root'),
    'password' => env('DB_PASSWORD', ''),
    'unix_socket' => env('DB_SOCKET', ''),
    'charset' => 'utf8mb4',
    'collation' => 'utf8mb4_unicode_ci',
    'prefix' => '',
    'strict' => true,
    'engine' => null,
],

My .env:

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=
DB_DATABASE=feki_test
DB_USERNAME=root
DB_PASSWORD=

Body:
Based on the comments, you're trying to access the local xampp mysql server from within Homestead. This won't work as the application is in an isolated virtual machine. You will need to use Homestead's mysql server for your application. Use the default connection information for this.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret

To access Homestead's server on your local machine change the port to 33060. This can be helpful if you want to use a SQL tool to connect to the database.


问:
Sticky Footer on a Site with 100% height
I'm trying to get a sticky footer on a page with 100% heigth in every tag.
My problem is that, if the content is bigger than the display and I scroll downwards, the footer is no longer at the bottom of the page.
The footer stays at the position like this: Picture of the footer

Here is an example:(Sorry that was the wrong link..)
http://jsfiddle.net/qt3m1p4c/

```<code><html style:"height: 100%">
   <body style:"height: 100%">
        A lot of Content
   </body>
   <footer style:"position: absolute; bottom: 0;">
        Sticky Footer
   </footer>
</html>
</code>```

Does someone no how to fix this, without removing the heigth attributes?

答:
You need to set position: fixed to your footer, this means whatever happens on your page, this element will stand in same place, here your code with changed position</p>

```<code> .footer {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background:#ccc;
}
</code>```

Body:
I'm trying to get a sticky footer on a page with 100% heigth in every tag.
My problem is that, if the content is bigger than the display and I scroll downwards, the footer is no longer at the bottom of the page.
The footer stays at the position like this: Picture of the footer

Here is an example:(Sorry that was the wrong link..)
http://jsfiddle.net/qt3m1p4c/

        A lot of Content

        Sticky Footer

Does someone no how to fix this, without removing the heigth attributes?

Body:
You need to set position: fixed to your footer, this means whatever happens on your page, this element will stand in same place, here your code with changed position

 .footer {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background:#ccc;
}


问:
XOR on HEX value in textbox Visual Basic 2010
I have Vb.net 2010.

I have:

Textbox1.text with "4B 4E 61 58 1A 07 00 CF 90 73 00 00 0D"

Textbox2.text with "1b"

Command Button with this code:

```<code>Dim M As String = TextBox1.Text
Dim hex2 As String = TextBox2.Text
Dim R
' StringTest2 += Chr(Convert.ToInt32(Mid(StringTest1, i, 2), 16)).ToString
For i = 1 To M.Length Step 2
    TextBox1.Text = TextBox1.Text & "-"
    Dim dec1 As Integer = Mid(M, i, 2).ToString
    Dim dec2 As Integer = Convert.ToInt32(hex2, 16)
    ' MsgBox(dec2)
    Dim result As Integer = dec1 Xor dec2
    R = R & result
Next

TextBox1.Text = R
</code>```

Textbox1 can be changed as I wish but in this case it's "4B 4E 61 58 1A 07 00 CF 90 73 00 00 0D" hex.
Textbox2 contain the value to XOR with...

I want simply to Xor each value in textbox1 with 1B like "4B XOR 0x1b" etc...

When I do it with this code he gives me: "When casting from a number the value must be less than infinity"
When I put a "On error resume next" before the code he gave me in result : "2731313830191927282727276528242727272727"

The correct result on xor'ing ONE time "4B 4E 61 58 1A 07 00 CF 90 73 00 00 0D" with 0x1b (27 decimal) is "50 55 7A 43 01 1C 1B D4 8B 68 1B 1B 16"

If we apply Xor another time on the result "50 55 7A 43 01 1C 1B D4 8B 68 1B 1B 16" we must found the First Hex string as reply "4B 4E 61 58 1A 07 00 CF 90 73 00 00 0D"

答:
I believe this is what you're trying to do:

```<code>    Dim input As String = "4B 4E 61 58 1A 07 00 CF 90 73 00 00 0D"
    Dim sb As New System.Text.StringBuilder()

    Dim xorhex As String = "1B"
    Dim xornum As Integer = Integer.Parse(xorhex, Globalization.NumberStyles.HexNumber)

    For Each numhex As String In input.Split(" "c)
        Dim num As Integer = Integer.Parse(numhex, Globalization.NumberStyles.HexNumber)
        sb.Append((num Xor xornum).ToString("X2")).Append(" ")
    Next

    Console.WriteLine(sb.ToString())
</code>```

You should be able to easily switch the variables to match your code -- I specifically wanted to post this as an example that compiles and displays information if run in a console app environment.

Body:
I have Vb.net 2010.

I have:

Textbox1.text with "4B 4E 61 58 1A 07 00 CF 90 73 00 00 0D"

Textbox2.text with "1b"

Command Button with this code:

Dim M As String = TextBox1.Text
Dim hex2 As String = TextBox2.Text
Dim R
' StringTest2 += Chr(Convert.ToInt32(Mid(StringTest1, i, 2), 16)).ToString
For i = 1 To M.Length Step 2
    TextBox1.Text = TextBox1.Text & "-"
    Dim dec1 As Integer = Mid(M, i, 2).ToString
    Dim dec2 As Integer = Convert.ToInt32(hex2, 16)
    ' MsgBox(dec2)
    Dim result As Integer = dec1 Xor dec2
    R = R & result
Next

TextBox1.Text = R

Textbox1 can be changed as I wish but in this case it's "4B 4E 61 58 1A 07 00 CF 90 73 00 00 0D" hex.
Textbox2 contain the value to XOR with...

I want simply to Xor each value in textbox1 with 1B like "4B XOR 0x1b" etc...

When I do it with this code he gives me: "When casting from a number the value must be less than infinity"
When I put a "On error resume next" before the code he gave me in result : "2731313830191927282727276528242727272727"

The correct result on xor'ing ONE time "4B 4E 61 58 1A 07 00 CF 90 73 00 00 0D" with 0x1b (27 decimal) is "50 55 7A 43 01 1C 1B D4 8B 68 1B 1B 16"

If we apply Xor another time on the result "50 55 7A 43 01 1C 1B D4 8B 68 1B 1B 16" we must found the First Hex string as reply "4B 4E 61 58 1A 07 00 CF 90 73 00 00 0D"

Body:
I believe this is what you're trying to do:

    Dim input As String = "4B 4E 61 58 1A 07 00 CF 90 73 00 00 0D"
    Dim sb As New System.Text.StringBuilder()

    Dim xorhex As String = "1B"
    Dim xornum As Integer = Integer.Parse(xorhex, Globalization.NumberStyles.HexNumber)

    For Each numhex As String In input.Split(" "c)
        Dim num As Integer = Integer.Parse(numhex, Globalization.NumberStyles.HexNumber)
        sb.Append((num Xor xornum).ToString("X2")).Append(" ")
    Next

    Console.WriteLine(sb.ToString())

You should be able to easily switch the variables to match your code -- I specifically wanted to post this as an example that compiles and displays information if run in a console app environment.


问:
QtCharts in Qt 5.6
I want to use QtCharts inside Qt 5.6. (I have no plans to install Qt 5.7/5.8 in the next months). Although I've found a Blog on the Qt site where Qt Charts add-in for At 5.6 is presented I did not find a download link. Has anyone any idea how to download Qt Charts lib and how to embed it inside Qt 5.6?</p>

答:
Download Qt 5.9

Copy the charts module over to Qt 5.6

Init a git repo in the module (you'll need it!)

Attempt a build of the module.

Fix bugs.

Goto 4 until you succeed.

You'll need to backport the module configuration - Qt 5.6 can't handle the .json file, and I'm not sure how much the Qt Quick Charts depends on new features in 5.8/9. You may wish to disable Qt Quick Charts at least initially to get the widget side working first.

Title: QtCharts in Qt 5.6


问:
hitting javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated even imported cert
Good day,

As my understanding, if an application needs to connect to a https web service, I have to download the cert from the URL and import the cert to WAS Console. This is working fine for me.

Until today, the application has to call a new https URL. Same way, I download the cert and import the cert into WAS Console, but application hitting peer not authenticated error.

After my checking, this URL is using CA cert, not the self-sign cert that I imported usually. May I know is it the way to import CA cert into WAS Console different?

Based on the screen shot below, I imported total 3 cents.

Am I doing the correct way? or for CA cert URL, I need to ask cert from the URL owner? instead of downloading myself.

Will it be caused by protocol issue? I already set the WAS setting protocol to SSL_TLSv2

Kindly advise.

答:
WebSphere has a "retrieve signer from port" function in the SSL Certificate Management UI. That will connect to the host/port you instruct it to and find the root, self-signed issuer (if the server sends it, it's not required) and add it as trusted.

If the server does not send its root, self-signed issuer, you can always look at the last certificate it provides in the chain and add it manually.