问:
Ajax fails when sending a data object to the NodeJs server
when pressing a button this code gets executed

```<code>function submitData() {
    $.ajax({
        type: 'GET',
        url: '/questionnaire/submit', // listen to a route
        dataType: "json",
        data: JSON.stringify({ // some test data
            satisfactory: "house",
            improvement: "bla",
            rating: "this is a text"
        })
    }).done(function () {
        $(location).attr('href', '/sendOff'); // redirect to another route
    }).fail(function () {
        console.log("Error");
    });
}
</code>```

and the server is listening on this

```<code>app.get('/questionnaire/submit', function (req, res) {
    var data = req.query; // Get the data object from the Ajax call

    console.log(data);

    res.send(null); // Send nothing back
});
</code>```

Whenever pressing the button, "Error" gets logged in the console. The Ajax call always fails.

Even when writing res.send("Success"); the client will log "Error". What am I missing?

Update:
I installed the body parser middleware and use this code now

my app.js

```<code>const path = require('path');
const express = require('express');
const exphbs  = require('express-handlebars');
const bodyParser = require('body-parser');

const handlebars = exphbs.create({
    defaultLayout: 'index',
    extname: 'hbs'
});

const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

require('./Server/Routes/questionnaire')(app);
require('./Server/Routes/sendOff')(app);

app.engine('hbs', handlebars.engine);
app.set('view engine', 'hbs');

app.use(express.static(path.join(__dirname, 'Public')));

app.listen(8888, function () {
    console.log('Server running on port 8888');
});
</code>```

my route

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

    app.get('/questionnaire', function (req, res) {
        res.render('questionnaire');
    });

    app.post('/questionnaire/submit', function (req, res) {
        var data = req.body;

        console.log(data);

        res.send(null);
    });
};
</code>```

and my client function

```<code>function submitData() {
    $.ajax({
        type: 'POST',
        url: '/questionnaire/submit',
        dataType: "json",
        data: JSON.stringify({
            satisfactory: $("#edtSatisfactory").val(),
            improvement: $("#edtImprovement").val(),
            rating: currentRating / ratingElements.length
        })
    }).done(function () {
        $(location).attr('href', '/sendOff');
    }).fail(function () {

    });
}
</code>```

And when executing the Ajax call the client still runs into .fail()

答:
You're using a GET http method, which shouldn't take body, you should instead append your data to the back of the url. Or if you want to use a body, then switch to a POST.

```<code>url: '/questionnaire/submit?satisfactory=house&improvement=bla&rating=sometext
</code>```

If you're using POST don't forget:

```<code>'Content-Type': 'application/json',
</code>```

Edit: On the server you need to parse the JSON request, this is best done with a middleware called body-parser:

```<code>npm install --save body-parser
const bodyParser = require('body-parser');
app.use(bodyParser.json());
</code>```

This will parse your JSON and add it to req.body.

Body:
when pressing a button this code gets executed

function submitData() {
    $.ajax({
        type: 'GET',
        url: '/questionnaire/submit', // listen to a route
        dataType: "json",
        data: JSON.stringify({ // some test data
            satisfactory: "house",
            improvement: "bla",
            rating: "this is a text"
        })
    }).done(function () {
        $(location).attr('href', '/sendOff'); // redirect to another route
    }).fail(function () {
        console.log("Error");
    });
}

and the server is listening on this

app.get('/questionnaire/submit', function (req, res) {
    var data = req.query; // Get the data object from the Ajax call

    console.log(data);

    res.send(null); // Send nothing back
});

Whenever pressing the button, "Error" gets logged in the console. The Ajax call always fails.

Even when writing res.send("Success"); the client will log "Error". What am I missing?

Update:
I installed the body parser middleware and use this code now

my app.js

const path = require('path');
const express = require('express');
const exphbs  = require('express-handlebars');
const bodyParser = require('body-parser');

const handlebars = exphbs.create({
    defaultLayout: 'index',
    extname: 'hbs'
});

const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

require('./Server/Routes/questionnaire')(app);
require('./Server/Routes/sendOff')(app);

app.engine('hbs', handlebars.engine);
app.set('view engine', 'hbs');

app.use(express.static(path.join(__dirname, 'Public')));

app.listen(8888, function () {
    console.log('Server running on port 8888');
});

my route

module.exports = function (app) {

    app.get('/questionnaire', function (req, res) {
        res.render('questionnaire');
    });

    app.post('/questionnaire/submit', function (req, res) {
        var data = req.body;

        console.log(data);

        res.send(null);
    });
};

and my client function

function submitData() {
    $.ajax({
        type: 'POST',
        url: '/questionnaire/submit',
        dataType: "json",
        data: JSON.stringify({
            satisfactory: $("#edtSatisfactory").val(),
            improvement: $("#edtImprovement").val(),
            rating: currentRating / ratingElements.length
        })
    }).done(function () {
        $(location).attr('href', '/sendOff');
    }).fail(function () {

    });
}

And when executing the Ajax call the client still runs into .fail()

Body:
You're using a GET http method, which shouldn't take body, you should instead append your data to the back of the url. Or if you want to use a body, then switch to a POST.

url: '/questionnaire/submit?satisfactory=house&improvement=bla&rating=sometext

If you're using POST don't forget:

'Content-Type': 'application/json',

Edit: On the server you need to parse the JSON request, this is best done with a middleware called body-parser:

npm install --save body-parser
const bodyParser = require('body-parser');
app.use(bodyParser.json());

This will parse your JSON and add it to req.body.


来源: stackexchange

问:
How do I use a converter in NativeScript?
I'm trying to use a simple converter in {N}. I have read the docs at https://docs.nativescript.org/core-concepts/data-binding#using-converters-in-bindings about 14 times so far but I do not understand the concept because the documentation seem to be very vague. They use a half finished example of a dateConverter, and they do...

```<code>source.set("dateConverter", dateConverter);
source.set("testDate", new Date());
page.bindingContext = source;
</code>```

...without explaining where is the "source" is coming from or how do they set it up? Also, I already have a page.bindingContext assigned so I don't know how do I relate that to the example provided in the docs.

This is my XML file:

```<code><page navigatingTo="onNavigatingTo" backgroundColor="orange">
    <action-bar title="{{ name, name | uppercase }}" class="action-bar" />

    <stack-layout orientation="vertical" verticalAlignment="center">
        <label text="Welcome to Page-B" textAlignment="center" />
    </stack-layout>
</page>
</code>```

I want the title of the actionBar to be uppercased, so I add an uppercase converter (or at least trying to). Here's the corresponding js file:

```<code>exports.onNavigatingTo = function(args) {
    var page = args.object;
    page.bindingContext = page.navigationContext;

    var uppercase = {
        toView: function(value) {
            console.log(`value: ${value}`);
            return value.toUpperCase();
        }
    }
}
</code>```

I get the error: Cannot find function or filter: uppercase

I know I'm missing some sort of binding somewhere, to bind the converter to something else, but I have no idea how to do this. Anyone could provide a small example based on this?

I have seen this similar question Using nativescript converters but that is not helpful because I am also not using Angular (just plain NativeScript/JS) and that post doesn't have a meaningful, concluded answer either.

答:
The uppercase method should be part of your view-model as you are binding it in your XML. Detailed article section about converters in plain JS and/or TypeScript projects can be found here

e.g.

```<code>var uppercase = {
    toView: function(value) {
        console.log(`value: ${value}`);
        return value.toUpperCase();
    }
}

myViewModel.set("uppercase", uppercase); // e.g. myViewModel === new Observable();

page.bindingContext = myViewModel;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to use a simple converter in {N}. I have read the docs at https://docs.nativescript.org/core-concepts/data-binding#using-converters-in-bindings about 14 times so far but I do not understand the concept because the documentation seem to be very vague. They use a half finished example of a dateConverter, and they do...

source.set("dateConverter", dateConverter);
source.set("testDate", new Date());
page.bindingContext = source;

...without explaining where is the "source" is coming from or how do they set it up? Also, I already have a page.bindingContext assigned so I don't know how do I relate that to the example provided in the docs.

This is my XML file:

<page navigatingTo="onNavigatingTo" backgroundColor="orange">
    <action-bar title="{{ name, name | uppercase }}" class="action-bar" />

    <stack-layout orientation="vertical" verticalAlignment="center">

    </stack-layout>
</page>

I want the title of the actionBar to be uppercased, so I add an uppercase converter (or at least trying to). Here's the corresponding js file:

exports.onNavigatingTo = function(args) {
    var page = args.object;
    page.bindingContext = page.navigationContext;

    var uppercase = {
        toView: function(value) {
            console.log(`value: ${value}`);
            return value.toUpperCase();
        }
    }
}

I get the error: Cannot find function or filter: uppercase

I know I'm missing some sort of binding somewhere, to bind the converter to something else, but I have no idea how to do this. Anyone could provide a small example based on this?

I have seen this similar question Using nativescript converters but that is not helpful because I am also not using Angular (just plain NativeScript/JS) and that post doesn't have a meaningful, concluded answer either.

Body:
The uppercase method should be part of your view-model as you are binding it in your XML. Detailed article section about converters in plain JS and/or TypeScript projects can be found here

e.g.

var uppercase = {
    toView: function(value) {
        console.log(`value: ${value}`);
        return value.toUpperCase();
    }
}

myViewModel.set("uppercase", uppercase); // e.g. myViewModel === new Observable();

page.bindingContext = myViewModel;


问:
Material-ui table pagination
I am using Material-ui table for listing data. table will load all data at once from remote server. Is there any way to load data through pagination, as page changes data has to be fetched from remote.

when page loads i will get data from following code.

```<code>const options = { method: 'GET', headers: { Origin: '*' } };
    fetch(`https://some-url/user_groups`, options)
        .then(function (result) {
           //i will get data here
        })
        .catch(error => console.log('error while fetching ', error));
</code>```

答:
Follow following steps:

Step 1. Change the server side to return only 1 page of data, and also return number of available records.

```<code>/api/getData?offset=5&limit=10
</code>```

Step 2. On your react components, or redux store, create following state:

```<code>{
    data: list of data item to display on the table
    page: the current page of the table
    resultCount: number of available records
}
</code>```

Step 3. Implement loadData to load the current page of data & result count.

Step 4. On component mount & page change event, reload the data.

Title: Material-ui table pagination

Body:
I am using Material-ui table for listing data. table will load all data at once from remote server. Is there any way to load data through pagination, as page changes data has to be fetched from remote.

when page loads i will get data from following code.

const options = { method: 'GET', headers: { Origin: '*' } };
    fetch(`https://some-url/user_groups`, options)
        .then(function (result) {
           //i will get data here
        })
        .catch(error => console.log('error while fetching ', error));

Body:
Follow following steps:

Step 1. Change the server side to return only 1 page of data, and also return number of available records.

/api/getData?offset=5&limit=10

Step 2. On your react components, or redux store, create following state:

{
    data: list of data item to display on the table
    page: the current page of the table
    resultCount: number of available records
}

Step 3. Implement loadData to load the current page of data & result count.

Step 4. On component mount & page change event, reload the data.


问:
Can't get Share Button aligned!
I'm trying to align the share, like and tweet button horizontally but I can't get the share button right. I tried adding vertical align top, changing the height and display:inline but it always remains more or less 10px belowe the others. What should I do to get them all aligned?

```<code><div style='vertical-align: top;'>

<a expr:share_url='data:post.url' name='fb_share'/>

<a class='twitter-share-button' data-count='horizontal' data-lang='es' data-related=':' data-via='' expr:data-text='data:post.title' expr:data-url='data:post.url' href='http://twitter.com/share' rel='nofollow'/>

<iframe allowTransparency='true' expr:src='"http://www.facebook.com/plugins/like.php?href=" + data:post.url + "&layout=button_count&show_faces=false&width=100&action=like&font=arial&colorscheme=light"' frameborder='0' scrolling='no' style='border:none; overflow:hidden; width:110px; height:20px;'/>
</div>

<script src='http://static.ak.fbcdn.net/connect.php/js/FB.Share' type='text/javascript'>
</script>

<script src='http://platform.twitter.com/widgets.js' type='text/javascript'>
</script>
</code>```

