问:
select more than one checkbox to execute condition
I want a text file to show contents in memo1 once I have selected 2 checkboxes.
How would I do this?

I tried the code below but I can't seem to get it right.

```<code>if CheckBox1.Checked and CheckBox2.Checked then
begin
memo1.lines.LoadFromFile('files\RS.txt');
end;
</code>```

I also want to be able to select the checkboxes individually Like:
(pointing this out in case combining them prevents checking them individually)

Checkbox1:

```<code>procedure TForm1.CheckBox1Change(Sender: TObject);
begin
   memo1.lines.LoadFromFile('files\R.txt');
end;
</code>```

Checkbox2:

```<code>procedure TForm1.CheckBox2Change(Sender: TObject);
begin
   memo1.lines.LoadFromFile('files\S.txt');
end;
</code>```

Any suggestions/Improvements will be appreciated.

Running Lazarus IDE v1.6.4

Windows 10 x64

答:
A separate checkboxchange proocedure per event is automatically generated by the designer if you double click the event. However that is not a rigid decision.

If you have the initial codefragment in e.g. checkbox1change, you can simply point the onchange of checkbox2 to that existing checkbox1change by using the dropdown of the onchange of checkbox2

Body:
I want a text file to show contents in memo1 once I have selected 2 checkboxes.
How would I do this?

I tried the code below but I can't seem to get it right.

if CheckBox1.Checked and CheckBox2.Checked then
begin
memo1.lines.LoadFromFile('files\RS.txt');
end;

I also want to be able to select the checkboxes individually Like:
(pointing this out in case combining them prevents checking them individually)

Checkbox1:

procedure TForm1.CheckBox1Change(Sender: TObject);
begin
   memo1.lines.LoadFromFile('files\R.txt');
end;

Checkbox2:

procedure TForm1.CheckBox2Change(Sender: TObject);
begin
   memo1.lines.LoadFromFile('files\S.txt');
end;

Any suggestions/Improvements will be appreciated.

Running Lazarus IDE v1.6.4

Windows 10 x64


来源: stackexchange

问:
"Do nothing" in the else-part of the ternary operator?
What's the standard line to add to the ternary operator in order to do nothing if the condition is not met?

Example:

```<code>int a = 0;
a > 10 ? a = 5 : /*do nothing*/;
</code>```

Using a seems to do the trick, but I am wondering if there is a more generally accepted way.

答:
Another option:

```<code>a ? void(a = 0) : void();
</code>```

What's good about this one is that it works even if you can't construct an instance of decltype(a = 0) to put into the 'do nothing' expression. (Which doesn't matter for primitive types anyway.)

ContentLicense: CC BY-SA 3.0

Body:
What's the standard line to add to the ternary operator in order to do nothing if the condition is not met?

Example:

int a = 0;
a > 10 ? a = 5 : /*do nothing*/;

Using a seems to do the trick, but I am wondering if there is a more generally accepted way.

Body:
Another option:

a ? void(a = 0) : void();

What's good about this one is that it works even if you can't construct an instance of decltype(a = 0) to put into the 'do nothing' expression. (Which doesn't matter for primitive types anyway.)


问:
my bundle.js doesn't seem to be created
I am building a simple app with the use of webpack to combine all my modules. My webpack seem to be running (although, I have battled its not-working).
Now it looks like a bundle.js necessary to see my app cannot be found. I get this error:

the error

So here are my files that might cause the issue

the config.webpack.js file

my packageJSON

```<code>{
 "name": "quiz",
 "version": "1.0.0",
 "description": "",
 "main": "app.js",
 "scripts": {
   "test": "mocha specs"
 },
 "author": "",
 "license": "ISC",
 "devDependencies": {
   "mocha": "^3.4.2",
   "webpack": "1.12.15"
 }
}
</code>```

and the html file that looks for the bundle.js file

```<code><!DOCTYPE html>
<html>
<head>
    <title>Quiz game</title>
</head>
<body>
    <script src = "build.js "></script>
    <div>
    Quiz game
    </div>
</body>
</html>
</code>```

Any ideas on what might be wrong?

答:
First,

Probably, you can change your project structure a little as webpack cli will find the webpack.config.js file under root folder by default.

```<code>  webpack-demo
  |- package.json
+ |- webpack.config.js
  |- /dist
    |- index.html
  |- /src
    |- index.js
</code>```

Second,
you may change your webpack.config.js a little bit by require path to point out the output path clearly:

```<code>var path = require('path');

module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  }
};
</code>```

Third,

If your index.html is under the same folder as bundle.js in dist folder,

```<code> <script src="bundle.js"></script>
</code>```

is correct. But put it at the bottom the body, so that it won't block rendering and can manipulate DOM when page load.

```<code><!DOCTYPE html>
<html>
<head>
    <title>Quiz game</title>
</head>
<body>
    <div>
    Quiz game
    </div>
    <script src="build.js"></script>
</body>
</html>
</code>```

Title: my bundle.js doesn't seem to be created

Body:
I am building a simple app with the use of webpack to combine all my modules. My webpack seem to be running (although, I have battled its not-working).
Now it looks like a bundle.js necessary to see my app cannot be found. I get this error:

the error

So here are my files that might cause the issue

the config.webpack.js file

my packageJSON

{
 "name": "quiz",
 "version": "1.0.0",
 "description": "",
 "main": "app.js",
 "scripts": {
   "test": "mocha specs"
 },
 "author": "",
 "license": "ISC",
 "devDependencies": {
   "mocha": "^3.4.2",
   "webpack": "1.12.15"
 }
}

and the html file that looks for the bundle.js file

<!DOCTYPE html>

    <title>Quiz game</title>

    Quiz game

Any ideas on what might be wrong?

Body:
First,

Probably, you can change your project structure a little as webpack cli will find the webpack.config.js file under root folder by default.

  webpack-demo
  |- package.json
+ |- webpack.config.js
  |- /dist
    |- index.html
  |- /src
    |- index.js

Second,
you may change your webpack.config.js a little bit by require path to point out the output path clearly:

var path = require('path');

module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  }
};

Third,

If your index.html is under the same folder as bundle.js in dist folder,

 <script src="bundle.js"></script>

is correct. But put it at the bottom the body, so that it won't block rendering and can manipulate DOM when page load.

<!DOCTYPE html>
<html>
<head>
    <title>Quiz game</title>
</head>
<body>
    <div>
    Quiz game
    </div>
    <script src="build.js"></script>
</body>
</html>


问:
Count years of increasing profits
I want to count how many years a company has increased the profit from now. So if the previous year had lower profits than this year it counts as 1 and goes one year back in past to count until there is one years profit higher than the year after that. So it must be a ongoing trend from this year (2017) so that it counts the years.

(Years of increases should be 5 not 4, sorry!)

In the picture it has to count until 2011 because there was a year(2012) without increasing profits relative to last year(2011).

So maybe its even possible with a Excel Function. Otherwise VBA is probably the way to do this.

EDIT: Is it possible to count years of steady profits, too? Like if 2015 = 5 and 2016 = 5 then this should not stop streak.

答:
If you are looking for the streak of "increased/same profit" starting from current year, try the below formulas in the 2nd row:

 - in cell K2: =IF(B2>=A2,1,0)

 - in cell S2: =IF(K2=1,A4+K2,K2)

 - in cell J2: =Z2

then copy the cell K2 to the range L2:R2, cell S2 to the range T2:Z2, and then copy the range J2:Z2 to all the applicable rows as per below pic.

Note: instead of filling-up with formulas in rows 3 & 4, sure it can be done directly in cell J2 by way of Excel array, but for the sake of simplicity this method is preferable.

Edit: the above post was updated as per subsequent discussion with @technotoast to make the following adjustments:

 - there are many companies in the list - not just "Apple"

 - the streak will continue for same profit levels also - not just increasing profit

Title: Count years of increasing profits


问:
How to set the frequency of metric output in lightGBM?
In the documents, it is said that we can set the parameter metric_freq to set the frequency. I have also tried the parameter verbose, the parameters are set as

```<code>params = {
    'task': 'train',
    'boosting_type': 'gbdt',
    'objective': 'binary',
    'metric': { 'binary_logloss'},
    'metric_freq':10,
    'num_leaves': 511,
    'max_depth':8,
    'learning_rate': 0.1,
    'feature_fraction': 1,
    'bagging_fraction': 0.8,
    'bagging_freq': 1,
    'verbose':10
}
</code>```

However, I still got the result as following,

```<code>[1] valid_0's binary_logloss: 0.607487
Train until valid scores didn't improve in 5 rounds.
[2] valid_0's binary_logloss: 0.537403
[3] valid_0's binary_logloss: 0.479081
[4] valid_0's binary_logloss: 0.429961
[5] valid_0's binary_logloss: 0.388182
[6] valid_0's binary_logloss: 0.35239
[7] valid_0's binary_logloss: 0.321529
[8] valid_0's binary_logloss: 0.294795
[9] valid_0's binary_logloss: 0.271543
[10]    valid_0's binary_logloss: 0.251267
[11]    valid_0's binary_logloss: 0.233531
[12]    valid_0's binary_logloss: 0.217997
[13]    valid_0's binary_logloss: 0.204344
</code>```

Which showed that the parameter metric_freq didn't work at all. So which parameter is used to set the frequency of output?

In R, we can use eval_freq, but there is no eval_freq parameter in python wrapper!

答: Try giving verbose_eval=10 as a keyword argument (rather than in params).</p>

Body:
In the documents, it is said that we can set the parameter metric_freq to set the frequency. I have also tried the parameter verbose, the parameters are set as

params = {
    'task': 'train',
    'boosting_type': 'gbdt',
    'objective': 'binary',
    'metric': { 'binary_logloss'},
    'metric_freq':10,
    'num_leaves': 511,
    'max_depth':8,
    'learning_rate': 0.1,
    'feature_fraction': 1,
    'bagging_fraction': 0.8,
    'bagging_freq': 1,
    'verbose':10
}

However, I still got the result as following,

[1] valid_0's binary_logloss: 0.607487
Train until valid scores didn't improve in 5 rounds.
[2] valid_0's binary_logloss: 0.537403
[3] valid_0's binary_logloss: 0.479081
[4] valid_0's binary_logloss: 0.429961
[5] valid_0's binary_logloss: 0.388182
[6] valid_0's binary_logloss: 0.35239
[7] valid_0's binary_logloss: 0.321529
[8] valid_0's binary_logloss: 0.294795
[9] valid_0's binary_logloss: 0.271543
[10]    valid_0's binary_logloss: 0.251267
[11]    valid_0's binary_logloss: 0.233531
[12]    valid_0's binary_logloss: 0.217997
[13]    valid_0's binary_logloss: 0.204344

Which showed that the parameter metric_freq didn't work at all. So which parameter is used to set the frequency of output?

In R, we can use eval_freq, but there is no eval_freq parameter in python wrapper!


问:
Panorama control truncating long titles
I'm trying to create a simple Windows Phone 7 app in which one of the pages uses a Panorama control. My control has five PanoramaItem children. Using the code below, the title is truncated on the fourth screen in the middle of the word "anyone." How can I make the Panorama control display the full title?

