问:
VBA Excel Removing duplicate rows
So I'm trying to remove any rows that have a duplicate in column C. This is a column of about 700 records however this value varies with different data used hence I've implemented a "LastRow" function. Here's my code:

```<code>Public Function LastRowInCRC() As Long

    Dim wsCRC As Worksheet
    Set wsCRC = Worksheets("CRC")

    With wsCRC
        LastRowInCRC = .Cells(.Rows.Count, "C").End(xlUp).Row
    End With

End Function

Sub DeleteDupRowsCRC()

    Dim wsCRC As Worksheet
    Set wsCRC = Worksheets("CRC")

    Dim lrowcrc As Long
    lrowcrc = CRC.LastRowInCRC

    'Debug.Print "C8:C" & lrowcrc

    With wsCRC

        .Range("C8:C" & lrowcrc).RemoveDuplicates Columns:=Array(3)

    End With

End Sub
</code>```

I get the "application-defined or object-defined" error at the following line when I step by step debug:

```<code>.Range("C8:C" & lrowcrc).RemoveDuplicates Columns:=Array(3)
</code>```

Any ideas whats going wrong? I call the "C8:C" & lrowcrc to the immediate window which is commented out, and it gives me the correct range values so I don't think the issue is in that but I cannot find whats wrong... any help greatly appreciated.

答:
I think your range Invalid syntax.
Please, try this below

```<code>With wsCRC
    .Range(Cells(8, 3), Cells(lrowcrc, 3)).Select
    .Range(Cells(8, 3), Cells(lrowcrc, 3)).RemoveDuplicates Columns:=1, Header:=xlYes

End With
</code>```

Beside, I think you should using below

lrowcrc = LastRowInCRC

Or using this code to get last row

wsCRC.[C8].SpecialCells(xlCellTypeLastCell).Row

Title: VBA Excel Removing duplicate rows

Body:
So I'm trying to remove any rows that have a duplicate in column C. This is a column of about 700 records however this value varies with different data used hence I've implemented a "LastRow" function. Here's my code:

Public Function LastRowInCRC() As Long

    Dim wsCRC As Worksheet
    Set wsCRC = Worksheets("CRC")

    With wsCRC
        LastRowInCRC = .Cells(.Rows.Count, "C").End(xlUp).Row
    End With

End Function

Sub DeleteDupRowsCRC()

    Dim wsCRC As Worksheet
    Set wsCRC = Worksheets("CRC")

    Dim lrowcrc As Long
    lrowcrc = CRC.LastRowInCRC

    'Debug.Print "C8:C" & lrowcrc

    With wsCRC

        .Range("C8:C" & lrowcrc).RemoveDuplicates Columns:=Array(3)

    End With

End Sub

I get the "application-defined or object-defined" error at the following line when I step by step debug:

.Range("C8:C" & lrowcrc).RemoveDuplicates Columns:=Array(3)

Any ideas whats going wrong? I call the "C8:C" & lrowcrc to the immediate window which is commented out, and it gives me the correct range values so I don't think the issue is in that but I cannot find whats wrong... any help greatly appreciated.

Body:
I think your range Invalid syntax.
Please, try this below

With wsCRC
    .Range(Cells(8, 3), Cells(lrowcrc, 3)).Select
    .Range(Cells(8, 3), Cells(lrowcrc, 3)).RemoveDuplicates Columns:=1, Header:=xlYes

End With

Beside, I think you should using below

lrowcrc = LastRowInCRC

Or using this code to get last row

wsCRC.[C8].SpecialCells(xlCellTypeLastCell).Row


来源: stackexchange

问:
Ligatures in Chrome: Only displaying when adding other characters
I created a font with icomoon

and I wanted to use ligatures. Currently all my ligatures have hyphens in the ligature code.
For example: my-ligature

So when I use

```<code><i>my-ligature</i>
</code>```

It works as expected in Firefox and IE but not Chrome.
When I add a   or any other character like

```<code><i>my-ligature </i>
<i>my-ligature </li>
</code>```

It also works in Chrome.

As soon as I replace the hyphen in the ligature code with something else like an underscore it works in Chrome as expected (no whitespace etc. necessary)

Is this a Chrome Bug or are hyphens not allowed here?

You'll find a demo of the whole thing here (made with a standard icomoon icon)
http://www.swisscocktailblog.ch/icomoon/demo.html

