问:
Trying to click next button while scraping
I have a scraping program I need to click the next button while scraping and I actually asked a question on here a week or so ago about how to do that that and got some good responses but the code that I got for the answers only works partially.  It will scrape page 1 and page 2 but instead of going on to page 3 it skips to that last page, page 10 and I cannot figure out why.

```<code>import csv
from scrapy.spiders import Spider
from scrapy_splash import SplashRequest
from ..items import GameItem
def process_csv(csv_file):
    data = []
    reader = csv.reader(csv_file)
    next(reader)
    for fields in reader:
        if fields[0] != "":
            url = fields[0]
        else:
            continue # skip the whole row if the url column is empty
        if fields[1] != "":
            ip = "http://" + fields[1] + ":8050" # adding http and port because this is the needed scheme
        if fields[2] != "":
            useragent = fields[2]
        data.append({"url": url, "ip": ip, "ua": useragent})
    return data
class MySpider(Spider):
    name = 'splash_spider'  # Name of Spider

    # notice that we don't need to define start_urls
    # just make sure to get all the urls you want to scrape inside start_requests function

    # getting all the url + ip address + useragent pairs then request them
    def start_requests(self):

        # get the file path of the csv file that contains the pairs from the settings.py
        with open(self.settings["PROXY_CSV_FILE"], mode="r") as csv_file:
           # requests is a list of dictionaries like this -> {url: str, ua: str, ip: str}
            requests = process_csv(csv_file)

        for req in requests:
            # no need to create custom middlewares  # just pass useragent using the headers param, and pass proxy using the meta param

            yield SplashRequest(url=req["url"], callback=self.parse, args={"wait": 3},
                    headers={"User-Agent": req["ua"]},
                    splash_url = req["ip"],
                    )

    # Scraping
    def parse(self, response):
        item = GameItem()
        for game in response.css("tr"):
            # Card Name
            yield {
                    'card_name':  game.css("a.card_popup::text").get(),
                    }

           next_page = response.css('table+ div a:nth-child(8)::attr("href")').get()
            if next_page is not None:
                yield response.follow(next_page, self.parse)
</code>```

UPDATE #1

SplashSpider.py

```<code>import csv
from scrapy.spiders import Spider
from scrapy_splash import SplashRequest
from ..items import GameItem

# process the csv file so the url + ip address + useragent pairs are the same as defined in the file # returns a list of dictionaries, example:
# [ {'url': 'http://www.starcitygames.com/catalog/category/Rivals%20of%20Ixalan',
#    'ip': 'http://204.152.114.244:8050',
#    'ua': "Mozilla/5.0 (BlackBerry; U; BlackBerry 9320; en-GB) AppleWebKit/534.11"},
#    ...
# ]
def process_csv(csv_file):
    data = []
    reader = csv.reader(csv_file)
    next(reader)
    for fields in reader:
        if fields[0] != "":
            url = fields[0]
        else:
            continue # skip the whole row if the url column is empty
        if fields[1] != "":
            ip = "http://" + fields[1] + ":8050" # adding http and port because this is the needed scheme
        if fields[2] != "":
            useragent = fields[2]
        data.append({"url": url, "ip": ip, "ua": useragent})
    return data

class MySpider(Spider):
    name = 'splash_spider'  # Name of Spider

    # notice that we don't need to define start_urls
    # just make sure to get all the urls you want to scrape inside start_requests function

    # getting all the url + ip address + useragent pairs then request them
    def start_requests(self):

        # get the file path of the csv file that contains the pairs from the settings.py
        with open(self.settings["PROXY_CSV_FILE"], mode="r") as csv_file:
           # requests is a list of dictionaries like this -> {url: str, ua: str, ip: str}
            requests = process_csv(csv_file)

        for req in requests:
            # no need to create custom middlewares
            # just pass useragent using the headers param, and pass proxy using the meta param

            yield SplashRequest(url=req["url"], callback=self.parse, args={"wait": 3},
                    headers={"User-Agent": req["ua"]},
                    splash_url = req["ip"],
                    )
    # Scraping
    def parse(self, response):
        item = GameItem()
        for game in response.css("tr[class^=deckdbbody]"):
            # Card Name
            item["card_name"] = game.css("a.card_popup::text").extract_first()
            item["stock"] = game.css("td[class^=deckdbbody].search_results_8::text").extract_first()
            item["price"] = game.css("td[class^=deckdbbody].search_results_9::text").extract_first()

            yield item
        next_page = response.css('#content > div:last-of-type > a[href]:last-of-type').get()
        if next_page is not None:
            yield response.follow(next_page_url, self.parse)
</code>```

UPDATE #2 (neither work correctly)

```<code>next_page = response.css('#content > div:last-of-type > a[href]:last-of-type').get()
next_page_url = next_page.xpath("@href").get()
if next_page is not None:
    yield response.follow(next_page_url, self.parse)
</code>```

```<code>next_page = response.css('#content > div:last-of-type > a[href]:last-of-type').get()
if next_page is not None:
    yield response.follow(next_page, self.parse)
</code>```

答:
next_page = response.css('table+ div a:nth-child(8)::attr("href")').get()

You for sure don't want nth-child(8), you want the last div and its last a that contains an href attribute, which is:

```<code>response.css("#content > div:last-of-type > a[href]:last-of-type')
</code>```

If you wanted to be extra diligent, you'd check the text of the matching  to ensure it contained the phrase Next

Body:
I have a scraping program I need to click the next button while scraping and I actually asked a question on here a week or so ago about how to do that that and got some good responses but the code that I got for the answers only works partially.  It will scrape page 1 and page 2 but instead of going on to page 3 it skips to that last page, page 10 and I cannot figure out why.

import csv
from scrapy.spiders import Spider
from scrapy_splash import SplashRequest
from ..items import GameItem
def process_csv(csv_file):
    data = []
    reader = csv.reader(csv_file)
    next(reader)
    for fields in reader:
        if fields[0] != "":
            url = fields[0]
        else:
            continue # skip the whole row if the url column is empty
        if fields[1] != "":
            ip = "http://" + fields[1] + ":8050" # adding http and port because this is the needed scheme
        if fields[2] != "":
            useragent = fields[2]
        data.append({"url": url, "ip": ip, "ua": useragent})
    return data
class MySpider(Spider):
    name = 'splash_spider'  # Name of Spider

    # notice that we don't need to define start_urls
    # just make sure to get all the urls you want to scrape inside start_requests function

    # getting all the url + ip address + useragent pairs then request them
    def start_requests(self):

        # get the file path of the csv file that contains the pairs from the settings.py
        with open(self.settings["PROXY_CSV_FILE"], mode="r") as csv_file:
           # requests is a list of dictionaries like this -> {url: str, ua: str, ip: str}
            requests = process_csv(csv_file)

        for req in requests:
            # no need to create custom middlewares  # just pass useragent using the headers param, and pass proxy using the meta param

            yield SplashRequest(url=req["url"], callback=self.parse, args={"wait": 3},
                    headers={"User-Agent": req["ua"]},
                    splash_url = req["ip"],
                    )

    # Scraping
    def parse(self, response):
        item = GameItem()
        for game in response.css("tr"):
            # Card Name
            yield {
                    'card_name':  game.css("a.card_popup::text").get(),
                    }

           next_page = response.css('table+ div a:nth-child(8)::attr("href")').get()
            if next_page is not None:
                yield response.follow(next_page, self.parse)

UPDATE #1

SplashSpider.py

import csv
from scrapy.spiders import Spider
from scrapy_splash import SplashRequest
from ..items import GameItem

# process the csv file so the url + ip address + useragent pairs are the same as defined in the file # returns a list of dictionaries, example:
# [ {'url': 'http://www.starcitygames.com/catalog/category/Rivals%20of%20Ixalan',
#    'ip': 'http://204.152.114.244:8050',
#    'ua': "Mozilla/5.0 (BlackBerry; U; BlackBerry 9320; en-GB) AppleWebKit/534.11"},
#    ...
# ]
def process_csv(csv_file):
    data = []
    reader = csv.reader(csv_file)
    next(reader)
    for fields in reader:
        if fields[0] != "":
            url = fields[0]
        else:
            continue # skip the whole row if the url column is empty
        if fields[1] != "":
            ip = "http://" + fields[1] + ":8050" # adding http and port because this is the needed scheme
        if fields[2] != "":
            useragent = fields[2]
        data.append({"url": url, "ip": ip, "ua": useragent})
    return data

class MySpider(Spider):
    name = 'splash_spider'  # Name of Spider

    # notice that we don't need to define start_urls
    # just make sure to get all the urls you want to scrape inside start_requests function

    # getting all the url + ip address + useragent pairs then request them
    def start_requests(self):

        # get the file path of the csv file that contains the pairs from the settings.py
        with open(self.settings["PROXY_CSV_FILE"], mode="r") as csv_file:
           # requests is a list of dictionaries like this -> {url: str, ua: str, ip: str}
            requests = process_csv(csv_file)

        for req in requests:
            # no need to create custom middlewares
            # just pass useragent using the headers param, and pass proxy using the meta param

            yield SplashRequest(url=req["url"], callback=self.parse, args={"wait": 3},
                    headers={"User-Agent": req["ua"]},
                    splash_url = req["ip"],
                    )
    # Scraping
    def parse(self, response):
        item = GameItem()
        for game in response.css("tr[class^=deckdbbody]"):
            # Card Name
            item["card_name"] = game.css("a.card_popup::text").extract_first()
            item["stock"] = game.css("td[class^=deckdbbody].search_results_8::text").extract_first()
            item["price"] = game.css("td[class^=deckdbbody].search_results_9::text").extract_first()

            yield item
        next_page = response.css('#content > div:last-of-type > a[href]:last-of-type').get()
        if next_page is not None:
            yield response.follow(next_page_url, self.parse)

UPDATE #2 (neither work correctly)

next_page = response.css('#content > div:last-of-type > a[href]:last-of-type').get()
next_page_url = next_page.xpath("@href").get()
if next_page is not None:
    yield response.follow(next_page_url, self.parse)

