问:
Best practice to implement method getXXX from db using cursor for Android
For example code below. Do we need to close cursor? Do we better use try/catch/finally instead of using if()?

```<code>public int getCount() {

    final Cursor countCursor = contentResolver.query(
            AnalyticContract.CONTENT_URI,
            new String[] {"count(*) AS count"},
            null,
            null,
            null);
    if (countCursor == null) {
        return 0;
    }

    countCursor.moveToFirst();
    final int count = countCursor.getInt(0);
    return count;
}
</code>```

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.
https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

答:
The answer I believe is primarily opinion-based. It depends I guess on coder's preference and the circumstances.

I have always preferred the if (cursor != null) or vice versa approach. Unless something truly spectacular has happened; which will be handled by throws Exception, I'd use if-else checks wherever I want the reader/reviewer to see which parts are really and truly exceptions and which are occurrences of different possible/valid scenarios.

This brings us to the current problem of Curosr and applying null checks.

AFAIK (since mostly a Cursor is related with a SQLiteDatabase) a ContentResolver.query() should never return a null Cursor if the query itself is valid unless in case of an invalid query which is a real exception and you should instead get an Exception.

So in my opinion the best approach would be using your example either

```<code>public int getCount() throws Exception {

    Cursor countCursor;
    try {
        countCursor = contentResolver.query(
                AnalyticContract.CONTENT_URI,
                new String[] {"count(*) AS count"},
                null,
                null,
                null);

        countCursor.moveToFirst();
        return countCursor.getInt(0);
    }
    finally {
        cursor.close();
    }
}
</code>```

Or a variation where Exception is caught and handled within the method itself.

Now to answer your second question whether or not you should close() a Cursor: you should always close a Cursor. Whenever you don't have need for it. If you delve deeper into any of the Cursor.close() method-implementations. Since Curosr is an interface which in case of SQLite is implemented by SQLiteCursor you will notice that this method releases any and all allocations held by it.

Body:
For example code below. Do we need to close cursor? Do we better use try/catch/finally instead of using if()?

public int getCount() {

    final Cursor countCursor = contentResolver.query(
            AnalyticContract.CONTENT_URI,
            new String[] {"count(*) AS count"},
            null,
            null,
            null);
    if (countCursor == null) {
        return 0;
    }

    countCursor.moveToFirst();
    final int count = countCursor.getInt(0);
    return count;
}

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.
https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

Body:
The answer I believe is primarily opinion-based. It depends I guess on coder's preference and the circumstances.

I have always preferred the if (cursor != null) or vice versa approach. Unless something truly spectacular has happened; which will be handled by throws Exception, I'd use if-else checks wherever I want the reader/reviewer to see which parts are really and truly exceptions and which are occurrences of different possible/valid scenarios.

This brings us to the current problem of Curosr and applying null checks.

AFAIK (since mostly a Cursor is related with a SQLiteDatabase) a ContentResolver.query() should never return a null Cursor if the query itself is valid unless in case of an invalid query which is a real exception and you should instead get an Exception.

So in my opinion the best approach would be using your example either

public int getCount() throws Exception {

    Cursor countCursor;
    try {
        countCursor = contentResolver.query(
                AnalyticContract.CONTENT_URI,
                new String[] {"count(*) AS count"},
                null,
                null,
                null);

        countCursor.moveToFirst();
        return countCursor.getInt(0);
    }
    finally {
        cursor.close();
    }
}

Or a variation where Exception is caught and handled within the method itself.

Now to answer your second question whether or not you should close() a Cursor: you should always close a Cursor. Whenever you don't have need for it. If you delve deeper into any of the Cursor.close() method-implementations. Since Curosr is an interface which in case of SQLite is implemented by SQLiteCursor you will notice that this method releases any and all allocations held by it.


来源: stackexchange

问:
Create adjacency matrix based on binary variable
I have a data.frame with two columns. One indicating objects, the other one  indicates if the objects are within some group. How can I create an adjacency matrix without writing a loop?

```<code>data("mtcars")
testdf <- data.frame(names=as.character(row.names(mtcars)[1:5]),
                 ingroup=0)

set.seed(123)
testdf$ingroup[testdf$names%in%row.names(mtcars)[sample(length(row.names(mtcars)[1:5]), 2)]] <- 1

testdf
              names ingroup
1         Mazda RX4       0
2     Mazda RX4 Wag       1
3        Datsun 710       0
4    Hornet 4 Drive       1
5 Hornet Sportabout       0
</code>```

EDIT: The desired output should be a matrix indicating if objects are within a certain group:

```<code>data.frame(x1=c(0,0,0,0,0),
       x2=c(0,1,0,0,1),
       x3=c(0,0,0,0,0),
       x4=c(0,0,0,0,0),
       x5=c(0,1,0,0,1))
colnames(output) <- c("Datsun 710", "Hornet 4 Drive", "Hornet Sportabout", "Mazda RX4","Mazda RX4 Wag")
rownames(output) <- c("Datsun 710", "Hornet 4 Drive", "Hornet Sportabout", "Mazda RX4","Mazda RX4 Wag")

output
                  Datsun 710 Hornet 4 Drive Hornet Sportabout Mazda RX4 Mazda RX4 Wag
Datsun 710                 0              0                 0         0             0
Hornet 4 Drive             0              1                 0         0             1
Hornet Sportabout          0              0                 0         0             0
Mazda RX4                  0              0                 0         0             0
Mazda RX4 Wag              0              1                 0         0             1
</code>```

Thanks,
Thomas

答:
You just take the cross product of the ingroup variable:

```<code>res <- tcrossprod(testdf$ingroup)
rownames(res) <- testdf$names
colnames(res) <- testdf$names
res

# Mazda RX4 Mazda RX4 Wag Datsun 710 Hornet 4 Drive Hornet Sportabout
# Mazda RX4                 0             0          0              0                 0
# Mazda RX4 Wag             0             1          0              1                 0
# Datsun 710                0             0          0              0                 0
# Hornet 4 Drive            0             1          0              1                 0
# Hornet Sportabout         0             0          0              0                 0
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a data.frame with two columns. One indicating objects, the other one  indicates if the objects are within some group. How can I create an adjacency matrix without writing a loop?

data("mtcars")
testdf <- data.frame(names=as.character(row.names(mtcars)[1:5]),
                 ingroup=0)

set.seed(123)
testdf$ingroup[testdf$names%in%row.names(mtcars)[sample(length(row.names(mtcars)[1:5]), 2)]] <- 1

testdf
              names ingroup
1         Mazda RX4       0
2     Mazda RX4 Wag       1
3        Datsun 710       0
4    Hornet 4 Drive       1
5 Hornet Sportabout       0

EDIT: The desired output should be a matrix indicating if objects are within a certain group:

data.frame(x1=c(0,0,0,0,0),
       x2=c(0,1,0,0,1),
       x3=c(0,0,0,0,0),
       x4=c(0,0,0,0,0),
       x5=c(0,1,0,0,1))
colnames(output) <- c("Datsun 710", "Hornet 4 Drive", "Hornet Sportabout", "Mazda RX4","Mazda RX4 Wag")
rownames(output) <- c("Datsun 710", "Hornet 4 Drive", "Hornet Sportabout", "Mazda RX4","Mazda RX4 Wag")

output
                  Datsun 710 Hornet 4 Drive Hornet Sportabout Mazda RX4 Mazda RX4 Wag
Datsun 710                 0              0                 0         0             0
Hornet 4 Drive             0              1                 0         0             1
Hornet Sportabout          0              0                 0         0             0
Mazda RX4                  0              0                 0         0             0
Mazda RX4 Wag              0              1                 0         0             1

Thanks,
Thomas

Body:
You just take the cross product of the ingroup variable:

res <- tcrossprod(testdf$ingroup)
rownames(res) <- testdf$names
colnames(res) <- testdf$names
res

# Mazda RX4 Mazda RX4 Wag Datsun 710 Hornet 4 Drive Hornet Sportabout
# Mazda RX4                 0             0          0              0                 0
# Mazda RX4 Wag             0             1          0              1                 0
# Datsun 710                0             0          0              0                 0
# Hornet 4 Drive            0             1          0              1                 0
# Hornet Sportabout         0             0          0              0                 0


问:
retrieve data using AJAX
I have tow file
first file (pie_chart.php ) make more than one  query to select data weekly or daily or monthly from database
this data will be send to the other file (test.php) via json
this file will retrieve this json data to draw chart using google chart api
this is the content of test.php

function pie_chart() {

      var jsonData = $.ajax({
          url: "pie_chart.php",
          dataType: "json",
          async: false
          }).responseText;

      // Create our data table out of JSON data loaded from server.
 alert(jsonData);
      var data = new google.visualization.DataTable(jsonData);

      // Instantiate and draw our chart, passing in some options.
      var chart = new google.visualization.LineChart(document.getElementById('piechart_div'));
      chart.draw(data, {width: 600, height: 400});
 }

</script>```
</div>
</div>
</p>

<p>the question now is
how can I tell ajax to get data from pie_chart.php after if condition
ie
in the pie_chart.php there is </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><?php
include ("inc/db_settings.php");
if($_POST['tar']=='week')
{$sql="SELECT count(username) as count, date(AcctStartTime) AS date1 FROM radacct where date(AcctStartTime) >= curdate() - INTERVAL DAYOFWEEK(curdate())+30 DAY  AND date(AcctStartTime) < curdate() - INTERVAL DAYOFWEEK(curdate())-3 DAY GROUP BY date1";

#$sql = "SELECT

   # `cnumber`AS `count`,`date`
#FROM `chart` WHERE date >= curdate() - INTERVAL DAYOFWEEK(curdate())+6 DAY
#AND date < curdate() - INTERVAL DAYOFWEEK(curdate())-1 DAY";
#$sql="SELECT COUNT(DISTINCT `username`) AS `count`,date(`AcctStartTime`) AS `date` FROM `radacct` where date(AcctStartTime) = curdate() - INTERVAL DAYOFWEEK(curdate())+6 DAY  AND date(AcctStartTime) < curdate() - INTERVAL DAYOFWEEK(curdate())-1 DAY";

/*
SELECT count(username) as count, date(AcctStartTime) AS date1
FROM radacct where date(AcctStartTime) >= curdate() - INTERVAL DAYOFWEEK(curdate())+6 DAY  AND date(AcctStartTime) < curdate() - INTERVAL DAYOFWEEK(curdate())-1 DAY
GROUP BY date1
*/
$query = mysql_query($sql);
while($result = mysql_fetch_array($query))
{
  $rows[]=array("c"=>array("0"=>array("v"=>$result['date1'],"f"=>NULL),"1"=>array("v"=>(int)$result['count'],"f" =>NULL)));

}

echo $format = '{
"cols":
[
{"label":"date1","pattern":"","type":"string"},
{"label":"count","pattern":"","type":"number"}
],
"rows":'.json_encode($rows).'}';
}

