问:
JaCoCo Gradle Kotlin DSL exclude file from violation rules
I am trying to set my project up to run JaCoCo and to fail the build if it has less that 80% test coverage.  The caveat is that I want to exclude a particular file and I can't seem to make that work.  I have scoured the web and read oodles of Stack Overflow answers, blog posts, and the documentation for the plugin, but I cannot make anything work.  It always still includes the file that I am trying to exclude.

I started with:

```<code>tasks.jacocoTestCoverageVerification {
    violationRules {
        rule {
            limit {
                minimum = "0.8".toBigDecimal()
            }
        }
    }
}
</code>```

which obviously will include everything and it does. I have tried the following variations based on what I have read, but none of them have worked:

```<code>tasks.jacocoTestCoverageVerification {
    violationRules {
        rule {
            classDirectories.setFrom(sourceSets.main.get().output.asFileTree.matching {
                exclude("path.to.my.class.HelloWorld")
            })
            limit {
                minimum = "0.8".toBigDecimal()
            }
        }
    }
}
</code>```

```<code>tasks.jacocoTestCoverageVerification {
    classDirectories.setFrom(
            sourceSets.main.get().output.asFileTree.matching {
                exclude("path.to.my.class.HelloWorld")
            }
    )
    violationRules {
        rule {
            limit {
                minimum = "0.8".toBigDecimal()
            }
        }
    }
}
</code>```

```<code>tasks.jacocoTestCoverageVerification {
    violationRules {
        rule {
            limit {
                minimum = "0.8".toBigDecimal()
            }
        }
    }
}
tasks {
    getByName<JacocoReport>("jacocoTestReport") {
        afterEvaluate {
            classDirectories.setFrom(files(classDirectories.files.map {
                fileTree(it) {
                    exclude("path.to.my.class.HelloWorld")
                }
            }))
        }
    }
}
</code>```

```<code>tasks.jacocoTestCoverageVerification {
    violationRules {
        rule {
            limit {
                minimum = "0.8".toBigDecimal()
            }
        }
    }
}
tasks.withType<JacocoReport> {
    classDirectories.setFrom(
        sourceSets.main.get().output.asFileTree.matching {
            exclude("path.to.my.class.HelloWorld")
        }
    )
}
</code>```

The output of all of these is exactly the same:

```<code>Execution failed for task ':jacocoTestCoverageVerification'.
> Rule violated for bundle OneUIBackend: instructions covered ratio is 0.6, but expected minimum is 0.8
</code>```

Does anyone have any insight in to how to do this properly?

答:
So it turns out that I was declaring the excluded file as a classpath rather than a filepath.  The final solution is:</p>

```<code>tasks.jacocoTestReport {
    dependsOn(tasks.test)
    finalizedBy(tasks.jacocoTestCoverageVerification)
    classDirectories.setFrom(
            sourceSets.main.get().output.asFileTree.matching {
                exclude("path/to/my/file/HelloWorld*")
            }
    )
}
tasks.jacocoTestCoverageVerification {
    violationRules {
        rule {
            classDirectories.setFrom(sourceSets.main.get().output.asFileTree.matching {
                exclude("path/to/my/file/HelloWorld*")
            })
            limit {
                minimum = "0.8".toBigDecimal()
            }
        }
    }
}
</code>```

Body:
I am trying to set my project up to run JaCoCo and to fail the build if it has less that 80% test coverage.  The caveat is that I want to exclude a particular file and I can't seem to make that work.  I have scoured the web and read oodles of Stack Overflow answers, blog posts, and the documentation for the plugin, but I cannot make anything work.  It always still includes the file that I am trying to exclude.

I started with:

tasks.jacocoTestCoverageVerification {
    violationRules {
        rule {
            limit {
                minimum = "0.8".toBigDecimal()
            }
        }
    }
}

which obviously will include everything and it does. I have tried the following variations based on what I have read, but none of them have worked:

tasks.jacocoTestCoverageVerification {
    violationRules {
        rule {
            classDirectories.setFrom(sourceSets.main.get().output.asFileTree.matching {
                exclude("path.to.my.class.HelloWorld")
            })
            limit {
                minimum = "0.8".toBigDecimal()
            }
        }
    }
}

tasks.jacocoTestCoverageVerification {
    classDirectories.setFrom(
            sourceSets.main.get().output.asFileTree.matching {
                exclude("path.to.my.class.HelloWorld")
            }
    )
    violationRules {
        rule {
            limit {
                minimum = "0.8".toBigDecimal()
            }
        }
    }
}

tasks.jacocoTestCoverageVerification {
    violationRules {
        rule {
            limit {
                minimum = "0.8".toBigDecimal()
            }
        }
    }
}
tasks {
    getByName<JacocoReport>("jacocoTestReport") {
        afterEvaluate {
            classDirectories.setFrom(files(classDirectories.files.map {
                fileTree(it) {
                    exclude("path.to.my.class.HelloWorld")
                }
            }))
        }
    }
}

tasks.jacocoTestCoverageVerification {
    violationRules {
        rule {
            limit {
                minimum = "0.8".toBigDecimal()
            }
        }
    }
}
tasks.withType<JacocoReport> {
    classDirectories.setFrom(
        sourceSets.main.get().output.asFileTree.matching {
            exclude("path.to.my.class.HelloWorld")
        }
    )
}

The output of all of these is exactly the same:

Execution failed for task ':jacocoTestCoverageVerification'.
> Rule violated for bundle OneUIBackend: instructions covered ratio is 0.6, but expected minimum is 0.8

Does anyone have any insight in to how to do this properly?

Body:
So it turns out that I was declaring the excluded file as a classpath rather than a filepath.  The final solution is:

tasks.jacocoTestReport {
    dependsOn(tasks.test)
    finalizedBy(tasks.jacocoTestCoverageVerification)
    classDirectories.setFrom(
            sourceSets.main.get().output.asFileTree.matching {
                exclude("path/to/my/file/HelloWorld*")
            }
    )
}
tasks.jacocoTestCoverageVerification {
    violationRules {
        rule {
            classDirectories.setFrom(sourceSets.main.get().output.asFileTree.matching {
                exclude("path/to/my/file/HelloWorld*")
            })
            limit {
                minimum = "0.8".toBigDecimal()
            }
        }
    }
}


来源: stackexchange

问:
Installing Sonar without database in Spring Boot
We are setting up sonar with maven build using what is described here.
However I am interested in finding out if it is possible to set up sonar without having a database. Is it possible for sonar to generate a PDF with all metrix in memory and save it to some directory for later use than saving in to database?</p>

答:
Little late but it is possible though but I'm new to this so I don't know is this a good approach or not so, please correct me if I'm wrong.

Here is the process to install Sonarqube without a database:

Download the Sonarqube file from here. You can download the latest version or any version you like. I download 6.6 because it was a stable version.

Then after download, unzip the file and go to the terminal/cmd and follow the following command:

$ cd /Downloads/sonarqube-6.6/bin/linux-x86-64
 $ ./sonar.sh start

Here I'm using linux-86-64 so that's why I used that folder. If you are using any other device you can find your device folder in bin and choose that.

Then you can check the status of sonar with:
./sonar.sh status and the output will be like this:
SonarQube is running (26602).

Then go to http://localhost:9000/ and log in with username: admin and password: admin then it will ask you your project language like java, c#, etc and your automation tool. Mine was java and Gradle.

After this, it will say to give a name to generate a key and a small part will show you a version name and a Gradle command(If you have chosen any different option it will generate command according to that)

Copy the version name and put it in plugin in build.gradle file:

plugins {
id "org.sonarqube" version "2.7"
   }

And build gradle. For me, it was 2.7 but it can be different for you.

Then copy the command and run it in terminal. The command would look like this:
./gradlew sonarqube   -Dsonar.host.url=http://localhost:9000   -Dsonar.login=86606bed1bbb1fa68649401674d2f59e395481ff

where Dsonar.login value will be different for every key generated.

Then go to http://localhost:9000/ and then you can see your project name there with its bugs, vulnerability, code smell, etc.

And this is how you can user Sonar without the database.

PS: I don't know is this the best approach or not but for a small project like mine it came in quite handy without setting up a database.

ContentLicense: CC BY-SA 4.0


问:
In Python, how do I index a list with another list?
I would like to index a list with another list like this

```<code>L = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
Idx = [0, 3, 7]
T = L[ Idx ]
</code>```

and T should end up being a list containing ['a', 'd', 'h'].

Is there a better way than

```<code>T = []
for i in Idx:
    T.append(L[i])

print T
# Gives result ['a', 'd', 'h']
</code>```

答:
You could also use the __getitem__ method combined with map like the following:

```<code>L = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
Idx = [0, 3, 7]
res = list(map(L.__getitem__, Idx))
print(res)
# ['a', 'd', 'h']
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I would like to index a list with another list like this

L = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
Idx = [0, 3, 7]
T = L[ Idx ]

and T should end up being a list containing ['a', 'd', 'h'].

Is there a better way than

T = []
for i in Idx:
    T.append(L[i])

print T
# Gives result ['a', 'd', 'h']

Body:
You could also use the __getitem__ method combined with map like the following:

L = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
Idx = [0, 3, 7]
res = list(map(L.__getitem__, Idx))
print(res)
# ['a', 'd', 'h']


问:
How to calculate the sunrise and sunset in javascript?
i am using appcelerator titanium to develop an IOS app and i want to let my app send local notification to the users in sunrise and sunset

a good tool to solve this is Yahoo weather using YQL ; however, yahoo weather is for non-commercial use only!!

i am trying to find a javascript library to calculate the sunrise/set + a database of the world's countries and cities with the latitude and longtude

have anyone ever needed the same?

Any idea.

答:
Use NOAA's javascript routines for the solar position: here

They include a short list of cities with latitude and longitude. I think you can also get that from iOS, but here's another answer on getting it from city, state, etc.

ContentLicense: CC BY-SA 3.0


问:
Dependency Injection into an ILogger object
I have a Server side Blazor application where I am implementing an ILogger object to catch unhandled application errors and log them.  You can see how I did that in my answer here:
Processing unhandled exceptions in ASP.NET Core 3.1

What I would like to do is to use dependency injection to pass objects into my ILogger object so it can get more information to log about the exception.  But I am not able to figure out how to do that.  I tried adding DI objects to the constructor of the ExceptionLoggerProvider and ExceptionLogger objects, but I couldn't get that to work.  Can someone provide an example of how to do that?

For example, I have a LoginAccount DI class I created which tracks the logged in user which I setup like this which I would like to be injected into my ILogger object.

```<code>services.AddScoped<LoginAccount>();
</code>```

答:
You need to add the reference in startup.cs service object.

```<code>public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IDataAccess, DataAccess>();
}
</code>```

Did you add that or you missed that?

Body:
I have a Server side Blazor application where I am implementing an ILogger object to catch unhandled application errors and log them.  You can see how I did that in my answer here:
Processing unhandled exceptions in ASP.NET Core 3.1

What I would like to do is to use dependency injection to pass objects into my ILogger object so it can get more information to log about the exception.  But I am not able to figure out how to do that.  I tried adding DI objects to the constructor of the ExceptionLoggerProvider and ExceptionLogger objects, but I couldn't get that to work.  Can someone provide an example of how to do that?

For example, I have a LoginAccount DI class I created which tracks the logged in user which I setup like this which I would like to be injected into my ILogger object.

services.AddScoped<LoginAccount>();

Body:
You need to add the reference in startup.cs service object.

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IDataAccess, DataAccess>();
}

Did you add that or you missed that?


问:
im trying to add a header section to my profile page using swift (Xcode) with out using the storyboard
This is what i have done so far but it keeps giving me the error:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'could not dequeue a view of kind: UICollectionElementKindSectionFooter with identifier ProfileHeader - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'

how would i fix this?

```<code>private let reuseIdentifier = "Cell"
private let headerIdentifier = "ProfileHeader"

