问:
Select after bulk insert doesn't work in MS access database
There is a windows form application. I am using the MS Access database for some data manipulation. I want to copy data from one database to another. The table name, schema and the data types are same in both the tables.

I am using the below query to bulk insert data in destination database by selecting data from the source database.

```<code>INSERT INTO [Table1] IN 'C:\Data\Users.mdf' SELECT * FROM [Table1]
</code>```

After data is inserted, I am querying to the target table to fetch the inserted data. I am using OleDbConnection for performing the database operations.

The issue I am facing here is that, after the above mentioned INSERT query is executed when I am executing the SELECT statement to fetch the data, I am not getting the data. However, when I am checking in debugging mode then I am getting the data.

I noticed that if I am waiting for some time after the INSERT statement is executed then the data is coming correctly. So I assume that it needs some time(delay?) to complete the bulk insert operation.

I tried providing Task.Delay(20000) after the INSERT query execution but no luck. Could someone help me here, how I can resolve this issue? Any help is highly appreciated.

答:
I didn't find a good way to handle this but did a work around for the same. After data is inserted into the table, I am firing another query to check whether there is any data in the inserted table or not. This happens in a do..while loop like follows. The table is dropped every time the operation is completed.

```<code>        var insertQuery = "INSERT INTO [Table1] IN 'C:\Data\Users.mdf' SELECT * FROM [Table1]";
        ExecuteQuery(insertQuery, connProd);

        var count = 10;

        do
        {
            var selectQuery = "SELECT TOP 1 * FROM " + tableProdCopy;
            var dtTopRowData = GetQueryData(selectQuery, connOther);

            if (dtTopRowData != null && dtTopRowData.Rows.Count > 0)
            {
                count = 0;
                break;
            }

            System.Threading.Thread.Sleep(2000);

            count = count - 1;
        } while (count > 0);

        private DataTable GetQueryData(string query, OleDbConnection conn)
        {
            using (OleDbCommand cmdOutput = new OleDbCommand(query, conn))
            {
                using (OleDbDataAdapter adapterOutput = new OleDbDataAdapter(cmdOutput))
                {
                    var dtOutput = new DataTable();

                    adapterOutput.Fill(dtOutput);

                    return dtOutput;
                }
            }
        }

        private void ExecuteQuery(string query, OleDbConnection conn)
        {
            using (OleDbCommand cmdInput = new OleDbCommand(query, conn))
            {
                cmdInput.ExecuteNonQuery();
            }
        }
</code>```

Body:
There is a windows form application. I am using the MS Access database for some data manipulation. I want to copy data from one database to another. The table name, schema and the data types are same in both the tables.

I am using the below query to bulk insert data in destination database by selecting data from the source database.

INSERT INTO [Table1] IN 'C:\Data\Users.mdf' SELECT * FROM [Table1]

After data is inserted, I am querying to the target table to fetch the inserted data. I am using OleDbConnection for performing the database operations.

The issue I am facing here is that, after the above mentioned INSERT query is executed when I am executing the SELECT statement to fetch the data, I am not getting the data. However, when I am checking in debugging mode then I am getting the data.

I noticed that if I am waiting for some time after the INSERT statement is executed then the data is coming correctly. So I assume that it needs some time(delay?) to complete the bulk insert operation.

I tried providing Task.Delay(20000) after the INSERT query execution but no luck. Could someone help me here, how I can resolve this issue? Any help is highly appreciated.

Body:
I didn't find a good way to handle this but did a work around for the same. After data is inserted into the table, I am firing another query to check whether there is any data in the inserted table or not. This happens in a do..while loop like follows. The table is dropped every time the operation is completed.

        var insertQuery = "INSERT INTO [Table1] IN 'C:\Data\Users.mdf' SELECT * FROM [Table1]";
        ExecuteQuery(insertQuery, connProd);

        var count = 10;

        do
        {
            var selectQuery = "SELECT TOP 1 * FROM " + tableProdCopy;
            var dtTopRowData = GetQueryData(selectQuery, connOther);

            if (dtTopRowData != null && dtTopRowData.Rows.Count > 0)
            {
                count = 0;
                break;
            }

            System.Threading.Thread.Sleep(2000);

            count = count - 1;
        } while (count > 0);

        private DataTable GetQueryData(string query, OleDbConnection conn)
        {
            using (OleDbCommand cmdOutput = new OleDbCommand(query, conn))
            {
                using (OleDbDataAdapter adapterOutput = new OleDbDataAdapter(cmdOutput))
                {
                    var dtOutput = new DataTable();

                    adapterOutput.Fill(dtOutput);

                    return dtOutput;
                }
            }
        }

        private void ExecuteQuery(string query, OleDbConnection conn)
        {
            using (OleDbCommand cmdInput = new OleDbCommand(query, conn))
            {
                cmdInput.ExecuteNonQuery();
            }
        }


来源: stackexchange

问:
Do users have problems adopting Silverlight?
My group is thinking about switching our platform for web UI from ASP.net to Silverlight for several reasons. To be clear, these are business websites that provide a service to our users, we develop and host them ourselves.

Has anyone switched their business / intranet web site from a traditional server-based web technology such as ASP.net to Silverlight? Or have you added Silverlight to your website? If so...

Have your users complained or resisted installing Silverlight?

Have any significant number of users been unable to install Silverlight?

Have they commented on the look or responsiveness of Silverlight UI?

What other comments have they had?

In short, are my web site's users gonna freak if I start using Silverlight on my page?

If your answer is "It depends" then please give an idea of what the determining factors are.

As an aside, is there an easy way to detect how many of your users install / have already installed Silverlight?

Edit:

Thanks for the answers so far! I may be reaching, but has anyone yet had concrete experience with deploying a Silverlight app?  I was wondering if anyone had gone through this and if their users had any major issues.

答:
If you plan on making your website only usable by users with Silverlight, then you are going to limit the potential use of the site.

Whilst those in the know about IT, may well have heard of Silverlight, and have it installed, many users may not have at all, and asking them to download it to be able to view your website may very well put them off.

That said, if your users are not casual users, but ones who visit regularly, part of a community, or just plain have to use your site, then they will be more inclined to install Silverlight.

The only reason Flash has become so ubiquitous on the web today is that enough people had, or would download the client, mainly to be able to play flash based games! Once/If Silverlight gets to that point, then this will no longer be an issue.

OwnerDisplayName: TJB

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: TJB

LastEditorDisplayName: Samuel


问:
Unable to call JSON data from Hacker News API
I'm trying to use Hacker News API , i am able to call the API and make the request to fetch the stories. As per their API documentation the source URL must contain the ID(required) to access the stories' content, I am getting the correct URL in the console and clicking on the URL gives the appropriate JSON  but beyond that I am unable to use/call the JSON content like author name,title etc.

```<code>JS CODE:

var records;
var userRecords;
var fileJson;
var startRequest = new XMLHttpRequest();
var sourceUrl = "https://hacker-news.firebaseio.com/v0/";
var sourceUrlAdd = "showstories.json";
var finalURL = sourceUrl + sourceUrlAdd;

startRequest.open("GET",finalURL);
startRequest.onload = function() {
    fileJson = JSON.parse(startRequest.responseText);
    for(var i = 0 ; i < fileJson.length; i++) {
        userRecords = sourceUrl + fileJson[i] + ".json";
    }
}
startRequest.send();
</code>```

How do I make it work??

答:
Looking at the information on: GitHub

Your URL in the loop should be modified to:

```<code>    for(var i = 0 ; i < fileJson.length; i++) {
       userRecords = sourceUrl + "/item/" + fileJson[i] + ".json";
    }
</code>```

Your code doesn't look complete as the loop will just overwrite userRecords for every iteration, if you want to store them:

```<code>    userRecords = [];
    for(var i = 0 ; i < fileJson.length; i++) {
       userRecords.push(sourceUrl + "/item/" + fileJson[i] + ".json");
    }
</code>```

The above will give you an array populated with all the results.

For example this is the content from the first item in the userRecords array:

```<code>    {"by":"ntrippar"
    ,"descendants":45
    ,"id":15853345
    ,"kids"[15858055,15854752,15856479,15854664,15858253,15856298,15854305,15855332,15858118,15857061,15854116]
    ,"score":159
    ,"time":1512494533
    ,"title":"Show HN: SeKey: An SSH Agent for OS X, Using Secure Enclave and TouchID, in Rust"
    ,"type":"story"
    ,"url":"https://github.com/ntrippar/sekey"}
</code>```

If you parse the above it will translate into an object.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to use Hacker News API , i am able to call the API and make the request to fetch the stories. As per their API documentation the source URL must contain the ID(required) to access the stories' content, I am getting the correct URL in the console and clicking on the URL gives the appropriate JSON  but beyond that I am unable to use/call the JSON content like author name,title etc.

JS CODE:

var records;
var userRecords;
var fileJson;
var startRequest = new XMLHttpRequest();
var sourceUrl = "https://hacker-news.firebaseio.com/v0/";
var sourceUrlAdd = "showstories.json";
var finalURL = sourceUrl + sourceUrlAdd;

startRequest.open("GET",finalURL);
startRequest.onload = function() {
    fileJson = JSON.parse(startRequest.responseText);
    for(var i = 0 ; i < fileJson.length; i++) {
        userRecords = sourceUrl + fileJson[i] + ".json";
    }
}
startRequest.send();

How do I make it work??

Body:
Looking at the information on: GitHub

Your URL in the loop should be modified to:

    for(var i = 0 ; i < fileJson.length; i++) {
       userRecords = sourceUrl + "/item/" + fileJson[i] + ".json";
    }

Your code doesn't look complete as the loop will just overwrite userRecords for every iteration, if you want to store them:

    userRecords = [];
    for(var i = 0 ; i < fileJson.length; i++) {
       userRecords.push(sourceUrl + "/item/" + fileJson[i] + ".json");
    }

The above will give you an array populated with all the results.

For example this is the content from the first item in the userRecords array:

    {"by":"ntrippar"
    ,"descendants":45
    ,"id":15853345
    ,"kids"[15858055,15854752,15856479,15854664,15858253,15856298,15854305,15855332,15858118,15857061,15854116]
    ,"score":159
    ,"time":1512494533
    ,"title":"Show HN: SeKey: An SSH Agent for OS X, Using Secure Enclave and TouchID, in Rust"
    ,"type":"story"
    ,"url":"https://github.com/ntrippar/sekey"}

If you parse the above it will translate into an object.