else if($_POST['month'])
{
 $sql="select `employee_id`,`date`,`checkin`,`checkout`
from `attendence`
where `date` BETWEEN  MONTH('01-10-2012')
AND  MONTH( '31-10-2012')";
 //do some thing

}?></code>```

I want to make chart (monthly , weekly ,year) using google chart when user select week for example from select object
I send user's choice to pie_chart.php using ajax and make query deppending on it
after that I conver the result to json to send it to test.php which will retrieve this json data to make chart
hope I explained my problem clearly

答:
Use data: in your Ajax to send data parameter

```<code>var aData= [];
aData[1]="Some value";
    var jsonData = JSON.stringify({ aData:aData});
    $.ajax({
        type: "POST",
         url: "pie_chart.php",
        data: jsonData,
        contentType: "application/json; charset=utf-8",
        dataType: "json", // dataType is json format
        success: OnSuccess,
        error: OnErrorCall
    });

    function OnSuccess(response) {

    }
    function OnErrorCall(response) { console.log(error); }
    });
</code>```

Title: retrieve data using AJAX

Body:
I have tow file
first file (pie_chart.php ) make more than one  query to select data weekly or daily or monthly from database
this data will be send to the other file (test.php) via json
this file will retrieve this json data to draw chart using google chart api
this is the content of test.php

function pie_chart() {

      var jsonData = $.ajax({
          url: "pie_chart.php",
          dataType: "json",
          async: false
          }).responseText;

      // Create our data table out of JSON data loaded from server.
 alert(jsonData);
      var data = new google.visualization.DataTable(jsonData);

      // Instantiate and draw our chart, passing in some options.
      var chart = new google.visualization.LineChart(document.getElementById('piechart_div'));
      chart.draw(data, {width: 600, height: 400});
 }

</script>

the question now is
how can I tell ajax to get data from pie_chart.php after if condition
ie
in the pie_chart.php there is

<?php
include ("inc/db_settings.php");
if($_POST['tar']=='week')
{$sql="SELECT count(username) as count, date(AcctStartTime) AS date1 FROM radacct where date(AcctStartTime) >= curdate() - INTERVAL DAYOFWEEK(curdate())+30 DAY  AND date(AcctStartTime) < curdate() - INTERVAL DAYOFWEEK(curdate())-3 DAY GROUP BY date1";

#$sql = "SELECT

   # `cnumber`AS `count`,`date`
#FROM `chart` WHERE date >= curdate() - INTERVAL DAYOFWEEK(curdate())+6 DAY
#AND date < curdate() - INTERVAL DAYOFWEEK(curdate())-1 DAY";
#$sql="SELECT COUNT(DISTINCT `username`) AS `count`,date(`AcctStartTime`) AS `date` FROM `radacct` where date(AcctStartTime) = curdate() - INTERVAL DAYOFWEEK(curdate())+6 DAY  AND date(AcctStartTime) < curdate() - INTERVAL DAYOFWEEK(curdate())-1 DAY";

/*
SELECT count(username) as count, date(AcctStartTime) AS date1
FROM radacct where date(AcctStartTime) >= curdate() - INTERVAL DAYOFWEEK(curdate())+6 DAY  AND date(AcctStartTime) < curdate() - INTERVAL DAYOFWEEK(curdate())-1 DAY
GROUP BY date1
*/
$query = mysql_query($sql);
while($result = mysql_fetch_array($query))
{
  $rows[]=array("c"=>array("0"=>array("v"=>$result['date1'],"f"=>NULL),"1"=>array("v"=>(int)$result['count'],"f" =>NULL)));

}

echo $format = '{
"cols":
[
{"label":"date1","pattern":"","type":"string"},
{"label":"count","pattern":"","type":"number"}
],
"rows":'.json_encode($rows).'}';
}

else if($_POST['month'])
{
 $sql="select `employee_id`,`date`,`checkin`,`checkout`
from `attendence`
where `date` BETWEEN  MONTH('01-10-2012')
AND  MONTH( '31-10-2012')";
 //do some thing

}?>

I want to make chart (monthly , weekly ,year) using google chart when user select week for example from select object
I send user's choice to pie_chart.php using ajax and make query deppending on it
after that I conver the result to json to send it to test.php which will retrieve this json data to make chart
hope I explained my problem clearly

Body:
Use data: in your Ajax to send data parameter

var aData= [];
aData[1]="Some value";
    var jsonData = JSON.stringify({ aData:aData});
    $.ajax({
        type: "POST",
         url: "pie_chart.php",
        data: jsonData,
        contentType: "application/json; charset=utf-8",
        dataType: "json", // dataType is json format
        success: OnSuccess,
        error: OnErrorCall
    });

    function OnSuccess(response) {

    }
    function OnErrorCall(response) { console.log(error); }
    });


问:
jQuery - hide link/"a" element's text in IE
Hi

Suppose I have a code like that:

```<code><a style="background: url(button.jpg);" herf="#">test</a>
</code>```

This code will display a link with a button image, In Chrome/FF, the text "test" have not displayed, but in IE, it displayed.

I try to use text-indent: -999px to hide the text "test", and not work, could someone provide an idea for this problem?

Found a solution:
http://schleichermann.wordpress.com/2009/02/25/css-hide-link-text-let-your-images-shine-through/

Thanks you

答:
Using jQuery:</p>

```<code>$("a").contents().hide();
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Hi

Suppose I have a code like that:

test

This code will display a link with a button image, In Chrome/FF, the text "test" have not displayed, but in IE, it displayed.

I try to use text-indent: -999px to hide the text "test", and not work, could someone provide an idea for this problem?

Found a solution:
http://schleichermann.wordpress.com/2009/02/25/css-hide-link-text-let-your-images-shine-through/

Thanks you

Body:
Using jQuery:

$("a").contents().hide();


问:
Why is there a curly parenthesis in the following C# code?
I am new in C#. I am following a video on a GUI framework. I wonder why there is not normal parenthesis '()' but curly parenthesis '{}' after the 'new Label' in the following code.

Are we not instantiating a class here?

```<code>Content = new Label {
    HorizontalOptions = LayoutOptions.Center,
    VerticalOptions = LayoutOptions.Center,
    Text = "Hello word"
};
</code>```

答:
This is an object initializer - introduced in C# 3.0

```<code>Content = new Label {
    HorizontalOptions = LayoutOptions.Center,
    VerticalOptions = LayoutOptions.Center,
    Text = "Hello word"
};
</code>```

Will only work if Label has a parameterless constructor.

We can assume Label looks something like this:

```<code>public class Label
{
    public Label()
    {
        //this empty ctor is not required by the compiler
        //just here for illustration
    }

    public string HorizontalOptions {get;set}
    public string VerticalOptions  {get;set}
    public string Text {get;set}
}
</code>```

The object initializer is setting the properties, when it's instantiated.

If, however, Label did have a parameter in the ctor, like this:

```<code>public class Label
{
    public Label(string text)
    {
        Text = text
    }

    public string HorizontalOptions {get;set}
    public string VerticalOptions  {get;set}
    public string Text {get;set}
}
</code>```

then this would be equivalent

```<code>Content = new Label("Hello World") { //notice I'm passing parameter to ctor here
    HorizontalOptions = LayoutOptions.Center,
    VerticalOptions = LayoutOptions.Center,
};
</code>```

Body:
I am new in C#. I am following a video on a GUI framework. I wonder why there is not normal parenthesis '()' but curly parenthesis '{}' after the 'new Label' in the following code.

Are we not instantiating a class here?

Content = new Label {
    HorizontalOptions = LayoutOptions.Center,
    VerticalOptions = LayoutOptions.Center,
    Text = "Hello word"
};

Body:
This is an object initializer - introduced in C# 3.0

Content = new Label {
    HorizontalOptions = LayoutOptions.Center,
    VerticalOptions = LayoutOptions.Center,
    Text = "Hello word"
};

Will only work if Label has a parameterless constructor.

We can assume Label looks something like this:

public class Label
{
    public Label()
    {
        //this empty ctor is not required by the compiler
        //just here for illustration
    }

    public string HorizontalOptions {get;set}
    public string VerticalOptions  {get;set}
    public string Text {get;set}
}

The object initializer is setting the properties, when it's instantiated.

If, however, Label did have a parameter in the ctor, like this:

public class Label
{
    public Label(string text)
    {
        Text = text
    }

    public string HorizontalOptions {get;set}
    public string VerticalOptions  {get;set}
    public string Text {get;set}
}

then this would be equivalent

Content = new Label("Hello World") { //notice I'm passing parameter to ctor here
    HorizontalOptions = LayoutOptions.Center,
    VerticalOptions = LayoutOptions.Center,
};


问:
Can admob banner ads be applied on Dialog? Or its against google ads placement policies
I have custom dialog in my app, they popup when some event occur.
I am thinking to put banner ads on my app dialog popups.
Will that be a good practice ,or its against google banner ads placement policy ?</p>

答: Even I had the same problem. You cannot use them in Dialog box as the ads wont appear.</p>


问:
Why do I keep getting an error saying e in endtime is invalid syntax in Python?
```<code>import time as t
t = t.time
starttime = t
def calcprod():
    prod = 1
    for i in range(1, 1000000):
        prod = prod * i
p = calcprod()
print("The result is %s digits" % (str(len(p))))
endtime = t
print("It took %s seconds to calculate" % (starttime - endtime))
</code>```

I don't know how I can fix my code.

答:
Below you find some hopefully useful comments to solve your problems:</p>

```<code>import time as t
t = t.time    # Don't name this the same as your time library
              # Also use t.time() instead of t.time
starttime = t
def calcprod():
    prod = 1
    for i in range(1, 1000000):
        prod = prod * i
        # return a value here (hint: cast the result to a string)
p = calcprod()
print("The result is %s digits" % (str(len(p))))
endtime = t    # This assigns the same value to 'endtime' as starttime.
               # You need to measure the current time again.
               # How can you do this?
print("It took %s seconds to calculate" % (starttime - endtime))
                # Does it make sense to calculate starttime-endtime?
                # Which one is the bigger value?
</code>```

Body:
import time as t
t = t.time
starttime = t
def calcprod():
    prod = 1
    for i in range(1, 1000000):
        prod = prod * i
p = calcprod()
print("The result is %s digits" % (str(len(p))))
endtime = t
print("It took %s seconds to calculate" % (starttime - endtime))