EDIT:
As requested the css for the ligatures (it's the one used in the demo)

```<code>@font-face {
    font-family: 'icomoon';
    src:url('fonts/icomoon.eot?6mfq3a');
    src:url('fonts/icomoon.eot?#iefix6mfq3a') format('embedded-opentype'),
    url('fonts/icomoon.ttf?6mfq3a') format('truetype'),
    url('fonts/icomoon.woff?6mfq3a') format('woff'),
    url('fonts/icomoon.svg?6mfq3a#icomoon') format('svg');
    font-weight: normal;
    font-style: normal;
}

i, .icomoon-liga {
    font-family: 'icomoon';
    speak: none;
    font-style: normal;
    font-weight: normal;
    font-variant: normal;
    text-transform: none;
    line-height: 1;

    /* Enable Ligatures ================ */
    letter-spacing: 0;
    -webkit-font-feature-settings: "liga";
    -moz-font-feature-settings: "liga=1";
    -moz-font-feature-settings: "liga";
    -ms-font-feature-settings: "liga" 1;
    -o-font-feature-settings: "liga";
    font-feature-settings: "liga";

    /* Better Font Rendering =========== */
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}

.icon-wifi-full:before {
    content: "\e600";
}
</code>```

答:
We too have the same issue in Angular 4 when creating our own icon in chrome 59.0.  using css property

```<code>{
    white-space : pre;
}
</code>```

does solve this.
Mozilla 54.0.1 its working fine.

ContentLicense: CC BY-SA 3.0

Body:
I created a font with icomoon

and I wanted to use ligatures. Currently all my ligatures have hyphens in the ligature code.
For example: my-ligature

So when I use

my-ligature

It works as expected in Firefox and IE but not Chrome.
When I add a   or any other character like

my-ligature
my-ligature

It also works in Chrome.

As soon as I replace the hyphen in the ligature code with something else like an underscore it works in Chrome as expected (no whitespace etc. necessary)

Is this a Chrome Bug or are hyphens not allowed here?

You'll find a demo of the whole thing here (made with a standard icomoon icon)
http://www.swisscocktailblog.ch/icomoon/demo.html

EDIT:
As requested the css for the ligatures (it's the one used in the demo)

@font-face {
    font-family: 'icomoon';
    src:url('fonts/icomoon.eot?6mfq3a');
    src:url('fonts/icomoon.eot?#iefix6mfq3a') format('embedded-opentype'),
    url('fonts/icomoon.ttf?6mfq3a') format('truetype'),
    url('fonts/icomoon.woff?6mfq3a') format('woff'),
    url('fonts/icomoon.svg?6mfq3a#icomoon') format('svg');
    font-weight: normal;
    font-style: normal;
}

i, .icomoon-liga {
    font-family: 'icomoon';
    speak: none;
    font-style: normal;
    font-weight: normal;
    font-variant: normal;
    text-transform: none;
    line-height: 1;

    /* Enable Ligatures ================ */
    letter-spacing: 0;
    -webkit-font-feature-settings: "liga";
    -moz-font-feature-settings: "liga=1";
    -moz-font-feature-settings: "liga";
    -ms-font-feature-settings: "liga" 1;
    -o-font-feature-settings: "liga";
    font-feature-settings: "liga";

    /* Better Font Rendering =========== */
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}

.icon-wifi-full:before {
    content: "\e600";
}

Body:
We too have the same issue in Angular 4 when creating our own icon in chrome 59.0.  using css property

{
    white-space : pre;
}

does solve this.
Mozilla 54.0.1 its working fine.


问:
Cast TreeViewItem to XElement?
I'm trying to iterate through the XElement of two collections so I can compare them, but I get the error :

System.InvalidCastException: 'Unable to cast object of type
  'System.Windows.Controls.TreeViewItem' to type
  'System.Xml.Linq.XElement'.'

My code is:

```<code>private void CompareTrees(ItemCollection xml,ItemCollection xsd )
    {
        bool isMatch = false;
        string header = string.Empty;

        foreach (XElement xexsd in xsd)
        {
            foreach (XElement xexml in xml)
            {
                    if (xexsd.Name.LocalName + " - " + xexsd.Value == xexml.Name.LocalName + " - " + xexsd.Value)
                    {
                    CompareTrees(xml, xsd);
                    isMatch = true;
                    break;
                    }
            }
            if (isMatch == true)
            {
                continue;
            }
            else
            {
                var item = new ListBoxItem();
                lbItems.Items.Add(item);
            }
        }
    }
</code>```

答:
Apparently the ItemCollection contains TreeViewItems. Try this:

```<code>foreach (TreeViewItem tvi in xml.OfType<TreeViewItem>())
{
    XElement xexsd = tvi.DataContext as XElement;
    if (xexsd != null && xexsd.Name.LocalName + " - " + xexsd.Value == xexml.Name.LocalName + " - " + xexsd.Value)
    {
        CompareTrees(xml, xsd);
        isMatch = true;
        break;
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Cast TreeViewItem to XElement?

Body:
I'm trying to iterate through the XElement of two collections so I can compare them, but I get the error :

System.InvalidCastException: 'Unable to cast object of type
  'System.Windows.Controls.TreeViewItem' to type
  'System.Xml.Linq.XElement'.'

My code is:

private void CompareTrees(ItemCollection xml,ItemCollection xsd )
    {
        bool isMatch = false;
        string header = string.Empty;

        foreach (XElement xexsd in xsd)
        {
            foreach (XElement xexml in xml)
            {
                    if (xexsd.Name.LocalName + " - " + xexsd.Value == xexml.Name.LocalName + " - " + xexsd.Value)
                    {
                    CompareTrees(xml, xsd);
                    isMatch = true;
                    break;
                    }
            }
            if (isMatch == true)
            {
                continue;
            }
            else
            {
                var item = new ListBoxItem();
                lbItems.Items.Add(item);
            }
        }
    }

Body:
Apparently the ItemCollection contains TreeViewItems. Try this:

foreach (TreeViewItem tvi in xml.OfType<TreeViewItem>())
{
    XElement xexsd = tvi.DataContext as XElement;
    if (xexsd != null && xexsd.Name.LocalName + " - " + xexsd.Value == xexml.Name.LocalName + " - " + xexsd.Value)
    {
        CompareTrees(xml, xsd);
        isMatch = true;
        break;
    }
}


问:
using jquery.noConflict()
I have two files. HTML and .js files. in code.js, I have written jquery code and in HTML file, I am including code.js as following:

```<code><script src="jquery-1.4.2.js"></script>
<script src="jquery.interval.js"></script>
<script src="code.js">
jQuery.noConflict();
var $jcode = jQuery;
</script>
</code>```

in code.js, I have written following:

```<code>jcode(document).ready(function() {
     jcode.interval(checkForms, 2000);
});
</code>```

When I run it, it gives me error as can not read property of interval undefined.
I think there is something wrong with my usage of noConflict. Can you please help?

Thanks

答:
```<code><script src="jquery-1.4.2.js"></script>
<script src="jquery.interval.js"></script>
<script src="code.js">
$.noConflict();
</script>

jQuery(document).ready(function($) {
     $.interval(checkForms, 2000);
});
</code>```

Try this instead of $ symbol use jQuery

ContentLicense: CC BY-SA 2.5

Title: using jquery.noConflict()

Body:
I have two files. HTML and .js files. in code.js, I have written jquery code and in HTML file, I am including code.js as following:

in code.js, I have written following:

jcode(document).ready(function() {
     jcode.interval(checkForms, 2000);
});

When I run it, it gives me error as can not read property of interval undefined.
I think there is something wrong with my usage of noConflict. Can you please help?

Thanks

Body:
<script src="jquery-1.4.2.js"></script>
<script src="jquery.interval.js"></script>
<script src="code.js">
$.noConflict();
</script>

jQuery(document).ready(function($) {
     $.interval(checkForms, 2000);
});

Try this instead of $ symbol use jQuery


问:
Determining the object type which send as parameter
I have three classes called Person, City and District, and some other.

I'm sending one of these three classes as a function parameter. I want to do an operation depends on which one of these three has been sended. How can I do that? All these three classes extends an Entity class.

Now it's like:

```<code>public void Insert (City newCity)
</code>```

but I want it be like:

```<code>public void Insert (Entity e)
</code>```

or something like that, and whichever it is (City or Person), I want to use it's properties.

Thank you!

答:
The best way would be implementing different methods. If they have some general logic inside, just take it to the different method and call it.

```<code>public void Insert (City newCity)
{
    // TODO logic for City
}

public void Insert (Entity e)
{
    // TODO logic for Entity
}
</code>```

Another way to do it is inheritance. If City can be derived from Entity than better do it this way:

```<code>public class Entity
{
    public virutal void Insert (Entity e)
    {
        // TODO logic for Entity
    }
}

public class City : Entity
{
    public override void Insert (City city)
    {
        // TODO logic for City
    }
}
</code>```

Body:
I have three classes called Person, City and District, and some other.

I'm sending one of these three classes as a function parameter. I want to do an operation depends on which one of these three has been sended. How can I do that? All these three classes extends an Entity class.

Now it's like:

public void Insert (City newCity)

but I want it be like:

public void Insert (Entity e)

or something like that, and whichever it is (City or Person), I want to use it's properties.

Thank you!

Body:
The best way would be implementing different methods. If they have some general logic inside, just take it to the different method and call it.

public void Insert (City newCity)
{
    // TODO logic for City
}

public void Insert (Entity e)
{
    // TODO logic for Entity
}

Another way to do it is inheritance. If City can be derived from Entity than better do it this way:

public class Entity
{
    public virutal void Insert (Entity e)
    {
        // TODO logic for Entity
    }
}

public class City : Entity
{
    public override void Insert (City city)
    {
        // TODO logic for City
    }
}


问:
android studio 2.3.3 sdk manager show package details not working
As i updated Android Studio to 2.3, i am facing this issue of SDK Manager. Due to which I am unable to update my SDK.

Here is a screen shot of Android Studio SDK manager where you can see that SHOW DETAILS option is frozen

答: I simply uninstalled Android Studio completely, downloaded the latest version of Android Studio & reinstalled it. And now every thing is working fine.</p>


问:
Swift is not assigning variables from JSON results
I have an issue with loading JSON results within swift (php connection).

I can retrieve JSON data but it will not let me assign it to a variable.

it always assigns the results as Optional.

The JSON Data:

```<code>{
"country": [{
    "id": 1,
    "name": "Australia",
    "code": 61
}, {
    "id": 2,
    "name": "New Zealand",
    "code": 64
}]
}
</code>```

The xCode Output:

```<code> ["country": <__NSArrayI 0x60000002da20>(
 {
     code = 61;
     id = 1;
     name = Australia;
 },
 {
     code = 64;
     id = 2;
     name = "New Zealand";
 }
 )
 ]
 Country Name: Optional(Australia)
 Country Name: Optional(New Zealand)
</code>```

The .swift file:

```<code>//function did_load
override func viewDidLoad() {
    super.viewDidLoad()

    //created RequestURL
    let requestURL = URL(string: get_codes)

    //creating NSMutable
    let request = NSMutableURLRequest(url: requestURL!)

    //setting the method to GET
    request.httpMethod = "GET"

    //create a task to get results
    let task = URLSession.shared.dataTask(with: request as URLRequest) {
        data, response, error in

        if error != nil{
            print("error is \(String(describing: error))")
            return;
        }

        //lets parse the response
        do {
            let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String: Any]
            print(json)
            if let countries = json["country"] as? [[String: AnyObject]] {
                for country in countries {
                    print("Country Name: \(String(describing: country["name"]))")
                    print("Country Code: \(String(describing: country["code"]))")
                    if let couname = country["name"] as? [AnyObject] {
                        print(couname)
                    }

                    if let coucode = country["code"] as? [AnyObject] {
                        print(coucode)
                    }
                }
            }
        } catch {
            print("Error Serializing JSON: \(error)")
        }
    }
    //executing the task
    task.resume()
}
</code>```

答:
You need to unwrap the optional before you try to use it via string interpolation. The safest way to do that is via optional binding:

Please use below code, which will work for you.

```<code>  if let countries = json["country"] as? [[String: AnyObject]] {
            for country in countries {
                print("Country Name: \(country["name"] as! String)")
                print("Country Code: \(country["code"] as! String)")
                if let couname = country["name"] as? String {
                    print(couname)
                }

                if let coucode = country["code"] as? Int {
                    print(coucode)
                }
            }
        }
</code>```

Body:
I have an issue with loading JSON results within swift (php connection).

I can retrieve JSON data but it will not let me assign it to a variable.

it always assigns the results as Optional.

The JSON Data:

{
"country": [{
    "id": 1,
    "name": "Australia",
    "code": 61
}, {
    "id": 2,
    "name": "New Zealand",
    "code": 64
}]
}

The xCode Output:

 ["country": <__NSArrayI 0x60000002da20>(
 {
     code = 61;
     id = 1;
     name = Australia;
 },
 {
     code = 64;
     id = 2;
     name = "New Zealand";
 }
 )
 ]
 Country Name: Optional(Australia)
 Country Name: Optional(New Zealand)

The .swift file:

//function did_load
override func viewDidLoad() {
    super.viewDidLoad()

    //created RequestURL
    let requestURL = URL(string: get_codes)

    //creating NSMutable
    let request = NSMutableURLRequest(url: requestURL!)

    //setting the method to GET
    request.httpMethod = "GET"

    //create a task to get results
    let task = URLSession.shared.dataTask(with: request as URLRequest) {
        data, response, error in

        if error != nil{
            print("error is \(String(describing: error))")
            return;
        }

        //lets parse the response
        do {
            let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String: Any]
            print(json)
            if let countries = json["country"] as? [[String: AnyObject]] {
                for country in countries {
                    print("Country Name: \(String(describing: country["name"]))")
                    print("Country Code: \(String(describing: country["code"]))")
                    if let couname = country["name"] as? [AnyObject] {
                        print(couname)
                    }

                    if let coucode = country["code"] as? [AnyObject] {
                        print(coucode)
                    }
                }
            }
        } catch {
            print("Error Serializing JSON: \(error)")
        }
    }
    //executing the task
    task.resume()
}

Body:
You need to unwrap the optional before you try to use it via string interpolation. The safest way to do that is via optional binding:

Please use below code, which will work for you.

  if let countries = json["country"] as? [[String: AnyObject]] {
            for country in countries {
                print("Country Name: \(country["name"] as! String)")
                print("Country Code: \(country["code"] as! String)")
                if let couname = country["name"] as? String {
                    print(couname)
                }

                if let coucode = country["code"] as? Int {
                    print(coucode)
                }
            }
        }


问:
ZAP seems to incorrectly report path traversal vulnerability in Angular app
I'm running OWASP ZAP as part of an automated CI/CD process.  I am doing a spider and active scan.  The report showed that there is a Path Traversal error.

First, this is an Angular 2 site so there wouldn't be anything revealed on the server.  Second, when I view the URL in question with and without the "attack", the results are the same.  This URL just downloads a JavaScript file to the browser and the querystring is ignored.  We are using webpack to do the bundling.

https://mysite/js/vendor.ece5bf651436a14bea3e.bundle.js?query=c%3A%2F

If it is a false positive, how can we flag this so subsequent runs don't continue to flag this as an issue? We are using the weekly docker image for this automated process.

答:
You can configure ZAP to automatically flag them as false positives using Context Alert Filters.

However it would be really useful if you would also raise a ZAP issue giving as much information as you can, that way we can hopefully fix the code so that it is no longer reported.


问:
Unable to locate webelement on text box?
I used below link to automate testing:

https://roundtheworld.skyteam.com/B2C/en/Home/WelcomePage

but I am not able to locate the text box web element.

please let me know, if any body know the solution how to locate web element for this website.

答:
If you are using Chrome , either use F12 or ctrl+shift+i to open developer console and than you can do the inspection of element using find function. Hope this helps your problem in inspecting the element. For Firefox use Shift+f2 & for Edge use F12 to open developer option. </p>

<p>There are id and name present for the textbox so you can use them inplace of xpath or css </p>

```<code>driver.find_element_by_id('CityOfOrigin').send_keys("This is test")

driver.find_element_by_name('CityOfOrigin').send_keys("This is test1")
</code>```

Body:
If you are using Chrome , either use F12 or ctrl+shift+i to open developer console and than you can do the inspection of element using find function. Hope this helps your problem in inspecting the element. For Firefox use Shift+f2 & for Edge use F12 to open developer option.

There are id and name present for the textbox so you can use them inplace of xpath or css

driver.find_element_by_id('CityOfOrigin').send_keys("This is test")

driver.find_element_by_name('CityOfOrigin').send_keys("This is test1")


问:
Remove message for whole session with button?
I am using the code below to show a message when a mobile device (smartphone or tablet) is in portrait mode. This works fine!

However, I need code that when the user clicks on the X-button, the message does not appear anymore as long as ANY of the pages of the website are being visited in that session.

But if the website is closed; at the next visit the message should appear again when the website is viewed in portrait mode.

How can this be done?

html,
body {
  width: 100%;
  height: 200%;
}

#warning-message {
  display: none;
}

@media only screen and (orientation:portrait) {
  #warning-message {
    display: block;
  }
}

@media only screen and (orientation:landscape) {
  #warning-message {
    display: none;
  }
}

#landscape-button {
  background-color: #2A3847;
  color: #ffffff;
  border-radius: 0px;
  border: 1px solid white;
  padding: 10px 10px 10px 10px;
  float: right;
  margin-top: -25px;
  margin-right: -15px;
  font-size: 1.3em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Please open in "full page" mode and scale your window to a portrait size to see the message appear.<br><br>
<div id="warning-message" style="position:fixed; margin: 0 auto 0 auto; z-index: 99999999; background-color: #2A3847; width: 90vw; min-height: 90vh; text-align:center; padding:25px 15px 35px 15px; right: 0;
    left: 0;
    margin-right: auto;
    margin-left: auto;">
  <button type="button" id="landscape-button">X</button>
  <p style="font-size: 1.3em; color: #ffffff; positie:absolute; text-align:center;"><span style="margin: 0 0 0 25px; text-align:center; font-size: 2em; letter-spacing: -0.04em;">please rotate your screen</span><br><br>This website is best viewed in landscape mode. So please, rotate your mobile device, and if activated also disable
    your screen rotation lock. If you prefer to remain in portrait mode, ignore this message and close it at the "x".</p>
</div></code>```

答:
Below is what works, taking into account that the session storage only starts after the "X" button is clicked. So even if the page is reloaded before the close button "X" is clicked, the message will still appear when the window is sized to portrait mode or if the mobile device is held in portrait mode. After the "X" button is clicked, the message will no longer appear upon reload of the page within the same session.

See the example here!

```<code>$(document).ready(function() {
    var data = sessionStorage.getItem('isfirst');
    if (data == undefined) {
        $("#warning-message").addClass("shown-modal");
    } else {
        $("#warning-message").hide();
    }
});
//close the pop
$("#landscape-button").on('click', function() {
    sessionStorage.setItem('isfirst', 'true');
    $("#warning-message").hide();
});
</code>```

Body:
I am using the code below to show a message when a mobile device (smartphone or tablet) is in portrait mode. This works fine!

However, I need code that when the user clicks on the X-button, the message does not appear anymore as long as ANY of the pages of the website are being visited in that session.

But if the website is closed; at the next visit the message should appear again when the website is viewed in portrait mode.

How can this be done?

html,
body {
  width: 100%;
  height: 200%;
}

#warning-message {
  display: none;
}