问:
Most efficient way to implement matrix functions?
I've been trying for a while to figure out the most efficient way of handling a two dimensional array (i.e. a matrix) that contains a variable.
I construct a large matrix by concatenating smaller arrays, weighted with a variable. As a simplified example, this is what I currently do.

```<code>function myMatrix(x::Float64)
    M = vcat(hcat(x*A, C), hcat(C, 2*x*B))
    return M
end

const A = ones(2,2)
const B = ones(2,2)
const C = zeros(2,2)
y_values = collect(0:0.01:10)

for y in y_values
    eivals, eivecs = eig(myMatrix(y))
    dosomething(eivals,eivecs)
end
</code>```

The problem: I have more (and more complex, non-diagonal) matrices and the final size is pretty large. At this moment, I call the function a few hundred times. Does anyone have a suggestion on what to do to make this process more efficient in terms of runtime?

Thanks in advance

答:
EDIT: Based on the comment below, this does not answer the question.

Do you mean constructing the Matrix? One way of doing that which is ideomatic is to use a block Matrix:

```<code>M = [x*A   C
    C    2x*B]
</code>```

Not sure if that's the most efficient in terms of runtime, sorry.

Body:
I've been trying for a while to figure out the most efficient way of handling a two dimensional array (i.e. a matrix) that contains a variable.
I construct a large matrix by concatenating smaller arrays, weighted with a variable. As a simplified example, this is what I currently do.

function myMatrix(x::Float64)
    M = vcat(hcat(x*A, C), hcat(C, 2*x*B))
    return M
end

const A = ones(2,2)
const B = ones(2,2)
const C = zeros(2,2)
y_values = collect(0:0.01:10)

for y in y_values
    eivals, eivecs = eig(myMatrix(y))
    dosomething(eivals,eivecs)
end

The problem: I have more (and more complex, non-diagonal) matrices and the final size is pretty large. At this moment, I call the function a few hundred times. Does anyone have a suggestion on what to do to make this process more efficient in terms of runtime?

Thanks in advance

Body:
EDIT: Based on the comment below, this does not answer the question.

Do you mean constructing the Matrix? One way of doing that which is ideomatic is to use a block Matrix:

M = [x*A   C
    C    2x*B]

Not sure if that's the most efficient in terms of runtime, sorry.


问:
Mininet/OpenFlow/POX - Connection between subnets
I'm working with a Mininet topology that has this structure with 3 switches and 4 hosts:

```<code>         +--+
         |s1|
         +--+
          |
    ------+---------
    |              |
   +--+          +--+
   |s2|          |s3|
   +--+          +--+
   |  |          |  |
+--+  +--+    +--+  +--+
|h1|  |h2|    |h3|  |h4|
+--+  +--+    +--+  +--+
</code>```

I'm also using POX in python to create an SDN controller for the network. And here is where my issue comes.

I'm just setting the switches like hubs to test connectivity and after that apply custom rules to the network.

Setting switches like hubs and just flooding all packets makes connectivity between hosts in the same subnet works (ie h1 can connect with h2 and h3 can connect with h4). However, I cannot make it for h1 to reach h3.

When I try to ping from one to the other it fails and prints "Destination Host Unreachable" and I cannot understand why.

For what I can see in the controller, s2 is flooding the packets but none of them are reaching s1. I've tried flooding with both of.OFPP_ALL and of.OFPP_FLOOD.

Mininet shows the links between nodes:

I really could use some help here. Either what do I need to do or where I can look it up. Because POX documentation is really bad and I can't find anything.

Solved

Got it.
My main problem here was setting s2 and s3 to connect to s1 on port 0 (reserved for the local interface) So when I tried to access that port something went wrong.

答: maybe you can assign ip addresses under the same subnet for all hosts</p>

ContentLicense: CC BY-SA 4.0

Body:
I'm working with a Mininet topology that has this structure with 3 switches and 4 hosts:

         +--+
         |s1|
         +--+
          |
    ------+---------
    |              |
   +--+          +--+
   |s2|          |s3|
   +--+          +--+
   |  |          |  |
+--+  +--+    +--+  +--+
|h1|  |h2|    |h3|  |h4|
+--+  +--+    +--+  +--+

I'm also using POX in python to create an SDN controller for the network. And here is where my issue comes.

I'm just setting the switches like hubs to test connectivity and after that apply custom rules to the network.

Setting switches like hubs and just flooding all packets makes connectivity between hosts in the same subnet works (ie h1 can connect with h2 and h3 can connect with h4). However, I cannot make it for h1 to reach h3.

When I try to ping from one to the other it fails and prints "Destination Host Unreachable" and I cannot understand why.

For what I can see in the controller, s2 is flooding the packets but none of them are reaching s1. I've tried flooding with both of.OFPP_ALL and of.OFPP_FLOOD.

Mininet shows the links between nodes:

I really could use some help here. Either what do I need to do or where I can look it up. Because POX documentation is really bad and I can't find anything.

Solved

Got it.
My main problem here was setting s2 and s3 to connect to s1 on port 0 (reserved for the local interface) So when I tried to access that port something went wrong.


问:
Rotating whole body in y-axis
I created a stick figure with
 tags and I want to rotate the figures whole body in itsY-Axis. I try to find out how I can rotate the middle of the body in itsY-axis, but its always out of place.

Here is how it looks now:

 @keyframes rotate{
0% {transform:rotate(0deg);}
50% {transform:rotate(135deg);}
0% {transform:rotate(0deg);}
 }

  @keyframes rotate2{
0% {transform:rotate(0deg);}
50% {transform:rotate(-135deg);}
0% {transform:rotate(0deg);}
 }

@keyframes rotate3{
 0% {transform: rotateY(0deg);}
 50% {transform: rotateY(360deg);}
 0% {transform: rotateY(0deg);}
 }

pre{
position:absolute;
text-shadow: 10px 10px 3px #DCDCDC;
font-size: 400%;
}

div{
border-bottom: 5px solid magenta;
position:absolute;
width: 160px;
left:200px;
bottom:50px;
/*margin-top: 0px;*/
/*margin-bottom: 0px;*/
}

.head{
 position:absolute;
animation-duration:4s;
animation-name:rotate3;
animation-iteration-count:infinite;
}

.legs{
 position:absolute;
animation-duration:4s;
animation-name:rotate3;
animation-iteration-count:infinite;
}

.leftleg.rightleg{
position:absolute;}

.stomach{
 position:absolute;
animation-duration:4s;
animation-name:rotate3;
animation-iteration-count:infinite;
}

.rightarm{
position:absolute;
transform-origin:top right;
animation-iteration-count: infinite;
animation-name:rotate;
animation-duration: 4s;
}

.leftarm{
 position:absolute;
 transform-origin: top left;
 animation-name:rotate2;
 animation-iteration-count: infinite;
animation-duration: 4s;
}

