问:
constexpr and virtual
I've been thinking why constexr and virtual are mutually exclusive, and someone added:

... constexpr is all about execution at compile time; if we're executing the function at compile time, we obviously know the type of data upon which it's acting at compile time as well, so late binding clearly isn't relevant.

However, it's possible that the dynamic type is not identical to the static type even in compile-time, and there might be cases where the dynamic type is needed:

```<code>class A {
public:
    /* virtual */ constexpr int foo() {
        return 1;
    }
};

class B : public A {
public:
    constexpr int foo() {
        return 2;
    }
};

constexpr int foo(A &a) {
    // The static type is fixed here.
    // What if we want to call B::foo() ?
    return a.foo();
}

int main() {
    B b;
    constexpr int c = foo(b);
    return 0;
}
</code>```

That is, my question is

what's the (possible) rationale behind the standard prohibiting the combination of the two?

答:
Because virtual calls are resolved via vtables/RTTI (RunTime Type Information) located in the memory layout of your object at runtime, the "true type" behind the "used object handle" is not known at compile time.

In your example:

```<code>constexpr int foo(A &a) {
    // The static type is fixed here.
    // What if we want to call B::foo() ?
    return a.foo();
}
</code>```

If the foo member function is virtual there is no way for that foo function to be executed at compile time. And there is no point in marking a function as constexpr if it can never be executed at compile time. Hence there is no point in ever marking something both constexpr and virtual.

Now technically, depending on the code complexity, multiple cases might be resolvable by adding a completely new system (other than RTTI) to resolve virtual calls that would be compile time compatible (e.g some form of compiler meta data when everything is constexpr that remembers what type of instance you put in a pointer/reference) but that simply is not a thing right now.

If you want a runtime indirection (which is what virtual does) it doesn't make much sense to also want that to be executed at compile time.

P.S: sorry for the "compile time" and "runtime" spam.

Title: constexpr and virtual

Body:
I've been thinking why constexr and virtual are mutually exclusive, and someone added:

... constexpr is all about execution at compile time; if we're executing the function at compile time, we obviously know the type of data upon which it's acting at compile time as well, so late binding clearly isn't relevant.

However, it's possible that the dynamic type is not identical to the static type even in compile-time, and there might be cases where the dynamic type is needed:

class A {
public:
    /* virtual */ constexpr int foo() {
        return 1;
    }
};

class B : public A {
public:
    constexpr int foo() {
        return 2;
    }
};

constexpr int foo(A &a) {
    // The static type is fixed here.
    // What if we want to call B::foo() ?
    return a.foo();
}

int main() {
    B b;
    constexpr int c = foo(b);
    return 0;
}

That is, my question is

what's the (possible) rationale behind the standard prohibiting the combination of the two?

Body:
Because virtual calls are resolved via vtables/RTTI (RunTime Type Information) located in the memory layout of your object at runtime, the "true type" behind the "used object handle" is not known at compile time.

In your example:

constexpr int foo(A &a) {
    // The static type is fixed here.
    // What if we want to call B::foo() ?
    return a.foo();
}

If the foo member function is virtual there is no way for that foo function to be executed at compile time. And there is no point in marking a function as constexpr if it can never be executed at compile time. Hence there is no point in ever marking something both constexpr and virtual.

Now technically, depending on the code complexity, multiple cases might be resolvable by adding a completely new system (other than RTTI) to resolve virtual calls that would be compile time compatible (e.g some form of compiler meta data when everything is constexpr that remembers what type of instance you put in a pointer/reference) but that simply is not a thing right now.

If you want a runtime indirection (which is what virtual does) it doesn't make much sense to also want that to be executed at compile time.

P.S: sorry for the "compile time" and "runtime" spam.


来源: stackexchange

问:
Displaying appropriate error message when data from JSON doesn't get fetched in HTML
I've a sample JSON:

```<code>[
    {
        "componentid": 4,
        "displayImageUrl": "https://via.placeholder.com/350x200",
        "title": "theme",
        "shortdesc": "to set theme for different applications"
    },
    {
        "componentid": 7,
        "displayImageUrl": "https://via.placeholder.com/350x200",
        "title": "preferences",
        "shortdesc": "preferences screen for apps"
    }
]
</code>```

I've a JavaScript code that goes through above JSON and fetches the data