Thanks

答:
to do display:inline you can wrap each control into list like this:

```<code>  <ul><li>
<a class=....../>
</li> <li> <a expr....../> </li></ul>
</code>```

Also, add: list-style-type:none;
To make your controls stick to the right side of the screen,
do:
position:absolute;
right:0;

ContentLicense: CC BY-SA 2.5

Title: Can't get Share Button aligned!

Body:
I'm trying to align the share, like and tweet button horizontally but I can't get the share button right. I tried adding vertical align top, changing the height and display:inline but it always remains more or less 10px belowe the others. What should I do to get them all aligned?

Thanks

Body:
to do display:inline you can wrap each control into list like this:

  <ul><li>
<a class=....../>
</li> <li> <a expr....../> </li></ul>

Also, add: list-style-type:none;
To make your controls stick to the right side of the screen,
do:
position:absolute;
right:0;


问:
Mysql query with and conditions
I've two tables,

table 1

```<code>userid  filter
thiru   1
thiru   2
thiru   3
raja    1
raja    2
</code>```

table 2

```<code>headline    filter1 filter2
test          1       3
test2         1       2
</code>```

If I want to select the users applicable for filters.

when i select test - thiru is applicable ( filter1 and filter2 ) matching

when i select test2 - thiru and raja are applicable ( filter1 and filter2 ) matching.

Basically the filters are with and condition.

Here is the query that i tried:

```<code>select userid
  from table1
 where filter in (select filter1
                    from table2
                   where headline = 'test')
   and filter in (select filter2
                    from table2
                   where headline = 'test');
</code>```

Please give me the query for this.
Thanks in advance.

答:
You can get the desired results for your both filters by using following approach

```<code>select a.userid
from table1 a
left join table2 b on a.filter = b.filter1
left join table2 b1 on a.filter = b1.filter2
group by a.userid
having sum(b.headline = 'test')
and sum(b1.headline = 'test')
</code>```

demo(test) , demo(test2)

Title: Mysql query with and conditions

Body:
I've two tables,

table 1

userid  filter
thiru   1
thiru   2
thiru   3
raja    1
raja    2

table 2

headline    filter1 filter2
test          1       3
test2         1       2

If I want to select the users applicable for filters.

when i select test - thiru is applicable ( filter1 and filter2 ) matching

when i select test2 - thiru and raja are applicable ( filter1 and filter2 ) matching.

Basically the filters are with and condition.

Here is the query that i tried:

select userid
  from table1
 where filter in (select filter1
                    from table2
                   where headline = 'test')
   and filter in (select filter2
                    from table2
                   where headline = 'test');

Please give me the query for this.
Thanks in advance.

Body:
You can get the desired results for your both filters by using following approach

select a.userid
from table1 a
left join table2 b on a.filter = b.filter1
left join table2 b1 on a.filter = b1.filter2
group by a.userid
having sum(b.headline = 'test')
and sum(b1.headline = 'test')

demo(test) , demo(test2)


问:
How to keep footer at the bottom of page under the body content
What I am trying to accomplish is to get the footer of all my pages underneath the content of the body. All pages will have different sizes of body content. The challenging bit for me is to keep only one CSS for all pages.

I tried my best showing the css and HTML here but no luck. Instead here is a the JSFiddle of my code: https://jsfiddle.net/zsrsd20m/

```<code> .container {
min-height:80%;
position:relative;
}

.titleText{
width:100%;
padding-top: 35px;
padding-bottom: 35px;
background-color: #127577;

color: white;
text-align: center;
}

.navBar{
 padding-right: 20px;
 float:left;
 }

.mainText{
 height:100%;
 padding-left:220px;
 padding-right:250px;
 padding-bottom:0px;
 font-size: 20px;
 text-align: justify;
}

.footerText{
 width:100%;
 padding-top: 35px;
 padding-top: 23px;
 background-color: #127577;
 color: white;
 text-align: center;
}
</code>```

.Container and all the other Divs made in HTML was made because of this: http://matthewjamestaylor.com/blog/keeping-footers-at-the-bottom-of-the-page

I want it so that even if the body content is too small the footer always stays at the bottom of the page. Same applies for if the body content is big. Currently when setting the height of the body content to 100% it shows me a scroll bar even when the content is small and doesnt need a scroll bar. When removing the height it makes the footer directly under the small body content which is half good but its not at the bottom of the page so it looks horrible.

Screenshots of the problems:
https://imgur.com/a/x16RC

答:
Try this.

```<code><div class="navbar navbar-default navbar-fixed-bottom">
    <div class="container">
      <p class="navbar-text pull-left">© 2014 - Site Built By Mr. M.
           <a href="" >Test Link</a>
      </p>

      <a href="" class="navbar-btn btn-danger btn pull-right">
      <span class="glyphicon glyphicon-star"></span>Copyright 2017</a>
    </div>
</code>```

Reference: https://bootsnipp.com/snippets/featured/easy-sticky-footer

ContentLicense: CC BY-SA 4.0

Body:
What I am trying to accomplish is to get the footer of all my pages underneath the content of the body. All pages will have different sizes of body content. The challenging bit for me is to keep only one CSS for all pages.

I tried my best showing the css and HTML here but no luck. Instead here is a the JSFiddle of my code: https://jsfiddle.net/zsrsd20m/

 .container {
min-height:80%;
position:relative;
}

.titleText{
width:100%;
padding-top: 35px;
padding-bottom: 35px;
background-color: #127577;

color: white;
text-align: center;
}

.navBar{
 padding-right: 20px;
 float:left;
 }

.mainText{
 height:100%;
 padding-left:220px;
 padding-right:250px;
 padding-bottom:0px;
 font-size: 20px;
 text-align: justify;
}

.footerText{
 width:100%;
 padding-top: 35px;
 padding-top: 23px;
 background-color: #127577;
 color: white;
 text-align: center;
}

.Container and all the other Divs made in HTML was made because of this: http://matthewjamestaylor.com/blog/keeping-footers-at-the-bottom-of-the-page

I want it so that even if the body content is too small the footer always stays at the bottom of the page. Same applies for if the body content is big. Currently when setting the height of the body content to 100% it shows me a scroll bar even when the content is small and doesnt need a scroll bar. When removing the height it makes the footer directly under the small body content which is half good but its not at the bottom of the page so it looks horrible.

Screenshots of the problems:
https://imgur.com/a/x16RC

Body:
Try this.

<div class="navbar navbar-default navbar-fixed-bottom">
    <div class="container">
      <p class="navbar-text pull-left">© 2014 - Site Built By Mr. M.
           <a href="" >Test Link</a>
      </p>

      <a href="" class="navbar-btn btn-danger btn pull-right">
      <span class="glyphicon glyphicon-star"></span>Copyright 2017</a>
    </div>

Reference: https://bootsnipp.com/snippets/featured/easy-sticky-footer


答:
Essentially you're looking to join the two tables together on the filter in table1 being either = to filter1 or = filter2, and you only want usernames that appear twice in the joined list. This is what the group by does => afte rthe tables are joined together, it groups up the number of times the username appears. Then the HAVING COUNT(*) > 1 excludes all usernames that only appear once (i.e. only matched one of the filter1 or filter2)

```<code>SELECT
  userid
FROM
  table1 t1
  INNER JOIN
  table2 t2
  ON
    t1.filter=t2.filter1 OR
    t1.filter=t2.filter2
WHERE
  t2.headline = 'test'
GROUP BY
  userid
HAVING COUNT(*) > 1
</code>```

Your own query was actually almost working, but it has a fatal flaw:

You wrote WHERE filter in (something) AND filter in (somethingelse). A number 1 is never = to 1 AND 3 at the same time, so there is no one row whose filter can be 1 AND 3 simultaneously.. There are DIFFERENT rows that can match this, but for that your query would need to be:

```<code>select userid from table1
where
  filter in (select filter1 from table2 where headline = 'test') OR
  filter in (select filter2 from table2 where headline = 'test')
</code>```

I only changed the AND to OR.. This would return two rows for THIRU and one row for RAJA, so we would still need to group it up and count them:

```<code>select userid from table1
where
  filter in (select filter1 from table2 where headline = 'test') OR
  filter in (select filter2 from table2 where headline = 'test')
GROUP BY username HAVING COUNT(*)>1
</code>```

Soo.. you were close, you just need to think about things as row by row

Title: Mysql query with and conditions

Body:
Essentially you're looking to join the two tables together on the filter in table1 being either = to filter1 or = filter2, and you only want usernames that appear twice in the joined list. This is what the group by does => afte rthe tables are joined together, it groups up the number of times the username appears. Then the HAVING COUNT(*) > 1 excludes all usernames that only appear once (i.e. only matched one of the filter1 or filter2)

SELECT
  userid
FROM
  table1 t1
  INNER JOIN
  table2 t2
  ON
    t1.filter=t2.filter1 OR
    t1.filter=t2.filter2
WHERE
  t2.headline = 'test'
GROUP BY
  userid
HAVING COUNT(*) > 1

Your own query was actually almost working, but it has a fatal flaw:

You wrote WHERE filter in (something) AND filter in (somethingelse). A number 1 is never = to 1 AND 3 at the same time, so there is no one row whose filter can be 1 AND 3 simultaneously.. There are DIFFERENT rows that can match this, but for that your query would need to be:

select userid from table1
where
  filter in (select filter1 from table2 where headline = 'test') OR
  filter in (select filter2 from table2 where headline = 'test')

I only changed the AND to OR.. This would return two rows for THIRU and one row for RAJA, so we would still need to group it up and count them:

select userid from table1
where
  filter in (select filter1 from table2 where headline = 'test') OR
  filter in (select filter2 from table2 where headline = 'test')
GROUP BY username HAVING COUNT(*)>1

Soo.. you were close, you just need to think about things as row by row


问:
C# - List of objects, containing list of sub-objects
I have a question regarding on how to structure my code :

I want to display in 4 different ListView, list of objects.
Concretely, I have a list of Contract, each Contract contain a list of Subcontract, each Subcontracts has a list of assemblies, and each Assembly contain a list of Detail.
For Database I have no problem, I made a table for each Object, and they are linked by Id.

But until now, when I go from a ListView to another, I made a double-clic on my Contract, to display the ListView containing all its Subcontract. It also means a SQL request everytime.

I just got the idea to add in my Contract object, a property :

```<code>List<Subcontract> ListSubcontract {get;set;}
</code>```

In my Subcontract object add property :

```<code>List<Assembly> ListAssemblies {get;set;}
</code>```

Ans for Assembly :

```<code>List<Detail> ListDetails {get;set;}
</code>```

I am just wondering in term of performance, is this a good thing to make so, because my Contract objects will have a list, of list, of list...

So regarding to you is this better to make a SQL query on every "double-clic" when I want to "navigate"? Or is this better to load "all at once my list of contracts, and then just navigate in my objects already built, updating only the ListCollections?

Thanks in advance for your advises

答: Start with the simplest and most flexible solution, when and if you detect performance issues, you can address them. And if round-trips to the database are expensive, there are various ways you can cache data to optimize it.  Having said that, if you know ahead of time you need to fetch a lot of data, minimising the number of queries is usually a good strategy.</p>

Body:
I have a question regarding on how to structure my code :

