问:
Why does mysql_query() return TRUE with a SELECT statement?
According to the manual of mysql_query() and to everything I know about this function that I used so many times, it can either return a resource or FALSE if the query is a SELECT. Yet it returns TRUE from time to time.

How can this be? It never ever happened before. Is this a bug in PHP 5.3.2? Does anyone know anything about this?

The code is something like:

```<code>if (!$resource = mysql_query($query, $handle)) {
    throw some exception;
}

var_dump($query);
if ($resource === true && strpos($query, 'SELECT') !== false) {
    throw new Exception('mysql_query() returned TRUE for SELECT');
}
</code>```

It's pretty hard to reproduce, too. It happens only from time to time. I also noticed that it's likely this happens at the same time the server interrupts the connection suddenly, in which case it should return FALSE...

答:
What James was trying to say is that the function mysql_query() simply returns true if the query has been taken and executed properly. It has nothing to do with the results the query yields.

If you want to actually fetch the results, use mysql_fetch_assoc()/ mysql_fetch_array()/ mysql_results().

Body:
According to the manual of mysql_query() and to everything I know about this function that I used so many times, it can either return a resource or FALSE if the query is a SELECT. Yet it returns TRUE from time to time.

How can this be? It never ever happened before. Is this a bug in PHP 5.3.2? Does anyone know anything about this?

The code is something like:

if (!$resource = mysql_query($query, $handle)) {
    throw some exception;
}

var_dump($query);
if ($resource === true && strpos($query, 'SELECT') !== false) {
    throw new Exception('mysql_query() returned TRUE for SELECT');
}

It's pretty hard to reproduce, too. It happens only from time to time. I also noticed that it's likely this happens at the same time the server interrupts the connection suddenly, in which case it should return FALSE...


来源: stackexchange

问:
Loop and select ranges if some sheets contain an AutoFilter and others not
I have an Excel file with multiple sheets. Some of them contain an AutoFilter. Some others not.

Now, I want to loop through all of them and

a) if they have an Autofilter the first non-hidden cell below the AutoFilter should be selected.

b) if all rows are hidden below the AutoFilter the Cell B29 should be selected.

c) if there is no AutoFilter in the sheet the Cell CB29 should be selected.

I tried to combine the solutions from this question and this question but could not make it work so far:

```<code>Sub Select_Range ()
Dim b As Worksheet
For Each b In Worksheets
    If b.AutoFilterMode _
    Or b.AutoFilter.Range.Columns(1).SpecialCells(xlCellTypeVisible).Count > 1 _
    Then
    b.Select
    b.AutoFilter.Range.Offset(1).SpecialCells(xlCellTypeVisible).Cells(1, 2).Select
    Else
    b.Select
    b.Range("B29").Select
    End If
Next b
End Sub
</code>```

I get runtime error 91.

What do I need to change in my loop to make it work?

答:
If AutoFilterMode is false, no auto filter is active - and in that case AutoFilter is not set. This causes the runtime error 91.

You have to check AutoFilterMode and AutoFilter in two separate If-statements because you need to ensure that AutoFilter is set before checking it. VBA will always evaluate all parts of an IF-statement.

Try something like

```<code>For Each b In ThisWorkbook.Worksheets
    b.Select
    b.Range("B29").Select
    If b.AutoFilterMode Then
        If b.AutoFilter.Range.Columns(1).SpecialCells(xlCellTypeVisible).Count > 1 Then
            b.AutoFilter.Range.Offset(1).SpecialCells(xlCellTypeVisible).Cells(1, 2).Select
        End If
    End If
Next b
</code>```

(you should think about better variable names, b is really not a good name for a worksheet.)

ContentLicense: CC BY-SA 4.0

Body:
I have an Excel file with multiple sheets. Some of them contain an AutoFilter. Some others not.

Now, I want to loop through all of them and

a) if they have an Autofilter the first non-hidden cell below the AutoFilter should be selected.

b) if all rows are hidden below the AutoFilter the Cell B29 should be selected.

c) if there is no AutoFilter in the sheet the Cell CB29 should be selected.

I tried to combine the solutions from this question and this question but could not make it work so far:

Sub Select_Range ()
Dim b As Worksheet
For Each b In Worksheets
    If b.AutoFilterMode _
    Or b.AutoFilter.Range.Columns(1).SpecialCells(xlCellTypeVisible).Count > 1 _
    Then
    b.Select
    b.AutoFilter.Range.Offset(1).SpecialCells(xlCellTypeVisible).Cells(1, 2).Select
    Else
    b.Select
    b.Range("B29").Select
    End If
Next b
End Sub

I get runtime error 91.

What do I need to change in my loop to make it work?

Body:
If AutoFilterMode is false, no auto filter is active - and in that case AutoFilter is not set. This causes the runtime error 91.

You have to check AutoFilterMode and AutoFilter in two separate If-statements because you need to ensure that AutoFilter is set before checking it. VBA will always evaluate all parts of an IF-statement.

Try something like

For Each b In ThisWorkbook.Worksheets
    b.Select
    b.Range("B29").Select
    If b.AutoFilterMode Then
        If b.AutoFilter.Range.Columns(1).SpecialCells(xlCellTypeVisible).Count > 1 Then
            b.AutoFilter.Range.Offset(1).SpecialCells(xlCellTypeVisible).Cells(1, 2).Select
        End If
    End If
Next b

(you should think about better variable names, b is really not a good name for a worksheet.)


问:
In a .NET console app, is it possible to have a line of text stay visible in the console all the time?
I was thinking of adding a simple bandwidth monitor to a console application and I was wondering if it would be possible to keep a line in the console window visible at all times. I could set something up manually to pass new console output into a method that would get the contents of the console, clear the console, add the bandwidth data on the first row, then rewrite each line of previous information back to the console, etc.. but that seems like a really hacky way to go about it, and I'd be limited to the amount of rows visible at once in the console window (no scrolling).

Any idea?  Any built in functionality for this?   Example:

```<code>STATS: Downloaded: 2599b, Uploaded: 754b  <- this always stays at the top
constantly changing text
constantly changing text
constantly changing text
constantly changing text
constantly changing text
constantly changing text
constantly changing text
constantly changing text
constantly changing text
constantly changing text
constantly changing text
constantly changing text
</code>```

答:
```<code>for (int i = 0, j = 0; i < 10000; i++, j++)
{
    top = Console.CursorTop;
    left = Console.CursorLeft;
    Console.SetCursorPosition(0, 0);
    Console.WriteLine("STATS: Downloaded: {0}b, Uploaded: {1}b", i, j);
}
</code>```

This will keep the STATS at the top, but depending on the refresh rate and the data below it could become ugly.  Basically it will place the text at the very top of the Console window (at the top of the scroll).

ContentLicense: CC BY-SA 3.0

Body:
I was thinking of adding a simple bandwidth monitor to a console application and I was wondering if it would be possible to keep a line in the console window visible at all times. I could set something up manually to pass new console output into a method that would get the contents of the console, clear the console, add the bandwidth data on the first row, then rewrite each line of previous information back to the console, etc.. but that seems like a really hacky way to go about it, and I'd be limited to the amount of rows visible at once in the console window (no scrolling).

Any idea?  Any built in functionality for this?   Example:

STATS: Downloaded: 2599b, Uploaded: 754b  <- this always stays at the top
constantly changing text
constantly changing text
constantly changing text
constantly changing text
constantly changing text
constantly changing text
constantly changing text
constantly changing text
constantly changing text
constantly changing text
constantly changing text
constantly changing text

Body:
for (int i = 0, j = 0; i < 10000; i++, j++)
{
    top = Console.CursorTop;
    left = Console.CursorLeft;
    Console.SetCursorPosition(0, 0);
    Console.WriteLine("STATS: Downloaded: {0}b, Uploaded: {1}b", i, j);
}

This will keep the STATS at the top, but depending on the refresh rate and the data below it could become ugly.  Basically it will place the text at the very top of the Console window (at the top of the scroll).


问:
Microsoft.Azure.Management give access to Virtual Machines
I use Microsoft.Azure.Management to manage Virtual Machines for my tenant, using clientId, clientSecret and tenantId.
If another tenant wants to give me access to manage his Virtual Machines, is it possible to connect to his Virtual Machines using this way, changing only the tenantId?

Is it possible to give access to Virtual Machines using Microsoft authorization? And what flow would it be?

Or which way is the best for my needs?

```<code>using Microsoft.Azure.Management.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Authentication;
//...

var creds = new AzureCredentialsFactory().FromServicePrincipal(clientId, clientSecret, tenantId, AzureEnvironment.AzureGlobalCloud);

IAzure azure = Azure.Authenticate(creds).WithDefaultSubscription();

var machines = azure.VirtualMachines.List().ToList();
</code>```

答:
If another tenant wants to give me access to manage his Virtual
  Machines, is it possible to connect to his Virtual Machines using this
  way, changing only the tenantId?

Simply changing the tenant id will not work as the Service Principal (SP) you created to access VMs reside in the original tenant. Somehow you will need that SP to be linked to the other tenant.

Please see this answer for more details: Grant service principal access to application in other tenant.

Body:
I use Microsoft.Azure.Management to manage Virtual Machines for my tenant, using clientId, clientSecret and tenantId.
If another tenant wants to give me access to manage his Virtual Machines, is it possible to connect to his Virtual Machines using this way, changing only the tenantId?

Is it possible to give access to Virtual Machines using Microsoft authorization? And what flow would it be?

Or which way is the best for my needs?

using Microsoft.Azure.Management.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Authentication;
//...

var creds = new AzureCredentialsFactory().FromServicePrincipal(clientId, clientSecret, tenantId, AzureEnvironment.AzureGlobalCloud);

IAzure azure = Azure.Authenticate(creds).WithDefaultSubscription();

var machines = azure.VirtualMachines.List().ToList();


问:
How should I launch ipython notebook from Docker once a session has been launched?
I have to run ipython notebook using a docker image. I am on Windows 10. I have installed Docker Toolbox and pulled a docker image - all went fine. I have set up a bashrc file according to the instructions found there.

Here is the bashrc function for convenience:
kjupyter() {
  (sleep 3 && open "http://$(docker-machine ip docker2):8888")&
  docker run -v $PWD:/tmp/working -w=/tmp/working -p 8888:8888 --rm -it kaggle/python jupyter notebook  --ip="127.0.0.1" --no-browser --notebook-dir=/tmp/working
}