next_page = response.css('#content > div:last-of-type > a[href]:last-of-type').get()
if next_page is not None:
    yield response.follow(next_page, self.parse)

Body:
next_page = response.css('table+ div a:nth-child(8)::attr("href")').get()

You for sure don't want nth-child(8), you want the last div and its last a that contains an href attribute, which is:

response.css("#content > div:last-of-type > a[href]:last-of-type')

If you wanted to be extra diligent, you'd check the text of the matching <a> to ensure it contained the phrase Next


来源: stackexchange

问:
How to properly define global enum in Typescript
I cannot understand what im missing in defining enum globally.

constants.ts

enum CREEP_ROLE {
  HARVESTER = 0,
  BUILDER = 1,
}
```

<p>main.ts</p>

<pre class="lang-js prettyprint-override"><code>import './constants'

const test = CREEP_ROLE.HARVESTER;
</code>```

Here is what typescript compiler compile this code into:

```<code>var CREEP_ROLE$1;
(function (CREEP_ROLE) {
    CREEP_ROLE[CREEP_ROLE["HARVESTER"] = 0] = "HARVESTER";
    CREEP_ROLE[CREEP_ROLE["BUILDER"] = 1] = "BUILDER";
})(CREEP_ROLE$1 || (CREEP_ROLE$1 = {}));
//# sourceMappingURL=constants.js.map

const test = CREEP_ROLE.HARVESTER;
</code>```

When i run generated file, im getting ReferenceError: CREEP_ROLE is not defined. What i am missing?

my tslint:

```<code>{
  "compilerOptions": {
    "module": "esnext",
    "lib": ["esnext"],
    "target": "es2017",
    "moduleResolution": "Node",
    "outDir": "dist",
    "baseUrl": "src/",
    "sourceMap": true,
    "strict": true,
    "experimentalDecorators": true,
    "noImplicitReturns": true,
    "allowSyntheticDefaultImports": true,
    "allowUnreachableCode": false
  },
  "exclude": [
    "node_modules"
  ]
}

</code>```

答:
Export your enum:

```<code>export enum CREEP_ROLE {
    HARVESTER = 0,
    BUILDER = 1,
}
</code>```

And then import like so:

```<code>import {CREEP_ROLE} from './constants';
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I cannot understand what im missing in defining enum globally.

constants.ts

enum CREEP_ROLE {
  HARVESTER = 0,
  BUILDER = 1,
}

main.ts

import './constants'

const test = CREEP_ROLE.HARVESTER;

Here is what typescript compiler compile this code into:

var CREEP_ROLE$1;
(function (CREEP_ROLE) {
    CREEP_ROLE[CREEP_ROLE["HARVESTER"] = 0] = "HARVESTER";
    CREEP_ROLE[CREEP_ROLE["BUILDER"] = 1] = "BUILDER";
})(CREEP_ROLE$1 || (CREEP_ROLE$1 = {}));
//# sourceMappingURL=constants.js.map

const test = CREEP_ROLE.HARVESTER;

When i run generated file, im getting ReferenceError: CREEP_ROLE is not defined. What i am missing?

my tslint:

{
  "compilerOptions": {
    "module": "esnext",
    "lib": ["esnext"],
    "target": "es2017",
    "moduleResolution": "Node",
    "outDir": "dist",
    "baseUrl": "src/",
    "sourceMap": true,
    "strict": true,
    "experimentalDecorators": true,
    "noImplicitReturns": true,
    "allowSyntheticDefaultImports": true,
    "allowUnreachableCode": false
  },
  "exclude": [
    "node_modules"
  ]
}

Body:
Export your enum:

export enum CREEP_ROLE {
    HARVESTER = 0,
    BUILDER = 1,
}

And then import like so:

import {CREEP_ROLE} from './constants';


问:
Asserting an exception thrown from a mock object constructor
Assume: VS2010, .NET 4, C#, NUnit, Moq

I am new to TDD and came across this issue while working through a project.

Given the class:

```<code>public abstract class MyFileType
{
    public MyFileType(String fullPathToFile)
    {
        if (!File.Exists(fullPathToFile))
        {
            throw new FileNotFoundException();
        }

        // method continues

    }
}
</code>```

I am trying to test it using the method:

```<code>[Test]
[ExpectedException(typeof(System.IO.FileNotFoundException))]
public void MyFileType_CreationWithNonexistingPath_ExceptionThrown()
{
    String nonexistingPath = "C:\\does\\not\\exist\\file.ext";
    var mock = new Mock<MyFileType>(nonexistingPath);
}
</code>```

The test fails and NUnit reports an exception was never thrown.

I did find a section in the NUnit docs talking about asserting with exceptions, but the examples didn't seem like what I am trying to do. I am still getting started with NUnit and Moq so I may be going about this the wrong way.

UPDATE:

To help clarify why this example uses an abstract class, it is the base class of a series file types where only the loading and disposing of the data would differ between subclassed types. My initial thought was to put the logic for open/setup into a base class since it is the same for all types.

答:
If you tring to test MyFileType class, that it throws an exception if file does not exist, why you are creating mock. You code should be simple</p>

```<code>[Test]
[ExpectedException(typeof(System.IO.FileNotFoundException))]
public void MyFileType_CreationWithNonexistingPath_ExceptionThrown()
{
    // arrange
    var nonexistingPath = "C:\\does\\not\\exist\\file.ext";

    // act / assert
    var mock = new MyFileType(nonexistingPath);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Assume: VS2010, .NET 4, C#, NUnit, Moq

I am new to TDD and came across this issue while working through a project.

Given the class:

public abstract class MyFileType
{
    public MyFileType(String fullPathToFile)
    {
        if (!File.Exists(fullPathToFile))
        {
            throw new FileNotFoundException();
        }

        // method continues

    }
}

I am trying to test it using the method:

[Test]
[ExpectedException(typeof(System.IO.FileNotFoundException))]
public void MyFileType_CreationWithNonexistingPath_ExceptionThrown()
{
    String nonexistingPath = "C:\\does\\not\\exist\\file.ext";
    var mock = new Mock<MyFileType>(nonexistingPath);
}

The test fails and NUnit reports an exception was never thrown.

I did find a section in the NUnit docs talking about asserting with exceptions, but the examples didn't seem like what I am trying to do. I am still getting started with NUnit and Moq so I may be going about this the wrong way.

UPDATE:

To help clarify why this example uses an abstract class, it is the base class of a series file types where only the loading and disposing of the data would differ between subclassed types. My initial thought was to put the logic for open/setup into a base class since it is the same for all types.

Body:
If you tring to test MyFileType class, that it throws an exception if file does not exist, why you are creating mock. You code should be simple

[Test]
[ExpectedException(typeof(System.IO.FileNotFoundException))]
public void MyFileType_CreationWithNonexistingPath_ExceptionThrown()
{
    // arrange
    var nonexistingPath = "C:\\does\\not\\exist\\file.ext";

    // act / assert
    var mock = new MyFileType(nonexistingPath);
}


问:
How to get the current ProcessID in UWP?
Using .Net Framework, it can be achieved here: How to get the current ProcessID?.

But how to get current PorcessId in UWP?
System.Diagnostics does not even have Process class.

答:
As UWP allow win32 api GetCurrentProcessId, you can call it from c#. I used to call it from c++/winrt uwp project.

```<code>using System.Runtime.InteropServices;
class public xxx{
        [DllImport("Kernel32.dll", EntryPoint = "GetCurrentProcessId")]
        static extern UInt32 GetCurrentProcessId();

   public void xxx(){
            var processId = GetCurrentProcessId();
            Debug.WriteLine("my process Id:"+ processId.ToString());
   }
}
</code>```

Ps1:

Windows.System.Diagnostics.ProcessDiagnosticInfo.GetForCurrentProcess() crash sometimes in my uwp c# project(not always crash). Get exception of  "Attempted to read or write protected memory. This is often an indication that other memory is corrupt."

Ps2:

System.Diagnostics.Process.GetCurrentProcess() not exist in my uwp c# project . https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.process.getcurrentprocess?view=netframework-4.8

Body:
As UWP allow win32 api GetCurrentProcessId, you can call it from c#. I used to call it from c++/winrt uwp project.

using System.Runtime.InteropServices;
class public xxx{
        [DllImport("Kernel32.dll", EntryPoint = "GetCurrentProcessId")]
        static extern UInt32 GetCurrentProcessId();

   public void xxx(){
            var processId = GetCurrentProcessId();
            Debug.WriteLine("my process Id:"+ processId.ToString());
   }
}

Ps1:

Windows.System.Diagnostics.ProcessDiagnosticInfo.GetForCurrentProcess() crash sometimes in my uwp c# project(not always crash). Get exception of  "Attempted to read or write protected memory. This is often an indication that other memory is corrupt."

Ps2:

System.Diagnostics.Process.GetCurrentProcess() not exist in my uwp c# project . https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.process.getcurrentprocess?view=netframework-4.8


问:
How to copy and paste unique data according to date, when the dates are repeated?
I am trying to copy data from one sheet to another according to matching dates and so far I can do this but the problem is that the most recent data for a corresponding date over writes all other data for the same date.

E.G.

I want to copy data from sheet 2 column 1 (based on the date in column 2)

I want to paste this data into sheet 1 column 2 (Based on the date in column 1)

As can be seen, only the last number from sheet 2 column 1 which corresponds to the respective date is pasted into ALL corresponding dates in sheet 1 column 2.

Instead, if there are two dates, I want two different numbers( from sheet 2 column 1 ) to be pasted into sheet 1 column 2.

My original code is as follows:

```<code>Sub Macroturnip()
'
' Macroturnip Macro
'

Dim Row As Double 'row is the row variable for the destination spreadsheet
Dim i As Date
Dim x As Long 'x is the row variable for the source spreadsheet

For Row = 1 To 825

    i = Sheets("1").Cells(Row, 1)

      If i <> DateSerial(1900, 1, 0) Then
        'DateSerial(1900, 1, 0) --> this is the default for no data in the field, i.e. i want to skip these

            For x = 2 To 450

                    If Sheets("2").Cells(x, 2) = Sheets("1").Cells(Row, 1) Then
                    Sheets("2").Select
                    Cells(x, 1).Select
                    Selection.Copy
                    Sheets("1").Select
                    Cells(Row, 2).Select
                    ActiveSheet.Paste

                    End If

            Next x

     End If

Next Row

End Sub
</code>```

答:
Is good practice to avoid using variable names that are already representing something in code, i.e.: Row.

Row number should a be a integer/long type

You should declare and assign your worksheets to variables

Most code in VBA can be written without using .Select, though sometimes you might need it, this is not one of those times... and you should avoid at all cost using it in a nested loop. For ex:

Sheets("2").Select
Cells(x, 1).Select
Selection.Copy
```

<p>Can be easily rewritten as such:</p>

<pre class="lang-vb prettyprint-override"><code>Sheets("2").Cells(x, 1).Copy
</code>```

This might need some better logic, but based on your screenshots, it works:

Sub Macroturnip()
'
' Macroturnip Macro
'

Dim wsDst As Worksheet: Set wsDst = ActiveWorkbook.Sheets("1")
Dim lRowDst As Long: lRowDst = wsDst.Cells(wsDst.Rows.Count, 1).End(xlUp).Row

Dim wsSrc As Worksheet: Set wsSrc = ActiveWorkbook.Sheets("2")
Dim lRowSrc As Long: lRowSrc = wsSrc.Cells(wsSrc.Rows.Count, 1).End(xlUp).Row

Dim rngFind As Range
Dim Rs As Long, Rd As Long 'row is the row variable for the destination spreadsheet

    For Rd = 2 To lRowDst

        If wsDst.Cells(Rd, 1) <> "" Then
        'DateSerial(1900, 1, 0) --> this is the default for no data in the field, i.e. i want to skip these
            For Rs = 2 To lRowSrc
                If wsDst.Cells(Rd, 1) = wsSrc.Cells(Rs, 2) Then

                    Set rngFind = wsDst.Range("B2:B" & Rd).Find(wsSrc.Cells(Rs, 1), Lookat:=xlWhole)
                    If rngFind Is Nothing Then
                        wsDst.Cells(Rd, 2) = wsSrc.Cells(Rs, 1).Value
                        Exit For 'No need to keep checking, move on
                    End If
                    Set rngFind = Nothing
                End If
            Next Rs
        End If
    Next Rd
End Sub
```

PS: I've assumed that by Sheets("2") you actually referred to a sheet named 2, and not Sheet2 or Sheets(2) which though look similar, are not the same thing.

Body:
I am trying to copy data from one sheet to another according to matching dates and so far I can do this but the problem is that the most recent data for a corresponding date over writes all other data for the same date.

E.G.

I want to copy data from sheet 2 column 1 (based on the date in column 2)

I want to paste this data into sheet 1 column 2 (Based on the date in column 1)

As can be seen, only the last number from sheet 2 column 1 which corresponds to the respective date is pasted into ALL corresponding dates in sheet 1 column 2.

Instead, if there are two dates, I want two different numbers( from sheet 2 column 1 ) to be pasted into sheet 1 column 2.

My original code is as follows:

Sub Macroturnip()
'
' Macroturnip Macro
'

Dim Row As Double 'row is the row variable for the destination spreadsheet
Dim i As Date
Dim x As Long 'x is the row variable for the source spreadsheet

For Row = 1 To 825

    i = Sheets("1").Cells(Row, 1)

      If i <> DateSerial(1900, 1, 0) Then
        'DateSerial(1900, 1, 0) --> this is the default for no data in the field, i.e. i want to skip these

            For x = 2 To 450

                    If Sheets("2").Cells(x, 2) = Sheets("1").Cells(Row, 1) Then
                    Sheets("2").Select
                    Cells(x, 1).Select
                    Selection.Copy
                    Sheets("1").Select
                    Cells(Row, 2).Select
                    ActiveSheet.Paste

                    End If

            Next x

     End If

Next Row

End Sub

Body:
Is good practice to avoid using variable names that are already representing something in code, i.e.: Row.

Row number should a be a integer/long type

You should declare and assign your worksheets to variables

Most code in VBA can be written without using .Select, though sometimes you might need it, this is not one of those times... and you should avoid at all cost using it in a nested loop. For ex:

Sheets("2").Select
Cells(x, 1).Select
Selection.Copy

Can be easily rewritten as such:

Sheets("2").Cells(x, 1).Copy

This might need some better logic, but based on your screenshots, it works:

Sub Macroturnip()
'
' Macroturnip Macro
'

Dim wsDst As Worksheet: Set wsDst = ActiveWorkbook.Sheets("1")
Dim lRowDst As Long: lRowDst = wsDst.Cells(wsDst.Rows.Count, 1).End(xlUp).Row

Dim wsSrc As Worksheet: Set wsSrc = ActiveWorkbook.Sheets("2")
Dim lRowSrc As Long: lRowSrc = wsSrc.Cells(wsSrc.Rows.Count, 1).End(xlUp).Row

Dim rngFind As Range
Dim Rs As Long, Rd As Long 'row is the row variable for the destination spreadsheet

    For Rd = 2 To lRowDst

        If wsDst.Cells(Rd, 1) <> "" Then
        'DateSerial(1900, 1, 0) --> this is the default for no data in the field, i.e. i want to skip these
            For Rs = 2 To lRowSrc
                If wsDst.Cells(Rd, 1) = wsSrc.Cells(Rs, 2) Then

                    Set rngFind = wsDst.Range("B2:B" & Rd).Find(wsSrc.Cells(Rs, 1), Lookat:=xlWhole)
                    If rngFind Is Nothing Then
                        wsDst.Cells(Rd, 2) = wsSrc.Cells(Rs, 1).Value
                        Exit For 'No need to keep checking, move on
                    End If
                    Set rngFind = Nothing
                End If
            Next Rs
        End If
    Next Rd
End Sub

PS: I've assumed that by Sheets("2") you actually referred to a sheet named 2, and not Sheet2 or Sheets(2) which though look similar, are not the same thing.


问:
Angular focus on input while clicking an element
I have attached the stackblitz below

https://stackblitz.com/edit/angular-dgx3pe

What i am trying to achieve is while clicking on the label element it should focus on the input.Hence the input:focus  class gets activated.What I belive is that it can be achievable through javascript/jquery.But i prefer the angular way to achieve this.

In Brief,these are the two things i am trying to do,

Make focus on the input element when label is clicked.

When the focus is changed to another input element and if the previous element is not empty(If some value is typed in).The label should maintain its position in the top.

HTML

```<code><input class="input" type="text">
<label class="label">Name</label>

<div>
<input class="input" type="text">
<label class="label">Name</label>
</div>
</code>```

CSS

p {
  font-family: Lato;
}
.input
{
  border:none;
  border-bottom:1px solid grey;
  outline:none;
   margin-top:20%;
}
.input:focus
{
    border-bottom:1px solid orange;
}
.label
{
  position:relative;
 left:-170px;
}
.input:focus + .label
{
   bottom:20px;
}
```

答:
I'm looking at this from the perspective of making a more "Angular" solution for your conditional style request.  To that end, you should focus on rolling your input/label combination into a custom input component.  Once you've created a component with your original elements as a starting template you can enact the following more effectively.

Basic strategy is to conditionally apply your styles using Angular's [class] property binding or [NgStyle] directives.

Do a ViewChild query on the template for the input element

Add an event listener on the input element in the template

Whenever a keyup event is detected, it will trigger of check of your <input> field value and update a class property representing whether the field is empty

Change detection will trigger, and the [NgClass] or [class] bindings will trigger updates to the element's class

```<code>//component.ts

import { Component, Input, ViewChild, ElementRef } from '@angular/core'

@Component({
  selector: 'app-input',
  styleUrls: ['./input.component.css'],
  templateUrl: './input.component.html'
})

export class InputComponent{
  @Input() labelName: string = "Your Label Here"
  @ViewChild("input") myInput:ElementRef<any> //ViewChild query

  empty: Boolean = true; // this property will track whether input value is truthy

  isEmpty(){ // attached to keyup event on input element in your template file

   if (this.myInput.nativeElement.value){
      this.empty = false;
    } else{
      this.empty = true;
    }
  }

  styles(){ // attached to the [ngClass] directive binding on input element in template file
    return {
      'empty': this.empty ? true: false,
      'not-empty': this.empty ? false: true
    }
  }

}

</code>```

```<code>//component.html with [ngClass] directive

<label for="my-input" #label> {{ labelName }}
<input type="text" id="my-input" [ngClass]="styles()" (keyup) = "isEmpty()" #input>

</code>```

```<code>//component.html with [style] property binding
// in this instance, empty is a reference to the property in the .ts file

<label for="my-input" #label> {{ labelName }}
<input type="text" id="my-input" [class.empty]="empty" #input>
</code>```

Body:
I have attached the stackblitz below

https://stackblitz.com/edit/angular-dgx3pe

What i am trying to achieve is while clicking on the label element it should focus on the input.Hence the input:focus  class gets activated.What I belive is that it can be achievable through javascript/jquery.But i prefer the angular way to achieve this.

In Brief,these are the two things i am trying to do,

Make focus on the input element when label is clicked.

When the focus is changed to another input element and if the previous element is not empty(If some value is typed in).The label should maintain its position in the top.

HTML

<input class="input" type="text">
Name

<input class="input" type="text">
Name

CSS

p {
  font-family: Lato;
}
.input
{
  border:none;
  border-bottom:1px solid grey;
  outline:none;
   margin-top:20%;
}
.input:focus
{
    border-bottom:1px solid orange;
}
.label
{
  position:relative;
 left:-170px;
}
.input:focus + .label
{
   bottom:20px;
}

Body:
I'm looking at this from the perspective of making a more "Angular" solution for your conditional style request.  To that end, you should focus on rolling your input/label combination into a custom input component.  Once you've created a component with your original elements as a starting template you can enact the following more effectively.

Basic strategy is to conditionally apply your styles using Angular's [class] property binding or [NgStyle] directives.

Do a ViewChild query on the template for the input element

Add an event listener on the input element in the template

Whenever a keyup event is detected, it will trigger of check of your <input> field value and update a class property representing whether the field is empty

Change detection will trigger, and the [NgClass] or [class] bindings will trigger updates to the element's class

//component.ts

import { Component, Input, ViewChild, ElementRef } from '@angular/core'

@Component({
  selector: 'app-input',
  styleUrls: ['./input.component.css'],
  templateUrl: './input.component.html'
})

export class InputComponent{
  @Input() labelName: string = "Your Label Here"
  @ViewChild("input") myInput:ElementRef<any> //ViewChild query

  empty: Boolean = true; // this property will track whether input value is truthy

  isEmpty(){ // attached to keyup event on input element in your template file

   if (this.myInput.nativeElement.value){
      this.empty = false;
    } else{
      this.empty = true;
    }
  }

  styles(){ // attached to the [ngClass] directive binding on input element in template file
    return {
      'empty': this.empty ? true: false,
      'not-empty': this.empty ? false: true
    }
  }

}

//component.html with [ngClass] directive

<label for="my-input" #label> {{ labelName }}
<input type="text" id="my-input" [ngClass]="styles()" (keyup) = "isEmpty()" #input>

//component.html with [style] property binding
// in this instance, empty is a reference to the property in the .ts file

<label for="my-input" #label> {{ labelName }}
<input type="text" id="my-input" [class.empty]="empty" #input>


问:
Basic C# question if - else
I was wondering if someone could tell me if this sample is correct please.
Please ignore the if statement i wrote it for demonstration purposes only.

basically what I want to know is, if I need to throw an exception in my else, is it right to have it return false then thrown an exception, like follows:

```<code>public bool test(Int j)
{
    if(!TestOnJThatcanThrowOutOfMemoryException E)
    {
        return true;
    }
    else
    {
        return false;
        throw new OutOfMemoryException();
    }
}
</code>```

OR - should I throw exception then return false outside else statement like this:

```<code>public bool test(Int j)
{
    if(!TestOnJThatcanThrowOutOfMemoryException E)
    {
        return true;
    }
    else
    {
        throw new OutOfMemoryException();
    }
    return false;
}
</code>```

答:
In both cases, as is, only the first of the two will execute. Both return and throw cause execution to leave the function, so neither is technically correct.

In the first case, it will return, and the throw will never be called. In the second, the opposite is true (for the else block).

If you want an exception, throw it. Don't bother putting a return false anywhere.

Title: Basic C# question if - else

Body:
I was wondering if someone could tell me if this sample is correct please.
Please ignore the if statement i wrote it for demonstration purposes only.

basically what I want to know is, if I need to throw an exception in my else, is it right to have it return false then thrown an exception, like follows:

public bool test(Int j)
{
    if(!TestOnJThatcanThrowOutOfMemoryException E)
    {
        return true;
    }
    else
    {
        return false;
        throw new OutOfMemoryException();
    }
}

OR - should I throw exception then return false outside else statement like this:

public bool test(Int j)
{
    if(!TestOnJThatcanThrowOutOfMemoryException E)
    {
        return true;
    }
    else
    {
        throw new OutOfMemoryException();
    }
    return false;
}


问:
finding the local and global efficiency of a graph using networkx
I am trying to find the local and global efficiency of a graph using networkx. I have a weighted graph where the weights of the links are greater than 0. So, the adjacency matrix (adj) is weighted. I tried the following code

```<code>import networkx as nx
G=nx. Graph(adj)      # adj is the weighted adjacency matrix
eff=nx.global_efficiency(G)
</code>```

However, I am getting the follwoing error:
AttributeError: 'module' object has no attribute 'global_efficiency'

Can anyone please help me solve this issue?

答:
I solved the issue. It was due to the older version of networkx that I was using. I was able to successfully run the above code after upgrading the networkx version.

Thank you.

Body:
I am trying to find the local and global efficiency of a graph using networkx. I have a weighted graph where the weights of the links are greater than 0. So, the adjacency matrix (adj) is weighted. I tried the following code

import networkx as nx
G=nx. Graph(adj)      # adj is the weighted adjacency matrix
eff=nx.global_efficiency(G)

However, I am getting the follwoing error:
AttributeError: 'module' object has no attribute 'global_efficiency'

Can anyone please help me solve this issue?


问:
Flask Mail does not send email
I am trying to send a reset password email using flask-mail. The code executes without errors but I didn't receive any email.

I tried the following:

adding those line to the app.config in the init.py file:

app.config['MAIL_SUPPRESS_SEND'] = False
app.config['MAIL_DEBUG'] = True
app.config['DEBUG'] = True
app.config['MAIL_FAIL_SILENTLY'] = False
app.config['TESTING'] = False
```

<ol start="2">
<li>Changing the (Less secure app access) setting in Gmail to be on.</li>
</ol>

<p>Here are some lines of my code:</p>

<p>In <strong>init</strong>.py file:</p>

<pre class="lang-py prettyprint-override"><code>import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
from flask_mail import Mail

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
db = SQLAlchemy(app)
bcrypt = Bcrypt(app)
login_manager = LoginManager(app)
login_manager.login_view = 'login'
login_manager.login_message_category = 'info'

app.config['MAIL_SERVER'] = 'smtp.gmail.com'
app.config['MAIL_PORT'] = 587
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USERNAME'] = os.environ.get('EMAIL_USER')
app.config['MAIL_PASSWORD'] = os.environ.get('EMAIL_PASS')
app.config['MAIL_SUPPRESS_SEND'] = False
app.config['MAIL_DEBUG'] = True
app.config['DEBUG'] = True
app.config['MAIL_FAIL_SILENTLY'] = False
app.config['TESTING'] = False
mail = Mail(app)
</code>```

In routes.py file:

def send_reset_email(user):
    token = user.get_reset_token()
    msg = Message(subject='Password Reset Request', sender='noreply@demo.com', recipients=[user.email])

    msg.body = f''' To reset your password, visit the following link!:
{url_for('reset_token', token=token, _external=True)}

If you did not make this request then simply ignore this email and no changes will be made
'''

@app.route("/reset_password", methods=['GET', 'POST'])
def reset_request():
    if current_user.is_authenticated:
        return redirect(url_for('home'))
    form = RequestResetForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        send_reset_email(user)
        flash('An email has been sent with instructions to reset your password.', 'info')
        return redirect(url_for('login'))
    return render_template('reset_request.html', title='Reset Password', form=form)
```

I expected to receive the reset email but I didn't and it fails silently.

答:
1) In add to init file

```<code>app.config['MAIL_SERVER'] = 'smtp.gmail.com'
app.config['MAIL_PORT'] = 587
app.config['MAIL_USERNAME'] = os.environ.get('EMAIL_USER')
app.config['MAIL_PASSWORD'] = os.environ.get('EMAIL_PASS')
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_TLS'] = True
</code>```

2) In route.py file

need for:

```<code>mail.send(msg)
</code>```

Title: Flask Mail does not send email

Body:
I am trying to send a reset password email using flask-mail. The code executes without errors but I didn't receive any email.

I tried the following:

adding those line to the app.config in the init.py file:

app.config['MAIL_SUPPRESS_SEND'] = False
app.config['MAIL_DEBUG'] = True
app.config['DEBUG'] = True
app.config['MAIL_FAIL_SILENTLY'] = False
app.config['TESTING'] = False

Changing the (Less secure app access) setting in Gmail to be on.

Here are some lines of my code:

In init.py file:

import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
from flask_mail import Mail

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
db = SQLAlchemy(app)
bcrypt = Bcrypt(app)
login_manager = LoginManager(app)
login_manager.login_view = 'login'
login_manager.login_message_category = 'info'

app.config['MAIL_SERVER'] = 'smtp.gmail.com'
app.config['MAIL_PORT'] = 587
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USERNAME'] = os.environ.get('EMAIL_USER')
app.config['MAIL_PASSWORD'] = os.environ.get('EMAIL_PASS')
app.config['MAIL_SUPPRESS_SEND'] = False
app.config['MAIL_DEBUG'] = True
app.config['DEBUG'] = True
app.config['MAIL_FAIL_SILENTLY'] = False
app.config['TESTING'] = False
mail = Mail(app)

In routes.py file:

def send_reset_email(user):
    token = user.get_reset_token()
    msg = Message(subject='Password Reset Request', sender='noreply@demo.com', recipients=[user.email])

    msg.body = f''' To reset your password, visit the following link!:
{url_for('reset_token', token=token, _external=True)}

If you did not make this request then simply ignore this email and no changes will be made
'''

@app.route("/reset_password", methods=['GET', 'POST'])
def reset_request():
    if current_user.is_authenticated:
        return redirect(url_for('home'))
    form = RequestResetForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        send_reset_email(user)
        flash('An email has been sent with instructions to reset your password.', 'info')
        return redirect(url_for('login'))
    return render_template('reset_request.html', title='Reset Password', form=form)

I expected to receive the reset email but I didn't and it fails silently.

Body:
1) In add to init file

app.config['MAIL_SERVER'] = 'smtp.gmail.com'
app.config['MAIL_PORT'] = 587
app.config['MAIL_USERNAME'] = os.environ.get('EMAIL_USER')
app.config['MAIL_PASSWORD'] = os.environ.get('EMAIL_PASS')
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_TLS'] = True

2) In route.py file

need for:

mail.send(msg)


问:
how to align multiple line text as the column of the table
I have to display text as follows(please notice that the month should be properly aligned with the months of other two rows, time should be properly aligned with the time of other two rows and so is the date as follows):

and all these values are coming from two way data binding inside a div in an angular 7 project as follows:

```<code><div *ngFor="let date of dates">
{{date.month}} {{date.day}} {{date.time}}
<div>
</code>```

please help me to display these values in the exact same style style.

答:
Stacklitz solution

 Follow below stacklitz code for solution

css

```<code>.wrapper{
    display: flex;
    justify-content: space-between;
}

.colm{
  min-width:100px;
}
</code>```

component

```<code><div class=" row wrapper" *ngFor="let date of dates">
 <div  class="colm">{{date.month}}</div>
 <div  class="colm">{{date.day}} </div>
 <div  class="colm">{{date.time}}</div>
<div>
</code>```

Body:
I have to display text as follows(please notice that the month should be properly aligned with the months of other two rows, time should be properly aligned with the time of other two rows and so is the date as follows):

and all these values are coming from two way data binding inside a div in an angular 7 project as follows:

{{date.month}} {{date.day}} {{date.time}}

please help me to display these values in the exact same style style.

Body:
Stacklitz solution

 Follow below stacklitz code for solution

css

.wrapper{
    display: flex;
    justify-content: space-between;
}

.colm{
  min-width:100px;
}

component

<div class=" row wrapper" *ngFor="let date of dates">
 <div  class="colm">{{date.month}}</div>
 <div  class="colm">{{date.day}} </div>
 <div  class="colm">{{date.time}}</div>
<div>


问:
Can source string be converted to destination string?
Is there a sequence of transformation steps to convert given source string to destination string?

Note: At every step, one character can be transformed (replacement should be a character between 'A'-'Z') and all the occurrences of that character have to be transformed.
Examples are given below.

```<code>Source: "ABA"
Dest: "BAB"
Output: True
Explanation: ABA -> A**C**A -> **B**C**B** -> B**A**B

Source: "AA"
Dest: "BC"
Output: False
Explanation: AA -> BB
</code>```

I think HashMap works. But is there another Data Structure where I don't go about comparing Character by Character?

答:
You basically have to check that in both the strings, how many characters are repeated how many times. Kindly check whether the below logic works

```<code> 1. Declare two arrays of size equal to the length of the string (suppose N). (The length
    of both the strings must be equal first of all). This array stores the number of
    characters which are repeated once,twice,thrice...N times

 2. Traverse the strings and calculate the frequency of each character. Sorting the
    strings beforehand might help.

 3. On getting the frequency of one character in a particular string, update the array
    corresponding to that string.

 4. Set array[newly found frequency] += 1;

 5. Repeat steps 3-4 for both the strings. After this is done for both the strings, we
    have two arrays containing the information about how many characters are repeated how
    many times in both the strings.

 6. Next step is to match both the arrays. If they match return True else False.
</code>```

I will explain the above steps with your example:

```<code>Source: ABA
Dest: BAB

Arrays would be: arr1[3]={0,0,0} and arr2[3]={0,0,0}

(storing nummber of characters with frequency n in arr[n-1])

In string 1: Characters with 2 repetitions: 1 (A) so- arr1[2-1]+=1;
             Characters with 1 repetition: 1 (B)  so- arr1[1-1]+=1;

arr1= {1,1,0}

In string 2: Characters with 2 repetitions: 1 (B) so- arr2[2-1]+=1;
             Characters with 1 repetition: 1 (A)  so- arr2[1-1]+=1;

arr2= {1,1,0}

As arr1 and arr2 match, the strings are convertible.
</code>```

Hope this helps :)

Body:
Is there a sequence of transformation steps to convert given source string to destination string?

Note: At every step, one character can be transformed (replacement should be a character between 'A'-'Z') and all the occurrences of that character have to be transformed.
Examples are given below.

Source: "ABA"
Dest: "BAB"
Output: True
Explanation: ABA -> A**C**A -> **B**C**B** -> B**A**B

Source: "AA"
Dest: "BC"
Output: False
Explanation: AA -> BB

I think HashMap works. But is there another Data Structure where I don't go about comparing Character by Character?

Body:
You basically have to check that in both the strings, how many characters are repeated how many times. Kindly check whether the below logic works

 1. Declare two arrays of size equal to the length of the string (suppose N). (The length
    of both the strings must be equal first of all). This array stores the number of
    characters which are repeated once,twice,thrice...N times

 2. Traverse the strings and calculate the frequency of each character. Sorting the
    strings beforehand might help.

 3. On getting the frequency of one character in a particular string, update the array
    corresponding to that string.

 4. Set array[newly found frequency] += 1;

 5. Repeat steps 3-4 for both the strings. After this is done for both the strings, we
    have two arrays containing the information about how many characters are repeated how
    many times in both the strings.

 6. Next step is to match both the arrays. If they match return True else False.

I will explain the above steps with your example:

Source: ABA
Dest: BAB

Arrays would be: arr1[3]={0,0,0} and arr2[3]={0,0,0}

(storing nummber of characters with frequency n in arr[n-1])

In string 1: Characters with 2 repetitions: 1 (A) so- arr1[2-1]+=1;
             Characters with 1 repetition: 1 (B)  so- arr1[1-1]+=1;

arr1= {1,1,0}

In string 2: Characters with 2 repetitions: 1 (B) so- arr2[2-1]+=1;
             Characters with 1 repetition: 1 (A)  so- arr2[1-1]+=1;

arr2= {1,1,0}

As arr1 and arr2 match, the strings are convertible.

Hope this helps :)


问:
How can I do a UML Schema from a JSON file?
Hello I have this JSON file :

```<code>{
    "Hello": "",
    "Olá": [
        {
            "Hour": "00:04:35",
            "hotel": [""],
        }
    ]
    "Ciao" : [
        {
            "Hour": "02:36:52"
        }
    ]
}
</code>```

And actually I am trying to convert this JSON file to an UML file.

Could you help me please ? :)

I thought of this :

Solution

答:
You may want to take a look at JSONDiscoverer http://som-research.uoc.edu/tools/jsonDiscoverer/#/ </p>

<p>(the site includes also the technical details on how the UML model is created)</p>

Body:
Hello I have this JSON file :

{
    "Hello": "",
    "Olá": [
        {
            "Hour": "00:04:35",
            "hotel": [""],
        }
    ]
    "Ciao" : [
        {
            "Hour": "02:36:52"
        }
    ]
}

And actually I am trying to convert this JSON file to an UML file.

Could you help me please ? :)

I thought of this :

Solution

Body:
You may want to take a look at JSONDiscoverer http://som-research.uoc.edu/tools/jsonDiscoverer/#/

(the site includes also the technical details on how the UML model is created)


问:
How do I cast this using Swift?
I am working on an app where I'm trying to display VNClassificationObservation type onto the navigation bar title when I take a picture of an item. But I am encountering a problem of type casting. It shows the error:

"Cast from 'VNClassificationObservation?' to unrelated type 'String'
  always fails".

Please point me to the right direction.

let request = VNCoreMLRequest(model: model) { (request, error) in
    guard let results = request.results as? [VNClassificationObservation] else {
                fatalError("Request failed.")
            }
    let firstResult = results.first as? String
    self.navigationItem.title = firstResult
}
```

I expect the output to be printed out correctly onto the navigation title without any error.

答:
Use</p>

```<code>let firstResult = results.first.identifier
</code>```

Title: How do I cast this using Swift?

Body:
I am working on an app where I'm trying to display VNClassificationObservation type onto the navigation bar title when I take a picture of an item. But I am encountering a problem of type casting. It shows the error:

"Cast from 'VNClassificationObservation?' to unrelated type 'String'
  always fails".

Please point me to the right direction.

let request = VNCoreMLRequest(model: model) { (request, error) in
    guard let results = request.results as? [VNClassificationObservation] else {
                fatalError("Request failed.")
            }
    let firstResult = results.first as? String
    self.navigationItem.title = firstResult
}

I expect the output to be printed out correctly onto the navigation title without any error.

Body:
Use

let firstResult = results.first.identifier


答:
The first example will never throw the exception as the return false ends the logic flow.

The second example the "return false;" will never be hit as either the return true; statement will be executed or the exception will be thrown.

Title: Basic C# question if - else


问:
Split bash script into separate commands and run them them one-by-one
I want to be able to run a bash shell script from Python (using something like subprocess.Popen), but display on my GUI the command that will be executed along with the output live as it comes in stdout and stderr. The GUI should show Input (newline) Output (newline) Input and so on. I am able to currently implement it for one-line bash commands, but I need a more sophisticated parser for multi-line commands. Here is my code which only works for simple one-line commands in bash.

test.sh:

```<code>ping -c 2 www.google.com

if [ "abc" = "ghi" ]; then
    echo expression evaluated as true
else
    echo expression evaluated as false
fi
</code>```

My python file:

```<code>with open("test.sh", "r") as script:
    for line in script:
        if not line.strip().startswith('#') and not line.strip() == "":
            print("Debug: Running " + line.strip() + " ...")
            proc = subprocess.Popen(shlex.split(line), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            while True:
                output = str(proc.stdout.readline().strip().decode()) + ""
                err = str(proc.stderr.readline().strip().decode()) + ""
                if output == '' and proc.poll() is not None:
                    print("Debug: Command completed...")
                    time.sleep(1)
                    break
                if output:
                    # Code for updating a Gtk TextView buffer
                    GLib.idle_add(self.updateConsoleText, output + "\n")
                if err:
                    # Code for updating a Gtk TextView buffer
                    GLib.idle_add(self.updateConsoleText, err + "\n")
</code>```

As expected, it does not work with multi-line code that involves if-else, loops, heredocs, etc. I am looking for a bash parser that at least recognises when a command ends and can split a bash script into separate commands in such cases where multi-line commands are used.

Do you think you could help me find such a library/tool?

答:
You can use the trap command.

Here a little example to demonstrate the concept:

```<code>#!/bin/bash

# redirect stderr to a logfile
exec 2>/tmp/test.log

# print commands and arguments at execution
set -x

# set trap for every step, sleep one second.
# "sleep 1" could be every bash command
trap "sleep 1" DEBUG

echo -n "Name: "; read -r name
echo -n "Age: "; read -r age
echo "$name is $age years old"
</code>```

Parallel to the run of this script you can use tail -f /tmp/test.log to track the call of the commands and their parameters.

Body:
I want to be able to run a bash shell script from Python (using something like subprocess.Popen), but display on my GUI the command that will be executed along with the output live as it comes in stdout and stderr. The GUI should show Input (newline) Output (newline) Input and so on. I am able to currently implement it for one-line bash commands, but I need a more sophisticated parser for multi-line commands. Here is my code which only works for simple one-line commands in bash.

test.sh:

ping -c 2 www.google.com

if [ "abc" = "ghi" ]; then
    echo expression evaluated as true
else
    echo expression evaluated as false
fi

My python file:

with open("test.sh", "r") as script:
    for line in script:
        if not line.strip().startswith('#') and not line.strip() == "":
            print("Debug: Running " + line.strip() + " ...")
            proc = subprocess.Popen(shlex.split(line), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            while True:
                output = str(proc.stdout.readline().strip().decode()) + ""
                err = str(proc.stderr.readline().strip().decode()) + ""
                if output == '' and proc.poll() is not None:
                    print("Debug: Command completed...")
                    time.sleep(1)
                    break
                if output:
                    # Code for updating a Gtk TextView buffer
                    GLib.idle_add(self.updateConsoleText, output + "\n")
                if err:
                    # Code for updating a Gtk TextView buffer
                    GLib.idle_add(self.updateConsoleText, err + "\n")

As expected, it does not work with multi-line code that involves if-else, loops, heredocs, etc. I am looking for a bash parser that at least recognises when a command ends and can split a bash script into separate commands in such cases where multi-line commands are used.

Do you think you could help me find such a library/tool?

Body:
You can use the trap command.

Here a little example to demonstrate the concept:

#!/bin/bash

# redirect stderr to a logfile
exec 2>/tmp/test.log

# print commands and arguments at execution
set -x

# set trap for every step, sleep one second.
# "sleep 1" could be every bash command
trap "sleep 1" DEBUG

echo -n "Name: "; read -r name
echo -n "Age: "; read -r age
echo "$name is $age years old"

Parallel to the run of this script you can use tail -f /tmp/test.log to track the call of the commands and their parameters.


问:
Directory listing fails in FileZilla
I am trying to connect to a FTP server with Filezilla. It was working when I was using broadband but when I use my college internet it says:

```<code>Error:  Connection timed out
Error:  Failed to retrieve directory listing
</code>```

I tried both passive and active mode but all in vain. It connects but fails to give directory listing.

Below is the complete log for active mode

```<code>Status: Resolving address of where2service.com
Status: Connecting to 166.62.2.1:21...
Status: Connection established, waiting for welcome message...
Response:   220---------- Welcome to Pure-FTPd [privsep] [TLS] ----------
Response:   220-You are user number 22 of 500 allowed.
Response:   220-Local time is now 05:09. Server port: 21.
Response:   220-This is a private system - No anonymous login
Response:   220 You will be disconnected after 3 minutes of inactivity.
Command:    USER where2service
Response:   331 User where2service OK. Password required
Command:    PASS ***********
Response:   230 OK. Current restricted directory is /
Status: Server does not support non-ASCII characters.
Status: Connected
Status: Retrieving directory listing...
Command:    PWD
Response:   257 "/" is your current location
Command:    TYPE I
Response:   200 TYPE is now 8-bit binary
Command:    PORT 192,168,126,200,228,90
Response:   200 Port command successful.
Command:    MLSD
Response:   150 Accepted data connection
Response:   226-Options: -a -l
Response:   226 18 matches total
Error:  Connection timed out
</code>```

Below is the log for passive mode:

```<code>Status: Resolving address of where2service.com
Status: Connecting to 166.62.2.1:21...
Status: Connection established, waiting for welcome message...
Response:   220---------- Welcome to Pure-FTPd [privsep] [TLS] ----------
Response:   220-You are user number 20 of 500 allowed.
Response:   220-Local time is now 05:13. Server port: 21.
Response:   220-This is a private system - No anonymous login
Response:   220 You will be disconnected after 3 minutes of inactivity.
Command:    USER where2service
Response:   331 User where2service OK. Password required
Command:    PASS ***********
Response:   230 OK. Current restricted directory is /
Status: Server does not support non-ASCII characters.
Status: Connected
Status: Retrieving directory listing...
Command:    PWD
Response:   257 "/" is your current location
Command:    TYPE I
Response:   200 TYPE is now 8-bit binary
Command:    PASV
Response:   227 Entering Passive Mode (166,62,2,1,174,209)
Command:    MLSD
Response:   150 Accepted data connection
Response:   226-Options: -a -l
Response:   226 18 matches total
Error:  Connection timed out
Error:  Failed to retrieve directory listing
</code>```

答:
When i connect to my hosting ftp server, i got below error.

Status: Connection established, waiting for welcome message...
Status: Initializing TLS...
Status: Verifying certificate...
Status: TLS connection established.
Status: Logged in
Status: Retrieving directory listing...
Command: PWD Response: 257 "/" is your current location
Command: TYPE I Response: 200 TYPE is now 8-bit binary
Command: PASV
Response: 227 Entering Passive Mode (138,128,162,194,117,133)
Command: MLSD Error: Connection timed out after 20 seconds of inactivity Error: Failed to retrieve directory listing

This is the correct path for solve above question. I am using filezilla as my ftp client application.

1) Click on “File” menu and click on top of the “Site Manager” icon.
2) In encryption section choose “only use plain FTP” from drop down.
3) Also change logon type to "Normal".