.arms{
 position:absolute;
animation-duration:4s;
animation-name:rotate3;
animation-iteration-count:infinite;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>```
  o
 / O \
 / \

```</code>```

答:
Add transform-origin: left to .stomach

 @keyframes rotate{
0% {transform:rotate(0deg);}
50% {transform:rotate(135deg);}
0% {transform:rotate(0deg);}
 }

  @keyframes rotate2{
0% {transform:rotate(0deg);}
50% {transform:rotate(-135deg);}
0% {transform:rotate(0deg);}
 }

@keyframes rotate3{
 0% {transform: rotateY(0deg);}
 50% {transform: rotateY(360deg);}
 0% {transform: rotateY(0deg);}
 }

pre{
position:absolute;
text-shadow: 10px 10px 3px #DCDCDC;
font-size: 400%;
}

div{
border-bottom: 5px solid magenta;
position:absolute;
width: 160px;
left:200px;
bottom:50px;
/*margin-top: 0px;*/
/*margin-bottom: 0px;*/
}

.head{
 position:absolute;
animation-duration:4s;
animation-name:rotate3;
animation-iteration-count:infinite;
}

.legs{
 position:absolute;
animation-duration:4s;
animation-name:rotate3;
animation-iteration-count:infinite;
}

.leftleg.rightleg{
position:absolute;}

.stomach{
 position:absolute;
animation-duration:4s;
animation-name:rotate3;
animation-iteration-count:infinite;
transform-origin: left;
}

.rightarm{
position:absolute;
transform-origin:top right;
animation-iteration-count: infinite;
animation-name:rotate;
animation-duration: 4s;
}

.leftarm{
 position:absolute;
 transform-origin: top left;
 animation-name:rotate2;
 animation-iteration-count: infinite;
animation-duration: 4s;
}

.arms{
 position:absolute;
animation-duration:4s;
animation-name:rotate3;
animation-iteration-count:infinite;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>```
  o
 / O \
 / \

```</code>```

Title: Rotating whole body in y-axis

Body:
I created a stick figure with
 tags and I want to rotate the figures whole body in itsY-Axis. I try to find out how I can rotate the middle of the body in itsY-axis, but its always out of place.

Here is how it looks now:

 @keyframes rotate{
0% {transform:rotate(0deg);}
50% {transform:rotate(135deg);}
0% {transform:rotate(0deg);}
 }

  @keyframes rotate2{
0% {transform:rotate(0deg);}
50% {transform:rotate(-135deg);}
0% {transform:rotate(0deg);}
 }

@keyframes rotate3{
 0% {transform: rotateY(0deg);}
 50% {transform: rotateY(360deg);}
 0% {transform: rotateY(0deg);}
 }

pre{
position:absolute;
text-shadow: 10px 10px 3px #DCDCDC;
font-size: 400%;
}

div{
border-bottom: 5px solid magenta;
position:absolute;
width: 160px;
left:200px;
bottom:50px;
/*margin-top: 0px;*/
/*margin-bottom: 0px;*/
}

.head{
 position:absolute;
animation-duration:4s;
animation-name:rotate3;
animation-iteration-count:infinite;
}

.legs{
 position:absolute;
animation-duration:4s;
animation-name:rotate3;
animation-iteration-count:infinite;
}

.leftleg.rightleg{
position:absolute;}

.stomach{
 position:absolute;
animation-duration:4s;
animation-name:rotate3;
animation-iteration-count:infinite;
}

.rightarm{
position:absolute;
transform-origin:top right;
animation-iteration-count: infinite;
animation-name:rotate;
animation-duration: 4s;
}

.leftarm{
 position:absolute;
 transform-origin: top left;
 animation-name:rotate2;
 animation-iteration-count: infinite;
animation-duration: 4s;
}

.arms{
 position:absolute;
animation-duration:4s;
animation-name:rotate3;
animation-iteration-count:infinite;
}

  o
 / O \
 / \

Body:
Add transform-origin: left to .stomach

 @keyframes rotate{
0% {transform:rotate(0deg);}
50% {transform:rotate(135deg);}
0% {transform:rotate(0deg);}
 }

  @keyframes rotate2{
0% {transform:rotate(0deg);}
50% {transform:rotate(-135deg);}
0% {transform:rotate(0deg);}
 }

@keyframes rotate3{
 0% {transform: rotateY(0deg);}
 50% {transform: rotateY(360deg);}
 0% {transform: rotateY(0deg);}
 }

pre{
position:absolute;
text-shadow: 10px 10px 3px #DCDCDC;
font-size: 400%;
}

div{
border-bottom: 5px solid magenta;
position:absolute;
width: 160px;
left:200px;
bottom:50px;
/*margin-top: 0px;*/
/*margin-bottom: 0px;*/
}

.head{
 position:absolute;
animation-duration:4s;
animation-name:rotate3;
animation-iteration-count:infinite;
}

.legs{
 position:absolute;
animation-duration:4s;
animation-name:rotate3;
animation-iteration-count:infinite;
}

.leftleg.rightleg{
position:absolute;}

.stomach{
 position:absolute;
animation-duration:4s;
animation-name:rotate3;
animation-iteration-count:infinite;
transform-origin: left;
}

.rightarm{
position:absolute;
transform-origin:top right;
animation-iteration-count: infinite;
animation-name:rotate;
animation-duration: 4s;
}

.leftarm{
 position:absolute;
 transform-origin: top left;
 animation-name:rotate2;
 animation-iteration-count: infinite;
animation-duration: 4s;
}

.arms{
 position:absolute;
animation-duration:4s;
animation-name:rotate3;
animation-iteration-count:infinite;
}

<pre>
  <span class="all"><span class="head">o</span>
 <span class="arms"><span class="rightarm">/</span> <span class="stomach">O</span> <span class="leftarm">\</span></span>
 <span class="legs"><span class="rightleg">/</span> <span class="leftleg">\</span></span><span>
 <div></div>
</pre>


问:
Azure SQL Data Warehouse Computed Column Error
I am really not sure what the error below is, but this statement works perfectly in Azure SQL Database but not on Azure SQL Data Warehouse. Is there anything specific to computed columns in SQL Data warehouse?

Here is the simple create table statement I am trying

CREATE TABLE Authors
(
 AuthorId int IDENTITY(1,1) NOT NULL,
 FirstName nvarchar(100),
 LastName nvarchar(100),
 FullName AS (FirstName + SPACE(1) + LastName) -- computed column
)

And the error:

Msg 103010, Level 16, State 1, Line 1
Parse error at line: 6, column: 11: Incorrect syntax near 'AS'.

答:
see Migrating Computed Columns

Computed columns are not supported in memory-optimized tables.
  However, you can simulate a computed column.

The reference suggests using a view to mimic the effect of non-persisted computed columns.

For persisted computed columns the reference proposes the use of stored procedures (one to insert another to update).

You would need to asses if the benefits of persisted data outweighs the simplicity of using views.


问:
React doesn't append class from className
I have a problem with React and don't know why, but React doesn't appent the attribute class in rendered HTML code. I import css file in body, import styles in react script, write className attribute, etc..

The result on page will be block without class –
test

In App.js

```<code>import React, {Component} from 'react';
import styles from '../assets/main.css';

export default class App extends Component {
    constructor(props) {
        super(props);
    }

    render() {
        return (
            <div>
                <div className={styles.test}>test</div>
            </div>
        );
    }
}
</code>```

In main.css

```<code>.test {
    color: red;
}
</code>```

Webpack config

```<code>const HTMLWebpackPlugin = require('html-webpack-plugin');
const HTMLWebpackPluginConfig = new HTMLWebpackPlugin({
    template: __dirname + '/app/index.html',
    filename: 'index.html',
    inject: 'body'
});
const webpack = require('webpack');

module.exports = {
    entry: [
        'react-hot-loader/patch',
        __dirname + '/app/index.js'
    ],
    devServer: {
        hot: true
    },
    module: {
        loaders: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                loader: 'babel-loader'
            },
            {
                test: /\.css$/,
                loader: "style-loader!css-loader"
            }
        ]
    },
    output: {
        filename: 'transformed.js',
        path: __dirname + '/build'
    },
    plugins: [
        HTMLWebpackPluginConfig,
        new webpack.NamedModulesPlugin(),
        new webpack.HotModuleReplacementPlugin()
    ],
    resolve: {
        extensions: ['.js', '.jsx', '.css']
    }
};
</code>```

答:
I think you should try importing your main.css file in your entry file i.e app/index.js. You don't need to add {styles.test} in className.

```<code>import './assets/main.css';
</code>```

When the webpack bundle will run it will take all your css.

You just need to give same className like :

```<code>        <div>
            <div className='test'>test</div>
        </div>
</code>```

Also, make sure you have installed all loaders like file-loader, css-loader, url-loader, style-loader and included them in your webpack.config file.

Body:
I have a problem with React and don't know why, but React doesn't appent the attribute class in rendered HTML code. I import css file in body, import styles in react script, write className attribute, etc..

The result on page will be block without class –
test

In App.js

import React, {Component} from 'react';
import styles from '../assets/main.css';

export default class App extends Component {
    constructor(props) {
        super(props);
    }

    render() {
        return (

test

        );
    }
}

In main.css

.test {
    color: red;
}

Webpack config

const HTMLWebpackPlugin = require('html-webpack-plugin');
const HTMLWebpackPluginConfig = new HTMLWebpackPlugin({
    template: __dirname + '/app/index.html',
    filename: 'index.html',
    inject: 'body'
});
const webpack = require('webpack');

module.exports = {
    entry: [
        'react-hot-loader/patch',
        __dirname + '/app/index.js'
    ],
    devServer: {
        hot: true
    },
    module: {
        loaders: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                loader: 'babel-loader'
            },
            {
                test: /\.css$/,
                loader: "style-loader!css-loader"
            }
        ]
    },
    output: {
        filename: 'transformed.js',
        path: __dirname + '/build'
    },
    plugins: [
        HTMLWebpackPluginConfig,
        new webpack.NamedModulesPlugin(),
        new webpack.HotModuleReplacementPlugin()
    ],
    resolve: {
        extensions: ['.js', '.jsx', '.css']
    }
};

Body:
I think you should try importing your main.css file in your entry file i.e app/index.js. You don't need to add {styles.test} in className.

import './assets/main.css';

When the webpack bundle will run it will take all your css.

You just need to give same className like :

        <div>
            <div className='test'>test</div>
        </div>

Also, make sure you have installed all loaders like file-loader, css-loader, url-loader, style-loader and included them in your webpack.config file.


问:
Can a scala object constructor be run twice as race condition?
I have an object with vars that will change only from inside the object and during the initialisation / construction  of the object instance.

Can the same object constructor be run twice by accident in a race condition scenario? Or Scala offers proper checks to ensure it can only be run once?

答: Yes, it's safe: the constructor runs in a static initializer. See e.g. http://blogs.tedneward.com/patterns/singleton-scala/.</p>


问:
Is there a way to check for shift held down THEN control held down for each input?
I'm trying to use _getch to get keyboard strokes for incrementing money in a game. If I want the money to be incremented faster, in 10's while shift is held down and 100's control is held down what would be the best way to do that? If I just check for shifts it's easy enough, but if I want to check for a shift then a control afterwards it won't work.

For instance checking to increment by 1 or 10 I'd do something like this

```<code>key = _getch();
if (key == 224)
{
    key = _getch();
    if (key == 75) // left arrow
    {
        if (GetAsyncKeyState(VK_SHIFT)
            for (int i = 0; i < 10; i++) // go left 10 times
                    left();
        else
            left();
    }
}
</code>```

If I add an else if for control for 100's it will NOT work. Most likely because running the GetAsyncKeyState fucntion again makes it not read the key state properly.

```<code>else if (GetAsyncKeyState(VK_CONTROL)
    for (int i = 0; i < 100; i++) // go left 100 times
        left();
</code>```

Any possible workaround? Thanks!

答:
Try the below code to make sure you can use multiple keys together. There is a limitation by the hardware to recognize simultaneous multiple key press so keep this in your mind.

Main calling function,

```<code>while(!keydown(VK_LCONTROL))
{
    if(keydown(VK_LCONTROL) && keydown(VK_NUMPAD1) && keydown(VK_UP))
    {
        cout << "combo pressed!" << endl;
    }
    Sleep(10);
}
</code>```

Function keydown,

```<code>BOOL keydown(int key)
{
    return (GetAsyncKeyState(key) & 0x8000) != 0;
}
</code>```

(GetAsyncKeyState(key) & 0x8000) != 0; We are only interested in the 15th bit so check this one. For further details check the respective bit's info.

Try combination of keys like control+numberpad1+Up for 1's increment, control+numberpad2+Up for 10's increment etc.

Body:
I'm trying to use _getch to get keyboard strokes for incrementing money in a game. If I want the money to be incremented faster, in 10's while shift is held down and 100's control is held down what would be the best way to do that? If I just check for shifts it's easy enough, but if I want to check for a shift then a control afterwards it won't work.

For instance checking to increment by 1 or 10 I'd do something like this