Now when I open the Docker Terminal and type kjupyter, the dashboard does not launch - makes sense bc of "--no-browser" so I need to launch it manually. Prompt windows says 'The Jupyter Notebook is running at: http://0.0.0.0:888/'. But when I type this into my browser (Chrome), it tells me it's not accessible. So how can I access the usual jupter dashboard?
Thanks.

答:
For me the thing with the bashrc did not work.
I looked into how create aliases for the cmd line on windows(which is was the bashrc thing basically does) but the options are limited.
So I just put in the command like it is.

```<code> (sleep 3 && open "http://$(docker-machine ip docker2):8888")&
 docker run -v $PWD:/tmp/working -w=/tmp/working -p 8888:8888 --rm -it kaggle/python jupyter notebook --ip="127.0.0.1" --no-browser --notebook-dir=/tmp/working
</code>```

I realized that the first part is just to open the Browser with the URL of jupyter.
So I cut that part. After some further search I ended up with:

```<code>docker run -v "%cd%":/tmp/working -w=/tmp/working -p 8888:8888 --rm -it kaggle/python jupyter notebook --no-browser --ip=0.0.0.0 --port=8888 --notebook-dir=/tmp/working --allow-root
</code>```

Replaced $PWD with "%cd%" and added --ip=0.0.0.0 --port=8888
This should get your jupyter up and running under http://localhost:8888
It will ask you for a token, just take the first token from the commandline outputed url (taking the whole url did not work for me strangely)

Body:
For me the thing with the bashrc did not work.
I looked into how create aliases for the cmd line on windows(which is was the bashrc thing basically does) but the options are limited.
So I just put in the command like it is.

 (sleep 3 && open "http://$(docker-machine ip docker2):8888")&
 docker run -v $PWD:/tmp/working -w=/tmp/working -p 8888:8888 --rm -it kaggle/python jupyter notebook --ip="127.0.0.1" --no-browser --notebook-dir=/tmp/working

I realized that the first part is just to open the Browser with the URL of jupyter.
So I cut that part. After some further search I ended up with:

docker run -v "%cd%":/tmp/working -w=/tmp/working -p 8888:8888 --rm -it kaggle/python jupyter notebook --no-browser --ip=0.0.0.0 --port=8888 --notebook-dir=/tmp/working --allow-root

Replaced $PWD with "%cd%" and added --ip=0.0.0.0 --port=8888
This should get your jupyter up and running under http://localhost:8888
It will ask you for a token, just take the first token from the commandline outputed url (taking the whole url did not work for me strangely)


问:
How to retrieve data from flask using Ajax without refreshing the page
In my html, I want to submit a form to server-side.
However, after the server-side(flask）receives this data,
I want the html page retrieve the data, and display it by Ajax without JQuery

I spent all day on that please help me. here is my data:

```<code>  <div class="login-container">
    <form action="/" method="POST" name='form1'>
      <table class="form-table">
          <tr>
            <td><span class="title-name">name:<span id="start">*</span>: </span>
              <input id="name" type="text" name="name" required></td>
          </tr>

          <tr>
            <td>
              <button class="button" type="reset" name="clear" for="form1">Clear</button>
              <button class="button" type="submit" name="submit" for="form1" onclick="submitForm()">Search</button>
            </td>
          </tr>
  </form>
  </div>
  </div>
</code>```

my js:

```<code>function submitForm(){
    //checkInput();
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        console.log(this.status);
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("bottom").innerHTML=xmlhttp.responseText;
      }
    };
    xhttp.open("POST", "/res", true);
    xhttp.send();
}
</code>```

my flask

```<code>from flask import Flask,send_file
from flask import request,jsonify

app = Flask(__name__)
req_dict=None
req_json=None

@app.route('/',methods=['GET','POST'])
def index():
    return send_file('index.html')

@app.route('/res',methods=['GET','POST'])
def success():
    if(request.method=='POST'):
        req_dict=dict(request.form)
        req_json=jsonify(req_dict)

    return req_json

</code>```

the data flow is : front-end > server side > ajax > front-end.

答:
To prevent an event, like submit, to use its default behavior, use: Event.preventDefault(). This allows you to create your own behavior on when something has to happen when a form is submitted.

Also, instead of listening for a click on the submit button, listen for submit on the form element. That is the element that you want to control.

Try to use addEventListener instead of inline attributes to listen for events. It will make your code a lot cleaner and easier to maintain and using inline attributes such as onclick is considered an outdated practice.

```<code><form id="form-one" action="/" method="POST" name='form1'>
  <table class="form-table">
    <tr>
      <td>
        <label for="name" class="title-name">name:<span id="start">*</span>: </label>
        <input id="name" type="text" name="name" required></td>
    </tr>
    <tr>
      <td>
        <button class="button" type="reset" name="clear" for="form1">Clear</button>
        <button class="button" type="submit" name="submit" for="form1">Search</button>
      </td>
    </tr>
  </table>
</form>
</code>```

I noticed a typo in the xhttp variable in side theonreadystatechange callback. Instead of xhttp, you used xmlhttp. Correct it.

```<code>var formOne = document.getElementById('form-one');

function submitForm(event){
    event.preventDefault(); // Prevent default submit behavior.
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        console.log(this.status);
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("bottom").innerHTML = xhttp.responseText;
      }
    };
    xhttp.open("POST", "/res", true);
    xhttp.send();
}

formOne.addEventListener('submit', submitForm);
</code>```

Body:
In my html, I want to submit a form to server-side.
However, after the server-side(flask）receives this data,
I want the html page retrieve the data, and display it by Ajax without JQuery

I spent all day on that please help me. here is my data:

    <form action="/" method="POST" name='form1'>

            name:*:
              <input id="name" type="text" name="name" required>

              <button class="button" type="reset" name="clear" for="form1">Clear</button>
              <button class="button" type="submit" name="submit" for="form1" onclick="submitForm()">Search</button>

  </form>

my js:

function submitForm(){
    //checkInput();
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        console.log(this.status);
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("bottom").innerHTML=xmlhttp.responseText;
      }
    };
    xhttp.open("POST", "/res", true);
    xhttp.send();
}

my flask

from flask import Flask,send_file
from flask import request,jsonify

app = Flask(__name__)
req_dict=None
req_json=None

@app.route('/',methods=['GET','POST'])
def index():
    return send_file('index.html')

@app.route('/res',methods=['GET','POST'])
def success():
    if(request.method=='POST'):
        req_dict=dict(request.form)
        req_json=jsonify(req_dict)

    return req_json

the data flow is : front-end > server side > ajax > front-end.

Body:
To prevent an event, like submit, to use its default behavior, use: Event.preventDefault(). This allows you to create your own behavior on when something has to happen when a form is submitted.

Also, instead of listening for a click on the submit button, listen for submit on the form element. That is the element that you want to control.

Try to use addEventListener instead of inline attributes to listen for events. It will make your code a lot cleaner and easier to maintain and using inline attributes such as onclick is considered an outdated practice.

<form id="form-one" action="/" method="POST" name='form1'>
  <table class="form-table">
    <tr>
      <td>
        <label for="name" class="title-name">name:<span id="start">*</span>:&nbsp;</label>
        <input id="name" type="text" name="name" required></td>
    </tr>
    <tr>
      <td>
        <button class="button" type="reset" name="clear" for="form1">Clear</button>
        <button class="button" type="submit" name="submit" for="form1">Search</button>
      </td>
    </tr>
  </table>
</form>

I noticed a typo in the xhttp variable in side theonreadystatechange callback. Instead of xhttp, you used xmlhttp. Correct it.

var formOne = document.getElementById('form-one');

function submitForm(event){
    event.preventDefault(); // Prevent default submit behavior.
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        console.log(this.status);
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("bottom").innerHTML = xhttp.responseText;
      }
    };
    xhttp.open("POST", "/res", true);
    xhttp.send();
}

formOne.addEventListener('submit', submitForm);


问:
How to Measure child expandable list height and width
I am using expandable list view to make 3 - level hierarchy, would like to know how to set internal list height and width.
I knew we have onMeasure for this purpose but in my case it not allowing me to capture whole space of parent list view.

may be I am giving wrong value to it, here is the code which is I am using for setting height and width of child expandable list.

```<code>    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {

        widthMeasureSpec = MeasureSpec.makeMeasureSpec(960,MeasureSpec.AT_MOST);
        heightMeasureSpec = MeasureSpec.makeMeasureSpec(800,MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
</code>```

Currently it appearing as follow

```<code><ParentGroup1                >
<ChildParentGroup>
<Child1>
<Child2>
<child3>
<ParentGroup2                >
</code>```

and it should appear like below.

```<code><ParentGroup1                >
<ChildParentGroup            >
<Child1                      >
<Child2                      >
<child3                      >
<ParentGroup2                >
</code>```

Please advise/suggest for the same.

Thanks for your time.

答:
Adding to muhammadSalem's answer. This is how I solved my problem by calculating the height of expandableListView's children's total height.

```<code> private fun getSubItemTotalHeight(groupPosition: Int): Int {
    val children: Int = mAdapter.getChildrenCount(groupPosition)

    val desiredWidth: Int = View.MeasureSpec.makeMeasureSpec(mExpandableListView.width,
            View.MeasureSpec.UNSPECIFIED)
    var subItemTotalHeight = 0
    repeat(children) {
        val child = mAdapter.getChildView(groupPosition, it, true, null, null)
        child.layoutParams = ViewGroup.LayoutParams(
                desiredWidth, View.MeasureSpec.UNSPECIFIED)
        child.measure(View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.UNSPECIFIED), View.MeasureSpec
                .makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED))
        subItemTotalHeight += child.measuredHeight
    }

    val dividerCount = children - 1
    val dividerTotalCount = (dividerCount * mExpandableListView.dividerHeight).toFloat()
    showToast(mExpandableListView.dividerHeight.toString())
    val totalDividerPixels = TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP,
            dividerTotalCount,
            resources.displayMetrics
    )
    return subItemTotalHeight + totalDividerPixels.toInt()
}
</code>```

One thing to note is that if you added a divider height for your expandableListview, you should include the calculations for it. What I did is convert the total divider height which is in dp into pixels and added it into the totalHeight. This solved the clipping issues I encountered.

Then to use it would be just :