Title: Directory listing fails in FileZilla

Body:
I am trying to connect to a FTP server with Filezilla. It was working when I was using broadband but when I use my college internet it says:

Error:  Connection timed out
Error:  Failed to retrieve directory listing

I tried both passive and active mode but all in vain. It connects but fails to give directory listing.

Below is the complete log for active mode

Status: Resolving address of where2service.com
Status: Connecting to 166.62.2.1:21...
Status: Connection established, waiting for welcome message...
Response:   220---------- Welcome to Pure-FTPd [privsep] [TLS] ----------
Response:   220-You are user number 22 of 500 allowed.
Response:   220-Local time is now 05:09. Server port: 21.
Response:   220-This is a private system - No anonymous login
Response:   220 You will be disconnected after 3 minutes of inactivity.
Command:    USER where2service
Response:   331 User where2service OK. Password required
Command:    PASS ***********
Response:   230 OK. Current restricted directory is /
Status: Server does not support non-ASCII characters.
Status: Connected
Status: Retrieving directory listing...
Command:    PWD
Response:   257 "/" is your current location
Command:    TYPE I
Response:   200 TYPE is now 8-bit binary
Command:    PORT 192,168,126,200,228,90
Response:   200 Port command successful.
Command:    MLSD
Response:   150 Accepted data connection
Response:   226-Options: -a -l
Response:   226 18 matches total
Error:  Connection timed out