@media only screen and (orientation:portrait) {
  #warning-message {
    display: block;
  }
}

@media only screen and (orientation:landscape) {
  #warning-message {
    display: none;
  }
}

#landscape-button {
  background-color: #2A3847;
  color: #ffffff;
  border-radius: 0px;
  border: 1px solid white;
  padding: 10px 10px 10px 10px;
  float: right;
  margin-top: -25px;
  margin-right: -15px;
  font-size: 1.3em;
}

Please open in "full page" mode and scale your window to a portrait size to see the message appear.

  <button type="button" id="landscape-button">X</button>

please rotate your screen

This website is best viewed in landscape mode. So please, rotate your mobile device, and if activated also disable
    your screen rotation lock. If you prefer to remain in portrait mode, ignore this message and close it at the "x".

Body:
Below is what works, taking into account that the session storage only starts after the "X" button is clicked. So even if the page is reloaded before the close button "X" is clicked, the message will still appear when the window is sized to portrait mode or if the mobile device is held in portrait mode. After the "X" button is clicked, the message will no longer appear upon reload of the page within the same session.

See the example here!

$(document).ready(function() {
    var data = sessionStorage.getItem('isfirst');
    if (data == undefined) {
        $("#warning-message").addClass("shown-modal");
    } else {
        $("#warning-message").hide();
    }
});
//close the pop
$("#landscape-button").on('click', function() {
    sessionStorage.setItem('isfirst', 'true');
    $("#warning-message").hide();
});


问:
How would you go about making this if else if program much more simplistic and less code redundant (C++)?
Write a program that asks for the names of three runners and the time it took each
of them to finish a race. The program should display who came in first, second, and
third place.
Input Validation: Only accept positive numbers for the times.

My Code

```<code>#include <iostream>
#include <string>
using namespace std;

int main()
{
    string runner1, runner2, runner3;
    int time1, time2, time3;

    cout << "Please enter the names of three runners" << endl;
    cin >> runner1 >> runner2 >> runner3;
    cout << "How many minutes did it take " << runner1 << " to finish the race?" << endl;
    cin >> time1;
    cout << "How many minutes did it take " << runner2 << " to finish the race?" << endl;
    cin >> time2;
    cout << "How many minutes did it take " << runner3 << " to finish the race?" << endl;
    cin >> time3;

    if (time1 < time2 && time1 < time3)
    {
        cout << runner1 << " is 1st place!" << endl;

        if (time2 < time3)
        {
            cout << runner2 << " is 2nd place!" << endl;
            cout << runner3 << " is 3rd place!" << endl;
        }
        else if (time3 < time2)
        {
            cout << runner3 << " is 2nd place!" << endl;
            cout << runner2 << " is 3rd place!" << endl;
        }
    }
    else if (time2 < time1 && time2 < time3)
    {
        cout << runner2 << " is 1st place!" << endl;

        if (time1 < time3)
        {
            cout << runner1 << " is 2nd place!" << endl;
            cout << runner3 << " is 3rd place!" << endl;
        }
        else if (time3 < time1)
        {
            cout << runner3 << " is 2nd place!" << endl;
            cout << runner2 << " is 3rd place!" << endl;
        }
    }
    else if (time3 < time2 && time3 < time1)
    {
        cout << runner3 << " is 1st Place!" << endl;

        if (time2 < time1)
        {
            cout << runner2 << " is 2nd place!" << endl;
            cout << runner1 << " is 3rd place!" << endl;
        }
        else if (time1 < time2)
        {
            cout << runner1 << " is 2nd place!" << endl;
            cout << runner2 << " is 3rd place!" << endl;
        }
    }
    else
    {
        cout << "Error! Please restart the program and input a positive value" << endl;
    }
    return 0;
}
</code>```

答:
I may have laughed a little at the complexity of Richard's answer.

He makes excellent points about organizing code, of course.

I end up posting my own review and a "simpler" sample, because I think the most important side of a program is functionality.

In this case,

you need error handling (the user may enter illegal values)

you need to check input (the user may enter more than 3 names, may enter identical names etc)

you need to properly report ranks. If two runners had the same time, you will rank them in "arbitrary" order. You will want to correctly rate them as shared places.

My code