```<code>    mExpandableListView.setOnGroupExpandListener { groupPosition ->
            mExpandableListView.layoutParams.height += getSubItemTotalHeight(groupPosition)
            mExpandableListView.requestLayout()
        }
        mExpandableListView.setOnGroupCollapseListener { groupPosition ->
            mExpandableListView.layoutParams.height -= getSubItemTotalHeight(groupPosition)
            mExpandableListView.requestLayout()
        }
</code>```

Body:
I am using expandable list view to make 3 - level hierarchy, would like to know how to set internal list height and width.
I knew we have onMeasure for this purpose but in my case it not allowing me to capture whole space of parent list view.

may be I am giving wrong value to it, here is the code which is I am using for setting height and width of child expandable list.

    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {

        widthMeasureSpec = MeasureSpec.makeMeasureSpec(960,MeasureSpec.AT_MOST);
        heightMeasureSpec = MeasureSpec.makeMeasureSpec(800,MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

Currently it appearing as follow

<ParentGroup1                >
<ChildParentGroup>
<Child1>
<Child2>
<child3>
<ParentGroup2                >

and it should appear like below.

<ParentGroup1                >
<ChildParentGroup            >
<Child1                      >
<Child2                      >
<child3                      >
<ParentGroup2                >

Please advise/suggest for the same.

Thanks for your time.

Body:
Adding to muhammadSalem's answer. This is how I solved my problem by calculating the height of expandableListView's children's total height.

 private fun getSubItemTotalHeight(groupPosition: Int): Int {
    val children: Int = mAdapter.getChildrenCount(groupPosition)

    val desiredWidth: Int = View.MeasureSpec.makeMeasureSpec(mExpandableListView.width,
            View.MeasureSpec.UNSPECIFIED)
    var subItemTotalHeight = 0
    repeat(children) {
        val child = mAdapter.getChildView(groupPosition, it, true, null, null)
        child.layoutParams = ViewGroup.LayoutParams(
                desiredWidth, View.MeasureSpec.UNSPECIFIED)
        child.measure(View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.UNSPECIFIED), View.MeasureSpec
                .makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED))
        subItemTotalHeight += child.measuredHeight
    }

    val dividerCount = children - 1
    val dividerTotalCount = (dividerCount * mExpandableListView.dividerHeight).toFloat()
    showToast(mExpandableListView.dividerHeight.toString())
    val totalDividerPixels = TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP,
            dividerTotalCount,
            resources.displayMetrics
    )
    return subItemTotalHeight + totalDividerPixels.toInt()
}

One thing to note is that if you added a divider height for your expandableListview, you should include the calculations for it. What I did is convert the total divider height which is in dp into pixels and added it into the totalHeight. This solved the clipping issues I encountered.

Then to use it would be just :

    mExpandableListView.setOnGroupExpandListener { groupPosition ->
            mExpandableListView.layoutParams.height += getSubItemTotalHeight(groupPosition)
            mExpandableListView.requestLayout()
        }
        mExpandableListView.setOnGroupCollapseListener { groupPosition ->
            mExpandableListView.layoutParams.height -= getSubItemTotalHeight(groupPosition)
            mExpandableListView.requestLayout()
        }


问:
How to access JavaScript variable in laravel route
how can access JavaScript variable in laravel blade route

this is my code:

```<code>'{{ URL::signedRoute('downloadvideo', ['video_Id' => videoId]) }}'
</code>```

and the error is:

```<code>Use of undefined constant videoId - assumed 'videoId'
</code>```

答:
You can try this</p>

```<code>url: "{{url('')}}/your_url/"+your_variable,
</code>```

Body:
how can access JavaScript variable in laravel blade route

this is my code:

'{{ URL::signedRoute('downloadvideo', ['video_Id' => videoId]) }}'

and the error is:

Use of undefined constant videoId - assumed 'videoId'

Body:
You can try this

url: "{{url('')}}/your_url/"+your_variable,


问:
Need to understand the solution to this query
We define an employee's total earnings to be their monthly  worked, and the maximum total earnings to be the maximum total earnings for any employee in the Employee table. Write a query to find the maximum total earnings for all employees as well as the total number of employees who have maximum total earnings. Then print these values as  space-separated integers.
This is link to the question for better understanding https://www.hackerrank.com/challenges/earnings-of-employees/problem

I am a beginner in SQL and couldn't understand the solution which was given

```<code>1.SELECT (months*salary) as earnings,
 2.COUNT(*) FROM Employee
3. GROUP BY earnings
4. ORDER BY earnings DESC
 5.LIMIT 1;
</code>```

I understood the first step where we are giving months*salary an Alias which is earnings
in the 2nd step we are counting the no. of employees from employee table. I didn't understand why we are using group by here, 4th and 5th step is also clear, we used order by clause in order to rank earnings from highest to lowest, and limit 1 will fetch me the highest value. But why GROUP BY?
 Ignore 1,2,3,4,5. These are just numbers I used for better clarity

答:
You have splitted the query errorneously.

Must be:

```<code>SELECT (months*salary) as earnings, -- 2 and 4
       COUNT(*)                     -- 4
FROM Employee                       -- 1
GROUP BY earnings                   -- 3
ORDER BY earnings DESC              -- 5
LIMIT 1;                            -- 6
</code>```

Step 1 - table Employee is used as data source

Step 2 - the value of the expression (months*salary) for each record in the table is calculated

Step 3 - the records which have the same value of the expression from (2) are treated as a group

Step 4 - for each group the value of the expression from (2) is put into output buffer,  and the amount of records in a group is calculated and added to output buffer

Step 5 - the rows in output buffer are sorted by the expression from (2) in descending order

Step 6 - the first row from the buffer (i.e. which have greatest value of the expression from (2)) is returned.

Body:
We define an employee's total earnings to be their monthly  worked, and the maximum total earnings to be the maximum total earnings for any employee in the Employee table. Write a query to find the maximum total earnings for all employees as well as the total number of employees who have maximum total earnings. Then print these values as  space-separated integers.
This is link to the question for better understanding https://www.hackerrank.com/challenges/earnings-of-employees/problem

I am a beginner in SQL and couldn't understand the solution which was given

1.SELECT (months*salary) as earnings,
 2.COUNT(*) FROM Employee
3. GROUP BY earnings
4. ORDER BY earnings DESC
 5.LIMIT 1;

I understood the first step where we are giving months*salary an Alias which is earnings
in the 2nd step we are counting the no. of employees from employee table. I didn't understand why we are using group by here, 4th and 5th step is also clear, we used order by clause in order to rank earnings from highest to lowest, and limit 1 will fetch me the highest value. But why GROUP BY?
 Ignore 1,2,3,4,5. These are just numbers I used for better clarity

Body:
You have splitted the query errorneously.

Must be:

SELECT (months*salary) as earnings, -- 2 and 4
       COUNT(*)                     -- 4
FROM Employee                       -- 1
GROUP BY earnings                   -- 3
ORDER BY earnings DESC              -- 5
LIMIT 1;                            -- 6

Step 1 - table Employee is used as data source

Step 2 - the value of the expression (months*salary) for each record in the table is calculated

Step 3 - the records which have the same value of the expression from (2) are treated as a group

Step 4 - for each group the value of the expression from (2) is put into output buffer,  and the amount of records in a group is calculated and added to output buffer

Step 5 - the rows in output buffer are sorted by the expression from (2) in descending order

Step 6 - the first row from the buffer (i.e. which have greatest value of the expression from (2)) is returned.


问:
Flutter error on updating Android Studio, Kotlin, Flutter, Dart plugins are incompatible with the new Android Studio version 4.0
I just updated the Android Studio to 4.0, and now I am getting the errors in my IDE that  Kotlin, Flutter, Dart plugins are incompatible with the new Android Studio version 4.0, what's the solution?</p>

答:
Press cmd + , to open Settings.

Look for Plugins in the tab bar.