Below is the log for passive mode:

Status: Resolving address of where2service.com
Status: Connecting to 166.62.2.1:21...
Status: Connection established, waiting for welcome message...
Response:   220---------- Welcome to Pure-FTPd [privsep] [TLS] ----------
Response:   220-You are user number 20 of 500 allowed.
Response:   220-Local time is now 05:13. Server port: 21.
Response:   220-This is a private system - No anonymous login
Response:   220 You will be disconnected after 3 minutes of inactivity.
Command:    USER where2service
Response:   331 User where2service OK. Password required
Command:    PASS ***********
Response:   230 OK. Current restricted directory is /
Status: Server does not support non-ASCII characters.
Status: Connected
Status: Retrieving directory listing...
Command:    PWD
Response:   257 "/" is your current location
Command:    TYPE I
Response:   200 TYPE is now 8-bit binary
Command:    PASV
Response:   227 Entering Passive Mode (166,62,2,1,174,209)
Command:    MLSD
Response:   150 Accepted data connection
Response:   226-Options: -a -l
Response:   226 18 matches total
Error:  Connection timed out
Error:  Failed to retrieve directory listing


问:
How to change the text background of ListView item
I'm implementing a ListView with ArrayAdapter. Whenever any ListView item is clicked, I'd like the text color of the item to be changed and also saved in SharedPreference. I'm a beginner I don't know how to implement it.