```<code><controls:Panorama Title="This is the longest title anyone has ever seen" >
</code>```

答:
I would expect this to be limited to be 1024px in width. (The same as the background image width.)

This constraint is perfectly fine within the intended use of the Panorama header/title. From the UI Design and Interaction Guide:

It is meant to let the user identify the application

and

Use the same panorama title for the launch tile in Start for consistency.

Due to space restrictions on the Start Tile and the application list a guideline of 13 characters is suggested to avoid text clipping. This will also definitely fit on a panorama header.

ContentLicense: CC BY-SA 2.5

Title: Panorama control truncating long titles

Body:
I'm trying to create a simple Windows Phone 7 app in which one of the pages uses a Panorama control. My control has five PanoramaItem children. Using the code below, the title is truncated on the fourth screen in the middle of the word "anyone." How can I make the Panorama control display the full title?

<controls:Panorama Title="This is the longest title anyone has ever seen" >


问:
ReactJS - Unexpected token '.' error
I am starting with my react project on VS2013 working together with ASP.NET MVC. I have configured webpack and configuration seemed working well until I tried to implement the following class.

```<code>class Hello extends React.Component {
    this.state = { visible: true }
    render() {
       /** Method definition **/
    ...
}
</code>```

I am getting an error Unexpected Token at '.' at 'this.state'. I have already check es2015 is set as babel preset. If I remove state and toggleVisibility assignments, webpack bundles OK.

Any idea what else can I try?

答:
It's a class so the correct syntax should be </p>

```<code>class Hello extends React.Component {
    state = { visible: true }
    render() {
       /** Method definition **/
    ...
}
</code>```

<p>Also, the recommended way of defining initial state should be </p>

```<code>class Hello extends React.Component {
    constructor(props) {
      super(props)
      this.state = { visible: true }
    }

    render() {
       /** Method definition **/
    ...
}
</code>```

Title: ReactJS - Unexpected token '.' error

Body:
I am starting with my react project on VS2013 working together with ASP.NET MVC. I have configured webpack and configuration seemed working well until I tried to implement the following class.

class Hello extends React.Component {
    this.state = { visible: true }
    render() {
       /** Method definition **/
    ...
}

I am getting an error Unexpected Token at '.' at 'this.state'. I have already check es2015 is set as babel preset. If I remove state and toggleVisibility assignments, webpack bundles OK.

Any idea what else can I try?

Body:
It's a class so the correct syntax should be

class Hello extends React.Component {
    state = { visible: true }
    render() {
       /** Method definition **/
    ...
}

Also, the recommended way of defining initial state should be

class Hello extends React.Component {
    constructor(props) {
      super(props)
      this.state = { visible: true }
    }