is less tied to 3 runners (only when reading the three names, because that's what the sample required)

exemplifies the use of partial_sort to get just the first 3 positions sorted That is no longer possible since the display function handles collections of unknown size and sharing places implies there maybe more than 3 ranked runners.

Live On Coliru

```<code>#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <set>

void static inline ignore_rest_of_line() {
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}

struct Runner {
    std::string name;
    int time = 0;

    bool operator<(Runner const& o) const { return time < o.time; }
};

std::vector<Runner> read_three() {
    std::string name1, name2, name3;
    auto unique = [&] { return std::set<std::string>{ name1, name2, name3 }.size() == 3; };

    std::cout << "Please enter the names of three runners\n";

    while (std::cin) {
        if (std::cin >> name1 >> name2 >> name3 && unique())
            break;
        std::cout << "Enter 3 unique names\n";
        ignore_rest_of_line();
    }

    ignore_rest_of_line();
    return { { name1, 0 }, { name2, 0 }, { name3, 0 } };
}

void read_time(Runner& runner) {
    while (std::cin) {
        std::cout << "How many minutes did it take " << runner.name << " to finish the race?\n";
        if ((std::cin >> runner.time) && runner.time > 0)
            break;
        std::cout << "Enter a valid time\n";
        std::cin.clear();
        ignore_rest_of_line();
    }

    ignore_rest_of_line();
}

template <typename List>
void display_winners(List runners) {
    std::sort(std::begin(runners), std::end(runners));

    std::string ranks[] = { "1st", "2nd", "3rd" };

    auto prev = runners.begin();
    auto rank = std::begin(ranks);

    for (auto& runner : runners) {
        if (runner.time != prev->time)
            ++rank;
        if (rank == std::end(ranks))
            break;
        std::cout << runner.name << " is " << *rank << " place\n";
    }
}

int main() {
    std::cin.exceptions(std::ios::eofbit);
    auto runners = read_three();

    for (auto& runner : runners) {
        read_time(runner);
    }

    display_winners(runners);
}
</code>```

The sample run shows

Please enter the names of three runners

  a a b

  Enter 3 unique names

  a b c

  How many minutes did it take a to finish the race?

  9

  How many minutes did it take b to finish the race?

  invalid time 7

  Enter a valid time

  How many minutes did it take b to finish the race?

  8

  How many minutes did it take c to finish the race?

  8

  c is 1st place

  b is 1st place

  a is 2nd place

Body:
Write a program that asks for the names of three runners and the time it took each
of them to finish a race. The program should display who came in first, second, and
third place.
Input Validation: Only accept positive numbers for the times.

My Code

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string runner1, runner2, runner3;
    int time1, time2, time3;

    cout << "Please enter the names of three runners" << endl;
    cin >> runner1 >> runner2 >> runner3;
    cout << "How many minutes did it take " << runner1 << " to finish the race?" << endl;
    cin >> time1;
    cout << "How many minutes did it take " << runner2 << " to finish the race?" << endl;
    cin >> time2;
    cout << "How many minutes did it take " << runner3 << " to finish the race?" << endl;
    cin >> time3;

    if (time1 < time2 && time1 < time3)
    {
        cout << runner1 << " is 1st place!" << endl;

        if (time2 < time3)
        {
            cout << runner2 << " is 2nd place!" << endl;
            cout << runner3 << " is 3rd place!" << endl;
        }
        else if (time3 < time2)
        {
            cout << runner3 << " is 2nd place!" << endl;
            cout << runner2 << " is 3rd place!" << endl;
        }
    }
    else if (time2 < time1 && time2 < time3)
    {
        cout << runner2 << " is 1st place!" << endl;

        if (time1 < time3)
        {
            cout << runner1 << " is 2nd place!" << endl;
            cout << runner3 << " is 3rd place!" << endl;
        }
        else if (time3 < time1)
        {
            cout << runner3 << " is 2nd place!" << endl;
            cout << runner2 << " is 3rd place!" << endl;
        }
    }
    else if (time3 < time2 && time3 < time1)
    {
        cout << runner3 << " is 1st Place!" << endl;

        if (time2 < time1)
        {
            cout << runner2 << " is 2nd place!" << endl;
            cout << runner1 << " is 3rd place!" << endl;
        }
        else if (time1 < time2)
        {
            cout << runner1 << " is 2nd place!" << endl;
            cout << runner2 << " is 3rd place!" << endl;
        }
    }
    else
    {
        cout << "Error! Please restart the program and input a positive value" << endl;
    }
    return 0;
}

Body:
I may have laughed a little at the complexity of Richard's answer.

He makes excellent points about organizing code, of course.

I end up posting my own review and a "simpler" sample, because I think the most important side of a program is functionality.

In this case,

you need error handling (the user may enter illegal values)

you need to check input (the user may enter more than 3 names, may enter identical names etc)

you need to properly report ranks. If two runners had the same time, you will rank them in "arbitrary" order. You will want to correctly rate them as shared places.

My code