I want to display in 4 different ListView, list of objects.
Concretely, I have a list of Contract, each Contract contain a list of Subcontract, each Subcontracts has a list of assemblies, and each Assembly contain a list of Detail.
For Database I have no problem, I made a table for each Object, and they are linked by Id.

But until now, when I go from a ListView to another, I made a double-clic on my Contract, to display the ListView containing all its Subcontract. It also means a SQL request everytime.

I just got the idea to add in my Contract object, a property :

List<Subcontract> ListSubcontract {get;set;}

In my Subcontract object add property :

List<Assembly> ListAssemblies {get;set;}

Ans for Assembly :

List<Detail> ListDetails {get;set;}

I am just wondering in term of performance, is this a good thing to make so, because my Contract objects will have a list, of list, of list...

So regarding to you is this better to make a SQL query on every "double-clic" when I want to "navigate"? Or is this better to load "all at once my list of contracts, and then just navigate in my objects already built, updating only the ListCollections?

Thanks in advance for your advises


问:
Acces Outlook via Visual Basic error
I'm trying to create a program which retrieves all emails from Outlook's(2007 desktop version) Inbox and puts them into a DataGridView.

Code:

```<code>Imports Outlook = Microsoft.Office.Interop.Outlook

Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim dt As DataTable
    Try
        Dim app As Outlook.Application = New Outlook.Application()
        Dim ns As Outlook.[NameSpace] = app.GetNamespace("MAPI")
        Dim inbox As Outlook.MAPIFolder = ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox)
        ns.SendAndReceive(True)
        dt = New DataTable("Inbox")
        dt.Columns.Add("Subject", GetType(String))
        dt.Columns.Add("Sender", GetType(String))
        dt.Columns.Add("Body", GetType(String))
        dt.Columns.Add("Date", GetType(String))
        DataGridView1.DataSource = dt
        For Each item As Object In inbox.Items
            If TypeOf item Is Outlook.MailItem Then
                Dim item1 As Outlook.MailItem = CType(item, Outlook.MailItem)
                dt.Rows.Add(New Object() {item1.Subject, item1.Sender, item1.HTMLBody, item1.SentOn.ToLongDateString() & "" + item1.SentOn.ToLongTimeString()})
            End If
        Next
        MessageBox.Show("done")
    Catch ex As Exception
        MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.[Error])
    End Try
End Sub
End Class
</code>```

When I try to Build the project I'm getting the follow error:

System.Runtime.InteropServices.COMException (0x80040154): Retrieving the COM class factory for component with CLSID {0006F03A-0000-0000-C000-000000000046} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))

UPDATE

I've changed the Compiler CPU to x86 and x64, this does not solve the error.

Target platform

答: The problem causing the error was that both applications(VS2015 and MS Office 2007) were not running under the same rights. Open both applications with same rights(administrator or user) and the application will work. Thanks for the help!</p>

Title: Acces Outlook via Visual Basic error

Body:
I'm trying to create a program which retrieves all emails from Outlook's(2007 desktop version) Inbox and puts them into a DataGridView.

Code:

Imports Outlook = Microsoft.Office.Interop.Outlook

Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim dt As DataTable
    Try
        Dim app As Outlook.Application = New Outlook.Application()
        Dim ns As Outlook.[NameSpace] = app.GetNamespace("MAPI")
        Dim inbox As Outlook.MAPIFolder = ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox)
        ns.SendAndReceive(True)
        dt = New DataTable("Inbox")
        dt.Columns.Add("Subject", GetType(String))
        dt.Columns.Add("Sender", GetType(String))
        dt.Columns.Add("Body", GetType(String))
        dt.Columns.Add("Date", GetType(String))
        DataGridView1.DataSource = dt
        For Each item As Object In inbox.Items
            If TypeOf item Is Outlook.MailItem Then
                Dim item1 As Outlook.MailItem = CType(item, Outlook.MailItem)
                dt.Rows.Add(New Object() {item1.Subject, item1.Sender, item1.HTMLBody, item1.SentOn.ToLongDateString() & "" + item1.SentOn.ToLongTimeString()})
            End If
        Next
        MessageBox.Show("done")
    Catch ex As Exception
        MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.[Error])
    End Try
End Sub
End Class

When I try to Build the project I'm getting the follow error:

System.Runtime.InteropServices.COMException (0x80040154): Retrieving the COM class factory for component with CLSID {0006F03A-0000-0000-C000-000000000046} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))

UPDATE

I've changed the Compiler CPU to x86 and x64, this does not solve the error.

Target platform


问:
How to use std::foreach with parameters/modification
I've found myself writing

```<code>for(int i=0;i<myvec.size();i++)
   myvec[i]->DoWhatever(param);
</code>```

a lot, and I'd like to compress this into a foreach statement, but I'm not sure how to get param in there without going super-verbose. I've also got things like

```<code>for(int i=0;i<myvec.size();i++)
   if(myvec[i]->IsOK())
      myvec[i]->DoWhatever(param);
</code>```

and I'd like to rewrite that guy too. Any thoughts?

Oh, also, for various reasons, I don't want to use boost.

答:
```<code>#include <vector>
#include <algorithm>
#include <functional>

class X
{
    public:
        void doWhat(int x) {}
        bool IsOK() const {return true;}
};
class CallWhatIfOk
{
    public:
        CallWhatIfOk(int p): param(p) {}

        void operator()(X& x) const
        {   if (x.IsOK())    {x.doWhat(param);}}
    private:
        int param;
};

int main()
{
    std::vector<X>      myVec;

    std::for_each(  myVec.begin(),
                    myVec.end(),
                    std::bind2nd(std::mem_fun_ref(&X::doWhat),4)
                 );

    std::for_each(  myVec.begin(),
                    myVec.end(),
                    CallWhatIfOk(4)
                 );
}
</code>```

OwnerDisplayName: Jesse Beder

Body:
I've found myself writing

for(int i=0;i<myvec.size();i++)
   myvec[i]->DoWhatever(param);

a lot, and I'd like to compress this into a foreach statement, but I'm not sure how to get param in there without going super-verbose. I've also got things like

for(int i=0;i<myvec.size();i++)
   if(myvec[i]->IsOK())
      myvec[i]->DoWhatever(param);

and I'd like to rewrite that guy too. Any thoughts?

Oh, also, for various reasons, I don't want to use boost.

OwnerDisplayName: Martin York

LastEditorDisplayName: Martin York


问:
How to translate this Silverlight control into HTML/CSS/JS
I am in the process of converting a Silverlight app into a standard Web app (ie all HTML, CSS and JavaScript via jQuery 1.4.4). I'm not the most experienced when it comes to web development, so I am wondering what would be the best way to convert this custom Silverlight control into a web equivalent?

It boils down to just being a fancy radio button group. The user can click on any type, and only one type can be selected at a time. For the web equivalent, it needs to set a value that will get POSTed to the server.

For now I am just using a standard <select> tag which is of course functional and doesn't require JavaScript (which is nice), but ultimately is not going to fly. I will place a <select> inside of a  tag to allow non-js people to still be functional.

Can anyone recommend a good approach for tackling this? Any existing plugins/controls out in the wild I could take advantage of?

(I am using ASP.NET MVC 3, but I don't think that's very relevant here)

答:
I would use a
 and make the selections a
.  Styling is easy enough to apply to that, and there are tons of samples online.

Place a click on the li using jQuery to disable.  If you are going to disable other selections, you should also include a reset/clear type function to they can choose again in case they made a mistake.

Body:
I would use a <ul> and make the selections a <li>.  Styling is easy enough to apply to that, and there are tons of samples online.

Place a click on the li using jQuery to disable.  If you are going to disable other selections, you should also include a reset/clear type function to they can choose again in case they made a mistake.


问:
Redirect page after login using php framework laravel
I'm trying to show a page from myController after successful to login.

```<code>$email = $req->input('username');
$pass = $req->input('password');
$login = DB::table('for_login')->where(['E_mail'=>$email, 'Password'=>$pass])->get();
if(count($login)>0) {
    return view('frontEnd.Home');
} else {
    echo "Invalid username/password";
}
</code>```

How can I redirect a page after a successful login?

答:
Go to AuthController.php and add authenticated method'

```<code>protected function authenticated($request){
    return view('frontEnd.home');
}
</code>```

The built-in authentication functionality of laravel looks for authenticated method upon successful login and performs it, if it is declared. Hope this helps.

Body:
I'm trying to show a page from myController after successful to login.

$email = $req->input('username');
$pass = $req->input('password');
$login = DB::table('for_login')->where(['E_mail'=>$email, 'Password'=>$pass])->get();
if(count($login)>0) {
    return view('frontEnd.Home');
} else {
    echo "Invalid username/password";
}

How can I redirect a page after a successful login?

Body:
Go to AuthController.php and add authenticated method'

protected function authenticated($request){
    return view('frontEnd.home');
}

The built-in authentication functionality of laravel looks for authenticated method upon successful login and performs it, if it is declared. Hope this helps.


问:
Woocommerce, get products by category with wp query
I tried many methods, but I can't show products with category name or id</p>

```<code>                  $args = array(
                       'post_type'             => 'product',
                       'post_status'           => 'publish',
                       'ignore_sticky_posts'   => 1,
                       'cat'                   => 40,
                       'posts_per_page'        => '12',
                   );

                  $loop = new WP_Query( $args );
</code>```

答:
I suggest used >> wc_get_product_terms( $vars->ID, 'pa_brand_category' )

please check this screenshot >> http://prntscr.com/hjawu5

Body:
I tried many methods, but I can't show products with category name or id

                  $args = array(
                       'post_type'             => 'product',
                       'post_status'           => 'publish',
                       'ignore_sticky_posts'   => 1,
                       'cat'                   => 40,
                       'posts_per_page'        => '12',
                   );

                  $loop = new WP_Query( $args );


问:
Apache Beam Version 2.2.0
I'm currently using apache beam version 2.1.0 but there is a bug that, fortunatly, has been fixed in the new version. According to this, it seems that version 2.2.0 is ready but the release date has not yet been published. Does anyone know when it can happen? </p>

答:
Apache Beam 2.2.0 is now available as of 2017-12-01!

Google Cloud Dataflow team is also working on releasing the matching Dataflow release.

Title: Apache Beam Version 2.2.0


问:
Eclipse RCP: Required plugin could not be found
I am new to Eclipse RCP and plugin development so please don't be cruel.

I am using Maven and I have a remote repository. Yesterday Eclipse was fine but today it got messed up and I imported all the projects again so I reconfigured all but I can't get out of this problem. We use e(fx)clipse 2.5 but I installed the 3.0 version of it because I didn't find the link to install it via Eclipse.

Could you please tell me how I add a dependency? There is something that I am missing there?

Thank you

答: Adding the location http://download.eclipse.org/releases/oxygen/ to your target platform should fix the errors.


问:
Accessing Localhost and Virtualhost From Emulator in Android Studio?
I want to access localhost from android studio emulator or from genymotion without typing the IP address instead typing as localhost or as domain name.
If you are into web development you could under stand more like we assign domain for IP in the C:\Windows\System32\drivers\etc\hosts file in windows system.
I tried out steps from some blogs but couldn't figure it out.

Please do help me out. Thanks!

答: Use ip 10.0.2.2 to connect the client app on an emulator with a server running on the same pc as the emulator does.</p>


问:
Unable to create a constant value of type 'WebApplication13.Models.Service'. Only primitive types or enumeration types are supported in this context
i am trying to convert a project from ASP.NET CORE to ASP.NET MVC 4.6.1,
And i am having an issue with a linq when i try to get some data from db.

Here's the code from Asp.Net Core