You will see an option to update them and restart IDE, (I already did that, so it's not showing that option).

After updating, click on File > Invalidate Caches / Restart .... in Android Studio toolbar.

Run

```<code>flutter clean
</code>```

Body:
Press cmd + , to open Settings.

Look for Plugins in the tab bar.

You will see an option to update them and restart IDE, (I already did that, so it's not showing that option).

After updating, click on File > Invalidate Caches / Restart .... in Android Studio toolbar.

Run

flutter clean


问:
Not getting server response when passed as bean
I have a controller where I pass direct Bean and @valid annotation to validate.  I have created a custom annotation and added it to each field in the bean. It validates but doesn't give messages from a custom exception handler. Next, if I don't pass bean and pass request param in for every field then it gives proper response from a custom exception handler.

Adding screenshots.

You can see /group gives the response of validation when passed as @RequestParam and /check doesn't give a response message just gives 400 request code.

I have added a response message in custom exception handler

You can see the message passed in constraints violation exception. I Have created custom annotation which just validates special characters nothing else. It works for RequestParam.

答:
If 400 is in response maybe the problem is not in @Valid annotation just Group is interpreted as a bad parameter. Try deleting this annotation does 400 still appear?

One thing I don't understand is that you are creating a GET only with @Valid annotation maybe try adding also @RequestParam to it. What exactly is Group bean in context of this endpoint?

[EDIT: added as answer because of low rep]


问:
CUDA GPU processing: TypeError: compile_kernel() got an unexpected keyword argument 'boundscheck'
Today I started working with CUDA and GPU processing. I found this tutorial:
https://www.geeksforgeeks.org/running-python-script-on-gpu/

Unfortunately my first attempt to run gpu code failed:

```<code>from numba import jit, cuda
import numpy as np
# to measure exec time
from timeit import default_timer as timer

# normal function to run on cpu
def func(a):
    for i in range(10000000):
        a[i]+= 1

# function optimized to run on gpu
@jit(target ="cuda")
def func2(a):
    for i in range(10000000):
        a[i]+= 1
if __name__=="__main__":
    n = 10000000
    a = np.ones(n, dtype = np.float64)
    b = np.ones(n, dtype = np.float32)

    start = timer()
    func(a)
    print("without GPU:", timer()-start)

    start = timer()
    func2(a)
    print("with GPU:", timer()-start)
</code>```

Output:

```<code>/home/amu/anaconda3/bin/python /home/amu/PycharmProjects/gpu_processing_base/gpu_base_1.py
without GPU: 4.89985659904778
Traceback (most recent call last):
  File "/home/amu/PycharmProjects/gpu_processing_base/gpu_base_1.py", line 30, in <module>
    func2(a)
  File "/home/amu/anaconda3/lib/python3.7/site-packages/numba/cuda/dispatcher.py", line 40, in __call__
    return self.compiled(*args, **kws)
  File "/home/amu/anaconda3/lib/python3.7/site-packages/numba/cuda/compiler.py", line 758, in __call__
    kernel = self.specialize(*args)
  File "/home/amu/anaconda3/lib/python3.7/site-packages/numba/cuda/compiler.py", line 769, in specialize
    kernel = self.compile(argtypes)
  File "/home/amu/anaconda3/lib/python3.7/site-packages/numba/cuda/compiler.py", line 785, in compile
    **self.targetoptions)
  File "/home/amu/anaconda3/lib/python3.7/site-packages/numba/core/compiler_lock.py", line 32, in _acquire_compile_lock
    return func(*args, **kwargs)
TypeError: compile_kernel() got an unexpected keyword argument 'boundscheck'

Process finished with exit code 1
</code>```

I have installed numba and cudatoolkit mentioned in the tutorial in an anaconda environment in pycharm.

答:
Adding an answer to get this off the unanswered queue.

The code in that example is broken. It isn't anything wrong with your numba or CUDA installations. There is no way that the code in your question (or the blog you copied it from) can emit the result the blog post claims.

There are many ways this could potentially be modified to work. One would be like this:

```<code>from numba import vectorize, jit, cuda
import numpy as np
# to measure exec time
from timeit import default_timer as timer

# normal function to run on cpu
def func(a):
    for i in range(10000000):
        a[i]+= 1

# function optimized to run on gpu
@vectorize(['float64(float64)'], target ="cuda")
def func2(x):
    return x+1

if __name__=="__main__":
    n = 10000000
    a = np.ones(n, dtype = np.float64)

    start = timer()
    func(a)
    print("without GPU:", timer()-start)

    start = timer()
    func2(a)
    print("with GPU:", timer()-start)
</code>```

Here func2 becomes a ufunc which is compiled for the device. It will then be run over the whole input array on the GPU. Doing so does this:

```<code>$ python bogoexample.py
without GPU: 4.314514834433794
with GPU: 0.21419800259172916
</code>```

So it is faster, but keep in mind that the GPU time includes the time taken for compilation of the GPU ufunc

Another alternative would be to actually write a GPU kernel. Like this:

```<code>from numba import vectorize, jit, cuda
import numpy as np
# to measure exec time
from timeit import default_timer as timer

# normal function to run on cpu
def func(a):
    for i in range(10000000):
        a[i]+= 1

# function optimized to run on gpu
@vectorize(['float64(float64)'], target ="cuda")
def func2(x):
    return x+1

# kernel to run on gpu
@cuda.jit
def func3(a, N):
    tid = cuda.grid(1)
    if tid < N:
        a[tid] += 1

if __name__=="__main__":
    n = 10000000
    a = np.ones(n, dtype = np.float64)

    for i in range(0,5):
         start = timer()
         func(a)
         print(i, " without GPU:", timer()-start)

    for i in range(0,5):
         start = timer()
         func2(a)
         print(i, " with GPU ufunc:", timer()-start)

    threadsperblock = 1024
    blockspergrid = (a.size + (threadsperblock - 1)) // threadsperblock
    for i in range(0,5):
         start = timer()
         func3[blockspergrid, threadsperblock](a, n)
         print(i, " with GPU kernel:", timer()-start)
</code>```

which runs like this:

```<code>$ python bogoexample.py
0  without GPU: 4.885275377891958
1  without GPU: 4.748716968111694
2  without GPU: 4.902181145735085
3  without GPU: 4.889955999329686
4  without GPU: 4.881594380363822
0  with GPU ufunc: 0.16726416163146496
1  with GPU ufunc: 0.03758022002875805
2  with GPU ufunc: 0.03580896370112896
3  with GPU ufunc: 0.03530424740165472
4  with GPU ufunc: 0.03579768259078264
0  with GPU kernel: 0.1421878095716238
1  with GPU kernel: 0.04386183246970177
2  with GPU kernel: 0.029975440353155136
3  with GPU kernel: 0.029602501541376114
4  with GPU kernel: 0.029780613258481026
</code>```

Here you can see that the kernel runs slightly faster than the ufunc, and that caching (and this is caching of the JIT compiled functions, not memoization of the calls) significantly speeds up the call on the GPU.

Body:
Today I started working with CUDA and GPU processing. I found this tutorial:
https://www.geeksforgeeks.org/running-python-script-on-gpu/

Unfortunately my first attempt to run gpu code failed:

from numba import jit, cuda
import numpy as np
# to measure exec time
from timeit import default_timer as timer

# normal function to run on cpu
def func(a):
    for i in range(10000000):
        a[i]+= 1

# function optimized to run on gpu
@jit(target ="cuda")
def func2(a):
    for i in range(10000000):
        a[i]+= 1
if __name__=="__main__":
    n = 10000000
    a = np.ones(n, dtype = np.float64)
    b = np.ones(n, dtype = np.float32)

    start = timer()
    func(a)
    print("without GPU:", timer()-start)

    start = timer()
    func2(a)
    print("with GPU:", timer()-start)

Output:

/home/amu/anaconda3/bin/python /home/amu/PycharmProjects/gpu_processing_base/gpu_base_1.py
without GPU: 4.89985659904778
Traceback (most recent call last):
  File "/home/amu/PycharmProjects/gpu_processing_base/gpu_base_1.py", line 30, in <module>
    func2(a)
  File "/home/amu/anaconda3/lib/python3.7/site-packages/numba/cuda/dispatcher.py", line 40, in __call__
    return self.compiled(*args, **kws)
  File "/home/amu/anaconda3/lib/python3.7/site-packages/numba/cuda/compiler.py", line 758, in __call__
    kernel = self.specialize(*args)
  File "/home/amu/anaconda3/lib/python3.7/site-packages/numba/cuda/compiler.py", line 769, in specialize
    kernel = self.compile(argtypes)
  File "/home/amu/anaconda3/lib/python3.7/site-packages/numba/cuda/compiler.py", line 785, in compile
    **self.targetoptions)
  File "/home/amu/anaconda3/lib/python3.7/site-packages/numba/core/compiler_lock.py", line 32, in _acquire_compile_lock
    return func(*args, **kwargs)
TypeError: compile_kernel() got an unexpected keyword argument 'boundscheck'

Process finished with exit code 1

I have installed numba and cudatoolkit mentioned in the tutorial in an anaconda environment in pycharm.

Body:
Adding an answer to get this off the unanswered queue.

The code in that example is broken. It isn't anything wrong with your numba or CUDA installations. There is no way that the code in your question (or the blog you copied it from) can emit the result the blog post claims.

There are many ways this could potentially be modified to work. One would be like this:

from numba import vectorize, jit, cuda
import numpy as np
# to measure exec time
from timeit import default_timer as timer

# normal function to run on cpu
def func(a):
    for i in range(10000000):
        a[i]+= 1

# function optimized to run on gpu
@vectorize(['float64(float64)'], target ="cuda")
def func2(x):
    return x+1

if __name__=="__main__":
    n = 10000000
    a = np.ones(n, dtype = np.float64)

    start = timer()
    func(a)
    print("without GPU:", timer()-start)

    start = timer()
    func2(a)
    print("with GPU:", timer()-start)

Here func2 becomes a ufunc which is compiled for the device. It will then be run over the whole input array on the GPU. Doing so does this:

$ python bogoexample.py
without GPU: 4.314514834433794
with GPU: 0.21419800259172916

So it is faster, but keep in mind that the GPU time includes the time taken for compilation of the GPU ufunc

Another alternative would be to actually write a GPU kernel. Like this:

from numba import vectorize, jit, cuda
import numpy as np
# to measure exec time
from timeit import default_timer as timer

# normal function to run on cpu
def func(a):
    for i in range(10000000):
        a[i]+= 1

# function optimized to run on gpu
@vectorize(['float64(float64)'], target ="cuda")
def func2(x):
    return x+1

# kernel to run on gpu
@cuda.jit
def func3(a, N):
    tid = cuda.grid(1)
    if tid < N:
        a[tid] += 1

if __name__=="__main__":
    n = 10000000
    a = np.ones(n, dtype = np.float64)

    for i in range(0,5):
         start = timer()
         func(a)
         print(i, " without GPU:", timer()-start)

    for i in range(0,5):
         start = timer()
         func2(a)
         print(i, " with GPU ufunc:", timer()-start)

    threadsperblock = 1024
    blockspergrid = (a.size + (threadsperblock - 1)) // threadsperblock
    for i in range(0,5):
         start = timer()
         func3[blockspergrid, threadsperblock](a, n)
         print(i, " with GPU kernel:", timer()-start)

which runs like this:

$ python bogoexample.py
0  without GPU: 4.885275377891958
1  without GPU: 4.748716968111694
2  without GPU: 4.902181145735085
3  without GPU: 4.889955999329686
4  without GPU: 4.881594380363822
0  with GPU ufunc: 0.16726416163146496
1  with GPU ufunc: 0.03758022002875805
2  with GPU ufunc: 0.03580896370112896
3  with GPU ufunc: 0.03530424740165472
4  with GPU ufunc: 0.03579768259078264
0  with GPU kernel: 0.1421878095716238
1  with GPU kernel: 0.04386183246970177
2  with GPU kernel: 0.029975440353155136
3  with GPU kernel: 0.029602501541376114
4  with GPU kernel: 0.029780613258481026

Here you can see that the kernel runs slightly faster than the ufunc, and that caching (and this is caching of the JIT compiled functions, not memoization of the calls) significantly speeds up the call on the GPU.


问:
How to send user_data with gtk signals in loop
I have signals "make" and "send" registered in core class in main thread. I call call_make() from user class in same thread. call_make() will do some work and fetch some data from worker thread and after return it will emit signal "make".

This is code of user class

```<code>struct my_struct{
   int cur_make_id;
   int cur_send_id;    //there may be many id's if multiple signals
}

void on_send_cb(core, gpointer data){
   my_struct *user_data = (my_struct *) data;
   printf("cure_make_id %d", user_data->cur_make_id);   \\ this prints "4" everytime
   printf("cure_send_id %d", user_data->cur_send_id);   \\ this prints "2" everytime
}

void on_make_cb(core, gpointer data){
   my_struct *user_data = (my_struct *) data;
   printf("cure_make_id %d", user_data->cur_make_id);   \\ this prints "4" everytime
   for(int index=0;index<3;index++){
       call_send();
       user_data->cur_send_id = index;
       g_signal_connect(core, "send", G_CALLBACK(on_send_cb), user_data );
   }
}

void function(){
   my_struct *user_data = g_malloc0(sizeof(my_struct));
   for(int index=0;index<5;index++){
       call_make();
       user_data->cur_make_id = index;
       g_signal_connect(core, "make", G_CALLBACK(on_make_cb), user_data );
   }
}
</code>```

I get wrong cur_make_id and cur_send_id for all signals (getting last index of for loop)

I know signal_emit and connect delayed and for loop moved forward. I want to know how can I share this user_data to callback so that I can know that this callback is for which index?

(for simplicity I made these call_make() api's, I can't change arguments of api's)

答:
Assuming you are only talking about the user_data provided during connecting the callback, you have wrong memory allocation:

```<code>void function(){
   my_struct *user_data = g_malloc0(sizeof(my_struct));
   for(int index=0;index<5;index++){
       call_make();
       user_data->cur_make_id = index;
       g_signal_connect(core, "make", G_CALLBACK(on_make_cb), user_data );
   }
}
</code>```

In this function you have only 1 single block of memory that is passed to all connected callback functions. Whenever the callbacks are called, they will see whatever was written there last.
In your case this will be index=4.

To provide different data for different handlers, you actually need to allocate different data:

```<code>void function(){
   for(int index=0;index<5;index++){
       my_struct *user_data = g_malloc0(sizeof(my_struct));
       call_make();
       user_data->cur_make_id = index;
       g_signal_connect(core, "make", G_CALLBACK(on_make_cb), user_data);
   }
}
</code>```

If you also have problems providing data from the function triggering the signal, you need to show more code.

Body:
I have signals "make" and "send" registered in core class in main thread. I call call_make() from user class in same thread. call_make() will do some work and fetch some data from worker thread and after return it will emit signal "make".

This is code of user class

struct my_struct{
   int cur_make_id;
   int cur_send_id;    //there may be many id's if multiple signals
}

void on_send_cb(core, gpointer data){
   my_struct *user_data = (my_struct *) data;
   printf("cure_make_id %d", user_data->cur_make_id);   \\ this prints "4" everytime
   printf("cure_send_id %d", user_data->cur_send_id);   \\ this prints "2" everytime
}

void on_make_cb(core, gpointer data){
   my_struct *user_data = (my_struct *) data;
   printf("cure_make_id %d", user_data->cur_make_id);   \\ this prints "4" everytime
   for(int index=0;index<3;index++){
       call_send();
       user_data->cur_send_id = index;
       g_signal_connect(core, "send", G_CALLBACK(on_send_cb), user_data );
   }
}

void function(){
   my_struct *user_data = g_malloc0(sizeof(my_struct));
   for(int index=0;index<5;index++){
       call_make();
       user_data->cur_make_id = index;
       g_signal_connect(core, "make", G_CALLBACK(on_make_cb), user_data );
   }
}

I get wrong cur_make_id and cur_send_id for all signals (getting last index of for loop)

I know signal_emit and connect delayed and for loop moved forward. I want to know how can I share this user_data to callback so that I can know that this callback is for which index?

(for simplicity I made these call_make() api's, I can't change arguments of api's)

Body:
Assuming you are only talking about the user_data provided during connecting the callback, you have wrong memory allocation:

void function(){
   my_struct *user_data = g_malloc0(sizeof(my_struct));
   for(int index=0;index<5;index++){
       call_make();
       user_data->cur_make_id = index;
       g_signal_connect(core, "make", G_CALLBACK(on_make_cb), user_data );
   }
}

In this function you have only 1 single block of memory that is passed to all connected callback functions. Whenever the callbacks are called, they will see whatever was written there last.
In your case this will be index=4.

To provide different data for different handlers, you actually need to allocate different data:

void function(){
   for(int index=0;index<5;index++){
       my_struct *user_data = g_malloc0(sizeof(my_struct));
       call_make();
       user_data->cur_make_id = index;
       g_signal_connect(core, "make", G_CALLBACK(on_make_cb), user_data);
   }
}

If you also have problems providing data from the function triggering the signal, you need to show more code.


问:
jQuery scroll to element and then click it
I'm currently trying to make jQuery scroll to an element (in this case an accordion item) and then I want it to be automatically opened (clicked). So far I can successfully scroll to the item via jquery animate, but I can't seem to figure out how to click it AFTER the animate function has completed. This is my code so far:

```<code>$([document.documentElement, document.body]).animate({
            scrollTop: $("#"+ articleID +"").offset().top
        }, 800).then(function(){
            $("div[id='"+ articleID +"']").click();
        });
</code>```

Variables are being defined as function arguments, but the rest of the function is not relevant to the issue.

The code above successfully scrolls to the desired element, but won't click it afterwards. Any ideas how to approach this issue?

答:
I am proposing a workaround.</p>

```<code>var t = 800;
 $([document.documentElement, document.body]).animate({
        scrollTop: $("#"+ articleID +"").offset().top
    }, t);
 setTimeout(function(){
    $("div[id='" + articleID + "']").click();
 }, t);
</code>```

Body:
I'm currently trying to make jQuery scroll to an element (in this case an accordion item) and then I want it to be automatically opened (clicked). So far I can successfully scroll to the item via jquery animate, but I can't seem to figure out how to click it AFTER the animate function has completed. This is my code so far:

$([document.documentElement, document.body]).animate({
            scrollTop: $("#"+ articleID +"").offset().top
        }, 800).then(function(){
            $("div[id='"+ articleID +"']").click();
        });

Variables are being defined as function arguments, but the rest of the function is not relevant to the issue.

The code above successfully scrolls to the desired element, but won't click it afterwards. Any ideas how to approach this issue?

Body:
I am proposing a workaround.

var t = 800;
 $([document.documentElement, document.body]).animate({
        scrollTop: $("#"+ articleID +"").offset().top
    }, t);
 setTimeout(function(){
    $("div[id='" + articleID + "']").click();
 }, t);


问:
App crashes everytime on moving from activity, with no errors
I'm currently facing a problem on an app I'm developing that simply can't debug. I'm on SDK 27, Graddle 3.0.1, using ZXing 1.9.8.

In an Activity, I call for a QR Reader class I made out of ZXing library, so it reads the code and sends it to another Activity via Bundle for it to analyse it.

What is happening is it opens the camera, reads the code, then the app closes, out of nowhere, doesn't even get to open the next Activity.
When the user chooses to insert the code by hand on a little input dialog I made, it now reaches the next activity, but it's simply too unpredictable since it doesn't stop on any breakpoint there so I can debug it.

I reduced the amount of errors by putting Sleeps of 1sec between calling bundle.putExtra and startactivity() which is as understandable to me as black magic.

Since there are no errors, I started looking at the logcat and found this, repeatedly:

```<code>01-29 15:28:32.706 701-765/system_process I/ActivityManager: Displayed com.psa.dkd/.activities.GetCarDetails: +90ms
01-29 15:28:32.858 701-1562/system_process I/WindowManager: WIN DEATH: Window{f7887c u0 com.psa.dkd/com.psa.dkd.activities.GetCarDetails}
01-29 15:28:32.862 701-889/system_process W/ActivityManager: Force removing ActivityRecord{7d4750 u0 com.psa.dkd/.activities.GetCarDetails t165}: app died, no saved state
01-29 15:28:32.869 701-1530/system_process I/WindowManager: WIN DEATH: Window{6bb4c7f u0 com.psa.dkd/com.psa.dkd.activities.ReaderQR EXITING}
01-29 15:28:32.871 701-1486/system_process I/WindowManager: WIN DEATH: Window{11094d u0 SurfaceView - com.psa.dkd/com.psa.dkd.activities.ReaderQR EXITING}
01-29 15:28:32.875 701-1528/system_process I/WindowManager: WIN DEATH: Window{a96ce5a u0 com.psa.dkd/com.psa.dkd.activities.ReadChassisActivity}
</code>```

From what I gathered, WIN DEATH happens when the main thread has too much work to execute, but this had worked in the past, perfectly. Besides, there isn't that much work in the main thread since I use threads when possible.

Could it have been an update that caused this? I'm lost.

EDIT

ReadChassisActivity: https://pastebin.com/r60SPPHF

ReaderQR: https://pastebin.com/PSPT29Da

GetCarDetails: https://pastebin.com/Sgbi1XDi

ReadChassisActivity

```<code>import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.psa.dkd.R;
import com.psa.dkd.utils.Logger;
import com.psa.dkd.utils.SessionManagement;

import java.util.concurrent.TimeUnit;

public class ReadChassisActivity extends AppCompatActivity {

    private int BARCODE_READER_REQUEST_CODE;
    SessionManagement session;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_read_chassis);
        session = new SessionManagement(getApplicationContext());

        setTitle("Welcome" + session.getUserDetails().get("name"));

        RelativeLayout new_car_manual = (RelativeLayout) findViewById(R.id.new_car_manual);
        new_car_manual.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View view) {
                LayoutInflater li = LayoutInflater.from(ReadChassisActivity.this);
                View promptsView = li.inflate(R.layout.input_prompt, null);
                final EditText input = promptsView.findViewById(R.id.editTextDialogUserInput);
                input.requestFocus();

                AlertDialog alertDialog = new AlertDialog.Builder(ReadChassisActivity.this, R.style.DialogTheme).create();
                alertDialog.setTitle("Manual Input");
                alertDialog.setMessage("Insert barcode");
                alertDialog.setView(promptsView);
                alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        String result = input.getText().toString().toUpperCase();
                        Logger.writeToLog(result, 0, 9);
                        Logger.writeLogToDB(session, 0, result, 9, 0);
                        Intent workIntent = new Intent(ReadChassisActivity.this, GetCarDetails.class);
                        Bundle b = new Bundle();
                        b.putString("car_code", result);
                        workIntent.putExtras(b);
                        /*try {
                            TimeUnit.SECONDS.sleep(1);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }*/
                        startActivity(workIntent);
                        finish();
                    }
                });
                alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                alertDialog.show();
            }
        });

        RelativeLayout new_car = (RelativeLayout) findViewById(R.id.new_car);
        new_car.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(ReadChassisActivity.this, "Connecting camera...", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(ReadChassisActivity.this, ReaderQR.class);
                startActivityForResult(intent, BARCODE_READER_REQUEST_CODE);
            }
        });

        RelativeLayout exit = (RelativeLayout) findViewById(R.id.exit);
        exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog alertDialog = new AlertDialog.Builder(ReadChassisActivity.this, R.style.DialogTheme).create();
                alertDialog.setTitle("Exit");
                alertDialog.setMessage("Return to login");
                alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        finishAffinity();
                        finish();
                        //session.logoutUser();
                        Intent i = new Intent(ReadChassisActivity.this, LoginActivity.class);
                        startActivity(i);
                    }
                });
                alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                alertDialog.show();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == BARCODE_READER_REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                String result = data.getStringExtra("code");
                Logger.writeToLog(result, 0, 9);
                Logger.writeLogToDB(session, 0, result, 9, 0);

                Intent workIntent = new Intent(ReadChassisActivity.this, GetCarDetails.class);
                Bundle b = new Bundle();
                b.putString("car_code", result);
                workIntent.putExtras(b);
                /*try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }*/
                startActivity(workIntent);
                finish();
            }
            if (resultCode == Activity.RESULT_CANCELED) {
                //Write your code if there's no result
                Toast.makeText(getApplicationContext(), "No results", Toast.LENGTH_LONG).show();
                Intent choiceIntent = new Intent(ReadChassisActivity.this, ReadChassisActivity.class);
                startActivity(choiceIntent);
                finish();
            }
        }
    }

    @Override
    public void onBackPressed() {

    }
}
</code>```

ReaderQR

```<code>import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import com.google.zxing.Result;
import com.psa.dkd.R;

import me.dm7.barcodescanner.zxing.ZXingScannerView;

public class ReaderQR extends AppCompatActivity implements ZXingScannerView.ResultHandler {

    private ZXingScannerView mScannerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reader_qr);
        QrScanner(this.mScannerView);
        setTitle("Pass it over the code!");
    }

    public void QrScanner(View view) {
        mScannerView = new ZXingScannerView(this);
        setContentView(mScannerView);
        mScannerView.setResultHandler(this);
        mScannerView.startCamera();
    }

    @Override
    public void onPause() {
        super.onPause();
        mScannerView.stopCamera();
    }

    public void handleResult(Result rawResult) {
        Intent returnIntent = new Intent();
        returnIntent.putExtra("code", rawResult.getText());
        setResult(Activity.RESULT_OK, returnIntent);
        finish();
    }
}
</code>```

GetCarDetails

```<code>import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.psa.dkd.R;
import com.psa.dkd.utils.SessionManagement;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.concurrent.ExecutionException;

import static com.psa.dkd.utils.Misc.jsonToMap;

public class GetCarDetails extends Activity {

    private final int WAIT_TIME = 1000;
    private String car_code;
    private String server;
    private String worker_id;
    private HashMap<String, String> car_data;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_get_details);
        findViewById(R.id.mainSpinner2).setVisibility(View.VISIBLE);
        SessionManagement session = new SessionManagement(GetCarDetails.this);
        this.server = session.getUserDetails().get("server");
        this.worker_id = session.getUserDetails().get("id");
        this.car_code = getIntent().getExtras().getString("car_code");

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                // GET CAR DETAILS FROM DB - car_code

                try {
                        Log.d("TEST", "TRYING...");
                    String result = new getCarData().execute("APP/getCarDetails.php", car_code, worker_id).get();
                    Log.d("TEST", "RECEIVED: " + result);
                    car_data = jsonToMap(result);
                } catch (InterruptedException | ExecutionException | JSON    Exception e) {
                    Log.d("TESTE", e.toString());
                    Toast.makeText(getApplicationContext(), "Error has happened", Toast.LENGTH_LONG).show();
                    Intent choiceIntent = new Intent(GetCarDetails.this, ReadChassisActivity.class);
                    startActivity(choiceIntent);
                    finish();
                }

                if (car_data.get("result").equals("1")) {
                    Bundle b = new Bundle();
                    b.putString("car_code", car_code);
                    (...)
                    Intent i = new Intent(GetCarDetails.this, JobSelectActivity.class);
                    i.putExtras(b);
                    startActivity(i);
                    finish();
                } else {
                    if (car_data.get("result").equals("0")) {
                        Toast.makeText(GetCarDetails.this, "Nothing scheduled", Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(GetCarDetails.this, "This one is done, take another", Toast.LENGTH_LONG).show();
                    }
                    Intent mainIntent = new Intent(GetCarDetails.this, ReadChassisActivity.class);
                    startActivity(mainIntent);
                    finish();
                }
            }
        }, WAIT_TIME);
    }

    public class getCarData extends AsyncTask<String, String, String> {

        @Override
        protected String doInBackground(String... params) {

            String text = "";
            BufferedReader reader = null;

            try {
                URL url = new URL(server + params[0]);
                JSONObject postDataParams = new JSONObject();
                postDataParams.put("code", params[1]);
                postDataParams.put("user_id", params[1]);

                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(15000); // milliseconds
                conn.setConnectTimeout(15000); // milliseconds
                conn.setRequestMethod("POST");
                conn.setDoInput(true);
                conn.setDoOutput(true);
                conn.setRequestProperty("json", postDataParams.toString());

                DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
                String param = "json=" + URLEncoder.encode(postDataParams.toString(), "UTF-8");
                wr.write(param.getBytes());
                wr.flush();
                wr.close();
                // Get the server response
                reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line = null;
                // Read Server Response
                while ((line = reader.readLine()) != null) {
                    // Append server response in string
                    sb.append(line).append("\n");
                }
                text = sb.toString();
                return text;
            } catch (Exception e) {
                Log.d("ERROR FETCHING DATA", "Exception: " + e.getMessage());
                return "Exception: " + e.getMessage();
            }
        }
    }
}
</code>```

答:
Try to remove Toast.makeText

I've been searching similar bug for the last 3 days. I had no exception, only WINDEATH like you.

I hope it could be helpful for someone.

Body:
I'm currently facing a problem on an app I'm developing that simply can't debug. I'm on SDK 27, Graddle 3.0.1, using ZXing 1.9.8.

In an Activity, I call for a QR Reader class I made out of ZXing library, so it reads the code and sends it to another Activity via Bundle for it to analyse it.

What is happening is it opens the camera, reads the code, then the app closes, out of nowhere, doesn't even get to open the next Activity.
When the user chooses to insert the code by hand on a little input dialog I made, it now reaches the next activity, but it's simply too unpredictable since it doesn't stop on any breakpoint there so I can debug it.

I reduced the amount of errors by putting Sleeps of 1sec between calling bundle.putExtra and startactivity() which is as understandable to me as black magic.

Since there are no errors, I started looking at the logcat and found this, repeatedly:

01-29 15:28:32.706 701-765/system_process I/ActivityManager: Displayed com.psa.dkd/.activities.GetCarDetails: +90ms
01-29 15:28:32.858 701-1562/system_process I/WindowManager: WIN DEATH: Window{f7887c u0 com.psa.dkd/com.psa.dkd.activities.GetCarDetails}
01-29 15:28:32.862 701-889/system_process W/ActivityManager: Force removing ActivityRecord{7d4750 u0 com.psa.dkd/.activities.GetCarDetails t165}: app died, no saved state
01-29 15:28:32.869 701-1530/system_process I/WindowManager: WIN DEATH: Window{6bb4c7f u0 com.psa.dkd/com.psa.dkd.activities.ReaderQR EXITING}
01-29 15:28:32.871 701-1486/system_process I/WindowManager: WIN DEATH: Window{11094d u0 SurfaceView - com.psa.dkd/com.psa.dkd.activities.ReaderQR EXITING}
01-29 15:28:32.875 701-1528/system_process I/WindowManager: WIN DEATH: Window{a96ce5a u0 com.psa.dkd/com.psa.dkd.activities.ReadChassisActivity}

From what I gathered, WIN DEATH happens when the main thread has too much work to execute, but this had worked in the past, perfectly. Besides, there isn't that much work in the main thread since I use threads when possible.

Could it have been an update that caused this? I'm lost.

EDIT

ReadChassisActivity: https://pastebin.com/r60SPPHF

ReaderQR: https://pastebin.com/PSPT29Da

GetCarDetails: https://pastebin.com/Sgbi1XDi

ReadChassisActivity

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.psa.dkd.R;
import com.psa.dkd.utils.Logger;
import com.psa.dkd.utils.SessionManagement;

import java.util.concurrent.TimeUnit;

public class ReadChassisActivity extends AppCompatActivity {

    private int BARCODE_READER_REQUEST_CODE;
    SessionManagement session;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_read_chassis);
        session = new SessionManagement(getApplicationContext());

        setTitle("Welcome" + session.getUserDetails().get("name"));

        RelativeLayout new_car_manual = (RelativeLayout) findViewById(R.id.new_car_manual);
        new_car_manual.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View view) {
                LayoutInflater li = LayoutInflater.from(ReadChassisActivity.this);
                View promptsView = li.inflate(R.layout.input_prompt, null);
                final EditText input = promptsView.findViewById(R.id.editTextDialogUserInput);
                input.requestFocus();

                AlertDialog alertDialog = new AlertDialog.Builder(ReadChassisActivity.this, R.style.DialogTheme).create();
                alertDialog.setTitle("Manual Input");
                alertDialog.setMessage("Insert barcode");
                alertDialog.setView(promptsView);
                alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        String result = input.getText().toString().toUpperCase();
                        Logger.writeToLog(result, 0, 9);
                        Logger.writeLogToDB(session, 0, result, 9, 0);
                        Intent workIntent = new Intent(ReadChassisActivity.this, GetCarDetails.class);
                        Bundle b = new Bundle();
                        b.putString("car_code", result);
                        workIntent.putExtras(b);
                        /*try {
                            TimeUnit.SECONDS.sleep(1);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }*/
                        startActivity(workIntent);
                        finish();
                    }
                });
                alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                alertDialog.show();
            }
        });

        RelativeLayout new_car = (RelativeLayout) findViewById(R.id.new_car);
        new_car.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(ReadChassisActivity.this, "Connecting camera...", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(ReadChassisActivity.this, ReaderQR.class);
                startActivityForResult(intent, BARCODE_READER_REQUEST_CODE);
            }
        });

        RelativeLayout exit = (RelativeLayout) findViewById(R.id.exit);
        exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog alertDialog = new AlertDialog.Builder(ReadChassisActivity.this, R.style.DialogTheme).create();
                alertDialog.setTitle("Exit");
                alertDialog.setMessage("Return to login");
                alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        finishAffinity();
                        finish();
                        //session.logoutUser();
                        Intent i = new Intent(ReadChassisActivity.this, LoginActivity.class);
                        startActivity(i);
                    }
                });
                alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                alertDialog.show();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == BARCODE_READER_REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                String result = data.getStringExtra("code");
                Logger.writeToLog(result, 0, 9);
                Logger.writeLogToDB(session, 0, result, 9, 0);

                Intent workIntent = new Intent(ReadChassisActivity.this, GetCarDetails.class);
                Bundle b = new Bundle();
                b.putString("car_code", result);
                workIntent.putExtras(b);
                /*try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }*/
                startActivity(workIntent);
                finish();
            }
            if (resultCode == Activity.RESULT_CANCELED) {
                //Write your code if there's no result
                Toast.makeText(getApplicationContext(), "No results", Toast.LENGTH_LONG).show();
                Intent choiceIntent = new Intent(ReadChassisActivity.this, ReadChassisActivity.class);
                startActivity(choiceIntent);
                finish();
            }
        }
    }

    @Override
    public void onBackPressed() {

    }
}