class UserProfileVC: UICollectionViewController, UICollectionViewDelegateFlowLayout {

// MARK: Properties
var USER_NAME: String = "Username"

override func viewDidLoad() {
    super.viewDidLoad()
    collectionView.register(UINib(nibName: headerIdentifier, bundle: nil), forCellWithReuseIdentifier: reuseIdentifier)
    self.navigationItem.title = "Profile"

    self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
    self.collectionView!.register(ProfileHeader.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: headerIdentifier)
    fetchUsersData()

}

// MARK: UICollectionViewDataSource

override func numberOfSections(in collectionView: UICollectionView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
}

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of items
    return 0
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {

    return CGSize(width: view.frame.width, height: 200)
}

override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {

    //Declare header
    let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headerIdentifier, for: indexPath) as! ProfileHeader
    return header
}

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)

    // Configure the cell

    return cell
}

// MARK - API

func fetchUsersData() {

    guard let currentUser = Auth.auth().currentUser?.uid else { return }
    print("Current user id is \(currentUser)")

    Database.database().reference().child("Users").child(currentUser).child(USER_NAME).observeSingleEvent(of: .value) { (snapshot) in
        guard let username = snapshot.value as? String else {return}
        self.navigationItem.title = username
    }
}
}
</code>```

答:
ViewForSupplementary is called for both header and footer view

```<code>func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if kind == UICollectionView.elementKindSectionHeader {
            let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headerIdentifier, for: indexPath) as! ProfileHeader
            return header
        }
        else {
            fatalError("Unexpected element kind")
        }
    }
</code>```

And if you don't want viewForSupplementaryElement to be called for footer set

```<code>extension UserProfileVC: UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView,
                          layout collectionViewLayout: UICollectionViewLayout,
                          referenceSizeForFooterInSection section: Int) -> CGSize {
        return CGSize.zero
    }
}
</code>```

Also Please remove

```<code>collectionView.register(UINib(nibName: headerIdentifier, bundle: nil), forCellWithReuseIdentifier: reuseIdentifier)
</code>```

This is registering a ProfileHeader as cell and in next statement you register ProfileHeader as section header also self.collectionView!.register(ProfileHeader.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: headerIdentifier)

EDIT 2:

As OP is facing difficulty fun understanding solution, I am writing whole class below

```<code>private let reuseIdentifier = "Cell"
private let headerIdentifier = "ProfileHeader"

class UserProfileVC: UICollectionViewController, UICollectionViewDelegateFlowLayout {

    // MARK: Properties
    var USER_NAME: String = "Username"

    override func viewDidLoad() {
        super.viewDidLoad()
        collectionView.register(UINib(nibName: headerIdentifier, bundle: nil), forCellWithReuseIdentifier: reuseIdentifier)
        self.navigationItem.title = "Profile"

        self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        self.collectionView!.register(ProfileHeader.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: headerIdentifier)
        fetchUsersData()

    }

    // MARK: UICollectionViewDataSource

    override func numberOfSections(in collectionView: UICollectionView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        return 0
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {

        return CGSize.zero
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize(width: view.frame.width, height: 200)
    }

    override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {

        if kind == UICollectionView.elementKindSectionHeader {
            let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headerIdentifier, for: indexPath) as! ProfileHeader
            return header
        }
        else {
            fatalError("Unexpected element kind")
        }
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)

        // Configure the cell

        return cell
    }

    // MARK - API

    func fetchUsersData() {

        guard let currentUser = Auth.auth().currentUser?.uid else { return }
        print("Current user id is \(currentUser)")

        Database.database().reference().child("Users").child(currentUser).child(USER_NAME).observeSingleEvent(of: .value) { (snapshot) in
            guard let username = snapshot.value as? String else {return}
            self.navigationItem.title = username
        }
    }
}
</code>```

Body:
This is what i have done so far but it keeps giving me the error:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'could not dequeue a view of kind: UICollectionElementKindSectionFooter with identifier ProfileHeader - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'

how would i fix this?

private let reuseIdentifier = "Cell"
private let headerIdentifier = "ProfileHeader"

class UserProfileVC: UICollectionViewController, UICollectionViewDelegateFlowLayout {

// MARK: Properties
var USER_NAME: String = "Username"

override func viewDidLoad() {
    super.viewDidLoad()
    collectionView.register(UINib(nibName: headerIdentifier, bundle: nil), forCellWithReuseIdentifier: reuseIdentifier)
    self.navigationItem.title = "Profile"

    self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
    self.collectionView!.register(ProfileHeader.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: headerIdentifier)
    fetchUsersData()

}

// MARK: UICollectionViewDataSource

override func numberOfSections(in collectionView: UICollectionView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
}

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of items
    return 0
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {

    return CGSize(width: view.frame.width, height: 200)
}

override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {

    //Declare header
    let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headerIdentifier, for: indexPath) as! ProfileHeader
    return header
}

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)

    // Configure the cell

    return cell
}

// MARK - API

func fetchUsersData() {

    guard let currentUser = Auth.auth().currentUser?.uid else { return }
    print("Current user id is \(currentUser)")

    Database.database().reference().child("Users").child(currentUser).child(USER_NAME).observeSingleEvent(of: .value) { (snapshot) in
        guard let username = snapshot.value as? String else {return}
        self.navigationItem.title = username
    }
}
}

Body:
ViewForSupplementary is called for both header and footer view

func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if kind == UICollectionView.elementKindSectionHeader {
            let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headerIdentifier, for: indexPath) as! ProfileHeader
            return header
        }
        else {
            fatalError("Unexpected element kind")
        }
    }

And if you don't want viewForSupplementaryElement to be called for footer set

extension UserProfileVC: UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView,
                          layout collectionViewLayout: UICollectionViewLayout,
                          referenceSizeForFooterInSection section: Int) -> CGSize {
        return CGSize.zero
    }
}

Also Please remove

collectionView.register(UINib(nibName: headerIdentifier, bundle: nil), forCellWithReuseIdentifier: reuseIdentifier)

This is registering a ProfileHeader as cell and in next statement you register ProfileHeader as section header also self.collectionView!.register(ProfileHeader.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: headerIdentifier)

EDIT 2:

As OP is facing difficulty fun understanding solution, I am writing whole class below

private let reuseIdentifier = "Cell"
private let headerIdentifier = "ProfileHeader"

class UserProfileVC: UICollectionViewController, UICollectionViewDelegateFlowLayout {

    // MARK: Properties
    var USER_NAME: String = "Username"

    override func viewDidLoad() {
        super.viewDidLoad()
        collectionView.register(UINib(nibName: headerIdentifier, bundle: nil), forCellWithReuseIdentifier: reuseIdentifier)
        self.navigationItem.title = "Profile"

        self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        self.collectionView!.register(ProfileHeader.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: headerIdentifier)
        fetchUsersData()

    }

    // MARK: UICollectionViewDataSource

    override func numberOfSections(in collectionView: UICollectionView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        return 0
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {

        return CGSize.zero
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize(width: view.frame.width, height: 200)
    }

    override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {

        if kind == UICollectionView.elementKindSectionHeader {
            let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headerIdentifier, for: indexPath) as! ProfileHeader
            return header
        }
        else {
            fatalError("Unexpected element kind")
        }
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)

        // Configure the cell

        return cell
    }

    // MARK - API

    func fetchUsersData() {

        guard let currentUser = Auth.auth().currentUser?.uid else { return }
        print("Current user id is \(currentUser)")

        Database.database().reference().child("Users").child(currentUser).child(USER_NAME).observeSingleEvent(of: .value) { (snapshot) in
            guard let username = snapshot.value as? String else {return}
            self.navigationItem.title = username
        }
    }
}


问:
SQL Server : Merge output based on ID
I have a SQL Server table containing multiple file names and their versions.

When I run

```<code>SELECT AssetID, File, Version
FROM tblAssets
</code>```

I get

```<code>|  AssetID  |  File    |  Version |
+-----------+----------+----------+
|  1        |  FileA   |  1.1     |
|  1        |  FileB   |  3.0     |
|  2        |  FileA   |  1.2     |
|  2        |  FileB   |  2.9     |
</code>```

I'd like the output to be

```<code>|  AssetID  |  FileA Version   |  FileB Version |
+-----------+------------------+----------------+
|  1        |  1.1             |  3.0           |
|  2        |  1.2             |  2.9           |
</code>```

I believe this can be achieved by using CASE, but haven't been successful and therefore seek your advise.

答:
Use conditional aggregation:</p>

```<code>select assetId,
       max(case when file = 'FileA' then version end) as filea_version,
       max(case when file = 'FileB' then version end) as fileb_version