```<code>public IEnumerable<UserOperators> GetSkillAgents(List<Models.Services> skillsList)
{
    return _context.UserOperators.Include(p => p.GroupOperators)
        .Where(p => p.GroupOperators.Any(o => o.GuidGroup == Guid.Parse("11111111-1111-1111-1111-000000000004")))
        .Include(p => p.Lines).Where(p => p.Lines.Any(o => o.ServicesLines.Any(a => skillsList.Any(s => s.GuidService == a.GuidService))));
}
</code>```

And heres the code i made for Asp.Net MVC 4.6.1

```<code>public IEnumerable<UserOperator> GetSkillAgents(List<Service> skillsList)
{
    var guid = Guid.Parse("11111111-1111-1111-1111-000000000004");
    return _context.UserOperators.Where(p => p.GroupOperators.Any(o => o.guidGroup == guid))
       .Where(p => p.Lines.Any(o => o.Services_Lines.Any(a => skillsList.Any(s => s.guidService == a.guidService))));
    }
</code>```

this throwns an error :

Unable to create a constant value of type 'WebApplication13.Models.Service'. Only primitive types or enumeration types are supported in this context.**

I found some answers and tried adding .AsEnumerable(), it works perferct and does not throw any error but the query takes so long to execute and return datas (like 3-4 seconds more than in ASP.NET CORE).

```<code>return _context.UserOperators.Where(p => p.GroupOperators
    .Any(o => o.guidGroup == guid)).AsEnumerable()
    .Where(p => p.Lines.Any(o => o.Services_Lines.Any(a => skillsList.Any(s => s.guidService == a.guidService))));
</code>```

So basically what i need from this query is to return me that user if the Service_Lines list and skillsList has any same item (guidService).

This is the query linq makes for sql

```<code>"SELECT \r\n    [Extent1].[guidUserOperator] AS [guidUserOperator],
\r\n    [Extent1].[Number] AS [Number],
\r\n    [Extent1].[Name] AS [Name],
\r\n    [Extent1].[strAccountName] AS [strAccountName],
 \r\n    [Extent1].[strRemotePwd] AS [strRemotePwd],
\r\n    [Extent1].[guidServiceForCallingNr] AS [guidServiceForCallingNr],
\r\n    [Extent1].[nSuppressCallingNr] AS [nSuppressCallingNr],
\r\n    [Extent1].[DynamOpPhoneNr] AS [DynamOpPhoneNr],
\r\n    [Extent1].[guidDynamOpMandant] AS [guidDynamOpMandant],
\r\n    [Extent1].[dtDisableBefore] AS [dtDisableBefore],
\r\n    [Extent1].[dtDisableAfter] AS [dtDisableAfter],
\r\n    [Extent1].[recordingIn] AS [recordingIn],
\r\n    [Extent1].[guidSecurityGroup] AS [guidSecurityGroup],
\r\n    [Extent1].[strMailbox] AS [strMailbox],
\r\n    [Extent1].[nAlwaysSendMessageToEmail] AS [nAlwaysSendMessageToEmail],
 \r\n    [Extent1].[strSMS] AS [strSMS],
\r\n    [Extent1].[recordingOut] AS [recordingOut],
\r\n    [Extent1].[guidServiceForCallingNrOutbound] AS [guidServiceForCallingNrOutbound],
\r\n    [Extent1].[LoginWithOffHookMode] AS [LoginWithOffHookMode],
\r\n    [Extent1].[LogoutCallAction] AS [LogoutCallAction],
\r\n    [Extent1].[OffHookMode] AS [OffHookMode],
\r\n    [Extent1].[StatusMessage] AS [StatusMessage],
\r\n    [Extent1].[PreferAcceptByCTI] AS [PreferAcceptByCTI],
\r\n    [Extent1].[ExternalId] AS [ExternalId],
\r\n    [Extent1].[EnableAdministrativeRecording] AS [EnableAdministrativeRecording],
 \r\n    [Extent1].[Surname] AS [Surname],
 \r\n    [Extent1].[RingingTimeoutAction] AS [RingingTimeoutAction],
\r\n    [Extent1].[Pin] AS [Pin]
\r\n    FROM [dbo].[UserOperators] AS [Extent1]\r\n
        WHERE ( EXISTS (SELECT
\r\n        1 AS [C1]
\r\n        FROM [dbo].[GroupOperators] AS [Extent2]
\r\n        WHERE ([Extent1].[guidUserOperator] = [Extent2].[guidUserOperator])
        AND ([Extent2].[guidGroup] = @p__linq__0)
\r\n    )) AND ( EXISTS (SELECT
\r\n        1 AS [C1]
\r\n        FROM ( SELECT
\r\n            [Extent3].[guidLine] AS [guidLine]
\r\n            FROM [dbo].[Lines] AS [Extent3]
\r\n            WHERE [Extent1].[guidUserOperator] = [Extent3].[guidOwnerAgent]
\r\n        )  AS [Project2]
\r\n        WHERE  EXISTS (SELECT
\r\n            1 AS [C1]
\r\n            FROM ( SELECT
\r\n                [Extent4].[guidService] AS [guidService]
\r\n                FROM [dbo].[Services_Lines] AS [Extent4]
\r\n                WHERE [Project2].[guidLine] = [Extent4].[guidLine]
\r\n            )  AS [Project3]
\r\n            WHERE  EXISTS (SELECT
\r\n                1 AS [C1]
\r\n                FROM  ( SELECT 1 AS X ) AS [SingleRowTable1]
\r\n                WHERE 1 = 0
\r\n            )
\r\n        )
\r\n    ))"
</code>```

答:
I can't test it, but give this a go:

```<code>    public IEnumerable<UserOperator> GetSkillAgents(List<Service> skillsList)
    {
        var guid = "11111111-1111-1111-1111-000000000004";

        from userOperator in _context.UserOperators
        from groupOperator in userOperator.GroupOperators
        from line in userOperator.Lines
        from services_Line in line.Services_Lines
        from skill in skillsList
        where groupOperator.guidGroup.ToString() == guid &&
              skill.guidService == services_Line.guidService
        select userOperator;
    }
</code>```

EDIT Now, we're comparing strings with strings.

Body:
i am trying to convert a project from ASP.NET CORE to ASP.NET MVC 4.6.1,
And i am having an issue with a linq when i try to get some data from db.

Here's the code from Asp.Net Core

public IEnumerable<UserOperators> GetSkillAgents(List<Models.Services> skillsList)
{
    return _context.UserOperators.Include(p => p.GroupOperators)
        .Where(p => p.GroupOperators.Any(o => o.GuidGroup == Guid.Parse("11111111-1111-1111-1111-000000000004")))
        .Include(p => p.Lines).Where(p => p.Lines.Any(o => o.ServicesLines.Any(a => skillsList.Any(s => s.GuidService == a.GuidService))));
}

And heres the code i made for Asp.Net MVC 4.6.1

public IEnumerable<UserOperator> GetSkillAgents(List<Service> skillsList)
{
    var guid = Guid.Parse("11111111-1111-1111-1111-000000000004");
    return _context.UserOperators.Where(p => p.GroupOperators.Any(o => o.guidGroup == guid))
       .Where(p => p.Lines.Any(o => o.Services_Lines.Any(a => skillsList.Any(s => s.guidService == a.guidService))));
    }

this throwns an error :

Unable to create a constant value of type 'WebApplication13.Models.Service'. Only primitive types or enumeration types are supported in this context.**

I found some answers and tried adding .AsEnumerable(), it works perferct and does not throw any error but the query takes so long to execute and return datas (like 3-4 seconds more than in ASP.NET CORE).

return _context.UserOperators.Where(p => p.GroupOperators
    .Any(o => o.guidGroup == guid)).AsEnumerable()
    .Where(p => p.Lines.Any(o => o.Services_Lines.Any(a => skillsList.Any(s => s.guidService == a.guidService))));

So basically what i need from this query is to return me that user if the Service_Lines list and skillsList has any same item (guidService).

This is the query linq makes for sql

"SELECT \r\n    [Extent1].[guidUserOperator] AS [guidUserOperator],
\r\n    [Extent1].[Number] AS [Number],
\r\n    [Extent1].[Name] AS [Name],
\r\n    [Extent1].[strAccountName] AS [strAccountName],
 \r\n    [Extent1].[strRemotePwd] AS [strRemotePwd],
\r\n    [Extent1].[guidServiceForCallingNr] AS [guidServiceForCallingNr],
\r\n    [Extent1].[nSuppressCallingNr] AS [nSuppressCallingNr],
\r\n    [Extent1].[DynamOpPhoneNr] AS [DynamOpPhoneNr],
\r\n    [Extent1].[guidDynamOpMandant] AS [guidDynamOpMandant],
\r\n    [Extent1].[dtDisableBefore] AS [dtDisableBefore],
\r\n    [Extent1].[dtDisableAfter] AS [dtDisableAfter],
\r\n    [Extent1].[recordingIn] AS [recordingIn],
\r\n    [Extent1].[guidSecurityGroup] AS [guidSecurityGroup],
\r\n    [Extent1].[strMailbox] AS [strMailbox],
\r\n    [Extent1].[nAlwaysSendMessageToEmail] AS [nAlwaysSendMessageToEmail],
 \r\n    [Extent1].[strSMS] AS [strSMS],
\r\n    [Extent1].[recordingOut] AS [recordingOut],
\r\n    [Extent1].[guidServiceForCallingNrOutbound] AS [guidServiceForCallingNrOutbound],
\r\n    [Extent1].[LoginWithOffHookMode] AS [LoginWithOffHookMode],
\r\n    [Extent1].[LogoutCallAction] AS [LogoutCallAction],
\r\n    [Extent1].[OffHookMode] AS [OffHookMode],
\r\n    [Extent1].[StatusMessage] AS [StatusMessage],
\r\n    [Extent1].[PreferAcceptByCTI] AS [PreferAcceptByCTI],
\r\n    [Extent1].[ExternalId] AS [ExternalId],
\r\n    [Extent1].[EnableAdministrativeRecording] AS [EnableAdministrativeRecording],
 \r\n    [Extent1].[Surname] AS [Surname],
 \r\n    [Extent1].[RingingTimeoutAction] AS [RingingTimeoutAction],
\r\n    [Extent1].[Pin] AS [Pin]
\r\n    FROM [dbo].[UserOperators] AS [Extent1]\r\n
        WHERE ( EXISTS (SELECT
\r\n        1 AS [C1]
\r\n        FROM [dbo].[GroupOperators] AS [Extent2]
\r\n        WHERE ([Extent1].[guidUserOperator] = [Extent2].[guidUserOperator])
        AND ([Extent2].[guidGroup] = @p__linq__0)
\r\n    )) AND ( EXISTS (SELECT
\r\n        1 AS [C1]
\r\n        FROM ( SELECT
\r\n            [Extent3].[guidLine] AS [guidLine]
\r\n            FROM [dbo].[Lines] AS [Extent3]
\r\n            WHERE [Extent1].[guidUserOperator] = [Extent3].[guidOwnerAgent]
\r\n        )  AS [Project2]
\r\n        WHERE  EXISTS (SELECT
\r\n            1 AS [C1]
\r\n            FROM ( SELECT
\r\n                [Extent4].[guidService] AS [guidService]
\r\n                FROM [dbo].[Services_Lines] AS [Extent4]
\r\n                WHERE [Project2].[guidLine] = [Extent4].[guidLine]
\r\n            )  AS [Project3]
\r\n            WHERE  EXISTS (SELECT
\r\n                1 AS [C1]
\r\n                FROM  ( SELECT 1 AS X ) AS [SingleRowTable1]
\r\n                WHERE 1 = 0
\r\n            )
\r\n        )
\r\n    ))"