    render() {
       /** Method definition **/
    ...
}


问:
Generate PDF file from HTML code
I would like to generate a PDF file from a HTML code which contains the stylesheet rules, using PHP.

I am trying to do it using the MPDF library, but when is generated it doesn't look like the HTML page. Most of the elements are not situated in the right position and is like some css rules were not applied.

Does anyone know how can I make it look fine, please?

答:
You can get value from another page using post method also. Your choice.</p>

```<code><?php $student_id = $_GET['student_id']; ?>
<?php
include("mpdf/mpdf.php");
$html .= "
<html>
<head>
<style>
body {font-family: sans-serif;
    font-size: 10pt;
    background-image: url(\"images/ok.jpg\");

    background-repeat: no-repeat;
    padding-top:10pt;
    margin-top: 100px;
    padding-top: 50px;
}
td { vertical-align: top;
    border-left: 0.6mm solid #000000;
    border-right: 0.6mm solid #000000;
    align: center;
}

p.student_id{
    padding-left : 140px;
    padding-top  : -27px;
}

</style>
</head>
<body>
<!--mpdf

<p class=\"student_id\">$student_id</p>

<sethtmlpageheader name='myheader' value='on' show-this-page='1' />
<sethtmlpagefooter name='myfooter' value='on' />
mpdf-->

</body>
</html>
";

$mpdf=new mPDF();
$mpdf->WriteHTML($html);
$mpdf->SetDisplayMode('fullpage');

$mpdf->Output();
?>
</code>```

Title: Generate PDF file from HTML code

Body:
You can get value from another page using post method also. Your choice.

<?php $student_id = $_GET['student_id']; ?>
<?php
include("mpdf/mpdf.php");
$html .= "
<html>
<head>
<style>
body {font-family: sans-serif;
    font-size: 10pt;
    background-image: url(\"images/ok.jpg\");

    background-repeat: no-repeat;
    padding-top:10pt;
    margin-top: 100px;
    padding-top: 50px;
}
td { vertical-align: top;
    border-left: 0.6mm solid #000000;
    border-right: 0.6mm solid #000000;
    align: center;
}

p.student_id{
    padding-left : 140px;
    padding-top  : -27px;
}

</style>
</head>
<body>
<!--mpdf

<p class=\"student_id\">$student_id</p>

<sethtmlpageheader name='myheader' value='on' show-this-page='1' />
<sethtmlpagefooter name='myfooter' value='on' />
mpdf-->

</body>
</html>
";

$mpdf=new mPDF();
$mpdf->WriteHTML($html);
$mpdf->SetDisplayMode('fullpage');

$mpdf->Output();
?>


问:
How can I upload an image with AJAX?
I am trying to upload an image with AJAX. When I try like this, nothing happens. AJAX does not call H_FileUpload.php. But the $("#in_profile_img") part does work. Only the AJAX call does not work. Why doesn't it work?

HTML:

```<code><ul class="dropdown-menu fm-menu" role="menu">
    <li>
        <a href="javascript:void(0)" onclick="$.change_profile_img()">
            <i class="fa fa-pencil"></i> Change
        </a>
    </li>
    <li><a href="#"><i class="fa fa-trash-o"></i> Delete</a></li>
</ul>
<form id="form_profile_image" enctype="multipart/form-data" action="" method="POST">
    <input type="file" name="profile_img" id="in_profile_img" style="display:none;" />
</form><!-- profile image form -->
</code>```

JavaScript:

```<code>$.change_profile_img = function() {
    $("#in_profile_img").click();
}

$("#in_profile_img").on('change', (function(e) {
    e.preventDefault;
    var formData = new FormData(this);

    $.ajax({
        url : "./handlers/H_FileUpload.php",
        type : "POST",
        data : formData,
        cache : false,
        contentType : false,
        processType : false,
        success : function(data) {
            alert("Success");
            alert(data);
        }
    });
}));
</code>```

PHP (H_FileUpload.php):

```<code><?php
$name = $_FILES["profile_img"]["name"];
$result["ok"] = $name;

echo json_encode($result);

?>
</code>```

答:
You could use jquery which would significantly simplify the task.
Import jquery: https://code.jquery.com/jquery-3.2.1.min.js</p>

```<code>var formData = $("#in_profile_img");
$.post('./handlers/H_FileUpload.php',{data:formData},function(e){
    alert("success");
    alert(e);
});
</code>```

Title: How can I upload an image with AJAX?

Body:
I am trying to upload an image with AJAX. When I try like this, nothing happens. AJAX does not call H_FileUpload.php. But the $("#in_profile_img") part does work. Only the AJAX call does not work. Why doesn't it work?

HTML:

             Change

 Delete

<form id="form_profile_image" enctype="multipart/form-data" action="" method="POST">
    <input type="file" name="profile_img" id="in_profile_img" style="display:none;" />
</form>

JavaScript:

$.change_profile_img = function() {
    $("#in_profile_img").click();
}

$("#in_profile_img").on('change', (function(e) {
    e.preventDefault;
    var formData = new FormData(this);

    $.ajax({
        url : "./handlers/H_FileUpload.php",
        type : "POST",
        data : formData,
        cache : false,
        contentType : false,
        processType : false,
        success : function(data) {
            alert("Success");
            alert(data);
        }
    });
}));

PHP (H_FileUpload.php):

<?php
$name = $_FILES["profile_img"]["name"];
$result["ok"] = $name;

echo json_encode($result);

?>

Body:
You could use jquery which would significantly simplify the task.
Import jquery: https://code.jquery.com/jquery-3.2.1.min.js

var formData = $("#in_profile_img");
$.post('./handlers/H_FileUpload.php',{data:formData},function(e){
    alert("success");
    alert(e);
});


问:
HOW TO Return value array on function php mysql
Hy I have code below,
I wanna return value array with function :

```<code>    <?php

include "config/koneksi.php";

//script1
$fetch1 = mysqli_query($conn, "SELECT * FROM orders_temp");

$array = array();
while($row = mysqli_fetch_assoc($fetch1)){
    $array[] = $row[id_orders_temp];
}
echo "script1: ";
print_r($array);

echo "<br>";

//script2
function cart(){
    $array1= array();

    $fetch2 = mysqli_query($conn,"SELECT * FROM orders_temp");

    while ($r=mysqli_fetch_assoc($fetch2)) {
        $array1[] = $r[id_orders_temp];
    }
    return $array1;
}

$cart1 = cart();
echo "script2 : ";
print_r($cart1);

?>
</code>```

and the result :

```<code>script1: Array ( [0] => 150 [1] => 151 )
script2 : Array ( )
</code>```

there's no problem if I print_r array without function, but
when I used function as above, I got blank array( ).
How can I get array value with function ?

答:
The variable $conn is not defined within the function, so you need to either pass it to the function or reference the globally available $conn.

Pass in $conn

```<code>include "config/koneksi.php";

function cart($conn) {
    $identifiers = array();

    $result = mysqli_query($conn, 'SELECT id_orders_temp FROM orders_temp');

    while ($row = mysqli_fetch_assoc($result)) {
        $identifiers[] = $row['id_orders_temp'];
    }

    return $identifiers;
}

$cart = cart($conn);

var_dump($cart);
</code>```

Reference global $conn

Ideally, you should limit global state (and accessing it), so I would not recommend this.

```<code>include "config/koneksi.php";

function cart() {
    global $conn;

    $identifiers = array();

    $result = mysqli_query($conn, 'SELECT id_orders_temp FROM orders_temp');

    while ($row = mysqli_fetch_assoc($result)) {
        $identifiers[] = $row['id_orders_temp'];
    }

    return $identifiers;
}

$cart = cart();

var_dump($cart);
</code>```

Note I have renamed variables within cart() and optimized the SQL query to select only those columns actually required.

Body:
Hy I have code below,
I wanna return value array with function :

    <?php

include "config/koneksi.php";

//script1
$fetch1 = mysqli_query($conn, "SELECT * FROM orders_temp");

$array = array();
while($row = mysqli_fetch_assoc($fetch1)){
    $array[] = $row[id_orders_temp];
}
echo "script1: ";
print_r($array);

echo "
";

//script2
function cart(){
    $array1= array();

    $fetch2 = mysqli_query($conn,"SELECT * FROM orders_temp");

    while ($r=mysqli_fetch_assoc($fetch2)) {
        $array1[] = $r[id_orders_temp];
    }
    return $array1;
}

$cart1 = cart();
echo "script2 : ";
print_r($cart1);

?>

and the result :

script1: Array ( [0] => 150 [1] => 151 )
script2 : Array ( )

there's no problem if I print_r array without function, but
when I used function as above, I got blank array( ).
How can I get array value with function ?

Body:
The variable $conn is not defined within the function, so you need to either pass it to the function or reference the globally available $conn.

Pass in $conn

include "config/koneksi.php";

function cart($conn) {
    $identifiers = array();

    $result = mysqli_query($conn, 'SELECT id_orders_temp FROM orders_temp');

    while ($row = mysqli_fetch_assoc($result)) {
        $identifiers[] = $row['id_orders_temp'];
    }

    return $identifiers;
}

$cart = cart($conn);

var_dump($cart);

Reference global $conn

Ideally, you should limit global state (and accessing it), so I would not recommend this.

include "config/koneksi.php";

function cart() {
    global $conn;

    $identifiers = array();

    $result = mysqli_query($conn, 'SELECT id_orders_temp FROM orders_temp');

    while ($row = mysqli_fetch_assoc($result)) {
        $identifiers[] = $row['id_orders_temp'];
    }

    return $identifiers;
}

$cart = cart();

var_dump($cart);

Note I have renamed variables within cart() and optimized the SQL query to select only those columns actually required.


问:
Why are level 0 members tagged as never share
I am a fresher learning essbase and Hyperion, in one of project there was a outline in essbase where level 0 members were tagged as never share, I just don't understand why they are tagged as never share when they don't have children under them which will make implied sharing happen??</p>

答:
You're on the right track regarding implied sharing. I don't think the Never Share option was used a lot before the advent of Hyperion Planning, but when Planning came to be, they started marking members as Never Share by default so that people wouldn't accidentally stumble in to issues where implied sharing was happening on parents with just one child and data was being entered into a form. Then, if you eventually go add children to the member so that it becomes a parent, you won't have implied sharing issues.

There isn't much harm in having Never Share set across the board and treating it as the default member property. Also, given advancements in cube technology and hardware, there is precious little to be gained by saving a few bytes with an implied sharing relationship anymore, especially if it prevents some difficult and time-consuming issue to troubleshoot with your data that happens as a result of an implied sharing relationship.


问:
Android get a View reference to action bar item?
I'm using MaterialShowcaseView to show the user a quick tutorial, when they first start the app.

The problem I'm having is that I'm only able to get a view reference to the items in my action bar items when the user selects that item in onOptionsItemSelected.

i.e.

```<code>@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.my_location:
            // User chose the "Favorite" action, mark the current item
            // as a favorite...
            ShowcaseConfig config = new ShowcaseConfig();
            config.setDelay(500); // half second between each showcase view

            MaterialShowcaseSequence sequence = new MaterialShowcaseSequence(this, SHOWCASE_ID);

            sequence.setConfig(config);

            sequence.addSequenceItem(findViewById(R.id.action_my_location),
                    "This is button one", "GOT IT");
            sequence.start();
            Toast.makeText(MapsActivity.this, "My location action press", Toast.LENGTH_SHORT).show();

            return true;

        default:
            // If we got here, the user's action was not recognized.
            // Invoke the superclass to handle it.
            return super.onOptionsItemSelected(item);
    }
}
</code>```

The above code works.

Is it possible to get a view reference in onCreateOptionsMenu? Everything else I've tried gives me a null object reference for the view.

I've tried this answer too, to no success.

I should mention that for the actionBar I used android's action bar tutorial.

Thanks guys.

EDIT:

This is what I've tried to do now:

```<code>@Override
    public void invalidateOptionsMenu() {
        super.invalidateOptionsMenu();

    }
    MenuItem mi;
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        mi = menu.findItem(R.id.action_my_location);
        new MaterialShowcaseView.Builder(this)
                .setTarget(mi.getActionView())
                .setDismissText("GOT IT")
                .setContentText("This is some amazing feature you should know about")
                .setDelay(300) // optional but starting animations immediately in onCreate can make them choppy
                .singleUse("101010110") // provide a unique ID used to ensure it is only shown once
                .show();
        return super.onPrepareOptionsMenu(menu);
}
</code>```

Error:

java.lang.NullPointerException: Attempt to invoke virtual method 'void
  android.view.View.getLocationInWindow(int[])' on a null object
  reference

答:
You need this class:

```<code>public class ToolbarActionItemTarget implements Target {

private final Toolbar toolbar;
private final int menuItemId;

public ToolbarActionItemTarget(Toolbar toolbar, @IdRes int itemId) {
    this.toolbar = toolbar;
    this.menuItemId = itemId;
}

@Override
public Point getPoint() {
    return new ViewTarget(toolbar.findViewById(menuItemId)).getPoint();
}
</code>```

So:

```<code>showcaseView = new ShowcaseView.Builder(getActivity())
            .setTarget(Target.NONE)
            .setTarget(new ToolbarActionItemTarget(toolbar, R.id.action_view))
</code>```

Referenced by: https://github.com/amlcurran/ShowcaseView/releases/tag/5.3.0

`

Body:
I'm using MaterialShowcaseView to show the user a quick tutorial, when they first start the app.

The problem I'm having is that I'm only able to get a view reference to the items in my action bar items when the user selects that item in onOptionsItemSelected.

i.e.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.my_location:
            // User chose the "Favorite" action, mark the current item
            // as a favorite...
            ShowcaseConfig config = new ShowcaseConfig();
            config.setDelay(500); // half second between each showcase view

            MaterialShowcaseSequence sequence = new MaterialShowcaseSequence(this, SHOWCASE_ID);

            sequence.setConfig(config);

            sequence.addSequenceItem(findViewById(R.id.action_my_location),
                    "This is button one", "GOT IT");
            sequence.start();
            Toast.makeText(MapsActivity.this, "My location action press", Toast.LENGTH_SHORT).show();

            return true;

        default:
            // If we got here, the user's action was not recognized.
            // Invoke the superclass to handle it.
            return super.onOptionsItemSelected(item);
    }
}

The above code works.

Is it possible to get a view reference in onCreateOptionsMenu? Everything else I've tried gives me a null object reference for the view.

I've tried this answer too, to no success.

I should mention that for the actionBar I used android's action bar tutorial.

Thanks guys.

EDIT:

This is what I've tried to do now:

@Override
    public void invalidateOptionsMenu() {
        super.invalidateOptionsMenu();

    }
    MenuItem mi;
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        mi = menu.findItem(R.id.action_my_location);
        new MaterialShowcaseView.Builder(this)
                .setTarget(mi.getActionView())
                .setDismissText("GOT IT")
                .setContentText("This is some amazing feature you should know about")
                .setDelay(300) // optional but starting animations immediately in onCreate can make them choppy
                .singleUse("101010110") // provide a unique ID used to ensure it is only shown once
                .show();
        return super.onPrepareOptionsMenu(menu);
}

Error:

java.lang.NullPointerException: Attempt to invoke virtual method 'void
  android.view.View.getLocationInWindow(int[])' on a null object
  reference

Body:
You need this class:

public class ToolbarActionItemTarget implements Target {

private final Toolbar toolbar;
private final int menuItemId;

public ToolbarActionItemTarget(Toolbar toolbar, @IdRes int itemId) {
    this.toolbar = toolbar;
    this.menuItemId = itemId;
}

@Override
public Point getPoint() {
    return new ViewTarget(toolbar.findViewById(menuItemId)).getPoint();
}

So:

showcaseView = new ShowcaseView.Builder(getActivity())
            .setTarget(Target.NONE)
            .setTarget(new ToolbarActionItemTarget(toolbar, R.id.action_view))

Referenced by: https://github.com/amlcurran/ShowcaseView/releases/tag/5.3.0

`


问:
Vimeo videos should play one after the another
I am using divi theme and there I have added vimeo videos using the video module slider. How I can play the vimeo videos automatically one after the another using video slider module in divi theme?</p>

答:
You should be able to achieve this, with the help of Vimeo's Javascript API.

If you have a look at their event section, you will find the "on ended" event handeler. An example could be:

```<code><div id="player"></div>

<script src="https://player.vimeo.com/api/player.js"></script>
<script>
    var options = {
        id: 59777392,
        width: 640
    };

    var player = new Vimeo.Player('player', options);

    player.on('ended', function() {

        // Change video id and show your new video
        var options = {
            id: 59777392
        };

        var player = new Vimeo.Player('player', options);

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

It could be coded up in a more beautiful maner, but this should point you in the right direction. Hope it helps.

Body:
You should be able to achieve this, with the help of Vimeo's Javascript API.

If you have a look at their event section, you will find the "on ended" event handeler. An example could be:

<div id="player"></div>

<script src="https://player.vimeo.com/api/player.js"></script>
<script>
    var options = {
        id: 59777392,
        width: 640
    };

    var player = new Vimeo.Player('player', options);

    player.on('ended', function() {

        // Change video id and show your new video
        var options = {
            id: 59777392
        };

        var player = new Vimeo.Player('player', options);

    });
</script>

It could be coded up in a more beautiful maner, but this should point you in the right direction. Hope it helps.


答:
You should define this.state in a constructor like

```<code>constructor(props) {
  super(props);
  this.state = {
     visible: true
  };
}
</code>```

Hence, your code should be

```<code>class Hello extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      visible: true
    };
  }

  render() {}
}
</code>```

From React docs:

The constructor is the right place to initialize state. If you don't
  initialize state and you don't bind methods, you don't need to
  implement a constructor for your React component.

Title: ReactJS - Unexpected token '.' error

Body:
You should define this.state in a constructor like

constructor(props) {
  super(props);
  this.state = {
     visible: true
  };
}

Hence, your code should be

class Hello extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      visible: true
    };
  }

  render() {}
}

From React docs:

The constructor is the right place to initialize state. If you don't
  initialize state and you don't bind methods, you don't need to
  implement a constructor for your React component.


问:
TensorFlow Model Restore ValueError - At least two variables have the same name
I have saved a model and now I am trying to restore it, after restoring it works for the first time correctly but when I press 'TEST' button on the same running program to test another image it gives error

ValueError: At least two variables have the same name: Variable_2/Adam

```<code>def train_neural_network(x):
    prediction = neural_network_model(x)#logits

    softMax=tf.nn.softmax_cross_entropy_with_logits(
            logits=prediction, labels=y)#prediction and original comapriosn
    cost = tf.reduce_mean(softMax)#total loss
    optimizer = tf.train.AdamOptimizer(learning_rate=0.001).minimize(cost)#learning_rate=0.01
    hm_epochs = 20

    new_saver = tf.train.Saver()
    with tf.Session() as sess:
        global s
        s=sess
        sess.run(tf.global_variables_initializer())
        new_saver = tf.train.import_meta_graph('../MY_MODELS/my_MNIST_Model_1.meta')
        new_saver.restore(s, tf.train.latest_checkpoint('../MY_MODELS'))

        correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1))

        accuracy = tf.reduce_mean(tf.cast(correct, 'float'))

        print('Accuracy:', accuracy.eval(
            {x: mnist.test.images, y: mnist.test.labels}))