ReaderQR

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import com.google.zxing.Result;
import com.psa.dkd.R;

import me.dm7.barcodescanner.zxing.ZXingScannerView;

public class ReaderQR extends AppCompatActivity implements ZXingScannerView.ResultHandler {

    private ZXingScannerView mScannerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reader_qr);
        QrScanner(this.mScannerView);
        setTitle("Pass it over the code!");
    }

    public void QrScanner(View view) {
        mScannerView = new ZXingScannerView(this);
        setContentView(mScannerView);
        mScannerView.setResultHandler(this);
        mScannerView.startCamera();
    }

    @Override
    public void onPause() {
        super.onPause();
        mScannerView.stopCamera();
    }

    public void handleResult(Result rawResult) {
        Intent returnIntent = new Intent();
        returnIntent.putExtra("code", rawResult.getText());
        setResult(Activity.RESULT_OK, returnIntent);
        finish();
    }
}

GetCarDetails

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.psa.dkd.R;
import com.psa.dkd.utils.SessionManagement;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.concurrent.ExecutionException;

import static com.psa.dkd.utils.Misc.jsonToMap;

public class GetCarDetails extends Activity {

    private final int WAIT_TIME = 1000;
    private String car_code;
    private String server;
    private String worker_id;
    private HashMap<String, String> car_data;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_get_details);
        findViewById(R.id.mainSpinner2).setVisibility(View.VISIBLE);
        SessionManagement session = new SessionManagement(GetCarDetails.this);
        this.server = session.getUserDetails().get("server");
        this.worker_id = session.getUserDetails().get("id");
        this.car_code = getIntent().getExtras().getString("car_code");

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                // GET CAR DETAILS FROM DB - car_code

                try {
                        Log.d("TEST", "TRYING...");
                    String result = new getCarData().execute("APP/getCarDetails.php", car_code, worker_id).get();
                    Log.d("TEST", "RECEIVED: " + result);
                    car_data = jsonToMap(result);
                } catch (InterruptedException | ExecutionException | JSON    Exception e) {
                    Log.d("TESTE", e.toString());
                    Toast.makeText(getApplicationContext(), "Error has happened", Toast.LENGTH_LONG).show();
                    Intent choiceIntent = new Intent(GetCarDetails.this, ReadChassisActivity.class);
                    startActivity(choiceIntent);
                    finish();
                }

                if (car_data.get("result").equals("1")) {
                    Bundle b = new Bundle();
                    b.putString("car_code", car_code);
                    (...)
                    Intent i = new Intent(GetCarDetails.this, JobSelectActivity.class);
                    i.putExtras(b);
                    startActivity(i);
                    finish();
                } else {
                    if (car_data.get("result").equals("0")) {
                        Toast.makeText(GetCarDetails.this, "Nothing scheduled", Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(GetCarDetails.this, "This one is done, take another", Toast.LENGTH_LONG).show();
                    }
                    Intent mainIntent = new Intent(GetCarDetails.this, ReadChassisActivity.class);
                    startActivity(mainIntent);
                    finish();
                }
            }
        }, WAIT_TIME);
    }

    public class getCarData extends AsyncTask<String, String, String> {

        @Override
        protected String doInBackground(String... params) {

            String text = "";
            BufferedReader reader = null;

            try {
                URL url = new URL(server + params[0]);
                JSONObject postDataParams = new JSONObject();
                postDataParams.put("code", params[1]);
                postDataParams.put("user_id", params[1]);

                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(15000); // milliseconds
                conn.setConnectTimeout(15000); // milliseconds
                conn.setRequestMethod("POST");
                conn.setDoInput(true);
                conn.setDoOutput(true);
                conn.setRequestProperty("json", postDataParams.toString());

                DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
                String param = "json=" + URLEncoder.encode(postDataParams.toString(), "UTF-8");
                wr.write(param.getBytes());
                wr.flush();
                wr.close();
                // Get the server response
                reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line = null;
                // Read Server Response
                while ((line = reader.readLine()) != null) {
                    // Append server response in string
                    sb.append(line).append("\n");
                }
                text = sb.toString();
                return text;
            } catch (Exception e) {
                Log.d("ERROR FETCHING DATA", "Exception: " + e.getMessage());
                return "Exception: " + e.getMessage();
            }
        }
    }
}


