问:
Adjust a UIButton's highlight glow radius size on touch
Background:

The UIButton control has a property “Shows Touch On Highlight” that can be set in the Storyboard. When this option is checked, and the UIButton is touched, a white glow is visible on the UIButton text.

Question:

How can I adjust the radius size of the UIButton glow when touched?

答:
Connect your button to an @IBOutlet and call it button, then you can do that by putting this code inside viewDidLoad method:

```<code>button.layer.shadowColor = UIColor.red.cgColor
button.layer.shadowRadius = 30.0
button.layer.shadowOpacity = 0.9
button.layer.shadowOffset = CGSize.zero
button.layer.masksToBounds = false
</code>```

And you can change the customization in the way you like. Good luck!

Body:
Connect your button to an @IBOutlet and call it button, then you can do that by putting this code inside viewDidLoad method:

button.layer.shadowColor = UIColor.red.cgColor
button.layer.shadowRadius = 30.0
button.layer.shadowOpacity = 0.9
button.layer.shadowOffset = CGSize.zero
button.layer.masksToBounds = false

And you can change the customization in the way you like. Good luck!


来源: stackexchange

问:
onchange event and programmatic input value change conflict on IE
I've noticed that in different versions of Internet Explorer the onchange event is not captured when the value of an input is altered by a js function, behavior that does not occur with other browsers such as Mozilla or Chrome.

Investigating a little I found that the correct operation of onchange in IE is not guaranteed when the value is altered by js:

onchange not fired on IE

onchange not fired when autocomplete is on

Example (test on IE):

function onchangeRequest(){
  console.log('onchange fired');
}