key = _getch();
if (key == 224)
{
    key = _getch();
    if (key == 75) // left arrow
    {
        if (GetAsyncKeyState(VK_SHIFT)
            for (int i = 0; i < 10; i++) // go left 10 times
                    left();
        else
            left();
    }
}

If I add an else if for control for 100's it will NOT work. Most likely because running the GetAsyncKeyState fucntion again makes it not read the key state properly.

else if (GetAsyncKeyState(VK_CONTROL)
    for (int i = 0; i < 100; i++) // go left 100 times
        left();

Any possible workaround? Thanks!

Body:
Try the below code to make sure you can use multiple keys together. There is a limitation by the hardware to recognize simultaneous multiple key press so keep this in your mind.

Main calling function,

while(!keydown(VK_LCONTROL))
{
    if(keydown(VK_LCONTROL) && keydown(VK_NUMPAD1) && keydown(VK_UP))
    {
        cout << "combo pressed!" << endl;
    }
    Sleep(10);
}

Function keydown,

BOOL keydown(int key)
{
    return (GetAsyncKeyState(key) & 0x8000) != 0;
}

(GetAsyncKeyState(key) & 0x8000) != 0; We are only interested in the 15th bit so check this one. For further details check the respective bit's info.

Try combination of keys like control+numberpad1+Up for 1's increment, control+numberpad2+Up for 10's increment etc.


问:
How to transfer my Firebase Realtime database to Firebase Cloud Firestore
I'm already using Firebase Realtime database, but now Firebase has launched Cloud Firestore for database so, how can I transfer my data from realtime database to firestore as I already have users and they are using realtime database on the android app.

So, is there a way that I can transfer the database to firestore?

答:
i made a script for converting data from firebase to firestore </p>

```<code>import { AngularFirestore, AngularFirestoreCollection } from 'angularfire2/firestore';
import { AngularFireDatabase } from 'angularfire2/database';
constructor(
private afs: AngularFirestore,
private angularfire: AngularFireDatabase
) { }convert() {
this.itemsCollection = this.afs.collection('requests'); //ref()
this.angularfire.list('/requests/').auditTrail().subscribe((data: any) => {
  _.each(data, element => {
    this.itemsCollection.doc(element.key).set(element.payload.val())
      .then((result) => {
      });
  });
});}
</code>```

Body:
i made a script for converting data from firebase to firestore

import { AngularFirestore, AngularFirestoreCollection } from 'angularfire2/firestore';
import { AngularFireDatabase } from 'angularfire2/database';
constructor(
private afs: AngularFirestore,
private angularfire: AngularFireDatabase
) { }convert() {
this.itemsCollection = this.afs.collection('requests'); //ref()
this.angularfire.list('/requests/').auditTrail().subscribe((data: any) => {
  _.each(data, element => {
    this.itemsCollection.doc(element.key).set(element.payload.val())
      .then((result) => {
      });
  });
});}


问:
Generate pdf with jspdf and Vue.js
I am new with Vue.js, and I am trying to generate a PDF, but I have no idea how to do it.

This is what I have:

```<code>import * as jsPDF  from "jspdf"

export default {

  props: ['id'],

  methods: {
    pdf () {
      const doc = new jsPDF()
    }
  }

}
</code>```

Error:

Property or method "pdf" is not defined on the instance but referenced during render

答:
First import the PDF library as:

```<code>import jsPDF from 'jspdf'
</code>```

Then simply instantiate the object and give it the contents:

```<code>methods: {
  createPDF () {
    let pdfName = 'test';
    var doc = new jsPDF();
    doc.text("Hello World", 10, 10);
    doc.save(pdfName + '.pdf');
  }
}
</code>```

Make sure to read the documentation for more

Title: Generate pdf with jspdf and Vue.js

Body:
I am new with Vue.js, and I am trying to generate a PDF, but I have no idea how to do it.

This is what I have:

import * as jsPDF  from "jspdf"

export default {

  props: ['id'],

  methods: {
    pdf () {
      const doc = new jsPDF()
    }
  }

}

Error:

Property or method "pdf" is not defined on the instance but referenced during render

Body:
First import the PDF library as:

import jsPDF from 'jspdf'

Then simply instantiate the object and give it the contents:

methods: {
  createPDF () {
    let pdfName = 'test';
    var doc = new jsPDF();
    doc.text("Hello World", 10, 10);
    doc.save(pdfName + '.pdf');
  }
}

Make sure to read the documentation for more


问:
Calling Method of another class from Recursion Method: Java
I have two class as A and B-

Class A:- This class has getData method, which is used to get data from DB.

```<code>class A {
    public synchronized getData() {
       // get some data from database, in finally block close connection
    }
}
</code>```

Class B:- Which has recursion method m(), inside this method I am calling the getData() of class A.

```<code>class B {
   m() {
      //some condition to terminate the recursion
      A a = new A();
      a.getData();
      m();
   }
}
</code>```

Error I am getting:-

java.lang.NullPointerException: null
      at com.mchange.v2.c3p0.impl.NewProxyConnection.getAutoCommit(NewProxyConnection.java:1226) ~[c3p0-0.9.5.1.jar:0.9.5.1]

For the first call of getData() method, I am able to get data from DB, but after second recursion onward I am getting the connection as closed. Any help would be highly appreciated.

Update:

I have DB Util method which is opening the connection each time when getData() method is calling. It's working fine if I am calling this without recursion method(many times) but if I am using recursion I'm getting error. Is any special case I have to handle for recursion method?

答:
The error specifies that connection is closed. Also, in your comment // get some data from database, in finally block close connection, you have mentioned that you have closed the connection after use but, you didn't mentioned that if you are opening the connection in he getData() method or not.

I would suggest following:

Check if you are opening the connection in getData() method. If not then either open the connection in this method only(remove the code for opening connection from some other method) or don't close the connection after use in this method instead use a different method to close the connection as per need.

Check if connection resource is reusable.

Body:
I have two class as A and B-

Class A:- This class has getData method, which is used to get data from DB.

class A {
    public synchronized getData() {
       // get some data from database, in finally block close connection
    }
}

Class B:- Which has recursion method m(), inside this method I am calling the getData() of class A.

class B {
   m() {
      //some condition to terminate the recursion
      A a = new A();
      a.getData();
      m();
   }
}

Error I am getting:-

java.lang.NullPointerException: null
      at com.mchange.v2.c3p0.impl.NewProxyConnection.getAutoCommit(NewProxyConnection.java:1226) ~[c3p0-0.9.5.1.jar:0.9.5.1]

For the first call of getData() method, I am able to get data from DB, but after second recursion onward I am getting the connection as closed. Any help would be highly appreciated.

Update:

I have DB Util method which is opening the connection each time when getData() method is calling. It's working fine if I am calling this without recursion method(many times) but if I am using recursion I'm getting error. Is any special case I have to handle for recursion method?


问:
gluster peer probe failed: <node> is either already part of another cluster or having volumes configured
I have 2 gluster clusters of type distributed-replicated:

Cluster 1 (C1): with bricks in machines M1 and M2.

Cluster 2 (C2): with bricks in machines M3 and M4.

I want to expand C1 by adding M4 (already part of C2) and another machine M5.

For adding the bricks, first I need to add M4 and M5 into C1 by probing M4 and M5 from either M1 or M2. When I do peer probe, I am able to add machine M5, but when I try to add M4 to C1 by

sudo gluster peer probe M4

I get:

peer probe: failed: M4 is either already part of another cluster or having volumes configured

I have two questions:

Is it even possible to achieve what I want (since I am mixing two different clusters)?

If yes, how to do it?

PS: I have read the following links but my issue still is not resolved:
redhat mailing list, redhat mailing list-2

答:
At any point of time, a node can be in only one cluster.

You should first do a gluster peer detach M4 of M4 from C2 and then you can add to C1.

Check this link:
http://docs.gluster.org/en/latest/Administrator%20Guide/Storage%20Pools/#removing-servers-from-the-trusted-storage-pool

# gluster peer detach <server>


问:
Groovy: Check if text contains a string more than one time
I want to check if the word "test" appears more than 1 time in the logs.
The following code just checks if the word 'test' appears more than 0 times in the string. (it just checks if the logs contain the word).

```<code> if (env.logs.contains('test')) {
      xxx
}
</code>```

What do I have to change to let this part of code check for more than one appearances of the word test?

答:
Increment a value when if condition is true

like as

```<code>int testCount=0;
 if (env.logs.contains('test')) {
  testCount++;
 }
</code>```

and check condtion

if testCount>0 then write somethinng what you want.

Body:
I want to check if the word "test" appears more than 1 time in the logs.
The following code just checks if the word 'test' appears more than 0 times in the string. (it just checks if the logs contain the word).

 if (env.logs.contains('test')) {
      xxx
}

What do I have to change to let this part of code check for more than one appearances of the word test?

Body:
Increment a value when if condition is true

like as

int testCount=0;
 if (env.logs.contains('test')) {
  testCount++;
 }

and check condtion

if testCount>0 then write somethinng what you want.


问:
How to add one column which is the count(*) from the table?
I have a table which includes only two columns: session_id, word_id , the table is session_word

We can get two values as the sql query below:

```<code>select count(*) as sum_word_freq from session_word
select count(distinct session_id) as sum_session_freq from session_word
</code>```

I have establish a table as

```<code>select word_id, count(*) as word_freq , count(distinct session_id) as word_session_freq
    from session_word
    group by word_id
</code>```

But I want to include the result with another two columns: sum_word_freq  and sum_session_freq .
How can I realize it in an intact sql query.

答:
If you want aggregations by different groups in a single query then using analytic functions is the solution:</p>

```<code>select
        word_id,
        word_freq,
        word_session_freq,
        --the sum for all dataset
        sum(word_freq)         over() as sum_word_freq,
        sum(word_session_freq) over() as sum_session_freq
from
(
 select word_id,
        count(*)                   as word_freq,
        count(distinct session_id) as word_session_freq
    from session_word
    group by word_id
)s;
</code>```

Body:
I have a table which includes only two columns: session_id, word_id , the table is session_word

We can get two values as the sql query below:

select count(*) as sum_word_freq from session_word
select count(distinct session_id) as sum_session_freq from session_word

I have establish a table as

select word_id, count(*) as word_freq , count(distinct session_id) as word_session_freq
    from session_word
    group by word_id

But I want to include the result with another two columns: sum_word_freq  and sum_session_freq .
How can I realize it in an intact sql query.

Body:
If you want aggregations by different groups in a single query then using analytic functions is the solution:

select
        word_id,
        word_freq,
        word_session_freq,
        --the sum for all dataset
        sum(word_freq)         over() as sum_word_freq,
        sum(word_session_freq) over() as sum_session_freq
from
(
 select word_id,
        count(*)                   as word_freq,
        count(distinct session_id) as word_session_freq
    from session_word
    group by word_id
)s;


问:
Service routine vs Interrupt service routine?
I've been reviewing some slides for the computer science class I am in and I've seen the word service routine thrown around a lot. Now I know what an interrupt service routine is but I can't really seem to find a set definition on what a service routine in general is.

Is there any difference between a service routine or an ISR is what I'm aiming to find out?

答:
There are two types of service routines in the LC-3

Trap Service Routines and Interrupt Service Routines.

A Trap Service Routine would be the code that gets executed as part of a trap.  The Trap vector table which contains the addresses of the trap service routines is located from x00 - xFF.  So if you wanted to see the code for the HALT trap look in memory address x25 and then that will tell you the address of the code that handles the HALT trap.

An Interrupt Service Routine is just code to handle an interrupt.  The LC-3 has only two things that can cause interrupts, the console and an exception.  The interrupt vector table is located from x100 - x1FF and like the TVT contains the addresses of the code to handle them.  For the console that would be x180, and for the two types of exceptions x100 and x101 (privelege mode exception, and illegal opcode respectively).


问:
android virtual keyboard listener
Though i have asked the question before but dint get any proper answer. I have an EditText when edit text is focused android virtual keyboard pops up, i have added Done button to the keyboard using ime option from property window. Now i want to perform some action by pressing the Done button. How to do this? Please any body help.</p>

答:
you an do it by firest finding reference of edittext and than set belows code for ur edittext:

```<code> editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            performSearch();//do here your stuff f
            return true;
        }
        return false;
    }
  });
</code>```

here i have taken editText name which is ref. editextbox which u added and you have to add actionId==type of ime options which u have setted

Title: android virtual keyboard listener

Body:
you an do it by firest finding reference of edittext and than set belows code for ur edittext:

 editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            performSearch();//do here your stuff f
            return true;
        }
        return false;
    }
  });