I don't know how I can fix my code.

Body:
Below you find some hopefully useful comments to solve your problems:

import time as t
t = t.time    # Don't name this the same as your time library
              # Also use t.time() instead of t.time
starttime = t
def calcprod():
    prod = 1
    for i in range(1, 1000000):
        prod = prod * i
        # return a value here (hint: cast the result to a string)
p = calcprod()
print("The result is %s digits" % (str(len(p))))
endtime = t    # This assigns the same value to 'endtime' as starttime.
               # You need to measure the current time again.
               # How can you do this?
print("It took %s seconds to calculate" % (starttime - endtime))
                # Does it make sense to calculate starttime-endtime?
                # Which one is the bigger value?


问:
ASP MVC multiple razor forms submits to same controller?
I have created two razor forms in one view file in the view file i have created two Html.BeginForm() and mentioned different controllers, but when i submit the form, form submits to same controller.

view file

```<code>@using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
    @Html.AntiForgeryToken()
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

    @Html.TextBoxFor(m => m.email, new { @class = "form-control" })
    @Html.ValidationMessageFor(m => m.email, "", new { @class = "text-danger" })

    @Html.PasswordFor(m => m.password, new { @class = "form-control" })
    @Html.ValidationMessageFor(m => m.password, "", new { @class = "text-danger" })

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Log in" class="btn btn-default" />
        </div>
    </div>

}

@using (Html.BeginForm(Html.BeginForm("Register", "Account", FormMethod.Post, new { @class = "login", id = "f1" })))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

    @Html.ValidationSummary("", new { @class = "text-danger" })
        <p class="form-row form-row-first input-required">

    @Html.EditorFor(model => model.email, new { htmlAttributes = new { @class = "input-text" } })
    @Html.ValidationMessageFor(model => model.email, "", new { @class = "text-danger" })

    @Html.PasswordFor(model => model.password, new { htmlAttributes = new { @class = "input-text" } })
    @Html.ValidationMessageFor(model => model.password, "", new { @class = "text-danger" })

    @Html.PasswordFor(model => model.ConfirmPassword, new { htmlAttributes = new { @class = "input-text" } })
    @Html.ValidationMessageFor(model => model.ConfirmPassword, "", new { @class = "text-danger" })

    @Html.EditorFor(model => model.first_name, new { htmlAttributes = new { @class = "input-text" } })
    @Html.ValidationMessageFor(model => model.first_name, "", new { @class = "text-danger" })

    @Html.EditorFor(model => model.last_name, new { htmlAttributes = new { @class = "input-text" } })
    @Html.ValidationMessageFor(model => model.last_name, "", new { @class = "text-danger" })

    @Html.EditorFor(model => model.address, new { htmlAttributes = new { @class = "input-text" } })
    @Html.ValidationMessageFor(model => model.address, "", new { @class = "text-danger" })

    <div class="clear"></div>
        <input type="submit" value="Signup" name="signup" class="button btn btn-default" />
    <div class="clear"></div>
}
</code>```

Controller File

```<code>[HttpPost]
[ValidateAntiForgeryToken]
    public ActionResult Login()
    {
        //Controller stuffs
    }

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Register()
{
   //Controller stuffs
}
</code>```

Each time when i submit the form it is going to register  controller how to fix this?

答:
Try specify the parameters name in Html.BeginForm

```<code>@using (Html.BeginForm(actionName: "Register", controllerName: "Account", method: FormMethod.Post, htmlAttributes: new { @class = "login", id = "f1" }))
</code>```

Also I believe you have a typo Html.BeginForm(Html.BeginForm

Body:
I have created two razor forms in one view file in the view file i have created two Html.BeginForm() and mentioned different controllers, but when i submit the form, form submits to same controller.

view file

@using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
    @Html.AntiForgeryToken()

    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

    @Html.TextBoxFor(m => m.email, new { @class = "form-control" })
    @Html.ValidationMessageFor(m => m.email, "", new { @class = "text-danger" })

    @Html.PasswordFor(m => m.password, new { @class = "form-control" })
    @Html.ValidationMessageFor(m => m.password, "", new { @class = "text-danger" })

            <input type="submit" value="Log in" class="btn btn-default" />

}

@using (Html.BeginForm(Html.BeginForm("Register", "Account", FormMethod.Post, new { @class = "login", id = "f1" })))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

    @Html.ValidationSummary("", new { @class = "text-danger" })

    @Html.EditorFor(model => model.email, new { htmlAttributes = new { @class = "input-text" } })
    @Html.ValidationMessageFor(model => model.email, "", new { @class = "text-danger" })

    @Html.PasswordFor(model => model.password, new { htmlAttributes = new { @class = "input-text" } })
    @Html.ValidationMessageFor(model => model.password, "", new { @class = "text-danger" })

    @Html.PasswordFor(model => model.ConfirmPassword, new { htmlAttributes = new { @class = "input-text" } })
    @Html.ValidationMessageFor(model => model.ConfirmPassword, "", new { @class = "text-danger" })

    @Html.EditorFor(model => model.first_name, new { htmlAttributes = new { @class = "input-text" } })
    @Html.ValidationMessageFor(model => model.first_name, "", new { @class = "text-danger" })

    @Html.EditorFor(model => model.last_name, new { htmlAttributes = new { @class = "input-text" } })
    @Html.ValidationMessageFor(model => model.last_name, "", new { @class = "text-danger" })

    @Html.EditorFor(model => model.address, new { htmlAttributes = new { @class = "input-text" } })
    @Html.ValidationMessageFor(model => model.address, "", new { @class = "text-danger" })

        <input type="submit" value="Signup" name="signup" class="button btn btn-default" />

}

Controller File

[HttpPost]
[ValidateAntiForgeryToken]
    public ActionResult Login()
    {
        //Controller stuffs
    }

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Register()
{
   //Controller stuffs
}

Each time when i submit the form it is going to register  controller how to fix this?

Body:
Try specify the parameters name in Html.BeginForm

@using (Html.BeginForm(actionName: "Register", controllerName: "Account", method: FormMethod.Post, htmlAttributes: new { @class = "login", id = "f1" }))