function changeValue (input){
  input.value +=  "hello"
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h4> focus lost doesnt invoke onchangeRequest() </h4>

<input id="valueInput"  onkeyup="changeValue(this);" onchange="onchangeRequest();" />

<h4> focus lost invokes onchangeRequest() </h4>

<input id="valueInput" onchange="onchangeRequest();" /></code>```

I have not found a convincing explanation of the reasons why IE does not solve those situations correctly. Is this a "known bug" which we have to deal with? Is there any official reference where it is stated that IE does not guarantee the correct behavior of onchange event?

答:
I have found that for many years Microsoft followed a strategy whereby it didnt follow the W3C standards in its browser, but the behavior is correct according to IE's own specification:

The onchange event does not fire when the selected option of the select object is changed programmatically.

Reference: MSDN - onchange event

A possible workaround to solve this problem and make your solution cross browser would be:

onfocus: save the input value on a expando property

onblur: call a js function that compares the old value with the current value.

In my real life scenario i need to fire an ajax action just when the input value changed, so using onblur event without comparing changes would result in a lot of unnecessary calls to the backend.

Here is an example:

function onchangeRequest(input){
  if(input.value != input.oldValue){
      console.log('value changed: do ajax request');
  }else{
      console.log('value didnt change');
  }
}

function changeValue (input){
     input.value +=  "add"
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="valueInput" onkeyup="changeValue(this);" onfocus="this.oldValue = this.value;" onblur="onchangeRequest(this);" /></code>```

ContentLicense: CC BY-SA 3.0

Body:
I've noticed that in different versions of Internet Explorer the onchange event is not captured when the value of an input is altered by a js function, behavior that does not occur with other browsers such as Mozilla or Chrome.

Investigating a little I found that the correct operation of onchange in IE is not guaranteed when the value is altered by js:

onchange not fired on IE

onchange not fired when autocomplete is on

Example (test on IE):

function onchangeRequest(){
  console.log('onchange fired');
}

function changeValue (input){
  input.value +=  "hello"
}

 focus lost doesnt invoke onchangeRequest()

<input id="valueInput"  onkeyup="changeValue(this);" onchange="onchangeRequest();" />

 focus lost invokes onchangeRequest()

<input id="valueInput" onchange="onchangeRequest();" />

I have not found a convincing explanation of the reasons why IE does not solve those situations correctly. Is this a "known bug" which we have to deal with? Is there any official reference where it is stated that IE does not guarantee the correct behavior of onchange event?

Body:
I have found that for many years Microsoft followed a strategy whereby it didnt follow the W3C standards in its browser, but the behavior is correct according to IE's own specification:

The onchange event does not fire when the selected option of the select object is changed programmatically.

Reference: MSDN - onchange event

A possible workaround to solve this problem and make your solution cross browser would be:

onfocus: save the input value on a expando property

onblur: call a js function that compares the old value with the current value.

In my real life scenario i need to fire an ajax action just when the input value changed, so using onblur event without comparing changes would result in a lot of unnecessary calls to the backend.

Here is an example:

function onchangeRequest(input){
  if(input.value != input.oldValue){
      console.log('value changed: do ajax request');
  }else{
      console.log('value didnt change');
  }
}

function changeValue (input){
     input.value +=  "add"
 }

<input id="valueInput" onkeyup="changeValue(this);" onfocus="this.oldValue = this.value;" onblur="onchangeRequest(this);" />


问:
Cordova nodejs routing issue
I am new to cordova.

I am trying to build cordova app with nodejs as a backend. When I run the app using browser (cordova run browser) it is redirecting me to http://localhost:8000/index.html which is fine.

My issue is, when I logged in to the website the browser redirects to "http://localhost:8000/home" and gives not found error. I have set the routing from routes.js to "/home" (nodejs backend).

Any help will be appreciated. Thank you.

答:
did you have something for routing the view like </p>

```<code>router.addRoute('name of view',function(){'your code here'})
</code>```

Title: Cordova nodejs routing issue

Body:
did you have something for routing the view like

router.addRoute('name of view',function(){'your code here'})


问:
How can I return null or bool from a function
I have this function:

```<code>public bool GetBoolSetting(Settings setting)
{
    return int.Parse(GetStringSetting(setting)) == 0 ? false : true;
}
</code>```

There is a problem in that GetStringSetting(setting) can return null, "0" or "1".  When it returns a null I get an exception.

Is it possible for me to make the GetBoolSetting function return a null if this happens?

答:
You likely want to use a nullable bool, like so:

```<code>public bool? GetBoolSetting(Settings setting)
{
    var s = GetStringSetting(setting);
    if (string.IsNullOrEmpty(s))
        return null;
    return int.Parse(s) == 0 ? false : true;
}
</code>```

Or, if you'd rather treat null as false:

```<code>public bool GetBoolSetting(Settings setting)
{
    var s = GetStringSetting(setting);
    if (string.IsNullOrEmpty(s))
        return false;
    return int.Parse(s) == 0 ? false : true;
}
</code>```

Also, consider using TryParse rather than Parse.

Body:
I have this function:

public bool GetBoolSetting(Settings setting)
{
    return int.Parse(GetStringSetting(setting)) == 0 ? false : true;
}

There is a problem in that GetStringSetting(setting) can return null, "0" or "1".  When it returns a null I get an exception.

Is it possible for me to make the GetBoolSetting function return a null if this happens?

Body:
You likely want to use a nullable bool, like so:

public bool? GetBoolSetting(Settings setting)
{
    var s = GetStringSetting(setting);
    if (string.IsNullOrEmpty(s))
        return null;
    return int.Parse(s) == 0 ? false : true;
}

Or, if you'd rather treat null as false:

public bool GetBoolSetting(Settings setting)
{
    var s = GetStringSetting(setting);
    if (string.IsNullOrEmpty(s))
        return false;
    return int.Parse(s) == 0 ? false : true;
}

Also, consider using TryParse rather than Parse.


问:
Find which phrases have at most one capital letter
I am using RegEx (php) to find out which Addresses have one or less capital letters. For example:

av. St Joan 128 (Not match)

Av. st joan 122 (match)

av. St joan 212 (match)

Av. St.joan 121 (Not match)

AV. st joan 232 (Not match)

答:
Using preg_grep:

```<code>$strings = [
    'av. St Joan 128',
    'Av. st joan 122',
    'av. St joan 212',
    'Av. St.joan 121',
    'AV. st joan 232'
];

$results = preg_grep('~^[^A-Z]*[A-Z]?[^A-Z]*$~', $strings);
</code>```

The pattern is simple and describes a whole string (using anchors to figure the beginning and the end of the string).

Breakdown:

```<code>^               #match start of the string
[^A-Z]*         #match zero or more (greedily) non-uppercase characters
[A-Z]?          #match zero or one uppercase character
[^A-Z]*         #match zero or more (greedily) non-uppercase characters
$               #match end of the string
</code>```

Meaning, that the string may have unlimited non-uppercase characters, but the uppercase letter can only occur zero or one time.  If the pattern finds a second uppercase character (anywhere), it is instantly a mis-match/fail.

Note that you can also use @bobblebubble pattern with the PREG_GREP_INVERT option to exclude strings that match:

```<code>$result = preg_grep('~[A-Z][^A-Z]*[A-Z]~', $strings, PREG_GREP_INVERT);
</code>```

Body:
Using preg_grep:

$strings = [
    'av. St Joan 128',
    'Av. st joan 122',
    'av. St joan 212',
    'Av. St.joan 121',
    'AV. st joan 232'
];

$results = preg_grep('~^[^A-Z]*[A-Z]?[^A-Z]*$~', $strings);

The pattern is simple and describes a whole string (using anchors to figure the beginning and the end of the string).

Breakdown:

^               #match start of the string
[^A-Z]*         #match zero or more (greedily) non-uppercase characters
[A-Z]?          #match zero or one uppercase character
[^A-Z]*         #match zero or more (greedily) non-uppercase characters
$               #match end of the string

Meaning, that the string may have unlimited non-uppercase characters, but the uppercase letter can only occur zero or one time.  If the pattern finds a second uppercase character (anywhere), it is instantly a mis-match/fail.

Note that you can also use @bobblebubble pattern with the PREG_GREP_INVERT option to exclude strings that match:

$result = preg_grep('~[A-Z][^A-Z]*[A-Z]~', $strings, PREG_GREP_INVERT);


问:
Symfony \ Component \ Debug \ Exception \ FatalErrorException syntax error, unexpected end of file (Laravel)
The master.blade.php's file contains:

```<code>@section('content')
  @foreach($admons as $admon)
    <p>{{ $admons->admon }}</p>
  @foreach
@stop
</code>```

and it is throwing me the error:

```<code>Symfony \ Component \ Debug \ Exception \ FatalErrorException
syntax error, unexpected end of file
</code>```

C:\AppServ\www\Viniza\app\storage\views\b48f03c3d0a952af7b5dd24750898f94

```<code> $(document).ready(function() {
$('ul.sf-menu').sooperfish();
$('.top').click(function() {$('html, body').animate({scrollTop:0}, 'fast'); return false;});
});
</script>
</body>
</html>
</code>```

the full content of master.blade.php's file is:

```<code>{{ HTML::style('css/style.css') }}
{{ HTML::script('js/jquery.js') }}

@section('content')
  @foreach($admons as $admon)
    <p>{{ $admons->admon }}</p>
  @foreach
@stop

<!DOCTYPE HTML>
<html>

<head>
  <title>Viniza Konw</title>
  <meta name="keywords" content="coffee buy shop" />
  <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
</head>

<body>
  <div id="main">
    <header>
      <div id="logo">
        <div id="logo_text">
          <h1><a href="index.html">Coffe<span class="logo_colour">JuanValdez</span></a></h1>
        </div>
      </div>
      <nav>
        <div id="menu_container">
          <ul class="sf-menu" id="nav">
            <li><a href="#">Home</a></li>
          </ul>
        </div>
      </nav>
    </header>

    <div id="site_content">
      <div class="content">
        <h1></h1>

        <div class="header_image">
          {{ HTML::image('images/header_image.jpg', "Imagen no encontrada",
            array('id' => 'center', 'title' => 'center')) }}
        </div>

        <div class="border_top"></div>
        <div class="border_bottom"></div>

      </div>
    </div>
    <div id="scroll">
      <a title="Scroll to the top" class="top" href="#"><img src="images/top.png" alt="top" /></a>
    </div>
    <footer>
      <p><img src="images/twitter.png" alt="twitter" />
         <img src="images/facebook.png" alt="facebook" />
         <img src="images/rss.png" alt="rss" />           </p>
      <p>Copyright © CSS3_winter_scene | <a href="http://www.css3templates.co.uk">design from css3templates.co.uk</a></p>
    </footer>
  </div>
  <!-- javascript at the bottom for fast page loading -->
  <script type="text/javascript" src="js/jquery.js"></script>
  <script type="text/javascript" src="js/jquery.easing-sooper.js"></script>
  <script type="text/javascript" src="js/jquery.sooperfish.js"></script>
  <script type="text/javascript">
    $(document).ready(function() {
      $('ul.sf-menu').sooperfish();
      $('.top').click(function() {$('html, body').animate({scrollTop:0}, 'fast'); return false;});
    });
  </script>
</body>
</html>
</code>```

答:
In my case, it was the silliest mistake. I missed out a ; while creating a route with a closure function.

So, if you've not made any mistakes as pointed out by above 2 answers, look for any syntax error in your routes\web.php (Laravel 5.3+)

Body:
The master.blade.php's file contains:

@section('content')
  @foreach($admons as $admon)

{{ $admons->admon }}

  @foreach
@stop

and it is throwing me the error:

Symfony \ Component \ Debug \ Exception \ FatalErrorException
syntax error, unexpected end of file

C:\AppServ\www\Viniza\app\storage\views\b48f03c3d0a952af7b5dd24750898f94

 $(document).ready(function() {
$('ul.sf-menu').sooperfish();
$('.top').click(function() {$('html, body').animate({scrollTop:0}, 'fast'); return false;});
});
</script>

the full content of master.blade.php's file is:

{{ HTML::style('css/style.css') }}
{{ HTML::script('js/jquery.js') }}

@section('content')
  @foreach($admons as $admon)

{{ $admons->admon }}

  @foreach
@stop

<!DOCTYPE HTML>

  <title>Viniza Konw</title>
  <meta name="keywords" content="coffee buy shop" />
  <meta http-equiv="content-type" content="text/html; charset=UTF-8" />

CoffeJuanValdez

Home

          {{ HTML::image('images/header_image.jpg', "Imagen no encontrada",
            array('id' => 'center', 'title' => 'center')) }}

Copyright © CSS3_winter_scene | design from css3templates.co.uk


问:
Query returns no result (Delphi, Oracle, DBExpress)
I am trying to get the query result from the Oracle sql server and insert it in the StringGridShowPapers table.

I have SQLConnection1 (a DBExpress connection) set up and working, SQLDataSetPapers DataSet and a query SQLQueryPapers.

When I am running this procedure, the query seems to return nothing:

```<code>procedure TFormOperator.TabSheetShowPapersShow(Sender: TObject);
begin
    SQLQueryShowPapers.SQL.Text := 'SELECT * FROM papers';
    SQLQueryShowPapers.Open;
    SQLQueryShowPapers.First;

    if (NOT SQLQueryShowPapers.IsEmpty) then begin
        SQLQueryShowPapers.First;
        StringGridShowPapers.RowCount := 2;

        while (NOT SQLQueryShowPapers.EOF) do begin
            if (SQLQueryShowPapers.Fields[2].AsString = Frame11.ID) then begin
                with StringGridShowPapers do begin
                  Cells[0, (StringGridShowPapers.RowCount - 1)] :=
                    SQLQueryShowPapers.Fields[0].AsString;
                  Cells[1, (StringGridShowPapers.RowCount - 1)] :=
                    SQLQueryShowPapers.Fields[1].AsString;
                  Cells[2, (StringGridShowPapers.RowCount - 1)] :=
                    SQLQueryShowPapers.Fields[2].AsString;
                end;
                SQLQueryShowPapers.Next;
                StringGridShowPapers.RowCount := StringGridShowPapers.RowCount + 1;
            end;
        end;
    end;

end;
</code>```

Frame11.ID contains a string value  of a number.

Running the same query SELECT * FROM papers in oracle SQL Developer results a number of rows.

What could trigger the problem?

Thanks in advance!

Looks like i found the solution:

It looks like the some (global) variables and properties in Delphi are inaccessable or simply cleaned up after the procedure that assigns them is finished. So you may need to assign first form value to a global variable of second one (that you use this value in) in a runtime of the first form procedure.

答:
You have a couple of flaws in your code.

First, you don't need IsEmpty, and you don't need either call to First. When you first open a query, the dataset is automatically set at the first row, and you can omit IsEmpty if you know you're going to iterate over the rows.

Second, you should never SELECT without a WHERE clause and then filter the data afterward. The only reason to SELECT without a WHERE is if you're absolutely certain you need every single row (and column) from the table. If you don't, add a WHERE in order to limit the number of rows that are returned from the server (and to avoid having to write so much code to filter it on the client side).

Try something like this instead. I don't know what datatype Fields[2] or Frame11.ID are, so I'm going to treat them as string as your existing code does. If they're not strings, then change both references to the actual data type needed. I'm also going to presume that Fields[2].FieldName is ID; again, if it's not, change the code accordingly.

```<code>procedure TFormOperator.TabSheetShowPapersShow(Sender: TObject);
var
  GridRow: Integer;
begin
  SQLQueryShowPapers.SQL.Text := 'SELECT * FROM papers WHERE ID = :ID';
  SQLQueryShowPapers.Parameters.ParamByName('ID').Value := Frame11.ID;
  SQLQueryShowPapers.Open;  // No need for First. Happens automatically

  StringGridShowPapers.RowCount := 1;

  // No need for IsEmpty. If no rows were returned, this loop will not be entered
  while not SQLQueryShowPapers.EOF do
  begin
    StringGridShowPapers.RowCount := StringGridShowPapers.RowCount + 1;
    GridRow := StringGridShowPapers.RowCount - 1;

    StringGridShowPapers.Cells[0, GridRow] := SQLQueryShowPapers.Fields[0].AsString;
    StringGridShowPapers.Cells[1, GridRow] := SQLQueryShowPapers.Fields[1].AsString;
    StringGridShowPapers.Cells[2, GridRow] := SQLQueryShowPapers.Fields[2].AsString;
    SQLQueryShowPapers.Next;
  end;
end;
</code>```

As an aside, I'd do a couple of things:

Most importantly, stop using SELECT * and actually list the columns you need. It's easier to maintain the code, and it reduces overhead of moving data from the server across the network that you're not going to use.

Also, stop using hard-coded references to field positions (Fields[0], Fields[1], etc.). It's error prone, it will bite you in the backside when a column changes in the future, and it makes the code impossible to maintain 6 months from now when you don't remember exactly what order the columns are in or someone else needs to work with your code. Either add persistent fields to your query or use FieldByName to retrieve them by name.

Shorten the variable names to avoid typing somewhat. SQLQueryShowPapers, for instance, could just be QryPapers (unless you have some other type of query than a SQL query, that is), and StringGridShowPapers could be GridPapers or PaperGrid.

You'll note I added a local integer variable GridRow to reduce the typing required for all the repeated calls to StringGridShowPapers.RowCount - 1 in every access to Cells.

You'll also note I made it simpler to deal with adding new rows to StringGridShowPapers in the loop.

I also removed the need to test Fields[0].AsString = Frame11.ID by adding a parameter and a WHERE clause to your SQL statement. It also reduces the amount of data that has to pass from the server across the network, reduces the memory requirements of your application, and cuts the amount of time you spend unnecessarily reading rows you won't be using and skipping them (iterations through the loop). In other words, I removed the entire if test.

Lastly, you could reduce this entire code down to three lines (setting the SQL.Text, assigning a value to the parameter, and opening the query) if you got rid of the TStringGrid entirely and used a TDBGrid instead. It's specifically designed to display data from a dataset. All you do is add the TDBGrid to your form in place of the TStringGrid, drop a TDataSource as well, connect the TDBGrid.DataSource to theTDataSourceand theTDataSource.DataSet` to your query. Then open your query as usual, and the grid is automatically populated with the data with zero lines of code.

Body:
I am trying to get the query result from the Oracle sql server and insert it in the StringGridShowPapers table.

I have SQLConnection1 (a DBExpress connection) set up and working, SQLDataSetPapers DataSet and a query SQLQueryPapers.

When I am running this procedure, the query seems to return nothing:

procedure TFormOperator.TabSheetShowPapersShow(Sender: TObject);
begin
    SQLQueryShowPapers.SQL.Text := 'SELECT * FROM papers';
    SQLQueryShowPapers.Open;
    SQLQueryShowPapers.First;

    if (NOT SQLQueryShowPapers.IsEmpty) then begin
        SQLQueryShowPapers.First;
        StringGridShowPapers.RowCount := 2;

        while (NOT SQLQueryShowPapers.EOF) do begin
            if (SQLQueryShowPapers.Fields[2].AsString = Frame11.ID) then begin
                with StringGridShowPapers do begin
                  Cells[0, (StringGridShowPapers.RowCount - 1)] :=
                    SQLQueryShowPapers.Fields[0].AsString;
                  Cells[1, (StringGridShowPapers.RowCount - 1)] :=
                    SQLQueryShowPapers.Fields[1].AsString;
                  Cells[2, (StringGridShowPapers.RowCount - 1)] :=
                    SQLQueryShowPapers.Fields[2].AsString;
                end;
                SQLQueryShowPapers.Next;
                StringGridShowPapers.RowCount := StringGridShowPapers.RowCount + 1;
            end;
        end;
    end;

end;

Frame11.ID contains a string value  of a number.

Running the same query SELECT * FROM papers in oracle SQL Developer results a number of rows.

What could trigger the problem?

Thanks in advance!

Looks like i found the solution:

It looks like the some (global) variables and properties in Delphi are inaccessable or simply cleaned up after the procedure that assigns them is finished. So you may need to assign first form value to a global variable of second one (that you use this value in) in a runtime of the first form procedure.

Body:
You have a couple of flaws in your code.

First, you don't need IsEmpty, and you don't need either call to First. When you first open a query, the dataset is automatically set at the first row, and you can omit IsEmpty if you know you're going to iterate over the rows.

Second, you should never SELECT without a WHERE clause and then filter the data afterward. The only reason to SELECT without a WHERE is if you're absolutely certain you need every single row (and column) from the table. If you don't, add a WHERE in order to limit the number of rows that are returned from the server (and to avoid having to write so much code to filter it on the client side).

Try something like this instead. I don't know what datatype Fields[2] or Frame11.ID are, so I'm going to treat them as string as your existing code does. If they're not strings, then change both references to the actual data type needed. I'm also going to presume that Fields[2].FieldName is ID; again, if it's not, change the code accordingly.

procedure TFormOperator.TabSheetShowPapersShow(Sender: TObject);
var
  GridRow: Integer;
begin
  SQLQueryShowPapers.SQL.Text := 'SELECT * FROM papers WHERE ID = :ID';
  SQLQueryShowPapers.Parameters.ParamByName('ID').Value := Frame11.ID;
  SQLQueryShowPapers.Open;  // No need for First. Happens automatically

  StringGridShowPapers.RowCount := 1;

  // No need for IsEmpty. If no rows were returned, this loop will not be entered
  while not SQLQueryShowPapers.EOF do
  begin
    StringGridShowPapers.RowCount := StringGridShowPapers.RowCount + 1;
    GridRow := StringGridShowPapers.RowCount - 1;

    StringGridShowPapers.Cells[0, GridRow] := SQLQueryShowPapers.Fields[0].AsString;
    StringGridShowPapers.Cells[1, GridRow] := SQLQueryShowPapers.Fields[1].AsString;
    StringGridShowPapers.Cells[2, GridRow] := SQLQueryShowPapers.Fields[2].AsString;
    SQLQueryShowPapers.Next;
  end;
end;

As an aside, I'd do a couple of things:

Most importantly, stop using SELECT * and actually list the columns you need. It's easier to maintain the code, and it reduces overhead of moving data from the server across the network that you're not going to use.

Also, stop using hard-coded references to field positions (Fields[0], Fields[1], etc.). It's error prone, it will bite you in the backside when a column changes in the future, and it makes the code impossible to maintain 6 months from now when you don't remember exactly what order the columns are in or someone else needs to work with your code. Either add persistent fields to your query or use FieldByName to retrieve them by name.

Shorten the variable names to avoid typing somewhat. SQLQueryShowPapers, for instance, could just be QryPapers (unless you have some other type of query than a SQL query, that is), and StringGridShowPapers could be GridPapers or PaperGrid.

You'll note I added a local integer variable GridRow to reduce the typing required for all the repeated calls to StringGridShowPapers.RowCount - 1 in every access to Cells.

You'll also note I made it simpler to deal with adding new rows to StringGridShowPapers in the loop.

I also removed the need to test Fields[0].AsString = Frame11.ID by adding a parameter and a WHERE clause to your SQL statement. It also reduces the amount of data that has to pass from the server across the network, reduces the memory requirements of your application, and cuts the amount of time you spend unnecessarily reading rows you won't be using and skipping them (iterations through the loop). In other words, I removed the entire if test.

Lastly, you could reduce this entire code down to three lines (setting the SQL.Text, assigning a value to the parameter, and opening the query) if you got rid of the TStringGrid entirely and used a TDBGrid instead. It's specifically designed to display data from a dataset. All you do is add the TDBGrid to your form in place of the TStringGrid, drop a TDataSource as well, connect the TDBGrid.DataSource to theTDataSourceand theTDataSource.DataSet` to your query. Then open your query as usual, and the grid is automatically populated with the data with zero lines of code.


问:
How to label duplicate groups in pandas?
I have a DataFrame:

```<code>>>> df
     A
0  foo
1  bar
2  foo
3  baz
4  foo
5  bar
</code>```

I need to find all the duplicate groups and label them with sequential dgroup_id's:

```<code>>>> df
     A  dgroup_id
0  foo          1
1  bar          2
2  foo          1
3  baz
4  foo          1
5  bar          2
</code>```

(This means that foo belongs to the first group of duplicates, bar to the second group of duplicates, and baz is not duplicated.)

I did this:

```<code>import pandas as pd

df = pd.DataFrame({'A': ('foo', 'bar', 'foo', 'baz', 'foo', 'bar')})

duplicates = df.groupby('A').size()
duplicates = duplicates[duplicates>1]
# Yes, this is ugly, but I didn't know how to do it otherwise:
duplicates[duplicates.reset_index().index] = duplicates.reset_index().index
df.insert(1, 'dgroup_id', df['A'].map(duplicates))
</code>```

This leads to:

```<code>>>> df
     A  dgroup_id
0  foo        1.0
1  bar        0.0
2  foo        1.0
3  baz        NaN
4  foo        1.0
5  bar        0.0
</code>```

Is there a simpler/shorter way to achieve this in pandas? I read that maybe pandas.factorize could be of help here, but I don't know how to use it... (the pandas documentation on this function is of no help)

Also: I don't mind neither the 0-based group count, nor the weird sorting order; but I would like to have the dgroup_id's as ints, not floats.

答:
You could go for:</p>

```<code>import pandas as pd
import numpy as np
df = pd.DataFrame(['foo', 'bar', 'foo', 'baz', 'foo', 'bar',], columns=['name'])

# Create the groups order
ordered_names = df['name'].drop_duplicates().tolist()   # ['foo', 'bar', 'baz']

# Find index of each element in the ordered list
df['duplication_index'] = df['name'].apply(lambda x: ordered_names.index(x) + 1)

# Discard non-duplicated entries
df.loc[~df['name'].duplicated(keep=False), 'duplication_index'] = np.nan

print(df)
#   name  duplication_index
# 0  foo                1.0
# 1  bar                2.0
# 2  foo                1.0
# 3  baz                NaN
# 4  foo                1.0
# 5  bar                2.0
</code>```

Body:
I have a DataFrame:

>>> df
     A
0  foo
1  bar
2  foo
3  baz
4  foo
5  bar

I need to find all the duplicate groups and label them with sequential dgroup_id's:

>>> df
     A  dgroup_id
0  foo          1
1  bar          2
2  foo          1
3  baz
4  foo          1
5  bar          2

(This means that foo belongs to the first group of duplicates, bar to the second group of duplicates, and baz is not duplicated.)

I did this:

import pandas as pd

df = pd.DataFrame({'A': ('foo', 'bar', 'foo', 'baz', 'foo', 'bar')})

duplicates = df.groupby('A').size()
duplicates = duplicates[duplicates>1]
# Yes, this is ugly, but I didn't know how to do it otherwise:
duplicates[duplicates.reset_index().index] = duplicates.reset_index().index
df.insert(1, 'dgroup_id', df['A'].map(duplicates))

This leads to:

>>> df
     A  dgroup_id
0  foo        1.0
1  bar        0.0
2  foo        1.0
3  baz        NaN
4  foo        1.0
5  bar        0.0

Is there a simpler/shorter way to achieve this in pandas? I read that maybe pandas.factorize could be of help here, but I don't know how to use it... (the pandas documentation on this function is of no help)

Also: I don't mind neither the 0-based group count, nor the weird sorting order; but I would like to have the dgroup_id's as ints, not floats.

Body:
You could go for:

import pandas as pd
import numpy as np
df = pd.DataFrame(['foo', 'bar', 'foo', 'baz', 'foo', 'bar',], columns=['name'])

# Create the groups order
ordered_names = df['name'].drop_duplicates().tolist()   # ['foo', 'bar', 'baz']

# Find index of each element in the ordered list
df['duplication_index'] = df['name'].apply(lambda x: ordered_names.index(x) + 1)

# Discard non-duplicated entries
df.loc[~df['name'].duplicated(keep=False), 'duplication_index'] = np.nan

print(df)
#   name  duplication_index
# 0  foo                1.0
# 1  bar                2.0
# 2  foo                1.0
# 3  baz                NaN
# 4  foo                1.0
# 5  bar                2.0


问:
From multiple filter to single filter
Hi I am new to Rails and currently working on a project my teacher gave me.
I have this code which filters my card via checkboxes. The only problem is, that you can select multiple categories meaning that you can filter through multiple things.

But I only want this code to be able to filter one category each time.
It should only show me the cards for this category and if i select another category it should show me the corresponding cards.

Those are my filters:

    <form id="filters">
      <% @categories.each do |categ| %>

          <input type="checkbox" name='<%= categ %>' id='<%= categ %>'>
          <label class="index-category" for='<%= categ %>'>
            <% if categ == "Social Media" %>

            <% elsif categ == "Content" %>

            <% elsif categ == "Research" %>

            <% else %>

            <% end %>
          <%= categ %>

      <% end %>
    </form>

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

<p>My cards are divs with the class .selectable-cards</p>

```
My Cards

```

<p>And this is my Javascript for the filter</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function() {
  $('#filters input:checkbox').change(function () {
    var selectedCategoryNames = $('#filters input:checkbox:checked').map(function () {
      return $(this).attr('name')
    }).toArray();

    cards = $('.selectable-card');
    cards.hide()
    cards.each(function() {
      if (selectedCategoryNames.includes($(this).attr('data-category'))) $(this).delay(100).fadeIn(300);
    });

    if (selectedCategoryNames.length === 0) cards.show();
  });
});</code>```

答:
Ok i figured it out. All i had to do was add this line of code:</p>

```<code>$('#filters input:checkbox').not(this).prop('checked', false);
</code>```

Title: From multiple filter to single filter

Body:
Hi I am new to Rails and currently working on a project my teacher gave me.
I have this code which filters my card via checkboxes. The only problem is, that you can select multiple categories meaning that you can filter through multiple things.

But I only want this code to be able to filter one category each time.
It should only show me the cards for this category and if i select another category it should show me the corresponding cards.

Those are my filters:

    <form id="filters">
      <% @categories.each do |categ| %>

          <input type="checkbox" name='<%= categ %>' id='<%= categ %>'>
          <label class="index-category" for='<%= categ %>'>
            <% if categ == "Social Media" %>

            <% elsif categ == "Content" %>

            <% elsif categ == "Research" %>

            <% else %>

            <% end %>
          <%= categ %>

      <% end %>
    </form>

My cards are divs with the class .selectable-cards

My Cards

And this is my Javascript for the filter

$(document).ready(function() {
  $('#filters input:checkbox').change(function () {
    var selectedCategoryNames = $('#filters input:checkbox:checked').map(function () {
      return $(this).attr('name')
    }).toArray();

    cards = $('.selectable-card');
    cards.hide()
    cards.each(function() {
      if (selectedCategoryNames.includes($(this).attr('data-category'))) $(this).delay(100).fadeIn(300);
    });

    if (selectedCategoryNames.length === 0) cards.show();
  });
});

Body:
Ok i figured it out. All i had to do was add this line of code:

$('#filters input:checkbox').not(this).prop('checked', false);


答:
In C#, like most languages, regular booleans are not nullable. You can however use nullable types to get the result you want.

For example, if you want a method to be able to return true, false, or null, you specify a nullable bool as it's return type:

```<code>public bool? MyMethod()
{
    // Stuff
}
</code>```

Notice the ? after bool. That specifies that the boolean is nullable.

So in your case you could do:

```<code>public bool? GetBoolSetting(Settings setting)
{
    string myString = GetStringSetting(setting));
    if (string.IsNullOrEmpty(myString))
        return null;
    return int.Parse(myString) != 0;
}
</code>```

Be advised however, working with types like nullable bools is tricky. For example, if you try to pass this method's result to another method which takes a bool parameter, you will not be able to right away.

```<code>public void MyBoolMethod(bool parameter)
{
}