Body:
I can't test it, but give this a go:

    public IEnumerable<UserOperator> GetSkillAgents(List<Service> skillsList)
    {
        var guid = "11111111-1111-1111-1111-000000000004";

        from userOperator in _context.UserOperators
        from groupOperator in userOperator.GroupOperators
        from line in userOperator.Lines
        from services_Line in line.Services_Lines
        from skill in skillsList
        where groupOperator.guidGroup.ToString() == guid &&
              skill.guidService == services_Line.guidService
        select userOperator;
    }

EDIT Now, we're comparing strings with strings.


问:
How to perform an onClick event with text only link
How can I make simple text excecute some onClick code? I have tried Hyperlink but onClick doesn't work with that. The only way I can do an onclick is in a button like this..

```<code><asp:Button ID="btnInbox" runat="server" Text="InBox" onclick="BtnInBox_Click" />

Protected Sub btnInBox_Click(sender As Object, e As EventArgs)
    pnlMainPhoneMenu.visible=false
    pnlNewMessage.visible=false
    pnlInbox.visible=true
End Sub
</code>```

But I don't want it to look like a button.. I don't want the button box, I just want plain text that can be clicked on.
I am using Asp.Net and VB.Net

答:
You can use a LinkButton:

```<code><asp:LinkButton ID="btnInbox" runat="server" Text="Inbox" />

Protected Sub btnInbox_Click(sender As Object, e As EventArgs) Handles btnInbox.Click
  pnlMainPhoneMenu.Visible = False
  pnlNewMessage.Visible = False
  pnlInbox.Visible = True
End Sub
</code>```

For anyone new to this:

<asp:Button /> Renders as <input type="submit"/>

<asp:HyperLink /> Renders as href="#"/>

<asp:LinkButton /> Renders as href="javascript:__doPostBack('','')" />

Body:
How can I make simple text excecute some onClick code? I have tried Hyperlink but onClick doesn't work with that. The only way I can do an onclick is in a button like this..

<asp:Button ID="btnInbox" runat="server" Text="InBox" onclick="BtnInBox_Click" />

Protected Sub btnInBox_Click(sender As Object, e As EventArgs)
    pnlMainPhoneMenu.visible=false
    pnlNewMessage.visible=false
    pnlInbox.visible=true
End Sub

But I don't want it to look like a button.. I don't want the button box, I just want plain text that can be clicked on.
I am using Asp.Net and VB.Net

Body:
You can use a LinkButton:

<asp:LinkButton ID="btnInbox" runat="server" Text="Inbox" />

Protected Sub btnInbox_Click(sender As Object, e As EventArgs) Handles btnInbox.Click
  pnlMainPhoneMenu.Visible = False
  pnlNewMessage.Visible = False
  pnlInbox.Visible = True
End Sub

For anyone new to this:

<asp:Button /> Renders as <input type="submit"/>

<asp:HyperLink /> Renders as <a href="#"/>

<asp:LinkButton /> Renders as <a href="javascript:__doPostBack('','')" />


问:
Clamp Camera to Map (Zoom issue)
I'm creating a game in LibGDX and am using Tiled as my map system.

I'm trying to contain an OrthographicCamera within the bounds of my TiledMap. I use MathUtils.clamp to achieve this. When the camera is at a normal zoom of 1.0f, it works perfectly. However when the camera is zoomed in further, to lets say .75f, the camera is clamped to the wrong location because it has no information of the zoom value.

```<code>position.x = MathUtils.clamp(position.x * (gameScreen.gameCamera.camera.zoom), gameScreen.gameCamera.camera.viewportWidth / 2, gameScreen.mapHandler.mapPixelWidth - (gameScreen.gameCamera.camera.viewportWidth / 2));
position.y = MathUtils.clamp(position.y * (gameScreen.gameCamera.camera.zoom), (gameScreen.gameCamera.camera.viewportHeight / 2), gameScreen.mapHandler.mapPixelHeight - (gameScreen.gameCamera.camera.viewportHeight / 2));
</code>```

My question: How do I include the zoom value in my clamp code so the camera is correctly clamped? Any ideas?

Thank you!
- Jake

答:
You should multiply by zoom the world size, not the camera position:

```<code>    float worldWidth = gameScreen.mapHandler.mapPixelWidth;
    float worldHeight = gameScreen.mapHandler.mapPixelHeight;
    float zoom = gameScreen.gameCamera.camera.zoom;
    float zoomedHalfWorldWidth = zoom * gameScreen.gameCamera.camera.viewportWidth / 2;
    float zoomedHalfWorldHeight = zoom * gameScreen.gameCamera.camera.viewportHeight / 2;

    //min and max values for camera's x coordinate
    float minX = zoomedHalfWorldWidth;
    float maxX = worldWidth - zoomedHalfWorldWidth;

    //min and max values for camera's y coordinate
    float minY = zoomedHalfWorldHeight;
    float maxY = worldHeight - zoomedHalfWorldHeight;

    position.x = MathUtils.clamp(position.x, minX, maxX);
    position.y = MathUtils.clamp(position.y, minY, maxY);
</code>```

Note, that if a visible area can be smaller than the world size, then you must handle such situations differently:

```<code>    if (maxX <= minX) {
        //visible area width is bigger than the worldWidth -> set the camera at the world centerX
        position.x = worldWidth / 2;
    } else {
        position.x = MathUtils.clamp(position.x, minX, maxX);
    }

    if (maxY <= minY) {
        //visible area height is bigger than the worldHeight -> set the  camera at the world centerY
        position.y = worldHeight / 2;
    } else {
        position.y = MathUtils.clamp(position.y, minY, maxY);
    }
</code>```

Title: Clamp Camera to Map (Zoom issue)

Body:
I'm creating a game in LibGDX and am using Tiled as my map system.

I'm trying to contain an OrthographicCamera within the bounds of my TiledMap. I use MathUtils.clamp to achieve this. When the camera is at a normal zoom of 1.0f, it works perfectly. However when the camera is zoomed in further, to lets say .75f, the camera is clamped to the wrong location because it has no information of the zoom value.

position.x = MathUtils.clamp(position.x * (gameScreen.gameCamera.camera.zoom), gameScreen.gameCamera.camera.viewportWidth / 2, gameScreen.mapHandler.mapPixelWidth - (gameScreen.gameCamera.camera.viewportWidth / 2));
position.y = MathUtils.clamp(position.y * (gameScreen.gameCamera.camera.zoom), (gameScreen.gameCamera.camera.viewportHeight / 2), gameScreen.mapHandler.mapPixelHeight - (gameScreen.gameCamera.camera.viewportHeight / 2));

My question: How do I include the zoom value in my clamp code so the camera is correctly clamped? Any ideas?

Thank you!
- Jake

Body:
You should multiply by zoom the world size, not the camera position:

    float worldWidth = gameScreen.mapHandler.mapPixelWidth;
    float worldHeight = gameScreen.mapHandler.mapPixelHeight;
    float zoom = gameScreen.gameCamera.camera.zoom;
    float zoomedHalfWorldWidth = zoom * gameScreen.gameCamera.camera.viewportWidth / 2;
    float zoomedHalfWorldHeight = zoom * gameScreen.gameCamera.camera.viewportHeight / 2;

    //min and max values for camera's x coordinate
    float minX = zoomedHalfWorldWidth;
    float maxX = worldWidth - zoomedHalfWorldWidth;

    //min and max values for camera's y coordinate
    float minY = zoomedHalfWorldHeight;
    float maxY = worldHeight - zoomedHalfWorldHeight;

    position.x = MathUtils.clamp(position.x, minX, maxX);
    position.y = MathUtils.clamp(position.y, minY, maxY);

Note, that if a visible area can be smaller than the world size, then you must handle such situations differently:

    if (maxX <= minX) {
        //visible area width is bigger than the worldWidth -> set the camera at the world centerX
        position.x = worldWidth / 2;
    } else {
        position.x = MathUtils.clamp(position.x, minX, maxX);
    }

    if (maxY <= minY) {
        //visible area height is bigger than the worldHeight -> set the  camera at the world centerY
        position.y = worldHeight / 2;
    } else {
        position.y = MathUtils.clamp(position.y, minY, maxY);
    }


问:
L5.5 querybuilder where date not working
How can I check current time with availability_from and availability_ends date time,

I have tried with below code but it did not work

```<code>public function startSession()
{
      $avialable = TimeSlot::where('mentor_provider_id',$menter_id)
                    ->where('available_from', '>=', Carbon::now())
                    ->where('available_ends', '<=', Carbon::now())
                    ->first();
}
</code>```

Is there anything wrong in my code??

答:
Are your sure that you are using operators the right way round?

Try the following code:

```<code>public function startSession()
{
      $avialable = TimeSlot::where('mentor_provider_id',$menter_id)
                    ->where('available_from', '<=', Carbon::now())
                    ->where('available_ends', '>=', Carbon::now())
                    ->first();
}
</code>```

Body:
How can I check current time with availability_from and availability_ends date time,

I have tried with below code but it did not work

public function startSession()
{
      $avialable = TimeSlot::where('mentor_provider_id',$menter_id)
                    ->where('available_from', '>=', Carbon::now())
                    ->where('available_ends', '<=', Carbon::now())
                    ->first();
}

Is there anything wrong in my code??

Body:
Are your sure that you are using operators the right way round?

Try the following code:

public function startSession()
{
      $avialable = TimeSlot::where('mentor_provider_id',$menter_id)
                    ->where('available_from', '<=', Carbon::now())
                    ->where('available_ends', '>=', Carbon::now())
                    ->first();
}


问:
Python Selenium checkbox
i am using python 2.7+selenium chromdriver.
I am trying to automatically check the last checkbox (terms of use) in this page : https://www.insuranceonline.nrma.com.au/oss/GTConnect/UnifiedAcceptor/Portal.Quote?product=Comprehensive&brandId=nrma&_ga=2.57549100.746604201.1512466470-1388355662.1512466470 .

I tried several methods, but still can not get it working. the following method get it checked , but when i click on continue button , it asks me to agree on terms of use although it is checked .

```<code>browser.execute_script('document.getElementsByName("f9_chkAgree")[0].checked=true')
</code>```

any help please ?

Thanks.

答:
I am not much familiar with python. But the selenium methods are almost same in all languages.

First view the checkbox element.

```<code>elem = driver.findElement(By.className("chkAgree"));

jse = (JavascriptExecutor)driver;
jse.executeScript("arguments[0].scrollIntoView(true);", elem);
</code>```

Then select the checkbox.

```<code>checkBox = elem.findElement(By.cssSelector("input[type='checkbox']"));
checkBox.click();
</code>```

Title: Python Selenium checkbox

Body:
i am using python 2.7+selenium chromdriver.
I am trying to automatically check the last checkbox (terms of use) in this page : https://www.insuranceonline.nrma.com.au/oss/GTConnect/UnifiedAcceptor/Portal.Quote?product=Comprehensive&brandId=nrma&_ga=2.57549100.746604201.1512466470-1388355662.1512466470 .

I tried several methods, but still can not get it working. the following method get it checked , but when i click on continue button , it asks me to agree on terms of use although it is checked .

browser.execute_script('document.getElementsByName("f9_chkAgree")[0].checked=true')

any help please ?

Thanks.

Body:
I am not much familiar with python. But the selenium methods are almost same in all languages.

First view the checkbox element.

elem = driver.findElement(By.className("chkAgree"));

jse = (JavascriptExecutor)driver;
jse.executeScript("arguments[0].scrollIntoView(true);", elem);

Then select the checkbox.

checkBox = elem.findElement(By.cssSelector("input[type='checkbox']"));
checkBox.click();


问:
sudo apachectl -k start not work on MacOS HIGH SIERRA
I've run sudo apachectl -k start , but the httpd process wasn't created.
And when I've run apachectl configtest on terminal, it shows me Syntax OK.
Also I run other commands:

sudo apachectl -k restart  => httpd not running, trying to start.

sudo apachectl -k stop => httpd (pid 1369?) not running