Please help me to achieve this goal. I tried many sources but the problem couldn't be solved.

Here is my code.

```<code>public class ALLVERSE extends AppCompatActivity  implements NavigationView.OnNavigationItemSelectedListener {
    private ListView mylistview;
    private ArrayList<String>versenumber;
    private ArrayList<String>verselist;
    private ArrayList<String>id;
    private  ArrayList<String>refernce;
    private DatabaseHelper mDBHelper;
    private SQLiteDatabase mDb;
    private int booknumber;
    private  int chapternumber;
    private  String bookname;
    private TextView booknametitle;
    private  FullverseAdopter fullverseAdopter;

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

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        booknametitle=findViewById(R.id.bookname);

        Intent mIntent = getIntent();
        booknumber = mIntent.getIntExtra("Boooknumber",0);
        chapternumber= mIntent.getIntExtra("Chapternumber", 0);
        bookname=mIntent.getStringExtra("Bookname");

        booknametitle.setText(bookname.toString() +"   "+  chapternumber);

        //Toast.makeText(this, ""+bookname, Toast.LENGTH_SHORT).show();
        setSupportActionBar(toolbar);
        toolbar.setTitle("ALL VERSE");

        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        setData();

        mylistview=findViewById(R.id.mylistview);

        fullverseAdopter=new FullverseAdopter(ALLVERSE.this,R.layout.versedisplayrow,versenumber,verselist,refernce,id);

        mylistview.setAdapter(fullverseAdopter);

        mylistview.setOnItemClickListener(new AdapterView.OnItemClickListener(){

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Toast.makeText(ALLVERSE.this, "i am cliked", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // handle arrow click here
        if (item.getItemId() == android.R.id.home) {
            onBackPressed();
        }
        return super.onOptionsItemSelected(item);
    }

    private void setData() {
        versenumber=new ArrayList<>();
        verselist=new ArrayList<>();
        refernce=new ArrayList<>();
        id=new ArrayList<>();

        mDBHelper = new DatabaseHelper(this);
        mDb = mDBHelper.getReadableDatabase();
        Cursor cursor = mDb.rawQuery("SELECT id, v, t from t_kjv where b="+booknumber+" AND c="+chapternumber+";", new String[]{});
        if(cursor!=null && cursor.getCount() > 0)
        { if (cursor.moveToFirst())
        {
            do {
                id.add(cursor.getString(0));
                versenumber.add(cursor.getString(1));
                verselist.add(cursor.getString(2));
                refernce.add(bookname+" "+chapternumber);
            }
            while (cursor.moveToNext());
        }
        }
    }

    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        Fragment fragment;
        int id = item.getItemId();
        if (id == R.id.home) {
            Intent intent=new Intent(this,MainActivity.class);
            startActivity(intent);

        } else if (id == R.id.favoruite)
        { Intent intent=new Intent(this,Favourite.class);
            startActivity(intent);
        }  else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}
</code>```