MyBoolMethod(MyMethod()); // This doesn't compile
</code>```

You will have to cast your nullable boolean to a normal one, after of course making sure that it is not null:

```<code>MyBoolMethod((bool)MyMethod());
</code>```

..or alternatively, decide on a default value for this case (what the bool? should become if it is null so that it can be used elsewhere), and convert it.

Example with false as the default:

```<code>bool newBool = MyMethod() ?? false;
</code>```

An extra piece of advice, which has little to do with your question but I recommend you do. Instead of the unsafe int.Parse, which throws an exception if the provided string isn't valid, switch to Int32.TryParse:

```<code>public bool? GetBoolSetting(Settings setting)
{
    string myString = GetStringSetting(setting));
    int output = -1;
    if (string.IsNullOrEmpty(myString) || !int.TryParse(myString, out output))
        return null;
    return output != 0;
}
</code>```

Title: How can I return null or bool from a function

Body:
In C#, like most languages, regular booleans are not nullable. You can however use nullable types to get the result you want.

For example, if you want a method to be able to return true, false, or null, you specify a nullable bool as it's return type:

public bool? MyMethod()
{
    // Stuff
}

Notice the ? after bool. That specifies that the boolean is nullable.

So in your case you could do:

public bool? GetBoolSetting(Settings setting)
{
    string myString = GetStringSetting(setting));
    if (string.IsNullOrEmpty(myString))
        return null;
    return int.Parse(myString) != 0;
}

Be advised however, working with types like nullable bools is tricky. For example, if you try to pass this method's result to another method which takes a bool parameter, you will not be able to right away.

public void MyBoolMethod(bool parameter)
{
}

MyBoolMethod(MyMethod()); // This doesn't compile

You will have to cast your nullable boolean to a normal one, after of course making sure that it is not null:

MyBoolMethod((bool)MyMethod());

..or alternatively, decide on a default value for this case (what the bool? should become if it is null so that it can be used elsewhere), and convert it.

Example with false as the default:

bool newBool = MyMethod() ?? false;

An extra piece of advice, which has little to do with your question but I recommend you do. Instead of the unsafe int.Parse, which throws an exception if the provided string isn't valid, switch to Int32.TryParse:

public bool? GetBoolSetting(Settings setting)
{
    string myString = GetStringSetting(setting));
    int output = -1;
    if (string.IsNullOrEmpty(myString) || !int.TryParse(myString, out output))
        return null;
    return output != 0;
}


问:
What is the preferred way of working with run-time created instances?
I am writing a service that will collect a great number of values and build large structures around them. For some of these, lookup tables are needed, and due to memory constraints I do not want to copy the key or value passed to the HashMap. However, using references gets me into trouble with the borrow checker (see example below). What is the preferred way of working with run-time created instances?

```<code>use std::collections::HashMap;