More info about apache error_log file:  LogLevel debug

```<code>[Mon Nov 27 01:15:00.390588 2017] [unique_id:info] [pid 1572] AH01566: using ip addr 192.***.*.**
[Mon Nov 27 01:15:01.004998 2017] [ssl:info] [pid 1572] AH01887: Init: Initializing (virtual) servers for SSL
[Mon Nov 27 01:15:01.008629 2017] [ssl:info] [pid 1572] AH01876: mod_ssl/2.4.25 compiled against Server: Apache/2.4.25, Library: OpenSSL/1.0.2j
[Mon Nov 27 01:15:01.046466 2017] [unique_id:info] [pid 1574] AH01566: using ip addr 192.***.**.*
[Mon Nov 27 01:15:02.000248 2017] [ssl:warn] [pid 1574] AH01873: Init: Session Cache is not configured [hint: SSLSessionCache]
[Mon Nov 27 01:15:02.000473 2017] [ssl:info] [pid 1574] AH01887: Init: Initializing (virtual) servers for SSL
</code>```

答:
Maybe you have replaced the default ruby.

Open you terminal and enter:

```<code>sudo ln -s /System/Library/Frameworks/Ruby.framework/Versions/Current/usr/bin/ruby /usr/bin/ruby
</code>```

It works for me. Hope it helps.

Body:
I've run sudo apachectl -k start , but the httpd process wasn't created.
And when I've run apachectl configtest on terminal, it shows me Syntax OK.
Also I run other commands:

sudo apachectl -k restart  => httpd not running, trying to start.

sudo apachectl -k stop => httpd (pid 1369?) not running

More info about apache error_log file:  LogLevel debug

[Mon Nov 27 01:15:00.390588 2017] [unique_id:info] [pid 1572] AH01566: using ip addr 192.***.*.**
[Mon Nov 27 01:15:01.004998 2017] [ssl:info] [pid 1572] AH01887: Init: Initializing (virtual) servers for SSL
[Mon Nov 27 01:15:01.008629 2017] [ssl:info] [pid 1572] AH01876: mod_ssl/2.4.25 compiled against Server: Apache/2.4.25, Library: OpenSSL/1.0.2j
[Mon Nov 27 01:15:01.046466 2017] [unique_id:info] [pid 1574] AH01566: using ip addr 192.***.**.*
[Mon Nov 27 01:15:02.000248 2017] [ssl:warn] [pid 1574] AH01873: Init: Session Cache is not configured [hint: SSLSessionCache]
[Mon Nov 27 01:15:02.000473 2017] [ssl:info] [pid 1574] AH01887: Init: Initializing (virtual) servers for SSL

Body:
Maybe you have replaced the default ruby.

Open you terminal and enter:

sudo ln -s /System/Library/Frameworks/Ruby.framework/Versions/Current/usr/bin/ruby /usr/bin/ruby

It works for me. Hope it helps.


问:
Getting JSON exchange rate from fixer.io to HTML
I'm trying to get the current USD to EUR rate from fixer.io into a single line in a HTML file and replace the "." in the USD value with a ",".

Can somebody help me?

LINK: https://api.fixer.io/latest?symbols=USD

```<code>{
  "base": "EUR",
  "date": "2017-12-04",
  "rates": {
    "USD": 1.1865
  }
}
</code>```

What i need in a HTML file:

```<code>1,1865
</code>```

EDIT:

This is what i tried so far (literally never done this before):

HTML:

```<code><span id="rate_usd"></span>
</code>```

JS:

```<code>$(document).ready(function(){
  var url= "https://api.fixer.io/latest?symbols=USD"
  $.getJSON(url,function(data){
    document.getElementById("rate_usd").innerHTML = data.rates.USD;

  });
});
</code>```

答:
Try the below, it includes all the HTML, JS and jQuery dependency you were referencing.

You were pretty close, here we are taking the number returned by the API, converting it to a string with toString() and then replacing the . with , as requested.

```<code><html>
  <head>
    <title>USD Rate</title>
  </head>
  <body>
    <span id="rate_usd"></span>
    <script
      src="https://code.jquery.com/jquery-3.2.1.min.js"
      integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
      crossorigin="anonymous"></script>
    <script>
      $(function() {
        $.getJSON('https://api.fixer.io/latest?symbols=USD', function(data) {
          var usdRate = data.rates.USD.toString();
          var commaFormatted = usdRate.replace('.', ',')
          document.getElementById('rate_usd').innerHTML = commaFormatted;
        });
      });
    </script>
  </body>
</html>
</code>```

Body:
I'm trying to get the current USD to EUR rate from fixer.io into a single line in a HTML file and replace the "." in the USD value with a ",".

Can somebody help me?

LINK: https://api.fixer.io/latest?symbols=USD

{
  "base": "EUR",
  "date": "2017-12-04",
  "rates": {
    "USD": 1.1865
  }
}

What i need in a HTML file:

1,1865

EDIT:

This is what i tried so far (literally never done this before):

HTML:

JS:

$(document).ready(function(){
  var url= "https://api.fixer.io/latest?symbols=USD"
  $.getJSON(url,function(data){
    document.getElementById("rate_usd").innerHTML = data.rates.USD;

  });
});

Body:
Try the below, it includes all the HTML, JS and jQuery dependency you were referencing.

You were pretty close, here we are taking the number returned by the API, converting it to a string with toString() and then replacing the . with , as requested.

<html>
  <head>
    <title>USD Rate</title>
  </head>
  <body>
    <span id="rate_usd"></span>
    <script
      src="https://code.jquery.com/jquery-3.2.1.min.js"
      integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
      crossorigin="anonymous"></script>
    <script>
      $(function() {
        $.getJSON('https://api.fixer.io/latest?symbols=USD', function(data) {
          var usdRate = data.rates.USD.toString();
          var commaFormatted = usdRate.replace('.', ',')
          document.getElementById('rate_usd').innerHTML = commaFormatted;
        });
      });
    </script>
  </body>
</html>


问:
Why is this string not declared in the scope?
I'm experimenting with classes and I'm wondering why I'm getting an error saying "calvin" is not defined in the scope. Thanks.</p>

```<code>#include <iostream>
#include <string>
using namespace std;

class people
    {
    public:
        string name;
        int age;
    };

int main()
{
    people peeps[10];

    peeps[1].name = calvin;
    peeps[1].age = 21;

    cout << peeps[1].name << peeps[1].age;
}
</code>```

答: Without quotes, calvin is a variable (which is undefined). You should make it a literal (i.e. "calvin").

Body:
I'm experimenting with classes and I'm wondering why I'm getting an error saying "calvin" is not defined in the scope. Thanks.

#include <iostream>
#include <string>
using namespace std;

class people
    {
    public:
        string name;
        int age;
    };

int main()
{
    people peeps[10];

    peeps[1].name = calvin;
    peeps[1].age = 21;

    cout << peeps[1].name << peeps[1].age;
}


问:
Destroy and recreate a jQuery Datatables
I have two jQuery datatables with server side processing. I have a checkbox where I hide and show the two tables. I would like to destroy the none displayed and create another table. How would I do this?

This is what I tried but ajax.reload does not fire.

if ($('#mode').is(':checked')) {
    Table2.ajax.reload();
    Table1.clear();
    Table1.destroy();
} else {
    Table1.ajax.reload();
    Table2.clear();
    Table2.destroy()
}

var Table1 = $('#timesheet-table').DataTable({})
var Table2 = $('#timesheet-table-2').DataTable({})
```

答:
You have to clear the div content for properly destroy</p>

```<code> if($('#mode').is(':checked')) {
      Table2 = $('#timesheet-table-2').DataTable({})
      Table1.clear();
      Table1.destroy();
      $('#timesheet-table').empty();
}

else {
  Table1 = $('#timesheet-table').DataTable({})
  Table2.clear();
  Table2.destroy();
  $('#timesheet-table-2').empty();
}
</code>```

Body:
You have to clear the div content for properly destroy

 if($('#mode').is(':checked')) {
      Table2 = $('#timesheet-table-2').DataTable({})
      Table1.clear();
      Table1.destroy();
      $('#timesheet-table').empty();
}

else {
  Table1 = $('#timesheet-table').DataTable({})
  Table2.clear();
  Table2.destroy();
  $('#timesheet-table-2').empty();
}


问:
Any tips for making Hive run faster on Hadoop?
I'm new to Hive and Hadoop. I have Hadoop configured for pseudo-distributed operation with one data node and one name node, all on localhost.

I have a trivial employee table containing 4 records. I can select the records in a reasonable amount of time, but anything beyond that takes really long. For example:

```<code>0: jdbc:hive2://localhost:10000> select * from emp;
+------------+------------+-------------+-------------+------------+
| emp.empno  | emp.ename  |   emp.job   | emp.deptno  | emp.etype  |
+------------+------------+-------------+-------------+------------+
| 7369       | SMITH      | CLERK       | 10          | PART_TIME  |
| 7400       | JONES      | ENGINEER    | 10          | FULL_TIME  |
| 7500       | BROWN      | NIGHTGUARD  | 20          | FULL_TIME  |
| 7510       | LEE        | ENGINEER    | 20          | FULL_TIME  |
+------------+------------+-------------+-------------+------------+
4 rows selected (0.643 seconds)
0: jdbc:hive2://localhost:10000> select * from emp order by empno;
WARNING: Hive-on-MR is deprecated in Hive 2 and may not be available in the future versions. Consider using a different execution engine (i.e. spark, tez) or using Hive 1.X releases.
+------------+------------+-------------+-------------+------------+
| emp.empno  | emp.ename  |   emp.job   | emp.deptno  | emp.etype  |
+------------+------------+-------------+-------------+------------+
| 7369       | SMITH      | CLERK       | 10          | PART_TIME  |
| 7400       | JONES      | ENGINEER    | 10          | FULL_TIME  |
| 7500       | BROWN      | NIGHTGUARD  | 20          | FULL_TIME  |
| 7510       | LEE        | ENGINEER    | 20          | FULL_TIME  |
+------------+------------+-------------+-------------+------------+
4 rows selected (225.852 seconds)
</code>```

What's it doing that's taking so long? Are there polling periods that I could reduce? I know that Hive isn't optimized for small tasks but this seems ridiculous.

Here's the various files:
hive-site.xml

```<code><?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
  <property>
    <name>hive.mapred.mode</name>
    <value>nostrict</value>
  </property>
  <property>
    <name>javax.jdo.option.ConnectionURL</name>
    <value>jdbc:derby:;databaseName=metastore_db;create=true</value>
  </property>
  <property>
    <name>javax.jdo.option.ConnectionDriverName</name>
    <value>org.apache.derby.jdbc.EmbeddedDriver</value>
  </property>
  <property>
    <name>hive.exec.local.scratchdir</name>
    <value>/home/hadoop/tmp</value>
  </property>
  <property>
    <name>hive.downloaded.resources.dir</name>
    <value>/home/hadoop/tmp/${hive.session.id}_resources</value>
  </property>
  <property>
    <name>hive.querylog.location</name>
    <value>/home/hadoop/tmp</value>
  </property>
  <property>
    <name>hive.server2.logging.operation.log.location</name>
    <value>/home/hadoop/tmp/operation_logs</value>
  </property>
</configuration>
</code>```

hdfs.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
   <property>
      <name>dfs.replication</name>
      <value>1</value>
   </property>
   <property>
      <name>dfs.name.dir</name>
      <value>file:///home/hadoop/hadoopinfra/hdfs/namenode</value>
   </property>
   <property>
      <name>dfs.data.dir</name>
      <value>file:///home/hadoop/hadoopinfra/hdfs/datanode</value>
   </property>
</configuration>
</code>```