</code>```

答:
The graph which you have loaded already has all the variables needed for inference. You need to load the tensors like accuracy from the saved graph. In your case you have same variables declared outside, which conflicts with the variables in the graph.

During training, if you have named your tensor accuracy with a name='accuracy', then you can load it from the graph using: get_tensor_by_name('accuracy:0'). In your example, you need to load the input tensors x and y also from the graph. Your code should be like:

```<code>def inference():
   loaded_graph = tf.Graph()
   new_saver = tf.train.Saver()
   with tf.Session(graph=loaded_graph) as sess:
       new_saver = tf.train.import_meta_graph('../MY_MODELS/my_MNIST_Model_1.meta')
       new_saver.restore(s, tf.train.latest_checkpoint('../MY_MODELS'))

       #Get the tensors by their variable name
       # Note: the names of the following tensors have to be declared in your train graph for this to work. So just name them appropriately.
      _accuracy = loaded_graph.get_tensor_by_name('accuracy:0')
      _x  = loaded_graph.get_tensor_by_name('x:0')
      _y  = loaded_graph.get_tensor_by_name('y:0')

       print('Accuracy:', _accuracy.eval(
        {_x: mnist.test.images, _y: mnist.test.labels}))
</code>```

Body:
I have saved a model and now I am trying to restore it, after restoring it works for the first time correctly but when I press 'TEST' button on the same running program to test another image it gives error

ValueError: At least two variables have the same name: Variable_2/Adam

def train_neural_network(x):
    prediction = neural_network_model(x)#logits

    softMax=tf.nn.softmax_cross_entropy_with_logits(
            logits=prediction, labels=y)#prediction and original comapriosn
    cost = tf.reduce_mean(softMax)#total loss
    optimizer = tf.train.AdamOptimizer(learning_rate=0.001).minimize(cost)#learning_rate=0.01
    hm_epochs = 20

    new_saver = tf.train.Saver()
    with tf.Session() as sess:
        global s
        s=sess
        sess.run(tf.global_variables_initializer())
        new_saver = tf.train.import_meta_graph('../MY_MODELS/my_MNIST_Model_1.meta')
        new_saver.restore(s, tf.train.latest_checkpoint('../MY_MODELS'))

        correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1))

        accuracy = tf.reduce_mean(tf.cast(correct, 'float'))

        print('Accuracy:', accuracy.eval(
            {x: mnist.test.images, y: mnist.test.labels}))

Body:
The graph which you have loaded already has all the variables needed for inference. You need to load the tensors like accuracy from the saved graph. In your case you have same variables declared outside, which conflicts with the variables in the graph.

During training, if you have named your tensor accuracy with a name='accuracy', then you can load it from the graph using: get_tensor_by_name('accuracy:0'). In your example, you need to load the input tensors x and y also from the graph. Your code should be like:

def inference():
   loaded_graph = tf.Graph()
   new_saver = tf.train.Saver()
   with tf.Session(graph=loaded_graph) as sess:
       new_saver = tf.train.import_meta_graph('../MY_MODELS/my_MNIST_Model_1.meta')
       new_saver.restore(s, tf.train.latest_checkpoint('../MY_MODELS'))

       #Get the tensors by their variable name
       # Note: the names of the following tensors have to be declared in your train graph for this to work. So just name them appropriately.
      _accuracy = loaded_graph.get_tensor_by_name('accuracy:0')
      _x  = loaded_graph.get_tensor_by_name('x:0')
      _y  = loaded_graph.get_tensor_by_name('y:0')

       print('Accuracy:', _accuracy.eval(
        {_x: mnist.test.images, _y: mnist.test.labels}))


问:
Is there a way of doing the cast from xsd:duration to xsd:time in SPARQL?
For example I want to convert PT1H5M14.000S to 01:05:14

答:
You can just add the duration to a "zero" time:</p>

```<code>select * {
bind("PT1H5M14.000S"^^xsd:duration as ?x)
BIND("00:00:00"^^xsd:time + ?x as ?y) }
</code>```

Body:
You can just add the duration to a "zero" time:

select * {
bind("PT1H5M14.000S"^^xsd:duration as ?x)
BIND("00:00:00"^^xsd:time + ?x as ?y) }


问:
Fixing BeanNotOfRequiredTypeException on Spring proxy cast on a non-singleton bean?
I'm having an issue with pulling a Spring bean from an application context.

When I try;

```<code>InnerThread instance = (InnerThread) SpringContextFactory.getApplicationContext().getBean("innerThread", InnerThread.class);
</code>```

I get;

```<code>org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'innerThread' must be of type [com.generic.InnerThread], but was actually of type [$Proxy26]
</code>```

Without the specified class in the getBean() call I get a ClassCastException (which you can see in detail below).

The InnerThread bean is being initialized as a non-singleton, because I need multiple instances. The InnerThread class also extends Thread. The interesting thing is that this error shows up within OuterThread, which is set up in the exact same way the InnerThread is.

I've tried to include all relevant code listings/stack traces below. Could someone with more Spring experience tell me what is going on here?

Code/Configuration Listing

OuterThread.java snippet:

```<code>public class OuterThread extends Thread {
    private Queue<InnerThread> createInnerThreads() {
        Queue<InnerThread> threads = new ArrayBlockingQueue();

        ApplicationContext ctx = SpringContextFactory.getApplicationContext();
        int i = 0;
        for (SearchRule search : searches) {
            logger.debug("Number of times looped " + i++);
            //Seprated lines to get a better sense of what is going on
            Object proxy = ctx.getBean("innerThread", InnerThread.class);
            logger.debug(ReflectionToStringBuilder.toString(proxy));
            logger.debug("proxy.getClass(): " + proxy.getClass());
            logger.debug("proxy.getClass().getClassLoader(): " + proxy.getClass().getClassLoader());
            logger.debug("proxy.getClass().getDeclaringClass(): " + proxy.getClass().getDeclaringClass());
            logger.debug("InnerThread.class.getClassLoader(): " + InnerThread.class.getClassLoader());

            //---Exception here---
            InnerThread cst = (InnerThread) proxy;

            threads.add(cst);
        }
        return threads;
    }

    public static void main(String[] args) throws Exception {
        try {
            OuterThread instance = (OuterThread) SpringContextFactory.getApplicationContext().getBean("outerThread", OuterThread.class);
            instance.run();
        } catch (Exception ex) {
            logger.error("Fatal exception.", ex);
            throw ex;
        }
    }
}
</code>```

SpringContextFactory.java:

```<code>public class SpringContextFactory {
    static final Logger logger = LoggerFactory.getLogger(SpringContextFactory.class);
    private static ApplicationContext ctx;
    private static final String DEFAULT_PATH = "META-INF/app-context.xml";

    public static ApplicationContext getApplicationContext() {
        return getApplicationContext(DEFAULT_PATH);
    }

    public static synchronized ApplicationContext getApplicationContext(String path) {
        if (ctx == null) return createApplicationContext(path);
        else return ctx;
    }

    private static ApplicationContext createApplicationContext(String path) {
        if (logger.isDebugEnabled()) logger.debug("Loading Spring Context...");
        ctx = new ClassPathXmlApplicationContext(path);
        if (logger.isDebugEnabled()) logger.debug("Spring Context Loaded");
        return ctx;
    }
}
</code>```

app-context.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

    <!-- persistence context from separate jar -->
    <import resource="persistence-context.xml"/>

    <bean id="outerThread" class="com.generic.OuterThread" scope="prototype"/>
    <bean id="innerThread" class="com.generic.InnerThread" scope="prototype"/>

</beans>
</code>```

Stack Trace

```<code>2009-05-08 14:34:37,341 [main] DEBUG com.generic.OuterThread.init(OuterThread.java:59) - Initializing OuterThread object, com.generic.OuterThread@1c8fb4b[em=org.hibernate.ejb.EntityManagerImpl@e2892b,currentTime=java.util.GregorianCalendar[time=1241634874841,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="America/New_York",offset=-18000000,dstSavings=3600000,useDaylight=true,transitions=235,lastRule=java.util.SimpleTimeZone[id=America/New_York,offset=-18000000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2009,MONTH=4,WEEK_OF_YEAR=19,WEEK_OF_MONTH=2,DAY_OF_MONTH=6,DAY_OF_YEAR=126,DAY_OF_WEEK=4,DAY_OF_WEEK_IN_MONTH=1,AM_PM=1,HOUR=2,HOUR_OF_DAY=14,MINUTE=34,SECOND=34,MILLISECOND=841,ZONE_OFFSET=-18000000,DST_OFFSET=3600000],maxConcurrentThreads=5,reconId=3,reportUsername=TEST,useOffset=false,username=removed,uuid=bf61494d-ff96-431c-a41f-1e292d0c9fbe,name={T,h,r,e,a,d,-,1},priority=5,threadQ=<null>,eetop=0,single_step=false,daemon=false,stillborn=false,target=<null>,group=java.lang.ThreadGroup[name=main,maxpri=10],contextClassLoader=sun.misc.Launcher$AppClassLoader@11b86e7,inheritedAccessControlContext=java.security.AccessControlContext@1524d43,threadLocals=<null>,inheritableThreadLocals=java.lang.ThreadLocal$ThreadLocalMap@2cbc86,stackSize=0,nativeParkEventPointer=0,tid=9,threadStatus=0,parkBlocker=<null>,blocker=<null>,blockerLock=java.lang.Object@a68fd8,stopBeforeStart=false,throwableFromStop=<null>,uncaughtExceptionHandler=<null>]
2009-05-08 14:34:37,341 [main] DEBUG org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.doJoinTransaction(ExtendedEntityManagerCreator.java:385) - No local transaction to join
2009-05-08 14:34:37,529 [main] DEBUG com.generic.OuterThread.createInnerThreads(OuterThread.java:139) - Number of times looped 0
2009-05-08 14:34:37,529 [main] DEBUG org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:458) - Creating instance of bean 'searchThread' with merged definition [Root bean: class [com.generic.InnerThread]; scope=prototype; abstract=false; lazyInit=false; autowireCandidate=true; autowireMode=0; dependencyCheck=0; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in class path resource [META-INF/app-context.xml]]
2009-05-08 14:34:37,545 [main] DEBUG com.generic.InnerThread.<init>(InnerThread.java:50) - Constructing InnerThread object, com.generic.InnerThread@1080876[em=<null>,coolScheme=<null>,coolUrl=<null>,date=<null>,error=<null>,millisecondsTaken=0,thresholdMet=false,reconId=0,result=-2,searchId=0,username=<null>,uuid=<null>,name={T,h,r,e,a,d,-,2},priority=5,threadQ=<null>,eetop=0,single_step=false,daemon=false,stillborn=false,target=<null>,group=java.lang.ThreadGroup[name=main,maxpri=10],contextClassLoader=sun.misc.Launcher$AppClassLoader@11b86e7,inheritedAccessControlContext=java.security.AccessControlContext@1524d43,threadLocals=<null>,inheritableThreadLocals=java.lang.ThreadLocal$ThreadLocalMap@3aef16,stackSize=0,nativeParkEventPointer=0,tid=10,threadStatus=0,parkBlocker=<null>,blocker=<null>,blockerLock=java.lang.Object@126c6ea,stopBeforeStart=false,throwableFromStop=<null>,uncaughtExceptionHandler=<null>]
2009-05-08 14:34:37,545 [main] DEBUG org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:203) - Returning cached instance of singleton bean 'entityManagerFactory'
2009-05-08 14:34:37,545 [main] DEBUG org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:203) - Returning cached instance of singleton bean 'org.springframework.transaction.config.internalTransactionAdvisor'
2009-05-08 14:34:37,560 [main] DEBUG org.springframework.transaction.interceptor.AbstractFallbackTransactionAttributeSource.getTransactionAttribute(AbstractFallbackTransactionAttributeSource.java:108) - Adding transactional method [report] with attribute [PROPAGATION_REQUIRED,ISOLATION_DEFAULT]
2009-05-08 14:34:37,560 [main] DEBUG org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.buildAdvisors(AbstractAutoProxyCreator.java:494) - Creating implicit proxy for bean 'searchThread' with 0 common interceptors and 1 specific interceptors
2009-05-08 14:34:37,560 [main] DEBUG org.springframework.aop.framework.JdkDynamicAopProxy.getProxy(JdkDynamicAopProxy.java:113) - Creating JDK dynamic proxy: target source is SingletonTargetSource for target object [com.generic.InnerThread@1080876]
2009-05-08 14:34:37,591 [main] DEBUG com.generic.OuterThread.createInnerThreads(OuterThread.java:141) - $Proxy26@1594a88[h=org.springframework.aop.framework.JdkDynamicAopProxy@1f0cf51]
2009-05-08 14:34:37,591 [main] DEBUG com.generic.OuterThread.createInnerThreads(OuterThread.java:142) - proxy.getClass(): class $Proxy26
2009-05-08 14:34:37,591 [main] DEBUG com.generic.OuterThread.createInnerThreads(OuterThread.java:143) - proxy.getClass().getClassLoader(): sun.misc.Launcher$AppClassLoader@11b86e7
2009-05-08 14:34:37,591 [main] DEBUG com.generic.OuterThread.createInnerThreads(OuterThread.java:144) - proxy.getClass().getDeclaringClass(): null
2009-05-08 14:34:37,591 [main] DEBUG com.generic.OuterThread.createInnerThreads(OuterThread.java:145) - InnerThread.class.getClassLoader(): sun.misc.Launcher$AppClassLoader@11b86e7
2009-05-08 14:34:37,591 [main] ERROR com.generic.OuterThread.run(OuterThread.java:101) - Exception in OuterThread, ending reconciliation.
java.lang.ClassCastException: $Proxy26 cannot be cast to com.generic.InnerThread
    at com.generic.OuterThread.createInnerThreads(OuterThread.java:148)
    at com.generic.OuterThread.run(OuterThread.java:65)
    at com.generic.OuterThread.main(OuterThread.java:170)
</code>```