My adapter class

```<code>public class FullverseAdopter extends ArrayAdapter<String> {
    private ALLVERSE activity;
    private List<String> versenumber;
    private List<String>verseid;
    private List<String> verselist;
    private List<String> refernce;
    TextToSpeech textToSpeech;
    private DatabaseHelper mDBHelper;
    private SQLiteDatabase mDb;
    private  boolean ischeckd;
    String My_PREF="MY_PREF";

    public  String ex="switch";

    //check for availabe language
    int result;

    public FullverseAdopter(ALLVERSE context, int resource, List<String> versenumber, List<String> verselist, List<String> refernce, List<String>verseid) {
        super(context, resource, versenumber);
        this.activity = context;
        this.versenumber = versenumber;
        this.verselist = verselist;
        this.refernce = refernce;
        this.verseid=verseid;
    }

    @Override
    public int getCount() {
        return versenumber.size();
    }

    @Override
    public String getItem(int position) {
        return versenumber.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, final ViewGroup parent) {
        final ViewHolder holder;

        LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        // If holder not exist then locate all view from UI file.
        if (convertView == null) {
            // inflate UI from XML file
            convertView = inflater.inflate(R.layout.versedisplayrow, parent, false);
            // get all UI view
            holder = new ViewHolder(convertView);
            // set tag for holder
            holder.versenumber = (TextView) convertView.findViewById(R.id.versenumber);
            holder.verselist = (TextView) convertView.findViewById(R.id.verse);
            holder.addfavoruite=(ToggleButton)convertView.findViewById(R.id.adbookmark);

            convertView.setTag(holder);
        } else {
            // if holder created, get tag from view
            holder = (ViewHolder) convertView.getTag();
        }
        holder.versenumber.setText(versenumber.get(position));
        holder.verselist.setText(verselist.get(position));

        //verselist highlight
    /*holder.verselist.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        }
    });*/

        //share verse
        holder.share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toasty.info(activity, "Sharing a verse.", Toast.LENGTH_SHORT, true).show();
                Intent sendIntent = new Intent();
                sendIntent.setAction(Intent.ACTION_SEND);
                sendIntent.putExtra(Intent.EXTRA_TEXT, refernce.get(position) + ":" + versenumber.get(position) + '\n'   + verselist.get(position));
                sendIntent.setType("text/plain");
                activity.startActivity(sendIntent);
            }
        });

        //add in favourite
        holder.addfavoruite.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                if(isChecked){
                    mDBHelper = new DatabaseHelper(activity);
                    mDb = mDBHelper.getWritableDatabase();
                    ContentValues contentValues=new ContentValues();
                    contentValues.put("id",verseid.get(position));
                    contentValues.put("bookname",refernce.get(position));
                    contentValues.put("versenumber",versenumber.get(position));
                    contentValues.put("verse",verselist.get(position));
                    long check=mDb.insert("favourite",null,contentValues);
                    Log.d("MY_TAG","DB IS NOW "+check);

                    Toasty.success(activity, "Added in favouite", Toast.LENGTH_SHORT, true).show();
                }else {
                    mDBHelper = new DatabaseHelper(activity);
                    mDb = mDBHelper.getWritableDatabase();
                    long delete= mDb.delete("favourite","id=?",new String[]{verseid.get(position)});
                    Toasty.error(activity, "Remove in favouite", Toast.LENGTH_SHORT, true).show();
                }
            }
        });

           /* textToSpeech = new TextToSpeech(activity, new TextToSpeech.OnInitListener() {
                @Override
                public void onInit(int status) {

                    if (status == TextToSpeech.SUCCESS) {
                        result = textToSpeech.setLanguage(Locale.ENGLISH);
                    } else {

                        Toast.makeText(activity, "YOUR DEVICE NOT SUPPORTED", Toast.LENGTH_SHORT).show();
                    }
                }
            });
    */

        //My toggle button
           /* holder.speakverse.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    Toast.makeText(activity, "I AM CLICKED", Toast.LENGTH_SHORT).show();

                    if (result == TextToSpeech.LANG_NOT_SUPPORTED || result == TextToSpeech.LANG_MISSING_DATA) {

                        Toast.makeText(activity, "Language not supported or Missing", Toast.LENGTH_SHORT).show();

                    } else {

                        textToSpeech.speak(verselist.get(position), TextToSpeech.QUEUE_FLUSH, null);
                    }
                }
            });*/
        return convertView;
    }

    static class ViewHolder {
        private TextView versenumber;
        private TextView verselist;
        private ImageView share;
        private  ToggleButton addfavoruite;
        private ImageView speakverse;

        public ViewHolder(View v) {
            versenumber = (TextView) v.findViewById(R.id.versenumber);
            verselist = (TextView) v.findViewById(R.id.verse);
            share = (ImageView) v.findViewById(R.id.share);
            /*speakverse = (ImageView) v.findViewById(R.id.speakverse);*/
            addfavoruite=(ToggleButton)v.findViewById(R.id.adbookmark);
        }
    }

    public boolean CheckIsDataAlreadyInDBorNot(String TableName,  String dbfield, String fieldValue) {

        mDBHelper = new DatabaseHelper(activity);
        mDb = mDBHelper.getReadableDatabase();
        String Query = "Select * from " + TableName + " where " + dbfield + " = " + fieldValue;
        Cursor cursor = mDb.rawQuery(Query, null);
        if(cursor.getCount() <= 0){
            cursor.close();

            Toast.makeText(activity, "false", Toast.LENGTH_SHORT).show();
            return false;
        }else {

            Toast.makeText(activity, "TRUE", Toast.LENGTH_SHORT).show();
        }
        cursor.close();
        return true;
    }

    public  void opecolorpicker(){
        ColorPicker colorPicker = new ColorPicker(activity);
        ArrayList<String>colors=new ArrayList<>();
        colors.add("#FF0000");
        colors.add("#FFEC33");
        colors.add("#3C33FF");
        colors.add("#DA33FF");
        colors.add("#33FF99");
        colors.add("#90FF33");
        colors.add("#DD33FF");
        colors.add("#F0B27A");
        colors.add("#DAF7A6");
        colors.add("#34495E");

        colorPicker.setColors(colors).setTitle("HIGHLIGHT VERSE").setRoundColorButton(true).setOnChooseColorListener(new ColorPicker.OnChooseColorListener() {
            @Override
            public void onChooseColor(int position, int color) {

                Toast.makeText(activity, ""+color, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancel() {
            }
        }).show();
    }
}
</code>```