is less tied to 3 runners (only when reading the three names, because that's what the sample required)

exemplifies the use of partial_sort to get just the first 3 positions sorted That is no longer possible since the display function handles collections of unknown size and sharing places implies there maybe more than 3 ranked runners.

Live On Coliru

#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <set>

void static inline ignore_rest_of_line() {
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}

struct Runner {
    std::string name;
    int time = 0;

    bool operator<(Runner const& o) const { return time < o.time; }
};

std::vector<Runner> read_three() {
    std::string name1, name2, name3;
    auto unique = [&] { return std::set<std::string>{ name1, name2, name3 }.size() == 3; };

    std::cout << "Please enter the names of three runners\n";

    while (std::cin) {
        if (std::cin >> name1 >> name2 >> name3 && unique())
            break;
        std::cout << "Enter 3 unique names\n";
        ignore_rest_of_line();
    }

    ignore_rest_of_line();
    return { { name1, 0 }, { name2, 0 }, { name3, 0 } };
}

void read_time(Runner& runner) {
    while (std::cin) {
        std::cout << "How many minutes did it take " << runner.name << " to finish the race?\n";
        if ((std::cin >> runner.time) && runner.time > 0)
            break;
        std::cout << "Enter a valid time\n";
        std::cin.clear();
        ignore_rest_of_line();
    }

    ignore_rest_of_line();
}

template <typename List>
void display_winners(List runners) {
    std::sort(std::begin(runners), std::end(runners));

    std::string ranks[] = { "1st", "2nd", "3rd" };

    auto prev = runners.begin();
    auto rank = std::begin(ranks);

    for (auto& runner : runners) {
        if (runner.time != prev->time)
            ++rank;
        if (rank == std::end(ranks))
            break;
        std::cout << runner.name << " is " << *rank << " place\n";
    }
}

int main() {
    std::cin.exceptions(std::ios::eofbit);
    auto runners = read_three();

    for (auto& runner : runners) {
        read_time(runner);
    }

    display_winners(runners);
}

The sample run shows

Please enter the names of three runners

  a a b

  Enter 3 unique names

  a b c

  How many minutes did it take a to finish the race?

  9

  How many minutes did it take b to finish the race?

  invalid time 7

  Enter a valid time

  How many minutes did it take b to finish the race?

  8

  How many minutes did it take c to finish the race?

  8

  c is 1st place

  b is 1st place

  a is 2nd place


问:
click on textview on listview on fragment
click on textview on listview on fragment

TextView On category_row.xml textViewCategoryName

onclick SetText this textViewCategoryName ok!

CategoriesFragment.java

```<code>package com.example;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.widget.ContentLoadingProgressBar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.example.adapter.CategoryArrayAdapter;
import com.example.model.CategoryDataModel;
import com.example.parser.JSONParser;
import com.example.utils.Keys;

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

import java.util.ArrayList;

public class CategoriesFragment extends Fragment {

    private ListView listView;
    private ArrayList<CategoryDataModel> list;
    private CategoryArrayAdapter adapter;
    private TextView categoryCurrent;

    public CategoriesFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_categories, null);

        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        /**
         * Array List for Binding Data from JSON to this List
         */
        list = new ArrayList<>();

        adapter = new CategoryArrayAdapter(getActivity(), list);

        /**
         * Getting List and Setting List Adapter
         */
        listView = (ListView) getActivity().findViewById(R.id.listView);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Snackbar.make(getActivity().findViewById(R.id.parentLayout), list.get(position).getCategoryName(), Snackbar.LENGTH_LONG).show();
            }
        });

        /**
         * Check internet connection
         */
        //if (InternetConnection.checkConnection(getApplicationContext())) {
        new GetDataCategories().execute();
        //} else {
        //Snackbar.make(getActivity().findViewById(R.id.parentLayout), "اتصال به اینترنت برقرار نیست", Snackbar.LENGTH_LONG).show();
        //}

    }

    /**
     * Creating Get Data Task for Getting Data From Web
     */
    class GetDataCategories extends AsyncTask<Void, Void, Void> {

        ContentLoadingProgressBar progressBar;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            /**
             * Progress Bar for User Interaction
             */
            progressBar = (ContentLoadingProgressBar) getActivity().findViewById(R.id.progress);
            progressBar.show();
        }

        @Nullable
        @Override
        protected Void doInBackground(Void... params) {

            /**
             * Getting JSON Object from Web Using okHttp
             */
            JSONObject jsonObject = JSONParser.getDataFromWeb("http://example.com/api-service/v1/platform_categories/");

            try {
                /**
                 * Check Whether Its NULL???
                 */
                if (jsonObject != null) {
                    /**
                     * Check Length...
                     */
                    if(jsonObject.length() > 0) {
                        /**
                         * Getting Array named "Categories" From MAIN Json Object
                         */
                        JSONArray array = jsonObject.getJSONArray(Keys.KEY_CATEGORIES);

                        /**
                         * Check Length of Array...
                         */
                        int lenArray = array.length();
                        if(lenArray > 0) {
                            for(int jIndex = 0; jIndex < lenArray; jIndex++) {

                                /**
                                 * Creating Every time New Object
                                 * and
                                 * Adding into List
                                 */
                                CategoryDataModel model = new CategoryDataModel();

                                /**
                                 * Getting Inner Object from contacts array...
                                 * and
                                 * From that We will get Name of that Contact
                                 *
                                 */
                                JSONObject innerObject = array.getJSONObject(jIndex);

                                String category_name = innerObject.getString(Keys.KEY_CATEGORY_NAME);
                                String category_link = innerObject.getString(Keys.KEY_CATEGORY_LINK);

                                /**
                                 * Getting Object from Object "other"
                                 */
                                //JSONObject otherObject = innerObject.getJSONObject(Keys.KEY_NAME);
                                //String other = otherObject.getString(Keys.KEY_NAME_SUB);

                                model.setCategoryName(category_name);
                                model.setCategoryLink(category_link);

                                /**
                                 * Adding data in List...
                                 */
                                list.add(model);
                            }
                        }
                    }
                } else {

                }
            } catch (JSONException je) {
                Log.i(JSONParser.TAG, "" + je.getLocalizedMessage());
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);

            /**
             * Progress Bar for User Interaction
             */
            progressBar.hide();

            /**
             * Checking if List size if more than zero then
             * Update ListView
             */
            if(list.size() > 0) {
                adapter.notifyDataSetChanged();
            } else {
                Snackbar.make(getActivity().findViewById(R.id.parentLayout), "مشکلی در اتصال به سرورهای سخنک رخ داده است!", Snackbar.LENGTH_LONG).show();
            }
        }
    }

}
</code>```

CategoryArrayAdapter.java

```<code>package com.example.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.R;
import com.example.model.CategoryDataModel;

import java.util.List;

public class CategoryArrayAdapter extends ArrayAdapter<CategoryDataModel> {

    List<CategoryDataModel> modelList;
    Context context;
    private LayoutInflater mInflater;

    // Constructors
    public CategoryArrayAdapter(Context context, List<CategoryDataModel> objects) {
        super(context, 0, objects);
        this.context = context;
        this.mInflater = LayoutInflater.from(context);
        modelList = objects;
    }

    @Override
    public CategoryDataModel getItem(int position) {
        return modelList.get(position);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final ViewHolder vh;
        if (convertView == null) {
            View view = mInflater.inflate(R.layout.category_row, parent, false);
            vh = ViewHolder.create((RelativeLayout) view);
            view.setTag(vh);
        } else {
            vh = (ViewHolder) convertView.getTag();
        }

        CategoryDataModel item = getItem(position);

        vh.textViewCategoryName.setText(item.getCategoryName());

        return vh.rootView;
    }

    private static class ViewHolder {
        public final RelativeLayout rootView;
        public final TextView textViewCategoryName;

        private ViewHolder(RelativeLayout rootView, TextView textViewCategoryName) {
            this.rootView = rootView;
            this.textViewCategoryName = textViewCategoryName;
        }

        public static ViewHolder create(RelativeLayout rootView) {
            TextView textViewCategoryName = (TextView) rootView.findViewById(R.id.textViewCategoryName);
            return new ViewHolder(rootView, textViewCategoryName);
        }
    }
}
</code>```

fragment_categories.xml

```<code><?xml version="1.0" encoding="utf-8"?>

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:id="@+id/parentLayout"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context=".MainActivity">

    <android.support.v4.widget.ContentLoadingProgressBar
        android:id="@+id/progress"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:visibility="visible" />

    <ListView app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:id="@+id/listView"
        android:layout_width="fill_parent"
        android:layout_height="match_parent" />

</android.support.design.widget.CoordinatorLayout>
</code>```

category_row.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:orientation="vertical"
        android:layout_centerVertical="true"
        android:layout_height="wrap_content"
        android:layout_toLeftOf="@+id/imageViewProfilePhoto">

        <TextView
            android:id="@+id/textViewCategoryName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:textAppearance="?android:textAppearanceSmall"
            android:textIsSelectable="true"
            tools:text="Quote Content" />

        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="right"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true">

        </LinearLayout>

    </LinearLayout>

</RelativeLayout>
</code>```

答:
You have to set an onClickListener to your TextView in your ViewHolder.

```<code>private static class ViewHolder {
    public final RelativeLayout rootView;
    public final TextView textViewCategoryName;

    private ViewHolder(RelativeLayout rootView, TextView textViewCategoryName) {
        this.rootView = rootView;
        this.textViewCategoryName = textViewCategoryName;
    }

    public static ViewHolder create(RelativeLayout rootView) {
        TextView textViewCategoryName = (TextView) rootView.findViewById(R.id.textViewCategoryName);
        textViewCategoryName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Do whatever you want
            }
        });
        return new ViewHolder(rootView, textViewCategoryName);
    }
}
</code>```

Body:
click on textview on listview on fragment

TextView On category_row.xml textViewCategoryName

onclick SetText this textViewCategoryName ok!

CategoriesFragment.java

package com.example;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.widget.ContentLoadingProgressBar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.example.adapter.CategoryArrayAdapter;
import com.example.model.CategoryDataModel;
import com.example.parser.JSONParser;
import com.example.utils.Keys;

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

import java.util.ArrayList;

public class CategoriesFragment extends Fragment {

    private ListView listView;
    private ArrayList<CategoryDataModel> list;
    private CategoryArrayAdapter adapter;
    private TextView categoryCurrent;

    public CategoriesFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_categories, null);

        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        /**
         * Array List for Binding Data from JSON to this List
         */
        list = new ArrayList<>();

        adapter = new CategoryArrayAdapter(getActivity(), list);

        /**
         * Getting List and Setting List Adapter
         */
        listView = (ListView) getActivity().findViewById(R.id.listView);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Snackbar.make(getActivity().findViewById(R.id.parentLayout), list.get(position).getCategoryName(), Snackbar.LENGTH_LONG).show();
            }
        });

        /**
         * Check internet connection
         */
        //if (InternetConnection.checkConnection(getApplicationContext())) {
        new GetDataCategories().execute();
        //} else {
        //Snackbar.make(getActivity().findViewById(R.id.parentLayout), "اتصال به اینترنت برقرار نیست", Snackbar.LENGTH_LONG).show();
        //}

    }

    /**
     * Creating Get Data Task for Getting Data From Web
     */
    class GetDataCategories extends AsyncTask<Void, Void, Void> {

        ContentLoadingProgressBar progressBar;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            /**
             * Progress Bar for User Interaction
             */
            progressBar = (ContentLoadingProgressBar) getActivity().findViewById(R.id.progress);
            progressBar.show();
        }

        @Nullable
        @Override
        protected Void doInBackground(Void... params) {

            /**
             * Getting JSON Object from Web Using okHttp
             */
            JSONObject jsonObject = JSONParser.getDataFromWeb("http://example.com/api-service/v1/platform_categories/");

            try {
                /**
                 * Check Whether Its NULL???
                 */
                if (jsonObject != null) {
                    /**
                     * Check Length...
                     */
                    if(jsonObject.length() > 0) {
                        /**
                         * Getting Array named "Categories" From MAIN Json Object
                         */
                        JSONArray array = jsonObject.getJSONArray(Keys.KEY_CATEGORIES);

                        /**
                         * Check Length of Array...
                         */
                        int lenArray = array.length();
                        if(lenArray > 0) {
                            for(int jIndex = 0; jIndex < lenArray; jIndex++) {

                                /**
                                 * Creating Every time New Object
                                 * and
                                 * Adding into List
                                 */
                                CategoryDataModel model = new CategoryDataModel();

                                /**
                                 * Getting Inner Object from contacts array...
                                 * and
                                 * From that We will get Name of that Contact
                                 *
                                 */
                                JSONObject innerObject = array.getJSONObject(jIndex);

                                String category_name = innerObject.getString(Keys.KEY_CATEGORY_NAME);
                                String category_link = innerObject.getString(Keys.KEY_CATEGORY_LINK);

                                /**
                                 * Getting Object from Object "other"
                                 */
                                //JSONObject otherObject = innerObject.getJSONObject(Keys.KEY_NAME);
                                //String other = otherObject.getString(Keys.KEY_NAME_SUB);

                                model.setCategoryName(category_name);
                                model.setCategoryLink(category_link);

                                /**
                                 * Adding data in List...
                                 */
                                list.add(model);
                            }
                        }
                    }
                } else {

                }
            } catch (JSONException je) {
                Log.i(JSONParser.TAG, "" + je.getLocalizedMessage());
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);

            /**
             * Progress Bar for User Interaction
             */
            progressBar.hide();

            /**
             * Checking if List size if more than zero then
             * Update ListView
             */
            if(list.size() > 0) {
                adapter.notifyDataSetChanged();
            } else {
                Snackbar.make(getActivity().findViewById(R.id.parentLayout), "مشکلی در اتصال به سرورهای سخنک رخ داده است!", Snackbar.LENGTH_LONG).show();
            }
        }
    }

}

CategoryArrayAdapter.java

package com.example.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.R;
import com.example.model.CategoryDataModel;

import java.util.List;

public class CategoryArrayAdapter extends ArrayAdapter<CategoryDataModel> {

    List<CategoryDataModel> modelList;
    Context context;
    private LayoutInflater mInflater;

    // Constructors
    public CategoryArrayAdapter(Context context, List<CategoryDataModel> objects) {
        super(context, 0, objects);
        this.context = context;
        this.mInflater = LayoutInflater.from(context);
        modelList = objects;
    }

    @Override
    public CategoryDataModel getItem(int position) {
        return modelList.get(position);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final ViewHolder vh;
        if (convertView == null) {
            View view = mInflater.inflate(R.layout.category_row, parent, false);
            vh = ViewHolder.create((RelativeLayout) view);
            view.setTag(vh);
        } else {
            vh = (ViewHolder) convertView.getTag();
        }

        CategoryDataModel item = getItem(position);

        vh.textViewCategoryName.setText(item.getCategoryName());

        return vh.rootView;
    }

    private static class ViewHolder {
        public final RelativeLayout rootView;
        public final TextView textViewCategoryName;

        private ViewHolder(RelativeLayout rootView, TextView textViewCategoryName) {
            this.rootView = rootView;
            this.textViewCategoryName = textViewCategoryName;
        }

        public static ViewHolder create(RelativeLayout rootView) {
            TextView textViewCategoryName = (TextView) rootView.findViewById(R.id.textViewCategoryName);
            return new ViewHolder(rootView, textViewCategoryName);
        }
    }
}

fragment_categories.xml

<?xml version="1.0" encoding="utf-8"?>

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:id="@+id/parentLayout"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context=".MainActivity">

    <android.support.v4.widget.ContentLoadingProgressBar
        android:id="@+id/progress"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:visibility="visible" />

    <ListView app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:id="@+id/listView"
        android:layout_width="fill_parent"
        android:layout_height="match_parent" />

</android.support.design.widget.CoordinatorLayout>

category_row.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:orientation="vertical"
        android:layout_centerVertical="true"
        android:layout_height="wrap_content"
        android:layout_toLeftOf="@+id/imageViewProfilePhoto">

        <TextView
            android:id="@+id/textViewCategoryName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:textAppearance="?android:textAppearanceSmall"
            android:textIsSelectable="true"
            tools:text="Quote Content" />

        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="right"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true">

        </LinearLayout>

    </LinearLayout>

</RelativeLayout>

Body:
You have to set an onClickListener to your TextView in your ViewHolder.

private static class ViewHolder {
    public final RelativeLayout rootView;
    public final TextView textViewCategoryName;

    private ViewHolder(RelativeLayout rootView, TextView textViewCategoryName) {
        this.rootView = rootView;
        this.textViewCategoryName = textViewCategoryName;
    }

    public static ViewHolder create(RelativeLayout rootView) {
        TextView textViewCategoryName = (TextView) rootView.findViewById(R.id.textViewCategoryName);
        textViewCategoryName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Do whatever you want
            }
        });
        return new ViewHolder(rootView, textViewCategoryName);
    }
}


问:
Javascript - Change Button function once I click it
I have a button and 3 functions.
change each funtion once I click it
Please Help me.</p>

答:
```<code>i dont understand your question, i think you mean like this one button
</code>```

try it  and use document.getElementById

<button id="btn" type="button" onclick="document.getElementById('btn').innerHTML = 'Hey There'">Try it</button>```