from t
group by assetId
</code>```

Title: SQL Server : Merge output based on ID

Body:
I have a SQL Server table containing multiple file names and their versions.

When I run

SELECT AssetID, File, Version
FROM tblAssets

I get

|  AssetID  |  File    |  Version |
+-----------+----------+----------+
|  1        |  FileA   |  1.1     |
|  1        |  FileB   |  3.0     |
|  2        |  FileA   |  1.2     |
|  2        |  FileB   |  2.9     |

I'd like the output to be

|  AssetID  |  FileA Version   |  FileB Version |
+-----------+------------------+----------------+
|  1        |  1.1             |  3.0           |
|  2        |  1.2             |  2.9           |

I believe this can be achieved by using CASE, but haven't been successful and therefore seek your advise.

Body:
Use conditional aggregation:

select assetId,
       max(case when file = 'FileA' then version end) as filea_version,
       max(case when file = 'FileB' then version end) as fileb_version
from t
group by assetId


问:
How to convert DOS/Windows newline (CRLF) to Unix newline (LF)
How can I programmatically (not using vi) convert DOS/Windows newlines to Unix newlines?

The dos2unix and unix2dos commands are not available on certain systems.

How can I emulate them with commands such as sed, awk, and tr?

答:
With Bash 4.2 and newer you can use something like this to strip the trailing CR, which only uses Bash built-ins:</p>
```<code>if [[ "${str: -1}" == $'\r' ]]; then
    str="${str:: -1}"
fi
</code>```

Body:
With Bash 4.2 and newer you can use something like this to strip the trailing CR, which only uses Bash built-ins:

if [[ "${str: -1}" == $'\r' ]]; then
    str="${str:: -1}"
fi


问:
How to perform a room transaction usin Rxjava
How can I do a room transaction across 2 different DAOs usin rxjava?

I have this code that I would like to use with Rxjava  but I need it to return some kind of observable

```<code> @Transaction
fun insertStoreWithPictures(store: Store, pictures: List<StorePicture>) {

    insertStore(store)
    insertPictures(pictures)

}
</code>```

The store DAO

```<code>@Dao
abstract public class store {

@Insert
Single<Long> insert(store  entity);
}
</code>```

The storePicture DAO

```<code>@Dao
abstract public class storePicture {

    @Insert
    Completable insert(storePicture... entity);
}
</code>```

答: I think you can use zip or combine operator of RxJava. It would create an observable from an iterators observable source.

Body:
How can I do a room transaction across 2 different DAOs usin rxjava?

I have this code that I would like to use with Rxjava  but I need it to return some kind of observable

 @Transaction
fun insertStoreWithPictures(store: Store, pictures: List<StorePicture>) {

    insertStore(store)
    insertPictures(pictures)

}

The store DAO

@Dao
abstract public class store {

@Insert
Single<Long> insert(store  entity);
}

The storePicture DAO

@Dao
abstract public class storePicture {

    @Insert
    Completable insert(storePicture... entity);
}


问:
SQL Server - collapsing multiple row values into one field
I'm trying to produce the result shown in the "Desired Results" section (in SQL Server 2016) in my screenshot below, where the objections associated with each borrower number are in one column delimited by commas instead of separate rows.

I don't want to restructure my database - I just want to display the results as requested for a customer report. Thanks

答:
I was able to use the STRING_AGG function which I didn't know existed to produce the results I need.</p>

```<code>SELECT ht.Hearings_CaseID, Borrower_Number, STRING_AGG(Objection,',') AS Objection
FROM Hearings_Test ht INNER JOIN
Hearings_Objections_Test hot on ht.Hearings_CaseID = hot.Hearings_CaseID
GROUP BY
ht.Hearings_CaseID, Borrower_Number
</code>```

Body:
I was able to use the STRING_AGG function which I didn't know existed to produce the results I need.

SELECT ht.Hearings_CaseID, Borrower_Number, STRING_AGG(Objection,',') AS Objection
FROM Hearings_Test ht INNER JOIN
Hearings_Objections_Test hot on ht.Hearings_CaseID = hot.Hearings_CaseID
GROUP BY
ht.Hearings_CaseID, Borrower_Number


问:
Find locally declared Procedures and Methods in a webform code behind (GetMethods)
I am trying to get a subset of locally declared methods in a webform code behind using GetMethods but cannot figure out the proper BindingFlags settings (see code below)....and some further specific questions:

1) Is it possible to differentiate between Procedures and Functions?

2) Furthermore, I only want to fetch a certain subset of these....is there some way I can decorate the ones I want with an attribute, and then further filter based on that?

```<code>Private Sub LoadFunctions()
        Dim thisClass As Type = Me.GetType
        For Each method As MethodInfo In thisClass.GetMethods(BindingFlags.Instance Or BindingFlags.Public Or BindingFlags.DeclaredOnly)
            If method.Name.Substring(0, 3) = "Get" Then
                Me.ddlCodeSamples.Items.Add(method.Name)
            End If
        Next
    End Sub
</code>```

答:
a) The real source of the problem seemed to be reflecting on the wrong class.....from a webform, you must do:

```<code>Dim thisClass As Type = GetType(yourWebFormName)
</code>```

...not:

```<code>Dim thisClass As Type = Me.GetType
</code>```

b) I think method.ReturnType could be examined to differentiate between a procedure or method.

c) Here is how custom attributes could be used:

More or less working code:

```<code>Private Sub LoadFunctions()
        '....When run from a webform that you want to reflect on the locally defined functions:
        ' This is *incorrect*:
        '   Dim thisClass As Type = Me.GetType
        ' This is *correct* (I'm not sure why though):
        Dim thisClass As Type = GetType(CodeSamples)    '<-- "CodeSamples" is the webform name
        For Each method As MethodInfo In thisClass.GetMethods(BindingFlags.Public Or BindingFlags.NonPublic Or BindingFlags.Instance Or BindingFlags.DeclaredOnly)
            If Not method.IsSpecialName Then    '<-- to exclude property getter/setters, etc
                ' Rather than filtering on function name, could use custom attributes as discussed here:
                '        http://www.codeguru.com/vb/gen/vb_general/attributes/article.php/c6073
                If method.Name.Substring(0, 3) = "Get" Then
                    Me.ddlCodeSamples.Items.Add(method.Name)
                End If
            End If
        Next
    End Sub
</code>```

OwnerDisplayName: tbone

Body:
I am trying to get a subset of locally declared methods in a webform code behind using GetMethods but cannot figure out the proper BindingFlags settings (see code below)....and some further specific questions:

1) Is it possible to differentiate between Procedures and Functions?

2) Furthermore, I only want to fetch a certain subset of these....is there some way I can decorate the ones I want with an attribute, and then further filter based on that?

Private Sub LoadFunctions()
        Dim thisClass As Type = Me.GetType
        For Each method As MethodInfo In thisClass.GetMethods(BindingFlags.Instance Or BindingFlags.Public Or BindingFlags.DeclaredOnly)
            If method.Name.Substring(0, 3) = "Get" Then
                Me.ddlCodeSamples.Items.Add(method.Name)
            End If
        Next
    End Sub

Body:
a) The real source of the problem seemed to be reflecting on the wrong class.....from a webform, you must do:

Dim thisClass As Type = GetType(yourWebFormName)

...not:

Dim thisClass As Type = Me.GetType

b) I think method.ReturnType could be examined to differentiate between a procedure or method.

c) Here is how custom attributes could be used:

More or less working code:

Private Sub LoadFunctions()
        '....When run from a webform that you want to reflect on the locally defined functions:
        ' This is *incorrect*:
        '   Dim thisClass As Type = Me.GetType
        ' This is *correct* (I'm not sure why though):
        Dim thisClass As Type = GetType(CodeSamples)    '<-- "CodeSamples" is the webform name
        For Each method As MethodInfo In thisClass.GetMethods(BindingFlags.Public Or BindingFlags.NonPublic Or BindingFlags.Instance Or BindingFlags.DeclaredOnly)
            If Not method.IsSpecialName Then    '<-- to exclude property getter/setters, etc
                ' Rather than filtering on function name, could use custom attributes as discussed here:
                '        http://www.codeguru.com/vb/gen/vb_general/attributes/article.php/c6073
                If method.Name.Substring(0, 3) = "Get" Then
                    Me.ddlCodeSamples.Items.Add(method.Name)
                End If
            End If
        Next
    End Sub


问:
Ternary operator in perl yields unexpected result when assigning a variable in the statement
I'm trying to make a transition from php to perl and expectedly running into some weirdness.  I cannot understand why one version of my code works vs another.

This fails:

```<code>sub tester
{
$return;
($_[0] < 10) ? $return = "youre a youngin" : $return = "youre an old person";
return $return;
}

print "how old are you?";
$a = <>;
chomp $a;

print  tester($a);  #both result in "youre an old person"
</code>```

however this one works:

```<code>sub tester
{
    return ($_[0] < 10) ? "youre a youngin" : "youre an old person";
}

print "how old are you?";
$a = <>;
chomp $a;
print  tester($a);
</code>```

what is the real difference here?!

答:
I believe $return; is a syntax error. You don't need to declare it - variables in perl and php are scopeless.

In addition = takes precedence over ?: so you need to add () to both assignments.

Body:
I'm trying to make a transition from php to perl and expectedly running into some weirdness.  I cannot understand why one version of my code works vs another.

This fails:

sub tester
{
$return;
($_[0] < 10) ? $return = "youre a youngin" : $return = "youre an old person";
return $return;
}

print "how old are you?";
$a = <>;
chomp $a;

print  tester($a);  #both result in "youre an old person"

however this one works:

sub tester
{
    return ($_[0] < 10) ? "youre a youngin" : "youre an old person";
}

print "how old are you?";
$a = <>;
chomp $a;
print  tester($a);

what is the real difference here?!


问:
How do you check if string ends with another string in Ada?
There are canonical answers to this question for every popular language, even though that answer usually boils down to: "Use string.endsWith() from the standard library". For Ada, as far as I can find in the docs for the Fixed String package, there is no string.endswith function.

So, given two fixed strings A and B, how do you check if A ends with B?

```<code>declare
   A : constant String := "John Johnson";
   B : constant String := "son";
begin
   if A.Ends_With(B) then -- this doesn't compile
      Put_Line ("Yay!");
   end if;