Similar questions that do not answer my question

Auto-cast Spring Beans

ClassCastException when casting to  the same class.

答:
I had the same problem:

This is just a guess, but try making
  an interface InnerThreadInterface,
  then let InnerThread class extend it.
       After that you should be able to do:

I use this way instead of what is posted above and it worked fine. There was no need of setting the proxy-target-class to true, this required more libraries that wasn't on my classpath.

```<code>InnerThreadInterface inner = (InnerThreadInterface)ctx.getBean("innerThread");
</code>```

Body:
I'm having an issue with pulling a Spring bean from an application context.

When I try;

InnerThread instance = (InnerThread) SpringContextFactory.getApplicationContext().getBean("innerThread", InnerThread.class);

I get;

org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'innerThread' must be of type [com.generic.InnerThread], but was actually of type [$Proxy26]

Without the specified class in the getBean() call I get a ClassCastException (which you can see in detail below).

The InnerThread bean is being initialized as a non-singleton, because I need multiple instances. The InnerThread class also extends Thread. The interesting thing is that this error shows up within OuterThread, which is set up in the exact same way the InnerThread is.

I've tried to include all relevant code listings/stack traces below. Could someone with more Spring experience tell me what is going on here?

Code/Configuration Listing

OuterThread.java snippet:

public class OuterThread extends Thread {
    private Queue<InnerThread> createInnerThreads() {
        Queue<InnerThread> threads = new ArrayBlockingQueue();

        ApplicationContext ctx = SpringContextFactory.getApplicationContext();
        int i = 0;
        for (SearchRule search : searches) {
            logger.debug("Number of times looped " + i++);
            //Seprated lines to get a better sense of what is going on
            Object proxy = ctx.getBean("innerThread", InnerThread.class);
            logger.debug(ReflectionToStringBuilder.toString(proxy));
            logger.debug("proxy.getClass(): " + proxy.getClass());
            logger.debug("proxy.getClass().getClassLoader(): " + proxy.getClass().getClassLoader());
            logger.debug("proxy.getClass().getDeclaringClass(): " + proxy.getClass().getDeclaringClass());
            logger.debug("InnerThread.class.getClassLoader(): " + InnerThread.class.getClassLoader());

            //---Exception here---
            InnerThread cst = (InnerThread) proxy;

            threads.add(cst);
        }
        return threads;
    }

    public static void main(String[] args) throws Exception {
        try {
            OuterThread instance = (OuterThread) SpringContextFactory.getApplicationContext().getBean("outerThread", OuterThread.class);
            instance.run();
        } catch (Exception ex) {
            logger.error("Fatal exception.", ex);
            throw ex;
        }
    }
}

SpringContextFactory.java:

public class SpringContextFactory {
    static final Logger logger = LoggerFactory.getLogger(SpringContextFactory.class);
    private static ApplicationContext ctx;
    private static final String DEFAULT_PATH = "META-INF/app-context.xml";

    public static ApplicationContext getApplicationContext() {
        return getApplicationContext(DEFAULT_PATH);
    }

    public static synchronized ApplicationContext getApplicationContext(String path) {
        if (ctx == null) return createApplicationContext(path);
        else return ctx;
    }

    private static ApplicationContext createApplicationContext(String path) {
        if (logger.isDebugEnabled()) logger.debug("Loading Spring Context...");
        ctx = new ClassPathXmlApplicationContext(path);
        if (logger.isDebugEnabled()) logger.debug("Spring Context Loaded");
        return ctx;
    }
}

app-context.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

    <import resource="persistence-context.xml"/>

    <bean id="outerThread" class="com.generic.OuterThread" scope="prototype"/>
    <bean id="innerThread" class="com.generic.InnerThread" scope="prototype"/>

</beans>

Stack Trace

2009-05-08 14:34:37,341 [main] DEBUG com.generic.OuterThread.init(OuterThread.java:59) - Initializing OuterThread object, com.generic.OuterThread@1c8fb4b[em=org.hibernate.ejb.EntityManagerImpl@e2892b,currentTime=java.util.GregorianCalendar[time=1241634874841,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="America/New_York",offset=-18000000,dstSavings=3600000,useDaylight=true,transitions=235,lastRule=java.util.SimpleTimeZone[id=America/New_York,offset=-18000000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2009,MONTH=4,WEEK_OF_YEAR=19,WEEK_OF_MONTH=2,DAY_OF_MONTH=6,DAY_OF_YEAR=126,DAY_OF_WEEK=4,DAY_OF_WEEK_IN_MONTH=1,AM_PM=1,HOUR=2,HOUR_OF_DAY=14,MINUTE=34,SECOND=34,MILLISECOND=841,ZONE_OFFSET=-18000000,DST_OFFSET=3600000],maxConcurrentThreads=5,reconId=3,reportUsername=TEST,useOffset=false,username=removed,uuid=bf61494d-ff96-431c-a41f-1e292d0c9fbe,name={T,h,r,e,a,d,-,1},priority=5,threadQ=<null>,eetop=0,single_step=false,daemon=false,stillborn=false,target=<null>,group=java.lang.ThreadGroup[name=main,maxpri=10],contextClassLoader=sun.misc.Launcher$AppClassLoader@11b86e7,inheritedAccessControlContext=java.security.AccessControlContext@1524d43,threadLocals=<null>,inheritableThreadLocals=java.lang.ThreadLocal$ThreadLocalMap@2cbc86,stackSize=0,nativeParkEventPointer=0,tid=9,threadStatus=0,parkBlocker=<null>,blocker=<null>,blockerLock=java.lang.Object@a68fd8,stopBeforeStart=false,throwableFromStop=<null>,uncaughtExceptionHandler=<null>]
2009-05-08 14:34:37,341 [main] DEBUG org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.doJoinTransaction(ExtendedEntityManagerCreator.java:385) - No local transaction to join
2009-05-08 14:34:37,529 [main] DEBUG com.generic.OuterThread.createInnerThreads(OuterThread.java:139) - Number of times looped 0
2009-05-08 14:34:37,529 [main] DEBUG org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:458) - Creating instance of bean 'searchThread' with merged definition [Root bean: class [com.generic.InnerThread]; scope=prototype; abstract=false; lazyInit=false; autowireCandidate=true; autowireMode=0; dependencyCheck=0; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in class path resource [META-INF/app-context.xml]]
2009-05-08 14:34:37,545 [main] DEBUG com.generic.InnerThread.<init>(InnerThread.java:50) - Constructing InnerThread object, com.generic.InnerThread@1080876[em=<null>,coolScheme=<null>,coolUrl=<null>,date=<null>,error=<null>,millisecondsTaken=0,thresholdMet=false,reconId=0,result=-2,searchId=0,username=<null>,uuid=<null>,name={T,h,r,e,a,d,-,2},priority=5,threadQ=<null>,eetop=0,single_step=false,daemon=false,stillborn=false,target=<null>,group=java.lang.ThreadGroup[name=main,maxpri=10],contextClassLoader=sun.misc.Launcher$AppClassLoader@11b86e7,inheritedAccessControlContext=java.security.AccessControlContext@1524d43,threadLocals=<null>,inheritableThreadLocals=java.lang.ThreadLocal$ThreadLocalMap@3aef16,stackSize=0,nativeParkEventPointer=0,tid=10,threadStatus=0,parkBlocker=<null>,blocker=<null>,blockerLock=java.lang.Object@126c6ea,stopBeforeStart=false,throwableFromStop=<null>,uncaughtExceptionHandler=<null>]
2009-05-08 14:34:37,545 [main] DEBUG org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:203) - Returning cached instance of singleton bean 'entityManagerFactory'
2009-05-08 14:34:37,545 [main] DEBUG org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:203) - Returning cached instance of singleton bean 'org.springframework.transaction.config.internalTransactionAdvisor'
2009-05-08 14:34:37,560 [main] DEBUG org.springframework.transaction.interceptor.AbstractFallbackTransactionAttributeSource.getTransactionAttribute(AbstractFallbackTransactionAttributeSource.java:108) - Adding transactional method [report] with attribute [PROPAGATION_REQUIRED,ISOLATION_DEFAULT]
2009-05-08 14:34:37,560 [main] DEBUG org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.buildAdvisors(AbstractAutoProxyCreator.java:494) - Creating implicit proxy for bean 'searchThread' with 0 common interceptors and 1 specific interceptors
2009-05-08 14:34:37,560 [main] DEBUG org.springframework.aop.framework.JdkDynamicAopProxy.getProxy(JdkDynamicAopProxy.java:113) - Creating JDK dynamic proxy: target source is SingletonTargetSource for target object [com.generic.InnerThread@1080876]
2009-05-08 14:34:37,591 [main] DEBUG com.generic.OuterThread.createInnerThreads(OuterThread.java:141) - $Proxy26@1594a88[h=org.springframework.aop.framework.JdkDynamicAopProxy@1f0cf51]
2009-05-08 14:34:37,591 [main] DEBUG com.generic.OuterThread.createInnerThreads(OuterThread.java:142) - proxy.getClass(): class $Proxy26
2009-05-08 14:34:37,591 [main] DEBUG com.generic.OuterThread.createInnerThreads(OuterThread.java:143) - proxy.getClass().getClassLoader(): sun.misc.Launcher$AppClassLoader@11b86e7
2009-05-08 14:34:37,591 [main] DEBUG com.generic.OuterThread.createInnerThreads(OuterThread.java:144) - proxy.getClass().getDeclaringClass(): null
2009-05-08 14:34:37,591 [main] DEBUG com.generic.OuterThread.createInnerThreads(OuterThread.java:145) - InnerThread.class.getClassLoader(): sun.misc.Launcher$AppClassLoader@11b86e7
2009-05-08 14:34:37,591 [main] ERROR com.generic.OuterThread.run(OuterThread.java:101) - Exception in OuterThread, ending reconciliation.
java.lang.ClassCastException: $Proxy26 cannot be cast to com.generic.InnerThread
    at com.generic.OuterThread.createInnerThreads(OuterThread.java:148)
    at com.generic.OuterThread.run(OuterThread.java:65)
    at com.generic.OuterThread.main(OuterThread.java:170)