here i have taken editText name which is ref. editextbox which u added and you have to add actionId==type of ime options which u have setted


问:
Python blending concatenated Images
I am using Python and PIL to concatenate two images and trying to remove the attached boundary or seam to get a smoother and natural image without any artifacts.

```<code>def merge_images(image1, image2, mask):

    img1 = Image.open(image1)
    img2 = Image.open(image2)
    mask = Image.open(mask).convert('RGBA')

    #mask.show()

    height = img1.size[1] + (img2.size[1])
    width = img1.size[0]

    print(height , width)

    #height = img1.size[1]
    #width = img1.size[0]+(img2.size[0]/2)

    print(height - img1.size[1])

    newImage = Image.new("RGB", (width, height), (0,0,0))
    newImage.paste(img1, (0 , (height - img1.size[1])))
    #newImage.show()
    print(newImage.size)
    #newImage.paste(img1, ((width-img1.size[0]),0))
    newImage.paste(img2, (0 ,0), mask)

    return newImage
</code>```

This is referred from Blend Images

This is the expected output from the above link: Expected Output

I am not getting the same results and there is considerable seam in the concatenated image result.

Source:

The result is far off from the original. I am looking to remove the seam in the attached region and possibly the shadow at the bottom of the top image. I am guessing the problem is in the masking. Any suggestions would be very useful

Edit: Missed adding the mask image
Mask Image

答:
Here is an example I've created that demonstrates how you could blend two images using an alpha mask. Most import note,  width and height should be all same for all inputs. Images are attached to the source so it can be reproduced correctly.

The core idea is, that you multiply the pixels of lion image with the alpha, and use the rest to multiply it with the taj image. This is called weighted blending

```<code>import cv2
import numpy as np

lion = cv2.imread('lion.png',3)
taj = cv2.imread('taj.png',3)
alpha = cv2.imread('mask.png',0).astype(np.float32)

a_B, a_G, a_R = cv2.split(lion)
b_B, b_G, b_R = cv2.split(taj)

b = (a_B * (alpha/255.0)) + (b_B * (1.0 - (alpha/255.0)))
g = (a_G * (alpha/255.0)) + (b_G * (1.0 - (alpha/255.0)))
r = (a_R * (alpha/255.0)) + (b_R * (1.0 - (alpha/255.0)))
output = cv2.merge((b,g,r))

cv2.imwrite("lionoutput.png", output)
</code>```

Taj

lion

mask

Title: Python blending concatenated Images

Body:
I am using Python and PIL to concatenate two images and trying to remove the attached boundary or seam to get a smoother and natural image without any artifacts.

def merge_images(image1, image2, mask):

    img1 = Image.open(image1)
    img2 = Image.open(image2)
    mask = Image.open(mask).convert('RGBA')

    #mask.show()

    height = img1.size[1] + (img2.size[1])
    width = img1.size[0]

    print(height , width)

    #height = img1.size[1]
    #width = img1.size[0]+(img2.size[0]/2)

    print(height - img1.size[1])

    newImage = Image.new("RGB", (width, height), (0,0,0))
    newImage.paste(img1, (0 , (height - img1.size[1])))
    #newImage.show()
    print(newImage.size)
    #newImage.paste(img1, ((width-img1.size[0]),0))
    newImage.paste(img2, (0 ,0), mask)

    return newImage

This is referred from Blend Images

This is the expected output from the above link: Expected Output

I am not getting the same results and there is considerable seam in the concatenated image result.

Source:

The result is far off from the original. I am looking to remove the seam in the attached region and possibly the shadow at the bottom of the top image. I am guessing the problem is in the masking. Any suggestions would be very useful

Edit: Missed adding the mask image
Mask Image

Body:
Here is an example I've created that demonstrates how you could blend two images using an alpha mask. Most import note,  width and height should be all same for all inputs. Images are attached to the source so it can be reproduced correctly.

The core idea is, that you multiply the pixels of lion image with the alpha, and use the rest to multiply it with the taj image. This is called weighted blending

import cv2
import numpy as np

lion = cv2.imread('lion.png',3)
taj = cv2.imread('taj.png',3)
alpha = cv2.imread('mask.png',0).astype(np.float32)

a_B, a_G, a_R = cv2.split(lion)
b_B, b_G, b_R = cv2.split(taj)

b = (a_B * (alpha/255.0)) + (b_B * (1.0 - (alpha/255.0)))
g = (a_G * (alpha/255.0)) + (b_G * (1.0 - (alpha/255.0)))
r = (a_R * (alpha/255.0)) + (b_R * (1.0 - (alpha/255.0)))
output = cv2.merge((b,g,r))

cv2.imwrite("lionoutput.png", output)

Taj

lion

mask


问:
Initialization Configuration issues to integrate pyodbc with MSSQL Server via Web Browser
Initialization Configuration issues to integrate pyodbc with MSSQL Server via Web Browser

As I'm new to Python Web Programming

I need to code by clicking submit button that should retrive all the tables in the person database to the Web Browser via localhost.

What should be the server configuration to run with localhost:

Apache HTTP Server (or)

WSGI module (or)

Any Other Module/Server (pls Specify)

Check this below links that I have configured:

By adding one statement import pyodbc causes Internal Server Error in Apache HTTP Server

Importing pyodbc results as Internal server error in Apache HTTP Server

What should be my configuration to load pyodbc module on Apache Server to run simple queries mssql server database

I had tried with Apache HTTP Server with one command import pyodbc results in 500 Internal Server Error. But rest of the things worked fine with POST as well as in Python Shell.

I had coded this way. Kindly had anyone worked with Web Server via localhost let me know what should we need to add/modify with the below code

index.html

```<code><form action="/cgi-bin/hello_get.py" method="post">
Click the submmit button to retrive all the tables
<input type="submit" value="Submit" />
</form>
</code>```

hello_get.py

```<code>import pyodbc
cnxn = pyodbc.connect("Driver={ODBC Driver 13 for SQL Server};"
                      "Server=DESKTOP-C6RS3DO;"
                      "Database=demo2016;"
                      "Trusted_Connection=yes;")

cursor = cnxn.cursor()
cursor.execute('SELECT * FROM person')

print("Content-Type: text/html")
print("")
print("<html><head>")
print("")
print("</head><body>")
for row in cursor:
    print('row = %r' % (row,))

print("Hello from Python.")
print("</body></html>")

cursor.close()
cnxn.close()
</code>```

Do I need any extra modules and code from the above code?

 error.log

```<code>[cgi:error] [pid 9344:tid 1264] [client ::1:52332] AH01215:

End of script output before headers: hello_get.py, referer: http://localhost/index.html
Traceback (most recent call last):\r: C:/Apache24/htdocs/hello_get.py, referer: http://localhost/index.html
File "C:\\Apache24\\htdocs\\hello_get.py", line 6, in <module>\r: C:/Apache24/htdocs/hello_get.py, referer: http://localhost/index.html
import pyodbc\r: C:/Apache24/htdocs/hello_get.py, referer: http://localhost/index.html
ImportError: No module named pyodbc\r: C:/Apache24/htdocs/hello_get.py, referer: http://localhost/index.html
</code>```

But whenever try to load the module from httpd.config by adding

```<code> LoadModule pyodbc_module
 "c:/users/desktop/appdata/local/programs/python/python36-32/lib/site-packages/pyodbc.cp36-win32.pyd"
</code>```

and restarting the server results in httpd -k restart

```<code>httpd: Syntax error on line 576 of C:/Apache24/conf/httpd.conf: Can't locate API module structure `pyodbc_module' in file C:/Users/Vitriv-Desktop/AppData/Local/Programs/Python/Python36-32/Lib/site-packages/pyodbc.cp36-win32.pyd: No error
</code>```

答:
In Apache 500 Internal Error Solved. Because of importing pypyodbc.

In python shell I was able to connect successfully retrive the results in python shell as well as MSSQL Server 2017.

ex.py

```<code>    import sys
    sys.path.insert(0, 'C:/Users/Vitriv-Desktop/AppData/Local/Programs/Python/Python36-32/Lib/site-packages')
    import pypyodbc
    import cgi, cgitb

    # Create instance of FieldStorage
    form = cgi.FieldStorage()

    # Get data from fields
    first_name = form.getvalue('first_name')
    last_name  = form.getvalue('last_name')

    print("Content-Type:text/html\r\n\r\n")
    print("<html>")
    print("<head>")
    print("<title>Hello - Second CGI Program</title>")
    print("</head>")
    print("<body>")

    print("<h2>Hello %s %s</h2>" % (first_name, last_name))
    cnxn = pypyodbc.connect(driver='{ODBC Driver 13 for SQL Server}', server='DESKTOP-C6RS3DO', database='demo2016', Trusted_Connection='Yes')

    cursor = cnxn.cursor()
    cursor.execute('SELECT * FROM person')
    for row in cursor:
        print('row = %r' % (row,))
    print("<h2>Hello %s %s</h2>" % (first_name, last_name))
    cursor.close()
    cnxn.close()

    print("</body>")
    print("</html>")