#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)]
struct LargeKey;
struct LargeValue;

fn main() {
    let mut lots_of_lookups: HashMap<&LargeKey, &LargeValue> = HashMap::new();
    let run_time_created_key = LargeKey;
    let run_time_created_value = LargeValue;
    lots_of_lookups.insert(&run_time_created_key, &run_time_created_value);
    lots_of_lookups.clear();
}
</code>```

I was expecting clear() to release the borrows, but even if it actually does so, perhaps the compiler cannot figure that out?

答:
Also, I was expecting clear() to release the borrows, but even if it actually does so, perhaps the compiler cannot figure that out?

At the moment, borrowing is purely scope based. Only a method which consumes the borrower can revoke the borrow, which is not always ideal.

What is the preferred way of working with shared run-time created instances?

The simplest way to expressed shared ownership is to use shared ownership. It does come with some syntactic overhead, however it would greatly simplify reasoning.

In Rust, there are two simple standard ways of expressing shared ownership:

Rc<RefCell<T>>, for sharing within a thread,

Arc<Mutex<T>>, for sharing across threads.

There are some variations (using Cell instead of RefCell or RWLock instead of Mutex), however those are the basics.

Beyond syntactic overhead, there's also some amount of run-time overhead going into (a) increasing/decreasing the reference count whenever you make a clone and (b) checking/marking/clearing the usage flag when accessing the wrapped instance of T.

There is one non-negligible downside to this approach, though. The borrowing rules are now checked at runtime instead of compile time, and therefore violations lead to panic instead of compile time errors.

Body:
I am writing a service that will collect a great number of values and build large structures around them. For some of these, lookup tables are needed, and due to memory constraints I do not want to copy the key or value passed to the HashMap. However, using references gets me into trouble with the borrow checker (see example below). What is the preferred way of working with run-time created instances?

use std::collections::HashMap;

#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)]
struct LargeKey;
struct LargeValue;

fn main() {
    let mut lots_of_lookups: HashMap<&LargeKey, &LargeValue> = HashMap::new();
    let run_time_created_key = LargeKey;
    let run_time_created_value = LargeValue;
    lots_of_lookups.insert(&run_time_created_key, &run_time_created_value);
    lots_of_lookups.clear();
}

I was expecting clear() to release the borrows, but even if it actually does so, perhaps the compiler cannot figure that out?


问:
Android start activity when app started
This android project is about Webview.
It start the activity when it click some button called goURL.
but is it possible to start some activity when the app started?(not activity from the button).
my guess is put something on onCreate

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

}

public void goURL(View view){
    TextView tvURL = (TextView)findViewById(R.id.txtURL);
    String url = tvURL.getText().toString();
    Log.i("URL", "Opening URL with WebView :" + url);

    final long startTime = System.currentTimeMillis();
    WebView webView = (WebView)findViewById(R.id.webView);

//webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);

webView.loadUrl(url);
</code>```

My guess is that to create intent about view.
but not sure how to do it

答: You define in your Manifest.xml (or in Android Studio) which activity will be your MainActivity, which in turn is opened first, which then calls the onCreate method.</p>

Title: Android start activity when app started

Body:
This android project is about Webview.
It start the activity when it click some button called goURL.
but is it possible to start some activity when the app started?(not activity from the button).
my guess is put something on onCreate

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

}