Body:
i dont understand your question, i think you mean like this one button

try it  and use document.getElementById

<button id="btn" type="button" onclick="document.getElementById('btn').innerHTML = 'Hey There'">Try it</button>


问:
How does the rule "Resources should be closed" check that a connection is closed?
this is a question, not a problem.

I have a class called DSConnectionUtilExternal with one method to retrieve a database connection and one method to close it. This class is in a jar file.

In the other hand I have a project wich includes the jar file as a dependency.
In this proyect I have this code

```<code>Connection con = null;
ResultSet rsGet = null;
PreparedStatement psGet = null;
try {
    con = DSConnectionUtilExternal.openConnection();

    psGet = con.prepareStatement("SELECT * FROM TEST");
    rsGet = psGet.executeQuery();
    int counter = 0;
    while (rsGet.next()) {
        counter++;
        System.err.println(counter);
    }
} catch (Exception e) {
    e.printStackTrace();
} finally {
    try {
        if (rsGet != null) {
            rsGet.close();
        }
    } catch (Exception e2) {
        e2.printStackTrace();
    }
    rsGet = null;
    try {
        if (psGet != null) {
            psGet.close();
        }
    } catch (Exception e2) {
        e2.printStackTrace();
    }
    psGet = null;
    DSConnectionUtilExternal.closeConnection(con);
}
</code>```

If I delete the content of the method closeConnection at the jar file, sonar doesn't detect that the connection is not closed. I think it's normal, sonar doesn't decompile the jar file to access the jar file code.

So the question is? What is the criterion used by the "Resources should be closed" rule to determine if the connection is closed in the finally clause?

Thanks

答:
Correct assumption from your question : At the moment SonarJava  (4.11 just released) does not do cross file analysis and have no clue about what's going on in your closeConnection method.

However, the rule about unclosed resource has a simple heuristic to avoid false positives to consider resources closed if they are passed to a method named close.

SonarJava is on its way to be able to read your jar file and understand the resource is closed there but that is a complicated feature and we hope to deliver it in the near future.

Body:
this is a question, not a problem.

I have a class called DSConnectionUtilExternal with one method to retrieve a database connection and one method to close it. This class is in a jar file.

In the other hand I have a project wich includes the jar file as a dependency.
In this proyect I have this code

Connection con = null;
ResultSet rsGet = null;
PreparedStatement psGet = null;
try {
    con = DSConnectionUtilExternal.openConnection();

    psGet = con.prepareStatement("SELECT * FROM TEST");
    rsGet = psGet.executeQuery();
    int counter = 0;
    while (rsGet.next()) {
        counter++;
        System.err.println(counter);
    }
} catch (Exception e) {
    e.printStackTrace();
} finally {
    try {
        if (rsGet != null) {
            rsGet.close();
        }
    } catch (Exception e2) {
        e2.printStackTrace();
    }
    rsGet = null;
    try {
        if (psGet != null) {
            psGet.close();
        }
    } catch (Exception e2) {
        e2.printStackTrace();
    }
    psGet = null;
    DSConnectionUtilExternal.closeConnection(con);
}

If I delete the content of the method closeConnection at the jar file, sonar doesn't detect that the connection is not closed. I think it's normal, sonar doesn't decompile the jar file to access the jar file code.

So the question is? What is the criterion used by the "Resources should be closed" rule to determine if the connection is closed in the finally clause?

Thanks


问:
Sql Query results to CSV to a specified file path after stored procedure execution
I'm trying to execute a stored procedure (which i know works) in T-SQL that then gets those results into a CSV file and puts that file into a directory.  I'm not sure how to formulate that query, exactly though.  Here's what i've tried thus far to no avail:

```<code>EXECUTE CLR_ExportQueryToCSV @QueryCommand = 'execute databaseName.dbo.StoredProcedureName',
                          @FilePath = 'C:\Directory',
                          @FileName = '\FileToExport.csv',
                          @IncludeHeaders = 1
</code>```

I realize CLR_ExportQueryToCSV doesn't exist.  Is there any system stored procedure that will do what i'm wanting?

答:
There IS one way of doing what you're asking in SQL, but it's not neat or supported (AFAIK).

```<code>EXEC xp_cmdshell 'SQLCMD -S . -d MyDatabase -Q "select * from MyTable" -s "," -o "\\servername\output\result.csv" -W'
</code>```

You can find documentation for SQLCMD here, but essentially what this does is use the xp_cmdshell SP to execute the SQLCMD command line utility on the server and execute a sql statement, piping the output to a CSV file.

The params I've used are as follows:

```<code>-S: SQL Server name - . means current server
-d: database name
-Q: run SQL query and exit
-s: column separator
-o: output file. This is relative to the SQL Server, not your PC
-W: dynamic column witdth
</code>```

By default SQL Server does not allow you to run xp_cmdshell, so you may need to run the following SQL to enable it.

```<code>-- To allow advanced options to be changed.
EXEC sp_configure 'show advanced options', 1
GO
-- To update the currently configured value for advanced options.
RECONFIGURE
GO
-- To enable the feature.
EXEC sp_configure 'xp_cmdshell', 1
GO
-- To update the currently configured value for this feature.
RECONFIGURE
GO
</code>```

Body:
I'm trying to execute a stored procedure (which i know works) in T-SQL that then gets those results into a CSV file and puts that file into a directory.  I'm not sure how to formulate that query, exactly though.  Here's what i've tried thus far to no avail:

EXECUTE CLR_ExportQueryToCSV @QueryCommand = 'execute databaseName.dbo.StoredProcedureName',
                          @FilePath = 'C:\Directory',
                          @FileName = '\FileToExport.csv',
                          @IncludeHeaders = 1

I realize CLR_ExportQueryToCSV doesn't exist.  Is there any system stored procedure that will do what i'm wanting?

Body:
There IS one way of doing what you're asking in SQL, but it's not neat or supported (AFAIK).

EXEC xp_cmdshell 'SQLCMD -S . -d MyDatabase -Q "select * from MyTable" -s "," -o "\\servername\output\result.csv" -W'

You can find documentation for SQLCMD here, but essentially what this does is use the xp_cmdshell SP to execute the SQLCMD command line utility on the server and execute a sql statement, piping the output to a CSV file.

The params I've used are as follows:

-S: SQL Server name - . means current server
-d: database name
-Q: run SQL query and exit
-s: column separator
-o: output file. This is relative to the SQL Server, not your PC
-W: dynamic column witdth

By default SQL Server does not allow you to run xp_cmdshell, so you may need to run the following SQL to enable it.

-- To allow advanced options to be changed.
EXEC sp_configure 'show advanced options', 1
GO
-- To update the currently configured value for advanced options.
RECONFIGURE
GO
-- To enable the feature.
EXEC sp_configure 'xp_cmdshell', 1
GO
-- To update the currently configured value for this feature.
RECONFIGURE
GO


问:
Calculate total number of if-else clauses(including nested)
Need to calculate the number of if-else clauses. I'm using java parser to do it.

What I've done till now:
I've obtained the count of all if and else-if clauses by using the function

```<code>node.getChildNodesByType(IfStmt.class))
</code>```

Problem:
How do I count the else clauses?
This function ignores the "else" clause.

Example:

```<code>if(condition)
{
     if(condition 2)
       //
     else
 }

 else if(condition 3)
{
     if (condition 4)
      //
     else
}
 else
{
   if(condition 5)
      //
}
</code>```

In this case, I'd want the answer to be 8 but the size of the call will return 5 because it encounters only 5 "if's" and ignores the else clauses. Is there any function that can directly help me count the else clauses?

My code:

```<code>  public void visit(IfStmt n, Void arg)
            {
            System.out.println("Found an if statement @ " + n.getBegin());
            }

            void process(Node node)
            {
                count=0;
                for (Node child : node.getChildNodesByType(IfStmt.class))
                {
                    count++;
                   visit((IfStmt)child,null);
                }
            }
</code>```

答:
This answer has been solved on the following github thread.
The in-built methods of the java parser are more than sufficient to help out.

Answer:

```<code> static int process(Node node) {
    int complexity = 0;
    for (IfStmt ifStmt : node.getChildNodesByType(IfStmt.class)) {
        // We found an "if" - cool, add one.
        complexity++;
        printLine(ifStmt);
        if (ifStmt.getElseStmt().isPresent()) {
            // This "if" has an "else"
            Statement elseStmt = ifStmt.getElseStmt().get();
            if (elseStmt instanceof IfStmt) {
                // it's an "else-if". We already count that by counting the "if" above.
            } else {
                // it's an "else-something". Add it.
                complexity++;
                printLine(elseStmt);
            }
        }
    }
    return complexity;
}
</code>```

Body:
Need to calculate the number of if-else clauses. I'm using java parser to do it.

What I've done till now:
I've obtained the count of all if and else-if clauses by using the function

node.getChildNodesByType(IfStmt.class))

Problem:
How do I count the else clauses?
This function ignores the "else" clause.

Example:

if(condition)
{
     if(condition 2)
       //
     else
 }

 else if(condition 3)
{
     if (condition 4)
      //
     else
}
 else
{
   if(condition 5)
      //
}