Also I believe you have a typo Html.BeginForm(Html.BeginForm


问:
Could not remove the old plugin
I'm trying to update the plugins on my clients site and I'm getting this error for multiple plugins. He's using plesk.

```<code>Downloading update from https://downloads.wordpress.org/plugin/awesometastic.131026.zip…
Unpacking the update…
Installing the latest version…
Removing the old version of the plugin…
Plugin update failed.

An error occurred while updating Awesometastic Plugin: Could not remove the old plugin.
</code>```

I'm sure it's got something to do with directory permissions, although, could someone explain to me what the possible issues are and how to fix this?

Thanks!

答:
first you have to delete the old plugin than update

If you have SSH access to your blog
Login your site via SSH.
Use SSH commands to nagivate “../wp-content/plugins/”.
type the given command to see all files and folders in the plugin folder

```<code>    ls -al
</code>```

Search for the particular plugin folder in the list.
Next, type the given command to delete that folder.
In the command, replace the folder name with your plugin folder name which is you want to delete.

```<code>    rm folder name
</code>```

now you're able to delete your old plugin.

Title: Could not remove the old plugin

Body:
I'm trying to update the plugins on my clients site and I'm getting this error for multiple plugins. He's using plesk.

Downloading update from https://downloads.wordpress.org/plugin/awesometastic.131026.zip…
Unpacking the update…
Installing the latest version…
Removing the old version of the plugin…
Plugin update failed.

An error occurred while updating Awesometastic Plugin: Could not remove the old plugin.

I'm sure it's got something to do with directory permissions, although, could someone explain to me what the possible issues are and how to fix this?

Thanks!

Body:
first you have to delete the old plugin than update

If you have SSH access to your blog
Login your site via SSH.
Use SSH commands to nagivate “../wp-content/plugins/”.
type the given command to see all files and folders in the plugin folder

    ls -al

Search for the particular plugin folder in the list.
Next, type the given command to delete that folder.
In the command, replace the folder name with your plugin folder name which is you want to delete.

    rm folder name

now you're able to delete your old plugin.


问:
IOS:UISerachBar Filter name but not the related id with it
i have a JSON Dict in this format

```<code>{
  "382" : "sudhir kumar",
  "268" : "David  ",
  "385" : "aayush test",
  "261" : "Mike watson",
  "277" : "TestDrivers Driver",
  "381" : "sudhir kumar",
  "380" : "sudhir kumar",
  "383" : "asdfgh asdfgh",
  "376" : " "
}
</code>```

I have to display it in UISearchBar. Someone please help me to solve it as when i select any name from search its respective Id also selected

I am using the following code it filtered name but not their related ID's with name

My code is:

```<code>- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText;
{
    tempArray = [NSArray arrayWithArray:DriverNameArray];
    //NSString *stringToSearch = textField.text;

    tempId = [NSArray arrayWithArray:DriverIdArray];

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH[c] %@",searchText]; // if you need case sensitive search avoid '[c]' in the predicate

    //NSPredicate * predicateid = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH[c] %@",stringToSearch];

    NSArray *tempresults = [DriverNameArray filteredArrayUsingPredicate:predicate];
    if (tempresults.count > 0)
    {
        tempArray = [NSArray arrayWithArray:tempresults];
        tempId = [NSArray arrayWithArray:tempresults];
    }
    [SEarchTable reloadData];
    //return  YES;
}
</code>```

It always returns the same id for all the filtered names

答:
Create NSarray of NSdictionary containing id and name

```<code>MasterArray :

(
 0{ id = "382" , drivername = "sudhir kumar"}
 1{ id = "383" , drivername = "sudha mishra"}
.
.
 n{ id = "384" , drivername = "sudesh pandit"}
)
</code>```

whatever search result you will get in Your DriverNameArray. Iterate for loop through that and compare driver name with MasterArray
:

```<code>for(i = 0; i< DriverNameArray.count , i++)
{
    //take driver name from search result array
    NSString * driverName = [DriverNameArray objectAtIndex:i];
    for(j = 0; j< MasterArray.count , j++){// search driver name in MasterArray
        NSDictionary *driverInfoDic = [MasterArray objectAtIndex:j];
        if(driverName isEqualToString:[driverInfoDic objectForKey:@"drivername"])
            NSString *driverId = [driverInfoDic objectForKey:@"Id"];//use this driver id by storing it in DiverIdArray
    }
}
</code>```

Body:
i have a JSON Dict in this format

{
  "382" : "sudhir kumar",
  "268" : "David  ",
  "385" : "aayush test",
  "261" : "Mike watson",
  "277" : "TestDrivers Driver",
  "381" : "sudhir kumar",
  "380" : "sudhir kumar",
  "383" : "asdfgh asdfgh",
  "376" : " "
}

I have to display it in UISearchBar. Someone please help me to solve it as when i select any name from search its respective Id also selected

I am using the following code it filtered name but not their related ID's with name

My code is:

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText;
{
    tempArray = [NSArray arrayWithArray:DriverNameArray];
    //NSString *stringToSearch = textField.text;

    tempId = [NSArray arrayWithArray:DriverIdArray];

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH[c] %@",searchText]; // if you need case sensitive search avoid '[c]' in the predicate

    //NSPredicate * predicateid = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH[c] %@",stringToSearch];

    NSArray *tempresults = [DriverNameArray filteredArrayUsingPredicate:predicate];
    if (tempresults.count > 0)
    {
        tempArray = [NSArray arrayWithArray:tempresults];
        tempId = [NSArray arrayWithArray:tempresults];
    }
    [SEarchTable reloadData];
    //return  YES;
}

It always returns the same id for all the filtered names

Body:
Create NSarray of NSdictionary containing id and name

MasterArray :

(
 0{ id = "382" , drivername = "sudhir kumar"}
 1{ id = "383" , drivername = "sudha mishra"}
.
.
 n{ id = "384" , drivername = "sudesh pandit"}
)

whatever search result you will get in Your DriverNameArray. Iterate for loop through that and compare driver name with MasterArray
:

for(i = 0; i< DriverNameArray.count , i++)
{
    //take driver name from search result array
    NSString * driverName = [DriverNameArray objectAtIndex:i];
    for(j = 0; j< MasterArray.count , j++){// search driver name in MasterArray
        NSDictionary *driverInfoDic = [MasterArray objectAtIndex:j];
        if(driverName isEqualToString:[driverInfoDic objectForKey:@"drivername"])
            NSString *driverId = [driverInfoDic objectForKey:@"Id"];//use this driver id by storing it in DiverIdArray
    }
}


问:
Defining two objects of differeent classes inside each class
I created two classes.

One class is called Frames, and inside it I defined a Jframe and an Image.

In another class which is called Panels, I defined a Jpanel.

I want to pass the panel to Frames class  using getPanel method and pass the image to the Panels class using getImage methods.

So I created a Frames object inside Panels class to call getImage
and created a Panels object inside Frames class to call getPanel.
But when I run the code, this message appears:

Exception in thread "main" java.lang.StackOverflowError.

```<code>public class panels{

    frames framesObject = new frames();
    JPanel panel = new JPanel(){
        public void painComponent(Graphics g){
            super.paintComponent(g);
            g.drawImage(frames.getImage(),0,0,null);
        }
    };

    public Jpanel getPanel(){
        return panel;
    }

}

public class frames{

    JFrame frame= new JFrame();
    Toolkit toolkit= Toolkit.getDefaultToolkit();
    Image image = toolkit.getImage("..source file..");
    panels panelsObject= new panels();
    frame.add(panelsObject.getPanel());

    public Image getImage(){
        return image;
}
</code>```

答:
So I created a Frames object inside Panels class to call getImage() and created a Panels object inside Frames class to call getPanel().

So you created a mutual recursion.

Solution: don't. Make up your mind about which should be inside which, and stick to it.

Body:
I created two classes.

One class is called Frames, and inside it I defined a Jframe and an Image.

In another class which is called Panels, I defined a Jpanel.

I want to pass the panel to Frames class  using getPanel method and pass the image to the Panels class using getImage methods.

So I created a Frames object inside Panels class to call getImage
and created a Panels object inside Frames class to call getPanel.
But when I run the code, this message appears:

Exception in thread "main" java.lang.StackOverflowError.

public class panels{

    frames framesObject = new frames();
    JPanel panel = new JPanel(){
        public void painComponent(Graphics g){
            super.paintComponent(g);
            g.drawImage(frames.getImage(),0,0,null);
        }
    };

    public Jpanel getPanel(){
        return panel;
    }

}

public class frames{

    JFrame frame= new JFrame();
    Toolkit toolkit= Toolkit.getDefaultToolkit();
    Image image = toolkit.getImage("..source file..");
    panels panelsObject= new panels();
    frame.add(panelsObject.getPanel());

    public Image getImage(){
        return image;
}


问:
HTTP Connection in Iphone
Since I'm new in iphone I need help in learning about http Connections in Iphone.
Please guide me to some tutorials so that I could learn some http connections tricks in iphone and could communicate with websites.

Also please guide me through some Sample code for the following problem:
I want to send some "Hello world" text to the site and got a reply back from the Web the same word with adiition of s i.e. "Hello Worlds".. please brothers guide me through any sample code.. it's a part of my application that I'm developing in iphone.

答:
You may check this. ASIHTTPRequest package is a highly recommended tool for handling traffic on a iPhone app.

http://allseeing-i.com/ASIHTTPRequest/How-to-use

Title: HTTP Connection in Iphone


问:
setOnItemClickListener() not working on gridView in Fragment
setOnItemClickListener() not working on gridView in Fragment

I have a gridview inside A Fragment I hae set a onItemClick for that , however it does not work

I have tried  android:descendantFocusability="blocksDescendants" but still its not clicked

here is the code

```<code>public class ImageGalfrag extends Fragment {
    private Cursor cursor;
     private int columnIndex;
    ImageView thumbV;
    ImageButton videoICON;
    ArrayList<Bitmap> bitmapArray = new ArrayList<Bitmap>();
//   @Override
//    public void onCreate(Bundle savedInstanceState) {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    return inflater.inflate(R.layout.gallery_gridview, container, false);
}
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //setContentView(R.layout.gallery_gridview);
        try {
            String[] projection = {MediaStore.Images.Thumbnails._ID};

            cursor = getActivity().managedQuery( MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
                    projection, // Which columns to return
                    null,       // Return all rows
                    null,
                    MediaStore.Images.Thumbnails.IMAGE_ID);
            View v = getView();
            // Get the column index of the Thumbnails Image ID
            columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
            GridView sdcardImages = (GridView) v.findViewById(R.id.PhoneImageGrid);
            sdcardImages.setAdapter(new ImageAdapter(getActivity()));
            sdcardImages.setOnItemClickListener(new OnItemClickListener() {
               public void onItemClick(AdapterView parent, View v, int position, long id) {
                  String[] projection = {MediaStore.Images.Media.DATA};
                   cursor = getActivity().managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                           projection, // Which columns to return
                           null,       // Return all rows
                           null,
                           null);
                   columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                   cursor.moveToPosition(position);
                   String imagePath = cursor.getString(columnIndex);
           Toast.makeText(getActivity(), "" + imagePath, Toast.LENGTH_SHORT).show();
                   ImageAdd(imagePath);
                   Intent ImageIntent = new Intent(getActivity(), ZoomImageView.class);
                   ImageIntent.putExtra("ImageName", imagePath);
                   getActivity().startActivity(ImageIntent);

               }
           });
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
    }
    public void ImageAdd(String imagePath){

        try {
            BitmapFactory.Options bmOptions = new BitmapFactory.Options();
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath, bmOptions);
            bitmapArray.add(bitmap);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private class ImageAdapter extends BaseAdapter {
        private Context context;
        public ImageAdapter(Context localContext) {
            context = localContext;
        }
        public int getCount() {
            return cursor.getCount();
        }
        public Object getItem(int position) {
            return position;
        }
        public long getItemId(int position) {
            return position;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView imageView;
            View grid = null;
            try {
                LayoutInflater inflater = getActivity().getLayoutInflater();
                if (convertView == null) {
                    try {
                        cursor.moveToPosition(position);
                        int imageID = cursor.getInt(columnIndex);
                        //grid = new View(mContext);
                        grid = inflater.inflate(R.layout.gallery_view, null);
                        //TextView textView = (TextView) grid.findViewById(R.id.grid_text);
                        thumbV = (ImageView) grid.findViewById(R.id.thumbImage);
                        thumbV.setImageURI(Uri.withAppendedPath(
                                MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, "" + imageID));
                        videoICON = (ImageButton) grid.findViewById(R.id.videoICON);
                        //textView.setText("");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    grid = (View) convertView;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return grid;
        }
    }
}
</code>```

and the Layout is

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:descendantFocusability="blocksDescendants"
    >

    <GridView
        android:id="@+id/PhoneImageGrid"
        android:numColumns="2"
        android:gravity="center"
        android:columnWidth="250dp"
        android:stretchMode="columnWidth"
        android:layout_width="fill_parent"

        android:layout_height="wrap_content"></GridView>

</RelativeLayout>
</code>```

Grid Item is

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:id="@+id/fragment_gallery1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#FFFFFF"
    android:orientation="vertical"
    android:padding="5dp">

    <LinearLayout

        android:id="@+id/fragment_gallery"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#455569"
        android:orientation="vertical"
        android:padding="5dp">

        <ImageView
            android:id="@+id/thumbImage"
            android:layout_width="match_parent"
            android:layout_height="150dp"
            android:layout_gravity="center_horizontal"
            android:background="#CCCCCC"
            android:scaleType="fitXY"
            android:layout_margin="5dp"
            android:src="@mipmap/ic_launcher" />

        <ImageButton
            android:id="@+id/videoICON"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_below="@+id/thumbImage"
            android:layout_gravity="center_horizontal"
            android:layout_marginTop="0dp"
            android:background="#00000000"
            android:scaleType="fitXY" />

    </LinearLayout>
</LinearLayout>
</code>```

答:
Don't use an ItemClickListener.

In your getView() method, in your adapter. Do this:

```<code> @Override
 public View getView(final int position ...

    grid.setOnClickListener(new View.OnClickListener() {
        @Override

    public void onClick(View v) {

    //Do something

    }});
</code>```

Body:
setOnItemClickListener() not working on gridView in Fragment

I have a gridview inside A Fragment I hae set a onItemClick for that , however it does not work

I have tried  android:descendantFocusability="blocksDescendants" but still its not clicked

here is the code

public class ImageGalfrag extends Fragment {
    private Cursor cursor;
     private int columnIndex;
    ImageView thumbV;
    ImageButton videoICON;
    ArrayList<Bitmap> bitmapArray = new ArrayList<Bitmap>();
//   @Override
//    public void onCreate(Bundle savedInstanceState) {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    return inflater.inflate(R.layout.gallery_gridview, container, false);
}
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //setContentView(R.layout.gallery_gridview);
        try {
            String[] projection = {MediaStore.Images.Thumbnails._ID};

            cursor = getActivity().managedQuery( MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
                    projection, // Which columns to return
                    null,       // Return all rows
                    null,
                    MediaStore.Images.Thumbnails.IMAGE_ID);
            View v = getView();
            // Get the column index of the Thumbnails Image ID
            columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
            GridView sdcardImages = (GridView) v.findViewById(R.id.PhoneImageGrid);
            sdcardImages.setAdapter(new ImageAdapter(getActivity()));
            sdcardImages.setOnItemClickListener(new OnItemClickListener() {
               public void onItemClick(AdapterView parent, View v, int position, long id) {
                  String[] projection = {MediaStore.Images.Media.DATA};
                   cursor = getActivity().managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                           projection, // Which columns to return
                           null,       // Return all rows
                           null,
                           null);
                   columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                   cursor.moveToPosition(position);
                   String imagePath = cursor.getString(columnIndex);
           Toast.makeText(getActivity(), "" + imagePath, Toast.LENGTH_SHORT).show();
                   ImageAdd(imagePath);
                   Intent ImageIntent = new Intent(getActivity(), ZoomImageView.class);
                   ImageIntent.putExtra("ImageName", imagePath);
                   getActivity().startActivity(ImageIntent);

               }
           });
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
    }
    public void ImageAdd(String imagePath){

        try {
            BitmapFactory.Options bmOptions = new BitmapFactory.Options();
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath, bmOptions);
            bitmapArray.add(bitmap);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private class ImageAdapter extends BaseAdapter {
        private Context context;
        public ImageAdapter(Context localContext) {
            context = localContext;
        }
        public int getCount() {
            return cursor.getCount();
        }
        public Object getItem(int position) {
            return position;
        }
        public long getItemId(int position) {
            return position;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView imageView;
            View grid = null;
            try {
                LayoutInflater inflater = getActivity().getLayoutInflater();
                if (convertView == null) {
                    try {
                        cursor.moveToPosition(position);
                        int imageID = cursor.getInt(columnIndex);
                        //grid = new View(mContext);
                        grid = inflater.inflate(R.layout.gallery_view, null);
                        //TextView textView = (TextView) grid.findViewById(R.id.grid_text);
                        thumbV = (ImageView) grid.findViewById(R.id.thumbImage);
                        thumbV.setImageURI(Uri.withAppendedPath(
                                MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, "" + imageID));
                        videoICON = (ImageButton) grid.findViewById(R.id.videoICON);
                        //textView.setText("");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    grid = (View) convertView;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return grid;
        }
    }
}

and the Layout is

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:descendantFocusability="blocksDescendants"
    >

    <GridView
        android:id="@+id/PhoneImageGrid"
        android:numColumns="2"
        android:gravity="center"
        android:columnWidth="250dp"
        android:stretchMode="columnWidth"
        android:layout_width="fill_parent"

        android:layout_height="wrap_content"></GridView>

</RelativeLayout>

Grid Item is

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:id="@+id/fragment_gallery1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#FFFFFF"
    android:orientation="vertical"
    android:padding="5dp">

    <LinearLayout

        android:id="@+id/fragment_gallery"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#455569"
        android:orientation="vertical"
        android:padding="5dp">

        <ImageView
            android:id="@+id/thumbImage"
            android:layout_width="match_parent"
            android:layout_height="150dp"
            android:layout_gravity="center_horizontal"
            android:background="#CCCCCC"
            android:scaleType="fitXY"
            android:layout_margin="5dp"
            android:src="@mipmap/ic_launcher" />

        <ImageButton
            android:id="@+id/videoICON"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_below="@+id/thumbImage"
            android:layout_gravity="center_horizontal"
            android:layout_marginTop="0dp"
            android:background="#00000000"
            android:scaleType="fitXY" />

    </LinearLayout>
</LinearLayout>

Body:
Don't use an ItemClickListener.

In your getView() method, in your adapter. Do this:

 @Override
 public View getView(final int position ...

    grid.setOnClickListener(new View.OnClickListener() {
        @Override

    public void onClick(View v) {

    //Do something

    }});


问:
How to open a file in an application and press keys from batch file?
I have a file that I wish to update through a batch file. I am able to open the file in its application but not run CTRL+R to update it. Code below.

```<code>START "" "path to application" "path to file"

SLEEP 10

WshShell.SendKeys “^r”
</code>```

This results in the file being opened but not refreshed. Any tips?

答:
I managed to find the issue myself. It turns out that

```<code>"path to application" /r "path to file"
</code>```

was a viable solution as long as the paths didn't contain any scandinavian characters. It opens a file in a application presses CTRL+R which reloads my file.

Body:
I have a file that I wish to update through a batch file. I am able to open the file in its application but not run CTRL+R to update it. Code below.

START "" "path to application" "path to file"

SLEEP 10

WshShell.SendKeys “^r”

This results in the file being opened but not refreshed. Any tips?

Body:
I managed to find the issue myself. It turns out that

"path to application" /r "path to file"

was a viable solution as long as the paths didn't contain any scandinavian characters. It opens a file in a application presses CTRL+R which reloads my file.


问:
Manually put files to Android emulator SD card
I'm just having trouble with getting my emulator SD card work...
I created a new AVD device with a new SD card.

So how to put data onto it? I found the "correct" file to be mounted on Daemon tools, but is corrupt or simply not readable...

It would be great if you have any idea :)

答: One easy way is to drag and drop. It will copy files to /sdcard/Download. You can copy whole folders or multiple files. Make sure that "Enable Clipboard Sharing" is enabled. (under ...->Settings)


问:
Anchor link goes too low
First of all, my website is: www.interlaser.webovo.nl

The problem is the anchor links. If you click on "Lasershow" or "Over Interlaser" in the menu, the page goes a bit too low. The space between the menu and the header has to be atleast some pixels.

What i've tried:

make a div between them. But then the colour of the different sections is a problem.

Margin-top > doesnt help

Someone can tell what i did wrong?

答:
on each anchor element ( h2 for exemple ), adjust your height with margin and counterbalance with padding :</p>

```<code>  padding-top: 40px;
  margin-top: -40px;
</code>```

Title: Anchor link goes too low

Body:
on each anchor element ( h2 for exemple ), adjust your height with margin and counterbalance with padding :

  padding-top: 40px;
  margin-top: -40px;


问:
Swift 3: JSON into tableview challenge
I have the following swift3 code:

```<code>    var tempNames = ["Alan","Dan","Mark","Jack","Kelly","Andrew","Paul"]

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell", for: indexPath)

    let tempName = tempNames[indexPath.row]
    cell.textLabel?.text = tempName
    cell.detailTextLabel?.text = "Score"

    return cell
}
</code>```

Which produces the following:

As you can see the names are static and the score simply is the word "score".  The following JSON is returned from
"https://str8red.com/jsonoverallleaderboard/":

```<code>[["shanu", "1056"], ["snookro", "828"], ["tingeypa", "709"], ["shaun", "620"], ["chrakers", "506"]]
</code>```

What I would like to do is used the names and score from the above JSON instead of the static name and score already in use.

I have had a look around on stackoverflow and followed some guides without success.  Any help on this would be appreciated, Alan.

答:
Create a struct

```<code>struct Player {
    let name : String
    var score : String
}
</code>```

In the view controller create a data source array

```<code>var players = [Player]()
</code>```

After parsing the JSON having the array in the question (assuming it's in the variable jsonPlayers of type [[String]]) map the array to the struct

```<code>players = jsonPlayers.map { Player(name: $0[0], score: $0[1]) }
</code>```

In numberOfRows return

```<code>return players.count
</code>```

In cellForRow assign the values to the labels

```<code>let player = players[indexPath.row]
cell.textLabel?.text = player.name
cell.detailTextLabel?.text = player.score
</code>```

Title: Swift 3: JSON into tableview challenge

Body:
I have the following swift3 code:

    var tempNames = ["Alan","Dan","Mark","Jack","Kelly","Andrew","Paul"]

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell", for: indexPath)

    let tempName = tempNames[indexPath.row]
    cell.textLabel?.text = tempName
    cell.detailTextLabel?.text = "Score"

    return cell
}

Which produces the following:

As you can see the names are static and the score simply is the word "score".  The following JSON is returned from
"https://str8red.com/jsonoverallleaderboard/":

[["shanu", "1056"], ["snookro", "828"], ["tingeypa", "709"], ["shaun", "620"], ["chrakers", "506"]]

What I would like to do is used the names and score from the above JSON instead of the static name and score already in use.

I have had a look around on stackoverflow and followed some guides without success.  Any help on this would be appreciated, Alan.

Body:
Create a struct

struct Player {
    let name : String
    var score : String
}

In the view controller create a data source array

var players = [Player]()

After parsing the JSON having the array in the question (assuming it's in the variable jsonPlayers of type [[String]]) map the array to the struct

players = jsonPlayers.map { Player(name: $0[0], score: $0[1]) }

In numberOfRows return

return players.count

In cellForRow assign the values to the labels

let player = players[indexPath.row]
cell.textLabel?.text = player.name
cell.detailTextLabel?.text = player.score


问:
How to tell if a mobile page was designed specifically for mobile?
Is there a way to tell if a mobile page you've downloaded is just a desktop page modified with media queries, or is a separate page designed specifically for mobile? I'd like to go through a list of the "20 Best Mobile Pages" and see what percent were designed specially for mobile. </p>

答:
Let me express my understanding on your task:
You want to check whether one webpage, e.g. https://www.google.com, is designed for both mobile device and desktop computer(it means the two types visit could cause server deliver different webpage), or just for mobile device or just for desktop.

If my understanding is right, the following is my answer:

You could change the "user agent" in your http request, then analyze whether you could get the same or different content from the same URL. About the "user agent", more explanation is here:
https://www.thoughtco.com/detecting-hits-from-mobile-devices-3469093

After you get the contents from different "user agent" settings in your http requests, then if the mobile device's type "user agent" content is different from the desktop's type "user agent" content, then you could assume that URL page is specially designed for a mobile device.

But because there is no special international standard to tell the client whether the content is for mobile or for desktop computer, so it's your job to make this decision after you get the same HTML content from both mobile device "user agent" and desktop "user agent" settings.


问:
Setting up an environment for a frontend project
I'm working on a pure frontend project using VS Code. I have a folder for typescript and another one for sass. I'm compiling those with Gulp in separate folders for js and css.

I faced a problem when I tried to use var something = require('some-node-module'); and got an error both in typescript and browser console. I added @types for this but it didn't worked as I still got an error in browser console. I searched more and found this question, I understood what the problem is and I used Browserify from there. Now typescript is compiled without errors and I have to make a bundle everytime I change something. Is there anything I can do to get rid of Browserify and still be able to use require() in typescript. As this is my first pure frontend project I want to keep it simple and clean, not to use a lot of plugins/modules to make it work.

My tsconfig.json:

```<code>{
"files": [
    "ts/main.ts"
],
"compilerOptions": {
    "noImplicitAny": true,
    "target": "es5",
    "outDir": "js"
}
}
</code>```

Is there any way I can use types without the need to install more node modules to make it work?

答:
When you use require() or import, then you are using modules. When you use modules, you need a module bundler such as browserify or webpack.

But you don't HAVE to use modules in a typescript project. The typescript compiler automatically concatenates all your separate .ts files into one .js bundle already. You need to set the output file in tsconfig.json:

```<code>{
    "compilerOptions": {
        "sourceMap":  true,
        "removeComments": true,
        "target":"es5",
        "out": "dist/js/main.js"
    }
}
</code>```

A separate .ts file might look like this:

```<code>class Test {
   constructor(){
      console.log("hi!");
   }
}
</code>```

The difference with using modules is that your Test class will be placed in the global scope, but you could prevent that by using a namespace where you put all your classes:

```<code>namespace Game {
    export class Test {
       constructor(){
          console.log("hi!");
       }
    }
}
</code>```

Now there is only one object called 'Game' in the global scope and you don't need a module bundler to create that single .js file.

Body:
I'm working on a pure frontend project using VS Code. I have a folder for typescript and another one for sass. I'm compiling those with Gulp in separate folders for js and css.

I faced a problem when I tried to use var something = require('some-node-module'); and got an error both in typescript and browser console. I added @types for this but it didn't worked as I still got an error in browser console. I searched more and found this question, I understood what the problem is and I used Browserify from there. Now typescript is compiled without errors and I have to make a bundle everytime I change something. Is there anything I can do to get rid of Browserify and still be able to use require() in typescript. As this is my first pure frontend project I want to keep it simple and clean, not to use a lot of plugins/modules to make it work.

My tsconfig.json:

{
"files": [
    "ts/main.ts"
],
"compilerOptions": {
    "noImplicitAny": true,
    "target": "es5",
    "outDir": "js"
}
}

Is there any way I can use types without the need to install more node modules to make it work?

Body:
When you use require() or import, then you are using modules. When you use modules, you need a module bundler such as browserify or webpack.

But you don't HAVE to use modules in a typescript project. The typescript compiler automatically concatenates all your separate .ts files into one .js bundle already. You need to set the output file in tsconfig.json:

{
    "compilerOptions": {
        "sourceMap":  true,
        "removeComments": true,
        "target":"es5",
        "out": "dist/js/main.js"
    }
}

A separate .ts file might look like this:

class Test {
   constructor(){
      console.log("hi!");
   }
}

The difference with using modules is that your Test class will be placed in the global scope, but you could prevent that by using a namespace where you put all your classes:

namespace Game {
    export class Test {
       constructor(){
          console.log("hi!");
       }
    }
}

Now there is only one object called 'Game' in the global scope and you don't need a module bundler to create that single .js file.


问:
My tkinter command only runs once
I am using tkinter to code a little thing which displays new images each time a button is pressed, but it won't cycle more than once.</p>

```<code> from tkinter import *
 root=Tk()
 image1=PhotoImage(file="SCIMG_Gagagigo.png")
 image2=PhotoImage(file="SCIMG_7_Coloured_Fish.png")
 image3=PhotoImage(file="SCIMG_Jerry_Beans_Man.png")
 image4=PhotoImage(file="SCIMG_Axe_Raider.png")
 image5=PhotoImage(file="SCIMG_Guardian_of_the_Throne_Room.png")
 image6=PhotoImage(file="SCIMG_Alien_Shocktrooper.png")
 image7=PhotoImage(file="SCIMG_Evilswarm_Heliotrope.png")
 image8=PhotoImage(file="SCIMG_Alexandrite_Dragon.png")
 def change():
     for a in range(4):
         array.append(array[0])
         array.pop(0)
     b1=Button(image=array[0])
     b2=Button(image=array[1])
     b3=Button(image=array[2])
     b4=Button(image=array[3])
     b1.grid(row=0,column=0)
     b2.grid(row=0,column=1)
     b3.grid(row=1,column=0)
     b4.grid(row=1,column=1)
 array=[image8,image7,image6,image5,image4,image3,image2,image1]
 b1=Button(image=array[0],command=change)
 b2=Button(image=array[1],command=change)
 b3=Button(image=array[2],command=change)
 b4=Button(image=array[3],command=change)
 b1.grid(row=0,column=0)
 b2.grid(row=0,column=1)
 b3.grid(row=1,column=0)
 b4.grid(row=1,column=1)
 root.mainloop()
</code>```

答:
Bad Solution

That's because no command is set to your new Buttons.

```<code>def change():
    for a in range(4):
        array.append(array[0])
        array.pop(0)
    # Change start.
    b1=Button(image=array[0],command=change)
    b2=Button(image=array[1],command=change)
    b3=Button(image=array[2],command=change)
    b4=Button(image=array[3],command=change)
    # Change end.
    b1.grid(row=0,column=0)
    b2.grid(row=0,column=1)
    b3.grid(row=1,column=0)
    b4.grid(row=1,column=1)
</code>```

However, it is not a good fix.

Better Solution

Instead, configure the image:

```<code>def change():
    for a in range(4):
        array.append(array[0])
        array.pop(0)
    b1.configure(image=array[0])
    b2.configure(image=array[1])
    b3.configure(image=array[2])
    b4.configure(image=array[3])
</code>```

Extra: Better way to rotate your image array

Replace this

```<code>for a in range(4):
    array.append(array[0])
    array.pop(0)
</code>```

with

```<code>array = array[4:] + array[:4]
</code>```

Title: My tkinter command only runs once

Body:
I am using tkinter to code a little thing which displays new images each time a button is pressed, but it won't cycle more than once.

 from tkinter import *
 root=Tk()
 image1=PhotoImage(file="SCIMG_Gagagigo.png")
 image2=PhotoImage(file="SCIMG_7_Coloured_Fish.png")
 image3=PhotoImage(file="SCIMG_Jerry_Beans_Man.png")
 image4=PhotoImage(file="SCIMG_Axe_Raider.png")
 image5=PhotoImage(file="SCIMG_Guardian_of_the_Throne_Room.png")
 image6=PhotoImage(file="SCIMG_Alien_Shocktrooper.png")
 image7=PhotoImage(file="SCIMG_Evilswarm_Heliotrope.png")
 image8=PhotoImage(file="SCIMG_Alexandrite_Dragon.png")
 def change():
     for a in range(4):
         array.append(array[0])
         array.pop(0)
     b1=Button(image=array[0])
     b2=Button(image=array[1])
     b3=Button(image=array[2])
     b4=Button(image=array[3])
     b1.grid(row=0,column=0)
     b2.grid(row=0,column=1)
     b3.grid(row=1,column=0)
     b4.grid(row=1,column=1)
 array=[image8,image7,image6,image5,image4,image3,image2,image1]
 b1=Button(image=array[0],command=change)
 b2=Button(image=array[1],command=change)
 b3=Button(image=array[2],command=change)
 b4=Button(image=array[3],command=change)
 b1.grid(row=0,column=0)
 b2.grid(row=0,column=1)
 b3.grid(row=1,column=0)
 b4.grid(row=1,column=1)
 root.mainloop()

Body:
Bad Solution

That's because no command is set to your new Buttons.

def change():
    for a in range(4):
        array.append(array[0])
        array.pop(0)
    # Change start.
    b1=Button(image=array[0],command=change)
    b2=Button(image=array[1],command=change)
    b3=Button(image=array[2],command=change)
    b4=Button(image=array[3],command=change)
    # Change end.
    b1.grid(row=0,column=0)
    b2.grid(row=0,column=1)
    b3.grid(row=1,column=0)
    b4.grid(row=1,column=1)

However, it is not a good fix.

Better Solution

Instead, configure the image:

def change():
    for a in range(4):
        array.append(array[0])
        array.pop(0)
    b1.configure(image=array[0])
    b2.configure(image=array[1])
    b3.configure(image=array[2])
    b4.configure(image=array[3])

Extra: Better way to rotate your image array

Replace this

for a in range(4):
    array.append(array[0])
    array.pop(0)

with

array = array[4:] + array[:4]


问:
Cannot find symbol variable activity_main
I am new. Whenever i try to build and run this code this message appears.

Here is the XML code:

```<code>xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.android.justjava.MainActivity">

<TextView
    android:id="@+id/quantity_text_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="quantity"
    android:textAllCaps="true"
    android:textSize="16sp"
    android:textColor="@android:color/black"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="16dp"/>

<TextView
    android:id="@+id/zero_text_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="0"
    android:layout_below="@+id/quantity_text_view"
    android:textSize="16sp"
    android:textColor="@android:color/black"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="16dp"/>

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="order"
    android:textAllCaps="true"
    android:layout_below="@+id/zero_text_view"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="16dp"
    android:onClick="submitOrder"/>
</code>```

Here is the Java code:

/**  * IMPORTANT: Add your package below. Package name can be found in
  the project's AndroidManifest.xml file.  * This is the package name
  our example uses:  *  * package com.example.android.justjava;   *  */

import android.R; import android.os.Bundle; import
  android.support.v7.app.AppCompatActivity; import android.view.View;
  import android.widget.TextView;

import static com.example.android.justjava.R.id.quantity_text_view;

/**  * This app displays an order form to order coffee.  */ public
  class MainActivity extends AppCompatActivity {

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);
}

/**
 * This method is called when the order button is clicked.
 */
public void submitOrder(View view) {
    display(1);
}

/**
 * This method displays the given quantity value on the screen.
 */
private void display(int number) {
    TextView quantityTextView = (TextView) findViewById(R.id/quantity_text_view);
    quantityTextView.setText("" + number);
} }
</code>```

Here is the pic of the error:

https://i.stack.imgur.com/tlrUi.png

Please Help me

答:
Remove this line tools:context="com.example.android.justjava.MainActivity"
this line is for activity name but i think you copy paste XML of MainActivity.java
and that layout is not of MainActivity. you should remove this line it does not create any error.</p>

Body:
I am new. Whenever i try to build and run this code this message appears.

Here is the XML code:

xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.android.justjava.MainActivity">

<TextView
    android:id="@+id/quantity_text_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="quantity"
    android:textAllCaps="true"
    android:textSize="16sp"
    android:textColor="@android:color/black"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="16dp"/>

<TextView
    android:id="@+id/zero_text_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="0"
    android:layout_below="@+id/quantity_text_view"
    android:textSize="16sp"
    android:textColor="@android:color/black"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="16dp"/>

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="order"
    android:textAllCaps="true"
    android:layout_below="@+id/zero_text_view"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="16dp"
    android:onClick="submitOrder"/>

Here is the Java code:

/**  * IMPORTANT: Add your package below. Package name can be found in
  the project's AndroidManifest.xml file.  * This is the package name
  our example uses:  *  * package com.example.android.justjava;   *  */

import android.R; import android.os.Bundle; import
  android.support.v7.app.AppCompatActivity; import android.view.View;
  import android.widget.TextView;

import static com.example.android.justjava.R.id.quantity_text_view;

/**  * This app displays an order form to order coffee.  */ public
  class MainActivity extends AppCompatActivity {

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

/**
 * This method is called when the order button is clicked.
 */
public void submitOrder(View view) {
    display(1);
}

/**
 * This method displays the given quantity value on the screen.
 */
private void display(int number) {
    TextView quantityTextView = (TextView) findViewById(R.id/quantity_text_view);
    quantityTextView.setText("" + number);
} }

Here is the pic of the error:

https://i.stack.imgur.com/tlrUi.png

Please Help me


问:
3 part distributed right side advertisment issue
I'm looking for information.
Does someone ever heard about this kinda add?

I'm trying programming an add which opening itself when you click on it, but I'm stuck.

I found a solution if you wanna an opening style add like 2 distributed parts but not for 3 or more side, so if it's possible, so someone can help me find out how can I solve this problem?
This is the html file

I tried the 3rd "distribution" but that stucked under the 2nd so I deleted that part of the code.

.cards {
  width: 300px;
  height: 600px;
  margin: auto auto;
}

.card-toggle {
  display: none;
}

.card {
  display: block;
  width: 180px;
  height: 180px;
  position: relative;
  -webkit-perspective: 900;
  margin: auto auto;
  cursor: pointer;
}

.card:hover .face {
  -webkit-transition: all 0.3s ease-out;
  margin: auto auto;
}

.face {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  -webkit-backface-visibility: visible;
  -webkit-transition: all 0.5s ease-out;
  -webkit-transform-origin: 0 0;
}

.front {
  -webkit-transform: rotateY(0deg);
  z-index: auto;
  -webkit-backface-visibility: hidden;
}

.inner-left {
  -webkit-transform: rotateY(-10deg);
  z-index: 2;
}

.inner-left>img {
  -webkit-transform: rotateY(180deg);
}

.inner-right {
  -webkit-transform: rotateY(0deg);
  z-index: 1;
}

.card:hover .front,
.card:hover .inner-left {
  -webkit-transform: rotateY(-15deg);
}

.card-toggle:checked+.card .front,
.card-toggle:checked+.card .inner-left {
  -webkit-transform: rotateY(-180deg);
}

.card-toggle:checked+.card .inner-right {
  -webkit-transform: rotateY(0deg);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='cards'>
  <input type="checkbox" id="card-toggle" class="card-toggle" value="selected">
  <label class='card' for="card-toggle">
      <div class='front face'>
       Font view of the advertisement.
      </div>

      <div class="inner-left face">
       <img class="inner-left" width=300px height="600px" src='http://picanimal.com/wp-content/uploads/2017/07/cats-cat-play-hide-cute-pictures-hd-1366x768.jpg' />
      </div>

      <div class="inner-right face">
       <img class="inner-left" width=300px height="600px" src='http://picanimal.com/wp-content/uploads/2017/07/cats-cat-play-hide-cute-pictures-hd-1366x768.jpg' />
      </div>
     </label>
</div></code>```

答:
This version makes it open more like a book:

.cards {
  width: 300px;
  height: 600px;
  margin: auto auto;
}

.card-toggle {
  display: none;
}

.card {
  display: block;
  width: 180px;
  height: 180px;
  position: relative;
  perspective: 900;
  margin: auto auto;
  cursor: pointer;
}

.card:hover .face {
  transition: all 0.3s ease-out;
  margin: auto auto;
}

.face {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  -webkit-backface-visibility: visible;
  -webkit-transition: all 0.5s ease-out;
  -webkit-transform-origin: 0 0;
}

.front {
  /*-webkit-transform: rotateY(180deg);*/
  z-index: auto;
  -webkit-backface-visibility: hidden;
}

.inner-left {
  /*-webkit-transform: rotateY(-180deg);*/
  z-index: 2;
}

.inner-left>img {
  /*-webkit-transform: rotateY(180deg);*/
}

.inner-right {
  /*-webkit-transform: rotateY(180deg);*/
  z-index: 1;
}

.card:hover .front,
.card:hover .inner-left {
  transform: rotateY(180deg);
}

.card-toggle:checked+.card .front,
.card-toggle:checked+.card .inner-left {
  transform: rotateY(180deg);
}

.card-toggle:checked+.card .inner-right {
  transform: rotateY(-180deg);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='cards'>
  <input type="checkbox" id="card-toggle" class="card-toggle" value="selected">
  <label class='card' for="card-toggle">
      <div class='front face'>
       Front view of the advertisement.
      </div>

      <div class="inner-left face">
       <img class="inner-left" width=300px height="600px" src='http://picanimal.com/wp-content/uploads/2017/07/cats-cat-play-hide-cute-pictures-hd-1366x768.jpg' />
      </div>

      <div class="inner-right face">
       <img class="inner-left" width=300px height="600px" src='http://picanimal.com/wp-content/uploads/2017/07/cats-cat-play-hide-cute-pictures-hd-1366x768.jpg' />
      </div>
     </label>
</div></code>```

Body:
I'm looking for information.
Does someone ever heard about this kinda add?

I'm trying programming an add which opening itself when you click on it, but I'm stuck.

I found a solution if you wanna an opening style add like 2 distributed parts but not for 3 or more side, so if it's possible, so someone can help me find out how can I solve this problem?
This is the html file

I tried the 3rd "distribution" but that stucked under the 2nd so I deleted that part of the code.

.cards {
  width: 300px;
  height: 600px;
  margin: auto auto;
}

.card-toggle {
  display: none;
}

.card {
  display: block;
  width: 180px;
  height: 180px;
  position: relative;
  -webkit-perspective: 900;
  margin: auto auto;
  cursor: pointer;
}

.card:hover .face {
  -webkit-transition: all 0.3s ease-out;
  margin: auto auto;
}

.face {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  -webkit-backface-visibility: visible;
  -webkit-transition: all 0.5s ease-out;
  -webkit-transform-origin: 0 0;
}

.front {
  -webkit-transform: rotateY(0deg);
  z-index: auto;
  -webkit-backface-visibility: hidden;
}

.inner-left {
  -webkit-transform: rotateY(-10deg);
  z-index: 2;
}

.inner-left>img {
  -webkit-transform: rotateY(180deg);
}

.inner-right {
  -webkit-transform: rotateY(0deg);
  z-index: 1;
}

.card:hover .front,
.card:hover .inner-left {
  -webkit-transform: rotateY(-15deg);
}

.card-toggle:checked+.card .front,
.card-toggle:checked+.card .inner-left {
  -webkit-transform: rotateY(-180deg);
}

.card-toggle:checked+.card .inner-right {
  -webkit-transform: rotateY(0deg);
}

  <input type="checkbox" id="card-toggle" class="card-toggle" value="selected">

       Font view of the advertisement.

Body:
This version makes it open more like a book:

.cards {
  width: 300px;
  height: 600px;
  margin: auto auto;
}

.card-toggle {
  display: none;
}

.card {
  display: block;
  width: 180px;
  height: 180px;
  position: relative;
  perspective: 900;
  margin: auto auto;
  cursor: pointer;
}

.card:hover .face {
  transition: all 0.3s ease-out;
  margin: auto auto;
}

.face {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  -webkit-backface-visibility: visible;
  -webkit-transition: all 0.5s ease-out;
  -webkit-transform-origin: 0 0;
}

.front {
  /*-webkit-transform: rotateY(180deg);*/
  z-index: auto;
  -webkit-backface-visibility: hidden;
}

.inner-left {
  /*-webkit-transform: rotateY(-180deg);*/
  z-index: 2;
}

.inner-left>img {
  /*-webkit-transform: rotateY(180deg);*/
}

.inner-right {
  /*-webkit-transform: rotateY(180deg);*/
  z-index: 1;
}

.card:hover .front,
.card:hover .inner-left {
  transform: rotateY(180deg);
}

.card-toggle:checked+.card .front,
.card-toggle:checked+.card .inner-left {
  transform: rotateY(180deg);
}

.card-toggle:checked+.card .inner-right {
  transform: rotateY(-180deg);
}

<div class='cards'>
  <input type="checkbox" id="card-toggle" class="card-toggle" value="selected">
  <label class='card' for="card-toggle">
      <div class='front face'>
       Front view of the advertisement.
      </div>

      <div class="inner-left face">
       <img class="inner-left" width=300px height="600px" src='http://picanimal.com/wp-content/uploads/2017/07/cats-cat-play-hide-cute-pictures-hd-1366x768.jpg' />
      </div>

      <div class="inner-right face">
       <img class="inner-left" width=300px height="600px" src='http://picanimal.com/wp-content/uploads/2017/07/cats-cat-play-hide-cute-pictures-hd-1366x768.jpg' />
      </div>
     </label>
</div>


问:
Select a changed value from multiple dropdown
Based on the query , i am able to select a preselect a value ---
Preselect a value in a dropdown using knockout

Once the drop down value is getting changed i need to update the 'PrimarySiteUsers observable collection with the newly selected value.

Please let me know for any help.

答:
What you're looking for is a subscription. These will watch the specified observable and run whenever the observable is changed. They pass in the new value to whatever function you specifiy. Here is a short, albeit useless example.

function viewModel() {
  var self = this;

  self.DisplayPage = ko.observable("");

  self.PageDetails = ko.observable("");

  self.DisplayPage.subscribe(function(newValue) {
    if (newValue == "Home") {
      self.PageDetails("No Place like home");
    }
    if (newValue == "About") {
      self.PageDetails("What about it?");
    }
    if (newValue == "Contact") {
      self.PageDetails("Contact who?");
    }

  })

}

ko.applyBindings(new viewModel());```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<select data-bind="value: DisplayPage">
  <option value="Home">Home</option>
  <option value="About">About</option>
  <option value="Contact">Contact</option>
</select>

<div>

  <input data-bind="value: DisplayPage">

  <div data-bind="text: PageDetails"></div>

</div></code>```

Body:
What you're looking for is a subscription. These will watch the specified observable and run whenever the observable is changed. They pass in the new value to whatever function you specifiy. Here is a short, albeit useless example.

function viewModel() {
  var self = this;

  self.DisplayPage = ko.observable("");

  self.PageDetails = ko.observable("");

  self.DisplayPage.subscribe(function(newValue) {
    if (newValue == "Home") {
      self.PageDetails("No Place like home");
    }
    if (newValue == "About") {
      self.PageDetails("What about it?");
    }
    if (newValue == "Contact") {
      self.PageDetails("Contact who?");
    }

  })

}

ko.applyBindings(new viewModel());

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<select data-bind="value: DisplayPage">
  <option value="Home">Home</option>
  <option value="About">About</option>
  <option value="Contact">Contact</option>
</select>

<div>

  <input data-bind="value: DisplayPage">

  <div data-bind="text: PageDetails"></div>

</div>


问:
Error while trying to parse a website url using python . how to debug it?
```<code>#!/usr/bin/python
import json
import urllib
from BeautifulSoup import BeautifulSoup
from BeautifulSoup import BeautifulStoneSoup
import BeautifulSoup

def showsome(searchfor):
  query = urllib.urlencode({'q': searchfor})
  url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' % query
  search_response = urllib.urlopen(url)
  search_results = search_response.read()
  results = json.loads(search_results)
  data = results['responseData']
  print 'Total results: %s' % data['cursor']['estimatedResultCount']
  hits = data['results']
  print 'Top %d hits:' % len(hits)
  for h in hits:
    print ' ', h['url']
    resp = urllib.urlopen(h['url'])
        res = resp.read()

    soup = BeautifulSoup(res)
        print soup.prettify()
  print 'For more results, see %s' % data['cursor']['moreResultsUrl']

showsome('sachin')
</code>```

What is the wrong in this code ?

Note all the 4 links that I am getting out of the search , I am feeding it back to extract the contents out of it , and then use BeautifulSoup to parse it . How should I go about it ?

答: It appears you're trying to access the Google ajax API in Python.  You might consider using the Xgoogle library available on Github: https://github.com/pkrumins/xgoogle</p>

Body:
#!/usr/bin/python
import json
import urllib
from BeautifulSoup import BeautifulSoup
from BeautifulSoup import BeautifulStoneSoup
import BeautifulSoup

def showsome(searchfor):
  query = urllib.urlencode({'q': searchfor})
  url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' % query
  search_response = urllib.urlopen(url)
  search_results = search_response.read()
  results = json.loads(search_results)
  data = results['responseData']
  print 'Total results: %s' % data['cursor']['estimatedResultCount']
  hits = data['results']
  print 'Top %d hits:' % len(hits)
  for h in hits:
    print ' ', h['url']
    resp = urllib.urlopen(h['url'])
        res = resp.read()

    soup = BeautifulSoup(res)
        print soup.prettify()
  print 'For more results, see %s' % data['cursor']['moreResultsUrl']

showsome('sachin')

What is the wrong in this code ?

Note all the 4 links that I am getting out of the search , I am feeding it back to extract the contents out of it , and then use BeautifulSoup to parse it . How should I go about it ?


问:
small/tiny and overlap button, toolbox and etc in windbg on windows 10
I installed windbg on windows 10 (it worked fine on windows 7 for example)
The toolbar is too small, some text boxes are overlapped with other objects.

the text in some places was too small as well and I solved it by changing the font size of windbg, but it didn't solve the toolbox and the text-box issue

I think that maybe this problem is not related to windbg only, and it will reproduced in another applications

Any help would be appreciated.

you can see a screenshot here:

Thanks!

答:
Your version of WinDbg is ancient, I believe this is fixed in newer versions.

https://developer.microsoft.com/en-us/windows/hardware/download-windbg


问:
TableView Height Wrapping (Xamarin.Forms)
Am having little items in my Table View but am facing a challenge the TableView doesn't automatically wrap it's height according to the items in it, the TableView is long but having little items ,  how can i tackle this. Below is my XAML code :

```<code><TableView Intent="Form" x:Name="sales_tableView" RowHeight="-1">
            <TableView.Root >
                <TableSection Title="Agent Sales Details">

                    <TextCell Text="Agent Number" x:Name="agentNumber_txtcell" DetailColor="Purple"   />
                    <TextCell Text="Agent Rating "  x:Name="agentrating_txtcell" DetailColor="Purple"/>
                    <TextCell Text="Agent Phone "  x:Name="agentphone_txtcell" DetailColor="Purple" />
                    <TextCell Text="Agent Email " x:Name="agentemail_txtcell" DetailColor="Purple" />

                </TableSection>
            </TableView.Root>
        </TableView>
</code>```

EDIT:

This is the Screen shot :

答:
So you could simply add a static ViewCell to the bottom of your table that contains your button and hooks up as normal to the click method in the code behind, and then set the background to transparent.

```<code><TableView Intent="Form" x:Name="sales_tableView" RowHeight="-1">
            <TableView.Root >
                <TableSection Title="Agent Sales Details">

                    <TextCell Text="Agent Number" x:Name="agentNumber_txtcell" DetailColor="Purple"   />
                    <TextCell Text="Agent Rating "  x:Name="agentrating_txtcell" DetailColor="Purple"/>
                    <TextCell Text="Agent Phone "  x:Name="agentphone_txtcell" DetailColor="Purple" />
                    <TextCell Text="Agent Email " x:Name="agentemail_txtcell" DetailColor="Purple" />

                    <ViewCell>
                        <StackLayout Orientation="Horizontal">
                            <Button Text="MY CLIENTS" Clicked="MyClickMethod" />
                        </StackLayout>
                    </ViewCell>

                </TableSection>
            </TableView.Root>
    </TableView>
</code>```

I think you can just set the background colour in the XAML, i think you just add this property

```<code>BackgroundColor="Transparent"
</code>```

to the xaml of the tableview, but I can't quite remember if that's right, either way you can do the same thing in the code behind:

```<code>sales_tableView.BackgroundColor = Color.Transparent;
</code>```

Body:
Am having little items in my Table View but am facing a challenge the TableView doesn't automatically wrap it's height according to the items in it, the TableView is long but having little items ,  how can i tackle this. Below is my XAML code :

<TableView Intent="Form" x:Name="sales_tableView" RowHeight="-1">
            <TableView.Root >
                <TableSection Title="Agent Sales Details">

                    <TextCell Text="Agent Number" x:Name="agentNumber_txtcell" DetailColor="Purple"   />
                    <TextCell Text="Agent Rating "  x:Name="agentrating_txtcell" DetailColor="Purple"/>
                    <TextCell Text="Agent Phone "  x:Name="agentphone_txtcell" DetailColor="Purple" />
                    <TextCell Text="Agent Email " x:Name="agentemail_txtcell" DetailColor="Purple" />

                </TableSection>
            </TableView.Root>
        </TableView>

EDIT:

This is the Screen shot :

Body:
So you could simply add a static ViewCell to the bottom of your table that contains your button and hooks up as normal to the click method in the code behind, and then set the background to transparent.

<TableView Intent="Form" x:Name="sales_tableView" RowHeight="-1">
            <TableView.Root >
                <TableSection Title="Agent Sales Details">

                    <TextCell Text="Agent Number" x:Name="agentNumber_txtcell" DetailColor="Purple"   />
                    <TextCell Text="Agent Rating "  x:Name="agentrating_txtcell" DetailColor="Purple"/>
                    <TextCell Text="Agent Phone "  x:Name="agentphone_txtcell" DetailColor="Purple" />
                    <TextCell Text="Agent Email " x:Name="agentemail_txtcell" DetailColor="Purple" />

                    <ViewCell>
                        <StackLayout Orientation="Horizontal">
                            <Button Text="MY CLIENTS" Clicked="MyClickMethod" />
                        </StackLayout>
                    </ViewCell>

                </TableSection>
            </TableView.Root>
    </TableView>

I think you can just set the background colour in the XAML, i think you just add this property

BackgroundColor="Transparent"

to the xaml of the tableview, but I can't quite remember if that's right, either way you can do the same thing in the code behind:

sales_tableView.BackgroundColor = Color.Transparent;


问:
Qt sidebar comes up too wide
I use Qt designer (as opposed to building controls via the program) to lay out my sidebar and floating dialogs.  When first launching the application, the sidebar is WAY too wide and bears no resemblance to how I saved it.  The user can shrink it to a reasonable width, and that is 'remembered' after closing and re-opening the application.  But it doesn't create a good first impression of our application, and not all our users are savvy enough to realize that the sidebar width can be changed.

The sidebar is quite complex, with multiple forms (QStackedWidget) and each with multiple controls.  Any suggestions for forcing it to come up at the minimum width with the first use?  Thanks!

答:
You should be able to achieve the wanted behavior by setting "Horizontal Stretch" property in Qt Designer, for each of the widgets in your splitter or layout, whichever you are using to layout your components. See QSizePolicy documentation for more info.

The "Horizontal Stretch" & "Vertical Stretch" properties are located in Qt Designers Property Editor, under the sizePolicy.See the image for exact location of properties

Title: Qt sidebar comes up too wide


问:
Limit Amazon AWS Access of Specific EC2/RDS Instances
I have an Amazon EC2 instance and a corresponding RDS instance that I want to keep private. I'd like to keep it so that only myself and the sysadmin can access these instances. I don't want to provide access to other developers.

However, one of my developers is working on a project right now where he needs to create/configure his own EC2/RDS instance. I could have my sysadmin perform this work, but I'd rather have the developer do it for the sake of expediency.

Is there any way to configure a group/role/policy in a way that allows me to keep my current instances private from the new developer, but would allow him to create his own EC2 and RDS instances?

答:
Ok, the best explanation about how things works is in @John Rotestein response. But here a few practical suggestions (that must be considered as an complement to John's response):

You can create separate subnets and give permissions to your
developers to run instances in only one of the the subnets using IAM
Policies; But your developers still can reach your instance and you
must configure so/db/application restrictions.

If your company DO NOT use a shared gateway to the internet, you can
define the Network ACL to limit the access to your exclusive network
using your IP address. If you use a shared gateway, you will not be
able to use this solution;

In the second case, one way to limit the access is put your instance
in a private subnet and create a bastion host in your public subnet
to be used only by you (this solution must be configured to your RDS
instances too). The bastion host will be reachable by your
developers, but you can use a specific Key Pair that only you have
access. Just keep in mind that your instances and RDS will not be
available to the internet;

But I think that the simple solution would be create different
VPC's, one for your team and the other for the development team. In
this solution you can restrict access to all VPC resources to your
developers in the "main" VPC. Off course this also means no internet connection to your instances.