public void goURL(View view){
    TextView tvURL = (TextView)findViewById(R.id.txtURL);
    String url = tvURL.getText().toString();
    Log.i("URL", "Opening URL with WebView :" + url);

    final long startTime = System.currentTimeMillis();
    WebView webView = (WebView)findViewById(R.id.webView);

//webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);

webView.loadUrl(url);

My guess is that to create intent about view.
but not sure how to do it


答: You can directly put the code in onCreate() function.</p>

Title: Android start activity when app started


问:
Can an Iframe load its contents at the server side rather than client side?
I know that setting runat="server" and specifying an id for an iframe control, makes it accessible on the server side but what I need is that the iframe source contents get loaded at server side not client side.

Is it possible?

Why do I need it this way?

Currently my iframe source site is configured for ntlm authentication and sso which means it would read my windows credentials whereas I'd need it reads the credentials provided by the site which hosts that iframe.

Thanks

答: No, setting the runat="server" attribute of the iframe tag will allow you to modify it's attributes on the server side but the source of the iframe will still be downloaded from the client.</p>

ContentLicense: CC BY-SA 2.5


问:
how can i use the same number for all the calculations
```<code>import java.util.Scanner;
public class Calculator
{
    public static void main(String args[])
    {
        System.out.println("Enter the numbers only ");
        Scanner num =new Scanner(System.in);
        System.out.println("Enter the number of times you want to run loop ");
        Scanner loop =new Scanner(System.in);
        int n =loop.nextInt();
        while(n!=0)
        {
            System.out.println("Enter the Cases  1 for addition,2 for Subtraction,3 for Division 4 for multipication and 5 for reaminder  ");
            Scanner cas =new Scanner(System.in);
            int c = cas.nextInt();
            double calc,first,second;
            switch (c)
            {
            case 1:
                System.out.println("addition of two number is ");
                first = num.nextDouble();
                second=num.nextDouble();
                calc = first + second;
                System.out.println(calc);
                break;
            case 2:
                System.out.println("subtraction of two number is ");
                first = num.nextDouble();
                second = num.nextDouble();
                calc = first - second;
                System.out.println(calc);
                break;
            case 3:
                System.out.println("division of two number is ");
                first = num.nextDouble();
                second = num.nextDouble();
                calc = first / second;
                System.out.println(calc);
                break;
            case 4:
                System.out.println("multipication of two number is ");
                first = num.nextDouble();
                second = num.nextDouble();
                calc = first * second;
                System.out.println(calc);
                break;
            case 5:
                System.out.println("remainder of two number is ");
                first = num.nextDouble();
                second = num.nextDouble();
                calc = first % second;
                System.out.println(calc);
                break;
            default:
                System.out.println("you did not enter 1,2,3,4,5 you entered something else ");
            }
        n--;
        }
        System.out.println("the program has end, THANK YOU!!");
    }
}
</code>```

<p>This the java code for calculation by asking user for input. How can i use the same number for all the calculations in this code?it ask user every time for the new number but i want this code to do all the calculation by only one input. </p>

答:
You need to call the

```<code> first = num.nextDouble();
 second = num.nextDouble();
</code>```

only once. Call it where you want the user to enter the numbers.

For your example, you should change it to this:

```<code>import java.util.Scanner;
public class Calculator
{
    public static void main(String args[])
    {
        System.out.println("Enter the numbers only ");
        Scanner num =new Scanner(System.in);
        double first,second;
        first = num.nextDouble();  //Get first number
        second = num.nextDouble(); //Get second number
        System.out.println("Enter the number of times you want to run loop     ");
        Scanner loop =new Scanner(System.in);
        int n =loop.nextInt();
        while(n!=0)
        {
            System.out.println("Enter the Cases  1 for addition,2 for     Subtraction,3 for Division 4 for multipication and 5 for reaminder  ");
            Scanner cas =new Scanner(System.in);
            int c = cas.nextInt();
            double calc;
            switch (c)
            {
            case 1:
                System.out.println("addition of two number is ");
                calc = first + second;
                System.out.println(calc);
                break;
            case 2:
                System.out.println("subtraction of two number is ");
                calc = first - second;
                System.out.println(calc);
                break;
            case 3:
                System.out.println("division of two number is ");
                calc = first / second;
                System.out.println(calc);
                break;
            case 4:
                System.out.println("multipication of two number is ");
                calc = first * second;
                System.out.println(calc);
                break;
            case 5:
                System.out.println("remainder of two number is ");
                calc = first % second;
                System.out.println(calc);
                break;
            default:
                System.out.println("you did not enter 1,2,3,4,5 you entered     something else ");
            }
        n--;
        }
        System.out.println("the program has end, THANK YOU!!");
    }
}
</code>```

Body:
import java.util.Scanner;
public class Calculator
{
    public static void main(String args[])
    {
        System.out.println("Enter the numbers only ");
        Scanner num =new Scanner(System.in);
        System.out.println("Enter the number of times you want to run loop ");
        Scanner loop =new Scanner(System.in);
        int n =loop.nextInt();
        while(n!=0)
        {
            System.out.println("Enter the Cases  1 for addition,2 for Subtraction,3 for Division 4 for multipication and 5 for reaminder  ");
            Scanner cas =new Scanner(System.in);
            int c = cas.nextInt();
            double calc,first,second;
            switch (c)
            {
            case 1:
                System.out.println("addition of two number is ");
                first = num.nextDouble();
                second=num.nextDouble();
                calc = first + second;
                System.out.println(calc);
                break;
            case 2:
                System.out.println("subtraction of two number is ");
                first = num.nextDouble();
                second = num.nextDouble();
                calc = first - second;
                System.out.println(calc);
                break;
            case 3:
                System.out.println("division of two number is ");
                first = num.nextDouble();
                second = num.nextDouble();
                calc = first / second;
                System.out.println(calc);
                break;
            case 4:
                System.out.println("multipication of two number is ");
                first = num.nextDouble();
                second = num.nextDouble();
                calc = first * second;
                System.out.println(calc);
                break;
            case 5:
                System.out.println("remainder of two number is ");
                first = num.nextDouble();
                second = num.nextDouble();
                calc = first % second;
                System.out.println(calc);
                break;
            default:
                System.out.println("you did not enter 1,2,3,4,5 you entered something else ");
            }
        n--;
        }
        System.out.println("the program has end, THANK YOU!!");
    }
}

This the java code for calculation by asking user for input. How can i use the same number for all the calculations in this code?it ask user every time for the new number but i want this code to do all the calculation by only one input.

Body:
You need to call the

 first = num.nextDouble();
 second = num.nextDouble();

only once. Call it where you want the user to enter the numbers.

For your example, you should change it to this:

import java.util.Scanner;
public class Calculator
{
    public static void main(String args[])
    {
        System.out.println("Enter the numbers only ");
        Scanner num =new Scanner(System.in);
        double first,second;
        first = num.nextDouble();  //Get first number
        second = num.nextDouble(); //Get second number
        System.out.println("Enter the number of times you want to run loop     ");
        Scanner loop =new Scanner(System.in);
        int n =loop.nextInt();
        while(n!=0)
        {
            System.out.println("Enter the Cases  1 for addition,2 for     Subtraction,3 for Division 4 for multipication and 5 for reaminder  ");
            Scanner cas =new Scanner(System.in);
            int c = cas.nextInt();
            double calc;
            switch (c)
            {
            case 1:
                System.out.println("addition of two number is ");
                calc = first + second;
                System.out.println(calc);
                break;
            case 2:
                System.out.println("subtraction of two number is ");
                calc = first - second;
                System.out.println(calc);
                break;
            case 3:
                System.out.println("division of two number is ");
                calc = first / second;
                System.out.println(calc);
                break;
            case 4:
                System.out.println("multipication of two number is ");
                calc = first * second;
                System.out.println(calc);
                break;
            case 5:
                System.out.println("remainder of two number is ");
                calc = first % second;
                System.out.println(calc);
                break;
            default:
                System.out.println("you did not enter 1,2,3,4,5 you entered     something else ");
            }
        n--;
        }
        System.out.println("the program has end, THANK YOU!!");
    }
}


问:
JavaScript, Why does function name have no significance in function literals?
I had some doubts for function literals

Why does the function name in function literals have no significance?

Why aren't they important?

Why doesn't the function get invoked when we try to call using the function name in case of function literals?

```<code>var a = function b(){
        //some code
        }
b(); //Doesn't work
</code>```

Why does the name b have no significance but a does?

I am new to JavaScript and a beginner so any help would be appreciated!

答: Name b has significance only inside function. Outside you must call function via a.

Body:
I had some doubts for function literals

Why does the function name in function literals have no significance?

Why aren't they important?

Why doesn't the function get invoked when we try to call using the function name in case of function literals?

var a = function b(){
        //some code
        }
b(); //Doesn't work

Why does the name b have no significance but a does?

I am new to JavaScript and a beginner so any help would be appreciated!


问:
Angular Material Components Not Displayed
I am new to Angular 2 and Angular Material I tried creating one example to check Angular Material but its not working. I am getting empty html page. My code is as follows.

App Component ts:

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
}
</code>```

App Module .ts

```<code>    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    import { AppComponent } from './app.component';
    import {MdSidenavModule,MdMenuModule} from '@angular/material';
    import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
    import {NoopAnimationsModule} from '@angular/platform-browser/animations';
    import 'hammerjs';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    MdSidenavModule,
    BrowserAnimationsModule,
    NoopAnimationsModule,
    MdMenuModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

export class AppModule { }
</code>```

App Component Html;

```<code><!--The whole content below can be removed with the new code.-->

 <link href="https://unpkg.com/@angular/material/prebuilt-themes/indigo-pink.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
 <div>

 <md-sidenav-container>

   <md-sidenav opened="true">
    <button>
     Add
    </button>
   </md-sidenav>
 </md-sidenav-container>

 <md-menu>
  <button md-menu-item> Settings </button>
  <button md-menu-item> Help </button>
</md-menu>
</div>
</code>```

styles.css

```<code>@import "../node_modules/@angular/material/prebuilt-themes/deeppurple-amber.css";
</code>```

My Package.json

```<code>{
  "name": "asyncpipe",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^4.2.6",
    "@angular/cdk": "^2.0.0-beta.8",
    "@angular/common": "^4.0.0",
    "@angular/compiler": "^4.0.0",
    "@angular/core": "^4.0.0",
    "@angular/forms": "^4.0.0",
    "@angular/http": "^4.0.0",
    "@angular/material": "^2.0.0-beta.8",
    "@angular/platform-browser": "^4.0.0",
    "@angular/platform-browser-dynamic": "^4.0.0",
    "@angular/router": "^4.0.0",
    "core-js": "^2.4.1",
    "hammerjs": "^2.0.8",
    "rxjs": "^5.1.0",
    "zone.js": "^0.8.4"
  },
  "devDependencies": {
    "@angular/cli": "1.1.2",
    "@angular/compiler-cli": "^4.0.0",
    "@angular/language-service": "^4.0.0",
    "@types/jasmine": "2.5.45",
    "@types/node": "~6.0.60",
    "codelyzer": "~3.0.1",
    "jasmine-core": "~2.6.2",
    "jasmine-spec-reporter": "~4.1.0",
    "karma": "~1.7.0",
    "karma-chrome-launcher": "~2.1.1",
    "karma-cli": "~1.0.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "protractor": "~5.1.2",
    "ts-node": "~3.0.4",
    "tslint": "~5.3.2",
    "typescript": "~2.3.3"
  }
}
</code>```

My angular-cli.json

```<code>{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "project": {
    "name": "asyncpipe"
  },
  "apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico"
      ],
      "index": "index.html",
      "main": "main.ts",
      "polyfills": "polyfills.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.app.json",
      "testTsconfig": "tsconfig.spec.json",
      "prefix": "app",
      "styles": [
        "styles.css"
      ],
      "scripts": [
        "../node_modules/hammerjs/hammer.min.js"
      ],
      "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    }
  ],
  "e2e": {
    "protractor": {
      "config": "./protractor.conf.js"
    }
  },
  "lint": [
    {
      "project": "src/tsconfig.app.json"
    },
    {
      "project": "src/tsconfig.spec.json"
    },
    {
      "project": "e2e/tsconfig.e2e.json"
    }
  ],
  "test": {
    "karma": {
      "config": "./karma.conf.js"
    }
  },
  "defaults": {
    "styleExt": "css",
    "component": {}
  }
}
</code>```

I have included all dependencies as per mentioned on web. Please help me to resolve this.

答:
I think that the problem is not especially with your code. From your comments I see that you got problem with one of your project dependencies (@angular/platform-browser). There is a bug for that reported in angular:
https://github.com/angular/angular/issues/17400

Try to update your dependencies to the latests one : 4.2.6

To do that you need to run following command:

```<code> npm update
</code>```

To make sure that you are up to date, check version of installed packages:

```<code>npm ls --depth 0
</code>```

You also don't need to import every component seperately, if you have already imported all via MaterialModule.

```<code>@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    MaterialModule,
    BrowserAnimationsModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

Body:
I am new to Angular 2 and Angular Material I tried creating one example to check Angular Material but its not working. I am getting empty html page. My code is as follows.

App Component ts:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
}

App Module .ts

    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    import { AppComponent } from './app.component';
    import {MdSidenavModule,MdMenuModule} from '@angular/material';
    import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
    import {NoopAnimationsModule} from '@angular/platform-browser/animations';
    import 'hammerjs';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    MdSidenavModule,
    BrowserAnimationsModule,
    NoopAnimationsModule,
    MdMenuModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

export class AppModule { }

App Component Html;

 <link href="https://unpkg.com/@angular/material/prebuilt-themes/indigo-pink.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

 <md-sidenav-container>

   <md-sidenav opened="true">
    <button>
     Add
    </button>
   </md-sidenav>
 </md-sidenav-container>

 <md-menu>
  <button md-menu-item> Settings </button>
  <button md-menu-item> Help </button>
</md-menu>

styles.css

@import "../node_modules/@angular/material/prebuilt-themes/deeppurple-amber.css";

My Package.json

{
  "name": "asyncpipe",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^4.2.6",
    "@angular/cdk": "^2.0.0-beta.8",
    "@angular/common": "^4.0.0",
    "@angular/compiler": "^4.0.0",
    "@angular/core": "^4.0.0",
    "@angular/forms": "^4.0.0",
    "@angular/http": "^4.0.0",
    "@angular/material": "^2.0.0-beta.8",
    "@angular/platform-browser": "^4.0.0",
    "@angular/platform-browser-dynamic": "^4.0.0",
    "@angular/router": "^4.0.0",
    "core-js": "^2.4.1",
    "hammerjs": "^2.0.8",
    "rxjs": "^5.1.0",
    "zone.js": "^0.8.4"
  },
  "devDependencies": {
    "@angular/cli": "1.1.2",
    "@angular/compiler-cli": "^4.0.0",
    "@angular/language-service": "^4.0.0",
    "@types/jasmine": "2.5.45",
    "@types/node": "~6.0.60",
    "codelyzer": "~3.0.1",
    "jasmine-core": "~2.6.2",
    "jasmine-spec-reporter": "~4.1.0",
    "karma": "~1.7.0",
    "karma-chrome-launcher": "~2.1.1",
    "karma-cli": "~1.0.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "protractor": "~5.1.2",
    "ts-node": "~3.0.4",
    "tslint": "~5.3.2",
    "typescript": "~2.3.3"
  }
}