end
</code>```

My intent is to establish a standard answer for Ada.

答:
As a slight simplification of Jim’s answer, this works too:

```<code>   function Ends_With (Source, Pattern : String) return Boolean is
   begin
      if Pattern'Length > Source'Length then
         return False;
      else
         return Source (Source'Last - Pattern'Length + 1 .. Source'Last)
           = Pattern;
      end if;
   end Ends_With;
</code>```

but, even better (thanks, Zerte),

```<code>function Ends_With (Source, Pattern : String) return Boolean is
  (Pattern'Length <= Source'Length and then
     Source (Source'Last - Pattern'Length + 1 .. Source'Last) = Pattern);
</code>```

Body:
There are canonical answers to this question for every popular language, even though that answer usually boils down to: "Use string.endsWith() from the standard library". For Ada, as far as I can find in the docs for the Fixed String package, there is no string.endswith function.

So, given two fixed strings A and B, how do you check if A ends with B?

declare
   A : constant String := "John Johnson";
   B : constant String := "son";
begin
   if A.Ends_With(B) then -- this doesn't compile
      Put_Line ("Yay!");
   end if;
end

My intent is to establish a standard answer for Ada.

Body:
As a slight simplification of Jim’s answer, this works too:

   function Ends_With (Source, Pattern : String) return Boolean is
   begin
      if Pattern'Length > Source'Length then
         return False;
      else
         return Source (Source'Last - Pattern'Length + 1 .. Source'Last)
           = Pattern;
      end if;
   end Ends_With;

but, even better (thanks, Zerte),

function Ends_With (Source, Pattern : String) return Boolean is
  (Pattern'Length <= Source'Length and then
     Source (Source'Last - Pattern'Length + 1 .. Source'Last) = Pattern);


问:
Python: write outer product using map and reduce
Suppose I have a matrix

```<code>import numpy as np
from functools import reduce
np.random.seed(123)
X = np.random.normal(size=(5, 2))
</code>```

and I want to compute X^t X without using numpy functions and using map, reduce and lambda functions. Since we can write X^t X as a sum of outer products, my goal would be:

```<code>def outer_product(x):
    """Computes outer product of a vector with itself"""
    pass

map(outer_product, X)
</code>```

However I can't seem to find an efficient way of writing all of these with map reduce.

My Attempt

```<code>def outer(x):
    xxx = np.repeat(x, len(x))
    yyy = np.array(list(x) * len(x))
    return np.reshape(list(map(lambda x, y: x*y, xxx, yyy)), (len(x), len(x)))
</code>```

so that

```<code>outer(X[0, ])
</code>```

And then I've written the covariance matrix as follows

```<code>def cov(X):
    return np.array(reduce(lambda x, y: x + y, list(map(outer, X)))) / np.size(X, 0)
</code>```

答:
```<code>In [40]: X = np.arange(10).reshape(5,2)
</code>```

Using the outer and list/map from the accepted answer:

```<code>In [41]: outer = lambda V: np.array([[x*x1 for x in V] for x1 in V])
In [43]: list(map(outer, X))
Out[43]:
[array([[0, 0],
        [0, 1]]),
 array([[4, 6],
        [6, 9]]),
 array([[16, 20],
        [20, 25]]),
 array([[36, 42],
        [42, 49]]),
 array([[64, 72],
        [72, 81]])]
</code>```

Using numpy broadcasting:

```<code>In [44]: X[:,:,None]*X[:,None,:]
Out[44]:
array([[[ 0,  0],
        [ 0,  1]],

       [[ 4,  6],
        [ 6,  9]],

       [[16, 20],
        [20, 25]],

       [[36, 42],
        [42, 49]],

       [[64, 72],
        [72, 81]]])
</code>```

For a (5,2) X the result is a (5,2,2) array.

Some small time tests:

```<code>In [55]: timeit list(map(outer, X))
51.8 µs ± 1.29 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [57]: timeit [outer(i) for i in X]
49.8 µs ± 65.9 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [58]: timeit X[:,:,None]*X[:,None,:]
5.37 µs ± 11.6 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
</code>```

list/map has about the same speed as a list comprehension.  Generally I find list comprehensions to be clearer.  But broadcasted numpy operations are usually much faster.

If you are going to iterate, consider working with a lists; it's usually faster:

```<code>In [61]: timeit [outer(i) for i in X.tolist()]
24.3 µs ± 63.6 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [62]: outer0 = lambda V: [[x*x1 for x in V] for x1 in V]
In [64]: timeit [outer0(i) for i in X.tolist()]
7.33 µs ± 16 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
</code>```

Body:
Suppose I have a matrix

import numpy as np
from functools import reduce
np.random.seed(123)
X = np.random.normal(size=(5, 2))

and I want to compute X^t X without using numpy functions and using map, reduce and lambda functions. Since we can write X^t X as a sum of outer products, my goal would be:

def outer_product(x):
    """Computes outer product of a vector with itself"""
    pass

map(outer_product, X)

However I can't seem to find an efficient way of writing all of these with map reduce.

My Attempt

def outer(x):
    xxx = np.repeat(x, len(x))
    yyy = np.array(list(x) * len(x))
    return np.reshape(list(map(lambda x, y: x*y, xxx, yyy)), (len(x), len(x)))

so that

outer(X[0, ])

And then I've written the covariance matrix as follows

def cov(X):
    return np.array(reduce(lambda x, y: x + y, list(map(outer, X)))) / np.size(X, 0)

Body:
In [40]: X = np.arange(10).reshape(5,2)

Using the outer and list/map from the accepted answer:

In [41]: outer = lambda V: np.array([[x*x1 for x in V] for x1 in V])
In [43]: list(map(outer, X))
Out[43]:
[array([[0, 0],
        [0, 1]]),
 array([[4, 6],
        [6, 9]]),
 array([[16, 20],
        [20, 25]]),
 array([[36, 42],
        [42, 49]]),
 array([[64, 72],
        [72, 81]])]

Using numpy broadcasting:

In [44]: X[:,:,None]*X[:,None,:]
Out[44]:
array([[[ 0,  0],
        [ 0,  1]],

       [[ 4,  6],
        [ 6,  9]],

       [[16, 20],
        [20, 25]],

       [[36, 42],
        [42, 49]],

       [[64, 72],
        [72, 81]]])

For a (5,2) X the result is a (5,2,2) array.

Some small time tests:

In [55]: timeit list(map(outer, X))
51.8 µs ± 1.29 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [57]: timeit [outer(i) for i in X]
49.8 µs ± 65.9 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [58]: timeit X[:,:,None]*X[:,None,:]
5.37 µs ± 11.6 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

list/map has about the same speed as a list comprehension.  Generally I find list comprehensions to be clearer.  But broadcasted numpy operations are usually much faster.

If you are going to iterate, consider working with a lists; it's usually faster:

In [61]: timeit [outer(i) for i in X.tolist()]
24.3 µs ± 63.6 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [62]: outer0 = lambda V: [[x*x1 for x in V] for x1 in V]
In [64]: timeit [outer0(i) for i in X.tolist()]
7.33 µs ± 16 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)


问:
How to migrate bundleConfig.cs from project asp.net mvc to asp.net core?
I need to migrate bundleConfig from an old asp.net project mvc to asp.net core

I added in startup.cs:

```<code>app.UseBundling (
                // as we rebased the static files to / static (see UseStaticFiles ()),
                // we need to pass this information to the bundling middleware as well,
                // otherwise urls would be rewrited incorrectly
                new BundlingOptions
                {
                    StaticFilesRequestPath = "/static"
                },
                bundles =>
                {
                    bundles.AddJs ("/bundles /jquery")
                        .Include ("/Scripts/jquery-{version}.js");

                    bundles.AddCss ("/bundles/jquery")
                        .Include ("/Scripts/jquery-{version}.js");

                    // we use LESS in this demo
                    bundles.AddCss ("/site.css")
                        .Include ("/less/site.less");

                    // defines a Javascript bundle containing your Vue application and components
                    bundles.AddJs ("/app.js")
                        .Include ("/js/components /*.Js")
                        .Include ("/js/app.js");
                });
</code>```

答:
You would have to create a cs file in App_Start

```<code>using System.Web.Optimization;

namespace EnterYourProgramsNameSpaceHere
{
    public class BundleConfig
    {

        public static void RegisterBundles(BundleCollection bundles)
        {
            //Add your bundles here
            bundles.Add(new StyleBundle("~/Content/myStyle")
            .Include("~/Content/styles.css"));

            bundles.Add(new ScriptBundle("~/bundles/myjs")
             .Include("~/Scripts/jquery.js"));
        }
    }
}
</code>```

in startup.cs
add this line

```<code> BundleConfig.RegisterBundles(BundleTable.Bundles);
</code>```

You have to make sure that the spacing in your file paths is removed, in your example the program may have an issue finding your js/css files.

you can look up more info here : http://go.microsoft.com/fwlink/?LinkId=301862

Body:
I need to migrate bundleConfig from an old asp.net project mvc to asp.net core

I added in startup.cs:

app.UseBundling (
                // as we rebased the static files to / static (see UseStaticFiles ()),
                // we need to pass this information to the bundling middleware as well,
                // otherwise urls would be rewrited incorrectly
                new BundlingOptions
                {
                    StaticFilesRequestPath = "/static"
                },
                bundles =>
                {
                    bundles.AddJs ("/bundles /jquery")
                        .Include ("/Scripts/jquery-{version}.js");

                    bundles.AddCss ("/bundles/jquery")
                        .Include ("/Scripts/jquery-{version}.js");

                    // we use LESS in this demo
                    bundles.AddCss ("/site.css")
                        .Include ("/less/site.less");

                    // defines a Javascript bundle containing your Vue application and components
                    bundles.AddJs ("/app.js")
                        .Include ("/js/components /*.Js")
                        .Include ("/js/app.js");
                });

Body:
You would have to create a cs file in App_Start

using System.Web.Optimization;

namespace EnterYourProgramsNameSpaceHere
{
    public class BundleConfig
    {

        public static void RegisterBundles(BundleCollection bundles)
        {
            //Add your bundles here
            bundles.Add(new StyleBundle("~/Content/myStyle")
            .Include("~/Content/styles.css"));

            bundles.Add(new ScriptBundle("~/bundles/myjs")
             .Include("~/Scripts/jquery.js"));
        }
    }
}

in startup.cs
add this line

 BundleConfig.RegisterBundles(BundleTable.Bundles);

You have to make sure that the spacing in your file paths is removed, in your example the program may have an issue finding your js/css files.

you can look up more info here : http://go.microsoft.com/fwlink/?LinkId=301862


问:
Return Object Name With The Biggest Points Property In a List Of Objects
I have players containing multiple objects within. My end goal is to return the name property of the object with the highest points value.

For example this block should return a string of  Bob

```<code>const players = [

   {
      name: 'Jack',
      points: 3
   }

   {
      name: 'Jill',
      points: 2
   }

   {
      name: 'Bob',
      points: 4
   }

]

for(i = 0; i < players.length; i++){

   // return string of name property of object with highest value in points

}
</code>```

I'm not sure how to execute this inside the for loop

答:
You can reduce it

```<code>players.reduce((acc, obj)=>{
   return (acc.points || 0)<obj.points ? obj : acc;
},{})
</code>```

Body:
I have players containing multiple objects within. My end goal is to return the name property of the object with the highest points value.

For example this block should return a string of  Bob

const players = [

   {
      name: 'Jack',
      points: 3
   }

   {
      name: 'Jill',
      points: 2
   }

   {
      name: 'Bob',
      points: 4
   }

]

for(i = 0; i < players.length; i++){

   // return string of name property of object with highest value in points

}

I'm not sure how to execute this inside the for loop

Body:
You can reduce it

players.reduce((acc, obj)=>{
   return (acc.points || 0)<obj.points ? obj : acc;
},{})


问:
Extracting XML elements from a UIWebView
I'm writing a Bible Memory app for the IPhone and I need some help with picking out verses displayed in a UIWebView.

I have an xml file which is read into the UIWebView, and I need to be able to tell when a user taps on a specific verse. Here's a sample of the xml file:

```<code><bible translation="KJV">
<testament name="Old">
    <book name="Genesis">
        <chapter number="1">
            <verse number="1">In the beginning God created the heaven and the earth.</verse>
            <verse number="2">And the earth was without form, and void; and darkness was upon the face of the deep. And the Spirit of God moved upon the face of the waters.</verse>
            <verse number="3">And God said, Let there be light: and there was light.</verse>
            <verse number="4">And God saw the light, that it was good: and God divided the light from the darkness.</verse>
            <verse number="5">And God called the light Day, and the darkness he called Night. And the evening and the morning were the first day.</verse>
</code>```

In relation to the code above, if the user taps "In the beginning..." the program needs to know (at least) that the user just clicked a "verse" element and its "number = 1".

=================== EDITED ==========================

Here's my proposed solution..type..thingy.
Let me know how it sounds.

I still have the UIWebView reading the XML file. It is also being formatted my a CSS file in the bundle. Since UIWebViews take note of links (hrefs) [thanks Jonathan] I can add verse numbers in front of each tagged verse (I know its a little tedious, but I was planning on doing it anyway :)

This way, the xml file will look like this:

```<code><bible translation="KJV">
<testament name="Old">
    <book name="Genesis">
        <chapter number="1">
            <n>1</n><verse number="1">In the beginning God created the heaven and the earth.</verse>
            <n>2</n><verse number="2">And the earth was without form, and void; and darkness was upon the face of the deep. And the Spirit of God moved upon the face of the waters.</verse>
            <n>3</n><verse number="3">And God said, Let there be light: and there was light.</verse>
            <n>4</n><verse number="4">And God saw the light, that it was good: and God divided the light from the darkness.</verse>
            <n>5</n><verse number="5">And God called the light Day, and the darkness he called Night. And the evening and the morning were the first day.</verse>
            <n>6</n><verse number="6">And God said, Let there be a firmament in the midst of the waters, and let it divide the waters from the waters.</verse>
            <n>7</n><verse number="7">And God made the firmament, and divided the waters which were under the firmament from the waters which were above the firmament: and it was so.</verse>
</code>```

I'll either use css to force the 'n' tag as a link or just put 'href' elements instead.
This way, when the verse number, which will be shown before the verse, is tapped, I can fire a custom method to figure out where I am (what verse I'm in).
Here's a post I found about intercepting the firing of links in the UIWebView:
http://dblog.com.au/iphone-development/iphone-sdk-tip-firing-custom-events-when-a-link-is-clicked-in-a-uiwebview/

I'm hoping this will work, its a little ad-hockish.. but programs often begin that way.
Anyone try something like this before?

Don

答: The UIWebView delegate only responses to links (hrefs), so this might be a problem. In theory you could work around this by doing some hit-detection, but it would be more advisable (plus you'll sleep better at night :D ) to parse the XML and load it into a UITableView, much more maintainable and wayyyy more user friendly.</p>

Body:
I'm writing a Bible Memory app for the IPhone and I need some help with picking out verses displayed in a UIWebView.

I have an xml file which is read into the UIWebView, and I need to be able to tell when a user taps on a specific verse. Here's a sample of the xml file:

<bible translation="KJV">
<testament name="Old">
    <book name="Genesis">
        <chapter number="1">
            <verse number="1">In the beginning God created the heaven and the earth.</verse>
            <verse number="2">And the earth was without form, and void; and darkness was upon the face of the deep. And the Spirit of God moved upon the face of the waters.</verse>
            <verse number="3">And God said, Let there be light: and there was light.</verse>
            <verse number="4">And God saw the light, that it was good: and God divided the light from the darkness.</verse>
            <verse number="5">And God called the light Day, and the darkness he called Night. And the evening and the morning were the first day.</verse>

In relation to the code above, if the user taps "In the beginning..." the program needs to know (at least) that the user just clicked a "verse" element and its "number = 1".

=================== EDITED ==========================

Here's my proposed solution..type..thingy.
Let me know how it sounds.

I still have the UIWebView reading the XML file. It is also being formatted my a CSS file in the bundle. Since UIWebViews take note of links (hrefs) [thanks Jonathan] I can add verse numbers in front of each tagged verse (I know its a little tedious, but I was planning on doing it anyway :)

This way, the xml file will look like this:

<bible translation="KJV">
<testament name="Old">
    <book name="Genesis">
        <chapter number="1">
            <n>1</n><verse number="1">In the beginning God created the heaven and the earth.</verse>
            <n>2</n><verse number="2">And the earth was without form, and void; and darkness was upon the face of the deep. And the Spirit of God moved upon the face of the waters.</verse>
            <n>3</n><verse number="3">And God said, Let there be light: and there was light.</verse>
            <n>4</n><verse number="4">And God saw the light, that it was good: and God divided the light from the darkness.</verse>
            <n>5</n><verse number="5">And God called the light Day, and the darkness he called Night. And the evening and the morning were the first day.</verse>
            <n>6</n><verse number="6">And God said, Let there be a firmament in the midst of the waters, and let it divide the waters from the waters.</verse>
            <n>7</n><verse number="7">And God made the firmament, and divided the waters which were under the firmament from the waters which were above the firmament: and it was so.</verse>

I'll either use css to force the 'n' tag as a link or just put 'href' elements instead.
This way, when the verse number, which will be shown before the verse, is tapped, I can fire a custom method to figure out where I am (what verse I'm in).
Here's a post I found about intercepting the firing of links in the UIWebView:
http://dblog.com.au/iphone-development/iphone-sdk-tip-firing-custom-events-when-a-link-is-clicked-in-a-uiwebview/

I'm hoping this will work, its a little ad-hockish.. but programs often begin that way.
Anyone try something like this before?

Don


问:
Fixed: Angular 9: Undecorated base classes that use Angular features
I have recently updated to Angular v9 and as defined in the change-log, it's deprecated to have an undecorated base class that uses Angular features or is extended by a directive or component.

So I have many mixins in my application something like this:

Destroy:

```<code>export const Destroy = <T extends Constructor>(base: T = class {} as T) =>
  class extends base implements OnDestroy {
    destroy$ = new Subject<boolean>();

    ngOnDestroy(): void {
      this.destroy$.next(true);
      this.destroy$.complete();
    }
  };
</code>```

Scroll:

```<code>export const Scroll = <T extends Constructor>(base: T = class {
} as T) =>
  class extends base {
    public scrollToFirstError(form: FormGroup, scrollSelector?: string) {
      form.markAllAsTouched();
      const target = jQuery('.ng-invalid:not("form")').first();
      const scrollContainer = jQuery(scrollSelector || 'html,body');
      const subHeaderHeight = scrollSelector ? 0 : Number.parseInt(getComputedStyle(document.documentElement)
        .getPropertyValue('--height').trim(), 10);
      scrollContainer.animate(
        { scrollTop: jQuery(target).offset().top - jQuery(scrollContainer).offset().top - subHeaderHeight - 50 }, 'slow');
      target.focus();
    }
  };
</code>```

Extending it in my component like,

```<code>export class ComponentA extends Destroy(Scroll)
</code>```

and trying to access the properties of these mixins throws the following errors:

```<code>this.apiService.getData().pipe(takeUntil(this.destroy$)... // Property 'destroy$' does not exist on type 'ComponentA'.

this.scrollToFirstError(this.form, '.modal'); // Property 'scrollToFirstError' does not exist on type 'ComponentA'.
</code>```

Can anyone please help me with a suggestion to get it resolved? Thanks in advance!

******** Update *********

In my component:

```<code>export const MixinedClasses: any = Destroy(Scroll());

  @Component({
  selector: 'app-loan-list',
  templateUrl: './loan-list.component.html',
  styleUrls: ['./loan-list.component.scss']
})
export class Component extends MixinedClasses {}
</code>```

答:
Just convert Destroy and Scroll into @component decorated components and it should work fine.

Add:

```<code>// Destroy const becomes a decorated class
  @Component({
  selector: 'app-destroy'
})
export class Destroy implements OnDestroy{}

// Scroll const becomes a decorated class
  @Component({
  selector: 'app-scroll'
})
export class Scroll{}
</code>```

This just an idea, you'll have to make it right for your particular implementation.

To be honest I don't quite follow the way you were extending them with passing base in as a parameter, so you might need to rethink the whole approach using standard classes.

Body:
I have recently updated to Angular v9 and as defined in the change-log, it's deprecated to have an undecorated base class that uses Angular features or is extended by a directive or component.

So I have many mixins in my application something like this:

Destroy:

export const Destroy = <T extends Constructor>(base: T = class {} as T) =>
  class extends base implements OnDestroy {
    destroy$ = new Subject<boolean>();

    ngOnDestroy(): void {
      this.destroy$.next(true);
      this.destroy$.complete();
    }
  };

Scroll:

export const Scroll = <T extends Constructor>(base: T = class {
} as T) =>
  class extends base {
    public scrollToFirstError(form: FormGroup, scrollSelector?: string) {
      form.markAllAsTouched();
      const target = jQuery('.ng-invalid:not("form")').first();
      const scrollContainer = jQuery(scrollSelector || 'html,body');
      const subHeaderHeight = scrollSelector ? 0 : Number.parseInt(getComputedStyle(document.documentElement)
        .getPropertyValue('--height').trim(), 10);
      scrollContainer.animate(
        { scrollTop: jQuery(target).offset().top - jQuery(scrollContainer).offset().top - subHeaderHeight - 50 }, 'slow');
      target.focus();
    }
  };

Extending it in my component like,

export class ComponentA extends Destroy(Scroll)

and trying to access the properties of these mixins throws the following errors:

this.apiService.getData().pipe(takeUntil(this.destroy$)... // Property 'destroy$' does not exist on type 'ComponentA'.

this.scrollToFirstError(this.form, '.modal'); // Property 'scrollToFirstError' does not exist on type 'ComponentA'.

Can anyone please help me with a suggestion to get it resolved? Thanks in advance!

******** Update *********

In my component:

export const MixinedClasses: any = Destroy(Scroll());

  @Component({
  selector: 'app-loan-list',
  templateUrl: './loan-list.component.html',
  styleUrls: ['./loan-list.component.scss']
})
export class Component extends MixinedClasses {}

Body:
Just convert Destroy and Scroll into @component decorated components and it should work fine.

Add:

// Destroy const becomes a decorated class
  @Component({
  selector: 'app-destroy'
})
export class Destroy implements OnDestroy{}

// Scroll const becomes a decorated class
  @Component({
  selector: 'app-scroll'
})
export class Scroll{}

This just an idea, you'll have to make it right for your particular implementation.

To be honest I don't quite follow the way you were extending them with passing base in as a parameter, so you might need to rethink the whole approach using standard classes.


问:
Replace div element with html()
I have a problem replacing div element with ajax. The idea is start/stop button. There's a list of card elements on the page, each with its own button. Both buttons are stored in separate html files.

work_order_start.html:

```<code><div type="button" class="repairToggle" order_id="{{ order.id }}" func="start">
  <svg>...</svg>
</div>
</code>```

work_order_pause.html:

```<code><div type="button" class="repairToggle" order_id="{{ order.id }}" func="stop">
  <svg>...</svg>
</div>
</code>```

Initially only one is rendered on the page based of if condition:

```<code>{% if order.status == 'DN' %}
  {% include 'mtn/work_order_pause.html' %}
{% else %}
  {% include 'mtn/work_order_start.html' %}
{% endif %}
</code>```

Here's my script:

```<code>    var btns = document.querySelectorAll(".repairToggle");
    for (i = 0; i < btns.length; i++) {
      btns[i].addEventListener("click", manageOrderStatus);
    }
    function manageOrderStatus() {
      var order_id = this.getAttribute("order_id");
      var func = this.getAttribute("func");
      if(func == 'start'){
        var endpoint = "{% url 'ajax_start_order' %}";
      } else {
        var endpoint = "{% url 'ajax_stop_order' %}";
      }
      $.ajax({
        url: endpoint,
        type: "GET",
        data: {
          'order_id': order_id,
        },
        success: function (data) {
          $(this).html(data);
        }
      });
    }
</code>```

and my views:

```<code>def start_repair(request):
    ...
    return render(request, 'mtn/work_order_pause.html')

def end_repair(request):
    ...
    return render(request, 'mtn/work_order_start.html')
</code>```

The view executes correctly, but $(this).html(data); doesn't replace one div with another. What am i doing wrong?

答: $(this) refers to ajax context. You need to store $(this) in one variable outside of ajax call. Probably this will solve your problem. Without full code, not able to figure out. Check if this works </p>

Title: Replace div element with html()

Body:
I have a problem replacing div element with ajax. The idea is start/stop button. There's a list of card elements on the page, each with its own button. Both buttons are stored in separate html files.

work_order_start.html:

  <svg>...</svg>

work_order_pause.html:

  <svg>...</svg>

Initially only one is rendered on the page based of if condition:

{% if order.status == 'DN' %}
  {% include 'mtn/work_order_pause.html' %}
{% else %}
  {% include 'mtn/work_order_start.html' %}
{% endif %}

Here's my script:

    var btns = document.querySelectorAll(".repairToggle");
    for (i = 0; i < btns.length; i++) {
      btns[i].addEventListener("click", manageOrderStatus);
    }
    function manageOrderStatus() {
      var order_id = this.getAttribute("order_id");
      var func = this.getAttribute("func");
      if(func == 'start'){
        var endpoint = "{% url 'ajax_start_order' %}";
      } else {
        var endpoint = "{% url 'ajax_stop_order' %}";
      }
      $.ajax({
        url: endpoint,
        type: "GET",
        data: {
          'order_id': order_id,
        },
        success: function (data) {
          $(this).html(data);
        }
      });
    }

and my views:

def start_repair(request):
    ...
    return render(request, 'mtn/work_order_pause.html')

def end_repair(request):
    ...
    return render(request, 'mtn/work_order_start.html')

The view executes correctly, but $(this).html(data); doesn't replace one div with another. What am i doing wrong?


问:
How to handle online captchas in WebDriver
Like: 1+ 7 =

A website has a text box and this text box will accept the input of sum of two numbers. How we capture these two number like 1 and 7. And any number can be come at this location.

Please help me out.

答:
I prefer a manual solution, like this:</p>
```<code>input_captcha = input("Entered CAPTCHA Code is: ")
browser.find_element_by_id("j_captcha").send_keys(input_captcha)
</code>```

Body:
I prefer a manual solution, like this:

input_captcha = input("Entered CAPTCHA Code is: ")
browser.find_element_by_id("j_captcha").send_keys(input_captcha)


问:
Python: select specific entries of a list
Say

a = [1,2,3,4,5,6,7]

If I want to select the elements 0 to 4 of that I can do so by

a[0:3]

Now what I would like to do is to select, say, the first, third and fourth element with a similar command. So I would like to build the list [2,4,5] by a command such as

a[???]

What would I have to fill in for the ????

(I do not want to do [a[1],a[3],a[4]], since in my case a is the return of the function, and only want to call it once.)

Thanks for suggestions!

答:
```<code>x = a[1] + a[3:5]
</code>```

I think shorter version doesn't exist.

Body:
x = a[1] + a[3:5]

I think shorter version doesn't exist.


问:
firebase console not showing my App Crash report
I added firebase crashlytics to my app before two days ago .
Our app yesterday 10 times crashed this report i saw today in my play
console. But my firebase console not showing this data. what is the reason?

Firebase console now  showing me progress bar continues, but is not showing any report.

At the time of adding firebase crashlytics to project i followed steps from official documentation from https://firebase.google.com/docs/crashlytics/get-started?authuser=0&platform=android

答:
Crash reports are uploaded almost in real-time after your app crashes and relaunches. If you are still unable to see your crash reports, then likely your Crashlytics integration is off.

If you followed all of the documentation correctly that you linked, then you would need to contact Firebase support so they could take a look at your gradle files, and how you're calling Crashlytics in your app.


问:
Using Android to submit to a Google Spreadsheet Form
First time asking a question here. Usually I can find my answer without having to ask, but this time I'm stuck and can't figure out what I'm missing.

I'm just trying to have my Android app fill out a form on a website and submit it. I don't need the app to do anything with any data being sent back, just fill out the form and submit it. Basically I'm trying to collect the results of a voting app. I thought form submission would be simple so I created a Google Spreadsheet and made a form out of it. I figured I'd point the Android app to the form and then I would have all the data in the spreadsheet for later viewing. I can't get the Android app to actually fill out the form though. Here's the resources.

Form

Spreadsheet

```<code>private void submitVote(String outcome) {
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost("https://spreadsheets.google.com/spreadsheet/formResponse?hl=en_US&formkey=dDlwZzh4bGFvNFBxUmRsR0d2VTVhYnc6MQ&ifq");

    List<BasicNameValuePair> results = new ArrayList<BasicNameValuePair>();
    results.add(new BasicNameValuePair("entry.0.single", cardOneURL));
    results.add(new BasicNameValuePair("entry.1.single", outcome));
    results.add(new BasicNameValuePair("entry.2.single", cardTwoURL));

    try {
        post.setEntity(new UrlEncodedFormEntity(results));
    } catch (UnsupportedEncodingException e) {
        // Auto-generated catch block
        Log.e("YOUR_TAG", "An error has occurred", e);
    }
    try {
        client.execute(post);
    } catch (ClientProtocolException e) {
        // Auto-generated catch block
        Log.e("YOUR_TAG", "An error has occurred", e);
    } catch (IOException e) {
        // Auto-generated catch block
        Log.e("YOUR_TAG", "An error has occurred", e);
    }
}
</code>```

I made both the form and the spreadsheet public so feel free to mess around with it and try and get it to work yourself.

I get no errors from my program, no compile errors, no errors in DDMS. When I actually run the program and click the button that executes this code I can see the delay since right now this is in the UI thread, so I know it's executing it. It appears as if everything is working perfectly, but my spreadsheet doesn't update at all.

Any thoughts? I'm sure it's something stupid that I'm missing, but any help would be appreciated.

Here's the updated code with lots of logging and debugging stuff.

```<code>private void submitVote(String outcome) {
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost("https://spreadsheets.google.com/spreadsheet/formResponse?hl=en_US&formkey=dDlwZzh4bGFvNFBxUmRsR0d2VTVhYnc6MQ&ifq");

    List<BasicNameValuePair> results = new ArrayList<BasicNameValuePair>();
    results.add(new BasicNameValuePair("entry.0.single", cardOneURL));
    results.add(new BasicNameValuePair("entry.1.single", outcome));
    results.add(new BasicNameValuePair("entry.2.single", cardTwoURL));

    try {
        post.setEntity(new UrlEncodedFormEntity(results));
    } catch (UnsupportedEncodingException e) {
        // Auto-generated catch block
        Log.e("YOUR_TAG", "An error has occurred", e);
    }
    try {
        HttpResponse httpResponse = client.execute(post);
        Log.e("RESPONSE", "info: " + httpResponse);

        BufferedReader rd = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
        String line;
        while ((line = rd.readLine()) != null) {
        Log.i("words", line);
        }

        Intent intent = new Intent(this, ReadingView.class);
        intent.putExtra("html", line);
        startActivity(intent);
    } catch (ClientProtocolException e) {
        // Auto-generated catch block
        Log.e("YOUR_TAG", "client protocol exception", e);
    } catch (IOException e) {
        // Auto-generated catch block
        Log.e("YOUR_TAG", "io exception", e);
    }
}
</code>```

I use ReadingView.class for something else in my app, but hijacked it for this logging purpose right now. It only has an onCreate() method, which is below.

```<code>public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.readingview);

    WebView mWebView = (WebView) findViewById(R.id.webview);
    mWebView.getSettings().setJavaScriptEnabled(true);
    //mWebView.loadUrl(getIntent().getExtras().getString("url"));
    mWebView.loadData(getIntent().getExtras().getString("html"), "text/html", "utf-8");
}
</code>```

Also worth noting that in the DDMS it only logs one output of line. I believe this is just because the html code is returned all as one line. Correct me if I'm wrong.

答:
So I finally figured out what was going on. Through messing with manually encoding answers to the end of the form POST url I was able to find that the url it gave when viewing the source had encoding issues of it's own in it.

Here's the url from source:

```<code><form action="https://spreadsheets.google.com/spreadsheet/formResponse?hl=en_US&formkey=dDlwZzh4bGFvNFBxUmRsR0d2VTVhYnc6MQ&ifq" method="POST" id="ss-form">
</code>```

But here's what it needs to be to actually work in the above code:

```<code>https://spreadsheets.google.com/spreadsheet/formResponse?hl=en_US&formkey=dDlwZzh4bGFvNFBxUmRsR0d2VTVhYnc6MQ
</code>```

The extra amp; was what was messing it up. For whatever reason it works without the last &ifq too, so I left that off. Anyway, here's completed code:

```<code>private void submitVote(String outcome) {
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost("https://spreadsheets.google.com/spreadsheet/formResponse?hl=en_US&formkey=dDlwZzh4bGFvNFBxUmRsR0d2VTVhYnc6MQ");

    List<BasicNameValuePair> results = new ArrayList<BasicNameValuePair>();
    results.add(new BasicNameValuePair("entry.0.single", cardOneURL));
    results.add(new BasicNameValuePair("entry.1.single", outcome));
    results.add(new BasicNameValuePair("entry.2.single", cardTwoURL));

    try {
        post.setEntity(new UrlEncodedFormEntity(results));
    } catch (UnsupportedEncodingException e) {
        // Auto-generated catch block
        Log.e("YOUR_TAG", "An error has occurred", e);
    }
    try {
        client.execute(post);
    } catch (ClientProtocolException e) {
        // Auto-generated catch block
        Log.e("YOUR_TAG", "client protocol exception", e);
    } catch (IOException e) {
        // Auto-generated catch block
        Log.e("YOUR_TAG", "io exception", e);
    }
}
</code>```

Hope this helps someone else when trying to work with Google Spreadsheet Forms. And thanks to @pandre for pointing me in the right direction.

Body:
First time asking a question here. Usually I can find my answer without having to ask, but this time I'm stuck and can't figure out what I'm missing.

I'm just trying to have my Android app fill out a form on a website and submit it. I don't need the app to do anything with any data being sent back, just fill out the form and submit it. Basically I'm trying to collect the results of a voting app. I thought form submission would be simple so I created a Google Spreadsheet and made a form out of it. I figured I'd point the Android app to the form and then I would have all the data in the spreadsheet for later viewing. I can't get the Android app to actually fill out the form though. Here's the resources.

Form

Spreadsheet

private void submitVote(String outcome) {
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost("https://spreadsheets.google.com/spreadsheet/formResponse?hl=en_US&formkey=dDlwZzh4bGFvNFBxUmRsR0d2VTVhYnc6MQ&ifq");

    List<BasicNameValuePair> results = new ArrayList<BasicNameValuePair>();
    results.add(new BasicNameValuePair("entry.0.single", cardOneURL));
    results.add(new BasicNameValuePair("entry.1.single", outcome));
    results.add(new BasicNameValuePair("entry.2.single", cardTwoURL));

    try {
        post.setEntity(new UrlEncodedFormEntity(results));
    } catch (UnsupportedEncodingException e) {
        // Auto-generated catch block
        Log.e("YOUR_TAG", "An error has occurred", e);
    }
    try {
        client.execute(post);
    } catch (ClientProtocolException e) {
        // Auto-generated catch block
        Log.e("YOUR_TAG", "An error has occurred", e);
    } catch (IOException e) {
        // Auto-generated catch block
        Log.e("YOUR_TAG", "An error has occurred", e);
    }
}

I made both the form and the spreadsheet public so feel free to mess around with it and try and get it to work yourself.

I get no errors from my program, no compile errors, no errors in DDMS. When I actually run the program and click the button that executes this code I can see the delay since right now this is in the UI thread, so I know it's executing it. It appears as if everything is working perfectly, but my spreadsheet doesn't update at all.

Any thoughts? I'm sure it's something stupid that I'm missing, but any help would be appreciated.

Here's the updated code with lots of logging and debugging stuff.

private void submitVote(String outcome) {
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost("https://spreadsheets.google.com/spreadsheet/formResponse?hl=en_US&formkey=dDlwZzh4bGFvNFBxUmRsR0d2VTVhYnc6MQ&ifq");

    List<BasicNameValuePair> results = new ArrayList<BasicNameValuePair>();
    results.add(new BasicNameValuePair("entry.0.single", cardOneURL));
    results.add(new BasicNameValuePair("entry.1.single", outcome));
    results.add(new BasicNameValuePair("entry.2.single", cardTwoURL));

    try {
        post.setEntity(new UrlEncodedFormEntity(results));
    } catch (UnsupportedEncodingException e) {
        // Auto-generated catch block
        Log.e("YOUR_TAG", "An error has occurred", e);
    }
    try {
        HttpResponse httpResponse = client.execute(post);
        Log.e("RESPONSE", "info: " + httpResponse);

        BufferedReader rd = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
        String line;
        while ((line = rd.readLine()) != null) {
        Log.i("words", line);
        }

        Intent intent = new Intent(this, ReadingView.class);
        intent.putExtra("html", line);
        startActivity(intent);
    } catch (ClientProtocolException e) {
        // Auto-generated catch block
        Log.e("YOUR_TAG", "client protocol exception", e);
    } catch (IOException e) {
        // Auto-generated catch block
        Log.e("YOUR_TAG", "io exception", e);
    }
}

I use ReadingView.class for something else in my app, but hijacked it for this logging purpose right now. It only has an onCreate() method, which is below.

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.readingview);

    WebView mWebView = (WebView) findViewById(R.id.webview);
    mWebView.getSettings().setJavaScriptEnabled(true);
    //mWebView.loadUrl(getIntent().getExtras().getString("url"));
    mWebView.loadData(getIntent().getExtras().getString("html"), "text/html", "utf-8");
}

Also worth noting that in the DDMS it only logs one output of line. I believe this is just because the html code is returned all as one line. Correct me if I'm wrong.

Body:
So I finally figured out what was going on. Through messing with manually encoding answers to the end of the form POST url I was able to find that the url it gave when viewing the source had encoding issues of it's own in it.

Here's the url from source:

<form action="https://spreadsheets.google.com/spreadsheet/formResponse?hl=en_US&amp;formkey=dDlwZzh4bGFvNFBxUmRsR0d2VTVhYnc6MQ&amp;ifq" method="POST" id="ss-form">

But here's what it needs to be to actually work in the above code:

https://spreadsheets.google.com/spreadsheet/formResponse?hl=en_US&formkey=dDlwZzh4bGFvNFBxUmRsR0d2VTVhYnc6MQ

The extra amp; was what was messing it up. For whatever reason it works without the last &ifq too, so I left that off. Anyway, here's completed code:

private void submitVote(String outcome) {
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost("https://spreadsheets.google.com/spreadsheet/formResponse?hl=en_US&formkey=dDlwZzh4bGFvNFBxUmRsR0d2VTVhYnc6MQ");

    List<BasicNameValuePair> results = new ArrayList<BasicNameValuePair>();
    results.add(new BasicNameValuePair("entry.0.single", cardOneURL));
    results.add(new BasicNameValuePair("entry.1.single", outcome));
    results.add(new BasicNameValuePair("entry.2.single", cardTwoURL));

    try {
        post.setEntity(new UrlEncodedFormEntity(results));
    } catch (UnsupportedEncodingException e) {
        // Auto-generated catch block
        Log.e("YOUR_TAG", "An error has occurred", e);
    }
    try {
        client.execute(post);
    } catch (ClientProtocolException e) {
        // Auto-generated catch block
        Log.e("YOUR_TAG", "client protocol exception", e);
    } catch (IOException e) {
        // Auto-generated catch block
        Log.e("YOUR_TAG", "io exception", e);
    }
}

Hope this helps someone else when trying to work with Google Spreadsheet Forms. And thanks to @pandre for pointing me in the right direction.


问:
I have a problem with the in django search function
I have a problem with my search function.
He's tasked to search for movies by name
and I don't know how to write it and it works

My Views:

```<code>class AllMovies(ListView):
    model = Movie
    template_name = 'All_movies.html'
    cats = Category.objects.all()

    def get_context_data(self, *args, **kwargs):
        cat_menu = Category.objects.all()
        search_term = ''
        context = super(AllMovies, self).get_context_data(*args, **kwargs)
        context["cat_menu"] = cat_menu
        return context

    def search(request):  # wszytskie filmy (lista)
        movier = Movie.objects.all()

        search_term = ''
        if 'search' in request.GET:
            search_term = request.GET['search']
            movier = Movie.objects.filter(name__icontains=search_term)
        paginator = Paginator(movier, 30)
        page = request.GET.get('page')
        movier = paginator.get_page(page)
        get_dict_copy = request.GET.copy()
        params = get_dict_copy.pop('page', True) and get_dict_copy.urlencode()

        return render(request, 'AllMovies.html',
              {'movie': movie, 'params': params, 'search_term': search_term})
</code>```

Here, two functions should be divided and combined, but I don't know how

My urls:

```<code>   path("AllMovies/", AllMovies.as_view(), name="AllMovies"),
</code>```

My templates:

```<code>    <form class="form-inline">
             <input class="form-control mr-sm-2 " align="middle" type="search" placeholder="Name Movie"
                     aria-label="Search" name='search' value = "{{ search_term }}">
              <button class="btn btn-success my-2 my-sm-0" type="submit">Search</button>
     </form>
</code>```

The most important thing is for the search engine to work.
Help me!

答:
The ListView does not look at a method search, regardless of what you write, it will not be triggered.

You can filter the list of objects to return by overriding the .get_queryset(…) method [Django-doc]:

```<code>class AllMovies(ListView):
    model = Movie
    template_name = 'All_movies.html'
    paginate_by= 30
    context_object_name = 'movie'

    def get_context_data(self, *args, **kwargs):
        get_dict_copy = request.GET.copy()
        get_dict_copy.pop('page', True)
        return super().get_context_data(
            *args,
            **kwargs,
            cat_menu=Category.objects.all(),
            search_term=self.request.GET.get('search', '')
            params=get_dict_copy.urlencode()
        )

    def <b>get_queryset</b>(self, *args, **kwargs):
        qs = super().get_queryset(*args, **kwargs)
        if 'search' in self.request.GET:
            search_term = self.request.GET['search']
            return qs.filter(name__icontains=search_term)
        return qs</code>```

Body:
I have a problem with my search function.
He's tasked to search for movies by name
and I don't know how to write it and it works

My Views:

class AllMovies(ListView):
    model = Movie
    template_name = 'All_movies.html'
    cats = Category.objects.all()

    def get_context_data(self, *args, **kwargs):
        cat_menu = Category.objects.all()
        search_term = ''
        context = super(AllMovies, self).get_context_data(*args, **kwargs)
        context["cat_menu"] = cat_menu
        return context

    def search(request):  # wszytskie filmy (lista)
        movier = Movie.objects.all()

        search_term = ''
        if 'search' in request.GET:
            search_term = request.GET['search']
            movier = Movie.objects.filter(name__icontains=search_term)
        paginator = Paginator(movier, 30)
        page = request.GET.get('page')
        movier = paginator.get_page(page)
        get_dict_copy = request.GET.copy()
        params = get_dict_copy.pop('page', True) and get_dict_copy.urlencode()

        return render(request, 'AllMovies.html',
              {'movie': movie, 'params': params, 'search_term': search_term})

Here, two functions should be divided and combined, but I don't know how

My urls:

   path("AllMovies/", AllMovies.as_view(), name="AllMovies"),

My templates:

    <form class="form-inline">
             <input class="form-control mr-sm-2 " align="middle" type="search" placeholder="Name Movie"
                     aria-label="Search" name='search' value = "{{ search_term }}">
              <button class="btn btn-success my-2 my-sm-0" type="submit">Search</button>
     </form>

The most important thing is for the search engine to work.
Help me!

Body:
The ListView does not look at a method search, regardless of what you write, it will not be triggered.

You can filter the list of objects to return by overriding the .get_queryset(…) method [Django-doc]:

class AllMovies(ListView):
    model = Movie
    template_name = 'All_movies.html'
    paginate_by= 30
    context_object_name = 'movie'

    def get_context_data(self, *args, **kwargs):
        get_dict_copy = request.GET.copy()
        get_dict_copy.pop('page', True)
        return super().get_context_data(
            *args,
            **kwargs,
            cat_menu=Category.objects.all(),
            search_term=self.request.GET.get('search', '')
            params=get_dict_copy.urlencode()
        )

    def get_queryset(self, *args, **kwargs):
        qs = super().get_queryset(*args, **kwargs)
        if 'search' in self.request.GET:
            search_term = self.request.GET['search']
            return qs.filter(name__icontains=search_term)
        return qs


问:
JSONP http request gives 404 in Angular
I have been working with mailchimp integration into angular application and for using it in pure JS, I have got the code from embedded form in mailchimp site and the code as follows,

<link href="//cdn-images.mailchimp.com/embedcode/classic-10_7.css" rel="stylesheet" type="text/css">

<form action="https://gmail.us10.list-manage.com/subscribe/post?u=aaa7182511d7bd278fb9d510d&id=01681f1b55" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>

Subscribe

* indicates required

 Email Address  *

 <input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL">

<input type="text" name="b_aaa7182511d7bd278fb9d510d_01681f1b55" tabindex="-1" value="">

<input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button">

</form>

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

<p>The above code works fine and no issues.. The same thing needs to be included in angular application for which my try as follows,</p>

<p><strong>Reference</strong> I took: https://gist.github.com/inorganik/846c52550db97454646054270e4f1270</p>

<p>And the implementation as follows,</p>

<p><strong>app.component.ts</strong></p>

```import { Component, OnInit, OnDestroy } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { HttpClient, HttpParams } from '@angular/common/http';

interface MailChimpResponse {
  result: string;
  msg: string;
}

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
submitted = false;
  mailChimpEndpoint =
    'https://gmail.us10.list-manage.com/subscribe/post?u=aaa7182511d7bd278fb9d510d&id=01681f1b55';
  error = '';

  constructor(private http: HttpClient) {}

  userForm: FormGroup;

  ngOnInit(): void {
    this.userForm = new FormGroup({
      email: new FormControl('', [
           Validators.required,
            Validators.email,
        ]),
    });
  }

  subscribeEmail() {
    this.error = '';

        if (this.userForm.controls.email.status === 'VALID') {

      const params = new HttpParams()
                .set('EMAIL', this.userForm.controls.email.value)
      console.log(params);
            const mailChimpUrl = this.mailChimpEndpoint + params.toString();

            this.http.jsonp<MailChimpResponse>(mailChimpUrl, 'callback').subscribe(response => {
        console.log('response ', response)
                if (response.result && response.result !== 'error') {
                    this.submitted = true;
                }
                else {
                    this.error = response.msg;
                }
            }, error => {
                console.error(error);
                this.error = 'Sorry, an error occurred.';
            });
        }
  }
}
```

Working Stackblitz here ..

My requirement is the above code which works in the snippet doesn't work in angular application and it results in 404 error..

Please take a look at network/console tab in developer tool which gives 404..

Also I could notice that the param which I pass in to the url doesn't reflect in query param of network call..

Please help me to implement the same api url which works in click of subscribe button to be working in angular application as well.

Take a look at stackblitz please: https://stackblitz.com/edit/angular-jsonp-gfzdr1

答:
You are not sending the parameters properly.  Here is a working example that will send the request.  It does still return an error, but it is a response from MailChimp that you have processed too many records.

Working Version: https://stackblitz.com/edit/angular-jsonp-1qquhy

Title: JSONP http request gives 404 in Angular

Body:
I have been working with mailchimp integration into angular application and for using it in pure JS, I have got the code from embedded form in mailchimp site and the code as follows,

<link href="//cdn-images.mailchimp.com/embedcode/classic-10_7.css" rel="stylesheet" type="text/css">

<form action="https://gmail.us10.list-manage.com/subscribe/post?u=aaa7182511d7bd278fb9d510d&id=01681f1b55" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>

Subscribe

* indicates required

 Email Address  *

 <input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL">

<input type="text" name="b_aaa7182511d7bd278fb9d510d_01681f1b55" tabindex="-1" value="">

<input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button">

</form>

The above code works fine and no issues.. The same thing needs to be included in angular application for which my try as follows,

Reference I took: https://gist.github.com/inorganik/846c52550db97454646054270e4f1270

And the implementation as follows,

app.component.ts

import { Component, OnInit, OnDestroy } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { HttpClient, HttpParams } from '@angular/common/http';

interface MailChimpResponse {
  result: string;
  msg: string;
}

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
submitted = false;
  mailChimpEndpoint =
    'https://gmail.us10.list-manage.com/subscribe/post?u=aaa7182511d7bd278fb9d510d&id=01681f1b55';
  error = '';

  constructor(private http: HttpClient) {}

  userForm: FormGroup;

  ngOnInit(): void {
    this.userForm = new FormGroup({
      email: new FormControl('', [
           Validators.required,
            Validators.email,
        ]),
    });
  }

  subscribeEmail() {
    this.error = '';

        if (this.userForm.controls.email.status === 'VALID') {

      const params = new HttpParams()
                .set('EMAIL', this.userForm.controls.email.value)
      console.log(params);
            const mailChimpUrl = this.mailChimpEndpoint + params.toString();

            this.http.jsonp<MailChimpResponse>(mailChimpUrl, 'callback').subscribe(response => {
        console.log('response ', response)
                if (response.result && response.result !== 'error') {
                    this.submitted = true;
                }
                else {
                    this.error = response.msg;
                }
            }, error => {
                console.error(error);
                this.error = 'Sorry, an error occurred.';
            });
        }
  }
}

Working Stackblitz here ..

My requirement is the above code which works in the snippet doesn't work in angular application and it results in 404 error..

Please take a look at network/console tab in developer tool which gives 404..

Also I could notice that the param which I pass in to the url doesn't reflect in query param of network call..

Please help me to implement the same api url which works in click of subscribe button to be working in angular application as well.

Take a look at stackblitz please: https://stackblitz.com/edit/angular-jsonp-gfzdr1


问:
OAuth 2.0 Flow with Firebase Functions
How do I use Firebase Functions to successfully connect to an OAuth 2.0 app (ex: Alpaca)? The closest I've found is this GCP tutorial but it doesn't save the access token for future use.

How do I:

Remember the state (random string used to protect against request forgery attacks) across different Firestore Functions so I can determine whether it's unchanged?

Associate the access token with the user that authorized me (ideally saving the token in Firestore)?

Is there a library that does all this for me that will work from a Firebase Function?

答:
I followed a lot of the instructions from this guide. Here are the answers to my original questions for posterity:

(Remembering state) Generate it on the client side and save somewhere (I used localStorage). Pass the state to a Firebase function that generates your authorization url and returns it to the client.

(Saving access token) After authorization I redirect back to the client side (as opposed to a Firebase function). From the client I parse the auth code and check if state matches. I pass the authorization code to a Firebase Function to configure the request for the final access token. Since I called the function from the client I have access to the context param that tells me the uid associated with the access token.

Title: OAuth 2.0 Flow with Firebase Functions


问:
Why do we write [0] after get_or_create in model_name.object.get_or_create() in django
A function in Faker script to add data in my model Department.

department = ['I.T.','C.S.E','M.E.','E.C.']
def add_dept():
    d = Department.objects.get_or_create(dept_name=random.choice(depatment))[0]

答: The function you're calling returns a list or a tuple. In either case, the [0] simply extracts the first element from the result, and throws any remaining results away.</p>


答:
This is because get_or_create returns a tuple and you're usually only interested in the gotten or created object (first element) and not the boolean indicating if the object was just created (second element).

From the documentation on get_or_create:

Returns a tuple of (object, created), where object is the retrieved or created object and created is a boolean specifying whether a new object was created.

Though you can also use the syntax:

def add_dept():
    d, _ = Department.objects.get_or_create(dept_name=random.choice(depatment))
```

Title: Why do we write [0] after get_or_create in model_name.object.get_or_create() in django

Body:
A function in Faker script to add data in my model Department.

department = ['I.T.','C.S.E','M.E.','E.C.']
def add_dept():
    d = Department.objects.get_or_create(dept_name=random.choice(depatment))[0]