问:
check if there is a string followed by another c#
i need to verify if string is followed by other one in same string variable in C#.
for example:
string phrase= "life is is beautiful";
i need to set TRUE if there is a word followed by other separated by spaces or any. "is" is twice in this string variable. my code reads and find just one character folled by space and says 2. but it just read first character. i appreciate help.</p>

```<code>  string frase, frase2;
        int secuencia;
       frase="life is is beautiful";
        secuencia = 0;
        for (int i = 0; i < frase.Length; i++)
        {
               if (frase[i]==' ' && frase[i+1]=='i')secuencia++;
        }
        Console.WriteLine($"{secuencia} ");
</code>```

答:
A lot depends on what size of strings you want to deal with and performance needs, but a naive way to approach this would be:</p>

```<code>var splits = frase.split(" ");

for (int i = 0; i < splits.Length - 1; i++)
{
     if (splits[i]==splits[i+1]) secuencia++;
}
</code>```

Body:
i need to verify if string is followed by other one in same string variable in C#.
for example:
string phrase= "life is is beautiful";
i need to set TRUE if there is a word followed by other separated by spaces or any. "is" is twice in this string variable. my code reads and find just one character folled by space and says 2. but it just read first character. i appreciate help.

  string frase, frase2;
        int secuencia;
       frase="life is is beautiful";
        secuencia = 0;
        for (int i = 0; i < frase.Length; i++)
        {
               if (frase[i]==' ' && frase[i+1]=='i')secuencia++;
        }
        Console.WriteLine($"{secuencia} ");