In this case, I'd want the answer to be 8 but the size of the call will return 5 because it encounters only 5 "if's" and ignores the else clauses. Is there any function that can directly help me count the else clauses?

My code:

  public void visit(IfStmt n, Void arg)
            {
            System.out.println("Found an if statement @ " + n.getBegin());
            }

            void process(Node node)
            {
                count=0;
                for (Node child : node.getChildNodesByType(IfStmt.class))
                {
                    count++;
                   visit((IfStmt)child,null);
                }
            }

Body:
This answer has been solved on the following github thread.
The in-built methods of the java parser are more than sufficient to help out.

Answer:

 static int process(Node node) {
    int complexity = 0;
    for (IfStmt ifStmt : node.getChildNodesByType(IfStmt.class)) {
        // We found an "if" - cool, add one.
        complexity++;
        printLine(ifStmt);
        if (ifStmt.getElseStmt().isPresent()) {
            // This "if" has an "else"
            Statement elseStmt = ifStmt.getElseStmt().get();
            if (elseStmt instanceof IfStmt) {
                // it's an "else-if". We already count that by counting the "if" above.
            } else {
                // it's an "else-something". Add it.
                complexity++;
                printLine(elseStmt);
            }
        }
    }
    return complexity;
}


问:
Meteor Send email to intranet email
I am Developing a Meteor App to handle requests, the app is finished, but i need to have some emails with a default text sent everytime a request is created or updated.

The problem i run into is, i am on an intranet, and our mail server is using the standart 25 port.

i can ping the mail server and checked if the :25 port is open.
the localhost port 25 is on listening state.

I am using the default email package of meteor, that i have used many times before outside our intranet and always worked fine.

my server code is the following:

```<code>#in the meteor startup i put the env MAIL_URL
process.env.MAIL_URL = 'smtp://varajao.rjr:password@ipaddress:25';
#in the methods i put the sendMail Func
sendEmail: function(to, from, subject, text) {
  console.log('para: '+ to + 'de: ' + from);
  console.log('assunto ' + subject + 'texto: ' + text);
  check([to, from, subject, text], [String]);
  this.unblock();

  Email.send({to, from, subject, text});

}
</code>```

and i am getting the following on server, check the fist line and the comment in the end of it.

```<code>Exception while invoking method 'sendEmail' Error: getaddrinfo EAI_AGAIN varajao.rjr:587 **----->somehow this is my username with :587 port**
I20170511-13:50:57.171(1)?     at Object.Future.wait (/home/administrador/.meteor/packages/meteor-tool/.1.4.4_2.8rbyl1++os.linux.x86_64+web.browser+web.cordova/mt-os.linux.x86_64/dev_bundle/server-lib/node_modules/fibers/future.js:449:15)
I20170511-13:50:57.171(1)?     at Mail._syncSendMail (packages/meteor.js:213:24)
I20170511-13:50:57.172(1)?     at smtpSend (packages/email.js:110:13)
I20170511-13:50:57.172(1)?     at new Email.send (packages/email.js:168:5)
I20170511-13:50:57.173(1)?     at Object.Email.send (packages/meteortoys_email.js:28:25)
I20170511-13:50:57.174(1)?     at [object Object].Meteor.methods.sendEmail (server/main.js:375:13)
I20170511-13:50:57.175(1)?     at maybeAuditArgumentChecks (packages/ddp-server/livedata_server.js:1737:12)
I20170511-13:50:57.175(1)?     at packages/ddp-server/livedata_server.js:719:19
I20170511-13:50:57.176(1)?     at [object Object]._.extend.withValue (packages/meteor.js:1122:17)
I20170511-13:50:57.177(1)?     at packages/ddp-server/livedata_server.js:717:40
I20170511-13:50:57.178(1)?     - - - - -
I20170511-13:50:57.179(1)?   atObject.exports._errnoException(util.js:907:11)
I20170511-13:50:57.179(1)?     at errnoException (dns.js:32:15)
I20170511-13:50:57.180(1)?     at GetAddrInfoReqWrap.onlookup [as oncomplete](dns.js:78:26)
</code>```

the mail server is inside the intranet, and we can access it directly by out intranet.

Can you guys give me a hand?

thanks is advance

Rob

答:
Please, make sure your exchange is correctly configured, because if it is not you will get errors like the one i had in this question, for me, i had to allow the email relay to the IP of the app server.

Hope this helps

Rob

Title: Meteor Send email to intranet email

Body:
I am Developing a Meteor App to handle requests, the app is finished, but i need to have some emails with a default text sent everytime a request is created or updated.

The problem i run into is, i am on an intranet, and our mail server is using the standart 25 port.

i can ping the mail server and checked if the :25 port is open.
the localhost port 25 is on listening state.

I am using the default email package of meteor, that i have used many times before outside our intranet and always worked fine.

my server code is the following:

#in the meteor startup i put the env MAIL_URL
process.env.MAIL_URL = 'smtp://varajao.rjr:password@ipaddress:25';
#in the methods i put the sendMail Func
sendEmail: function(to, from, subject, text) {
  console.log('para: '+ to + 'de: ' + from);
  console.log('assunto ' + subject + 'texto: ' + text);
  check([to, from, subject, text], [String]);
  this.unblock();

  Email.send({to, from, subject, text});

}

and i am getting the following on server, check the fist line and the comment in the end of it.

Exception while invoking method 'sendEmail' Error: getaddrinfo EAI_AGAIN varajao.rjr:587 **----->somehow this is my username with :587 port**
I20170511-13:50:57.171(1)?     at Object.Future.wait (/home/administrador/.meteor/packages/meteor-tool/.1.4.4_2.8rbyl1++os.linux.x86_64+web.browser+web.cordova/mt-os.linux.x86_64/dev_bundle/server-lib/node_modules/fibers/future.js:449:15)
I20170511-13:50:57.171(1)?     at Mail._syncSendMail (packages/meteor.js:213:24)
I20170511-13:50:57.172(1)?     at smtpSend (packages/email.js:110:13)
I20170511-13:50:57.172(1)?     at new Email.send (packages/email.js:168:5)
I20170511-13:50:57.173(1)?     at Object.Email.send (packages/meteortoys_email.js:28:25)
I20170511-13:50:57.174(1)?     at [object Object].Meteor.methods.sendEmail (server/main.js:375:13)
I20170511-13:50:57.175(1)?     at maybeAuditArgumentChecks (packages/ddp-server/livedata_server.js:1737:12)
I20170511-13:50:57.175(1)?     at packages/ddp-server/livedata_server.js:719:19
I20170511-13:50:57.176(1)?     at [object Object]._.extend.withValue (packages/meteor.js:1122:17)
I20170511-13:50:57.177(1)?     at packages/ddp-server/livedata_server.js:717:40
I20170511-13:50:57.178(1)?     - - - - -
I20170511-13:50:57.179(1)?   atObject.exports._errnoException(util.js:907:11)
I20170511-13:50:57.179(1)?     at errnoException (dns.js:32:15)
I20170511-13:50:57.180(1)?     at GetAddrInfoReqWrap.onlookup [as oncomplete](dns.js:78:26)

the mail server is inside the intranet, and we can access it directly by out intranet.

Can you guys give me a hand?

thanks is advance

Rob


问:
Batch: Show last user input
(This is my first post here, so bear with me)

Can you show the last user-input in a batch file? I'm gonna try to keep it simple here.

```<code>@echo off

:menu
echo Type 1 to proceed.
set /p example=
if "%example%" == "1" GOTO :proceed
GOTO :error

:proceed
pause

:error
cls
echo You wrote (last user input), that's not correct.
timeout 30
GOTO :menu
</code>```

I know that I could replace the (last user input) with %example%, but then I'd have to make custom error messages for every category, and there are about 50 of them. It'd be easier with a last input command.

By the way, I've taught myself everything that I know about batch, so my example probably has major issues right now, but it works somehow.

答:
I don't know how to do it without temp file. TO get the things written int the console you need the doskey /history (this will skip the running of the script itself):

```<code>@echo off
setlocal enableDelayedExpansion
set "last="
set "but_last="
doskey /history > log.txt
for /f "tokens=* delims=" %%# in (log.txt) do (
    set "but_last=!last!"
    set "last=%%#"
)

echo "%but_last%"
del /s /q log.txt >nul 2>nul
</code>```

Title: Batch: Show last user input

Body:
(This is my first post here, so bear with me)

Can you show the last user-input in a batch file? I'm gonna try to keep it simple here.

@echo off

:menu
echo Type 1 to proceed.
set /p example=
if "%example%" == "1" GOTO :proceed
GOTO :error

:proceed
pause

:error
cls
echo You wrote (last user input), that's not correct.
timeout 30
GOTO :menu

I know that I could replace the (last user input) with %example%, but then I'd have to make custom error messages for every category, and there are about 50 of them. It'd be easier with a last input command.

By the way, I've taught myself everything that I know about batch, so my example probably has major issues right now, but it works somehow.

Body:
I don't know how to do it without temp file. TO get the things written int the console you need the doskey /history (this will skip the running of the script itself):

@echo off
setlocal enableDelayedExpansion
set "last="
set "but_last="
doskey /history > log.txt
for /f "tokens=* delims=" %%# in (log.txt) do (
    set "but_last=!last!"
    set "last=%%#"
)

echo "%but_last%"
del /s /q log.txt >nul 2>nul


问:
Flex not working in firefox while working correctly in chrome and safari
I am currently learning flex CSS property, and I am using it display a bunch of divs with four per row at maximum. Here is HTML and CSS for it:

.outer {
  display: flex;
  flex-wrap: wrap;
  margin: -5% -5% 0 -5%;
}

.step {
  text-align: center;
  display: inline-block;
  border: 2px solid black;
  margin: 5% 5% 0 5%;
  flex-grow: 1;
  height: 100px;
  width: 13%;
  overflow: auto;
}