My angular-cli.json

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "project": {
    "name": "asyncpipe"
  },
  "apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico"
      ],
      "index": "index.html",
      "main": "main.ts",
      "polyfills": "polyfills.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.app.json",
      "testTsconfig": "tsconfig.spec.json",
      "prefix": "app",
      "styles": [
        "styles.css"
      ],
      "scripts": [
        "../node_modules/hammerjs/hammer.min.js"
      ],
      "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    }
  ],
  "e2e": {
    "protractor": {
      "config": "./protractor.conf.js"
    }
  },
  "lint": [
    {
      "project": "src/tsconfig.app.json"
    },
    {
      "project": "src/tsconfig.spec.json"
    },
    {
      "project": "e2e/tsconfig.e2e.json"
    }
  ],
  "test": {
    "karma": {
      "config": "./karma.conf.js"
    }
  },
  "defaults": {
    "styleExt": "css",
    "component": {}
  }
}

I have included all dependencies as per mentioned on web. Please help me to resolve this.

Body:
I think that the problem is not especially with your code. From your comments I see that you got problem with one of your project dependencies (@angular/platform-browser). There is a bug for that reported in angular:
https://github.com/angular/angular/issues/17400

Try to update your dependencies to the latests one : 4.2.6

To do that you need to run following command:

 npm update

To make sure that you are up to date, check version of installed packages:

npm ls --depth 0

You also don't need to import every component seperately, if you have already imported all via MaterialModule.

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    MaterialModule,
    BrowserAnimationsModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

ContentLicense: CC BY-SA 4.0


问:
How to stop the error message, If JSON file failed to open stream
This is the error, i am getting

Warning: file_get_contents(https://api.themoviedb.org/3/movie/39740?api_key=522cec78237f49axxxxxxxxxxx6d1e0c834a): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found

Now, you may founder, what is inside that link?

That page contain this line only

{"status_code":34,"status_message":"The resource you requested could not be found."}

So, I think this is a valid page (which i can open in browser). I just want PHP to stop giving this error, if it failed to open stream.

This is my JSON code

```<code> $response = file_get_contents("https://api.themoviedb.org/3/movie/".$requestsDone."?api_key=522cec782xxxx6f6d1e0c834a");
if ($response != FALSE) {
    $response = json_decode($response, true);
}
</code>```

Edit: It is not duplicate of that question. That question is related to email and password, where mine is not

答:
Try to use curl to get the http response code and act when it's 404</p>

```<code><?php
// create a new cURL resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "https://api.themoviedb.org/3/movie/39740?api_key=522cec78237f49axxxxxxxxxxx6d1e0c834a");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$responsejson = curl_exec($ch);
switch ($http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE)) {
   case 200:  # OK
    // do your normal process
    $response = json_decode($responsejson, true);
   break;
  case 404:
    // do your thing for not found situation
   $response = 'Not found';
  break;
  case 401:
    // not allowed
   $response = 'api key wrong?';
  break;
 default:
  echo 'Unexpected HTTP code: ', $http_code, "\n";
 }
}

// close cURL resource, and free up system resources
curl_close($ch);
?>
</code>```

Body:
This is the error, i am getting

Warning: file_get_contents(https://api.themoviedb.org/3/movie/39740?api_key=522cec78237f49axxxxxxxxxxx6d1e0c834a): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found

Now, you may founder, what is inside that link?

That page contain this line only

{"status_code":34,"status_message":"The resource you requested could not be found."}

So, I think this is a valid page (which i can open in browser). I just want PHP to stop giving this error, if it failed to open stream.

This is my JSON code

 $response = file_get_contents("https://api.themoviedb.org/3/movie/".$requestsDone."?api_key=522cec782xxxx6f6d1e0c834a");
if ($response != FALSE) {
    $response = json_decode($response, true);
}

Edit: It is not duplicate of that question. That question is related to email and password, where mine is not

Body:
Try to use curl to get the http response code and act when it's 404

<?php
// create a new cURL resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "https://api.themoviedb.org/3/movie/39740?api_key=522cec78237f49axxxxxxxxxxx6d1e0c834a");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$responsejson = curl_exec($ch);
switch ($http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE)) {
   case 200:  # OK
    // do your normal process
    $response = json_decode($responsejson, true);
   break;
  case 404:
    // do your thing for not found situation
   $response = 'Not found';
  break;
  case 401:
    // not allowed
   $response = 'api key wrong?';
  break;
 default:
  echo 'Unexpected HTTP code: ', $http_code, "\n";
 }
}

// close cURL resource, and free up system resources
curl_close($ch);
?>


问:
php search help
following are my posted variables from search form:

```<code>$city = $_REQUEST['city'];
$location = $_REQUEST['location'];
$bedrooms = $_REQUEST['noofbedrooms'];
$addeddate = $_REQUEST['addeddate'];
$minprice = $_REQUEST['pricefrom'];
$maxprice = $_REQUEST['priceto'];
$minarea = $_REQUEST['areafrom'];
$maxarea = $_REQUEST['areato'];
$propertytype = $_REQUEST['proptype'];
</code>```

so far so good. Now i need some good suggestions for the following scenario.
Almost every element in my field are optional. That means i can get empty values in above variables.

What should be my scenario to create the mysql query for the above variables. On case can be that i use conditions for each and every scenario. eg

```<code>if($city=="")
  $query="";
elseif($location=="")
  $query="";
and so on....
</code>```

i need some professional approach for this.

答:
```<code>$city      = mysql_real_escape_string($_REQUEST['city']);
$location  = mysql_real_escape_string($_REQUEST['location']);
$bedrooms  = mysql_real_escape_string($_REQUEST['noofbedrooms']);
$addeddate = mysql_real_escape_string($_REQUEST['addeddate']);
$minprice  = mysql_real_escape_string($_REQUEST['pricefrom']);
$maxprice  = mysql_real_escape_string($_REQUEST['priceto']);
$minarea   = mysql_real_escape_string($_REQUEST['areafrom']);
$maxarea   = mysql_real_escape_string($_REQUEST['areato']);

$query = 'SELECT * FROM hotels WHERE 1 = 1 ';

$query .= strlen($city)     ? ' AND city = "'.$city.'"'         : '';
$query .= strlen($location) ? ' AND location = "'.$location.'"' : '';
$query .= strlen($bedrooms) ? ' AND bedrooms = "'.$bedrooms.'"' : '';
// ... do it for all params ...

echo $query;
</code>```

Title: php search help

Body:
following are my posted variables from search form:

$city = $_REQUEST['city'];
$location = $_REQUEST['location'];
$bedrooms = $_REQUEST['noofbedrooms'];
$addeddate = $_REQUEST['addeddate'];
$minprice = $_REQUEST['pricefrom'];
$maxprice = $_REQUEST['priceto'];
$minarea = $_REQUEST['areafrom'];
$maxarea = $_REQUEST['areato'];
$propertytype = $_REQUEST['proptype'];

so far so good. Now i need some good suggestions for the following scenario.
Almost every element in my field are optional. That means i can get empty values in above variables.

What should be my scenario to create the mysql query for the above variables. On case can be that i use conditions for each and every scenario. eg

if($city=="")
  $query="";
elseif($location=="")
  $query="";
and so on....

i need some professional approach for this.


问:
How to set minimum length of characters in inputText for bootsfaces?
I'm trying to use boots-faces for the first time and was looking for some validations at the client side like minimum length, maximum length or exact length.

I was able to find maxLength but I'm struggling to find how to do other length validations. Kindly suggest.

答:
We didn't implement it yet. Please open a feature request at https://github.com/TheCoder4eu/BootsFaces-OSP/issues.

By the way, how do you want the validation messages to be displayed? Currently, maxLength is simply added to the HTML sourcecode. So it's up to the browser to interpret it. In the case of maxLength, that's easy because it suffices to stop accepting input after reaching the maximum length.

minLength, exactLength, and pattern are different. They have to be able to show regular error messages. That amounts to finding the corresponding h:message(s), b:message(s), or p:message(s) tag and populating it with error messages on the client side.

The PrimeFaces team implemented the feature. That was a lot of work, and my perception is that few people miss it. I'd be happy to be proven wrong because the BootsFaces story is all about shifting logic to the client.

In the meantime, just follow the suggestion of @Tiny above and BalusC and use the AJAX engine:

```<code> <b:input value="...">
     <f:validateLength minimum="..." maximum="..." />
     <f:validateRegex pattern="^$|^[A-Za-z-_./\s]{2,50}$" />
 </b:input>
</code>```

Body:
We didn't implement it yet. Please open a feature request at https://github.com/TheCoder4eu/BootsFaces-OSP/issues.

By the way, how do you want the validation messages to be displayed? Currently, maxLength is simply added to the HTML sourcecode. So it's up to the browser to interpret it. In the case of maxLength, that's easy because it suffices to stop accepting input after reaching the maximum length.

minLength, exactLength, and pattern are different. They have to be able to show regular error messages. That amounts to finding the corresponding h:message(s), b:message(s), or p:message(s) tag and populating it with error messages on the client side.

The PrimeFaces team implemented the feature. That was a lot of work, and my perception is that few people miss it. I'd be happy to be proven wrong because the BootsFaces story is all about shifting logic to the client.

In the meantime, just follow the suggestion of @Tiny above and BalusC and use the AJAX engine:

 <b:input value="...">
     <f:validateLength minimum="..." maximum="..." />
     <f:validateRegex pattern="^$|^[A-Za-z-_./\s]{2,50}$" />
 </b:input>


问:
How to fix the image to a div when it's height is greater than its width?
In Facebook, when we post any size images, it shows perfectly on the timeline. How do they do this?

I have tried following.

Setting the image as background of the div.

CSS - width: 100%; height:auto;

Both did not work, All over the stack overflow there is no option for this,finally decided to add this.

答:
At facebook they don't show images as backgrounds. Images are shown there using img tag. If you observe the height of facebook images may differ from each other but the width is always same. Try to post an extremely long image and you will understand the thing.

Solution:

```<code><div>
    <img src="anysource">
</div>

<style>
   div{width: 480px;}
   div img{width: 100%; height: auto}
</style>
</code>```

Body:
At facebook they don't show images as backgrounds. Images are shown there using img tag. If you observe the height of facebook images may differ from each other but the width is always same. Try to post an extremely long image and you will understand the thing.

Solution:

<div>
    <img src="anysource">