</code>```

Index.html

```<code><form action="ex.py" method="post">
First Name: <input type="text" name="first_name">  <br />

Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form>
</code>```

Body:
Initialization Configuration issues to integrate pyodbc with MSSQL Server via Web Browser

As I'm new to Python Web Programming

I need to code by clicking submit button that should retrive all the tables in the person database to the Web Browser via localhost.

What should be the server configuration to run with localhost:

Apache HTTP Server (or)

WSGI module (or)

Any Other Module/Server (pls Specify)

Check this below links that I have configured:

By adding one statement import pyodbc causes Internal Server Error in Apache HTTP Server

Importing pyodbc results as Internal server error in Apache HTTP Server

What should be my configuration to load pyodbc module on Apache Server to run simple queries mssql server database

I had tried with Apache HTTP Server with one command import pyodbc results in 500 Internal Server Error. But rest of the things worked fine with POST as well as in Python Shell.

I had coded this way. Kindly had anyone worked with Web Server via localhost let me know what should we need to add/modify with the below code

index.html

<form action="/cgi-bin/hello_get.py" method="post">
Click the submmit button to retrive all the tables
<input type="submit" value="Submit" />
</form>

hello_get.py

import pyodbc
cnxn = pyodbc.connect("Driver={ODBC Driver 13 for SQL Server};"
                      "Server=DESKTOP-C6RS3DO;"
                      "Database=demo2016;"
                      "Trusted_Connection=yes;")

cursor = cnxn.cursor()
cursor.execute('SELECT * FROM person')

print("Content-Type: text/html")
print("")
print("")
print("")
print("")
for row in cursor:
    print('row = %r' % (row,))

print("Hello from Python.")
print("")

cursor.close()
cnxn.close()

Do I need any extra modules and code from the above code?

 error.log

[cgi:error] [pid 9344:tid 1264] [client ::1:52332] AH01215:

End of script output before headers: hello_get.py, referer: http://localhost/index.html
Traceback (most recent call last):\r: C:/Apache24/htdocs/hello_get.py, referer: http://localhost/index.html
File "C:\\Apache24\\htdocs\\hello_get.py", line 6, in <module>\r: C:/Apache24/htdocs/hello_get.py, referer: http://localhost/index.html
import pyodbc\r: C:/Apache24/htdocs/hello_get.py, referer: http://localhost/index.html
ImportError: No module named pyodbc\r: C:/Apache24/htdocs/hello_get.py, referer: http://localhost/index.html

But whenever try to load the module from httpd.config by adding

 LoadModule pyodbc_module
 "c:/users/desktop/appdata/local/programs/python/python36-32/lib/site-packages/pyodbc.cp36-win32.pyd"

and restarting the server results in httpd -k restart

httpd: Syntax error on line 576 of C:/Apache24/conf/httpd.conf: Can't locate API module structure `pyodbc_module' in file C:/Users/Vitriv-Desktop/AppData/Local/Programs/Python/Python36-32/Lib/site-packages/pyodbc.cp36-win32.pyd: No error

Body:
In Apache 500 Internal Error Solved. Because of importing pypyodbc.

In python shell I was able to connect successfully retrive the results in python shell as well as MSSQL Server 2017.

ex.py

    import sys
    sys.path.insert(0, 'C:/Users/Vitriv-Desktop/AppData/Local/Programs/Python/Python36-32/Lib/site-packages')
    import pypyodbc
    import cgi, cgitb

    # Create instance of FieldStorage
    form = cgi.FieldStorage()

    # Get data from fields
    first_name = form.getvalue('first_name')
    last_name  = form.getvalue('last_name')

    print("Content-Type:text/html\r\n\r\n")
    print("<html>")
    print("<head>")
    print("<title>Hello - Second CGI Program</title>")
    print("</head>")
    print("<body>")

    print("<h2>Hello %s %s</h2>" % (first_name, last_name))
    cnxn = pypyodbc.connect(driver='{ODBC Driver 13 for SQL Server}', server='DESKTOP-C6RS3DO', database='demo2016', Trusted_Connection='Yes')

    cursor = cnxn.cursor()
    cursor.execute('SELECT * FROM person')
    for row in cursor:
        print('row = %r' % (row,))
    print("<h2>Hello %s %s</h2>" % (first_name, last_name))
    cursor.close()
    cnxn.close()

    print("</body>")
    print("</html>")

Index.html

<form action="ex.py" method="post">
First Name: <input type="text" name="first_name">  <br />

Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form>


问:
vba Run-time error '429': ActiveX can't create object, with user defined vb.net dll (VB.NET 2017, Excel 2016)
I have written a simple dll in VB.NET 2017, and I am trying to call it from VBA (Excel 2016).  I have searched through Stack Overflow and MSDN, but despite many hits for this VBA error, I cannot find information related to a user defined dll that solves this particular problem.

I checked the box for the Register for COM Interop option when compiling the dll.  I also verified that the Make assembly COM-Visible box was also checked.

Compilation was successful, and I was able to find my library (called TestLibrary2) in References inside the VBA editor.  The class I created in it is called TestVBNET.  I checked TestLibrary2 to include it in VBA, and then attempted to run the following code in VBA:

```<code>Public Sub mySub()
    Dim myTest2 As TestLibrary2.TestVBNet
    Set myTest2 = New TestLibrary2.TestVBNet
End Sub
</code>```

When I ran the sub, I got the pop-up dialog with message: Run-time error '429': ActiveX can't create object

Based on what I have read on MSDN and other sites, the expected result is that the TestLibrary2.TestVBNet object should be instantiated successfully.

The code below is the VB.NET code that I compiled to the dll. The GUID's were generated using guidgen at the Windows 10 command prompt.

```<code>    Imports System.Runtime.InteropServices
    <Guid("2CEBF80D-D5FC-4C52-BCF1-E2F076318240")>
    Public Interface ITestVBNet
        Function addTrig(x As Double, y As Double) As Double
    End Interface

    <Guid("60983277-A724-4CDD-8ACE-B94CF9546F43")>
    <ClassInterface(ClassInterfaceType.None)>
    Public Class TestVBNet
        Function addTrig(x As Double, y As Double) As Double
            Return Math.Sin(x) + Math.Cos(x)
        End Function

    End Class
</code>```

Any help and or references would be greatly appreciated.  Thanks in advance.

EDIT (per comments below):  I compiled the dll as admin, which in fact was required for the Register for COM Interop option to run.  I also tried using regasm -- also as admin -- as follows, in the same directory as the compiled dll:

```<code>regasm /codebase /tlb TestLibrary2.dll
</code>```

The following was returned:

```<code>RegAsm : warning RA0000 : Registering an unsigned assembly with /codebase can cause your assembly to interfere with other applications that may be installed on the same computer. The /codebase switch is intended to be used only with signed assemblies. Please give your assembly a strong name and re-register it.
Types registered successfully
RegAsm : error RA0000 : An error occurred while saving the exported type library: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
</code>```

I apologize for being a newb here with respect to registering COM libraries, but what this seemed to indicate was the dll was registered successfully, but could not be transferred to the GAC.  It was my intention not to transfer it.  When I tried loading it in VBA, the same error as above occurred.

答:
It turns out that the above code compiled to a dll that was indeed callable from a C# client.  The problem with VBA, however, was that I neglected to put Implements ITestVBNet following the derived class declaration.  In VB.NET, though, in addition to this, one must also explicitly indicate function overriding in the derived function declaration as well; viz (scroll all the way to the right to see the entire line),

```<code>Public Function addTrig(x As Double, y As Double) As Double Implements ITestVBNet.addTrig
</code>```

By replacing the derived class above with the following, I was able to create an instance of the TestVBNet object in VBA and call the addTrig(.) method successfully:

```<code><Guid("60983277-A724-4CDD-8ACE-B94CF9546F43")>
<ClassInterface(ClassInterfaceType.None)>
Public Class TestVBNet
    Implements ITestVBNet

    Public Function addTrig(x As Double, y As Double) As Double Implements ITestVBNet.addTrig
        Return Math.Sin(x) + Math.Cos(x)
    End Function
End Class
</code>```

Body:
I have written a simple dll in VB.NET 2017, and I am trying to call it from VBA (Excel 2016).  I have searched through Stack Overflow and MSDN, but despite many hits for this VBA error, I cannot find information related to a user defined dll that solves this particular problem.

I checked the box for the Register for COM Interop option when compiling the dll.  I also verified that the Make assembly COM-Visible box was also checked.

Compilation was successful, and I was able to find my library (called TestLibrary2) in References inside the VBA editor.  The class I created in it is called TestVBNET.  I checked TestLibrary2 to include it in VBA, and then attempted to run the following code in VBA:

Public Sub mySub()
    Dim myTest2 As TestLibrary2.TestVBNet
    Set myTest2 = New TestLibrary2.TestVBNet
End Sub

When I ran the sub, I got the pop-up dialog with message: Run-time error '429': ActiveX can't create object

Based on what I have read on MSDN and other sites, the expected result is that the TestLibrary2.TestVBNet object should be instantiated successfully.

The code below is the VB.NET code that I compiled to the dll. The GUID's were generated using guidgen at the Windows 10 command prompt.

    Imports System.Runtime.InteropServices
    <Guid("2CEBF80D-D5FC-4C52-BCF1-E2F076318240")>
    Public Interface ITestVBNet
        Function addTrig(x As Double, y As Double) As Double
    End Interface

    <Guid("60983277-A724-4CDD-8ACE-B94CF9546F43")>
    <ClassInterface(ClassInterfaceType.None)>
    Public Class TestVBNet
        Function addTrig(x As Double, y As Double) As Double
            Return Math.Sin(x) + Math.Cos(x)
        End Function

    End Class

Any help and or references would be greatly appreciated.  Thanks in advance.

EDIT (per comments below):  I compiled the dll as admin, which in fact was required for the Register for COM Interop option to run.  I also tried using regasm -- also as admin -- as follows, in the same directory as the compiled dll:

regasm /codebase /tlb TestLibrary2.dll

The following was returned:

RegAsm : warning RA0000 : Registering an unsigned assembly with /codebase can cause your assembly to interfere with other applications that may be installed on the same computer. The /codebase switch is intended to be used only with signed assemblies. Please give your assembly a strong name and re-register it.
Types registered successfully
RegAsm : error RA0000 : An error occurred while saving the exported type library: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))

I apologize for being a newb here with respect to registering COM libraries, but what this seemed to indicate was the dll was registered successfully, but could not be transferred to the GAC.  It was my intention not to transfer it.  When I tried loading it in VBA, the same error as above occurred.

Body:
It turns out that the above code compiled to a dll that was indeed callable from a C# client.  The problem with VBA, however, was that I neglected to put Implements ITestVBNet following the derived class declaration.  In VB.NET, though, in addition to this, one must also explicitly indicate function overriding in the derived function declaration as well; viz (scroll all the way to the right to see the entire line),