function prepareTopComponentList(data) {

```<code>    try {

        var preparedHtml = "";

        for (var count = 0; count < data.length; count++) {
            preparedHtml += "<div class=\"col-lg-4\" style=\"margin-top: 20px\">\n" +
                "                <div class=\"card wow fadeIn\" data-wow-delay=\"0.2s\">\n" +
                "                    <img class=\"img-fluid\" src=\"";
            preparedHtml += data[count].displayImageUrl;
            preparedHtml += "\" alt=\"N/A\">\n" +
                "                    <div class=\"card-body\">\n" +
                "                        <h4 class=\"card-title\">";
            preparedHtml += data[count].title;
            preparedHtml += "</h4>\n" +
                "                        <p class=\"card-text\">";
            preparedHtml += data[count].shortdesc;
            preparedHtml += "</p>\n" +
                "                        <a  onclick='Redirect(this)' href='#' class=\"btn btn-info\" id=\"";
            preparedHtml += "component_desc_=" + data[count].componentid;
            preparedHtml += "\">Learn more</a>\n" +
                "                    </div>\n" +
                "\n" +
                "                </div>\n" +
                "            </div>";

        }

        $("#div_top_component").append(preparedHtml);

    } catch (err) {

    }

}
function Redirect(element) {
    try {
        window.location = "http://localhost:9090/Reusable%20Components/pages/homepage.php?" + element.id;
    } catch (err) {

    }

}
</code>```

I also have a HTML code for displaying error:

```<code><!--Error/Warning Modal-->
<div class="modal fade" id="modal_show_error" role="dialog">
    <div class="modal-dialog">

        <!-- Modal content-->
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">×</button>
                <h4 class="modal-title" id="modal_error_title"></h4>
            </div>
            <div class="modal-body">
                <p id="modal_error_description"></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" data-dismiss="modal">Okay</button>
            </div>
        </div>

    </div>
</div>
</code>```

I'm fetching componentid from JSON. But if it is NULL, then I want a bootstrap error pop up saying that componentid is NULL. Catch block of above JavaScript code is empty, I'm not getting what code I should put there to get bootstrap error pop up.

答:
The === is used to check the quality of the value and the type of variable....

You can do something like this...

```<code> if(data[count].componentid === undefined || data[count].componentid === null){

   //Use your modal code

    }
    else{

    //preparedHTML code

    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've a sample JSON:

[
    {
        "componentid": 4,
        "displayImageUrl": "https://via.placeholder.com/350x200",
        "title": "theme",
        "shortdesc": "to set theme for different applications"
    },
    {
        "componentid": 7,
        "displayImageUrl": "https://via.placeholder.com/350x200",
        "title": "preferences",
        "shortdesc": "preferences screen for apps"
    }
]

I've a JavaScript code that goes through above JSON and fetches the data

function prepareTopComponentList(data) {

    try {

        var preparedHtml = "";

        for (var count = 0; count < data.length; count++) {
            preparedHtml += "
\n" +
                "
\n" +
                "                    \n" +
                "
\n" +
                "
";
            preparedHtml += data[count].title;
            preparedHtml += "
\n" +
                "
";
            preparedHtml += data[count].shortdesc;
            preparedHtml += "
\n" +
                "                        Learn more\n" +
                "
\n" +
                "\n" +
                "
\n" +
                "
";

        }

        $("#div_top_component").append(preparedHtml);

    } catch (err) {

    }

}
function Redirect(element) {
    try {
        window.location = "http://localhost:9090/Reusable%20Components/pages/homepage.php?" + element.id;
    } catch (err) {

    }

}

I also have a HTML code for displaying error:

                <button type="button" class="close" data-dismiss="modal">×</button>

                <button type="button" class="btn btn-primary" data-dismiss="modal">Okay</button>

I'm fetching componentid from JSON. But if it is NULL, then I want a bootstrap error pop up saying that componentid is NULL. Catch block of above JavaScript code is empty, I'm not getting what code I should put there to get bootstrap error pop up.

Body:
The === is used to check the quality of the value and the type of variable....

You can do something like this...

 if(data[count].componentid === undefined || data[count].componentid === null){

   //Use your modal code

    }
    else{

    //preparedHTML code

    }


问:
Split string in a column into three columns in the same table and insert it into new table
Hello I am a beginner here.. here is my question

I have a table "tspade" with two columns that is shown below :

```<code>No  | Unixdatetime                                      |

1   | 1234567890 -1 #SUP: 2                             |

2   | 2345678901 -1 #SUP: 2                             |

3   | 3456789012 -1 #SUP: 3                             |

4   | 4567890123 -1 5678901234 -1 #SUP: 2               |

5   | 6789012345 -1 7890123456 -1 8901234567 -1 #SUP: 2 |
</code>```

I'd like to convert that table into like this :

```<code>No  | Unixdatetime1 | Unixdatetime2 | Unixdatetime3 |

1   | 1234567890    | 0             | 0             |

2   | 2345678901    | 0             | 0             |

3   | 3456789012    | 0             | 0             |

4   | 4567890123    | 5678901234    | 0             |

5   | 6789012345    | 7890123456    | 8901234567    |
</code>```

and save that to table try

I used this query :

```<code>Insert Into try (No,Unixdatetime1,Unixdatetime2,Unixdatetime3)
SELECT `No`, `Unixdatetime`,
    SUBSTRING_INDEX( `Unixdatetime` , ' -1 ', 1 ) AS Unixdatetime1,
    SUBSTRING_INDEX(SUBSTRING_INDEX( `Unixdatetime` , ' -1 ', 2 ),' -1 ',-1) AS Unixdatetime2,
    SUBSTRING_INDEX( `Unixdatetime` , ' -1 ', -1 ) AS Unixdatetime3
FROM tspade
</code>```

but it couldn't work...
Any advice or help?
Thanks in advance

答:
The first step would be selecting the values. Forget about SELECT INTO if you don't know 100% what you are doing.

```<code>Select No, SUBSTRING(...) as Date1, [...] from tspade
</code>```

Replace the ellipsis with the code you need to select the substrings as you want them on your result table (watch the result!).

When you have the results you need in your Select result, insert that into the next table.

```<code>Insert Into try(No, Unixdatetime1, Unixdatetime2, Unixdatetime3 )
Select No, SUBSTRING(...) as Date1, [...] from tspade
</code>```

Body:
Hello I am a beginner here.. here is my question

I have a table "tspade" with two columns that is shown below :

No  | Unixdatetime                                      |

1   | 1234567890 -1 #SUP: 2                             |

2   | 2345678901 -1 #SUP: 2                             |

3   | 3456789012 -1 #SUP: 3                             |

4   | 4567890123 -1 5678901234 -1 #SUP: 2               |

5   | 6789012345 -1 7890123456 -1 8901234567 -1 #SUP: 2 |

I'd like to convert that table into like this :

No  | Unixdatetime1 | Unixdatetime2 | Unixdatetime3 |

1   | 1234567890    | 0             | 0             |

2   | 2345678901    | 0             | 0             |

3   | 3456789012    | 0             | 0             |

4   | 4567890123    | 5678901234    | 0             |

5   | 6789012345    | 7890123456    | 8901234567    |

and save that to table try

I used this query :

Insert Into try (No,Unixdatetime1,Unixdatetime2,Unixdatetime3)
SELECT `No`, `Unixdatetime`,
    SUBSTRING_INDEX( `Unixdatetime` , ' -1 ', 1 ) AS Unixdatetime1,
    SUBSTRING_INDEX(SUBSTRING_INDEX( `Unixdatetime` , ' -1 ', 2 ),' -1 ',-1) AS Unixdatetime2,
    SUBSTRING_INDEX( `Unixdatetime` , ' -1 ', -1 ) AS Unixdatetime3
FROM tspade

but it couldn't work...
Any advice or help?
Thanks in advance

Body:
The first step would be selecting the values. Forget about SELECT INTO if you don't know 100% what you are doing.

Select No, SUBSTRING(...) as Date1, [...] from tspade

Replace the ellipsis with the code you need to select the substrings as you want them on your result table (watch the result!).

When you have the results you need in your Select result, insert that into the next table.

Insert Into try(No, Unixdatetime1, Unixdatetime2, Unixdatetime3 )
Select No, SUBSTRING(...) as Date1, [...] from tspade


问:
Adobe Flash Catalyst to author AIR 2.0 applications
Has anyone used Adobe Flash Catalyst to to author AIR 2.0 applications ?  Flash Catalyst allows to save a project in fxp format which can be imported by Flash Builder and then run on the Flash Player runtime. I want it to run on the Adobe Air debug runtime and then create as a Windows desktop application . But Catalyst doesn't seem to support that. Am I correct?</p>

答:
After completing your application in catalyst cs5 you can

click file menu, choose publish for swf or air and select build air application

You can also uncheck build version for upload to a web sever

Now you have air file and can install it

ContentLicense: CC BY-SA 2.5


问:
COUNT with subquery fail on H2 database with "Duplicate column name"
we aware strange behavior of H2 when querying COUNT with a subquery.

Prepare table:

```<code>CREATE TABLE Foo
(
  id INT PRIMARY KEY AUTO_INCREMENT,
  fieldName VARCHAR(30) NOT NULL,
);
</code>```

Test simple query (works fine):

```<code>SELECT F1.id, F2.id from Foo as F1 INNER JOIN Foo F2 on F1.id = F2.id
</code>```

Test same query with count:

```<code>SELECT count(*) FROM (
  SELECT F1.id, F2.id from Foo as F1 INNER JOIN Foo F2 on F1.id = F2.id
) q;
</code>```

Got following error:

[42S21][42121] Duplicate column name "ID"; SQL statement:
      select count(*) FROM (

Any workarounds?

UPDATED:
The problem was in that original table name erased when preparing subquery column names and in fact I have :

```<code>SELECT count(*) FROM (
  SELECT id, id from q
);
</code>```

Adding alias (as mentioned by Abdul Rasheed) fix the problem.

答:
I don't understand why to use the same field and the same table with aliases.
Why don't you use simply a query like that :</p>

```<code>SELECT count(id) FROM Foo
</code>```

Body:
we aware strange behavior of H2 when querying COUNT with a subquery.

Prepare table:

CREATE TABLE Foo
(
  id INT PRIMARY KEY AUTO_INCREMENT,
  fieldName VARCHAR(30) NOT NULL,
);

Test simple query (works fine):

SELECT F1.id, F2.id from Foo as F1 INNER JOIN Foo F2 on F1.id = F2.id

Test same query with count:

SELECT count(*) FROM (
  SELECT F1.id, F2.id from Foo as F1 INNER JOIN Foo F2 on F1.id = F2.id
) q;

Got following error:

[42S21][42121] Duplicate column name "ID"; SQL statement:
      select count(*) FROM (

Any workarounds?

UPDATED:
The problem was in that original table name erased when preparing subquery column names and in fact I have :

SELECT count(*) FROM (
  SELECT id, id from q
);

Adding alias (as mentioned by Abdul Rasheed) fix the problem.

Body:
I don't understand why to use the same field and the same table with aliases.
Why don't you use simply a query like that :

SELECT count(id) FROM Foo


问:
Which GhostScript command for PS scripting
I m using the command--->
C:\Program Files (x86)\gs\gs9.09\bin\gswin32 -q -dNOPAUSE  -sDEVICE=gswin32 -sOutputFile="\spool\PRINTER_NAME"  "FILE_NAME" -c quit
for printing through ghostscript. what should i use in place of -sDEVICE=gswin32
for PS Scripting</p>

答:
I'm not sure what you mean by 'PS scripting'.

However, it looks like you want to use Ghostscript to interpret PostScript programs (or PDF files) and send the rendered result of interpreting the program to the Windows Printing System, in order to send it to a printer supported by Windows.

In which case you need the mswinpr2 device.

This is covered in the documentation To be honest I'm somewhat surprised that you had managed to get the OutputFile correct, but not the DEVICE.....


问:
Assigning a class to the
 parent of an image
ETA - Solution found. Nice work Stack Overflow beauties!! What would I do without you ;) ;)

I'm building a carousel, some items have images, others don't. I need to be able to target the items without images for styling, so I'm trying to add a class to the div that wraps the image if that makes sense?

What I have is this :
For items with images:

      Day 1

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

<p><strong>For items without images :</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="carousel-item" style="width: 157.4px; margin-right: 2px;">
  <li>

      <span>Day 1</span>

  </li>
</div></code>```

And what I'm trying to do using jquery is add the class 'noImg' to the div 'carousel-item' what I've tried is many variations of this sort of thing :

$("div.carousel-item").addClass("noImg");
if ($(this).hasClass('.img-responsive')) {
  ("div.carousel-item").removeClass("noImg")
};
```

I've tried variations of .children .parent I've tried doing it the other way around and doing .find on image-responsive and adding classes that way.

Any suggestions of the 'you dope, you're missing this obvious thing' would very much be appreciated, Thanks very much in advance.

答:
Here you can use this working code:

```<code><div class="carousel-item active">
    <li>
        <a href="#" class="innerTabLink" rel="XYZ">
            <span>Day 1</span>
            <img src="http://via.placeholder.com/350x150" class="img-responsive" alt="words here" width="350" height="150" title="words here">
        </a>
    </li>
</div>
<div class="carousel-item" style="width: 157.4px; margin-right: 2px;">
    <li>
        <a href="#" class="innerTabLink" rel="XYZ">
            <span>Day 1</span>
        </a>
    </li>
</div>
</code>```

and script

```<code>$(document).ready(
        function () {

            $('.img-responsive').parents('.carousel-item').addClass('new-class');
        }
    );
</code>```

Title: Assigning a class to the <div> parent of an image

Body:
ETA - Solution found. Nice work Stack Overflow beauties!! What would I do without you ;) ;)

I'm building a carousel, some items have images, others don't. I need to be able to target the items without images for styling, so I'm trying to add a class to the div that wraps the image if that makes sense?

What I have is this :
For items with images:

      Day 1

For items without images :

      Day 1

And what I'm trying to do using jquery is add the class 'noImg' to the div 'carousel-item' what I've tried is many variations of this sort of thing :

$("div.carousel-item").addClass("noImg");
if ($(this).hasClass('.img-responsive')) {
  ("div.carousel-item").removeClass("noImg")
};

I've tried variations of .children .parent I've tried doing it the other way around and doing .find on image-responsive and adding classes that way.

Any suggestions of the 'you dope, you're missing this obvious thing' would very much be appreciated, Thanks very much in advance.

Body:
Here you can use this working code:

<div class="carousel-item active">
    <li>
        <a href="#" class="innerTabLink" rel="XYZ">
            <span>Day 1</span>
            <img src="http://via.placeholder.com/350x150" class="img-responsive" alt="words here" width="350" height="150" title="words here">
        </a>
    </li>
</div>
<div class="carousel-item" style="width: 157.4px; margin-right: 2px;">
    <li>
        <a href="#" class="innerTabLink" rel="XYZ">
            <span>Day 1</span>
        </a>
    </li>
</div>

and script

$(document).ready(
        function () {

            $('.img-responsive').parents('.carousel-item').addClass('new-class');
        }
    );


问:
How to get last record of current active user?
I need to take a last record which user uploaded to DB. I know how to find last one, it is easy(Documents.objects.last()). But I am not sure it's right, cause in same time another user can upload a file, so I will get his record. Here is my code:

models.py

```<code>from django.db import models

class Document(models.Model):
    username = models.CharField(max_length=100, blank=True, null=True)
    document = models.FileField(upload_to='documents/%Y/%m/%d/%H:%M:%S')
    uploaded_at = models.DateTimeField(auto_now_add=True)
</code>```

tabu.py

```<code>from .models import Document

class TabuName:
    def tabufunction(self):
        res = Document.objects.last()
        return res
</code>```

I can't use request.user.username in that file. I've read that it is not good practice in django. Do you know a solution of this problem?

答:
```<code>res = Document.objects.filter(username=request.user.username).order_by('-id')[0]
</code>```

Body:
I need to take a last record which user uploaded to DB. I know how to find last one, it is easy(Documents.objects.last()). But I am not sure it's right, cause in same time another user can upload a file, so I will get his record. Here is my code:

models.py

from django.db import models

class Document(models.Model):
    username = models.CharField(max_length=100, blank=True, null=True)
    document = models.FileField(upload_to='documents/%Y/%m/%d/%H:%M:%S')
    uploaded_at = models.DateTimeField(auto_now_add=True)

tabu.py

from .models import Document

class TabuName:
    def tabufunction(self):
        res = Document.objects.last()
        return res

I can't use request.user.username in that file. I've read that it is not good practice in django. Do you know a solution of this problem?


答:
first,you can change username to ForeignKey of User model

```<code>user = models.ForeignKey(User,on_delete=models.CASCADE)
</code>```

In normal the currency problem can be ignored.If you care about it,you can store last user info in cachedb,for example:Redis.

Title: How to get last record of current active user?

Body:
first,you can change username to ForeignKey of User model

user = models.ForeignKey(User,on_delete=models.CASCADE)

In normal the currency problem can be ignored.If you care about it,you can store last user info in cachedb,for example:Redis.


问:
MSCRM Opportunity Entities Reassigning Ownership
I have an issue in MSCRM where opportunities are being reassigned to a different owner. It's always the same owner that it gets assigned to and I can not see any workflows or plugins that do the reassigning.

Looking at the audit I can see the user that is doing the reassign is our support user which a lot of workflow use as their owner.

Is anyone else experiencing this issue? What else can I look at where the issue might be happening?

答:
Do you have any cascade behavior in opportunity relationship?

May be the reassignment of owning account/contact/lead/any parent record can trigger this reassignment.


问:
Script bash always running
I want to create a simple bash script that prints a text every 5 minutes.
Script will be launched at the boot.

```<code>#!/bin/bash
while true ; do
echo "You received a new mail"
sleep 300
done
</code>```

I tried to use nohup like this

```<code>nohup script.sh
</code>```

But the output is redirected to nohup.out, I don't want it and the process is not executed in background, it's working until I leave with ctrl+C

答:
You can easily redirect stdout/stderr however you want by running:

```<code>nohup script.sh > someotherfile.
</code>```

The point of nohup that it will continue to run when the shell closes, but it doesn't immediately get sent to the background. If you want it to:

```<code>nohup script.sh > someotherfile &
</code>```

If you forget the & the usual ctrl-z followed by bg works.
In any case if you close the shell/terminal it will continue running. Here's a quick tutorial: http://linux.101hacks.com/unix/nohup-command/.

If you want to lookup other options check setsid, and also crontab. That last one is a bit more flexible in terms of when to run and auto-starting. Here's a first good reference:

https://askubuntu.com/questions/2368/how-do-i-set-up-a-cron-job#2369

Title: Script bash always running

Body:
I want to create a simple bash script that prints a text every 5 minutes.
Script will be launched at the boot.

#!/bin/bash
while true ; do
echo "You received a new mail"
sleep 300
done

I tried to use nohup like this

nohup script.sh

But the output is redirected to nohup.out, I don't want it and the process is not executed in background, it's working until I leave with ctrl+C

Body:
You can easily redirect stdout/stderr however you want by running:

nohup script.sh > someotherfile.

The point of nohup that it will continue to run when the shell closes, but it doesn't immediately get sent to the background. If you want it to:

nohup script.sh > someotherfile &

If you forget the & the usual ctrl-z followed by bg works.
In any case if you close the shell/terminal it will continue running. Here's a quick tutorial: http://linux.101hacks.com/unix/nohup-command/.

If you want to lookup other options check setsid, and also crontab. That last one is a bit more flexible in terms of when to run and auto-starting. Here's a first good reference:

https://askubuntu.com/questions/2368/how-do-i-set-up-a-cron-job#2369


问:
Scrollable DataTables table
I'm trying to follow this example on DataTables to get a scrollable, searchable fixed height table. Here is my snippet of code so far:

$(document).ready(function() {
  $('#dataTables_paginate').DataTable({
    filter: true,
    info: false,
    scrollY: '25vh',
    scrollCollapse: true,
    paging: false,
    language: {
      search: "_INPUT_",
      searchPlaceholder: "Search..."
    }
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.dataTables_filter {
    float: left;
    text-align: left;
    padding: 0px;
    margin: 0px;
}</code>```

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

          Name

          Steve Jason Smith

          Steve Jason Smith

          Steve Jason Smith

          Steve Jason Smith

          Steve Jason Smith

          Steve Jason Smith

          Steve Jason Smith

          Steve Jason Smith

          Steve Jason Smith

          Steve Jason Smith

          Steve Jason Smith

          Steve Jason Smith

          Steve Jason Smith

          Steve Jason Smith

          Steve Jason Smith

          Steve Jason Smith

          Steve Jason Smith

          Steve Jason Smith

```

I have two issues with the code I have written so far. First of all, the
 seems to be detatched from the main body of the table wheras I would like it to all stay together.

Secondly, I have tried to left align the search box of the DataTable but I cannot get it to move over no matter what code I have used. Is there a way I can left align the search box and have it be the same width as the table?

答:
You forgot to add the CSS for datatables bootstrap dataTables.bootstrap.css which can be found on the CDN page of datatables for example. Including this fixes the problem with the header.

To apply a style to the filter / search box you should wrap it in a div, this can be done with the dom option of datatables, check the snippet below for an example.

$(document).ready(function() {
  $('#dataTables_paginate').DataTable({
    filter: true,
    info: false,
    scrollY: '25vh',
    scrollCollapse: true,
    paging: false,
    dom: '<"wrapper"f>lrtip',
    language: {
      search: "_INPUT_",
      searchPlaceholder: "Search..."
    }
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.wrapper {
    float: left;
    text-align: left;
    padding: 0px;
    margin: 0px;
}

.wrapper input {
  margin-left: 0 !important;
  font-size: 20px;
}</code>```

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

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

          Name

          Steve Jason Smith

          Steve Jason Smith

          Steve Jason Smith

          Steve Jason Smith

          Steve Jason Smith

          Steve Jason Smith

          Steve Jason Smith

          Steve Jason Smith

          Steve Jason Smith

          Steve Jason Smith

          Steve Jason Smith

          Steve Jason Smith

          Steve Jason Smith

          Steve Jason Smith

          Steve Jason Smith

          Steve Jason Smith

          Steve Jason Smith

          Steve Jason Smith

```

Title: Scrollable DataTables table

Body:
I'm trying to follow this example on DataTables to get a scrollable, searchable fixed height table. Here is my snippet of code so far:

$(document).ready(function() {
  $('#dataTables_paginate').DataTable({
    filter: true,
    info: false,
    scrollY: '25vh',
    scrollCollapse: true,
    paging: false,
    language: {
      search: "_INPUT_",
      searchPlaceholder: "Search..."
    }
  });
});

.dataTables_filter {
    float: left;
    text-align: left;
    padding: 0px;
    margin: 0px;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

          Name

          Steve Jason Smith

          Steve Jason Smith

          Steve Jason Smith

          Steve Jason Smith

          Steve Jason Smith

          Steve Jason Smith

          Steve Jason Smith

          Steve Jason Smith

          Steve Jason Smith

          Steve Jason Smith

          Steve Jason Smith

          Steve Jason Smith

          Steve Jason Smith

          Steve Jason Smith

          Steve Jason Smith

          Steve Jason Smith

          Steve Jason Smith

          Steve Jason Smith

I have two issues with the code I have written so far. First of all, the
 seems to be detatched from the main body of the table wheras I would like it to all stay together.

Secondly, I have tried to left align the search box of the DataTable but I cannot get it to move over no matter what code I have used. Is there a way I can left align the search box and have it be the same width as the table?

Body:
You forgot to add the CSS for datatables bootstrap dataTables.bootstrap.css which can be found on the CDN page of datatables for example. Including this fixes the problem with the header.

To apply a style to the filter / search box you should wrap it in a div, this can be done with the dom option of datatables, check the snippet below for an example.

$(document).ready(function() {
  $('#dataTables_paginate').DataTable({
    filter: true,
    info: false,
    scrollY: '25vh',
    scrollCollapse: true,
    paging: false,
    dom: '<"wrapper"f>lrtip',
    language: {
      search: "_INPUT_",
      searchPlaceholder: "Search..."
    }
  });
});

.wrapper {
    float: left;
    text-align: left;
    padding: 0px;
    margin: 0px;
}

.wrapper input {
  margin-left: 0 !important;
  font-size: 20px;
}

<script src="https://cdn.datatables.net/v/bs/jq-3.2.1/dt-1.10.16/datatables.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

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

<div class="container-fluid">
  <div class="col-lg-4">
    <table class="table table-striped table-bordered" id="dataTables_paginate">
      <thead>
        <tr>
          <th>Name</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>Steve Jason Smith</td>
        </tr>
        <tr>
          <td>Steve Jason Smith</td>
        </tr>
        <tr>
          <td>Steve Jason Smith</td>
        </tr>
        <tr>
          <td>Steve Jason Smith</td>
        </tr>
        <tr>
          <td>Steve Jason Smith</td>
        </tr>
        <tr>
          <td>Steve Jason Smith</td>
        </tr>
        <tr>
          <td>Steve Jason Smith</td>
        </tr>
        <tr>
          <td>Steve Jason Smith</td>
        </tr>
        <tr>
          <td>Steve Jason Smith</td>
        </tr>
        <tr>
          <td>Steve Jason Smith</td>
        </tr>
        <tr>
          <td>Steve Jason Smith</td>
        </tr>
        <tr>
          <td>Steve Jason Smith</td>
        </tr>
        <tr>
          <td>Steve Jason Smith</td>
        </tr>
        <tr>
          <td>Steve Jason Smith</td>
        </tr>
        <tr>
          <td>Steve Jason Smith</td>
        </tr>
        <tr>
          <td>Steve Jason Smith</td>
        </tr>
        <tr>
          <td>Steve Jason Smith</td>
        </tr>
        <tr>
          <td>Steve Jason Smith</td>
        </tr>
      </tbody>
    </table>
  </div>
</div>


问:
Update all local branches with all remote branches
How do I override all local branches with all remote branches?

Here are my local branches:

```<code>client-side-js-framework
client-side-js-framework-2
client-side-js-framework-3
handlebars
master
</code>```

And my remote branches:

```<code>client-side-js-framework
handlebars
master
no-network-connection
</code>```

I want my local branches to mirror my remote branches as my remote branches are more up to date.  In other words, my local branches should be:

```<code>client-side-js-framework
handlebars
master
no-network-connection
</code>```

Can this be done with one (or two) commands, rather than basically deleting my local repo, and re cloning it?

答:
Most likely, you should run:

```<code>git fetch origin
</code>```

and then simply delete (most or all of) the local branches.  The next time you run, e.g.:

```<code>git checkout handlebars
</code>```

your Git will search for your local name handlebars, fail to find it, search some more to see if there's exactly one name like origin/handlebars and upstream/handlebars and so on (one for each possible remote).

As long as there's exactly one such name, your Git will then say: Aha, I should create local name handlebars using the same commit as remote-tracking name origin/handlebars.  In that instant you will get a local branch named handlebars that matches origin/handlebars, Git will check it out, and you will be ready to work.  There's no need to drag half a dozen not-being-worked-on local names around like a set of balls-and-chains.

If you really do need each branch updated, you must use a loop, with one update command per branch to do an appropriate merge and push, unless they're all fast-forward not-really-a-merge operations, in which case:

```<code>git fetch origin 'refs/heads/*:refs/heads/*'
</code>```

will work—but don't do it (see the ball and chain link).

(It's a little trickier if you do have multiple remotes that use the same names.  In this case, git checkout --track origin/handlebars will achieve the desired result.  Meanwhile it's also tricky, and unwise, to let git fetch delete local names, but I think it can be done with --prune.)

Body:
How do I override all local branches with all remote branches?

Here are my local branches:

client-side-js-framework
client-side-js-framework-2
client-side-js-framework-3
handlebars
master

And my remote branches:

client-side-js-framework
handlebars
master
no-network-connection

I want my local branches to mirror my remote branches as my remote branches are more up to date.  In other words, my local branches should be:

client-side-js-framework
handlebars
master
no-network-connection

Can this be done with one (or two) commands, rather than basically deleting my local repo, and re cloning it?

Body:
Most likely, you should run:

git fetch origin

and then simply delete (most or all of) the local branches.  The next time you run, e.g.:

git checkout handlebars

your Git will search for your local name handlebars, fail to find it, search some more to see if there's exactly one name like origin/handlebars and upstream/handlebars and so on (one for each possible remote).

As long as there's exactly one such name, your Git will then say: Aha, I should create local name handlebars using the same commit as remote-tracking name origin/handlebars.  In that instant you will get a local branch named handlebars that matches origin/handlebars, Git will check it out, and you will be ready to work.  There's no need to drag half a dozen not-being-worked-on local names around like a set of balls-and-chains.

If you really do need each branch updated, you must use a loop, with one update command per branch to do an appropriate merge and push, unless they're all fast-forward not-really-a-merge operations, in which case:

git fetch origin 'refs/heads/*:refs/heads/*'

will work—but don't do it (see the ball and chain link).

(It's a little trickier if you do have multiple remotes that use the same names.  In this case, git checkout --track origin/handlebars will achieve the desired result.  Meanwhile it's also tricky, and unwise, to let git fetch delete local names, but I think it can be done with --prune.)


问:
Trying to add phaser-swipe file to my typescript project
I'm pretty new to javascript and typescript and I'm having difficulty adding a library to my project.

I have a phaser.io typescript project in VS2017 and I'm trying to add this library to it:

https://github.com/flogvit/phaser-swipe

I've copied the definitions file into my folder "tsDefinitions\phaser-swipe.d.ts" and copied the js file into "build\libs\swipe.js"

I added a reference to the definition file in my project.

```<code>/// <reference path="phaser-swipe.d.ts" />
</code>```

When I try to create the swipe class like in the documents I get the error "Cannot find name Swipe".

My Level01.ts:

```<code>export class Level01 extends Phaser.State {

    background: Phaser.Sprite;
    music: Phaser.Sound;
    player: Player;
    swipe: Swipe;
    create() {
        this.background = this.add.sprite(0, 0, 'level01-sprites','background');
        this.player = new Player(this.game, this.world.centerX, this.world.centerX);
        this.player.anchor.setTo(0, 5);

        //Here is where the intellisense error is occurring
        this.swipe = new Swipe(this.game);
    }
}
</code>```

Quick Actions adds the following to the top of the file, but it then breaks Phaser.Player and other references by giving the same "Cannot find name Player" error.

```<code>import Swipe from "phaser-swipe";
</code>```

swipe.js:
https://github.com/flogvit/phaser-swipe/blob/master/swipe.js

phaser-swipe.d.ts: https://github.com/flogvit/phaser-swipe/blob/master/phaser-swipe.d.ts

Am I missing something here? How can I get the definitions file to work correctly? Thanks!

答:
Just a wild guess that you should try making it a variable like

var Swipe = require(‘phaser-swipe’);

//Then in your create

this.swipe = new Swipe(this.game);

//then in the update it’ll be all just depending how you want to use it.

Always check your comas”,” and this”;” cz a simple coma can give you errors trust me I know x) hope it helps.

Body:
I'm pretty new to javascript and typescript and I'm having difficulty adding a library to my project.

I have a phaser.io typescript project in VS2017 and I'm trying to add this library to it:

https://github.com/flogvit/phaser-swipe

I've copied the definitions file into my folder "tsDefinitions\phaser-swipe.d.ts" and copied the js file into "build\libs\swipe.js"

I added a reference to the definition file in my project.

/// <reference path="phaser-swipe.d.ts" />

When I try to create the swipe class like in the documents I get the error "Cannot find name Swipe".

My Level01.ts:

export class Level01 extends Phaser.State {

    background: Phaser.Sprite;
    music: Phaser.Sound;
    player: Player;
    swipe: Swipe;
    create() {
        this.background = this.add.sprite(0, 0, 'level01-sprites','background');
        this.player = new Player(this.game, this.world.centerX, this.world.centerX);
        this.player.anchor.setTo(0, 5);

        //Here is where the intellisense error is occurring
        this.swipe = new Swipe(this.game);
    }
}

Quick Actions adds the following to the top of the file, but it then breaks Phaser.Player and other references by giving the same "Cannot find name Player" error.

import Swipe from "phaser-swipe";

swipe.js:
https://github.com/flogvit/phaser-swipe/blob/master/swipe.js

phaser-swipe.d.ts: https://github.com/flogvit/phaser-swipe/blob/master/phaser-swipe.d.ts

Am I missing something here? How can I get the definitions file to work correctly? Thanks!


问:
ASP.NET - Page.Form.Action error
On my local development server, I am running version 2.0.50727.4955 on the live server I am running 2.0.50727.42.

On my live server I get:

Compiler Error Message: CS0117: 'System.Web.UI.HtmlControls.HtmlForm' does not contain a definition for 'Action'

On my development server everything works fine. Is this a .NET version issue or something else? Is there a way to make this work on my liver server with its current .Net version? Is there a way to upgrade from 2.0.50727.42 to 2.0.50727.4955?

Thanks

EDIT (Code):

```<code>    if (Request.PathInfo.Length != 0)
    {
        string reqPath = Request.PathInfo;
        string raw = Request.RawUrl;
        string url = Request.Url.ToString();
        if (reqPath.Length > 0)
            url = url.Replace(reqPath, "");
        if (raw.Length > 0)
            url = url.Replace(raw, "");

        litBasePath.Text = "<base href=\"" + url + "\">";
        Page.Form.Attributes["Action"] = raw;
    }
</code>```

EDIT (Local Setup)

This is my local setup. I am not getting any compile errors when i run this locally.

答:
That server version indicates that it has never had patches applied.

.42 is the RTM release of .Net 2.0.  (see wikipedia)
.4955 was released in september of 2010 as a security update.

Before even bothering to figure out exactly what this issue is I would yell and scream at the people responsible for those servers (and their bosses) that every day they put off doing server patches they are putting your company at risk.

There have been a tremendous number of exploits released just in the last few months (POET was a big one), much less since 2.0 RTM'd, that would allow full access to the servers in question.  And no, McAfee or any other "security" tool or firewall won't stop them.

Sorry to go on about this but there was a reason worms like Code Red and Nimda tore through tens of thousands of servers.  That reason was simply that the people responsible for those servers failed to do their job and apply updates.

That said, your issue boils down to you are using 2.0 SP2 locally and your server doesn't have that applied.  SP2 introduced the HtmlForm.Action attribute  To get SP2 on your production server run windows update.

Title: ASP.NET - Page.Form.Action error

Body:
On my local development server, I am running version 2.0.50727.4955 on the live server I am running 2.0.50727.42.

On my live server I get:

Compiler Error Message: CS0117: 'System.Web.UI.HtmlControls.HtmlForm' does not contain a definition for 'Action'

On my development server everything works fine. Is this a .NET version issue or something else? Is there a way to make this work on my liver server with its current .Net version? Is there a way to upgrade from 2.0.50727.42 to 2.0.50727.4955?

Thanks

EDIT (Code):

    if (Request.PathInfo.Length != 0)
    {
        string reqPath = Request.PathInfo;
        string raw = Request.RawUrl;
        string url = Request.Url.ToString();
        if (reqPath.Length > 0)
            url = url.Replace(reqPath, "");
        if (raw.Length > 0)
            url = url.Replace(raw, "");

        litBasePath.Text = "<base href=\"" + url + "\">";
        Page.Form.Attributes["Action"] = raw;
    }

EDIT (Local Setup)

This is my local setup. I am not getting any compile errors when i run this locally.


问:
How to evaluate multiple expression in if--elif statement in python?
How to evaluate multiple expression in if--elif in below code snipet.

I am sure its basic syntax issue

```<code>n=5
if n%2 != 0:
    print ("weird")
elif n%2 == 0 && 2 < n && n <5:
    print "Not Weird"
elif n%2 == 0 && 6 < n && n < 20:
    print "Weird"
elif n%2 == 0 && n >20:
    print "NOt Weird"
</code>```

答:
Squeezing the size down a bit:</p>

```<code>n = 5

if n % 2 != 0:
    print("weird")
else:
    if 2 < n < 5:
        print("Not Weird")
    elif 6 < n < 20:
        print("Weird")
    elif 20 < n:
        print("NOt Weird")
</code>```

Body:
How to evaluate multiple expression in if--elif in below code snipet.

I am sure its basic syntax issue

n=5
if n%2 != 0:
    print ("weird")
elif n%2 == 0 && 2 < n && n <5:
    print "Not Weird"
elif n%2 == 0 && 6 < n && n < 20:
    print "Weird"
elif n%2 == 0 && n >20:
    print "NOt Weird"

Body:
Squeezing the size down a bit:

n = 5

if n % 2 != 0:
    print("weird")
else:
    if 2 < n < 5:
        print("Not Weird")
    elif 6 < n < 20:
        print("Weird")
    elif 20 < n:
        print("NOt Weird")


问:
cucumber jvm close browser after running all features
I'm testing a Spring Boot app using Cucumber-JVM and Selenium. I'm defining a web driver bean and passing a destroy method to quit (shutdown the webdriver and all instances of Chrome) but it is leaving the browser open.

```<code>@Configuration
@ComponentScan(basePackages = "com.rodmccutcheon.pensionator.bdd")
public class CucumberConfig {

    @Bean(destroyMethod = "quit")
    public WebDriver webDriver() {
        System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");
        return new ChromeDriver();
    }

}
</code>```

I've basically copied an example from the Cucumber for Java book. The difference is they use xml configuration and I've opted for Java configuration.

```<code><bean class="org.openqa.selenium.support.events.EventFiringWebDriver" destroy-method="quit">
    <constructor-arg>
        <bean class="org.openqa.selenium.firefox.FirefoxDriver" />
    </constructor-arg>
</bean>
</code>```

How do I get the browser to close at the end of all tests?

答:
It probably just that you picked the wrong attribute of the annotation (or simply a typo). Instead of using destroyMethod you should use destroyMethodName. Refer to this.

```<code>@Configuration
@ComponentScan(basePackages = "com.rodmccutcheon.pensionator.bdd")
public class CucumberConfig {

    @Bean(destroyMethodName = "quit")
    public WebDriver webDriver() {
        System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");
        return new ChromeDriver();
    }

}
</code>```

Body:
I'm testing a Spring Boot app using Cucumber-JVM and Selenium. I'm defining a web driver bean and passing a destroy method to quit (shutdown the webdriver and all instances of Chrome) but it is leaving the browser open.

@Configuration
@ComponentScan(basePackages = "com.rodmccutcheon.pensionator.bdd")
public class CucumberConfig {

    @Bean(destroyMethod = "quit")
    public WebDriver webDriver() {
        System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");
        return new ChromeDriver();
    }

}

I've basically copied an example from the Cucumber for Java book. The difference is they use xml configuration and I've opted for Java configuration.

<bean class="org.openqa.selenium.support.events.EventFiringWebDriver" destroy-method="quit">
    <constructor-arg>
        <bean class="org.openqa.selenium.firefox.FirefoxDriver" />
    </constructor-arg>
</bean>

How do I get the browser to close at the end of all tests?

Body:
It probably just that you picked the wrong attribute of the annotation (or simply a typo). Instead of using destroyMethod you should use destroyMethodName. Refer to this.

@Configuration
@ComponentScan(basePackages = "com.rodmccutcheon.pensionator.bdd")
public class CucumberConfig {

    @Bean(destroyMethodName = "quit")
    public WebDriver webDriver() {
        System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");
        return new ChromeDriver();
    }

}


问:
How to add templates in meteor?
I am learning meteor framework. I am trying to render template but it throws this error:

```<code>Errors prevented startup:

While processing files with static-html (for target web.browser):
client/html/sidebar.html:1: Expected <head> or <body> tag
</code>```

my layout.html file is this:

```<code><body>

    {{> sidebar}}

</body>
</code>```

and sidebar.html file is this:

```<code><template name="sidebar">
        <h1>Hello</h1>
</template>
</code>```

Why its not rendering on layout.html??

答:
Replace your body tag by a template called "layout" (for example) and make this template a layoutTemplate inside your router configuration.

```<code><template name="layout">

  {{> sidebar}}

  {{> yield}}

</template>
</code>```

With IronRouter for example:

```<code>Router.configure({
  layoutTemplate: 'layout'
});
</code>```

Title: How to add templates in meteor?

Body:
I am learning meteor framework. I am trying to render template but it throws this error:

Errors prevented startup:

While processing files with static-html (for target web.browser):
client/html/sidebar.html:1: Expected  or  tag

my layout.html file is this:

    {{> sidebar}}

and sidebar.html file is this:

<template name="sidebar">

Hello

</template>

Why its not rendering on layout.html??

Body:
Replace your body tag by a template called "layout" (for example) and make this template a layoutTemplate inside your router configuration.

<template name="layout">

  {{> sidebar}}

  {{> yield}}

</template>

With IronRouter for example:

Router.configure({
  layoutTemplate: 'layout'
});


问:
C# - How to get Class Name and Line Number when an Exception is called
I need two methods, one for getting the Class from where the exception was called, and another one which gets the line number where an exception was called.

So far I have this code, which gets me the Class Name and Line Number together (example: DatabaseHandler.cs:line 70):

```<code>    private string GetClassAndLine()
    {
        string tempName = e.GetBaseException().ToString();
        int tempPosition = 0;
        int length = tempName.Length;
        for (int i = 0; i < length; i++)
        {
            if (tempName.ElementAt(i).Equals('\\'))
            {
                tempPosition = i + 1;
            }
        }
        return tempName.Substring(tempPosition, length - tempPosition);
    }
</code>```

So if you have any ideas how I could get them individually, it would be of great help. These are then passed into Oracle to store any exceptions which occur.

Update 2:

I am currently testing this code, as some suggested:

```<code>        private string GetClassName()
    {
        System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(e, true);
        return trace.GetFrame(0).GetMethod().ReflectedType.FullName;
    }

    private int GetLineNumber()
    {
        System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(e, true);
        return trace.GetFrame(0).GetFileLineNumber();
    }
</code>```

This is what was returned at a particular Database Exception. No Line Number or Class Name where it was triggered. How can I get that?

```<code>    Error was found at Class: Oracle.DataAccess.Client.OracleException.
    Line Number: 0
</code>```

What I want is for Example: "Class: Logging.cs, Line: 57"

Thanks,
Ryan

答:
I'm using the following class DebugE to trace exceptions and log stuff in the application:
 It outputs the  Thread# DateTime, ClassName.MethodName, Line & Col numbers and the exception message.

```<code>using System;
using System.Diagnostics;
using System.Threading;
using System.Reflection;
using System.Text.RegularExpressions;
namespace YourApp
{
class DebugE
{
    public static void d(Exception e)
    {
        try
        {
            MethodBase site = e.TargetSite;//Get the methodname from the exception.
            string methodName = site == null ? "" : site.Name;//avoid null ref if it's null.
            methodName = ExtractBracketed(methodName);

            StackTrace stkTrace = new System.Diagnostics.StackTrace(e, true);
            for (int i = 0; i < 3; i++)
            {
                //In most cases GetFrame(0) will contain valid information, but not always. That's why a small loop is needed.
                var frame = stkTrace.GetFrame(i);
                int lineNum = frame.GetFileLineNumber();//get the line and column numbers
                int colNum = frame.GetFileColumnNumber();
                string className = ExtractBracketed(frame.GetMethod().ReflectedType.FullName);
                Trace.WriteLine(ThreadAndDateInfo + "Exception: " + className + "." + methodName + ", Ln " + lineNum + " Col " + colNum + ": " + e.Message);
                if (lineNum + colNum > 0)
                    break; //exit the for loop if you have valid info. If not, try going up one frame...
            }

        }
        catch (Exception ee)
        {
            //Avoid any situation that the Trace is what crashes you application. While trace can log to a file. Console normally not output to the same place.
            Console.WriteLine("Tracing exception in d(Exception e)" + ee.Message);
        }
    }
    public static void d(string str)
    {
        try
        {
            StackFrame frame = new StackFrame(1);
            var method = frame.GetMethod();
            string name = ExtractBracketed(method.Name);//extract the content that is inside <brackets> the rest is irrelevant

            Trace.WriteLine(ThreadAndDateInfo + method.DeclaringType + "." + name + ": " + str);
        }
        catch (Exception e)
        {
            Console.WriteLine("Tracing exception in d(string str)" + e.Message);
        }
    }

    private static string ExtractBracketed(string str)
    {
        string s;
        if (str.IndexOf('<') > -1) //using the Regex when the string does not contain <brackets> returns an empty string.
            s = Regex.Match(str, @"\<([^>]*)\>").Groups[1].Value;
        else
            s = str;
        if (s == "")
            return  "'Emtpy'"; //for log visibility we want to know if something it's empty.
        else
            return s;

    }

    public static string ThreadAndDateInfo
    {
        //returns thread number and precise date and time.
        get { return "[" + Thread.CurrentThread.ManagedThreadId + " - " + DateTime.Now.ToString("dd/MM HH:mm:ss.ffffff") + "] "; }
    }
}
}
</code>```

Call if from anywhere in your application:

```<code>catch (Exception e)
{
    DebugE.d(e);
}
</code>```

To use it for plain logging, call DebugE.d("some text");
It will return the same but without the line and col numbers.

Note that for production applications I always end up calling a "simpler" call systematically:
 void debug(string methodName, exception e).
 This is because the "nicer" solution above DID NOT ALWAYS RETURN THE CORRECT METHOD information to me. If my guess is correct, this would be the case if your exception occurs in a method that does not have a try catch, but was called by another method that does have a 'try catch'. If this is the only reason, you can say "i'll add proper try catch". The problem is that in real life you get a real problem, a real log to analyse. When you notice the irrelevant or insufficient method information you don't get the chance to go back to your code, add the try/catch and quickly reproduce the exception. You just end up with missing information to deal with...
The current improved methods digs a few frames deep to try and get around this and retrieve the class, line and column in these special situations it could look like this (the trace on the 3rd frame actually returns a valid name and line number):

[1 - 21/11 14:37:50.424914] Exception: System.Threading.Tasks.Task.Delay, Ln 0 Col 0: The value needs to translate in milliseconds to -1 (signifying an infinite timeout), 0 or a positive integer less than or equal to Int32.MaxValue.
Parameter name: delay
[1 - 21/11 14:37:50.425914] Exception: System.Threading.Tasks.Task.Delay, Ln 0 Col 0: The value needs to translate in milliseconds to -1 (signifying an infinite timeout), 0 or a positive integer less than or equal to Int32.MaxValue.
Parameter name: delay
[1 - 21/11 14:37:50.426415] Exception: ScheduleAction.Delay, Ln 156 Col 17: The value needs to translate in milliseconds to -1 (signifying an infinite timeout), 0 or a positive integer less than or equal to Int32.MaxValue.
Parameter name: delay

Body:
I need two methods, one for getting the Class from where the exception was called, and another one which gets the line number where an exception was called.

So far I have this code, which gets me the Class Name and Line Number together (example: DatabaseHandler.cs:line 70):

    private string GetClassAndLine()
    {
        string tempName = e.GetBaseException().ToString();
        int tempPosition = 0;
        int length = tempName.Length;
        for (int i = 0; i < length; i++)
        {
            if (tempName.ElementAt(i).Equals('\\'))
            {
                tempPosition = i + 1;
            }
        }
        return tempName.Substring(tempPosition, length - tempPosition);
    }

So if you have any ideas how I could get them individually, it would be of great help. These are then passed into Oracle to store any exceptions which occur.

Update 2:

I am currently testing this code, as some suggested:

        private string GetClassName()
    {
        System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(e, true);
        return trace.GetFrame(0).GetMethod().ReflectedType.FullName;
    }

    private int GetLineNumber()
    {
        System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(e, true);
        return trace.GetFrame(0).GetFileLineNumber();
    }

This is what was returned at a particular Database Exception. No Line Number or Class Name where it was triggered. How can I get that?

    Error was found at Class: Oracle.DataAccess.Client.OracleException.
    Line Number: 0

What I want is for Example: "Class: Logging.cs, Line: 57"

Thanks,
Ryan

Body:
I'm using the following class DebugE to trace exceptions and log stuff in the application:
 It outputs the  Thread# DateTime, ClassName.MethodName, Line & Col numbers and the exception message.

using System;
using System.Diagnostics;
using System.Threading;
using System.Reflection;
using System.Text.RegularExpressions;
namespace YourApp
{
class DebugE
{
    public static void d(Exception e)
    {
        try
        {
            MethodBase site = e.TargetSite;//Get the methodname from the exception.
            string methodName = site == null ? "" : site.Name;//avoid null ref if it's null.
            methodName = ExtractBracketed(methodName);

            StackTrace stkTrace = new System.Diagnostics.StackTrace(e, true);
            for (int i = 0; i < 3; i++)
            {
                //In most cases GetFrame(0) will contain valid information, but not always. That's why a small loop is needed.
                var frame = stkTrace.GetFrame(i);
                int lineNum = frame.GetFileLineNumber();//get the line and column numbers
                int colNum = frame.GetFileColumnNumber();
                string className = ExtractBracketed(frame.GetMethod().ReflectedType.FullName);
                Trace.WriteLine(ThreadAndDateInfo + "Exception: " + className + "." + methodName + ", Ln " + lineNum + " Col " + colNum + ": " + e.Message);
                if (lineNum + colNum > 0)
                    break; //exit the for loop if you have valid info. If not, try going up one frame...
            }

        }
        catch (Exception ee)
        {
            //Avoid any situation that the Trace is what crashes you application. While trace can log to a file. Console normally not output to the same place.
            Console.WriteLine("Tracing exception in d(Exception e)" + ee.Message);
        }
    }
    public static void d(string str)
    {
        try
        {
            StackFrame frame = new StackFrame(1);
            var method = frame.GetMethod();
            string name = ExtractBracketed(method.Name);//extract the content that is inside <brackets> the rest is irrelevant

            Trace.WriteLine(ThreadAndDateInfo + method.DeclaringType + "." + name + ": " + str);
        }
        catch (Exception e)
        {
            Console.WriteLine("Tracing exception in d(string str)" + e.Message);
        }
    }

    private static string ExtractBracketed(string str)
    {
        string s;
        if (str.IndexOf('<') > -1) //using the Regex when the string does not contain <brackets> returns an empty string.
            s = Regex.Match(str, @"\<([^>]*)\>").Groups[1].Value;
        else
            s = str;
        if (s == "")
            return  "'Emtpy'"; //for log visibility we want to know if something it's empty.
        else
            return s;

    }

    public static string ThreadAndDateInfo
    {
        //returns thread number and precise date and time.
        get { return "[" + Thread.CurrentThread.ManagedThreadId + " - " + DateTime.Now.ToString("dd/MM HH:mm:ss.ffffff") + "] "; }
    }
}
}

Call if from anywhere in your application:

catch (Exception e)
{
    DebugE.d(e);
}

To use it for plain logging, call DebugE.d("some text");
It will return the same but without the line and col numbers.

Note that for production applications I always end up calling a "simpler" call systematically:
 void debug(string methodName, exception e).
 This is because the "nicer" solution above DID NOT ALWAYS RETURN THE CORRECT METHOD information to me. If my guess is correct, this would be the case if your exception occurs in a method that does not have a try catch, but was called by another method that does have a 'try catch'. If this is the only reason, you can say "i'll add proper try catch". The problem is that in real life you get a real problem, a real log to analyse. When you notice the irrelevant or insufficient method information you don't get the chance to go back to your code, add the try/catch and quickly reproduce the exception. You just end up with missing information to deal with...
The current improved methods digs a few frames deep to try and get around this and retrieve the class, line and column in these special situations it could look like this (the trace on the 3rd frame actually returns a valid name and line number):

[1 - 21/11 14:37:50.424914] Exception: System.Threading.Tasks.Task.Delay, Ln 0 Col 0: The value needs to translate in milliseconds to -1 (signifying an infinite timeout), 0 or a positive integer less than or equal to Int32.MaxValue.
Parameter name: delay
[1 - 21/11 14:37:50.425914] Exception: System.Threading.Tasks.Task.Delay, Ln 0 Col 0: The value needs to translate in milliseconds to -1 (signifying an infinite timeout), 0 or a positive integer less than or equal to Int32.MaxValue.
Parameter name: delay
[1 - 21/11 14:37:50.426415] Exception: ScheduleAction.Delay, Ln 156 Col 17: The value needs to translate in milliseconds to -1 (signifying an infinite timeout), 0 or a positive integer less than or equal to Int32.MaxValue.
Parameter name: delay


问:
How do i set the default index to 0 when i bind to combobox?
I am using MVVM in my application and binding combobox to my collection. However when i run it the combobox doesn't have any selected index and it shows a ugly emtpy box. How do i get past this issue?

This is my code :-

```<code>  <ComboBox x:Name="cmbPasswordQuestion"  ItemsSource="{Binding PasswordQuestionList}"  DisplayMemberPath="SiteTermsXItemsName" SelectedValuePath="SiteTermsXItemId" SelectedValue="{Binding SignUpUser.PasswordQuestionId}" Margin="97,210,247,0" VerticalAlignment="Top" Height="24">
                                <i:Interaction.Triggers>
                                    <i:EventTrigger EventName="SelectionChanged">
                                        <GalaSoft_MvvmLight_Command:EventToCommand Command="{Binding PasswordQuestionCommand}" CommandParameter="{Binding SelectedItem, ElementName=cmbPasswordQuestion}"/>
                                    </i:EventTrigger>
                                </i:Interaction.Triggers>
                            </ComboBox>
</code>```

I am not able to set the SelectedIndex = 0 directly in xaml as i am binding the collection run time.

Thanks in advance :)

答: All you need is to set SignUpUser.PasswordQuestionId to the id of the first item in the combobox right after you initialized the PasswordQuestionList property. And the binding will do the rest.

Body:
I am using MVVM in my application and binding combobox to my collection. However when i run it the combobox doesn't have any selected index and it shows a ugly emtpy box. How do i get past this issue?

This is my code :-

  <ComboBox x:Name="cmbPasswordQuestion"  ItemsSource="{Binding PasswordQuestionList}"  DisplayMemberPath="SiteTermsXItemsName" SelectedValuePath="SiteTermsXItemId" SelectedValue="{Binding SignUpUser.PasswordQuestionId}" Margin="97,210,247,0" VerticalAlignment="Top" Height="24">

                                        <GalaSoft_MvvmLight_Command:EventToCommand Command="{Binding PasswordQuestionCommand}" CommandParameter="{Binding SelectedItem, ElementName=cmbPasswordQuestion}"/>

                            </ComboBox>

I am not able to set the SelectedIndex = 0 directly in xaml as i am binding the collection run time.

Thanks in advance :)


问:
How to get all users that the logged in user is not friends with in MySQL?
I am fully able to get all of the logged in users current friends, which I do with this query here -

```<code>SELECT users.*
FROM users
LEFT JOIN friends
ON users.id = friends.friend_id
WHERE friends.user_id = $user_logged_in_id
</code>```

But I want to do the opposite, and I can't figure it out.

I am trying to do friends logic.

I need to get all the users who the currently logged in user is not already friends with

I have a users table and a friends table to act as a many to many relationship between users and their friends. The keys in the friends table are user_id friend_id.

To illustrate that someone is friends with another user I put (say the logged in user id is 3, and friends user id is 6) user_id = 3 and friend_id = 6 as one row, and then put another row with the id's flipped to illustrate the friendship the other way, user_id = 6 and friend_id = 3.

users table

```<code>|---------------------|------------------|
|          id         |     username     |
|---------------------|------------------|
|          1          |     sonja12      |
|---------------------|------------------|
|          2          |     dorris32     |
|---------------------|------------------|
|          3          |     billy32      |
|---------------------|------------------|
|          4          |     micha97      |
|---------------------|------------------|
|          5          |     travis841    |
|---------------------|------------------|
|          6          |     johnny28     |
|---------------------|------------------|
</code>```

friends table

```<code>|---------------------|------------------|------------------|
|          id         |     user_id      |     friend_id    |
|---------------------|------------------|------------------|
|          1          |        3         |         6        |
|---------------------|------------------|------------------|
|          2          |        6         |         3        |
|---------------------|------------------|------------------|
</code>```

EDIT:

I think I have narrowed down my question a bit to be more concise.

I want to get all users from the users table where their id does not appear as a friend id beside the user_id of the current logged in user in the friends table.

答:
SQL

```<code>SELECT u.*
FROM usrs u
LEFT JOIN friends f
ON u.id = f.friend_id
GROUP BY u.id, u.username, IF(f.user_id = $user_logged_in_id, 1, 0)
HAVING MAX(IF(f.user_id = $user_logged_in_id, 1, 0)) = 0;
</code>```

Demo

http://rextester.com/ELXFZ39682

Explanation

The query is based on your original but is grouping by each user ID so duplicates aren't returned. In order to return those that aren't friends of the logged in user, the IF(f.user_id = $user_logged_in_id, 1, 0) adds a generated column to the group that is set to 1 if the row is a friend of the logged in user, otherwise 0. We can then use the HAVING MAX(...) = 0 to restrict to groups where none of the rows is a friend.

Body:
I am fully able to get all of the logged in users current friends, which I do with this query here -

SELECT users.*
FROM users
LEFT JOIN friends
ON users.id = friends.friend_id
WHERE friends.user_id = $user_logged_in_id

But I want to do the opposite, and I can't figure it out.

I am trying to do friends logic.

I need to get all the users who the currently logged in user is not already friends with

I have a users table and a friends table to act as a many to many relationship between users and their friends. The keys in the friends table are user_id friend_id.

To illustrate that someone is friends with another user I put (say the logged in user id is 3, and friends user id is 6) user_id = 3 and friend_id = 6 as one row, and then put another row with the id's flipped to illustrate the friendship the other way, user_id = 6 and friend_id = 3.

users table

|---------------------|------------------|
|          id         |     username     |
|---------------------|------------------|
|          1          |     sonja12      |
|---------------------|------------------|
|          2          |     dorris32     |
|---------------------|------------------|
|          3          |     billy32      |
|---------------------|------------------|
|          4          |     micha97      |
|---------------------|------------------|
|          5          |     travis841    |
|---------------------|------------------|
|          6          |     johnny28     |
|---------------------|------------------|

friends table

|---------------------|------------------|------------------|
|          id         |     user_id      |     friend_id    |
|---------------------|------------------|------------------|
|          1          |        3         |         6        |
|---------------------|------------------|------------------|
|          2          |        6         |         3        |
|---------------------|------------------|------------------|

EDIT:

I think I have narrowed down my question a bit to be more concise.

I want to get all users from the users table where their id does not appear as a friend id beside the user_id of the current logged in user in the friends table.

Body:
SQL

SELECT u.*
FROM usrs u
LEFT JOIN friends f
ON u.id = f.friend_id
GROUP BY u.id, u.username, IF(f.user_id = $user_logged_in_id, 1, 0)
HAVING MAX(IF(f.user_id = $user_logged_in_id, 1, 0)) = 0;

Demo

http://rextester.com/ELXFZ39682

Explanation

The query is based on your original but is grouping by each user ID so duplicates aren't returned. In order to return those that aren't friends of the logged in user, the IF(f.user_id = $user_logged_in_id, 1, 0) adds a generated column to the group that is set to 1 if the row is a friend of the logged in user, otherwise 0. We can then use the HAVING MAX(...) = 0 to restrict to groups where none of the rows is a friend.


问:
No item found in pull request in visual studio team explorer
Using VS 2017 15.4 with VSTS source control (GIT version control).

I am able to connect, push and pull with VSTS from Visual studio team explorer.

When i click the "Pull Requests" in VS team explorer it is not showing the Pull Requests created in VSTS which assigned to me or created by me and showing "You are not connected to a remote repository"

Please help

答:
Goto TeamExplorer --> Manage connections and see weather you have connections for it, else try to add connection.

If you are having connections then go to repository settings and see remotes origin fetch and push url's are correct or not.


问:
How to manually send a reset-password email?
I need to manually send a password reset email upen creating a new user. I followed the steps described here and created a drive-by HttpRequest (pwreset_request = HttpRequest()) to do so, but all I get in return to calling PasswordResetView.as_view()(pwreset_request) is a 403 because of an invalid CSRF token.

Despite that (and consequently getting that email) there are no errors on the page and everything is working fine.

```<code>from django.http import HttpResponseForbidden, HttpResponse, HttpRequest
from django.middleware.csrf import get_token

@login_required
@permission_required(["abonnenten.verlag_sachbearbeiter_fullaccess"])
def sachbearbeiter_create_or_edit(request, username=None):
    mode = "create" if username is None else "edit"

    if mode == "create":
        user = None
        sachbearbeiter = None
    else:
        user = get_object_or_404(User, username=username)
        sachbearbeiter = user.sachbearbeiter

        if user.is_superuser or user.is_staff:
            raise PermissionDenied

    user_form = UserForm(request.POST or None, instance=user)
    sachbearbeiter_form = SachbearbeiterForm(request.POST or None, instance=sachbearbeiter)

    if request.method == 'POST':
        if mode == "create":
            if user_form.is_valid() and sachbearbeiter_form.is_valid():
                user = user_form.save(commit=False)
                user.email = user.username
                user.save()
                sachbearbeiter = sachbearbeiter_form.save(commit=False)
                sachbearbeiter.user = user
                sachbearbeiter.save()

                # Manually send password reset mail
                # TODO Fix this shit (403)
                pwreset_request = HttpRequest()
                pwreset_request.method = 'POST'
                pwreset_request.META['HTTP_HOST'] = request.META['HTTP_HOST']
                pwreset_request.POST = {'email': user.email, 'csrfmiddlewaretoken': get_token(HttpRequest())}
                PasswordResetView.as_view()(pwreset_request)

                messages.success(request, 'Der Datensatz wurde erfolgreich gespeichert.')
                return redirect('sachbearbeiter_edit', username=user.username)
        elif mode == "edit":
            if user_form.is_valid() and sachbearbeiter_form.is_valid():
                user = user_form.save(commit=False)
                user.email = user.username
                user.save()
                sachbearbeiter_form.save()
                messages.success(request, 'Der Datensatz wurde erfolgreich gespeichert.')
                return redirect('sachbearbeiter_edit', username=user.username)
        else:
            raise ValueError("Variable `mode` must be 'create' or 'edit'")

    return render(request,
                  'sachbearbeiter/edit_or_create.html',
                  {'mode': mode,
                   'user': user,
                   'user_form': user_form,
                   'sachbearbeiter_form': sachbearbeiter_form})
</code>```

Any ideas how to fix that?

答:
Why creating by hand a new Request object, calling the password reset view, when you can just use the PasswordResetForm used by this view ?

So replace all your code below:

```<code># Manually send password reset mail
# TODO Fix this shit (403)
pwreset_request = HttpRequest()
pwreset_request.method = 'POST'
pwreset_request.META['HTTP_HOST'] = request.META['HTTP_HOST']
pwreset_request.POST = {'email': user.email, 'csrfmiddlewaretoken': get_token(HttpRequest())}
PasswordResetView.as_view()(pwreset_request)
</code>```

By this code:

```<code>from django.contrib.auth.forms import PasswordResetForm

reset_password_form = PasswordResetForm(data={'email': user.email})
if reset_password_form.is_valid():
     reset_password_form.save(request=request) # The save method will send the email
</code>```

Body:
I need to manually send a password reset email upen creating a new user. I followed the steps described here and created a drive-by HttpRequest (pwreset_request = HttpRequest()) to do so, but all I get in return to calling PasswordResetView.as_view()(pwreset_request) is a 403 because of an invalid CSRF token.

Despite that (and consequently getting that email) there are no errors on the page and everything is working fine.

from django.http import HttpResponseForbidden, HttpResponse, HttpRequest
from django.middleware.csrf import get_token

@login_required
@permission_required(["abonnenten.verlag_sachbearbeiter_fullaccess"])
def sachbearbeiter_create_or_edit(request, username=None):
    mode = "create" if username is None else "edit"

    if mode == "create":
        user = None
        sachbearbeiter = None
    else:
        user = get_object_or_404(User, username=username)
        sachbearbeiter = user.sachbearbeiter

        if user.is_superuser or user.is_staff:
            raise PermissionDenied

    user_form = UserForm(request.POST or None, instance=user)
    sachbearbeiter_form = SachbearbeiterForm(request.POST or None, instance=sachbearbeiter)

    if request.method == 'POST':
        if mode == "create":
            if user_form.is_valid() and sachbearbeiter_form.is_valid():
                user = user_form.save(commit=False)
                user.email = user.username
                user.save()
                sachbearbeiter = sachbearbeiter_form.save(commit=False)
                sachbearbeiter.user = user
                sachbearbeiter.save()

                # Manually send password reset mail
                # TODO Fix this shit (403)
                pwreset_request = HttpRequest()
                pwreset_request.method = 'POST'
                pwreset_request.META['HTTP_HOST'] = request.META['HTTP_HOST']
                pwreset_request.POST = {'email': user.email, 'csrfmiddlewaretoken': get_token(HttpRequest())}
                PasswordResetView.as_view()(pwreset_request)

                messages.success(request, 'Der Datensatz wurde erfolgreich gespeichert.')
                return redirect('sachbearbeiter_edit', username=user.username)
        elif mode == "edit":
            if user_form.is_valid() and sachbearbeiter_form.is_valid():
                user = user_form.save(commit=False)
                user.email = user.username
                user.save()
                sachbearbeiter_form.save()
                messages.success(request, 'Der Datensatz wurde erfolgreich gespeichert.')
                return redirect('sachbearbeiter_edit', username=user.username)
        else:
            raise ValueError("Variable `mode` must be 'create' or 'edit'")

    return render(request,
                  'sachbearbeiter/edit_or_create.html',
                  {'mode': mode,
                   'user': user,
                   'user_form': user_form,
                   'sachbearbeiter_form': sachbearbeiter_form})

Any ideas how to fix that?

Body:
Why creating by hand a new Request object, calling the password reset view, when you can just use the PasswordResetForm used by this view ?

So replace all your code below:

# Manually send password reset mail
# TODO Fix this shit (403)
pwreset_request = HttpRequest()
pwreset_request.method = 'POST'
pwreset_request.META['HTTP_HOST'] = request.META['HTTP_HOST']
pwreset_request.POST = {'email': user.email, 'csrfmiddlewaretoken': get_token(HttpRequest())}
PasswordResetView.as_view()(pwreset_request)

By this code:

from django.contrib.auth.forms import PasswordResetForm

reset_password_form = PasswordResetForm(data={'email': user.email})
if reset_password_form.is_valid():
     reset_password_form.save(request=request) # The save method will send the email


问:
?Why is my CSS not applying?
For some reason, my CSS is not applying to my HTML.

HTML:

```<code><textarea class="overlay-display-hide preview-caption" placeholder="Add Your Caption here..."></textarea>
</code>```

CSS:

```<code>.overlay-display-hide {
    display: hide !important;
}
.preview-caption {
    position: absolute;
    width: 360px;
    height: 260px;
    background-color:transparent;
    border-style: none;
    color: white;
    font-size: 14px;
    padding: 20px;
    resize: none;
    overflow: hidden;
}
</code>```

And for some reason, the "overlay-display-hide" class does not show up in the element when inspecting. Do you have any ideas? I bet I just oversaw something.

答:
Firstly, you should use display: none instead of display: hide to hide something. You can explore more on the display property here.

There are other ways to hide HTML elements that display: none might not be appropriate for, follow this link for that.

What are your intentions though? It's not so clear.

Title: ?Why is my CSS not applying?

Body:
For some reason, my CSS is not applying to my HTML.

HTML:

<textarea class="overlay-display-hide preview-caption" placeholder="Add Your Caption here..."></textarea>

CSS:

.overlay-display-hide {
    display: hide !important;
}
.preview-caption {
    position: absolute;
    width: 360px;
    height: 260px;
    background-color:transparent;
    border-style: none;
    color: white;
    font-size: 14px;
    padding: 20px;
    resize: none;
    overflow: hidden;
}

And for some reason, the "overlay-display-hide" class does not show up in the element when inspecting. Do you have any ideas? I bet I just oversaw something.


问:
How to change border width of custom UIButton
So, I'm working on simple form for my app. I have two button that allow user to choose wether they want to input email or phone number. I make 2 button that looks like android style tab button. Like Below:

So I made custom class for my button. Here is the code:

```<code>@IBDesignable
class HC24Button: UIButton {

    @IBInspectable var tabButtonBorderWidth: CGFloat = 1.0

    @IBInspectable var borderWidth: CGFloat = 0{
        didSet{
            layer.borderWidth = borderWidth
        }
    }

    @IBInspectable var borderColor: UIColor? {
        didSet{
            updateView()
        }
    }

    @IBInspectable var cornerRadius: CGFloat = 0{
        didSet{
            layer.cornerRadius = cornerRadius
        }
    }

    @IBInspectable var tabsButton : Bool = false{
        didSet{
            updateView()
        }
    }

    func updateView(){
        let border = CALayer()
        let width = tabButtonBorderWidth
        border.borderColor = borderColor?.cgColor
        border.frame = CGRect(x: 0, y: frame.size.height - width, width:  frame.size.width + 20, height: frame.size.height)

        border.borderWidth = width

        layer.addSublayer(border)
        layer.masksToBounds = true
    }

}
</code>```

And here is the code on my view controller:

```<code>   @IBAction func PhoneTapped(_ sender: HC24Button) {
        sender.titleLabel?.font = UIFont.boldSystemFont(ofSize: 17)
        sender.tabButtonBorderWidth = 4.0
        sender.borderColor = HC24AppColors.Main
        EmailButton.tabButtonBorderWidth = 1.0
        EmailButton.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        EmailButton.borderColor = .lightGray
        UserPhoneEmailTextField.text = "62"
        UserPhoneEmailTextField.keyboardType = .numberPad
    }

    @IBAction func EmailTapped(_ sender: HC24Button) {
        sender.titleLabel?.font = UIFont.boldSystemFont(ofSize: 17)
        sender.tabButtonBorderWidth = 4.0
        sender.borderColor = HC24AppColors.Main
        PhoneButton.tabButtonBorderWidth = 1.0
        PhoneButton.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        PhoneButton.borderColor = .lightGray
        UserPhoneEmailTextField.text = ""
        UserPhoneEmailTextField.placeholder = "Alamat Email"
    }
</code>```

But this is the result I got:

I want only one button that have colored border, like a switch. How can I fix this issue?

答:
You are not updating your view when ever an button click event is calling as well as you are neither removing previously added layer not changing width of that layer.</p>

```<code>@IBDesignable
class HC24Button: UIButton {

    @IBInspectable var tabButtonBorderWidth: CGFloat = 1.0 {
        didSet {
            updateView()
        }
    }
    var borderLayer: CALayer?

    @IBInspectable var borderWidth: CGFloat = 0{
        didSet{
            layer.borderWidth = borderWidth
        }
    }

    @IBInspectable var borderColor: UIColor? {
        didSet{
            updateView()
        }
    }

    @IBInspectable var cornerRadius: CGFloat = 0{
        didSet{
            layer.cornerRadius = cornerRadius
        }
    }

    @IBInspectable var tabsButton : Bool = false{
        didSet{
            updateView()
        }
    }

    func updateView(){
        let border = CALayer()
        let width = tabButtonBorderWidth
        border.borderColor = borderColor?.cgColor
        border.frame = CGRect(x: 0, y: frame.size.height - width, width:  frame.size.width + 20, height: frame.size.height)

        border.borderWidth = width
        if let layerObj = self.borderLayer {
            layerObj.removeFromSuperlayer()
        }
        self.borderLayer = border
        layer.addSublayer(border)
        layer.masksToBounds = true
    }

}
</code>```

Body:
So, I'm working on simple form for my app. I have two button that allow user to choose wether they want to input email or phone number. I make 2 button that looks like android style tab button. Like Below:

So I made custom class for my button. Here is the code:

@IBDesignable
class HC24Button: UIButton {

    @IBInspectable var tabButtonBorderWidth: CGFloat = 1.0

    @IBInspectable var borderWidth: CGFloat = 0{
        didSet{
            layer.borderWidth = borderWidth
        }
    }

    @IBInspectable var borderColor: UIColor? {
        didSet{
            updateView()
        }
    }

    @IBInspectable var cornerRadius: CGFloat = 0{
        didSet{
            layer.cornerRadius = cornerRadius
        }
    }

    @IBInspectable var tabsButton : Bool = false{
        didSet{
            updateView()
        }
    }

    func updateView(){
        let border = CALayer()
        let width = tabButtonBorderWidth
        border.borderColor = borderColor?.cgColor
        border.frame = CGRect(x: 0, y: frame.size.height - width, width:  frame.size.width + 20, height: frame.size.height)

        border.borderWidth = width

        layer.addSublayer(border)
        layer.masksToBounds = true
    }

}

And here is the code on my view controller:

   @IBAction func PhoneTapped(_ sender: HC24Button) {
        sender.titleLabel?.font = UIFont.boldSystemFont(ofSize: 17)
        sender.tabButtonBorderWidth = 4.0
        sender.borderColor = HC24AppColors.Main
        EmailButton.tabButtonBorderWidth = 1.0
        EmailButton.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        EmailButton.borderColor = .lightGray
        UserPhoneEmailTextField.text = "62"
        UserPhoneEmailTextField.keyboardType = .numberPad
    }

    @IBAction func EmailTapped(_ sender: HC24Button) {
        sender.titleLabel?.font = UIFont.boldSystemFont(ofSize: 17)
        sender.tabButtonBorderWidth = 4.0
        sender.borderColor = HC24AppColors.Main
        PhoneButton.tabButtonBorderWidth = 1.0
        PhoneButton.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        PhoneButton.borderColor = .lightGray
        UserPhoneEmailTextField.text = ""
        UserPhoneEmailTextField.placeholder = "Alamat Email"
    }

But this is the result I got:

I want only one button that have colored border, like a switch. How can I fix this issue?

Body:
You are not updating your view when ever an button click event is calling as well as you are neither removing previously added layer not changing width of that layer.

@IBDesignable
class HC24Button: UIButton {

    @IBInspectable var tabButtonBorderWidth: CGFloat = 1.0 {
        didSet {
            updateView()
        }
    }
    var borderLayer: CALayer?

    @IBInspectable var borderWidth: CGFloat = 0{
        didSet{
            layer.borderWidth = borderWidth
        }
    }

    @IBInspectable var borderColor: UIColor? {
        didSet{
            updateView()
        }
    }

    @IBInspectable var cornerRadius: CGFloat = 0{
        didSet{
            layer.cornerRadius = cornerRadius
        }
    }

    @IBInspectable var tabsButton : Bool = false{
        didSet{
            updateView()
        }
    }

    func updateView(){
        let border = CALayer()
        let width = tabButtonBorderWidth
        border.borderColor = borderColor?.cgColor
        border.frame = CGRect(x: 0, y: frame.size.height - width, width:  frame.size.width + 20, height: frame.size.height)

        border.borderWidth = width
        if let layerObj = self.borderLayer {
            layerObj.removeFromSuperlayer()
        }
        self.borderLayer = border
        layer.addSublayer(border)
        layer.masksToBounds = true
    }

}


问:
GLOBAL data per HTTP/Session request?
QUESTION:

Is there any way to create a variable storage in per session/http request? The variable must be globally accessible and different per HTTP request/connection/session, and need not be passed from function to function.

For example (just to illustrate):

```<code>setVariableThatCanBeAccessedByThisHTTPRequestOnly( 'a string data' );
</code>```

Anything should work, but I'd prefer to stay away from passing it from function to function.

```<code>//I'm trying to get rid of passing req parameter to all custom functions.
//I'd like to store it in a variable somehow, that it can be accessed globally, but only within that session/request.
exports.functionName = function( req, res ) {

   customFunctionThatRequiresReq( req );

};
</code>```

ORIGINAL QUESTIONS

I've been playing with node.js lately, and have a little concern about its GLOBAL scope. Let's say we have a server.js file:

```<code>username = ""; //Global scope
</code>```

Then when a connection is established and the server receives a request, it will do the followings:

```<code>username = selectUsernameWithConditions(); //This will return a username
</code>```

My question is: If 2 different computers are sending the requests to the server, will the value of username be independently different? I mean, does the username when the first request is processed different from the username when the second request is processed, or they are just one variable and will be overridden?

If they are overridden, what is the best way to store data and make them globally accessible within that requests and/or session only? For example, the following code:

```<code>username = selectUsernameWithConditions(); //This will return a username
</code>```

Will assign username differently for different requests and not overriding each other.

答:
have you tried using a cookies?
set the cookie to the browser and then everytime there is a request, you would know the user by its cookie..
you may use 'cookie-parser' node library.</p>

Title: GLOBAL data per HTTP/Session request?

Body:
QUESTION:

Is there any way to create a variable storage in per session/http request? The variable must be globally accessible and different per HTTP request/connection/session, and need not be passed from function to function.

For example (just to illustrate):

setVariableThatCanBeAccessedByThisHTTPRequestOnly( 'a string data' );

Anything should work, but I'd prefer to stay away from passing it from function to function.

//I'm trying to get rid of passing req parameter to all custom functions.
//I'd like to store it in a variable somehow, that it can be accessed globally, but only within that session/request.
exports.functionName = function( req, res ) {

   customFunctionThatRequiresReq( req );

};

ORIGINAL QUESTIONS

I've been playing with node.js lately, and have a little concern about its GLOBAL scope. Let's say we have a server.js file:

username = ""; //Global scope

Then when a connection is established and the server receives a request, it will do the followings:

username = selectUsernameWithConditions(); //This will return a username

My question is: If 2 different computers are sending the requests to the server, will the value of username be independently different? I mean, does the username when the first request is processed different from the username when the second request is processed, or they are just one variable and will be overridden?

If they are overridden, what is the best way to store data and make them globally accessible within that requests and/or session only? For example, the following code:

username = selectUsernameWithConditions(); //This will return a username

Will assign username differently for different requests and not overriding each other.


问:
What purpose is served by having an async keyword for a callback inside an awaited function?
I have the following code:

```<code>async createApiCall(apiCalls: IApiCallsTable):Promise<IApiCallsTable> {
  try {
    const instance: any = this.db.getEntities().dbo__api_calls.build(apiCalls);
    instance.isNewRecord = true;
    let result = await this.db.getSequelize().transaction( async (transaction) => {
      return instance.save();
    });
    return Promise.resolve(result.dataValues);
  }
  catch (error) {
    console.log(error);
    let message: ILogMessage = {
      code: ResponseErrorCode.unknownError,
      message: ResponseErrorCode.unknownError.toString(),
      meta: error,
      sourceFunction : 'ApiCallsQueries: createApiCall()'
    };
    log.error(message);
    return Promise.reject(error);
  }
}
</code>```

I would to understand if is it necessary to have an async labelling an anonymous function, i.e. this.db.getSequelize().transaction( async (transaction) => { ...? The code is working flawlessly, but I cannot seem to understand the reason to label a callback async if nothing is being awaited inside it? Is this a recommended pattern and/or best practice?

PS: Any further suggestions/recommendations on how this code could be improved are more than welcome :)

答:
If you're not using the await keyword inside a function body, you don't need to label any function as async.

An exception to this rule, is if you want that callback to behave like a Promise, which you don't in your code example.

```<code>let result = await this.db.getSequelize().transaction( async (transaction) => {
  return instance.save();
});
</code>```

Even if instance.save returns a Promise, which I'm guessing it does - you're already covered here without using async at all, since you're already building a proper Promise chain.

Body:
I have the following code:

async createApiCall(apiCalls: IApiCallsTable):Promise<IApiCallsTable> {
  try {
    const instance: any = this.db.getEntities().dbo__api_calls.build(apiCalls);
    instance.isNewRecord = true;
    let result = await this.db.getSequelize().transaction( async (transaction) => {
      return instance.save();
    });
    return Promise.resolve(result.dataValues);
  }
  catch (error) {
    console.log(error);
    let message: ILogMessage = {
      code: ResponseErrorCode.unknownError,
      message: ResponseErrorCode.unknownError.toString(),
      meta: error,
      sourceFunction : 'ApiCallsQueries: createApiCall()'
    };
    log.error(message);
    return Promise.reject(error);
  }
}

I would to understand if is it necessary to have an async labelling an anonymous function, i.e. this.db.getSequelize().transaction( async (transaction) => { ...? The code is working flawlessly, but I cannot seem to understand the reason to label a callback async if nothing is being awaited inside it? Is this a recommended pattern and/or best practice?

PS: Any further suggestions/recommendations on how this code could be improved are more than welcome :)

Body:
If you're not using the await keyword inside a function body, you don't need to label any function as async.

An exception to this rule, is if you want that callback to behave like a Promise, which you don't in your code example.

let result = await this.db.getSequelize().transaction( async (transaction) => {
  return instance.save();
});

Even if instance.save returns a Promise, which I'm guessing it does - you're already covered here without using async at all, since you're already building a proper Promise chain.