Similar questions that do not answer my question

Auto-cast Spring Beans

ClassCastException when casting to  the same class.

Body:
I had the same problem:

This is just a guess, but try making
  an interface InnerThreadInterface,
  then let InnerThread class extend it.
       After that you should be able to do:

I use this way instead of what is posted above and it worked fine. There was no need of setting the proxy-target-class to true, this required more libraries that wasn't on my classpath.

InnerThreadInterface inner = (InnerThreadInterface)ctx.getBean("innerThread");


问:
ViewGroup read all textview
If I use ViewGroup, Is have any method can read all TextView?</p>

```<code> ViewGroup viewGroup=(ViewGroup)view.getParent();
  int childCount = viewGroup.getChildCount();
       for (int i = 0; i < childCount; i++) {

                    TextView txtLikeStatus=(TextView)viewGroup.findViewById(R.id.ext);
                    String plus2= txtLikeStatus.getText().toString();
                    Toast.makeText(view.getContext(), "test:"+  txtLikeStatus, Toast.LENGTH_SHORT).show();
                            }
</code>```

答:
Yes Try this :

```<code> ViewGroup vg = (ViewGroup) view.getParent();
 for (int i = 0; i < vg.getChildCount(); i++) {
     View child = vg.getChildAt(i);
     if (child.getClass() == TextView.class) {
     //Do your work here.
     }
 }
</code>```

Hope this helps.

Title: ViewGroup read all textview

Body:
If I use ViewGroup, Is have any method can read all TextView?

 ViewGroup viewGroup=(ViewGroup)view.getParent();
  int childCount = viewGroup.getChildCount();
       for (int i = 0; i < childCount; i++) {

                    TextView txtLikeStatus=(TextView)viewGroup.findViewById(R.id.ext);
                    String plus2= txtLikeStatus.getText().toString();
                    Toast.makeText(view.getContext(), "test:"+  txtLikeStatus, Toast.LENGTH_SHORT).show();
                            }

Body:
Yes Try this :

 ViewGroup vg = (ViewGroup) view.getParent();
 for (int i = 0; i < vg.getChildCount(); i++) {
     View child = vg.getChildAt(i);
     if (child.getClass() == TextView.class) {
     //Do your work here.
     }
 }

Hope this helps.


问:
Git: replace all commits authors without changing history
I want to replace all of the commits authors names and emails before pushing changes into another repository. I'll need to make more changes and push them as well with replaced authors. But at the same time i want to preserve original authors in first repo.

I have found a lot of similar questions, but all of them suggesting solutions that are rewriting history. This will make it problematic to make more commits later on.

答:
To amplify what others have said:  The history is the commits.  The commits are identified by hash IDs.  The hash IDs are crypographic checksums of the commits' contents. If you change anything—even a single bit—in any commit, the checksum changes, so you have a different commit, so you have different history.

There is a potential light or two in all this darkness, though:

... all of them suggesting solutions that are rewriting history.  This will make it problematic to make more commits later on.

There are two different observations to make here:

Commit checksums, while cryptographically complex,1 are completely deterministic.  This means that if you make the same changes to the same inputs, you get the same results.  You can therefore build, at any time, a table of old-to-new hash IDs as long as you have the change-rule-set and the original inputs.

You can use this old ⟷ new mapping to compute the proper joining of the sub-graphs of disparate repositories, one that uses only "old" and one that uses any mix of old and/or new.  That is just a small matter of programming. :-)  Depending on how much you care about this problem, it's definitely solveable.  Just note that you must use a fully deterministic process when making your changes—e.g., you will need to keep the author and commit dates unchanged, or change them in a deterministic way.

There's often no need to do any of this at all, thanks to git notes.  Rather than copying old commits to new commits, simply attach notes to the old commits.

1Given that SHA-1 is now technically breakable given enough compute time and/or money thrown at the problem, it's no longer accurate to say "secure", hence "complex".  It's still impractical, though.


答:
I couldn't see an easy way of doing this other than by working backwards through the year using an offset of 0, -1, -2 etc. from the last one and searching for the first instance where the profit for the later year is not greater than the profit for the earlier year. If there is no such instance, then all years show an increasing profit.

```<code>=IFERROR(MATCH(FALSE,N(OFFSET($I2,0,COLUMN($B2)-COLUMN($B2:$H2),1,1))>N(OFFSET($H2,0,COLUMN($B2)-COLUMN($B2:$H2),1,1)),0)-1,"All in profit")
</code>```

This has to be entered as an array formula using CtrlShiftEnter

Title: Count years of increasing profits

Body:
I want to count how many years a company has increased the profit from now. So if the previous year had lower profits than this year it counts as 1 and goes one year back in past to count until there is one years profit higher than the year after that. So it must be a ongoing trend from this year (2017) so that it counts the years.

(Years of increases should be 5 not 4, sorry!)

In the picture it has to count until 2011 because there was a year(2012) without increasing profits relative to last year(2011).

So maybe its even possible with a Excel Function. Otherwise VBA is probably the way to do this.

EDIT: Is it possible to count years of steady profits, too? Like if 2015 = 5 and 2016 = 5 then this should not stop streak.

Body:
I couldn't see an easy way of doing this other than by working backwards through the year using an offset of 0, -1, -2 etc. from the last one and searching for the first instance where the profit for the later year is not greater than the profit for the earlier year. If there is no such instance, then all years show an increasing profit.

=IFERROR(MATCH(FALSE,N(OFFSET($I2,0,COLUMN($B2)-COLUMN($B2:$H2),1,1))>N(OFFSET($H2,0,COLUMN($B2)-COLUMN($B2:$H2),1,1)),0)-1,"All in profit")

This has to be entered as an array formula using CtrlShiftEnter


问:
Segmentation fault at first gl* call in LWJGL code
I am trying to create a program with LWJGL and OpenGL 3. However, when my code gets to the following line:

```<code>program = glCreateProgram();
</code>```

My program exits with the following output:

```<code>Version.getVerson() => 3.1.2 build 29
glfwInit() => true
glfwCreateWindow() => long
#
# A fatal error has been detected by the Java Runtime Environment:
#
#  SIGSEGV (0xb) at pc=0x00007faa30c86a67, pid=15863, tid=0x00007faa5a409700
#
# JRE version: Java(TM) SE Runtime Environment (8.0_131-b11) (build 1.8.0_131-b11)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (25.131-b11 mixed mode linux-amd64 compressed oops)
# Problematic frame:
# C  [liblwjgl_opengl.so+0x43a67]  Java_org_lwjgl_opengl_GL20_glCreateProgram+0x7
#
# Failed to write core dump. Core dumps have been disabled. To enable core dumping, try "ulimit -c unlimited" before starting Java again
#
# An error report file with more information is saved as:
# /home/tague/IdeaProjects/Jaav/hs_err_pid15863.log
#
# If you would like to submit a bug report, please visit:
#   http://bugreport.java.com/bugreport/crash.jsp
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
#

Process finished with exit code 134 (interrupted by signal 6: SIGABRT)
</code>```

I tried to add this line to my code, directly after my glfwMakeContextCurrent:

```<code>System.out.println("glGetString(GL_VERSION) => " + glGetString(GL_VERSION));
</code>```

But now, the program simply exits with a segfault there instead.

I am using the following GLFW window hints:

```<code>glfwDefaultWindowHints();

glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);

glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);  // Hide window at the start.
glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE); // Window is resizable.
</code>```

Edit: Here's the complete program, excluding things that aren't being called.

Main.java:

```<code>package me.tague.jaav;

import org.lwjgl.*;
import org.lwjgl.glfw.*;
import org.lwjgl.opengl.*;
import org.lwjgl.system.*;

import java.nio.*;

import static org.lwjgl.glfw.Callbacks.*;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.system.MemoryStack.*;
import static org.lwjgl.system.MemoryUtil.*;

public class Main {

    public long window;
    private Mesh main;

    // Run the actual LWJGL app.
    public void run () {
        System.out.println("Version.getVerson() => " + Version.getVersion());

        init();

        // System.out.println("glGetString(GL_VERSION) => " + glGetString(GL_VERSION)); // <=== ANOTHER SOURCE OF THE ERROR!!!

        float[] mainVerts = {
                -0.5f, -0.5f, 0.0f,
                0.5f, -0.5f, 0.0f,
                0.0f,  0.5f, 0.0f
        };
        main = new Mesh(mainVerts);

        // ...
    }

    private void init () {
        // Print GLFW errors to System.err.
        GLFWErrorCallback.createPrint(System.err).set();

        // Set up GLFW.
        if (!glfwInit()) throw new IllegalStateException("glfwInit() => false");
        else System.out.println("glfwInit() => true");

        glfwDefaultWindowHints();

        glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
        glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
        glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
        glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);

        glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);  // Hide window at the start.
        glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE); // Window is resizable.

        // Create the window.
        window = glfwCreateWindow(1024, 768, "Hello!", NULL, NULL);
        if (window == NULL) throw new RuntimeException("glfwCreateWindow() => NULL");
        else System.out.println("glfwCreateWindow() => long");

        glfwSetKeyCallback(window, (window, key, scancode, action, mods) -> {
            if (key == GLFW_KEY_ESCAPE && action == GLFW_RELEASE)
                glfwSetWindowShouldClose(window, true);
        });

        try (MemoryStack stack = stackPush()) {
            IntBuffer pWidth = stack.mallocInt(1);
            IntBuffer pHeight = stack.mallocInt(1);

            glfwGetWindowSize(window, pWidth, pHeight);

            GLFWVidMode vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor());

            // Center the window
            glfwSetWindowPos(
                    window,
                    (vidmode.width() - pWidth.get(0)) / 2,
                    (vidmode.height() - pHeight.get(0)) / 2
            );
        }

        glfwMakeContextCurrent(window);
        glfwSwapInterval(-1);
        glfwShowWindow(window);
    }

    public static void main(String[] args) {
        new Main().run();
    }
}
</code>```