Public Function addTrig(x As Double, y As Double) As Double Implements ITestVBNet.addTrig

By replacing the derived class above with the following, I was able to create an instance of the TestVBNet object in VBA and call the addTrig(.) method successfully:

<Guid("60983277-A724-4CDD-8ACE-B94CF9546F43")>
<ClassInterface(ClassInterfaceType.None)>
Public Class TestVBNet
    Implements ITestVBNet

    Public Function addTrig(x As Double, y As Double) As Double Implements ITestVBNet.addTrig
        Return Math.Sin(x) + Math.Cos(x)
    End Function
End Class


问:
How can I start a clickonce application with the visual studio debugger?
I'm using visual studio 2012.

I have a click once application that crashes on startup so I can't attach the the debugger to it after it starts running.

I'd like to be able to add the path to an executable which will start the clickonce app in the form below but I can't figure out the path of the executable to use. I'm in doubt there is actually an executable anywhere that's not wrapped up in some XML envelope.

Is this possible?

答:
Normally it would have been quite easy if your app were not crashing.

Go to task manager right click on the relevant process and select "open file location". Just in case you need to do it again for a different issue.


问:
Xcode cannot find a java class which I'm trying to extend
I'm working on a Java project which was written by someone else. This person made a hierarchy of folders inside the 'src' folder. I've added a new java class into one of those folders and defined it as 'XmlFile.java'.
Then, I'm trying to have it extend a previously written class 'GenericFile.java' by writing

```<code>package //Same package GenericFile is in

public class XmlFile extends GenericFile
{
...
}
</code>```

When I try to compile the project it gives me the error

```<code>Cannot find symbol
</code>```

and refers me to the line

```<code>public class XmlFile extends GenericFile
</code>```

if I take out

```<code>extends GenericFile
</code>```

everything compiles great.

I also notice after adding the new file (XmlFile.java) I cannot delete it (the option in Edit->Delete is not selectable for that file, or for any files/folders created by the person from whom I got the project).

Is there some sort of permission issue here or some hidden scope issue caused by the permissions being strange or what?

Please help me

Cheers,
WhiteTiger

答:
I admit I am not an expert enough to figure out "Cannot find symbol" from a Java compiler, but since there is no other answer, here is a sneaky idea -

If GenericFile is a working and useful abstract class, there has to be at least one other class (hopefully working) that extends it. Since you have the source code, find out one such file, copy it to XmlFile.java, edit it to change the constructor name to XmlFile and try to compile it. If it compiles, start from there. If not, you will know where the problem lies.

Just trying to help! Good luck, - M.S.

Body:
I'm working on a Java project which was written by someone else. This person made a hierarchy of folders inside the 'src' folder. I've added a new java class into one of those folders and defined it as 'XmlFile.java'.
Then, I'm trying to have it extend a previously written class 'GenericFile.java' by writing

package //Same package GenericFile is in

public class XmlFile extends GenericFile
{
...
}

When I try to compile the project it gives me the error

Cannot find symbol

and refers me to the line

public class XmlFile extends GenericFile

if I take out

extends GenericFile

everything compiles great.

I also notice after adding the new file (XmlFile.java) I cannot delete it (the option in Edit->Delete is not selectable for that file, or for any files/folders created by the person from whom I got the project).

Is there some sort of permission issue here or some hidden scope issue caused by the permissions being strange or what?

Please help me

Cheers,
WhiteTiger


问:
Cells disappearing during animation of UITableView
I have a normal UITableView in my UIViewController, constrained to fullscreen. This tableView has a custom interactive tableHeaderView. The tableHeaderView is dynamic in size, and expands on its own.
The headerView has a textField, and will change its own size depending on wether the textField has focus or not.

The problem is that the cells at the bottom of the screen aren't always animating correctly when changing the size of the tableHeaderView.
I am calling tableView.beginUpdates() and tableView.endUpdates() after layoutIfNeeded() inside my animation-block. This has to be done, or the cells won't follow the dynamic size at all.

I've made this gif. Look specifically at the bottom cells during the animation. I have slowed down the animation considerably, so it's easy to see the problem.

Speculation: It seems to me like the tableView calls for cellForRow:indexPath: as soon as the animation starts, and somehow finds out what state the entire tableView will be in after the animation, and removing the unnecessary cells, even though the animation has not yet completed.
The same way, when collapsing the header: the bottommost cells are not animated in the same way as the already loaded cells. They are animated in with a different animation..

Why is this happening? Is this preventable?

Edit: Animation code

```<code>self.navigationController?.setNavigationBarHidden(isEditing, animated: true)

var frame = tableHeaderView.frame
frame.size.height = tableHeaderView.headerHeight(forEditing: isEditing)

UIView.animate(withDuration: 0.3, animations: {

    if isEditing{
        let point = CGPoint(x: 0, y: -self.topLayoutGuide.length)
        self.tableView.setContentOffset(point, animated: false)
    }

    tableHeaderView.frame = frame
    tableHeaderView.layoutIfNeeded()
    self.view.layoutIfNeeded()
    self.tableView.beginUpdates()
    self.tableView.endUpdates()
}) { [weak self](completed:Bool) in
    //Do stuff
}
</code>```

答:
I just heard back from the Apple Developer Technical Support team regarding this issue, and here's their response verbatim (emphasis mine):

Hello Nicolas,

Thank you for contacting Apple Developer Technical Support (DTS).

The behavior and resulting limitations you describe are by design.

If you believe an alternative approach should be considered by Apple,
  we encourage you to file an enhancement request with information on
  how this design decision impacts you, and what you’d like to see done
  differently.

Although there is no promise that the behavior will be changed, it is
  the best way to ensure your thoughts on the matter are seen by the
  team responsible for the decision.

Best Regards,

Apple Developer Technical Support

It seems we're just stuck with having to use a simple call to either tableView.setContentOffset(_:animated:) or tableView.scrollToRow(at:at:animated:).

Body:
I have a normal UITableView in my UIViewController, constrained to fullscreen. This tableView has a custom interactive tableHeaderView. The tableHeaderView is dynamic in size, and expands on its own.
The headerView has a textField, and will change its own size depending on wether the textField has focus or not.

The problem is that the cells at the bottom of the screen aren't always animating correctly when changing the size of the tableHeaderView.
I am calling tableView.beginUpdates() and tableView.endUpdates() after layoutIfNeeded() inside my animation-block. This has to be done, or the cells won't follow the dynamic size at all.

I've made this gif. Look specifically at the bottom cells during the animation. I have slowed down the animation considerably, so it's easy to see the problem.

Speculation: It seems to me like the tableView calls for cellForRow:indexPath: as soon as the animation starts, and somehow finds out what state the entire tableView will be in after the animation, and removing the unnecessary cells, even though the animation has not yet completed.
The same way, when collapsing the header: the bottommost cells are not animated in the same way as the already loaded cells. They are animated in with a different animation..

Why is this happening? Is this preventable?

Edit: Animation code

self.navigationController?.setNavigationBarHidden(isEditing, animated: true)

var frame = tableHeaderView.frame
frame.size.height = tableHeaderView.headerHeight(forEditing: isEditing)

UIView.animate(withDuration: 0.3, animations: {

    if isEditing{
        let point = CGPoint(x: 0, y: -self.topLayoutGuide.length)
        self.tableView.setContentOffset(point, animated: false)
    }

    tableHeaderView.frame = frame
    tableHeaderView.layoutIfNeeded()
    self.view.layoutIfNeeded()
    self.tableView.beginUpdates()
    self.tableView.endUpdates()
}) { [weak self](completed:Bool) in
    //Do stuff
}


问:
Error: use of overloaded operator '[]' is ambiguous
I'm getting this error with some old inherited code that previously compiled under Android NDK version r8e (GCC). I'm trying to upgrade to compile using the Android NDK version r16 (Clang).  I haven't used C++ since university many years ago, but I'm not new to programming.

The method signatures look consistent with the headers, I can't see any other operator signatures that might cause ambiguity.  I'm not sure why it's ambiguous when the parameter is clearly an int.  What is the cause of this error?

Commenting out one of the operators fixes the issue, but both operators are needed.

Header:

```<code>class XmlNode
{
public:
    // ... - let me know if you think I might have snipped anything important
    XmlNode &operator[](int idx) const;
    XmlNode &operator[](const String &name);
    // ...
};

class XmlDoc : public XmlNode
{
public:
    // snipped ... no further overrides here
};
</code>```

Class:

```<code>// ...

XmlNode &operator[](int idx) const
{
    return *list[idx];
}

XmlNode &operator[](const String &name)
{
    // ...
    if(found)
    {
        // ...
        return *list[IndexOf(head)];
    }
    // not found - create new entry
    return Add(name);   // add the whole path
}
</code>```

Code in context:

```<code>// ...
int idx = xml.IndexOf("METHOD");
// ...
MyClient::setSaveTrace(xml[idx][0].GetTextAsInt("SaveTrace", TRUE));
</code>```

Error:

```<code>C:/.../myclass.cpp:3392:41: error: use of overloaded operator '[]' is ambiguous (with operand types 'KIT::XmlDoc' and 'int')
    MyClient::setSaveTrace(xml[idx][0].GetTextAsInt("SaveTrace", TRUE));
                           ~~~^~~~
C:/.../KIT-Xml.h:94:14: note: candidate function
    XmlNode &operator[](int idx) const;
             ^
C:/.../KIT-Xml.h:95:11: note: candidate function
    XmlNode &operator[](const String &name);
             ^
</code>```

答:
Starting here:

```<code>class XmlNode
{
public:
    // ... - let me know if you think I might have snipped anything important
    XmlNode &operator[](int idx) const;
    XmlNode &operator[](const String &name);
    // ...
};
</code>```

There are two operators: one const the other non-const.

For:

```<code>XmlDoc xml;
int idx;

xml[idx];
</code>```

this is ambiguous because the compiler obviously cannot decide which implicit cast to apply.

Either:

```<code>((const XmlDoc&)xml).operator[](idx) // for the first
</code>```

or:

```<code>xml.operator[](String::fromInt(idx)) // for the second
</code>```

Remark:

Paul McKenzy suggested that there might be an implicit conversion from String to int causing this trouble. While writing this down, I come to the conclusion it must be the opposite – there is an implicit conversion from int to String. Without knowing better, I just called it String::fromInt(int) (but it might be also String::String(int) or anything else).