</div>

<style>
   div{width: 480px;}
   div img{width: 100%; height: auto}
</style>


问:
Firing 'click' event on input submit without ID or name?
I am trying to auto-fill a form on a webpage using .NET's web browser int he C# language. I need to fire the submit button but it doesn't have a name or ID, all it has is a type and value.

The type is equal to "submit" and the value is equal to "Sign In"

Heres how I did it for Sign Up:

```<code>webBrowser1.Document.GetElementById("email").InnerText = email;
webBrowser1.Document.GetElementById("password").InnerText = password;
webBrowser1.Document.GetElementsByTagName("input")["register"].InvokeMember("click");
</code>```

But this time, the submit button doesn't have a name, can someone guide me in the right direction to getting an element by its type or even better, value?

HTML:

```<code><form accept-charset="utf-8" method="post">
    <div class="field">
        <label for="email">Email or Username</label> <span class="required">*</span> <input class="email" id="email" name="email" size="32" type="text">
    </div>
    <div class="field">
        <label for="password">Password</label> <span class="required">*</span> <input id="password" name="password" size="16" type="password">
        <p class="tip"><a href="/signin/reset" id="reset_password_link">I don't know my password</a></p>
    </div>
    <div class="field">
        <input id="persistent_hidden" name="persistent" type="hidden" value="f"> <input checked="checked" id="persistent" name="persistent" type="checkbox" value="t"> <label for="persistent">Keep me logged in</label>
    </div>
    <div class="submit">
        <input id="redirect_path" name="redirect_path" type="hidden"> <input type="submit" value="Sign In"> or <a class="cancel" href="/">Cancel</a>
    </div>
</form>
</code>```

答:
try :

```<code>foreach(HtmlElement elem in webBrowser.Document.getElementByTagName("input")) {
    if (elem.GetAttribute("value") == "Sign In") {
        elem.InvokeMember("Click");
    }
 }
</code>```

Body:
I am trying to auto-fill a form on a webpage using .NET's web browser int he C# language. I need to fire the submit button but it doesn't have a name or ID, all it has is a type and value.

The type is equal to "submit" and the value is equal to "Sign In"

Heres how I did it for Sign Up:

webBrowser1.Document.GetElementById("email").InnerText = email;
webBrowser1.Document.GetElementById("password").InnerText = password;
webBrowser1.Document.GetElementsByTagName("input")["register"].InvokeMember("click");

But this time, the submit button doesn't have a name, can someone guide me in the right direction to getting an element by its type or even better, value?

HTML:

<form accept-charset="utf-8" method="post">

        Email or Username * <input class="email" id="email" name="email" size="32" type="text">

        Password * <input id="password" name="password" size="16" type="password">

I don't know my password

        <input id="persistent_hidden" name="persistent" type="hidden" value="f"> <input checked="checked" id="persistent" name="persistent" type="checkbox" value="t"> Keep me logged in

        <input id="redirect_path" name="redirect_path" type="hidden"> <input type="submit" value="Sign In"> or Cancel

</form>

Body:
try :

foreach(HtmlElement elem in webBrowser.Document.getElementByTagName("input")) {
    if (elem.GetAttribute("value") == "Sign In") {
        elem.InvokeMember("Click");
    }
 }


问:
Mysterious MySQL encoding issue with Java Driver and Play Framework
Problem is that with inserting Nordic characters into a database I get the result I want in the command line, but when I fetch them in the application, the text and the encoding is somehow messed up

I am using MySQL 5.7.15 from the Docker -repository in the server where this issue occurs. I have a table where the names can have Nordic characters, i.e. å, ä and ö.

```<code>id    | name
1     | Kalle Anka
</code>```

If I do an inspection (SHOW FULL COLUMNS FROM users) to the table, it says name's collation is utf8_general_ci. Now I have a file updates.sql (UTF-8) that I am running against the database, with statements like this

```<code>update users set name = 'Gåsfrid Lukas' where id = 1;
# quite a few lines more
</code>```

The script runs fine in a local development environment and in a server environment. I get a similar response in the command line in both environments.

```<code>select * from site where id = 38593;
id       |  name
1        |  Gåsfrid Lukas
</code>```

I have a GET -route, which only does a simple query to the database and returns the user in JSON. It is using Play Framework 2.4.3, com.mysql.jdbc.Driver as the Driver (Squeryl as the ORM). I can get more into detail with the implementation if needed, but I don't think it's the problem here. The connection URL is configured like this.

```<code>db.default.url = "jdbc:mysql://localhost/duckbase?useUnicode=true&characterEncoding=utf-8&mysqlEncoding=utf8"
</code>```

In development everything works nice and correct, and it returns following JSON

```<code>{"name":"Gåsfrid Lukas","id":1}
</code>```

However, in the server environment everything isn't so nice anymore, and the encoding is messed up like this

```<code>{"name":"GÃ¥sfrid Lukas","id":1}
</code>```

To make things even more weird, if in a local development machine I take a database dump from the database, and put it in the server environment, and then update the original user with a statement

```<code>UPDATE users u1 INNER JOIN backup.users u2 ON u2.id = u1.id SET u1.name = u2.name WHERE u1.id = 1 AND u2.id = 1; #this copies Gåsfrid Lukas -name  from the backup to the actual DB
SELECT * from users WHERE id = 1;
# returns
id    | name
1     | G▒frid Lukas
</code>```

So the name seems to be corrupted in the database? Nope, the earlier REST-route returns following JSON with the corrupted entry.

```<code>{"name":"Gåsfrid Lukas","id":1}
</code>```

So bottom line, when everything looks to be OK in the database (CLI), the application doesn't work properly. When everything doesn't look to be OK in the database, the application works properly.

I am a little dumbfound by this. Is the MySQL Driver causing something there that is causing this behavior? If the MySQL Driver is somehow fixing a faulty encoding so that the G▒sfrid Lukas -entry works, how come the original UTF-8 -name is showing incorrectly? What MySQL configuration parameters should I look into that could shed light into this?

答:
Ã¥ is Mojibake for å.  See http://stackoverflow.com/questions/38363566/trouble-with-utf8-characters-what-i-see-is-not-what-i-stored for discussion of causes and prevention of such.

If that does not suffice, follow the debugging tips and show us the HEX, etc.

Body:
Problem is that with inserting Nordic characters into a database I get the result I want in the command line, but when I fetch them in the application, the text and the encoding is somehow messed up

I am using MySQL 5.7.15 from the Docker -repository in the server where this issue occurs. I have a table where the names can have Nordic characters, i.e. å, ä and ö.

id    | name
1     | Kalle Anka

If I do an inspection (SHOW FULL COLUMNS FROM users) to the table, it says name's collation is utf8_general_ci. Now I have a file updates.sql (UTF-8) that I am running against the database, with statements like this

update users set name = 'Gåsfrid Lukas' where id = 1;
# quite a few lines more

The script runs fine in a local development environment and in a server environment. I get a similar response in the command line in both environments.

select * from site where id = 38593;
id       |  name
1        |  Gåsfrid Lukas

I have a GET -route, which only does a simple query to the database and returns the user in JSON. It is using Play Framework 2.4.3, com.mysql.jdbc.Driver as the Driver (Squeryl as the ORM). I can get more into detail with the implementation if needed, but I don't think it's the problem here. The connection URL is configured like this.

db.default.url = "jdbc:mysql://localhost/duckbase?useUnicode=true&characterEncoding=utf-8&mysqlEncoding=utf8"

In development everything works nice and correct, and it returns following JSON

{"name":"Gåsfrid Lukas","id":1}

However, in the server environment everything isn't so nice anymore, and the encoding is messed up like this

{"name":"GÃ¥sfrid Lukas","id":1}

To make things even more weird, if in a local development machine I take a database dump from the database, and put it in the server environment, and then update the original user with a statement

UPDATE users u1 INNER JOIN backup.users u2 ON u2.id = u1.id SET u1.name = u2.name WHERE u1.id = 1 AND u2.id = 1; #this copies Gåsfrid Lukas -name  from the backup to the actual DB
SELECT * from users WHERE id = 1;
# returns
id    | name
1     | G▒frid Lukas

So the name seems to be corrupted in the database? Nope, the earlier REST-route returns following JSON with the corrupted entry.

{"name":"Gåsfrid Lukas","id":1}

So bottom line, when everything looks to be OK in the database (CLI), the application doesn't work properly. When everything doesn't look to be OK in the database, the application works properly.

I am a little dumbfound by this. Is the MySQL Driver causing something there that is causing this behavior? If the MySQL Driver is somehow fixing a faulty encoding so that the G▒sfrid Lukas -entry works, how come the original UTF-8 -name is showing incorrectly? What MySQL configuration parameters should I look into that could shed light into this?


问:
Gap between contents
I am trying to make a news website(in Bangla language)... so I am having a trouble.There is an image below for it

I want to fill the red marked area. How can I do it? The css of news content's is

```<code>.main-news {
    vertical-align: top;
    margin-top: 0;
    width: 33.1%;
    height: auto;
    overflow: auto;
    word-wrap: break-word;
    border: 1px solid #ccc;
    display: inline-block;
}
</code>```

Thanks in advance

答:
Flex is also a good approch see this for reference,
  Click here

OR,

You can give min-height instead of height it may be solve your issue,
  but it takes all the blocks same height

```<code>.main-news {
   vertical-align: top;
   margin-top: 0;
   width: 33.1%;
   min-height: 600px;
   overflow: auto;
   word-wrap: break-word;
   border: 1px solid #ccc;
   display: inline-block;
}
</code>```

Title: Gap between contents

Body:
I am trying to make a news website(in Bangla language)... so I am having a trouble.There is an image below for it

I want to fill the red marked area. How can I do it? The css of news content's is

.main-news {
    vertical-align: top;
    margin-top: 0;
    width: 33.1%;
    height: auto;
    overflow: auto;
    word-wrap: break-word;
    border: 1px solid #ccc;
    display: inline-block;
}

Thanks in advance

Body:
Flex is also a good approch see this for reference,
  Click here

OR,

You can give min-height instead of height it may be solve your issue,
  but it takes all the blocks same height

.main-news {
   vertical-align: top;
   margin-top: 0;
   width: 33.1%;
   min-height: 600px;
   overflow: auto;
   word-wrap: break-word;
   border: 1px solid #ccc;
   display: inline-block;
}


问:
Programmatically Determine a Duration of a Locked Workstation?
How can one determine, in code, how long the machine is locked?

Other ideas outside of C# are also welcome.

I like the windows service idea (and have accepted it) for simplicity and cleanliness, but unfortunately I don't think it will work for me in this particular case. I wanted to run this on my workstation at work rather than home (or in addition to home, I suppose), but it's locked down pretty hard courtesy of the DoD. That's part of the reason I'm rolling my own, actually.

I'll write it up anyway and see if it works. Thanks everyone!

答:
Below is the 100% working code to find if the PC is locked or not.