Mesh.java:

```<code>package me.tague.jaav;

import org.lwjgl.BufferUtils;

import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL15.*;
import static org.lwjgl.opengl.GL20.*;
import static org.lwjgl.opengl.GL30.*;

import java.nio.FloatBuffer;

public class Mesh {

    public Material material;

    public Mesh(float[] vertices) {
        // Set up a default, generic material.
        material = new Material();

        // ... some more stuff that isn't called yet.
    }
}
</code>```

Material.java:

```<code>package me.tague.jaav;

import java.io.*;

import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL20.*;

public class Material {
    private int program;

    public Material () {
        makeProgram("shaders/generic/vert.gl", "shaders/generic/frag.gl");
    }

    /**
     * Make an OpenGL Program, given vertex and fragment source files.
     * @param vert The filename for the vertex shader to use.
     * @param frag The filename for the fragment shader to use.
     * @return     The ID for the loaded program.
     */
    private void makeProgram(String vert, String frag) {
        // Create the program in OpenGL.
        program = glCreateProgram(); // <==== THE SOURCE OF THE ERROR !!!!!

        // ... more stuff that never runs
    }
}
</code>```

答: I found a solution: I was missing GL.createCapabilities() in my init. This function is required before any gl* calls are made.

Body:
I am trying to create a program with LWJGL and OpenGL 3. However, when my code gets to the following line:

program = glCreateProgram();

My program exits with the following output:

Version.getVerson() => 3.1.2 build 29
glfwInit() => true
glfwCreateWindow() => long
#
# A fatal error has been detected by the Java Runtime Environment:
#
#  SIGSEGV (0xb) at pc=0x00007faa30c86a67, pid=15863, tid=0x00007faa5a409700
#
# JRE version: Java(TM) SE Runtime Environment (8.0_131-b11) (build 1.8.0_131-b11)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (25.131-b11 mixed mode linux-amd64 compressed oops)
# Problematic frame:
# C  [liblwjgl_opengl.so+0x43a67]  Java_org_lwjgl_opengl_GL20_glCreateProgram+0x7
#
# Failed to write core dump. Core dumps have been disabled. To enable core dumping, try "ulimit -c unlimited" before starting Java again
#
# An error report file with more information is saved as:
# /home/tague/IdeaProjects/Jaav/hs_err_pid15863.log
#
# If you would like to submit a bug report, please visit:
#   http://bugreport.java.com/bugreport/crash.jsp
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
#

Process finished with exit code 134 (interrupted by signal 6: SIGABRT)

I tried to add this line to my code, directly after my glfwMakeContextCurrent:

System.out.println("glGetString(GL_VERSION) => " + glGetString(GL_VERSION));

But now, the program simply exits with a segfault there instead.

I am using the following GLFW window hints:

glfwDefaultWindowHints();

glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);

glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);  // Hide window at the start.
glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE); // Window is resizable.

Edit: Here's the complete program, excluding things that aren't being called.

Main.java:

package me.tague.jaav;

import org.lwjgl.*;
import org.lwjgl.glfw.*;
import org.lwjgl.opengl.*;
import org.lwjgl.system.*;

import java.nio.*;

import static org.lwjgl.glfw.Callbacks.*;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.system.MemoryStack.*;
import static org.lwjgl.system.MemoryUtil.*;

public class Main {

    public long window;
    private Mesh main;

    // Run the actual LWJGL app.
    public void run () {
        System.out.println("Version.getVerson() => " + Version.getVersion());

        init();

        // System.out.println("glGetString(GL_VERSION) => " + glGetString(GL_VERSION)); // <=== ANOTHER SOURCE OF THE ERROR!!!

        float[] mainVerts = {
                -0.5f, -0.5f, 0.0f,
                0.5f, -0.5f, 0.0f,
                0.0f,  0.5f, 0.0f
        };
        main = new Mesh(mainVerts);

        // ...
    }

    private void init () {
        // Print GLFW errors to System.err.
        GLFWErrorCallback.createPrint(System.err).set();

        // Set up GLFW.
        if (!glfwInit()) throw new IllegalStateException("glfwInit() => false");
        else System.out.println("glfwInit() => true");

        glfwDefaultWindowHints();

        glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
        glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
        glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
        glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);

        glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);  // Hide window at the start.
        glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE); // Window is resizable.

        // Create the window.
        window = glfwCreateWindow(1024, 768, "Hello!", NULL, NULL);
        if (window == NULL) throw new RuntimeException("glfwCreateWindow() => NULL");
        else System.out.println("glfwCreateWindow() => long");

        glfwSetKeyCallback(window, (window, key, scancode, action, mods) -> {
            if (key == GLFW_KEY_ESCAPE && action == GLFW_RELEASE)
                glfwSetWindowShouldClose(window, true);
        });

        try (MemoryStack stack = stackPush()) {
            IntBuffer pWidth = stack.mallocInt(1);
            IntBuffer pHeight = stack.mallocInt(1);

            glfwGetWindowSize(window, pWidth, pHeight);

            GLFWVidMode vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor());

            // Center the window
            glfwSetWindowPos(
                    window,
                    (vidmode.width() - pWidth.get(0)) / 2,
                    (vidmode.height() - pHeight.get(0)) / 2
            );
        }

        glfwMakeContextCurrent(window);
        glfwSwapInterval(-1);
        glfwShowWindow(window);
    }

    public static void main(String[] args) {
        new Main().run();
    }
}

Mesh.java:

package me.tague.jaav;

import org.lwjgl.BufferUtils;

import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL15.*;
import static org.lwjgl.opengl.GL20.*;
import static org.lwjgl.opengl.GL30.*;

import java.nio.FloatBuffer;

public class Mesh {

    public Material material;

    public Mesh(float[] vertices) {
        // Set up a default, generic material.
        material = new Material();

        // ... some more stuff that isn't called yet.
    }
}

Material.java:

package me.tague.jaav;

import java.io.*;

import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL20.*;

public class Material {
    private int program;

    public Material () {
        makeProgram("shaders/generic/vert.gl", "shaders/generic/frag.gl");
    }

    /**
     * Make an OpenGL Program, given vertex and fragment source files.
     * @param vert The filename for the vertex shader to use.
     * @param frag The filename for the fragment shader to use.
     * @return     The ID for the loaded program.
     */
    private void makeProgram(String vert, String frag) {
        // Create the program in OpenGL.
        program = glCreateProgram(); // <==== THE SOURCE OF THE ERROR !!!!!

        // ... more stuff that never runs
    }
}


问:
Running statistics on multiple lines in bash
I have multiple HTTP headers in one giant file, separated with one empty line.

```<code>Host
Connection
Accept
From
User-Agent
Accept-Encoding

Host
Connection
Accept
From
User-Agent
Accept-Encoding
X-Forwarded-For

cookie
Cache-Control
referer
x-fb-sim-hni
Host
Accept
user-agent
x-fb-net-sid
x-fb-net-hni
X-Purpose
accept-encoding
x-fb-http-engine
Connection

User-Agent
Host
Connection
Accept-Encoding
</code>```

I have approximately 10,000,000 of headers separated with an empty line.
If I want to discover trends, like header order, I want to do aggregate headers to a one-liner (how I can aggregate lines ending with an empty line and do that separately for all headers?):

Host,Connection,Accept,From,User-Agent,Accept-Encoding

and follow with: uniq -c|sort -nk1,
so I could receive:

```<code>197897 Host,Connection,Accept,From,User-Agent,Accept-Encoding
8732233 User-Agent,Host,Connection,Accept-Encoding
</code>```

What would be the best approach and most effective one to parse that massive file and get that data?

Thanks for hints.

答:
Using your your 1.5milGETs.txt file (and converting the triple \n\n\n to \n\n to separate blocks) you can use ruby in paragraph mode:

```<code>$ ruby -F'\n' -lane 'BEGIN{h=Hash.new(0); $/=""
                                       def commafy(n)
                                             n.to_s.reverse.gsub(/...(?=.)/,"\\&,").reverse
                                         end
                                         }
                                         h[$F.join(",")]+=1
                                        # p $_
                              END{ printf "Total blocks: %s\n", commafy(h.values.sum)
                                      h2=h.sort_by {|k,v| -v}
                                      h2[0..10].map {|k,v| printf "%10s %s\n", commafy(v), k}
                                      }' 1.5milGETs.txt
</code>```

That prints the total number of blocks, sorts them large->small, prints the top 10.

Prints:

```<code>Total blocks: 1,262,522
    71,639 Host,Accept,User-Agent,Pragma,Connection
    70,975 Host,ros-SecurityFlags,ros-SessionTicket,ros-Challenge,ros-HeadersHmac,Scs-Ticket,If-Modified-Since,User-Agent
    40,781 Host,Accept,User-Agent,Pragma,nnCoection,Connection,X-Forwarded-For
    35,485 Accept,ros-SecurityFlags,ros-SessionTicket,ros-Challenge,ros-HeadersHmac,Scs-Ticket,If-Modified-Since,User-Agent,Accept-Language,UA-CPU,Accept-Encoding,Host,Connection
    34,005 User-Agent,Host,Connection,Accept-Encoding
    30,668 Host,User-Agent,Accept-Encoding,Connection
    25,547 Host,Accept,Accept-Language,Connection,Accept-Encoding,User-Agent
    22,581 Host,User-Agent,Accept,Accept-Encoding
    19,311 Host,Connection,Accept,From,User-Agent,Accept-Encoding
    14,694 Host,Connection,User-Agent,Accept,Referer,Accept-Encoding,Accept-Language,Cookie
    12,290 Host,User-Agent,Accept-Encoding
</code>```

That takes about 8 seconds on a 6 year old Mac.

Awk will be 3x faster and entirely appropriate for this job.

Ruby will give you more output options and easier analysis of the data. You can create an interactive HTML documents; output JSON, quoted csv, xml trivially; interact with a database; invert keys and values in a statement; filter; etc.

Body:
I have multiple HTTP headers in one giant file, separated with one empty line.

Host
Connection
Accept
From
User-Agent
Accept-Encoding

Host
Connection
Accept
From
User-Agent
Accept-Encoding
X-Forwarded-For

cookie
Cache-Control
referer
x-fb-sim-hni
Host
Accept
user-agent
x-fb-net-sid
x-fb-net-hni
X-Purpose
accept-encoding
x-fb-http-engine
Connection

User-Agent
Host
Connection
Accept-Encoding

I have approximately 10,000,000 of headers separated with an empty line.
If I want to discover trends, like header order, I want to do aggregate headers to a one-liner (how I can aggregate lines ending with an empty line and do that separately for all headers?):

Host,Connection,Accept,From,User-Agent,Accept-Encoding

and follow with: uniq -c|sort -nk1,
so I could receive:

197897 Host,Connection,Accept,From,User-Agent,Accept-Encoding
8732233 User-Agent,Host,Connection,Accept-Encoding

What would be the best approach and most effective one to parse that massive file and get that data?

Thanks for hints.

Body:
Using your your 1.5milGETs.txt file (and converting the triple \n\n\n to \n\n to separate blocks) you can use ruby in paragraph mode:

$ ruby -F'\n' -lane 'BEGIN{h=Hash.new(0); $/=""
                                       def commafy(n)
                                             n.to_s.reverse.gsub(/...(?=.)/,"\\&,").reverse
                                         end
                                         }
                                         h[$F.join(",")]+=1
                                        # p $_
                              END{ printf "Total blocks: %s\n", commafy(h.values.sum)
                                      h2=h.sort_by {|k,v| -v}
                                      h2[0..10].map {|k,v| printf "%10s %s\n", commafy(v), k}
                                      }' 1.5milGETs.txt

That prints the total number of blocks, sorts them large->small, prints the top 10.

Prints:

Total blocks: 1,262,522
    71,639 Host,Accept,User-Agent,Pragma,Connection
    70,975 Host,ros-SecurityFlags,ros-SessionTicket,ros-Challenge,ros-HeadersHmac,Scs-Ticket,If-Modified-Since,User-Agent
    40,781 Host,Accept,User-Agent,Pragma,nnCoection,Connection,X-Forwarded-For
    35,485 Accept,ros-SecurityFlags,ros-SessionTicket,ros-Challenge,ros-HeadersHmac,Scs-Ticket,If-Modified-Since,User-Agent,Accept-Language,UA-CPU,Accept-Encoding,Host,Connection
    34,005 User-Agent,Host,Connection,Accept-Encoding
    30,668 Host,User-Agent,Accept-Encoding,Connection
    25,547 Host,Accept,Accept-Language,Connection,Accept-Encoding,User-Agent
    22,581 Host,User-Agent,Accept,Accept-Encoding
    19,311 Host,Connection,Accept,From,User-Agent,Accept-Encoding
    14,694 Host,Connection,User-Agent,Accept,Referer,Accept-Encoding,Accept-Language,Cookie
    12,290 Host,User-Agent,Accept-Encoding

That takes about 8 seconds on a 6 year old Mac.

Awk will be 3x faster and entirely appropriate for this job.

Ruby will give you more output options and easier analysis of the data. You can create an interactive HTML documents; output JSON, quoted csv, xml trivially; interact with a database; invert keys and values in a statement; filter; etc.


问:
Use commander in typescript
I try to use commander in typescript and I could like to give a proper type to my cli. So I start with this code:

```<code>import * as program from "commander";

const cli = program
  .version("1.0.0")
  .usage("[options]")
  .option("-d, --debug", "activate more debug messages. Can be set by env var DEBUG.", false)
  .parse(process.argv);

console.log(cli.debug)
</code>```

But I get this error:

```<code>example.ts(9,17): error TS2339: Property 'debug' does not exist on type 'Command'.
</code>```

So I tried to add an interface, as documented here:

```<code>import * as program from "commander";

interface InterfaceCLI extends commander.Command {
  debug?: boolean;
}

const cli: InterfaceCLI = program
  .version("1.0.0")
  .usage("[options]")
  .option("-d, --debug", "activate more debug messages. Can be set by env var DEBUG.", false)
  .parse(process.argv);

console.log(cli.debug)
</code>```

and I get this error:

```<code>example.ts(3,32): error TS2503: Cannot find namespace 'commander'.
</code>```

From what I understand, cli is actually a class of type commander.Command So I tried to add a class:

```<code>import * as program from "commander";

class Cli extends program.Command {
    public debug: boolean;
}

const cli: Cli = program
  .version("1.0.0")
  .usage("[options]")
  .option("-d, --debug", "activate more debug messages. Can be set by env var DEBUG.", false)
  .parse(process.argv);

console.log(cli.debug)
</code>```

Which gives me this error:

```<code>example.ts(7,7): error TS2322: Type 'Command' is not assignable to type 'Cli'.
  Property 'debug' is missing in type 'Command'.
</code>```

I don't know how to add a property to the Command class, either in my file or in a new .d.ts file.

答:
With your first code snippet and the following dependencies, I do not get an error:

```<code>"dependencies": {
    "commander": "^2.11.0"
},
"devDependencies": {
  "@types/commander": "^2.9.1",
  "typescript": "^2.4.1"
}
</code>```

Typescript interprets cli.debug as any. I guess the type declarations have been updated. So, if you are fine with any, the problem is solved.

If you really want to tell Typescript the type of debug, declaration merging would in principle be the way to go. It basically works like this:

class C {
    public foo: number;
}

interface C {
    bar: number;
}

const c = new C();
const fooBar = c.foo + c.bar;
```

<p>However, there is a problem: <code>program.Command</code> is not a type but a variable. So, you cannot do this:</p>

<pre class="lang-js prettyprint-override"><code>interface program.Command {
    debug: boolean;
}
</code>```

And while you can do this:

function f1(): typeof program.Command {
    return program.Command;
}

type T = typeof program.Command;

function f2(): T {
    return program.Command;
}
```

<p>You can neither do this:</p>

<pre class="lang-js prettyprint-override"><code>interface typeof program.Command {
}
</code>```

Nor this:

type T = typeof program.Command;

interface T {
}
```

I do not know whether this problem could be solved or not.

Title: Use commander in typescript

Body:
I try to use commander in typescript and I could like to give a proper type to my cli. So I start with this code:

import * as program from "commander";

const cli = program
  .version("1.0.0")
  .usage("[options]")
  .option("-d, --debug", "activate more debug messages. Can be set by env var DEBUG.", false)
  .parse(process.argv);

console.log(cli.debug)

But I get this error:

example.ts(9,17): error TS2339: Property 'debug' does not exist on type 'Command'.

So I tried to add an interface, as documented here:

import * as program from "commander";

interface InterfaceCLI extends commander.Command {
  debug?: boolean;
}

const cli: InterfaceCLI = program
  .version("1.0.0")
  .usage("[options]")
  .option("-d, --debug", "activate more debug messages. Can be set by env var DEBUG.", false)
  .parse(process.argv);

console.log(cli.debug)

and I get this error:

example.ts(3,32): error TS2503: Cannot find namespace 'commander'.

From what I understand, cli is actually a class of type commander.Command So I tried to add a class:

import * as program from "commander";

class Cli extends program.Command {
    public debug: boolean;
}

const cli: Cli = program
  .version("1.0.0")
  .usage("[options]")
  .option("-d, --debug", "activate more debug messages. Can be set by env var DEBUG.", false)
  .parse(process.argv);

console.log(cli.debug)

Which gives me this error:

example.ts(7,7): error TS2322: Type 'Command' is not assignable to type 'Cli'.
  Property 'debug' is missing in type 'Command'.

I don't know how to add a property to the Command class, either in my file or in a new .d.ts file.

Body:
With your first code snippet and the following dependencies, I do not get an error:

"dependencies": {
    "commander": "^2.11.0"
},
"devDependencies": {
  "@types/commander": "^2.9.1",
  "typescript": "^2.4.1"
}

Typescript interprets cli.debug as any. I guess the type declarations have been updated. So, if you are fine with any, the problem is solved.

If you really want to tell Typescript the type of debug, declaration merging would in principle be the way to go. It basically works like this:

class C {
    public foo: number;
}

interface C {
    bar: number;
}

const c = new C();
const fooBar = c.foo + c.bar;

However, there is a problem: program.Command is not a type but a variable. So, you cannot do this:

interface program.Command {
    debug: boolean;
}

And while you can do this:

function f1(): typeof program.Command {
    return program.Command;
}

type T = typeof program.Command;

function f2(): T {
    return program.Command;
}

You can neither do this:

interface typeof program.Command {
}

Nor this:

type T = typeof program.Command;

interface T {
}

I do not know whether this problem could be solved or not.


问:
Want to find the issues
Assuming there's no syntax error and the column names and table names are correct, what's wrong with the MySQL query below?

(FOR EVERY USER WE HAVE, this is supposed to return the number of messages they sent)

```<code>select
u.user_id
, sum(case when um.message_id is not null then 1 else 0 end) as number_of_messages_sent
from users u
left join users_messages um
  on um.user_id = u.user_id
where um.status = 'sent'
group by
u.user_id
;
</code>```

答:
Presumably you expect to see users with no sent messages and a message count of 0, but you are not seeing them?  This is because you include WHERE um.status = 'sent' and this eliminates those records from the result set before the aggregation is performed.

There are a number of solutions to the problem.  Assuming Klaus, in the comment below, states that you'll get the effect you want by moving the condition into the JOIN clause.  You can also do WHERE um.status = 'sent' or um.message_id IS NULL (assuming message_id is declared NOT NULL) or LEFT JOIN (SELECT * FROM user_messages WHERE status = 'sent') AS um in the FROM clause.

Title: Want to find the issues

Body:
Assuming there's no syntax error and the column names and table names are correct, what's wrong with the MySQL query below?

(FOR EVERY USER WE HAVE, this is supposed to return the number of messages they sent)

select
u.user_id
, sum(case when um.message_id is not null then 1 else 0 end) as number_of_messages_sent
from users u
left join users_messages um
  on um.user_id = u.user_id
where um.status = 'sent'
group by
u.user_id
;


问:
Receive an array of strings from a function and find out it's length
I have this code:

```<code>char** SplitToWords(char* str);

int main()
{
    char** wordarr;
    char str[] = "This is a sentence";
    wordarr = SplitToWords(str);

    return 0;
}
</code>```

After the main comes the function implementation.

I am not sure the following does what I want it to do (i.e. receive an array of strings from a function):

```<code>wordarr = SplitToWords(str);
</code>```

I somehow managed to convince the compiler that it's ok, but I assume it just does something else.

If it does, how do I find out the length of the array (the number of strings in it).

Thanks

答:
```<code>#include "stdafx.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MAXSTRINGS  5000

int main(int argc, char *argv[]) {

    char *stringTable[MAXSTRINGS];

    char sentence[] = "This is a sentence";

    char *token = NULL;

    int i = 0;

    while ((token = strtok(token == NULL ? sentence : NULL, " ")) != NULL)
    {
        printf("%s\n\r", token);
        stringTable[i] = (char *)malloc(strlen(token) + 1);  //have no "plain" C compiler - VS C++ used so cast needed :)
        strcpy(stringTable[i++], token);
    }
    stringTable[i] = NULL; // if you need to iterate through later
    printf("%d tokens found\n\r", i);

    for (int y = 0; y < i; y++)
        free(stringTable[y]);
}
</code>```

Body:
I have this code:

char** SplitToWords(char* str);

int main()
{
    char** wordarr;
    char str[] = "This is a sentence";
    wordarr = SplitToWords(str);

    return 0;
}

After the main comes the function implementation.

I am not sure the following does what I want it to do (i.e. receive an array of strings from a function):

wordarr = SplitToWords(str);

I somehow managed to convince the compiler that it's ok, but I assume it just does something else.

If it does, how do I find out the length of the array (the number of strings in it).

Thanks