Body:
A lot depends on what size of strings you want to deal with and performance needs, but a naive way to approach this would be:

var splits = frase.split(" ");

for (int i = 0; i < splits.Length - 1; i++)
{
     if (splits[i]==splits[i+1]) secuencia++;
}


问:
Add, Delete, Change, Disable/Enable menu items dynamically in material-ui and react
I have searched everywhere for this answer to no avail.  For instance, if I have a menu in the top right of a navbar, with TWO menu items to start (1. Login. 2. Register), and when a user clicks login or register and completes the form, the menu items change to (1 Logout 2. My Account).  There also may be other menu items that will be enabled/disabled based on login state and role.

I can't find ANY code that gives an example of how to accomplish ANY of this, not even how to disable a menu item dynamically.  I'm new to material-ui, but have been coding for decades. I can do this w/javascript but want to us material-ui.

Can someone help out with an example of how to do this using material-ui and react

答:
Material UI gives you the components and handles most of the UI state for you (open/close, etc.), what you are describing is something that you have to do it yourself, to my understanding.

The way I'd do it would be to have some kind of component that would generate the links by an object such as this:

```<code>const links = {
  loggedIn: [{text: "Logout", path: "/logout"}, {text: "myAccount", path: "/dashboard"}],
  loggedOut: [{text: "Login", path: "/login"}, {text: "Register", path: "/register"}]
}
</code>```

I'd then have a variable to hold the values that interest me in that situation:

```<code>const linksToShow = state.user ? links.loggedIn : links.loggedOut
</code>```

Then I'd have in my return/render (I'm not sure about the component itself, so I'll post some generic code here):

```<code><Menu>
  {state.user ? linksToShow.map(link => <Link to={link.path}>{link.text}</Link>)}
</Menu>
</code>```

Body:
Material UI gives you the components and handles most of the UI state for you (open/close, etc.), what you are describing is something that you have to do it yourself, to my understanding.

The way I'd do it would be to have some kind of component that would generate the links by an object such as this:

const links = {
  loggedIn: [{text: "Logout", path: "/logout"}, {text: "myAccount", path: "/dashboard"}],
  loggedOut: [{text: "Login", path: "/login"}, {text: "Register", path: "/register"}]
}

I'd then have a variable to hold the values that interest me in that situation:

const linksToShow = state.user ? links.loggedIn : links.loggedOut

Then I'd have in my return/render (I'm not sure about the component itself, so I'll post some generic code here):

<Menu>
  {state.user ? linksToShow.map(link => <Link to={link.path}>{link.text}</Link>)}
</Menu>


问:
How to compare time after date?
So I am building a service for selling theatre tickets, when someone wants to buy a ticket the customer will see a list of all available shows.

An available show is defined as follows:

The show is not sold out

The date has not been passed

The time hase not been passed

In the backend there is a query that looks like this to filter only the upcomming shows

```<code>SELECT *
FROM shows
WHERE CURRENT_DATE() <= show.date
</code>```

This query returns the shows of today and the upcomming shows, but it does not filter the shows of today where the start time has been passed. So a customer is still able to buy tickets from a show that has allready started.

I.e: Today is 29th may 2020 and the current time is 21:00:00 the show we are looking at is today and starts at 20:00:00. In the current system it is still possible to buy tickets for this show, but the show allready has started.

Queries like this won't work:

```<code>SELECT *
FROM shows
WHERE CURRENT_DATE() <= show.date AND CURRENT_TIME() <= show.time

OR

SELECT *
FROM shows
WHERE CURRENT_DATE() <= show.date OR CURRENT_TIME() <= show.time
</code>```

These queries wont fit the criteria above because the first query will not return any  show when the time has passed

And the second query doesn't work because it will also return older shows when the time condition matches.