To solve the ambiguity I first suggested the explicit const-cast:

```<code>((const XmlNode&)xml)[idx]
</code>```

but this was still not sufficient. (I'm not sure if this is a weakness of the specific compiler which is used.) Probably, the compiler still applies an implicit cast from const XmlNode& to XmlDoc& and thus recognizes still the same ambiguity. (It's just speculation.) Hence, my new suggestion:

```<code>((const XmlDoc&)xml[idx]
</code>```

This caused progress. (The ambiguity moved to the second operator[].)

Thus, the complete solution to the issue:

```<code>((const XmlNode&)((const XmlDoc&)xml)[idx])[0]
</code>```

Questioner reported success.

I have to admit that I cannot tell whether this behavior is according to (which) C++ standard.

Body:
I'm getting this error with some old inherited code that previously compiled under Android NDK version r8e (GCC). I'm trying to upgrade to compile using the Android NDK version r16 (Clang).  I haven't used C++ since university many years ago, but I'm not new to programming.

The method signatures look consistent with the headers, I can't see any other operator signatures that might cause ambiguity.  I'm not sure why it's ambiguous when the parameter is clearly an int.  What is the cause of this error?

Commenting out one of the operators fixes the issue, but both operators are needed.

Header:

class XmlNode
{
public:
    // ... - let me know if you think I might have snipped anything important
    XmlNode &operator[](int idx) const;
    XmlNode &operator[](const String &name);
    // ...
};

class XmlDoc : public XmlNode
{
public:
    // snipped ... no further overrides here
};

Class:

// ...

XmlNode &operator[](int idx) const
{
    return *list[idx];
}

XmlNode &operator[](const String &name)
{
    // ...
    if(found)
    {
        // ...
        return *list[IndexOf(head)];
    }
    // not found - create new entry
    return Add(name);   // add the whole path
}

Code in context:

// ...
int idx = xml.IndexOf("METHOD");
// ...
MyClient::setSaveTrace(xml[idx][0].GetTextAsInt("SaveTrace", TRUE));

Error:

C:/.../myclass.cpp:3392:41: error: use of overloaded operator '[]' is ambiguous (with operand types 'KIT::XmlDoc' and 'int')
    MyClient::setSaveTrace(xml[idx][0].GetTextAsInt("SaveTrace", TRUE));
                           ~~~^~~~
C:/.../KIT-Xml.h:94:14: note: candidate function
    XmlNode &operator[](int idx) const;
             ^
C:/.../KIT-Xml.h:95:11: note: candidate function
    XmlNode &operator[](const String &name);
             ^

Body:
Starting here:

class XmlNode
{
public:
    // ... - let me know if you think I might have snipped anything important
    XmlNode &operator[](int idx) const;
    XmlNode &operator[](const String &name);
    // ...
};

There are two operators: one const the other non-const.

For:

XmlDoc xml;
int idx;

xml[idx];

this is ambiguous because the compiler obviously cannot decide which implicit cast to apply.

Either:

((const XmlDoc&)xml).operator[](idx) // for the first

or:

xml.operator[](String::fromInt(idx)) // for the second

Remark:

Paul McKenzy suggested that there might be an implicit conversion from String to int causing this trouble. While writing this down, I come to the conclusion it must be the opposite – there is an implicit conversion from int to String. Without knowing better, I just called it String::fromInt(int) (but it might be also String::String(int) or anything else).

To solve the ambiguity I first suggested the explicit const-cast:

((const XmlNode&)xml)[idx]

but this was still not sufficient. (I'm not sure if this is a weakness of the specific compiler which is used.) Probably, the compiler still applies an implicit cast from const XmlNode& to XmlDoc& and thus recognizes still the same ambiguity. (It's just speculation.) Hence, my new suggestion:

((const XmlDoc&)xml[idx]

This caused progress. (The ambiguity moved to the second operator[].)

Thus, the complete solution to the issue:

((const XmlNode&)((const XmlDoc&)xml)[idx])[0]

Questioner reported success.

I have to admit that I cannot tell whether this behavior is according to (which) C++ standard.


问:
Wcf Rest Service GET Method Unable to display JSON data
I created wcf Rest Service to accept the POST , GET and DELETE Operation. When issue a GET request to the server ,its does not display the JSON data and displaying [] sign in Google chrome .

Here is the interface.

```<code>[OperationContract]
[WebInvoke(Method = "GET",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/GetCustomers/{prefix}")]
string GetCustomers(string prefix);
</code>```

Here is the Implementation .

```<code>public string GetCustomers(string prefix)
{

    List<object> customers = new List<object>();
    string sql = "SELECT * FROM Current_Account_Holder_Details WHERE Account_Holder_Last_Name LIKE @prefix + '%'";
    using (SqlConnection conn = new SqlConnection())
    {
        conn.ConnectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
        using (SqlCommand cmd = new SqlCommand(sql))
        {
            cmd.Parameters.AddWithValue("@prefix", prefix);
            cmd.Connection = conn;
            conn.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                while (sdr.Read())
                {
                    customers.Add(new
                    {
                        Tittle = sdr["Tittle"],
                        Account_Holder_First_Name = sdr["Account_Holder_First_Name"],
                        Account_Holder_Last_Name = sdr["Account_Holder_Last_Name"],
                        Account_Holder_DOB = sdr["Account_Holder_DOB"],
                        Account_Holder_House_No = sdr["Account_Holder_House_No"],
                        Account_Holder_Street_Name = sdr["Account_Holder_Street_Name"],
                        Account_Holder_Post_Code = sdr["Account_Holder_Post_Code"],
                        Account_Holder_Occupation = sdr["Account_Holder_Occupation"],
                        Account_Number = sdr["Account_Number"]
                     });
                 }
             }
             conn.Close();
         }
         return (new JavaScriptSerializer().Serialize(customers));
     }
}
</code>```

Here is the .SVC file.

```<code><%@ ServiceHost Language="C#" Debug="true" Service="HalifaxWCFProject.HalifaxService"%>
</code>```

Here is the web.config file.

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
  <connectionStrings>
    <add name="DBCS" connectionString="Data Source=;Initial Catalog=HalifaxDatabase;Integrated Security=True" providerName="System.Data.SqlClient" />
    <add name="HalifaxDatabaseEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=;initial catalog=HalifaxDatabase;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
  </connectionStrings>
  <system.serviceModel>
    <services>
      <service name="HalifaxWCFProject.HalifaxService" behaviorConfiguration="mexBehaviour">
        <endpoint address="" binding="webHttpBinding" bindingConfiguration="" behaviorConfiguration="REST" contract="HalifaxWCFProject.IHalifaxService" />
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8080/" />
          </baseAddresses>
        </host>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="mexBehaviour">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="REST">
          <webHttp />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="false" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.web>
    <compilation debug="true" />
  </system.web>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-10.0.0.0" newVersion="10.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>
</code>```

Here is the screen shot.

答:
I do it this way. Also are you sure about this part RequestFormat = WebMessageFormat.Json ?

```<code>[OperationContract]
[WebInvoke(Method = "GET",
           ResponseFormat = WebMessageFormat.Json,
           BodyStyle = WebMessageBodyStyle.Wrapped,
           UriTemplate = "register?serverCode={serverCode}")]
string Registration(string strVal);
public string Registration(string strVal)
{
    return "";
}
</code>```

Hope this helps.

Body:
I created wcf Rest Service to accept the POST , GET and DELETE Operation. When issue a GET request to the server ,its does not display the JSON data and displaying [] sign in Google chrome .

Here is the interface.

[OperationContract]
[WebInvoke(Method = "GET",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/GetCustomers/{prefix}")]
string GetCustomers(string prefix);

Here is the Implementation .

public string GetCustomers(string prefix)
{

    List<object> customers = new List<object>();
    string sql = "SELECT * FROM Current_Account_Holder_Details WHERE Account_Holder_Last_Name LIKE @prefix + '%'";
    using (SqlConnection conn = new SqlConnection())
    {
        conn.ConnectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
        using (SqlCommand cmd = new SqlCommand(sql))
        {
            cmd.Parameters.AddWithValue("@prefix", prefix);
            cmd.Connection = conn;
            conn.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                while (sdr.Read())
                {
                    customers.Add(new
                    {
                        Tittle = sdr["Tittle"],
                        Account_Holder_First_Name = sdr["Account_Holder_First_Name"],
                        Account_Holder_Last_Name = sdr["Account_Holder_Last_Name"],
                        Account_Holder_DOB = sdr["Account_Holder_DOB"],
                        Account_Holder_House_No = sdr["Account_Holder_House_No"],
                        Account_Holder_Street_Name = sdr["Account_Holder_Street_Name"],
                        Account_Holder_Post_Code = sdr["Account_Holder_Post_Code"],
                        Account_Holder_Occupation = sdr["Account_Holder_Occupation"],
                        Account_Number = sdr["Account_Number"]
                     });
                 }
             }
             conn.Close();
         }
         return (new JavaScriptSerializer().Serialize(customers));
     }
}

Here is the .SVC file.

<%@ ServiceHost Language="C#" Debug="true" Service="HalifaxWCFProject.HalifaxService"%>

Here is the web.config file.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <connectionStrings>
    <add name="DBCS" connectionString="Data Source=;Initial Catalog=HalifaxDatabase;Integrated Security=True" providerName="System.Data.SqlClient" />
    <add name="HalifaxDatabaseEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=;initial catalog=HalifaxDatabase;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
  </connectionStrings>
  <system.serviceModel>
    <services>
      <service name="HalifaxWCFProject.HalifaxService" behaviorConfiguration="mexBehaviour">
        <endpoint address="" binding="webHttpBinding" bindingConfiguration="" behaviorConfiguration="REST" contract="HalifaxWCFProject.IHalifaxService" />
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8080/" />
          </baseAddresses>
        </host>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="mexBehaviour">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="REST">
          <webHttp />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="false" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.web>
    <compilation debug="true" />
  </system.web>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-10.0.0.0" newVersion="10.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

Here is the screen shot.

Body:
I do it this way. Also are you sure about this part RequestFormat = WebMessageFormat.Json ?

[OperationContract]
[WebInvoke(Method = "GET",
           ResponseFormat = WebMessageFormat.Json,
           BodyStyle = WebMessageBodyStyle.Wrapped,
           UriTemplate = "register?serverCode={serverCode}")]
string Registration(string strVal);
public string Registration(string strVal)
{
    return "";
}

Hope this helps.