Before using this use the namespace System.Runtime.InteropServices.

```<code>[DllImport("user32", EntryPoint = "OpenDesktopA", CharSet = CharSet.Ansi,SetLastError = true, ExactSpelling = true)]
private static extern Int32 OpenDesktop(string lpszDesktop, Int32 dwFlags, bool fInherit, Int32 dwDesiredAccess);

[DllImport("user32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern Int32 CloseDesktop(Int32 hDesktop);

[DllImport("user32", CharSet = CharSet.Ansi,SetLastError = true,ExactSpelling = true)]
private static extern Int32 SwitchDesktop(Int32 hDesktop);

public static bool IsWorkstationLocked()
{
    const int DESKTOP_SWITCHDESKTOP = 256;
    int hwnd = -1;
    int rtn = -1;

    hwnd = OpenDesktop("Default", 0, false, DESKTOP_SWITCHDESKTOP);

    if (hwnd != 0)
    {
        rtn = SwitchDesktop(hwnd);
        if (rtn == 0)
        {
            // Locked
            CloseDesktop(hwnd);
            return true;
        }
        else
        {
            // Not locked
            CloseDesktop(hwnd);
        }
    }
    else
    {
        // Error: "Could not access the desktop..."
    }

    return false;
}
</code>```

OwnerDisplayName: AgentConundrum

Body:
Below is the 100% working code to find if the PC is locked or not.

Before using this use the namespace System.Runtime.InteropServices.

[DllImport("user32", EntryPoint = "OpenDesktopA", CharSet = CharSet.Ansi,SetLastError = true, ExactSpelling = true)]
private static extern Int32 OpenDesktop(string lpszDesktop, Int32 dwFlags, bool fInherit, Int32 dwDesiredAccess);

[DllImport("user32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern Int32 CloseDesktop(Int32 hDesktop);

[DllImport("user32", CharSet = CharSet.Ansi,SetLastError = true,ExactSpelling = true)]
private static extern Int32 SwitchDesktop(Int32 hDesktop);

public static bool IsWorkstationLocked()
{
    const int DESKTOP_SWITCHDESKTOP = 256;
    int hwnd = -1;
    int rtn = -1;

    hwnd = OpenDesktop("Default", 0, false, DESKTOP_SWITCHDESKTOP);

    if (hwnd != 0)
    {
        rtn = SwitchDesktop(hwnd);
        if (rtn == 0)
        {
            // Locked
            CloseDesktop(hwnd);
            return true;
        }
        else
        {
            // Not locked
            CloseDesktop(hwnd);
        }
    }
    else
    {
        // Error: "Could not access the desktop..."
    }

    return false;
}


问:
Why do we need to use `int main` and not `void main` in C++?
Why do we need to use int main and not void main in C++?

答:
Because int is the returncode a program can return to the OS.

You can query this value to check if operation has been succesfull.

This was extremely helpfull when using commandline scripts.

OwnerDisplayName: kasperasky

OwnerDisplayName: Gamecat


问:
Redirect data from console to the python script
I have .bat file which outputs data in console, than I need to read that data with  python script and run through "if cycles"

The question is: How to read that data with python script?

答:
There are two approaches you might take:

Use a pipe (the | character) in your command line to redirect the output that is going to the console to the Python script, and code the Python script to read from stdin.

Redirect the output that is going to the console to a file (with >filename) and then code the Python script to read from that file.


问:
Animate canvas point
I want to animate my canvas menu background.
On click on the menu button I want to fade out the menu with a little parallaxeffect.

I've created a fiddle DEMO

I've tried it with 'requestAnimationFrame' but I don't understand this method. It should look like the menu from this example. But their code I really don't understand...

Sorry, and thanks for helping.

```<code>My current JS
function drawCanvas() {
    var $canvas = document.getElementById('nav-bg');
    var windowH = window.innerHeight;

    const fillColor = '#00ffcd';
    const ctx = $canvas.getContext('2d');

    $canvas.height = windowH;
    $canvas.width = $canvas.width;

    ctx.fillStyle = fillColor;
    ctx.beginPath();
    ctx.moveTo(550, 0);
    ctx.lineTo(550, windowH);
    ctx.lineTo(0, windowH);
    ctx.lineTo(125, 0);
    ctx.closePath();
    ctx.fill();
}

drawCanvas();
</code>```

答:
Although I am in Germany, their page downloads (and executes) very slowly. That's why I didn't look at their code and just created something that looks similar to theirs.

I changed a few things (SCSS to CSS) in the following snippet. Also, the menu doesn't collapse when you click the button again. I'm sure you can figure out how to do that.

Moreover, I make use of window.requestAnimationFrame:

const canvas = document.getElementById('nav-bg');
const ctx = canvas.getContext('2d');
const fillColor = '#00ffcd';

const firstStepDuration = 500; // the first step is until the direction of the border changes
const firstStepWidth = 125; // how far should the first step go?
const secondStepDuration = 500;
const secondStepWidth = 250;

let startTime;

function draw () {
  const now = Date.now();
  const time = now - startTime; // time since button click
  const height = canvas.height = window.innerHeight;
  ctx.fillStyle = fillColor;

  if (time < firstStepDuration) {
    ctx.beginPath();
    ctx.moveTo(550, 0);
    ctx.lineTo(550, height);
    ctx.lineTo(firstStepWidth * time / firstStepDuration, height);
    ctx.lineTo(time / firstStepDuration * firstStepWidth - firstStepWidth, 0);
    ctx.closePath();
    ctx.fill();
  } else {
    ctx.beginPath();
    ctx.moveTo(550, 0);
    ctx.lineTo(550, height);
    ctx.lineTo(firstStepWidth, height);
    ctx.lineTo((time - firstStepDuration) / secondStepDuration * secondStepWidth, 0);
    ctx.closePath();
    ctx.fill();
  }

  if (time < firstStepDuration + secondStepDuration) {
    // call draw again in the next animation frame
    window.requestAnimationFrame(draw);
  }
};

document.querySelector('.nav-button').addEventListener('click', function () {
  startTime = Date.now();
  draw();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.nav-button {
    background-color: #00ffcd;
    border: 0;
    cursor: pointer;
    float: left;
    height: 60px;
    outline: 0;
    padding: 0;
    position: fixed;
    left: 25px;
    top: 25px;
    width: 60px;
    z-index: 99999;
}

span.icon-bar {
  background-color: black;
  display: block;
  height: 5px;
  margin-left: 15px;
  margin-top: 5px;
  width: 30px;
}

span.icon-bar:first-child {
  margin-top: 0;
}

.nav-button:hover > span.icon-bar.middle {
  margin-left: 10px;
}

#navigation {
  backface-visibility: hidden;
  bottom: 0;
  display: block;
  height: 100%;
  position: fixed;
  left: 0;
  right: 0;
  z-index: 500;
}

#nav-bg {
  position: relative;
  width: 100%;
  height: 100%;
  background-size: 100% auto;
  background-position: center center;
}</code>```

  <button class="nav-button">

  </button>

  <canvas id="nav-bg" width="550" height="750"></canvas>

```

If you want further explanation, feel free to ask!

Title: Animate canvas point

Body:
I want to animate my canvas menu background.
On click on the menu button I want to fade out the menu with a little parallaxeffect.

I've created a fiddle DEMO

I've tried it with 'requestAnimationFrame' but I don't understand this method. It should look like the menu from this example. But their code I really don't understand...

Sorry, and thanks for helping.

My current JS
function drawCanvas() {
    var $canvas = document.getElementById('nav-bg');
    var windowH = window.innerHeight;

    const fillColor = '#00ffcd';
    const ctx = $canvas.getContext('2d');

    $canvas.height = windowH;
    $canvas.width = $canvas.width;

    ctx.fillStyle = fillColor;
    ctx.beginPath();
    ctx.moveTo(550, 0);
    ctx.lineTo(550, windowH);
    ctx.lineTo(0, windowH);
    ctx.lineTo(125, 0);
    ctx.closePath();
    ctx.fill();
}

drawCanvas();

Body:
Although I am in Germany, their page downloads (and executes) very slowly. That's why I didn't look at their code and just created something that looks similar to theirs.

I changed a few things (SCSS to CSS) in the following snippet. Also, the menu doesn't collapse when you click the button again. I'm sure you can figure out how to do that.

Moreover, I make use of window.requestAnimationFrame:

const canvas = document.getElementById('nav-bg');
const ctx = canvas.getContext('2d');
const fillColor = '#00ffcd';

const firstStepDuration = 500; // the first step is until the direction of the border changes
const firstStepWidth = 125; // how far should the first step go?
const secondStepDuration = 500;
const secondStepWidth = 250;

let startTime;

function draw () {
  const now = Date.now();
  const time = now - startTime; // time since button click
  const height = canvas.height = window.innerHeight;
  ctx.fillStyle = fillColor;

  if (time < firstStepDuration) {
    ctx.beginPath();
    ctx.moveTo(550, 0);
    ctx.lineTo(550, height);
    ctx.lineTo(firstStepWidth * time / firstStepDuration, height);
    ctx.lineTo(time / firstStepDuration * firstStepWidth - firstStepWidth, 0);
    ctx.closePath();
    ctx.fill();
  } else {
    ctx.beginPath();
    ctx.moveTo(550, 0);
    ctx.lineTo(550, height);
    ctx.lineTo(firstStepWidth, height);
    ctx.lineTo((time - firstStepDuration) / secondStepDuration * secondStepWidth, 0);
    ctx.closePath();
    ctx.fill();
  }

  if (time < firstStepDuration + secondStepDuration) {
    // call draw again in the next animation frame
    window.requestAnimationFrame(draw);
  }
};

document.querySelector('.nav-button').addEventListener('click', function () {
  startTime = Date.now();
  draw();
});

.nav-button {
    background-color: #00ffcd;
    border: 0;
    cursor: pointer;
    float: left;
    height: 60px;
    outline: 0;
    padding: 0;
    position: fixed;
    left: 25px;
    top: 25px;
    width: 60px;
    z-index: 99999;
}

span.icon-bar {
  background-color: black;
  display: block;
  height: 5px;
  margin-left: 15px;
  margin-top: 5px;
  width: 30px;
}

span.icon-bar:first-child {
  margin-top: 0;
}

.nav-button:hover > span.icon-bar.middle {
  margin-left: 10px;
}

#navigation {
  backface-visibility: hidden;
  bottom: 0;
  display: block;
  height: 100%;
  position: fixed;
  left: 0;
  right: 0;
  z-index: 500;
}

#nav-bg {
  position: relative;
  width: 100%;
  height: 100%;
  background-size: 100% auto;
  background-position: center center;
}

<header>
  <button class="nav-button">
    <span class="icon-bar top"></span>
    <span class="icon-bar middle"></span>
    <span class="icon-bar bottom"></span>
  </button>
</header>
<div id="navigation">
  <canvas id="nav-bg" width="550" height="750"></canvas>
</div>

If you want further explanation, feel free to ask!