core-site.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
   <property>
      <name>fs.default.name</name>
      <value>hdfs://localhost:9000</value>
   </property>
   <property>
      <name>hadoop.proxyuser.hive.groups</name>
      <value>*</value>
   </property>
   <property>
      <name>hadoop.proxyuser.hive.hosts</name>
      <value>*</value>
   </property>
   <property>
      <name>hadoop.proxyuser.hadoop.hosts</name>
      <value>*</value>
   </property>
   <property>
      <name>hadoop.proxyuser.hadoop.groups</name>
      <value>*</value>
   </property>
</configuration>
</code>```

mapred-site.xml

```<code><?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
   <property>
      <name>mapreduce.framework.name</name>
      <value>yarn</value>
   </property>
</configuration>
</code>```

yarn-site.xml

```<code><?xml version="1.0"?>
<configuration>
   <property>
      <name>yarn.nodemanager.aux-services</name>
      <value>mapreduce_shuffle</value>
   </property>
</configuration>
</code>```

答:
You are using 'order by' in query, order by imposes the total order of all results, so there has to be single reducer to sort the final output.

Though the number of records are less in this case, because of the two stages (Map and Reduce) and Disk I/O, the query took time to process. If the number of rows in the output is too large, the single reducer could take a very long time to finish.

Suggest you to run Hive on Tez or Spark engines and dont run the queries which require full scan tables unless is really needed.

Body:
I'm new to Hive and Hadoop. I have Hadoop configured for pseudo-distributed operation with one data node and one name node, all on localhost.

I have a trivial employee table containing 4 records. I can select the records in a reasonable amount of time, but anything beyond that takes really long. For example:

0: jdbc:hive2://localhost:10000> select * from emp;
+------------+------------+-------------+-------------+------------+
| emp.empno  | emp.ename  |   emp.job   | emp.deptno  | emp.etype  |
+------------+------------+-------------+-------------+------------+
| 7369       | SMITH      | CLERK       | 10          | PART_TIME  |
| 7400       | JONES      | ENGINEER    | 10          | FULL_TIME  |
| 7500       | BROWN      | NIGHTGUARD  | 20          | FULL_TIME  |
| 7510       | LEE        | ENGINEER    | 20          | FULL_TIME  |
+------------+------------+-------------+-------------+------------+
4 rows selected (0.643 seconds)
0: jdbc:hive2://localhost:10000> select * from emp order by empno;
WARNING: Hive-on-MR is deprecated in Hive 2 and may not be available in the future versions. Consider using a different execution engine (i.e. spark, tez) or using Hive 1.X releases.
+------------+------------+-------------+-------------+------------+
| emp.empno  | emp.ename  |   emp.job   | emp.deptno  | emp.etype  |
+------------+------------+-------------+-------------+------------+
| 7369       | SMITH      | CLERK       | 10          | PART_TIME  |
| 7400       | JONES      | ENGINEER    | 10          | FULL_TIME  |
| 7500       | BROWN      | NIGHTGUARD  | 20          | FULL_TIME  |
| 7510       | LEE        | ENGINEER    | 20          | FULL_TIME  |
+------------+------------+-------------+-------------+------------+
4 rows selected (225.852 seconds)

What's it doing that's taking so long? Are there polling periods that I could reduce? I know that Hive isn't optimized for small tasks but this seems ridiculous.

Here's the various files:
hive-site.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
  <property>
    <name>hive.mapred.mode</name>
    <value>nostrict</value>
  </property>
  <property>
    <name>javax.jdo.option.ConnectionURL</name>
    <value>jdbc:derby:;databaseName=metastore_db;create=true</value>
  </property>
  <property>
    <name>javax.jdo.option.ConnectionDriverName</name>
    <value>org.apache.derby.jdbc.EmbeddedDriver</value>
  </property>
  <property>
    <name>hive.exec.local.scratchdir</name>
    <value>/home/hadoop/tmp</value>
  </property>
  <property>
    <name>hive.downloaded.resources.dir</name>
    <value>/home/hadoop/tmp/${hive.session.id}_resources</value>
  </property>
  <property>
    <name>hive.querylog.location</name>
    <value>/home/hadoop/tmp</value>
  </property>
  <property>
    <name>hive.server2.logging.operation.log.location</name>
    <value>/home/hadoop/tmp/operation_logs</value>
  </property>
</configuration>

hdfs.xml

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
   <property>
      <name>dfs.replication</name>
      <value>1</value>
   </property>
   <property>
      <name>dfs.name.dir</name>
      <value>file:///home/hadoop/hadoopinfra/hdfs/namenode</value>
   </property>
   <property>
      <name>dfs.data.dir</name>
      <value>file:///home/hadoop/hadoopinfra/hdfs/datanode</value>
   </property>
</configuration>

core-site.xml

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
   <property>
      <name>fs.default.name</name>
      <value>hdfs://localhost:9000</value>
   </property>
   <property>
      <name>hadoop.proxyuser.hive.groups</name>
      <value>*</value>
   </property>
   <property>
      <name>hadoop.proxyuser.hive.hosts</name>
      <value>*</value>
   </property>
   <property>
      <name>hadoop.proxyuser.hadoop.hosts</name>
      <value>*</value>
   </property>
   <property>
      <name>hadoop.proxyuser.hadoop.groups</name>
      <value>*</value>
   </property>
</configuration>

mapred-site.xml

<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
   <property>
      <name>mapreduce.framework.name</name>
      <value>yarn</value>
   </property>
</configuration>

yarn-site.xml

<?xml version="1.0"?>
<configuration>
   <property>
      <name>yarn.nodemanager.aux-services</name>
      <value>mapreduce_shuffle</value>
   </property>
</configuration>


问:
Hide Div until hover on icon
I have hit a brick wall on this one, I am working on a website where I need to hide a DIV of extra content until the user hovers over an icon but I cannot figure out how to do this. I have tried various different ways (>, + and ~) but I just cant get it to work.

HTML

.fa-canapes-icon:hover .canapes-popup{
    display:block;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="canapes">
<p>Canapes <i class="fa fa-info-circle fa-canapes-icon"></i></p>
<div class="canapes-popup">
<h1>Example Canape Menu</h1>
<p>This is a popular selection. We do of course have other options we are happy to discuss with you.<br>
Mini Yorkshires with Medium Roast Beef and Horseradish<br>
Satay Chicken Skewers with a Peanut Sauce<br>
Spicy Prawn with Mango<br>
Smoked Salmon & Mascarpone crostini with Dill & Lemon<br>
Mozzerella Pearls with Sun-blush tomatoes & Fresh Basil (V)<br>
Honey and Sesame Coated Cocktail Sausages</p>
</div>
</div></code>```

The page can be viewed here and it is the 'wedding package 3' with the canapes i icon that I am trying to add it onto.

Any help would be greatly appreciated.

答:
Your css is failing since  does NOT have any siblings; and your
 of interest is a sibling to 's parent. Therefore, you could do the following:

```<code><p class="icon-container">Canapes <i class="fa fa-info-circle fa-canapes-icon"></i></p>
</code>```

And, add the following CSS:

```<code>.icon-container:hover + .canapes-popup {
    display: block;
}
</code>```

It seems to be working. Let me know if it does for you too. fiddle

Title: Hide Div until hover on icon

Body:
I have hit a brick wall on this one, I am working on a website where I need to hide a DIV of extra content until the user hovers over an icon but I cannot figure out how to do this. I have tried various different ways (>, + and ~) but I just cant get it to work.

HTML

.fa-canapes-icon:hover .canapes-popup{
    display:block;

}

Canapes

Example Canape Menu

This is a popular selection. We do of course have other options we are happy to discuss with you.

Mini Yorkshires with Medium Roast Beef and Horseradish

Satay Chicken Skewers with a Peanut Sauce

Spicy Prawn with Mango

Smoked Salmon & Mascarpone crostini with Dill & Lemon

Mozzerella Pearls with Sun-blush tomatoes & Fresh Basil (V)

Honey and Sesame Coated Cocktail Sausages

The page can be viewed here and it is the 'wedding package 3' with the canapes i icon that I am trying to add it onto.

Any help would be greatly appreciated.

Body:
Your css is failing since <i> does NOT have any siblings; and your <div> of interest is a sibling to <i>'s parent. Therefore, you could do the following:

<p class="icon-container">Canapes <i class="fa fa-info-circle fa-canapes-icon"></i></p>

And, add the following CSS:

.icon-container:hover + .canapes-popup {
    display: block;
}

It seems to be working. Let me know if it does for you too. fiddle


问:
easiest way to apply the same mod_rewrite rules to many virtualhosts?
I have lots and lots of virtualhosts to support lots and lots of client domains. I want to add a feature to my core app that requires a couple mod_rewrite rules to be applied to ALL those domains. Best approach I have so far is to add the rules to my global httpd.conf, and add these two lines to every single virtualhost:

```<code>RewriteEngine On
RewriteOptions Inherit
</code>```

But it would obviously be preferable to accomplish this without having to edit every virtualhost. Is there any way to make my mod_rewrite rules apply to all virtualhosts without editing them?

答:
Well, this may not apply to you, but if you have a lot of virtualhosts and that all theses virtualhosts share common things you could use mod_rewrite to do the virtualhosting and have only one file:

Search "Mass Virtual Hosting" in this document and you can read this one for more detailled examples (going from the simpliest one to the one with a file mapping domains and document roots).

If you have some very specific configurations on some VirtualHosts you cannot handle them in this system, but if you can group your handled domains by types (with identical configurations for each type) you can use this system.

About the 'simpliest' way, this is maybe not the simpliest as it really need big changes and tests. But it will be really a simplier system after these changes if you are managing clones.

Body:
I have lots and lots of virtualhosts to support lots and lots of client domains. I want to add a feature to my core app that requires a couple mod_rewrite rules to be applied to ALL those domains. Best approach I have so far is to add the rules to my global httpd.conf, and add these two lines to every single virtualhost:

RewriteEngine On
RewriteOptions Inherit

But it would obviously be preferable to accomplish this without having to edit every virtualhost. Is there any way to make my mod_rewrite rules apply to all virtualhosts without editing them?


问:
Spring HATEOAS - two same links
lately I've been doing some projekt with Spring Data and Rest with HATEOAS.

My question is, is it normal, that in entity links secion, I have 2 same links?

Here is repository:

Repository

答:
Yes it is. But it's not always the case: the 'user' link is actually a templated link that gets enriched in certain cases.

For instance, should you define the following projection:

```<code>@Projection(name = "summary", types = { User.class })
interface Summary {

  String getUsername();
  String getEmail();

}
</code>```

then the user link would show the projection parameter:

```<code>...
"_links" : {
  "self" : {
    "href" : "http://localhost:8080/users/1"
  },
  "user" : {
    "href" : "http://localhost:8080/users/1{?projection}"
    "templated" : true
  }
</code>```

And you could be able to get a summary of user 1 by GETting http://localhost:8080/users/1?projection=summary.

Title: Spring HATEOAS - two same links

Body:
Yes it is. But it's not always the case: the 'user' link is actually a templated link that gets enriched in certain cases.

For instance, should you define the following projection:

@Projection(name = "summary", types = { User.class })
interface Summary {

  String getUsername();
  String getEmail();

}

then the user link would show the projection parameter:

...
"_links" : {
  "self" : {
    "href" : "http://localhost:8080/users/1"
  },
  "user" : {
    "href" : "http://localhost:8080/users/1{?projection}"
    "templated" : true
  }

And you could be able to get a summary of user 1 by GETting http://localhost:8080/users/1?projection=summary.


问:
Fetch value from json object and assign it to a dropdownlist
I am using asp.net WebForm page with C#, I have a class Place that has the properties int placeId, string place and Baladi baladi.

Baladi class has the properties int baladiId, string baladi.

In javascript I am calling a method that returns an object Place.
And I have a Bootstrap modal with a TextBox, HiddenField and DropDownList,
I am able to set the value of TextBox as Place.place and the HiddenField as Place.placeId.

What I need is to set the selected index of the DropDownList based on Place.baladi.baladiId.
When I try in my code it keeps selecting the first item in the DropDownList.

Below is my code:

```<code>public class Place
{
    public int placeId { get; set; }
    public string place { get; set; }
    public Baladi baladi { get; set; }
}
public class Baladi
{
    public int baladiId { get; set; }
    public string baladi { get; set; }
  }

<script>
        $(document).on("click", ".btnEdit", function () {
            var pid = $(this).data('id');
            $.ajax({
                type: "POST",
                url: "place.aspx/getPlace",
                data: '{placeId: "' + pid + '" }',
                contentType: "application/json; charset=utf-8",
                dataType: "json", // dataType is json format
                success: OnSuccess,
                error: OnErrorCall
            });

            function OnSuccess(response) {
                console.log(response.d);
                $("#txtEditPlace").val(response.d['place']);
                $("#ddlCity").val(response.d['baladi']['baladiId']);
                $("#hfPlaceId").val((response.d['placeId'] == null ? "" : response.d['placeId']));
            }
            function OnErrorCall(response) { console.log(response); }
        });
    </script>
</code>```

Any help would be appreciated!

答:
```<code>public int baladiId { get; set; }
</code>```

baladiId is declared as an int.  The val function should only work when passed a string IE "2" and 2 are not equivalent values.  Did you try casting the baladidId before setting the dropdown val?

```<code>$("#ddlCity").val(String(response.d['baladi']['baladiId']))
</code>```

Body:
I am using asp.net WebForm page with C#, I have a class Place that has the properties int placeId, string place and Baladi baladi.

Baladi class has the properties int baladiId, string baladi.

In javascript I am calling a method that returns an object Place.
And I have a Bootstrap modal with a TextBox, HiddenField and DropDownList,
I am able to set the value of TextBox as Place.place and the HiddenField as Place.placeId.

What I need is to set the selected index of the DropDownList based on Place.baladi.baladiId.
When I try in my code it keeps selecting the first item in the DropDownList.

Below is my code:

public class Place
{
    public int placeId { get; set; }
    public string place { get; set; }
    public Baladi baladi { get; set; }
}
public class Baladi
{
    public int baladiId { get; set; }
    public string baladi { get; set; }
  }

Any help would be appreciated!

Body:
public int baladiId { get; set; }

baladiId is declared as an int.  The val function should only work when passed a string IE "2" and 2 are not equivalent values.  Did you try casting the baladidId before setting the dropdown val?

$("#ddlCity").val(String(response.d['baladi']['baladiId']))


问:
How to use Count SQL Server Query
i write this post to ask for help on a query on the following schema:

Imagine having two formats, for example, PDF and EBOOK. My goal is to get the following result:

```<code>PushiblerName  |  Number_PDF   |  Numerber_BOOK  |
--------------------------------------------------
ExampleName1   |    2          |   0
ExampleName2   |    3          |   1
</code>```

Would anyone help me write this query?
Thanks in advance.

答:
```<code>select name,(select count(*) from t_book where IdPublisher = t_publisher.Id) as Numerber_BOOK,
(select count(*) from t_book where IdPublisher = t_publisher.Id and IdFormat = 3)  as Number_PDF from t_publisher
</code>```

replace 3 with the Id of Pdf format

Title: How to use Count SQL Server Query

Body:
i write this post to ask for help on a query on the following schema:

Imagine having two formats, for example, PDF and EBOOK. My goal is to get the following result:

PushiblerName  |  Number_PDF   |  Numerber_BOOK  |
--------------------------------------------------
ExampleName1   |    2          |   0
ExampleName2   |    3          |   1

Would anyone help me write this query?
Thanks in advance.

Body:
select name,(select count(*) from t_book where IdPublisher = t_publisher.Id) as Numerber_BOOK,
(select count(*) from t_book where IdPublisher = t_publisher.Id and IdFormat = 3)  as Number_PDF from t_publisher

replace 3 with the Id of Pdf format


问:
How to get visible viewController from app delegate when using storyboard?
I have some viewControllers, and I don't use NavigationController.
How can I get visible view controller in app delegate methods (e.g. applicationWillResignActive)?

I know how to do it from NSNotification, but I think it's the wrong way.

答:
In my case i have Tabbar controller and then Navigation controller for each Tab hope it helps someone</p>
```<code> UIViewController *loginViewController = self.window.rootViewController;

 UITabBarController *controller = loginViewController.tabBarController;

 UIViewController *currentController = controller.selectedViewController.childViewControllers.lastObject;
</code>```

Body:
In my case i have Tabbar controller and then Navigation controller for each Tab hope it helps someone

 UIViewController *loginViewController = self.window.rootViewController;

 UITabBarController *controller = loginViewController.tabBarController;

 UIViewController *currentController = controller.selectedViewController.childViewControllers.lastObject;


问:
pass array as argument to script module in ansible
I am using a script module to run a script on some hosts. I have an array ansible variable, that I want to pass the script as space separated arguments. Passing the array variable directly as argument does not help. Suggestions ?</p>

答:
You can join your list with jinja filter and pass it as a variable, like this:

ansible -m script -a "myscript.sh {{ test_list|join(' ') }}" localhost -e "{"test_list": [1,2,3]}"

If myscript.sh is:

```<code>#!/bin/bash
echo Args are: ${@}, 1st: $1 2nd: $2, 3d: $3
</code>```

The output will be:

```<code>localhost | SUCCESS => {
    "changed": true,
    "failed": false,
    "rc": 0,
    "stderr": "",
    "stdout": "Args are: 1 2 3, 1st: 1 2nd: 2, 3d: 3\n",
    "stdout_lines": [
        "Args are: 1 2 3, 1st: 1 2nd: 2, 3d: 3"
    ]
}
</code>```

Body:
You can join your list with jinja filter and pass it as a variable, like this:

ansible -m script -a "myscript.sh {{ test_list|join(' ') }}" localhost -e "{"test_list": [1,2,3]}"

If myscript.sh is:

#!/bin/bash
echo Args are: ${@}, 1st: $1 2nd: $2, 3d: $3

The output will be:

localhost | SUCCESS => {
    "changed": true,
    "failed": false,
    "rc": 0,
    "stderr": "",
    "stdout": "Args are: 1 2 3, 1st: 1 2nd: 2, 3d: 3\n",
    "stdout_lines": [
        "Args are: 1 2 3, 1st: 1 2nd: 2, 3d: 3"
    ]
}


问:
The type or namespace name could not be found
I have a C# solution with several projects in Visual Studio 2010.
One is a test project (I'll call it "PrjTest"), the other is a Windows Forms Application project (I'll call it "PrjForm").  There is also a third project referenced by PrjForm, which it is able to reference and use successfully.

PrjForm references PrjTest, and PrjForm has a class with a using statement:

```<code>using PrjTest;
</code>```

Reference has been correctly added

using statement is correctly in place

Spelling is correct

PrjTest builds successfully

PrjForm almost builds, but breaks on the using PrjTest; line with the error:

The type or namespace name 'PrjTest' could not be found (are you missing a using directive or an assembly reference?)

I've tried the following to resolve this:

Removed Resharper (since Resharper had no trouble recognizing the referenced project, I thought it might be worth a shot)

Removed and re-added the reference and using statement

Recreated PrjForm from scratch

PrjForm currently resides inside the PrjTest folder, I tried moving it to an outside folder

Loaded the solution on a different computer with a fresh copy of VS 2010

I have done my homework and spent far too long looking for an answer online, none of the solutions has helped yet.

What else could I try?

答:
See this question.

Turns out this was a client profiling issue.

PrjForm was set to ".Net Framework 4 Client Profile"
I changed it to ".Net Framework 4", and now I have a successful build.

Thanks everyone!
I guess it figures that after all that time spent searching online, I find the solution minutes after posting, I guess the trick is knowing the right question to ask..

Body:
I have a C# solution with several projects in Visual Studio 2010.
One is a test project (I'll call it "PrjTest"), the other is a Windows Forms Application project (I'll call it "PrjForm").  There is also a third project referenced by PrjForm, which it is able to reference and use successfully.

PrjForm references PrjTest, and PrjForm has a class with a using statement:

using PrjTest;

Reference has been correctly added

using statement is correctly in place

Spelling is correct

PrjTest builds successfully

PrjForm almost builds, but breaks on the using PrjTest; line with the error:

The type or namespace name 'PrjTest' could not be found (are you missing a using directive or an assembly reference?)

I've tried the following to resolve this:

Removed Resharper (since Resharper had no trouble recognizing the referenced project, I thought it might be worth a shot)

Removed and re-added the reference and using statement

Recreated PrjForm from scratch

PrjForm currently resides inside the PrjTest folder, I tried moving it to an outside folder

Loaded the solution on a different computer with a fresh copy of VS 2010

I have done my homework and spent far too long looking for an answer online, none of the solutions has helped yet.

What else could I try?


答:
The Problem:

The manner in which you have your css selectors currently defined:

```<code>.fa-canapes-icon:hover .canapes-popup
</code>```

...the popup element (.canapes-popup) would have to be nested within the icon element (.fa-canapes-icon) in order for this rule to apply as expected.

The Solution:

Apply a class to the containing p tag of the icon in question so that you can use it as a selector with the adjacent sibling combinator selector, e.g:

```<code>.canapes-icon:hover + .canapes-popup {
  display: block;
}
</code>```

.canapes-icon:hover + .canapes-popup {
  display: block;
}

.canapes-popup {
  display: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="canapes">
  <p class="canapes-icon">Canapes <i class="fa fa-info-circle fa-canapes-icon"></i></p>
  <div class="canapes-popup">
    <h1>Example Canape Menu</h1>
    <p>This is a popular selection. We do of course have other options we are happy to discuss with you.<br> Mini Yorkshires with Medium Roast Beef and Horseradish<br> Satay Chicken Skewers with a Peanut Sauce<br> Spicy Prawn with Mango<br> Smoked Salmon
      & Mascarpone crostini with Dill & Lemon<br> Mozzerella Pearls with Sun-blush tomatoes & Fresh Basil (V)<br> Honey and Sesame Coated Cocktail Sausages</p>
  </div>
</div></code>```

More on CSS combinators

Title: Hide Div until hover on icon

Body:
The Problem:

The manner in which you have your css selectors currently defined:

.fa-canapes-icon:hover .canapes-popup

...the popup element (.canapes-popup) would have to be nested within the icon element (.fa-canapes-icon) in order for this rule to apply as expected.

The Solution:

Apply a class to the containing p tag of the icon in question so that you can use it as a selector with the adjacent sibling combinator selector, e.g:

.canapes-icon:hover + .canapes-popup {
  display: block;
}

.canapes-icon:hover + .canapes-popup {
  display: block;
}

.canapes-popup {
  display: none;
}

<div class="canapes">
  <p class="canapes-icon">Canapes <i class="fa fa-info-circle fa-canapes-icon"></i></p>
  <div class="canapes-popup">
    <h1>Example Canape Menu</h1>
    <p>This is a popular selection. We do of course have other options we are happy to discuss with you.<br> Mini Yorkshires with Medium Roast Beef and Horseradish<br> Satay Chicken Skewers with a Peanut Sauce<br> Spicy Prawn with Mango<br> Smoked Salmon
      &amp; Mascarpone crostini with Dill &amp; Lemon<br> Mozzerella Pearls with Sun-blush tomatoes &amp; Fresh Basil (V)<br> Honey and Sesame Coated Cocktail Sausages</p>
  </div>
</div>

More on CSS combinators