答:
As per your question,

Using this you can get a perticular item in the list view and handle its click event, Change color if you want

```<code> mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {Log.e("TAG", "onItemClick: " + position); }});
</code>```

// Good way to use shared preference is like this

```<code>public class AppSharedPreference {

public static final String ABC_APP_SHARED_PREFERENCES =
        "com.example.bachatgatapp.sharedpreferences";

///////Agent Details need to store in shared preferences///////
private static final String MOBILE_FILE = "mobfile";
</code>```

// SET - GET "MOBILE NUMBER" IN SHARED PREFERENCE

```<code>public static void setMobileFile(Context context, String value) {

    SharedPreferences preferences = context.getSharedPreferences(ABC_APP_SHARED_PREFERENCES, Context.MODE_PRIVATE);

    preferences.edit().putString(MOBILE_FILE, value).commit();
}

public static String getMobileFile(Context context) {

    SharedPreferences preferences = context.getSharedPreferences(ABC_APP_SHARED_PREFERENCES, Context.MODE_PRIVATE);

    return preferences.getString(MOBILE_FILE, "");
}
</code>```

// Write this code to save value in shared preference

```<code>AppSharedPreference.setMobileFile(this, mobile_number);
</code>```

Body:
I'm implementing a ListView with ArrayAdapter. Whenever any ListView item is clicked, I'd like the text color of the item to be changed and also saved in SharedPreference. I'm a beginner I don't know how to implement it.

Please help me to achieve this goal. I tried many sources but the problem couldn't be solved.

Here is my code.

public class ALLVERSE extends AppCompatActivity  implements NavigationView.OnNavigationItemSelectedListener {
    private ListView mylistview;
    private ArrayList<String>versenumber;
    private ArrayList<String>verselist;
    private ArrayList<String>id;
    private  ArrayList<String>refernce;
    private DatabaseHelper mDBHelper;
    private SQLiteDatabase mDb;
    private int booknumber;
    private  int chapternumber;
    private  String bookname;
    private TextView booknametitle;
    private  FullverseAdopter fullverseAdopter;

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

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        booknametitle=findViewById(R.id.bookname);

        Intent mIntent = getIntent();
        booknumber = mIntent.getIntExtra("Boooknumber",0);
        chapternumber= mIntent.getIntExtra("Chapternumber", 0);
        bookname=mIntent.getStringExtra("Bookname");

        booknametitle.setText(bookname.toString() +"   "+  chapternumber);

        //Toast.makeText(this, ""+bookname, Toast.LENGTH_SHORT).show();
        setSupportActionBar(toolbar);
        toolbar.setTitle("ALL VERSE");

        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        setData();

        mylistview=findViewById(R.id.mylistview);

        fullverseAdopter=new FullverseAdopter(ALLVERSE.this,R.layout.versedisplayrow,versenumber,verselist,refernce,id);

        mylistview.setAdapter(fullverseAdopter);