.child {
  font-size: 1.25em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="outer" id="container">
  <div class='step' id=step0>
    <p class='child'> 1</p>
  </div>
  <div class='step' id=step1>
    <p class='child'> 2</p>
  </div>
  <div class='step' id=step2>
    <p class='child'>3</p>
  </div>
  <div class='step' id=step3>
    <p class='child'> 4</p>
  </div>
  <div class='step error' id=step7>
    <p class='child'>8</p>
  </div>
  <div class='step' id=step6>
    <p class='child'>7</p>
  </div>
  <div class='step' id=step5>
    <p class='child'>6</p>
  </div>
  <div class='step' id=step4>
    <p class='child'>5</p>
  </div>
  <div class='step' id=step8>
    <p class='child'>9</p>
  </div>
  <div class='step' id=step9>
    <p class='child'>10</p>
  </div>
</div></code>```

The css Works exactly the way I want it to work in Chrome, but in firefox vertical gap between different rows is zero, while it is not so in Chrome. What am I doing wrong?
(I have made a fiddle as well, https://jsfiddle.net/vLmnq7fL/2/ . Open in Chrome and firefox to see the difference)

答: Top and bottom margins in % don't work consistently (spec) when applied to flex items. I use px instead</p>

Body:
I am currently learning flex CSS property, and I am using it display a bunch of divs with four per row at maximum. Here is HTML and CSS for it:

.outer {
  display: flex;
  flex-wrap: wrap;
  margin: -5% -5% 0 -5%;
}

.step {
  text-align: center;
  display: inline-block;
  border: 2px solid black;
  margin: 5% 5% 0 5%;
  flex-grow: 1;
  height: 100px;
  width: 13%;
  overflow: auto;
}

.child {
  font-size: 1.25em;
}

 1

 2

3

 4

8

7

6

5

9

10

The css Works exactly the way I want it to work in Chrome, but in firefox vertical gap between different rows is zero, while it is not so in Chrome. What am I doing wrong?
(I have made a fiddle as well, https://jsfiddle.net/vLmnq7fL/2/ . Open in Chrome and firefox to see the difference)


问:
MySql get one record from two identical tables with a check
I want to get same records from two identical tables but with a check.

I have following two tables that are identical :

table_1

```<code>id  | enc   | first_name | last_name | address | city
1   | 1001  | John       | Doe       | abc     |
</code>```

table_2

```<code>id  | enc   | first_name | last_name | address | city
1   | 1001  |            | Doe       |         | xyz
</code>```

I want to get record from table_2 but since first_name and address are empty it should the from record table_1
But again city is empty in table_1 so it would get the record from table_2

I've tried the union like this :

```<code>(SELECT * from `table_1` where `id` = `1)
UNION
(SELECT * from `table_2` where `id` = `1)
</code>```

But its providing both the records from the table. I want only one record using both the table like this :

```<code>id  | enc   | first_name | last_name | address | city
1   | 1001  | John       | Doe       | abc     | xyz
</code>```

答:
You could try something like:

```<code>SELECT table1.id, table1.enc, table1.first_name, table2.last_name, table1.address, table2.city
INNER JOIN table2 on table2.id = table1.id
</code>```

Supposing you always want to get specific fields from one of the tables

Body:
I want to get same records from two identical tables but with a check.

I have following two tables that are identical :

table_1

id  | enc   | first_name | last_name | address | city
1   | 1001  | John       | Doe       | abc     |

table_2

id  | enc   | first_name | last_name | address | city
1   | 1001  |            | Doe       |         | xyz

I want to get record from table_2 but since first_name and address are empty it should the from record table_1
But again city is empty in table_1 so it would get the record from table_2

I've tried the union like this :

(SELECT * from `table_1` where `id` = `1)
UNION
(SELECT * from `table_2` where `id` = `1)

But its providing both the records from the table. I want only one record using both the table like this :

id  | enc   | first_name | last_name | address | city
1   | 1001  | John       | Doe       | abc     | xyz

Body:
You could try something like:

SELECT table1.id, table1.enc, table1.first_name, table2.last_name, table1.address, table2.city
INNER JOIN table2 on table2.id = table1.id

Supposing you always want to get specific fields from one of the tables


问:
EQU for non-immediates x86
I am pretty new to assembly, and I have been wondering if there is any operation that could do the same as EQU but with registers? E.g.:

```<code>Boink EQU EAX
</code>```

If there is no such operation, is there any way to equate Boink with EAX without having to use RESB, RESD and so on?

Apologies if this question seems a bit silly to you, and thank you in advance.

I am using NASM.

答:
The question does seem a bit silly, mainly because your motivation is not clear. Why do you want to do this? Is your goal to make the code more readable, essentially giving symbolic (human-readable) names to otherwise inscrutable register names?

If so, you can use preprocessor macros. Define the macro at the top of your block to introduce the symbolic name, and then make sure that you undefine it at the end of your block to prevent confusion. For example:

```<code>Max:

    %define value1 edx
    %define value2 ecx
    %define result eax

    sub  value1, value2
    sbb  result, result
    not  result
    and  result, value1
    add  result, value2

    %undef value1
    %undef value2
    %undef result

    ret
</code>```

There are cases where this can make the code more readable. The above is arguably one of those cases. It also makes it easier to change the register allocations, which is especially handy when you're playing with (read: benchmarking) code to determine the most optimal allocation strategy.

In MASM, you could do something very similar with the TEXTEQU directive—e.g.,

```<code>value1  TEXTEQU  <edx>
value2  TEXTEQU  <ecx>
result  TEXTEQU  <eax>
</code>```

But you do have to be very careful with this. In real code (at least, real code that has been written to be efficient, and if it's not meant to be efficient, why are you writing it in assembly?), you will almost always reuse registers for multiple purposes. This means that your symbolic names quickly become obsolete. Do you keep using the obsolete names throughout the code? Do you alias multiple symbolic names for each register, covering all possible uses? Do you continually define, undefine, and redefine new symbolic names for the registers? None of these are good options, and whatever you do, you will just make the code even more confusing.

As such, what you'll generally see assembly programmers do is use comments out to the side of each instruction to explain what is going on with that instruction. Something like:

```<code>; Uses branchless instructions to find the maximum of two integers.
; Parameters: EDX == value1
;             ECX == value2
; Returns:  Maximum integer value in EAX
; Clobbers: EDX
Max:
    sub  edx, ecx    ; edx <= (edx - ecx)
    sbb  eax, eax    ; eax <= (CF == 1) ? -1        :  0
    not  eax         ; eax <= (CF == 1) ? 0         : -1
    and  eax, edx    ; eax <= (CF == 1) ? 0         : (edx - ecx)
    add  eax, ecx    ; eax <= (CF == 1) ? (0 + ecx) : ((edx - ecx) + ecx)
    ret
</code>```

Title: EQU for non-immediates x86

Body:
I am pretty new to assembly, and I have been wondering if there is any operation that could do the same as EQU but with registers? E.g.:

Boink EQU EAX

If there is no such operation, is there any way to equate Boink with EAX without having to use RESB, RESD and so on?

Apologies if this question seems a bit silly to you, and thank you in advance.

I am using NASM.

Body:
The question does seem a bit silly, mainly because your motivation is not clear. Why do you want to do this? Is your goal to make the code more readable, essentially giving symbolic (human-readable) names to otherwise inscrutable register names?

If so, you can use preprocessor macros. Define the macro at the top of your block to introduce the symbolic name, and then make sure that you undefine it at the end of your block to prevent confusion. For example:

Max:

    %define value1 edx
    %define value2 ecx
    %define result eax

    sub  value1, value2
    sbb  result, result
    not  result
    and  result, value1
    add  result, value2

    %undef value1
    %undef value2
    %undef result

    ret

There are cases where this can make the code more readable. The above is arguably one of those cases. It also makes it easier to change the register allocations, which is especially handy when you're playing with (read: benchmarking) code to determine the most optimal allocation strategy.

In MASM, you could do something very similar with the TEXTEQU directive—e.g.,

value1  TEXTEQU  <edx>
value2  TEXTEQU  <ecx>
result  TEXTEQU  <eax>

But you do have to be very careful with this. In real code (at least, real code that has been written to be efficient, and if it's not meant to be efficient, why are you writing it in assembly?), you will almost always reuse registers for multiple purposes. This means that your symbolic names quickly become obsolete. Do you keep using the obsolete names throughout the code? Do you alias multiple symbolic names for each register, covering all possible uses? Do you continually define, undefine, and redefine new symbolic names for the registers? None of these are good options, and whatever you do, you will just make the code even more confusing.

As such, what you'll generally see assembly programmers do is use comments out to the side of each instruction to explain what is going on with that instruction. Something like:

; Uses branchless instructions to find the maximum of two integers.
; Parameters: EDX == value1
;             ECX == value2
; Returns:  Maximum integer value in EAX
; Clobbers: EDX
Max:
    sub  edx, ecx    ; edx <= (edx - ecx)
    sbb  eax, eax    ; eax <= (CF == 1) ? -1        :  0
    not  eax         ; eax <= (CF == 1) ? 0         : -1
    and  eax, edx    ; eax <= (CF == 1) ? 0         : (edx - ecx)
    add  eax, ecx    ; eax <= (CF == 1) ? (0 + ecx) : ((edx - ecx) + ecx)
    ret


问:
How to parse a DICOM file(.IMA files) using C++?
I know there are a few libraries available. But I have to write my own parser for it.
I am an amateur. How do I go about tackling this?
What things should I know before trying to write my own parser?</p>

答:
You should know about the DICOM rules for building objects (so-called IODs) and encoding rules for attributes. Then a few rules on file encoding apply, which you should also know.
The DICOM cookbook is a good starting point to familiarize with the terms and principles of the standard.

However, I agree to @Amit Joshi, that I would advise against writing a parser from scratch - there are many good toolkits around, some of them are for free. Especially the encoding rules are not trivial and require a lot of effor to cover all cases (e.g. Transfer Syntaxes, Sequence encoding).