问:
Vehicle drop down selector
Chasing some help on this one, unfortunately Javascript is not my forte; I am creating a simple drop down vehicle make, model and year selector which leads through to a link which is created dynamically depending on the users options selected.

Effectively the user should be able to select a make and then have a model show up which is associated with that make and finally a year that is associated with the model selected. I have been able to get the make and model selection to work but when I attempt the same thing by adding in the year it starts showing the year in place of the model.

Can someone please assist with this? My code is below along with a link to the fiddle.

http://jsfiddle.net/Yash91/qtd7patd/

function showURL() {
    var d1 = $("#make").find(":selected").attr("class");
    var d2 = $("#model").find(":selected").attr("class");
    var d3 = $("#year").find(":selected").attr("class");
    var url = ("http://www.web.com.au/" + d1 + "/" + d2 + "/" + d3);
    window.location = url;
    return true;
}

$(document).ready(function() {
var $make = $( '#make' ),
  $model = $( '#model' ),
    $options = $model.find( 'option' );

$make.on( 'change', function() {
 $model.html( $options.filter( '[value="' + this.value + '"]' ) );
} ).trigger( 'change' );

var $model = $( '#model' ),
  $year = $( '#year' ),
    $options = $year.find( 'option' );

$model.on( 'change', function() {
 $year.html( $options.filter( '[value="' + this.value + '"]' ) );
} ).trigger( 'change' );

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Vehicle Brand Selector List -->
<select name="make" id="make">
 <option class="vehicle-search" value="0">Make</option>
 <option class="vehicle-search" value="1">BMW</option>
 <option class="vehicle-search" value="2">Daewoo</option>
 <option class="vehicle-search" value="3">Ford</option>
 <option class="vehicle-search" value="4">Holden</option>
 <option class="vehicle-search" value="5">Honda</option>
 <option class="vehicle-search" value="6">Hyundai</option>
 <option class="vehicle-search" value="7">Isuzu</option>
 <option class="vehicle-search" value="8">Kia</option>
 <option class="vehicle-search" value="9">Lexus</option>
 <option class="vehicle-search" value="10">Mazda</option>
 <option class="vehicle-search" value="11">Mitsubishi</option>
 <option class="vehicle-search" value="12">Nissan</option>
 <option class="vehicle-search" value="13">Peugeot</option>
 <option class="vehicle-search" value="14">Subaru</option>
 <option class="vehicle-search" value="15">Suzuki</option>
 <option class="vehicle-search" value="16">Toyota</option>
 <option class="vehicle-search" value="17">Volkswagen</option>
</select>
<!-- Vehicle Model List -->
<select name="model" id="model">
 <option value="0">Model</option>
 <option class="318i" value="1">318i</option>
 <option class="lanos" value="2">Lanos</option>
 <option class="courier" value="3">Courier</option>
 <option class="falcon" value="3">Falcon</option>
 <option class="festiva" value="3">Festiva</option>
 <option class="fiesta" value="3">Fiesta</option>
 <option class="focus" value="3">Focus</option>
 <option class="laser" value="3">Laser</option>
 <option class="ranger" value="3">Ranger</option>
 <option class="territory" value="3">Territory</option>
 <option class="astra" value="4">Astra</option>
 <option class="barina" value="4">Barina</option>
 <option class="captiva" value="4">Captiva</option>
 <option class="colorado" value="4">Colorado</option>
 <option class="commodore" value="4">Commodore</option>
 <option class="cruze" value="4">Cruze</option>
 <option class="rodeo" value="4">Rodeo</option>
 <option class="viva" value="4">Viva</option>
</select>
<!-- Vehicle Year List -->
<select name="year" id="year">
 <option value="0">Year</option>
 <option class="1998-2005" value="1">1998-2005</option>
 <option class="1997-2005" value="2">1997-2005</option>
 <option class="1997-2005" value="3">1997-2005</option>
 <option class="1997-2005" value="3">1997-2005</option>
 <option class="1997-2005" value="3">1997-2005</option>
 <option class="1997-2005" value="3">1997-2005</option>
 <option class="1997-2005" value="3">1997-2005</option>
 <option class="1997-2005" value="3">1997-2005</option>
 <option class="1997-2005" value="3">1997-2005</option>
 <option class="1997-2005" value="3">1997-2005</option>
 <option class="1997-2005" value="4">1997-2005</option>
 <option class="1997-2005" value="4">1997-2005</option>
 <option class="1997-2005" value="4">1997-2005</option>
 <option class="1997-2005" value="4">1997-2005</option>
 <option class="1997-2005" value="4">1997-2005</option>
 <option class="1997-2005" value="4">1997-2005</option>
 <option class="1997-2005" value="4">1997-2005</option>
 <option class="1997-2005" value="4">1997-2005</option>
</select>
<input type="submit" name="button" id="button" onclick="showURL();" /></code>```

答:
This is because you are using the same $options for year too.

Change your code like below.

function showURL() {
    var d1 = $("#identifier").find(":selected").attr("class");
    var url = ("/store/vehicle-selected/" + d1);
    window.location = url;
    return true;
}

$(document).ready(function() {
var $make = $( '#make' ),
  $model = $( '#model' ),
    $options = $model.find( 'option' );

$make.on( 'change', function() {
 $model.html( $options.filter( '[value="' + this.value + '"]') );
  $model.trigger( 'change' );
} ).trigger( 'change' );

var $model = $( '#model' ),
  $year = $( '#year' ),
    $yearOptions = $year.find( 'option' );

$model.on( 'change', function() {
 $year.html( $yearOptions.filter( '[value="' + this.value + '"]' ) );
  $year.trigger( 'change' );
} ).trigger( 'change' );

var $year = $( '#year' ),
  $identifier = $( '#identifier' ),
    $identifierOptions = $identifier.find( 'option' );

$year.on( 'change', function() {
  var filteredIdetifiers = $identifierOptions.filter( '[value="' + this.value + '"]' );
    debugger
  if(!($("#make").val() == 3 && $("#model option:selected").text()  == 'Falcon')) {
       filteredIdetifiers = filteredIdetifiers.filter(function(i,e){ return e.value !== '3'    });
    }
    $identifier.html(filteredIdetifiers);
  $identifier.trigger( 'change' );
} ).trigger( 'change' );

});
 ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Vehicle Brand Selector List -->
<select name="make" id="make">
 <option value="0">Make</option>
 <option value="1">BMW</option>
 <option value="2">Daewoo</option>
 <option value="3">Ford</option>
 <option value="4">Holden</option>
 <option value="5">Honda</option>
 <option value="6">Hyundai</option>
 <option value="7">Isuzu</option>
 <option value="8">Kia</option>
 <option value="9">Lexus</option>
 <option value="10">Mazda</option>
 <option value="11">Mitsubishi</option>
 <option value="12">Nissan</option>
 <option value="13">Peugeot</option>
 <option value="14">Subaru</option>
 <option value="15">Suzuki</option>
 <option value="16">Toyota</option>
 <option value="17">Volkswagen</option>
</select>
<!-- Vehicle Model List -->
<select name="model" id="model">
 <option value="0">Model</option>
 <option class="318i" value="1">318i</option>
 <option class="lanos" value="2">Lanos</option>
 <option class="courier" value="3">Courier</option>
 <option class="falcon" value="3">Falcon</option>
 <option class="festiva" value="3">Festiva</option>
 <option class="fiesta" value="3">Fiesta</option>
 <option class="focus" value="3">Focus</option>
 <option class="laser" value="3">Laser</option>
 <option class="ranger" value="3">Ranger</option>
 <option class="territory" value="3">Territory</option>
 <option class="astra" value="4">Astra</option>
 <option class="barina" value="4">Barina</option>
 <option class="captiva" value="4">Captiva</option>
 <option class="colorado" value="4">Colorado</option>
 <option class="commodore" value="4">Commodore</option>
 <option class="cruze" value="4">Cruze</option>
 <option class="rodeo" value="4">Rodeo</option>
 <option class="viva" value="4">Viva</option>
</select>
<!-- Vehicle Year List -->
<select name="year" id="year">
 <option value="0">Year</option>
 <option value="1">1998</option>
 <option value="1">1999</option>
 <option value="1">2000</option>
 <option value="1">2001</option>
 <option value="1">2002</option>
 <option value="1">2003</option>
 <option value="1">2004</option>
 <option value="1">2005</option>
 <option value="2">1997</option>
 <option value="2">1998</option>
 <option value="2">1999</option>
 <option value="2">2000</option>
 <option value="2">2001</option>
 <option value="2">2002</option>
 <option value="2">2003</option>
 <option value="3">1991-1999</option>
 <option value="4">1997-2007</option>
 <option value="5">1997-2007</option>
 <option value="3">2002</option>
 <option value="3">2003</option>
 <option value="3">2004</option>
 <option value="3">2005</option>
 <option value="4">1997-2005</option>
 <option value="4">1997-2005</option>
 <option value="4">1997-2005</option>
 <option value="4">1997-2005</option>
 <option value="4">1997-2005</option>
 <option value="4">1997-2005</option>
 <option value="4">1997-2005</option>
 <option value="4">1997-2005</option>
</select>
<!-- Vehicle Identity List -->
<select name="identifier" id="identifier">
 <option value="0">Type</option>
 <option class="E46" value="1">E46</option>
 <option class="1997-2003" value="2">N/A</option>
 <option class="1997-2007" value="4">N/A</option>
 <option class="1997-2007" value="5">N/A</option>
 <option class="5041618" value="3">BA</option>
 <option class="1997-2005" value="3">AU</option>
 <option class="1997-2005" value="3">AU2</option>
 <option class="1997-2005" value="4">N/A</option>
 <option class="1997-2005" value="4">1997-2005</option>
 <option class="1997-2005" value="4">1997-2005</option>
 <option class="1997-2005" value="4">1997-2005</option>
 <option class="1997-2005" value="4">1997-2005</option>
 <option class="1997-2005" value="4">1997-2005</option>
</select>
<input type="submit" name="button" id="button" onclick="showURL();" /></code>```

Title: Vehicle drop down selector

Body:
Chasing some help on this one, unfortunately Javascript is not my forte; I am creating a simple drop down vehicle make, model and year selector which leads through to a link which is created dynamically depending on the users options selected.

Effectively the user should be able to select a make and then have a model show up which is associated with that make and finally a year that is associated with the model selected. I have been able to get the make and model selection to work but when I attempt the same thing by adding in the year it starts showing the year in place of the model.

Can someone please assist with this? My code is below along with a link to the fiddle.

http://jsfiddle.net/Yash91/qtd7patd/

function showURL() {
    var d1 = $("#make").find(":selected").attr("class");
    var d2 = $("#model").find(":selected").attr("class");
    var d3 = $("#year").find(":selected").attr("class");
    var url = ("http://www.web.com.au/" + d1 + "/" + d2 + "/" + d3);
    window.location = url;
    return true;
}

$(document).ready(function() {
var $make = $( '#make' ),
  $model = $( '#model' ),
    $options = $model.find( 'option' );

$make.on( 'change', function() {
 $model.html( $options.filter( '[value="' + this.value + '"]' ) );
} ).trigger( 'change' );

var $model = $( '#model' ),
  $year = $( '#year' ),
    $options = $year.find( 'option' );

$model.on( 'change', function() {
 $year.html( $options.filter( '[value="' + this.value + '"]' ) );
} ).trigger( 'change' );

});

<select name="make" id="make">
 <option class="vehicle-search" value="0">Make</option>
 <option class="vehicle-search" value="1">BMW</option>
 <option class="vehicle-search" value="2">Daewoo</option>
 <option class="vehicle-search" value="3">Ford</option>
 <option class="vehicle-search" value="4">Holden</option>
 <option class="vehicle-search" value="5">Honda</option>
 <option class="vehicle-search" value="6">Hyundai</option>
 <option class="vehicle-search" value="7">Isuzu</option>
 <option class="vehicle-search" value="8">Kia</option>
 <option class="vehicle-search" value="9">Lexus</option>
 <option class="vehicle-search" value="10">Mazda</option>
 <option class="vehicle-search" value="11">Mitsubishi</option>
 <option class="vehicle-search" value="12">Nissan</option>
 <option class="vehicle-search" value="13">Peugeot</option>
 <option class="vehicle-search" value="14">Subaru</option>
 <option class="vehicle-search" value="15">Suzuki</option>
 <option class="vehicle-search" value="16">Toyota</option>
 <option class="vehicle-search" value="17">Volkswagen</option>
</select>

<select name="model" id="model">
 <option value="0">Model</option>
 <option class="318i" value="1">318i</option>
 <option class="lanos" value="2">Lanos</option>
 <option class="courier" value="3">Courier</option>
 <option class="falcon" value="3">Falcon</option>
 <option class="festiva" value="3">Festiva</option>
 <option class="fiesta" value="3">Fiesta</option>
 <option class="focus" value="3">Focus</option>
 <option class="laser" value="3">Laser</option>
 <option class="ranger" value="3">Ranger</option>
 <option class="territory" value="3">Territory</option>
 <option class="astra" value="4">Astra</option>
 <option class="barina" value="4">Barina</option>
 <option class="captiva" value="4">Captiva</option>
 <option class="colorado" value="4">Colorado</option>
 <option class="commodore" value="4">Commodore</option>
 <option class="cruze" value="4">Cruze</option>
 <option class="rodeo" value="4">Rodeo</option>
 <option class="viva" value="4">Viva</option>
</select>

<select name="year" id="year">
 <option value="0">Year</option>
 <option class="1998-2005" value="1">1998-2005</option>
 <option class="1997-2005" value="2">1997-2005</option>
 <option class="1997-2005" value="3">1997-2005</option>
 <option class="1997-2005" value="3">1997-2005</option>
 <option class="1997-2005" value="3">1997-2005</option>
 <option class="1997-2005" value="3">1997-2005</option>
 <option class="1997-2005" value="3">1997-2005</option>
 <option class="1997-2005" value="3">1997-2005</option>
 <option class="1997-2005" value="3">1997-2005</option>
 <option class="1997-2005" value="3">1997-2005</option>
 <option class="1997-2005" value="4">1997-2005</option>
 <option class="1997-2005" value="4">1997-2005</option>
 <option class="1997-2005" value="4">1997-2005</option>
 <option class="1997-2005" value="4">1997-2005</option>
 <option class="1997-2005" value="4">1997-2005</option>
 <option class="1997-2005" value="4">1997-2005</option>
 <option class="1997-2005" value="4">1997-2005</option>
 <option class="1997-2005" value="4">1997-2005</option>
</select>
<input type="submit" name="button" id="button" onclick="showURL();" />

Body:
This is because you are using the same $options for year too.

Change your code like below.

function showURL() {
    var d1 = $("#identifier").find(":selected").attr("class");
    var url = ("/store/vehicle-selected/" + d1);
    window.location = url;
    return true;
}

$(document).ready(function() {
var $make = $( '#make' ),
  $model = $( '#model' ),
    $options = $model.find( 'option' );

$make.on( 'change', function() {
 $model.html( $options.filter( '[value="' + this.value + '"]') );
  $model.trigger( 'change' );
} ).trigger( 'change' );

var $model = $( '#model' ),
  $year = $( '#year' ),
    $yearOptions = $year.find( 'option' );

$model.on( 'change', function() {
 $year.html( $yearOptions.filter( '[value="' + this.value + '"]' ) );
  $year.trigger( 'change' );
} ).trigger( 'change' );

var $year = $( '#year' ),
  $identifier = $( '#identifier' ),
    $identifierOptions = $identifier.find( 'option' );

$year.on( 'change', function() {
  var filteredIdetifiers = $identifierOptions.filter( '[value="' + this.value + '"]' );
    debugger
  if(!($("#make").val() == 3 && $("#model option:selected").text()  == 'Falcon')) {
       filteredIdetifiers = filteredIdetifiers.filter(function(i,e){ return e.value !== '3'    });
    }
    $identifier.html(filteredIdetifiers);
  $identifier.trigger( 'change' );
} ).trigger( 'change' );

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Vehicle Brand Selector List -->
<select name="make" id="make">
 <option value="0">Make</option>
 <option value="1">BMW</option>
 <option value="2">Daewoo</option>
 <option value="3">Ford</option>
 <option value="4">Holden</option>
 <option value="5">Honda</option>
 <option value="6">Hyundai</option>
 <option value="7">Isuzu</option>
 <option value="8">Kia</option>
 <option value="9">Lexus</option>
 <option value="10">Mazda</option>
 <option value="11">Mitsubishi</option>
 <option value="12">Nissan</option>
 <option value="13">Peugeot</option>
 <option value="14">Subaru</option>
 <option value="15">Suzuki</option>
 <option value="16">Toyota</option>
 <option value="17">Volkswagen</option>
</select>
<!-- Vehicle Model List -->
<select name="model" id="model">
 <option value="0">Model</option>
 <option class="318i" value="1">318i</option>
 <option class="lanos" value="2">Lanos</option>
 <option class="courier" value="3">Courier</option>
 <option class="falcon" value="3">Falcon</option>
 <option class="festiva" value="3">Festiva</option>
 <option class="fiesta" value="3">Fiesta</option>
 <option class="focus" value="3">Focus</option>
 <option class="laser" value="3">Laser</option>
 <option class="ranger" value="3">Ranger</option>
 <option class="territory" value="3">Territory</option>
 <option class="astra" value="4">Astra</option>
 <option class="barina" value="4">Barina</option>
 <option class="captiva" value="4">Captiva</option>
 <option class="colorado" value="4">Colorado</option>
 <option class="commodore" value="4">Commodore</option>
 <option class="cruze" value="4">Cruze</option>
 <option class="rodeo" value="4">Rodeo</option>
 <option class="viva" value="4">Viva</option>
</select>
<!-- Vehicle Year List -->
<select name="year" id="year">
 <option value="0">Year</option>
 <option value="1">1998</option>
 <option value="1">1999</option>
 <option value="1">2000</option>
 <option value="1">2001</option>
 <option value="1">2002</option>
 <option value="1">2003</option>
 <option value="1">2004</option>
 <option value="1">2005</option>
 <option value="2">1997</option>
 <option value="2">1998</option>
 <option value="2">1999</option>
 <option value="2">2000</option>
 <option value="2">2001</option>
 <option value="2">2002</option>
 <option value="2">2003</option>
 <option value="3">1991-1999</option>
 <option value="4">1997-2007</option>
 <option value="5">1997-2007</option>
 <option value="3">2002</option>
 <option value="3">2003</option>
 <option value="3">2004</option>
 <option value="3">2005</option>
 <option value="4">1997-2005</option>
 <option value="4">1997-2005</option>
 <option value="4">1997-2005</option>
 <option value="4">1997-2005</option>
 <option value="4">1997-2005</option>
 <option value="4">1997-2005</option>
 <option value="4">1997-2005</option>
 <option value="4">1997-2005</option>
</select>
<!-- Vehicle Identity List -->
<select name="identifier" id="identifier">
 <option value="0">Type</option>
 <option class="E46" value="1">E46</option>
 <option class="1997-2003" value="2">N/A</option>
 <option class="1997-2007" value="4">N/A</option>
 <option class="1997-2007" value="5">N/A</option>
 <option class="5041618" value="3">BA</option>
 <option class="1997-2005" value="3">AU</option>
 <option class="1997-2005" value="3">AU2</option>
 <option class="1997-2005" value="4">N/A</option>
 <option class="1997-2005" value="4">1997-2005</option>
 <option class="1997-2005" value="4">1997-2005</option>
 <option class="1997-2005" value="4">1997-2005</option>
 <option class="1997-2005" value="4">1997-2005</option>
 <option class="1997-2005" value="4">1997-2005</option>
</select>
<input type="submit" name="button" id="button" onclick="showURL();" />


来源: stackexchange

问:
Return String from a webmethod instead of a dataset.
How would I refactor this to get it to return a string not a dataset?      </p>

```<code>[WebMethod]
public DataSet GetPONumber(string Database)
{
    SqlConnection sqlConn = new SqlConnection();

    sqlConn.ConnectionString = GetConnString(Database);

    // build query
    string strSQL = @" A SELECT QUERY!!!!! ";

    SqlDataAdapter da = new SqlDataAdapter(strSQL, sqlConn);
    DataSet ds = new DataSet();
    da.Fill(ds, "NEWPO");

    return (ds);
}
</code>```

答:
This is what I finnished with and is working, thank you for your input:</p>

```<code>[WebMethod]
    public String GetPONumber(string Database)
    {
        //Create Object ready for Value
        object po = "";

        //Set Connection
        SqlConnection Connection = new SqlConnection(GetConnString(Database));

        //Open Connection
        Connection.Open();

        //Set Query to string
        string Query = @" SQL QUERY GOES HERE!!!! ";

        //Run Query
        SqlCommand Command = new SqlCommand(Query, Connection);

        //Set Value from Query
        try
        {
            po = Command.ExecuteScalar();
        }
        catch
        {
            //Error
        }

        //Clean up sql
        Command.Dispose();
        Command = null;

        //Clean up connection
        Connection.Close();
        Connection.Dispose();
        Connection = null;

        //Return Value
        return po.ToString();
    }
</code>```

OwnerDisplayName: MartGriff

ContentLicense: CC BY-SA 3.0

Body:
How would I refactor this to get it to return a string not a dataset?

[WebMethod]
public DataSet GetPONumber(string Database)
{
    SqlConnection sqlConn = new SqlConnection();

    sqlConn.ConnectionString = GetConnString(Database);

    // build query
    string strSQL = @" A SELECT QUERY!!!!! ";

    SqlDataAdapter da = new SqlDataAdapter(strSQL, sqlConn);
    DataSet ds = new DataSet();
    da.Fill(ds, "NEWPO");

    return (ds);
}

Body:
This is what I finnished with and is working, thank you for your input:

[WebMethod]
    public String GetPONumber(string Database)
    {
        //Create Object ready for Value
        object po = "";

        //Set Connection
        SqlConnection Connection = new SqlConnection(GetConnString(Database));

        //Open Connection
        Connection.Open();

        //Set Query to string
        string Query = @" SQL QUERY GOES HERE!!!! ";

        //Run Query
        SqlCommand Command = new SqlCommand(Query, Connection);

        //Set Value from Query
        try
        {
            po = Command.ExecuteScalar();
        }
        catch
        {
            //Error
        }

        //Clean up sql
        Command.Dispose();
        Command = null;

        //Clean up connection
        Connection.Close();
        Connection.Dispose();
        Connection = null;

        //Return Value
        return po.ToString();
    }

ContentLicense: CC BY-SA 2.5


问:
Detecting the device moving direction using ACCELEROMETER in Android
Using the SensorManager I can find the x,y,z from the ACCELEROMETER.
I can detect that the device moves, but how I can I check if it moves DOWN direction and not up?

thanks.

答:
The value will be negative.

Edit:  The value of y will be negative if its moving down.  Positive if its moving up (I accept it may actually be the other way round and negative for up positive for down I've not played with the android accelerometer yet so I'm going on other accelerometers i have used).


问:
Android RecyclerView : Setting a view at the bottom of each row of recyclerView.
I have a view that works as a footer of each row of recyclerView. What I am trying to achieve is something like this.

The image represents a row of my recyclerView.and each box a different view.

For most of the part it is obvious but I am having issues placing the the view that is represented by the yellow box at the bottom of the row.

I have tried a few different ways for example:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <View
        android:id="@+id/colored_penal"
        android:layout_width="4dp"
        android:layout_height="fill_parent"/>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center"
        android:orientation="vertical">

        <TextView
            android:id="@+id/distance"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="128"
            android:textSize="24sp"/>

        <TextView
            android:id="@+id/unit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="mtr" />

    </LinearLayout>

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/hospital_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hey, this is a dummy hospital"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/hospital_address"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/hospital_name"
            android:text="At the end of the road" />

        <!--This is the yellow box view that I want at the bottom-->
        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_marginTop="8dp"
            android:layout_alignParentBottom="true">

            <TextView
                android:id="@+id/waiting_time"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Waiting time: 40 mins"
                android:textSize="8sp"
                android:layout_weight="1"/>

            <TextView
                android:id="@+id/travel_time"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Travel time: 20 mins"
                android:textSize="8sp"
                android:layout_weight="1"/>

        </LinearLayout>

    </RelativeLayout>

</LinearLayout>

</RelativeLayout>
</code>```

I have used alignParentBottom as true yet the view is not getting placed at the bottom of the row. It makes sense that Android squeezes each row to make sure it looks like a recyclerView but than how to put something at the bottom?

I also tried setting up layout_height="fill_parent"  and gravity="bottom" for the LinearLayout (yellow view) despite knowing fill_parent is deprecated but it didn't work anyways.

Would appreciate any input helping me achieve this.

答:
This might do what you are looking for

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/distance"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="128"
            android:textSize="24sp" />

        <TextView
            android:id="@+id/unit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="mtr" />

    </LinearLayout>

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center">

        <TextView
            android:id="@+id/hospital_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hey, this is a dummy hospital"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/hospital_address"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/hospital_name"
            android:text="At the end of the road" />

        <!--This is the yellow box view that I want at the bottom-->
        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_alignParentStart="true"
            android:layout_below="@+id/hospital_address">

            <TextView
                android:id="@+id/waiting_time"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="Waiting time: 40 mins"
                android:textSize="8sp" />

            <TextView
                android:id="@+id/travel_time"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="Travel time: 20 mins"
                android:textSize="8sp" />

        </LinearLayout>

        <View
            android:id="@+id/colored_penal"
            android:layout_width="match_parent"
            android:layout_height="4dp"
            android:layout_below="@+id/hospital_address"
            android:layout_marginTop="10dp" />

    </RelativeLayout>

</LinearLayout>
</code>```

Body:
I have a view that works as a footer of each row of recyclerView. What I am trying to achieve is something like this.

The image represents a row of my recyclerView.and each box a different view.

For most of the part it is obvious but I am having issues placing the the view that is represented by the yellow box at the bottom of the row.

I have tried a few different ways for example:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <View
        android:id="@+id/colored_penal"
        android:layout_width="4dp"
        android:layout_height="fill_parent"/>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center"
        android:orientation="vertical">

        <TextView
            android:id="@+id/distance"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="128"
            android:textSize="24sp"/>

        <TextView
            android:id="@+id/unit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="mtr" />

    </LinearLayout>

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/hospital_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hey, this is a dummy hospital"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/hospital_address"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/hospital_name"
            android:text="At the end of the road" />

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_marginTop="8dp"
            android:layout_alignParentBottom="true">

            <TextView
                android:id="@+id/waiting_time"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Waiting time: 40 mins"
                android:textSize="8sp"
                android:layout_weight="1"/>

            <TextView
                android:id="@+id/travel_time"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Travel time: 20 mins"
                android:textSize="8sp"
                android:layout_weight="1"/>

        </LinearLayout>

    </RelativeLayout>

</LinearLayout>

</RelativeLayout>

I have used alignParentBottom as true yet the view is not getting placed at the bottom of the row. It makes sense that Android squeezes each row to make sure it looks like a recyclerView but than how to put something at the bottom?

I also tried setting up layout_height="fill_parent"  and gravity="bottom" for the LinearLayout (yellow view) despite knowing fill_parent is deprecated but it didn't work anyways.

Would appreciate any input helping me achieve this.

Body:
This might do what you are looking for

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/distance"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="128"
            android:textSize="24sp" />

        <TextView
            android:id="@+id/unit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="mtr" />

    </LinearLayout>

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center">

        <TextView
            android:id="@+id/hospital_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hey, this is a dummy hospital"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/hospital_address"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/hospital_name"
            android:text="At the end of the road" />

        <!--This is the yellow box view that I want at the bottom-->
        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_alignParentStart="true"
            android:layout_below="@+id/hospital_address">

            <TextView
                android:id="@+id/waiting_time"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="Waiting time: 40 mins"
                android:textSize="8sp" />

            <TextView
                android:id="@+id/travel_time"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="Travel time: 20 mins"
                android:textSize="8sp" />

        </LinearLayout>

        <View
            android:id="@+id/colored_penal"
            android:layout_width="match_parent"
            android:layout_height="4dp"
            android:layout_below="@+id/hospital_address"
            android:layout_marginTop="10dp" />

    </RelativeLayout>

</LinearLayout>


问:
RecyclerAdapter not shown because of the keyboard
I am changing the dataset of the recyclerview adapter with different search query results. I am able to populate the data as well but the populated data only shows if the keyboard is closed.

This query("a") is valid but the result is shown only after I close the keyboard

答:
Why not remove the keyboard as soon as the data is populated.</p>

```<code>try {
    InputMethodManager imm = (InputMethodManager)
    getSystemService(INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
} catch (Exception e) {
}
</code>```

Body:
Why not remove the keyboard as soon as the data is populated.

try {
    InputMethodManager imm = (InputMethodManager)
    getSystemService(INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
} catch (Exception e) {
}


问:
Hide a button in onload using angularjs
I have one form with three buttons edit update and cancel.Onload of the page I need to hide the update button.

When I click edit button edit should be hide and update should be displayed.
when I click on update I need to redirect some other page.

Hoe to do this?

```<code>                <form id="show_details">

                        <label>Project Name</label>
                        <label><input type="text"></label>

                        <label>Client </label>
                        <label><input type="text"></label>

                        <label>Project Co-ordinator</label>
                        <label><input type="text" disabled="true" ></label>

                        <label>Client Co-ordinator</label>
                        <label><input type="text"></label>

                        <label>Resource</label>
                        <label><input type="text" disabled="true"></label>
                    </div>
                </form>
                <div class="row">
                    <span class="pull-right btnMarginTop">
                        <button class="btn btn-primary" id="projectDetailsEdit"  ng-click="goEvent()">Edit</button>
                        <button class="btn btn-primary" id="projectDetailsUpdate" ng-hide="editMode=true" ng-click="goEvent()">Update</button>
                        <button class="btn btn-default" onclick="window.location.href = '/Project/ProjectList'">Cancel</button>
                    </span>
                </div>

<script>
    var app = angular
                    .module("intranet_App", [])
                    .controller(function ($scope, $http) {
                       $scope.editMode = false;
                       $scope.goEvent = function(){
                       $scope.editMode = !$scope.editMode;
                       if($scope.editMode){
                          $scope.editMode = false;
                       }else{
                           $scope.editMode = true;
                       }
                    }
                    })
</script>
</code>```

答:
Use ng-show and pass an event to click function :</p>

```<code>create a scope variable with initial value false
        $scope.editMode =false;

             $scope.goEvent = function(event){
        if(event=='edit'){
        $scope.editMode = true;
        }else if(event=='update'){
        $scope.editMode = false;
        }
     }

    <button class="btn btn-primary" id="projectDetailsEdit"  ng-show="!editMode" ng-click="goEvent('edit')">Edit</button>
<button class="btn btn-primary" id="projectDetailsUpdate" ng-show="editMode" ng-click="goEvent('update')">Update</button>
</code>```

Title: Hide a button in onload using angularjs

Body:
I have one form with three buttons edit update and cancel.Onload of the page I need to hide the update button.

When I click edit button edit should be hide and update should be displayed.
when I click on update I need to redirect some other page.

Hoe to do this?

                <form id="show_details">

                        Project Name
                        <input type="text">

                        Client
                        <input type="text">

                        Project Co-ordinator
                        <input type="text" disabled="true" >

                        Client Co-ordinator
                        <input type="text">

                        Resource
                        <input type="text" disabled="true">

                </form>

                        <button class="btn btn-primary" id="projectDetailsEdit"  ng-click="goEvent()">Edit</button>
                        <button class="btn btn-primary" id="projectDetailsUpdate" ng-hide="editMode=true" ng-click="goEvent()">Update</button>
                        <button class="btn btn-default" onclick="window.location.href = '/Project/ProjectList'">Cancel</button>

Body:
Use ng-show and pass an event to click function :

create a scope variable with initial value false
        $scope.editMode =false;

             $scope.goEvent = function(event){
        if(event=='edit'){
        $scope.editMode = true;
        }else if(event=='update'){
        $scope.editMode = false;
        }
     }

    <button class="btn btn-primary" id="projectDetailsEdit"  ng-show="!editMode" ng-click="goEvent('edit')">Edit</button>
<button class="btn btn-primary" id="projectDetailsUpdate" ng-show="editMode" ng-click="goEvent('update')">Update</button>


问:
How do I get the ID of a record with highest up-votes grouped by parent field?
The following is my table named nested-tree

Database snapshot

I tried running this query:

```<code>SELECT id,max(upvotes),parent
  FROM nested-tree
 WHERE fid=1
 GROUP BY parent
</code>```

I get the highest upvotes grouped by parent field but I don't properly get which id has the highest upvotes.

The following is the table schema:

```<code>CREATE TABLE `nested-tree` (
  `id` int(11) NOT NULL,
  `fid` int(11) DEFAULT NULL,
  `user_id` int(11) DEFAULT NULL,
  `ctime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `contents` varchar(1024) COLLATE utf8_bin NOT NULL,
  `upvotes` int(11) NOT NULL DEFAULT '0',
  `lft` int(11) NOT NULL,
  `rgt` int(11) NOT NULL,
  `parent` int(11) NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

ALTER TABLE `nested-tree`
  ADD PRIMARY KEY (`id`),
  ADD KEY `fid` (`fid`);

INSERT INTO `nested-tree` (`id`, `fid`, `user_id`, `ctime`, `contents`, `upvotes`, `lft`, `rgt`, `parent`) VALUES
(1, 1, 1434, '2017-06-02 07:31:32', 'ELECTRONICS', 0, 1, 20, 0),
(2, 1, 1434, '2017-06-02 07:31:32', 'TELEVISIONS', 0, 2, 9, 1),
(3, 1, 1434, '2017-06-02 07:31:32', 'TUBE', 0, 3, 4, 2),
(4, 1, 1434, '2017-06-02 07:31:32', 'LCD', 9, 5, 6, 2),
(5, 1, 1434, '2017-06-02 07:31:32', 'PLASMA', 13, 7, 8, 2),
(6, 1, 1434, '2017-06-02 07:31:32', 'PORTABLE ELECTRONICS', 0, 10, 19, 1),
(7, 1, 1434, '2017-06-02 07:31:32', 'MP3 PLAYERS', 0, 11, 14, 10),
(8, 1, 1434, '2017-06-02 07:31:32', 'FLASH', 0, 12, 13, 11),
(9, 1, 1434, '2017-06-02 07:31:32', 'CD PLAYERS', 0, 15, 16, 10),
(10, 1, 1434, '2017-06-02 07:31:32', '2 WAY RADIOS', 4, 17, 18, 10);
</code>```

答:
This question is asked endlessly on SO. Occasionally it is correctly answered, too. The topic even has its own chapter in the manual. Oh, and don't include '-' in a table/column identifier. That's just asking for trouble.

Anyway:

```<code>SELECT x.*
  FROM my_table x
  JOIN (SELECT parent, MAX(upvotes) upvotes FROM my_table WHERE fid = 1 GROUP BY parent) y
    ON y.parent = x.parent
   AND y.upvotes = x.upvotes;
</code>```

Body:
The following is my table named nested-tree

Database snapshot

I tried running this query:

SELECT id,max(upvotes),parent
  FROM nested-tree
 WHERE fid=1
 GROUP BY parent

I get the highest upvotes grouped by parent field but I don't properly get which id has the highest upvotes.

The following is the table schema:

CREATE TABLE `nested-tree` (
  `id` int(11) NOT NULL,
  `fid` int(11) DEFAULT NULL,
  `user_id` int(11) DEFAULT NULL,
  `ctime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `contents` varchar(1024) COLLATE utf8_bin NOT NULL,
  `upvotes` int(11) NOT NULL DEFAULT '0',
  `lft` int(11) NOT NULL,
  `rgt` int(11) NOT NULL,
  `parent` int(11) NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

ALTER TABLE `nested-tree`
  ADD PRIMARY KEY (`id`),
  ADD KEY `fid` (`fid`);

INSERT INTO `nested-tree` (`id`, `fid`, `user_id`, `ctime`, `contents`, `upvotes`, `lft`, `rgt`, `parent`) VALUES
(1, 1, 1434, '2017-06-02 07:31:32', 'ELECTRONICS', 0, 1, 20, 0),
(2, 1, 1434, '2017-06-02 07:31:32', 'TELEVISIONS', 0, 2, 9, 1),
(3, 1, 1434, '2017-06-02 07:31:32', 'TUBE', 0, 3, 4, 2),
(4, 1, 1434, '2017-06-02 07:31:32', 'LCD', 9, 5, 6, 2),
(5, 1, 1434, '2017-06-02 07:31:32', 'PLASMA', 13, 7, 8, 2),
(6, 1, 1434, '2017-06-02 07:31:32', 'PORTABLE ELECTRONICS', 0, 10, 19, 1),
(7, 1, 1434, '2017-06-02 07:31:32', 'MP3 PLAYERS', 0, 11, 14, 10),
(8, 1, 1434, '2017-06-02 07:31:32', 'FLASH', 0, 12, 13, 11),
(9, 1, 1434, '2017-06-02 07:31:32', 'CD PLAYERS', 0, 15, 16, 10),
(10, 1, 1434, '2017-06-02 07:31:32', '2 WAY RADIOS', 4, 17, 18, 10);

Body:
This question is asked endlessly on SO. Occasionally it is correctly answered, too. The topic even has its own chapter in the manual. Oh, and don't include '-' in a table/column identifier. That's just asking for trouble.

Anyway:

SELECT x.*
  FROM my_table x
  JOIN (SELECT parent, MAX(upvotes) upvotes FROM my_table WHERE fid = 1 GROUP BY parent) y
    ON y.parent = x.parent
   AND y.upvotes = x.upvotes;


问:
SVG: using path element to create an area with "holes"
I'm trying to use SVG path element to define an area with "holes". I would like to use these areas for highlighting of some words of text in an image.

My goal is to present results from text extraction from an image using the OCR (Google Cloud Vision API). Results will be displayed in my Angular application in form of table with words from extracted text with ability to highlight/show selected word in an image from the user.

Using the OCR I got bounding box for each word of extracted text.

This is how I solved highlighting:

```<code><svg height="300" width="300">
  <image xlink:href="http://www.downloadclipart.net/thumb/17283-ok-icon-vector-thumb.png" x="0" y="0" height="300" width="300"/>
  <path fill="#ddd" opacity="0.7" fill-rule="evenodd" d="M0 0 H300 V300 H0 Z M10 10 H100 V100 H10 Z" style="visibility:visible"/>
  <path fill="#ddd" opacity="0.7" fill-rule="evenodd" d="M0 0 H300 V300 H0 Z M150 150 H200 V200 H150 Z" style="visibility:hidden"/>
</svg>
</code>```

Everything works fine. I have problem only with overlapping bounding boxes. I have an utility that converts image width and height and bounding boxes to the "d" attribute of path element.

```<code>public static String example(int width, int height, List<Box> boxes) {

    StringBuilder sb = new StringBuilder("M0 0")
            .append(" H").append(width)
            .append(" V").append(height)
            .append(" H0 Z");

    boxes.forEach((box) -> {
        sb.append(" M").append(box.getLeft())
                .append(" ").append(box.getTop())
                .append(" H").append(box.getRight())
                .append(" V").append(box.getBottom())
                .append(" H").append(box.getLeft())
                .append(" Z");
    });

    return sb.toString();
}
</code>```

But if boxes overlap, I got result like this

```<code><svg height="200" width="200">
  <path fill="red" fill-rule="evenodd" d="M0 0 H200 V200 H0 Z M40 40 H100 V100 H40 Z M10 10 H50 V50 H10 Z" />
</svg>
</code>```

and I want this

My question is if there is a better way how to define SVG path element to get result I want.

答:
Use a mask like this...

The path forms the hole.

<svg height="200" width="200">
  <image xlink:href="http://www.downloadclipart.net/thumb/17283-ok-icon-vector-thumb.png" height="200" width="200"/>
  <path fill="black" opacity="0.5" fill-rule="evenodd" d="M0 0 H200 V200 H0 Z M50 50 H100 V100 H50 Z M80 80 H150 V150 H80 Z" />
</svg>

<svg width="200" height="200">
  <defs>
    <mask id="Mask" maskContentUnits="userSpaceOnUse">
      <rect width="200" height="200" fill="white" opacity="0.5"/>
      <path d="M50 50 H100 V100 H50 Z M80 80 H150 V150 H80 Z" />
    </mask>
  </defs>
  <image xlink:href="http://www.downloadclipart.net/thumb/17283-ok-icon-vector-thumb.png" height="200" width="200"/>
  <rect width="200" height="200" mask="url(#Mask)" />
</svg>```

Body:
I'm trying to use SVG path element to define an area with "holes". I would like to use these areas for highlighting of some words of text in an image.

My goal is to present results from text extraction from an image using the OCR (Google Cloud Vision API). Results will be displayed in my Angular application in form of table with words from extracted text with ability to highlight/show selected word in an image from the user.

Using the OCR I got bounding box for each word of extracted text.

This is how I solved highlighting:

<svg height="300" width="300">
  <image xlink:href="http://www.downloadclipart.net/thumb/17283-ok-icon-vector-thumb.png" x="0" y="0" height="300" width="300"/>
  <path fill="#ddd" opacity="0.7" fill-rule="evenodd" d="M0 0 H300 V300 H0 Z M10 10 H100 V100 H10 Z" style="visibility:visible"/>
  <path fill="#ddd" opacity="0.7" fill-rule="evenodd" d="M0 0 H300 V300 H0 Z M150 150 H200 V200 H150 Z" style="visibility:hidden"/>
</svg>

Everything works fine. I have problem only with overlapping bounding boxes. I have an utility that converts image width and height and bounding boxes to the "d" attribute of path element.

public static String example(int width, int height, List<Box> boxes) {

    StringBuilder sb = new StringBuilder("M0 0")
            .append(" H").append(width)
            .append(" V").append(height)
            .append(" H0 Z");

    boxes.forEach((box) -> {
        sb.append(" M").append(box.getLeft())
                .append(" ").append(box.getTop())
                .append(" H").append(box.getRight())
                .append(" V").append(box.getBottom())
                .append(" H").append(box.getLeft())
                .append(" Z");
    });

    return sb.toString();
}

But if boxes overlap, I got result like this

<svg height="200" width="200">
  <path fill="red" fill-rule="evenodd" d="M0 0 H200 V200 H0 Z M40 40 H100 V100 H40 Z M10 10 H50 V50 H10 Z" />
</svg>

and I want this

My question is if there is a better way how to define SVG path element to get result I want.

Body:
Use a mask like this...

The path forms the hole.

<svg height="200" width="200">
  <image xlink:href="http://www.downloadclipart.net/thumb/17283-ok-icon-vector-thumb.png" height="200" width="200"/>
  <path fill="black" opacity="0.5" fill-rule="evenodd" d="M0 0 H200 V200 H0 Z M50 50 H100 V100 H50 Z M80 80 H150 V150 H80 Z" />
</svg>

<br>

<svg width="200" height="200">
  <defs>
    <mask id="Mask" maskContentUnits="userSpaceOnUse">
      <rect width="200" height="200" fill="white" opacity="0.5"/>
      <path d="M50 50 H100 V100 H50 Z M80 80 H150 V150 H80 Z" />
    </mask>
  </defs>
  <image xlink:href="http://www.downloadclipart.net/thumb/17283-ok-icon-vector-thumb.png" height="200" width="200"/>
  <rect width="200" height="200" mask="url(#Mask)" />
</svg>


问:
put() takes at least 3 arguments (2 given)
This is my code in Views.py

```<code>class NotificationsViewSet(viewsets.ModelViewSet):
    permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope]
    queryset = Notifications.objects.all()
    serializer_class = NotificationsSerializer
    filter_fields = ('status','task','survey_type',)

    def put(self, request, pk, format=None):
        notifications = self.get_object(pk)
        serializer = NotificationsSerializer(notifications, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, pk, format=None):
        notifications = self.get_object(pk)
        notifications.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)
</code>```

When i try to use method PUT i got error put() takes at least 3 arguments (2 given). What is wrong with my code?

答:
That's probably because you're doing a PUT on the set entry point where the pk isn't defined. Make it optional:

```<code>def put(self, request, pk=None, format=None):
</code>```

Note that there's no point in using viewset if you're overriding put.

Body:
This is my code in Views.py

class NotificationsViewSet(viewsets.ModelViewSet):
    permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope]
    queryset = Notifications.objects.all()
    serializer_class = NotificationsSerializer
    filter_fields = ('status','task','survey_type',)

    def put(self, request, pk, format=None):
        notifications = self.get_object(pk)
        serializer = NotificationsSerializer(notifications, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, pk, format=None):
        notifications = self.get_object(pk)
        notifications.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

When i try to use method PUT i got error put() takes at least 3 arguments (2 given). What is wrong with my code?

Body:
That's probably because you're doing a PUT on the set entry point where the pk isn't defined. Make it optional:

def put(self, request, pk=None, format=None):

Note that there's no point in using viewset if you're overriding put.


问:
How to make cards appear on screen - Unity, C#
I'm working on a card game, and I'm having trouble with making cards appear on screen. Does anyone know how I can make them appear at the bottom of the screen with a gap between each card? The idea being something similar to Solitaire, and when you click a card, it moves above the other cards with all the stats displayed.

My player manager code:

```<code>using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class s_PlayerManager : MonoBehaviour {

public bool isAi;
public s_DeckSetUp deckManager;
public List<Card> PlayerDeck = new List<Card>();
public List<Card> PlayerHand = new List<Card>();
public List<Card> PlayerGrave = new List<Card>();
public Card selectedCard;
private int totalHandCount = 5;
public int cardCount = 0;

void Start(){
    deckManager = GameObject.Find("Deck Manager").GetComponent<s_DeckSetUp>();
}

public void StartDeck(){
    for(int a = 0; a < deckManager.DeckAllCards.Count; a++){
        int b = Random.Range(0, deckManager.DeckAllCards.Count);
        PlayerDeck.Add(deckManager.DeckAllCards[b]);
    }
    DrawHand();
    EventSystem.current.currentSelectedGameObject.SetActive(false);
}

public void DrawHand(){
    for(cardCount = 0; cardCount < totalHandCount; cardCount++){
        int b = Random.Range(0, PlayerDeck.Count);
        PlayerHand.Add(PlayerDeck[b]);
        PlayerDeck.RemoveAt(b);
    }
}

public void CardDraw(){
    if(cardCount < totalHandCount){
        int b = Random.Range(0, PlayerDeck.Count);
        PlayerHand.Add(PlayerDeck[b]);
        PlayerDeck.RemoveAt(b);
        cardCount++;
    }
 }
}
</code>```

It handles creating the players deck, and drawing the first 5 cards. The CardDraw function is triggered by clicking a UI button. Can anyone possibly tell me how to have the cards appear on screen? I have the card art in the project files. Any help is greatly appreciated. I also posted this on the Unity forums:
https://forum.unity3d.com/threads/making-cards-appear-on-screen.475335/

答:
I will explain to you how to get a single card to show at the bottom of the screen first.

The hardest part for you would probably be to calculate the world position of where you have to put your sprites (I assume you have sprites for your cards).

How I would go about this is to calculate the SCREEN position of where you want your cards, since your requirement is for them to be at the bottom of the screen.

You can use Screen.width to get the width of your screen. The height does not matter because we want to place the cards at Zero height which is the bottom edge of the screen.

The bottom center of the screen in screen space will be

Vector2 botCenterScreenSpace = new Vector2(Screen.width/2, 0)

You can get the bottom center of the screen in world space by using the following code:

```<code>var botCenterWorldSpace = Camera.main.ScreenToWorldPoint(new Vector3(botCenterScreenSpace.x, botCenterScreenSpace.y, Camera.main.nearClipPlane));
</code>```

The quickest way to see if this works is to setup your sprites. By default the sprite anchor should be exactly in the center of the card which is fine for now.

Create a prefab for your card. To make things easier to test we will setup a CardDealerUi script.

```<code>public class CardDealerUi : MonoBehaviour
{
    [SerializeField] private GameObject cardPrefab;

    private Vector2 botCenterScreenSpace;
    private Vector3 botCenterWorldSpace;

    void Start()
    {
        this.botCenterScreenSpace = new Vector2(Screen.width/2, 0);
        this.botCenterWorldSpace = Camera.main.ScreenToWorldPoint(new Vector3(botCenterScreenSpace.x, botCenterScreenSpace.y, Camera.main.nearClipPlane));
    }

    void OnCardDrawn(Card cardDrawn)
    {
        GameObject newCardUi = GameObject.Instantiate(this.cardPrefab, this.botCenterWorldSpace, Quaternion.indentity);

        // Here you can swap sprites for your cards or so.
    }
}
</code>```

To test this just do some basic keyboard input and call OnCardDrawn with any Card object.

In this example you had only 1 prefab. For you to realize your game you may want to setup a prefab for every type of card or you would want to have 1 prefab and swap out the sprites where I commented above.

So far you should have one card on screen. Now the problem is where to put the second and third and forth card and so on. This will require some math to get it how you want.

I will not go into detail but you would most likely have 2 constants in your dealer script. float CardWidth and float CardGap.

When you deal 5 cards you would probably want to calculate the total width of all the cards including the gaps. That is var totalWidth = numCards * CardWidth + (numCards - 1) * CardGap. Then the offset from the botCenterWorldSpace would become something like:

```<code>for(int i = 0; i < cardsToDeal.Length; i++)
{
    var cardPosition = botCenterWorldSpace - new Vector3(totalWidth + (totalWidth/cardsToDeal.Length*i) + CardWidth/2, 0, 0);
}
</code>```

Just in case you wondered where this code belongs, you will have a new function in you CardDealerUi. Something like this:

```<code>public class CardDealerUi : MonoBehaviour
{
    [SerializeField] private GameObject cardPrefab;

    private Vector2 botCenterScreenSpace;
    private Vector3 botCenterWorldSpace;

    void Start()
    {
        this.botCenterScreenSpace = new Vector2(Screen.width/2, 0);
        this.botCenterWorldSpace = Camera.main.ScreenToWorldPoint(new Vector3(botCenterScreenSpace.x, botCenterScreenSpace.y, Camera.main.nearClipPlane));
    }

    void OnCardsDrawn(List<Card> cardsDrawn)
    {
         for(int i = 0; i < cardsDrawn.Length; i++)
        {
            var cardPosition = this.botCenterWorldSpace - new Vector3(totalWidth + (totalWidth/cardsDrawn.Length*i) + CardWidth/2, 0, 0);

            GameObject newCardUi = GameObject.Instantiate(this.cardPrefab, cardPosition , Quaternion.indentity);
        }

        // Here you can swap sprites for your cards or so.
    }
}
</code>```

I hope this can get you on the right track.

From here you will need separate research on animating the cards and moving them on mouse over.

Body:
I'm working on a card game, and I'm having trouble with making cards appear on screen. Does anyone know how I can make them appear at the bottom of the screen with a gap between each card? The idea being something similar to Solitaire, and when you click a card, it moves above the other cards with all the stats displayed.

My player manager code:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class s_PlayerManager : MonoBehaviour {

public bool isAi;
public s_DeckSetUp deckManager;
public List<Card> PlayerDeck = new List<Card>();
public List<Card> PlayerHand = new List<Card>();
public List<Card> PlayerGrave = new List<Card>();
public Card selectedCard;
private int totalHandCount = 5;
public int cardCount = 0;

void Start(){
    deckManager = GameObject.Find("Deck Manager").GetComponent<s_DeckSetUp>();
}

public void StartDeck(){
    for(int a = 0; a < deckManager.DeckAllCards.Count; a++){
        int b = Random.Range(0, deckManager.DeckAllCards.Count);
        PlayerDeck.Add(deckManager.DeckAllCards[b]);
    }
    DrawHand();
    EventSystem.current.currentSelectedGameObject.SetActive(false);
}

public void DrawHand(){
    for(cardCount = 0; cardCount < totalHandCount; cardCount++){
        int b = Random.Range(0, PlayerDeck.Count);
        PlayerHand.Add(PlayerDeck[b]);
        PlayerDeck.RemoveAt(b);
    }
}

public void CardDraw(){
    if(cardCount < totalHandCount){
        int b = Random.Range(0, PlayerDeck.Count);
        PlayerHand.Add(PlayerDeck[b]);
        PlayerDeck.RemoveAt(b);
        cardCount++;
    }
 }
}

It handles creating the players deck, and drawing the first 5 cards. The CardDraw function is triggered by clicking a UI button. Can anyone possibly tell me how to have the cards appear on screen? I have the card art in the project files. Any help is greatly appreciated. I also posted this on the Unity forums:
https://forum.unity3d.com/threads/making-cards-appear-on-screen.475335/

Body:
I will explain to you how to get a single card to show at the bottom of the screen first.

The hardest part for you would probably be to calculate the world position of where you have to put your sprites (I assume you have sprites for your cards).

How I would go about this is to calculate the SCREEN position of where you want your cards, since your requirement is for them to be at the bottom of the screen.

You can use Screen.width to get the width of your screen. The height does not matter because we want to place the cards at Zero height which is the bottom edge of the screen.

The bottom center of the screen in screen space will be

Vector2 botCenterScreenSpace = new Vector2(Screen.width/2, 0)

You can get the bottom center of the screen in world space by using the following code:

var botCenterWorldSpace = Camera.main.ScreenToWorldPoint(new Vector3(botCenterScreenSpace.x, botCenterScreenSpace.y, Camera.main.nearClipPlane));

The quickest way to see if this works is to setup your sprites. By default the sprite anchor should be exactly in the center of the card which is fine for now.

Create a prefab for your card. To make things easier to test we will setup a CardDealerUi script.

public class CardDealerUi : MonoBehaviour
{
    [SerializeField] private GameObject cardPrefab;

    private Vector2 botCenterScreenSpace;
    private Vector3 botCenterWorldSpace;

    void Start()
    {
        this.botCenterScreenSpace = new Vector2(Screen.width/2, 0);
        this.botCenterWorldSpace = Camera.main.ScreenToWorldPoint(new Vector3(botCenterScreenSpace.x, botCenterScreenSpace.y, Camera.main.nearClipPlane));
    }

    void OnCardDrawn(Card cardDrawn)
    {
        GameObject newCardUi = GameObject.Instantiate(this.cardPrefab, this.botCenterWorldSpace, Quaternion.indentity);

        // Here you can swap sprites for your cards or so.
    }
}

To test this just do some basic keyboard input and call OnCardDrawn with any Card object.

In this example you had only 1 prefab. For you to realize your game you may want to setup a prefab for every type of card or you would want to have 1 prefab and swap out the sprites where I commented above.

So far you should have one card on screen. Now the problem is where to put the second and third and forth card and so on. This will require some math to get it how you want.

I will not go into detail but you would most likely have 2 constants in your dealer script. float CardWidth and float CardGap.

When you deal 5 cards you would probably want to calculate the total width of all the cards including the gaps. That is var totalWidth = numCards * CardWidth + (numCards - 1) * CardGap. Then the offset from the botCenterWorldSpace would become something like:

for(int i = 0; i < cardsToDeal.Length; i++)
{
    var cardPosition = botCenterWorldSpace - new Vector3(totalWidth + (totalWidth/cardsToDeal.Length*i) + CardWidth/2, 0, 0);
}

Just in case you wondered where this code belongs, you will have a new function in you CardDealerUi. Something like this:

public class CardDealerUi : MonoBehaviour
{
    [SerializeField] private GameObject cardPrefab;

    private Vector2 botCenterScreenSpace;
    private Vector3 botCenterWorldSpace;

    void Start()
    {
        this.botCenterScreenSpace = new Vector2(Screen.width/2, 0);
        this.botCenterWorldSpace = Camera.main.ScreenToWorldPoint(new Vector3(botCenterScreenSpace.x, botCenterScreenSpace.y, Camera.main.nearClipPlane));
    }

    void OnCardsDrawn(List<Card> cardsDrawn)
    {
         for(int i = 0; i < cardsDrawn.Length; i++)
        {
            var cardPosition = this.botCenterWorldSpace - new Vector3(totalWidth + (totalWidth/cardsDrawn.Length*i) + CardWidth/2, 0, 0);

            GameObject newCardUi = GameObject.Instantiate(this.cardPrefab, cardPosition , Quaternion.indentity);
        }

        // Here you can swap sprites for your cards or so.
    }
}

I hope this can get you on the right track.

From here you will need separate research on animating the cards and moving them on mouse over.


问:
Push data into another object
How can I push new values into an existing object?

Basically I get some form datanoteValue and I have some other data being input to my component person which I would like to make part of noteValue before I run my save function.

```<code>let noteValue = form.value;
noteValue.said_by.person_name = this.person.name;
</code>```

This is an example I have working elsewhere but it doesn't seem to work:

```<code>let exValue = form.value;
exValue['due_date'].timestamp = this.timestamp;
</code>```

What am I missing? And is this even the right way to do this?

答:
You can use Object.assign().

Object.assign()  Properties in the target object will be overwritten by properties in the sources if they have the same key.

var obj1 = { foo: 'bar', x: 42 };
var obj2 = { foo: 'baz', y: 13 };
var obj = Object.assign({}, obj1, obj2);
console.log(obj);```

Title: Push data into another object

Body:
How can I push new values into an existing object?

Basically I get some form datanoteValue and I have some other data being input to my component person which I would like to make part of noteValue before I run my save function.

let noteValue = form.value;
noteValue.said_by.person_name = this.person.name;

This is an example I have working elsewhere but it doesn't seem to work:

let exValue = form.value;
exValue['due_date'].timestamp = this.timestamp;

What am I missing? And is this even the right way to do this?


问:
Converting a variable user input float into an array of characters in C?
my goal in the program is to prompt a user for a value of money (float) within a certain range to use in another function. However, the other function seems much easier to accomplish using an array of characters as the input. I have looked into using sprintf and snprintf, but am not sure how/if these can be implemented with a variable input instead of a constant.

The function this number will be passed to needs to convert the number to written words. Example: 1150.50 = One thousand one hundred fifty dollars and fifty cents.

Here is the segment of code I am trying to implement;

```<code>do {

        puts("Please enter the amount of the paycheck, this must be from 0$ to 10000$:  \n");
        scanf("%.2f", entered_amount);

        if (entered_amount < 0.00 && entered_amount > 10000.00) {
        printf("This is not a valid amount, please try again!   \n\n");

        }

    } while (entered_amount < 0.00 && entered_amount > 10000.00);

    sprintf(amount, "%f", entered_amount);
    //Trying to convert a float entered by the user to an array of characters to use in the number_to_word function!
    printf("%s", amount);
</code>```

Where entered_amount will be a user input float, and amount would be an
array of char's. Ex:
5555.55 = {"5,5,5,5,.,5,5"}

I appreciate all help and feedback, thanks!

答:
If amount is char array of sufficient size, then after calling sprintf, you have your desired structure.

```<code>sprintf(amount, "%f", entered_amount);
</code>```

You can print it easily by printf as you tried.

```<code>printf("%s", amount);   //Print entire array
//Print char by char
size_t i = 0;
for (i = 0; i < strlen(amount); i++)
    printf("%c", amount[i]);
</code>```

The problem is more with your if statement with checking for range.

```<code>if (entered_amount < 0.00 && entered_amount > 10000.00) {
</code>```

This will never be executed. Use this instead:

```<code>if (entered_amount < 0.00 || entered_amount > 10000.00) {
</code>```

When reading float, you should do it by pointer (Check additional & character):

```<code>scanf("%.2f", &entered_amount);
</code>```

Body:
my goal in the program is to prompt a user for a value of money (float) within a certain range to use in another function. However, the other function seems much easier to accomplish using an array of characters as the input. I have looked into using sprintf and snprintf, but am not sure how/if these can be implemented with a variable input instead of a constant.

The function this number will be passed to needs to convert the number to written words. Example: 1150.50 = One thousand one hundred fifty dollars and fifty cents.

Here is the segment of code I am trying to implement;

do {

        puts("Please enter the amount of the paycheck, this must be from 0$ to 10000$:  \n");
        scanf("%.2f", entered_amount);

        if (entered_amount < 0.00 && entered_amount > 10000.00) {
        printf("This is not a valid amount, please try again!   \n\n");

        }

    } while (entered_amount < 0.00 && entered_amount > 10000.00);

    sprintf(amount, "%f", entered_amount);
    //Trying to convert a float entered by the user to an array of characters to use in the number_to_word function!
    printf("%s", amount);

Where entered_amount will be a user input float, and amount would be an
array of char's. Ex:
5555.55 = {"5,5,5,5,.,5,5"}

I appreciate all help and feedback, thanks!

Body:
If amount is char array of sufficient size, then after calling sprintf, you have your desired structure.

sprintf(amount, "%f", entered_amount);

You can print it easily by printf as you tried.

printf("%s", amount);   //Print entire array
//Print char by char
size_t i = 0;
for (i = 0; i < strlen(amount); i++)
    printf("%c", amount[i]);

The problem is more with your if statement with checking for range.

if (entered_amount < 0.00 && entered_amount > 10000.00) {

This will never be executed. Use this instead:

if (entered_amount < 0.00 || entered_amount > 10000.00) {

When reading float, you should do it by pointer (Check additional & character):

scanf("%.2f", &entered_amount);


问:
How do I change the file creation date of a Windows file?
How do I change the file creation date of a Windows file from Python?</p>

答:
Here is a solution that works on Python 3.5 and windows 7.  Very easy. I admit it's sloppy coding... but it works.  You're welcome to clean it up.  I just needed a quick soln.

```<code>import pywintypes, win32file, win32con, datetime, pytz

def changeFileCreationTime(fname, newtime):
    wintime = pywintypes.Time(newtime)
    winfile = win32file.CreateFile(fname, win32con.GENERIC_WRITE,
                                   win32con.FILE_SHARE_READ |
                                   win32con.FILE_SHARE_WRITE |
                                   win32con.FILE_SHARE_DELETE,
                                   None,
                                   win32con.OPEN_EXISTING,
                                   win32con.FILE_ATTRIBUTE_NORMAL,
                                   None)

    win32file.SetFileTime(      winfile,  wintime,  wintime,     wintime)
    # None doesnt change args = file,     creation, last access, last write
    # win32file.SetFileTime(None, None, None, None) # does nonething
    winfile.close()

if __name__ == "__main__":
    local_tz = pytz.timezone('Antarctica/South_Pole')
    start_date = local_tz.localize(datetime.datetime(1776,7,4), is_dst=None)
    changeFileCreationTime(r'C:\homemade.pr0n', start_date )
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Here is a solution that works on Python 3.5 and windows 7.  Very easy. I admit it's sloppy coding... but it works.  You're welcome to clean it up.  I just needed a quick soln.

import pywintypes, win32file, win32con, datetime, pytz

def changeFileCreationTime(fname, newtime):
    wintime = pywintypes.Time(newtime)
    winfile = win32file.CreateFile(fname, win32con.GENERIC_WRITE,
                                   win32con.FILE_SHARE_READ |
                                   win32con.FILE_SHARE_WRITE |
                                   win32con.FILE_SHARE_DELETE,
                                   None,
                                   win32con.OPEN_EXISTING,
                                   win32con.FILE_ATTRIBUTE_NORMAL,
                                   None)

    win32file.SetFileTime(      winfile,  wintime,  wintime,     wintime)
    # None doesnt change args = file,     creation, last access, last write
    # win32file.SetFileTime(None, None, None, None) # does nonething
    winfile.close()

if __name__ == "__main__":
    local_tz = pytz.timezone('Antarctica/South_Pole')
    start_date = local_tz.localize(datetime.datetime(1776,7,4), is_dst=None)
    changeFileCreationTime(r'C:\homemade.pr0n', start_date )


问:
node.js - correct content security policy for socket.io (web sockets) using helmet
I am trying to implement content security policies (CSP) in a node server, and am having trouble setting up socket.io. It looks like I am setting up the connectSrc incorrectly in the code below. Could someone suggest the correct way to set up helmet so that web socket connections are allowed by the browser? Thanks in advance!

I am using helmet module for generation of CSP; the following is the code that sets up CSP:

```<code>securitySetup = function(app) {
  var connectSources, helmet, scriptSources, styleSources;
  helmet = require("helmet");
  app.use(helmet());
  app.use(helmet.hidePoweredBy());
  app.use(helmet.noSniff());
  app.use(helmet.crossdomain());
  scriptSources = ["'self'", "'unsafe-inline'", "'unsafe-eval'", "ajax.googleapis.com"];
  styleSources = ["'self'", "'unsafe-inline'", "ajax.googleapis.com"];
  connectSources = ["'self'"];
  return app.use(helmet.contentSecurityPolicy({
    defaultSrc: ["'self'"],
    scriptSrc: scriptSources,
    styleSrc: styleSources,
    connectSrc: connectSources,
    reportUri: '/report-violation',
    reportOnly: false,
    setAllHeaders: false,
    safari5: false
  }));
};
</code>```

This works fine for all HTTP/AJAX traffic, but fails for ws:// protocol. I get this error in chrome debugger when socket.io connection is made:

```<code>Refused to connect to 'ws://localhost:3000/socket.io/1/websocket/ubexeZHZiAHwAV53WQ7u' because it violates the following Content Security Policy directive: "connect-src 'self'".
</code>```

答:
Bit late to the party, but thought I'd throw something into the mix on this subject. @Ed4 is quite right, 'self' will indeed only match the same host, port and scheme. A way around it is to include it in one or more forms:

connect-src: wss: - to allow a connection to the whole wss scheme - basically any web socket (probably not ideal)

connect-src: wss://yoursite.domain.com  - to restrict it to a specific endpoint. This is most ideal, but might be restrictive if your subdomain changes between deployments (as ours do)

connect-src: wss://*.domain.com - can use wildcards in there to tighten security up a bit. This is what we do

TL;DR - use wildcards to make things more specific without just opening yourself up to any web sockets out there/

Refer to this passage from Google devs:

The source list in each directive is flexible. You can specify sources by scheme (data:, https:), or ranging in specificity from hostname-only (example.com, which matches any origin on that host: any scheme, any port) to a fully qualified URI (https://example.com:443, which matches only HTTPS, only example.com, and only port 443). Wildcards are accepted, but only as a scheme, a port, or in the leftmost position of the hostname: ://.example.com:* would match all subdomains of example.com (but not example.com itself), using any scheme, on any port.

https://developers.google.com/web/fundamentals/security/csp/

Body:
I am trying to implement content security policies (CSP) in a node server, and am having trouble setting up socket.io. It looks like I am setting up the connectSrc incorrectly in the code below. Could someone suggest the correct way to set up helmet so that web socket connections are allowed by the browser? Thanks in advance!

I am using helmet module for generation of CSP; the following is the code that sets up CSP:

securitySetup = function(app) {
  var connectSources, helmet, scriptSources, styleSources;
  helmet = require("helmet");
  app.use(helmet());
  app.use(helmet.hidePoweredBy());
  app.use(helmet.noSniff());
  app.use(helmet.crossdomain());
  scriptSources = ["'self'", "'unsafe-inline'", "'unsafe-eval'", "ajax.googleapis.com"];
  styleSources = ["'self'", "'unsafe-inline'", "ajax.googleapis.com"];
  connectSources = ["'self'"];
  return app.use(helmet.contentSecurityPolicy({
    defaultSrc: ["'self'"],
    scriptSrc: scriptSources,
    styleSrc: styleSources,
    connectSrc: connectSources,
    reportUri: '/report-violation',
    reportOnly: false,
    setAllHeaders: false,
    safari5: false
  }));
};

This works fine for all HTTP/AJAX traffic, but fails for ws:// protocol. I get this error in chrome debugger when socket.io connection is made:

Refused to connect to 'ws://localhost:3000/socket.io/1/websocket/ubexeZHZiAHwAV53WQ7u' because it violates the following Content Security Policy directive: "connect-src 'self'".


问:
Using Java+regex, I want to find repeating characters in a string and replace that substring(s) with character found and # of times it was found
sample

```<code>String str = "fghhhhjkjkljhdd"
</code>```

i need to transform it into output string "fgh4jkjkljhd2"

I have the following code but the problem here is that i only get a single occurence matched - "hhhh". I'm still missing "dd".
Once this problem is solved i can think about how to assign matches to a string(s) and count characters there, but for now i 'm not able to get multiple matches. Any pointers are appreciated.

```<code>    String str = "fghhhhjkjkljhdd";
    Pattern p = Pattern.compile("(\\w)\\1+");
    Matcher m = p.matcher(str);
    if (m.find()) System.out.println(m.group());
</code>```

答:
You may wrap the quantified backreference with a capturing group to be able to access this value later, and use a Matcher#appendReplacement to actually modify the matches inside the string:

```<code>String text = "fghhhhjkjkljhdd";
String regex = "(\\w)(\\1+)";
Pattern r = Pattern.compile(regex);
Matcher m = r.matcher(text);
StringBuffer sb = new StringBuffer();
while (m.find()) {
    m.appendReplacement(sb, m.group(1) + (m.group(2).length()+1));
}
m.appendTail(sb);
System.out.println(sb); // => fgh4jkjkljhd2
</code>```

See the Java demo.

Body:
sample

String str = "fghhhhjkjkljhdd"

i need to transform it into output string "fgh4jkjkljhd2"

I have the following code but the problem here is that i only get a single occurence matched - "hhhh". I'm still missing "dd".
Once this problem is solved i can think about how to assign matches to a string(s) and count characters there, but for now i 'm not able to get multiple matches. Any pointers are appreciated.

    String str = "fghhhhjkjkljhdd";
    Pattern p = Pattern.compile("(\\w)\\1+");
    Matcher m = p.matcher(str);
    if (m.find()) System.out.println(m.group());

Body:
You may wrap the quantified backreference with a capturing group to be able to access this value later, and use a Matcher#appendReplacement to actually modify the matches inside the string:

String text = "fghhhhjkjkljhdd";
String regex = "(\\w)(\\1+)";
Pattern r = Pattern.compile(regex);
Matcher m = r.matcher(text);
StringBuffer sb = new StringBuffer();
while (m.find()) {
    m.appendReplacement(sb, m.group(1) + (m.group(2).length()+1));
}
m.appendTail(sb);
System.out.println(sb); // => fgh4jkjkljhd2

See the Java demo.


问:
How to access Apache Solr's Velocity Search UI
I have just completed the Solr Quick Start Guide, and got it up and running, with the admin user interface seemingly working. Likewise, searches using curl (following the instructions in the guide) also works as expected, as do a very basic web find interface  ( http://localhost:8983/solr/gettingstarted_shard2_replica1/browse )

However, when I try to access the Velocity sample search UI mentioned in the reference, I get page not found 404 message. The reference doc is located at:

https://cwiki.apache.org/confluence/display/solr/Velocity+Search+UI

and it claims that the sample search UI should be accessible at

http://localhost:8983/solr/techproducts/browse

I'm guessing it may have something to do about the fact that I, following the instructions, created a sharded setup.

Is there any way I can access the sample UI in this setup, or is it something else I am missing.

Any suggestion will be greatly appreciated

答:
For a vanilla download use this command to setup the core and velocity ui

bin/solr -e techproducts


问:
datatable sum a column that include different elements
Table that have a column includes different elements and need to:
1) find the result of input name called price
2) sum this input in the footer of this column using the value of price.

I tried many ways but no success please help.

var table = $('#example').DataTable({
// I Need datatable find input=price
// sum all column

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css" rel="stylesheet"/>

<table id="example">
<thead>
    <tr>
        <th>Rendering engine</th>
        <th>Browser</th>
        <th>Platform(s)</th>
        <th>Engine version</th>
        <th>CSS grade</th>
        <th>price</th>
    </tr>
</thead>
<tfoot class='footer'>
    <tr>
        <th>Rendering engine</th>
        <th>Browser</th>
        <th>Platform(s)</th>
        <th>Engine version</th>
        <th>CSS grade</th>
        <th>price</th>
    </tr>
</tfoot>
<tfoot class='custo'>
  <tr >
      <th colspan=5 style=text-align:right>Total:</th>
      <th></th>
  </tr>
</tfoot>
<tbody>
    <tr>
        <td>Trident</td>
        <td>Internet Explorer 4.0</td>
        <td>Win 95+</td>
        <td> 4</td>
        <td>X</td>
        <td><input name='price' value='R$ 1.000,00'><input name='percent' value='10%'></td>
    </tr>
    <tr>
        <td>Trident</td>
        <td>Internet Explorer 5.0</td>
        <td>Win 95+</td>
        <td>5</td>
        <td>C</td>
        <td><input name='price' value='R$ 2.000,00'><input name='percent' value='10%'></td>
    </tr>
    <tr>
        <td>Trident</td>
        <td>Internet Explorer 5.5</td>
        <td>Win 95+</td>
        <td>5.5</td>
        <td>A</td>
        <td><input name='price' value='R$ 3.000,00'><input name='percent' value='10%'></td>
    </tr>
</tbody></code>```

答:
First change 3.000,00 to 3,000.00 and loop through prices using $( "#example input[name='price']" ).each to calculate the sum

sum=0;
$( "#example input[name='price']" ).each(function() {
var prc=$( this ).val().replace(',','').split(' ');
sum+=parseInt(prc[1])*1;
});
$('.custo > th:nth-child(2)').html('R$ '+sum);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css" rel="stylesheet"/>

<table id="example">
<thead>
    <tr>
        <th>Rendering engine</th>
        <th>Browser</th>
        <th>Platform(s)</th>
        <th>Engine version</th>
        <th>CSS grade</th>
        <th>price</th>
    </tr>
</thead>
<tfoot class='footer'>
    <tr>
        <th>Rendering engine</th>
        <th>Browser</th>
        <th>Platform(s)</th>
        <th>Engine version</th>
        <th>CSS grade</th>
        <th>price</th>
    </tr>
  <tr class="custo" >
      <th colspan="5" style="text-align:right">Total:</th>
      <th></th>
  </tr>
</tfoot>
<tbody>
    <tr>
        <td>Trident</td>
        <td>Internet Explorer 4.0</td>
        <td>Win 95+</td>
        <td> 4</td>
        <td>X</td>
        <td><input name='price' value='R$ 1,000.00'><input name='percent' value='10%'></td>
    </tr>
    <tr>
        <td>Trident</td>
        <td>Internet Explorer 5.0</td>
        <td>Win 95+</td>
        <td>5</td>
        <td>C</td>
        <td><input name='price' value='R$ 2,000.00'><input name='percent' value='10%'></td>
    </tr>
    <tr>
        <td>Trident</td>
        <td>Internet Explorer 5.5</td>
        <td>Win 95+</td>
        <td>5.5</td>
        <td>A</td>
        <td><input name='price' value='R$ 3,000.00'><input name='percent' value='10%'></td>
    </tr>
</tbody></code>```

Body:
Table that have a column includes different elements and need to:
1) find the result of input name called price
2) sum this input in the footer of this column using the value of price.

I tried many ways but no success please help.

var table = $('#example').DataTable({
// I Need datatable find input=price
// sum all column

});

<link href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css" rel="stylesheet"/>

        Rendering engine
        Browser
        Platform(s)
        Engine version
        CSS grade
        price

        Rendering engine
        Browser
        Platform(s)
        Engine version
        CSS grade
        price

      Total:

        Trident
        Internet Explorer 4.0
        Win 95+
         4
        X
        <input name='price' value='R$ 1.000,00'><input name='percent' value='10%'>

        Trident
        Internet Explorer 5.0
        Win 95+
        5
        C
        <input name='price' value='R$ 2.000,00'><input name='percent' value='10%'>

        Trident
        Internet Explorer 5.5
        Win 95+
        5.5
        A
        <input name='price' value='R$ 3.000,00'><input name='percent' value='10%'>

Body:
First change 3.000,00 to 3,000.00 and loop through prices using $( "#example input[name='price']" ).each to calculate the sum

sum=0;
$( "#example input[name='price']" ).each(function() {
var prc=$( this ).val().replace(',','').split(' ');
sum+=parseInt(prc[1])*1;
});
$('.custo > th:nth-child(2)').html('R$ '+sum);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css" rel="stylesheet"/>

<table id="example">
<thead>
    <tr>
        <th>Rendering engine</th>
        <th>Browser</th>
        <th>Platform(s)</th>
        <th>Engine version</th>
        <th>CSS grade</th>
        <th>price</th>
    </tr>
</thead>
<tfoot class='footer'>
    <tr>
        <th>Rendering engine</th>
        <th>Browser</th>
        <th>Platform(s)</th>
        <th>Engine version</th>
        <th>CSS grade</th>
        <th>price</th>
    </tr>
  <tr class="custo" >
      <th colspan="5" style="text-align:right">Total:</th>
      <th></th>
  </tr>
</tfoot>
<tbody>
    <tr>
        <td>Trident</td>
        <td>Internet Explorer 4.0</td>
        <td>Win 95+</td>
        <td> 4</td>
        <td>X</td>
        <td><input name='price' value='R$ 1,000.00'><input name='percent' value='10%'></td>
    </tr>
    <tr>
        <td>Trident</td>
        <td>Internet Explorer 5.0</td>
        <td>Win 95+</td>
        <td>5</td>
        <td>C</td>
        <td><input name='price' value='R$ 2,000.00'><input name='percent' value='10%'></td>
    </tr>
    <tr>
        <td>Trident</td>
        <td>Internet Explorer 5.5</td>
        <td>Win 95+</td>
        <td>5.5</td>
        <td>A</td>
        <td><input name='price' value='R$ 3,000.00'><input name='percent' value='10%'></td>
    </tr>
</tbody>


问:
Curl specific div class text and re display?php
I'm very new to PHP, and I know how to do this for any H2 that has an ID for example, because I stumbled upon a nice example:

```<code><?php
$html = file_get_contents('http://pokemondb.net/evolution'); //get the html
returned from the following url

$pokemon_doc = new DOMDocument();

libxml_use_internal_errors(TRUE); //disable libxml errors

if(!empty($html)){ //if any html is actually returned

$pokemon_doc->loadHTML($html);
libxml_clear_errors(); //remove errors for yucky html

$pokemon_xpath = new DOMXPath($pokemon_doc);

//get all the h2's with an id
$pokemon_row = $pokemon_xpath->query('//h2[@class]');

if($pokemon_row->length > 0){
    foreach($pokemon_row as $row){
        echo $row->nodeValue . "<br/>";
    }
}
}
?>
</code>```

However I'd like to apply this to a source that uses a div class instead. For ex:

```<code>  <div class="marketdata">
  <span class="market_item market_name">NASDAQ</span>
  <span class="market_item market_price">99999</span>
  <span class="market_item market_price  is-positive ">
   +24.38(0.39%)</span>
</code>```

I figured, maybe just re work the code like this:

```<code>//get all the h2's with an id
$pokemon_row = $pokemon_xpath->query('//marketdata[@class]');
</code>```

However, that doesn't work, it isn't that flexible. I'm needing a new approach to reference the div class. Any thoughts on what it is I need? Really appreciate it!
-Wilson

答:
solved. it's not perfect, but this ACTUALLY IS WORKING</p>

```<code><?php

$doc = new DOMDocument;

// We don't want to bother with white spaces
$doc->preserveWhiteSpace = false;

// Most HTML Developers are chimps and produce invalid markup...
$doc->strictErrorChecking = false;
$doc->recover = true;

$doc->loadHTMLFile('http://www.nbcnews.com/business');

$xpath = new DOMXPath($doc);

$query = "//div[@class='market']";

$entries = $xpath->query($query);
var_dump($entries->item(0)->textContent);

?>
</code>```

Body:
I'm very new to PHP, and I know how to do this for any H2 that has an ID for example, because I stumbled upon a nice example:

<?php
$html = file_get_contents('http://pokemondb.net/evolution'); //get the html
returned from the following url

$pokemon_doc = new DOMDocument();

libxml_use_internal_errors(TRUE); //disable libxml errors

if(!empty($html)){ //if any html is actually returned

$pokemon_doc->loadHTML($html);
libxml_clear_errors(); //remove errors for yucky html

$pokemon_xpath = new DOMXPath($pokemon_doc);

//get all the h2's with an id
$pokemon_row = $pokemon_xpath->query('//h2[@class]');

if($pokemon_row->length > 0){
    foreach($pokemon_row as $row){
        echo $row->nodeValue . "
";
    }
}
}
?>

However I'd like to apply this to a source that uses a div class instead. For ex:

  NASDAQ
  99999

   +24.38(0.39%)

I figured, maybe just re work the code like this:

//get all the h2's with an id
$pokemon_row = $pokemon_xpath->query('//marketdata[@class]');

However, that doesn't work, it isn't that flexible. I'm needing a new approach to reference the div class. Any thoughts on what it is I need? Really appreciate it!
-Wilson

Body:
solved. it's not perfect, but this ACTUALLY IS WORKING

<?php

$doc = new DOMDocument;

// We don't want to bother with white spaces
$doc->preserveWhiteSpace = false;

// Most HTML Developers are chimps and produce invalid markup...
$doc->strictErrorChecking = false;
$doc->recover = true;

$doc->loadHTMLFile('http://www.nbcnews.com/business');

$xpath = new DOMXPath($doc);

$query = "//div[@class='market']";

$entries = $xpath->query($query);
var_dump($entries->item(0)->textContent);

?>


问:
Gradle: Changing configuration of external dependency
We're in the situation where we update commons-collections from version 3 to version 4. As they've changed the group id to commons-collections4 we will end up having 2 versions of commons-collection in the classpath. The version 3 and version 4.
For our development the version 4 should be used. The version 3 will come in through external dependencies so if we have like:

```<code>compile ("org.hibernate:hibernate-entitymanager:3.5.6-Final")
</code>```

the version 3, which will come in through hibernate-entitymanager, will also be available at compile time. So the developers could use it.

Is there a way to say "commons-collections 3 should now be considered as runtime dependency when it comes through hibernate-entitymanager"?

We're using Gradle 3.5.

答:
Thanks to webdizz who brings me to that idea it seems that I managed it by doing the following:</p>

```<code>configurations.compileClasspath.resolutionStrategy {
    dependencySubstitution {
        substitute module('commons-collections:commons-collections') with module("org.apache.commons:commons-collections4:${COMMONS_COLLECTIONS_VERSION}")
    }
}
</code>```

Body:
We're in the situation where we update commons-collections from version 3 to version 4. As they've changed the group id to commons-collections4 we will end up having 2 versions of commons-collection in the classpath. The version 3 and version 4.
For our development the version 4 should be used. The version 3 will come in through external dependencies so if we have like:

compile ("org.hibernate:hibernate-entitymanager:3.5.6-Final")

the version 3, which will come in through hibernate-entitymanager, will also be available at compile time. So the developers could use it.

Is there a way to say "commons-collections 3 should now be considered as runtime dependency when it comes through hibernate-entitymanager"?

We're using Gradle 3.5.

Body:
Thanks to webdizz who brings me to that idea it seems that I managed it by doing the following:

configurations.compileClasspath.resolutionStrategy {
    dependencySubstitution {
        substitute module('commons-collections:commons-collections') with module("org.apache.commons:commons-collections4:${COMMONS_COLLECTIONS_VERSION}")
    }
}