        mylistview.setOnItemClickListener(new AdapterView.OnItemClickListener(){

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Toast.makeText(ALLVERSE.this, "i am cliked", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // handle arrow click here
        if (item.getItemId() == android.R.id.home) {
            onBackPressed();
        }
        return super.onOptionsItemSelected(item);
    }

    private void setData() {
        versenumber=new ArrayList<>();
        verselist=new ArrayList<>();
        refernce=new ArrayList<>();
        id=new ArrayList<>();

        mDBHelper = new DatabaseHelper(this);
        mDb = mDBHelper.getReadableDatabase();
        Cursor cursor = mDb.rawQuery("SELECT id, v, t from t_kjv where b="+booknumber+" AND c="+chapternumber+";", new String[]{});
        if(cursor!=null && cursor.getCount() > 0)
        { if (cursor.moveToFirst())
        {
            do {
                id.add(cursor.getString(0));
                versenumber.add(cursor.getString(1));
                verselist.add(cursor.getString(2));
                refernce.add(bookname+" "+chapternumber);
            }
            while (cursor.moveToNext());
        }
        }
    }

    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        Fragment fragment;
        int id = item.getItemId();
        if (id == R.id.home) {
            Intent intent=new Intent(this,MainActivity.class);
            startActivity(intent);

        } else if (id == R.id.favoruite)
        { Intent intent=new Intent(this,Favourite.class);
            startActivity(intent);
        }  else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}

My adapter class

public class FullverseAdopter extends ArrayAdapter<String> {
    private ALLVERSE activity;
    private List<String> versenumber;
    private List<String>verseid;
    private List<String> verselist;
    private List<String> refernce;
    TextToSpeech textToSpeech;
    private DatabaseHelper mDBHelper;
    private SQLiteDatabase mDb;
    private  boolean ischeckd;
    String My_PREF="MY_PREF";

    public  String ex="switch";

    //check for availabe language
    int result;

    public FullverseAdopter(ALLVERSE context, int resource, List<String> versenumber, List<String> verselist, List<String> refernce, List<String>verseid) {
        super(context, resource, versenumber);
        this.activity = context;
        this.versenumber = versenumber;
        this.verselist = verselist;
        this.refernce = refernce;
        this.verseid=verseid;
    }

    @Override
    public int getCount() {
        return versenumber.size();
    }

    @Override
    public String getItem(int position) {
        return versenumber.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, final ViewGroup parent) {
        final ViewHolder holder;

        LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        // If holder not exist then locate all view from UI file.
        if (convertView == null) {
            // inflate UI from XML file
            convertView = inflater.inflate(R.layout.versedisplayrow, parent, false);
            // get all UI view
            holder = new ViewHolder(convertView);
            // set tag for holder
            holder.versenumber = (TextView) convertView.findViewById(R.id.versenumber);
            holder.verselist = (TextView) convertView.findViewById(R.id.verse);
            holder.addfavoruite=(ToggleButton)convertView.findViewById(R.id.adbookmark);

            convertView.setTag(holder);
        } else {
            // if holder created, get tag from view
            holder = (ViewHolder) convertView.getTag();
        }
        holder.versenumber.setText(versenumber.get(position));
        holder.verselist.setText(verselist.get(position));

        //verselist highlight
    /*holder.verselist.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        }
    });*/

        //share verse
        holder.share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toasty.info(activity, "Sharing a verse.", Toast.LENGTH_SHORT, true).show();
                Intent sendIntent = new Intent();
                sendIntent.setAction(Intent.ACTION_SEND);
                sendIntent.putExtra(Intent.EXTRA_TEXT, refernce.get(position) + ":" + versenumber.get(position) + '\n'   + verselist.get(position));
                sendIntent.setType("text/plain");
                activity.startActivity(sendIntent);
            }
        });

        //add in favourite
        holder.addfavoruite.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                if(isChecked){
                    mDBHelper = new DatabaseHelper(activity);
                    mDb = mDBHelper.getWritableDatabase();
                    ContentValues contentValues=new ContentValues();
                    contentValues.put("id",verseid.get(position));
                    contentValues.put("bookname",refernce.get(position));
                    contentValues.put("versenumber",versenumber.get(position));
                    contentValues.put("verse",verselist.get(position));
                    long check=mDb.insert("favourite",null,contentValues);
                    Log.d("MY_TAG","DB IS NOW "+check);

                    Toasty.success(activity, "Added in favouite", Toast.LENGTH_SHORT, true).show();
                }else {
                    mDBHelper = new DatabaseHelper(activity);
                    mDb = mDBHelper.getWritableDatabase();
                    long delete= mDb.delete("favourite","id=?",new String[]{verseid.get(position)});
                    Toasty.error(activity, "Remove in favouite", Toast.LENGTH_SHORT, true).show();
                }
            }
        });

           /* textToSpeech = new TextToSpeech(activity, new TextToSpeech.OnInitListener() {
                @Override
                public void onInit(int status) {

                    if (status == TextToSpeech.SUCCESS) {
                        result = textToSpeech.setLanguage(Locale.ENGLISH);
                    } else {

                        Toast.makeText(activity, "YOUR DEVICE NOT SUPPORTED", Toast.LENGTH_SHORT).show();
                    }
                }
            });
    */

        //My toggle button
           /* holder.speakverse.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    Toast.makeText(activity, "I AM CLICKED", Toast.LENGTH_SHORT).show();

                    if (result == TextToSpeech.LANG_NOT_SUPPORTED || result == TextToSpeech.LANG_MISSING_DATA) {

                        Toast.makeText(activity, "Language not supported or Missing", Toast.LENGTH_SHORT).show();

                    } else {

                        textToSpeech.speak(verselist.get(position), TextToSpeech.QUEUE_FLUSH, null);
                    }
                }
            });*/
        return convertView;
    }

    static class ViewHolder {
        private TextView versenumber;
        private TextView verselist;
        private ImageView share;
        private  ToggleButton addfavoruite;
        private ImageView speakverse;

        public ViewHolder(View v) {
            versenumber = (TextView) v.findViewById(R.id.versenumber);
            verselist = (TextView) v.findViewById(R.id.verse);
            share = (ImageView) v.findViewById(R.id.share);
            /*speakverse = (ImageView) v.findViewById(R.id.speakverse);*/
            addfavoruite=(ToggleButton)v.findViewById(R.id.adbookmark);
        }
    }

    public boolean CheckIsDataAlreadyInDBorNot(String TableName,  String dbfield, String fieldValue) {

        mDBHelper = new DatabaseHelper(activity);
        mDb = mDBHelper.getReadableDatabase();
        String Query = "Select * from " + TableName + " where " + dbfield + " = " + fieldValue;
        Cursor cursor = mDb.rawQuery(Query, null);
        if(cursor.getCount() <= 0){
            cursor.close();

            Toast.makeText(activity, "false", Toast.LENGTH_SHORT).show();
            return false;
        }else {

            Toast.makeText(activity, "TRUE", Toast.LENGTH_SHORT).show();
        }
        cursor.close();
        return true;
    }

    public  void opecolorpicker(){
        ColorPicker colorPicker = new ColorPicker(activity);
        ArrayList<String>colors=new ArrayList<>();
        colors.add("#FF0000");
        colors.add("#FFEC33");
        colors.add("#3C33FF");
        colors.add("#DA33FF");
        colors.add("#33FF99");
        colors.add("#90FF33");
        colors.add("#DD33FF");
        colors.add("#F0B27A");
        colors.add("#DAF7A6");
        colors.add("#34495E");

        colorPicker.setColors(colors).setTitle("HIGHLIGHT VERSE").setRoundColorButton(true).setOnChooseColorListener(new ColorPicker.OnChooseColorListener() {
            @Override
            public void onChooseColor(int position, int color) {

                Toast.makeText(activity, ""+color, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancel() {
            }
        }).show();
    }
}

Body:
As per your question,

Using this you can get a perticular item in the list view and handle its click event, Change color if you want

 mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {Log.e("TAG", "onItemClick: " + position); }});

// Good way to use shared preference is like this

public class AppSharedPreference {

public static final String ABC_APP_SHARED_PREFERENCES =
        "com.example.bachatgatapp.sharedpreferences";

///////Agent Details need to store in shared preferences///////
private static final String MOBILE_FILE = "mobfile";

// SET - GET "MOBILE NUMBER" IN SHARED PREFERENCE

public static void setMobileFile(Context context, String value) {

    SharedPreferences preferences = context.getSharedPreferences(ABC_APP_SHARED_PREFERENCES, Context.MODE_PRIVATE);

    preferences.edit().putString(MOBILE_FILE, value).commit();
}

public static String getMobileFile(Context context) {

    SharedPreferences preferences = context.getSharedPreferences(ABC_APP_SHARED_PREFERENCES, Context.MODE_PRIVATE);

    return preferences.getString(MOBILE_FILE, "");
}

// Write this code to save value in shared preference

AppSharedPreference.setMobileFile(this, mobile_number);


问:
How can you make sure your npm dependencies are safe?
For example, when you do npm init and install express, you end up with a node_modules folder with 20 other folders in it.

I never ran into this issue... but isn't it something that may be a concern?

答:
First, it's important to do our homework before installing a package.

Read the package's page on npmjs.com and look at who published the package, the number of versions and the number of weekly downloads. If these numbers are very low, I would pass or definitely inspect the source code.

Another thing to do is to pay attention when you type the package name, when you install. Typo squatting is possible and there are published packages which have names close to popular packages.

In terms of how secure is NPM (the registry), they do periodic penetration testing and outgoing code reviews. Also, they report vulnerabilities to package authors and handle vulnerabilities reports from other users. But, it's a continuous fight against spammers, malware, etc.

Commands you can run:

npm outdated (for locals)  and npm outdated -g --depth=0 (for globals)

This will check which packages are outdated and it will list "Current  Wanted  Latest" versions for each outdated package.

npm audit

This will produce a report of security vulnerabilities with the affected package name, vulnerability severity and description, etc.

Also, npm audit automatically runs when you install a package with npm install.

npm audit fix

This automatically install compatible updates to vulnerable dependencies.

More:

(https://docs.npmjs.com/auditing-package-dependencies-for-security-vulnerabilities)
(https://www.youtube.com/watch?v=H48KuESn2sk)