So does anyone have an idea how to write a query that first selects all the shows where the date mathes the codition and the check if the time matches the condition. With respect to the upcomming show.

答:
```<code>You can write : CONVERT(date,GETDATE()) or CONVERT(date,CURRENT_DATE()) like this

SELECT *
FROM shows
WHERE CONVERT(date,GETDATE()) <= shows.date
</code>```

or

```<code>SELECT *
FROM shows
WHERE CONVERT(date,GETDATE()) <= CONVERT(date,shows.date)
</code>```

Title: How to compare time after date?

Body:
So I am building a service for selling theatre tickets, when someone wants to buy a ticket the customer will see a list of all available shows.

An available show is defined as follows:

The show is not sold out

The date has not been passed

The time hase not been passed

In the backend there is a query that looks like this to filter only the upcomming shows

SELECT *
FROM shows
WHERE CURRENT_DATE() <= show.date

This query returns the shows of today and the upcomming shows, but it does not filter the shows of today where the start time has been passed. So a customer is still able to buy tickets from a show that has allready started.

I.e: Today is 29th may 2020 and the current time is 21:00:00 the show we are looking at is today and starts at 20:00:00. In the current system it is still possible to buy tickets for this show, but the show allready has started.

Queries like this won't work:

SELECT *
FROM shows
WHERE CURRENT_DATE() <= show.date AND CURRENT_TIME() <= show.time

OR

SELECT *
FROM shows
WHERE CURRENT_DATE() <= show.date OR CURRENT_TIME() <= show.time

These queries wont fit the criteria above because the first query will not return any  show when the time has passed

And the second query doesn't work because it will also return older shows when the time condition matches.

So does anyone have an idea how to write a query that first selects all the shows where the date mathes the codition and the check if the time matches the condition. With respect to the upcomming show.

Body:
You can write : CONVERT(date,GETDATE()) or CONVERT(date,CURRENT_DATE()) like this

SELECT *
FROM shows
WHERE CONVERT(date,GETDATE()) <= shows.date

or

SELECT *
FROM shows
WHERE CONVERT(date,GETDATE()) <= CONVERT(date,shows.date)


问:
Virtualbox + shared folder gives protocol error for user with group access vboxsf
I have installed virtualbox Ubuntu 16.04 LTS - 64bit server on my windows 10 machine.
Installation went just fine.
However, now I am trying to get git clone from my existing repo to the shared folder "sf_Users" in this case, it keeps on giving error as

```<code>fatal: could not create work tree dir 'application': Protocol error

My VM settings -> shared folders -> machine folder says => Users C:/Users/app-dev
 -- auto-mount = Yes -- Access = Full
</code>```

from terminal my id shows up access to group vboxsf

```<code>dev@app-dev:/media/sf_Users$ id
uid=1000(dev) gid=1000(dev) groups=1000(dev),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),110(lxd),119(libvirtd),120(lpadmin),121(sambashare),125(vboxsf)
dev@app-dev:/media/sf_Users$ cd ..
dev@app-dev:/media$ ls -al
total 12
drwxr-xr-x  4 root root   4096 Nov 29  2016 .
drwxr-xr-x 23 root root   4096 Nov 29 10:04 ..
drwxr-xr-x  2 root root   4096 Nov 29 09:59 cdrom
drwxrwx---  1 root vboxsf    0 Nov 28 09:20 sf_Users
</code>```

from "id" command, I know that I have access to vboxsf. Am i missing something more?

答:
This image is the error I received

I tried Compressing the folder/file that caused the problem by ".7z" , then I copied and opened it on my windows host machine, it worked for me. Phew, The files were copied without leaving them out.

What did I see ?

Well i didn't care much less, i renamed it.

(This comment is only a quick post of what i resolved myself with no time to dig in)

Body:
I have installed virtualbox Ubuntu 16.04 LTS - 64bit server on my windows 10 machine.
Installation went just fine.
However, now I am trying to get git clone from my existing repo to the shared folder "sf_Users" in this case, it keeps on giving error as

fatal: could not create work tree dir 'application': Protocol error

My VM settings -> shared folders -> machine folder says => Users C:/Users/app-dev
 -- auto-mount = Yes -- Access = Full

from terminal my id shows up access to group vboxsf

dev@app-dev:/media/sf_Users$ id
uid=1000(dev) gid=1000(dev) groups=1000(dev),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),110(lxd),119(libvirtd),120(lpadmin),121(sambashare),125(vboxsf)
dev@app-dev:/media/sf_Users$ cd ..
dev@app-dev:/media$ ls -al
total 12
drwxr-xr-x  4 root root   4096 Nov 29  2016 .
drwxr-xr-x 23 root root   4096 Nov 29 10:04 ..
drwxr-xr-x  2 root root   4096 Nov 29 09:59 cdrom
drwxrwx---  1 root vboxsf    0 Nov 28 09:20 sf_Users

from "id" command, I know that I have access to vboxsf. Am i missing something more?


问:
Beginner Python programmer here, struggling to use the logical OR operator
Wrote the code snippet below on the Python IDLE and got the proper answer below:

```<code>>>> cars = ["audi", "bmw", "daimler", "toyota", "vw"]
>>> for car in cars:
    if "a" in car:
        print(car.title())
    else:
        print(car.upper())
</code>```

RESULT:

```<code>Audi
BMW
Daimler
Toyota
VW
</code>```

Then I changed the code so I could print the cars with no vowel UPPER and the rest Title as shown below but I got all cars printed Title:

```<code>>>> cars = ["audi", "bmw", "daimler", "toyota", "vw"]
>>> for car in cars:
    if "a" or "e" in car:
        print(car.title())
    else:
        print(car.upper())
</code>```

RESULT:

```<code>Audi
Bmw
Daimler
Toyota
Vw
</code>```

Can someone kindly help tell what is wrong with the last block of code, the goal is to print all cars without vowel fully uppercase and the rest as Title.

Thank you.

答:
if "a" or "e" in car will be always True since a is logically True.
Try instead:

```<code>if "a" in car or "e" in car:
    print(car.title())
else:
   print(car.upper())
</code>```

or you can use any if you would like to check more chars and want to avoid multiple ors:

```<code># any will return True if `car` contains one of the chars in the provided list.
if any(map(lambda c: c in car,["a","e"])):
    print(car.title())
else:
   print(car.upper())

</code>```

Body:
Wrote the code snippet below on the Python IDLE and got the proper answer below:

>>> cars = ["audi", "bmw", "daimler", "toyota", "vw"]
>>> for car in cars:
    if "a" in car:
        print(car.title())
    else:
        print(car.upper())

RESULT:

Audi
BMW
Daimler
Toyota
VW

Then I changed the code so I could print the cars with no vowel UPPER and the rest Title as shown below but I got all cars printed Title:

>>> cars = ["audi", "bmw", "daimler", "toyota", "vw"]
>>> for car in cars:
    if "a" or "e" in car:
        print(car.title())
    else:
        print(car.upper())

RESULT:

Audi
Bmw
Daimler
Toyota
Vw

Can someone kindly help tell what is wrong with the last block of code, the goal is to print all cars without vowel fully uppercase and the rest as Title.

Thank you.

Body:
if "a" or "e" in car will be always True since a is logically True.
Try instead:

if "a" in car or "e" in car:
    print(car.title())
else:
   print(car.upper())

or you can use any if you would like to check more chars and want to avoid multiple ors:

# any will return True if `car` contains one of the chars in the provided list.
if any(map(lambda c: c in car,["a","e"])):
    print(car.title())
else:
   print(car.upper())


问:
How to set the value of a variable defined outside in an arrow function (Axios, react, javascript)
I created a React component which fetches data from a server using Axios and renders it in a
 element.

Here's my code:

```<code>import React from "react";
import Axios from "axios";

class Abc extends React.Component {
    getUser = () => {
        let r;
        Axios.get("...").then(res => {
            r = res.data();
        });
        return r
    }

    render() {
        return <p>User: {getUser()}</p>
    }
}

</code>```

But the above code returns user as undefined. How can I fix this?

EDIT: For those of you asking me to use componentDidMount() and state, I need to use this user variable multiple times, and all times, the user will be different. What do I do now?

UPDATE: Fixed it. I just created a separate component for every user. Thanks all!

答:
You need use state, because getUser async method</p>

```<code>class Abc extends React.Component {
    state = {
        user: null,
    }

    componentDidMount() {
        Axios.get("...").then(res => {
            this.setState({ user: res.data() });
        });
    }

    render() {
        const { user } = this.state;

        if (!user) {
            return <p>Loading...</p>;
        }

        return <p>User: {user}</p>
    }
}
</code>```

Body:
I created a React component which fetches data from a server using Axios and renders it in a
 element.

Here's my code:

import React from "react";
import Axios from "axios";

class Abc extends React.Component {
    getUser = () => {
        let r;
        Axios.get("...").then(res => {
            r = res.data();
        });
        return r
    }

    render() {
        return
User: {getUser()}

    }
}

But the above code returns user as undefined. How can I fix this?

EDIT: For those of you asking me to use componentDidMount() and state, I need to use this user variable multiple times, and all times, the user will be different. What do I do now?

UPDATE: Fixed it. I just created a separate component for every user. Thanks all!

Body:
You need use state, because getUser async method

class Abc extends React.Component {
    state = {
        user: null,
    }

    componentDidMount() {
        Axios.get("...").then(res => {
            this.setState({ user: res.data() });
        });
    }

    render() {
        const { user } = this.state;

        if (!user) {
            return <p>Loading...</p>;
        }

        return <p>User: {user}</p>
    }
}


答:
Your expression:

```<code>"a" or "e" in car
</code>```

is equivalent to:

```<code>"a" or ("e" in car)
</code>```

which is always "a", a truthy value. That's why it's executing title() on everything.

You should instead be using:

```<code>if "a" in car or "e" in car
</code>```

or (half jokingly), since every problem can be solved by throwing more regular expressions at it:

```<code>if re.search("[ae]", car) is not None: # needs import re
</code>```

Title: Beginner Python programmer here, struggling to use the logical OR operator

Body:
Your expression:

"a" or "e" in car

is equivalent to:

"a" or ("e" in car)

which is always "a", a truthy value. That's why it's executing title() on everything.

You should instead be using:

if "a" in car or "e" in car

or (half jokingly), since every problem can be solved by throwing more regular expressions at it:

if re.search("[ae]", car) is not None: # needs import re