问:
StoreKit In App Purchases seem to be crashing on specific iPhone models?
I'm trying to identify a problem that seems to be happening on iPhone 6's but not iPhone 7's. Whenever one of my iPhone 6 users taps on the button to load my in app purchase data and display the actual in app purchase, it crashes for them. This doesn't seem to be the problem for people running iPhone 7s. I can't tell if the problem is per device model or something else

I have a function called constructPurchasePanel() which brings up a panel displaying my in app purchases. The title of my in app purchases is grabbed from an array of products I have stored in my Menu Scene (which is a singleton)

constructPurchasePanel() code

```<code>nameLabel.text = SceneCoordinator.shared.menuScene?.products[2].localizedTitle
nameLabel2.text = SceneCoordinator.shared.menuScene?.products[1].localizedTitle
nameLabel3.text = SceneCoordinator.shared.menuScene?.products[0].localizedTitle
</code>```

MenuScene products array initialization

```<code>var products = [SKProduct]()

MyProducts.store.requestProducts{success, products in
    if success {
       self.products = products!
    }
}
</code>```

requestProducts() function, and my other IAP related functions. 99% of this is from Ray Wenderlich's tutorial:

```<code>/*
 * Copyright (c) 2016 Razeware LLC
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

import StoreKit

public typealias ProductIdentifier = String
public typealias ProductsRequestCompletionHandler = (_ success: Bool, _ products: [SKProduct]?) -> ()

open class IAPHelper : NSObject  {

    static let IAPHelperPurchaseNotification = "IAPHelperPurchaseNotification"
    fileprivate let productIdentifiers: Set<ProductIdentifier>
    fileprivate var purchasedProductIdentifiers = Set<ProductIdentifier>()
    fileprivate var productsRequest: SKProductsRequest?
    fileprivate var productsRequestCompletionHandler: ProductsRequestCompletionHandler?

    public init(productIds: Set<ProductIdentifier>) {
        productIdentifiers = productIds
        for productIdentifier in productIds {
            let purchased = UserDefaults.standard.bool(forKey: productIdentifier)
            if purchased {
                purchasedProductIdentifiers.insert(productIdentifier)
                print("Previously purchased: \(productIdentifier)")
            } else {
                print("Not purchased: \(productIdentifier)")
            }
        }
        super.init()
        SKPaymentQueue.default().add(self)
    }

}

// MARK: - StoreKit API

extension IAPHelper {

    public func requestProducts(completionHandler: @escaping ProductsRequestCompletionHandler) {
        productsRequest?.cancel()
        productsRequestCompletionHandler = completionHandler

        productsRequest = SKProductsRequest(productIdentifiers: productIdentifiers)
        productsRequest!.delegate = self
        productsRequest!.start()
    }

    public func buyProduct(_ product: SKProduct) {
        print("Buying \(product.productIdentifier)...")
        let payment = SKPayment(product: product)
        SKPaymentQueue.default().add(payment)
    }

    public func isProductPurchased(_ productIdentifier: ProductIdentifier) -> Bool {
        return purchasedProductIdentifiers.contains(productIdentifier)
    }

    public class func canMakePayments() -> Bool {
        return SKPaymentQueue.canMakePayments()
    }

    public func restorePurchases() {
        SKPaymentQueue.default().restoreCompletedTransactions()
    }
}

// MARK: - SKProductsRequestDelegate

extension IAPHelper: SKProductsRequestDelegate {

    public func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
        let products = response.products
        print("Loaded list of products...")
        productsRequestCompletionHandler?(true, products)
        clearRequestAndHandler()

        for p in products {
            print("Found product: \(p.productIdentifier) \(p.localizedTitle) \(p.price.floatValue)")
        }
    }

    public func request(_ request: SKRequest, didFailWithError error: Error) {
        print("Failed to load list of products.")
        print("Error: \(error.localizedDescription)")
        productsRequestCompletionHandler?(false, nil)
        clearRequestAndHandler()
    }

    private func clearRequestAndHandler() {
        productsRequest = nil
        productsRequestCompletionHandler = nil
    }
}

// MARK: - SKPaymentTransactionObserver

extension IAPHelper: SKPaymentTransactionObserver {

    public func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
        for transaction in transactions {
            switch (transaction.transactionState) {
            case .purchased:
                complete(transaction: transaction)
                break
            case .failed:
                fail(transaction: transaction)
                break
            case .restored:
                restore(transaction: transaction)
                break
            case .deferred:
                break
            case .purchasing:
                break
            }
        }
    }

    private func applyEffect(productIdentifier: String) {
        switch(productIdentifier) {
        case StackyChefProducts.smallCoinPackage:
            SKTAudio.sharedInstance.playSoundEffect("Content/purchase.wav")

            Chef.sharedInstance.money += 30000
            SceneCoordinator.shared.shopScene?.updateBalance()
            for item in SceneCoordinator.shared.shopScene!.endlessItems { item.updateUI() }
            for item in SceneCoordinator.shared.shopScene!.upgradeItems { item.updateUI() }
        case StackyChefProducts.mediumCoinPackage:
            SKTAudio.sharedInstance.playSoundEffect("Content/purchase.wav")

            Chef.sharedInstance.money += 90000
            SceneCoordinator.shared.shopScene?.updateBalance()
            for item in SceneCoordinator.shared.shopScene!.endlessItems { item.updateUI() }
            for item in SceneCoordinator.shared.shopScene!.upgradeItems { item.updateUI() }
        case StackyChefProducts.largeCoinPackage:
            SKTAudio.sharedInstance.playSoundEffect("Content/purchase.wav")

            Chef.sharedInstance.money += 150000
            SceneCoordinator.shared.shopScene?.updateBalance()
            for item in SceneCoordinator.shared.shopScene!.endlessItems { item.updateUI() }
            for item in SceneCoordinator.shared.shopScene!.upgradeItems { item.updateUI() }
        case StackyChefProducts.removeAdsProduct:
            if GameData.sharedInstance.adsOn {
                SKTAudio.sharedInstance.playSoundEffect("Content/purchase.wav")

                GameData.sharedInstance.adsOn = false
                MenuScene.removeAds.removeFromParent()
                MenuScene.bannerView.removeFromSuperview()
            }
        case StackyChefProducts.couponProduct:
            SKTAudio.sharedInstance.playSoundEffect("Content/purchase.wav")

            GameData.sharedInstance.coupons += 1
            SceneCoordinator.shared.grabBagScene?.updateCouponButton()
            SceneCoordinator.shared.grabBagScene?.updateIAPButtons()
        case StackyChefProducts.couponsProduct:
            SKTAudio.sharedInstance.playSoundEffect("Content/purchase.wav")

            GameData.sharedInstance.coupons += 3
            SceneCoordinator.shared.grabBagScene?.updateCouponButton()
            SceneCoordinator.shared.grabBagScene?.updateIAPButtons()
        default:
            print("applyEffect() shouldn't reach this")
        }
    }

    private func complete(transaction: SKPaymentTransaction) {
        print("complete...")
        deliverPurchaseNotificationFor(identifier: transaction.payment.productIdentifier)
        SKPaymentQueue.default().finishTransaction(transaction)

        applyEffect(productIdentifier: transaction.payment.productIdentifier)
    }

    private func restore(transaction: SKPaymentTransaction) {
        guard let productIdentifier = transaction.original?.payment.productIdentifier else { return }

        print("restore... \(productIdentifier)")
        deliverPurchaseNotificationFor(identifier: productIdentifier)
        SKPaymentQueue.default().finishTransaction(transaction)

        applyEffect(productIdentifier: transaction.payment.productIdentifier)
    }

    private func fail(transaction: SKPaymentTransaction) {
        print("fail...")
        if let transactionError = transaction.error as NSError? {
            if transactionError.code != SKErrorCode.paymentCancelled.rawValue {
                print("Transaction Error: \(String(describing: transaction.error?.localizedDescription))")
            }
        }

        SKPaymentQueue.default().finishTransaction(transaction)
    }

    private func deliverPurchaseNotificationFor(identifier: String?) {
        guard let identifier = identifier else { return }

        purchasedProductIdentifiers.insert(identifier)
        UserDefaults.standard.set(true, forKey: identifier)
        UserDefaults.standard.synchronize()
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: IAPHelper.IAPHelperPurchaseNotification), object: identifier)
    }
}
</code>```

Does anyone have an idea of what could be causing this? What I think is happening is that constructPurchasePanel() gets called, and products array is empty, therefore causing the crash when I try to grab a title from one of the products. This mean something must be going wrong in requestProducts() I believe.

I know the products exist because this code works fine for me and others running iPhone 7s, and I can purchase an IAP with no trouble

EDIT:

After talking to some more users it doesn't seem like this is necessarily a device specific thing, so I'm not sure how it's crashing for some but working for others.

答:
The app crash because products not complete load at the time you call constructPurchasePanel()

You need load products before you use it:
SceneCoordinator.shared.menuScene?.products[2].localizedTitle

Like suggest from Ray Wenderlich's tutorial, make sure you requestProducts() function before, best solution is use in viewDidAppear method.

Body:
I'm trying to identify a problem that seems to be happening on iPhone 6's but not iPhone 7's. Whenever one of my iPhone 6 users taps on the button to load my in app purchase data and display the actual in app purchase, it crashes for them. This doesn't seem to be the problem for people running iPhone 7s. I can't tell if the problem is per device model or something else

I have a function called constructPurchasePanel() which brings up a panel displaying my in app purchases. The title of my in app purchases is grabbed from an array of products I have stored in my Menu Scene (which is a singleton)

constructPurchasePanel() code

nameLabel.text = SceneCoordinator.shared.menuScene?.products[2].localizedTitle
nameLabel2.text = SceneCoordinator.shared.menuScene?.products[1].localizedTitle
nameLabel3.text = SceneCoordinator.shared.menuScene?.products[0].localizedTitle

MenuScene products array initialization

var products = [SKProduct]()

MyProducts.store.requestProducts{success, products in
    if success {
       self.products = products!
    }
}

requestProducts() function, and my other IAP related functions. 99% of this is from Ray Wenderlich's tutorial:

/*
 * Copyright (c) 2016 Razeware LLC
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

import StoreKit

public typealias ProductIdentifier = String
public typealias ProductsRequestCompletionHandler = (_ success: Bool, _ products: [SKProduct]?) -> ()

open class IAPHelper : NSObject  {

    static let IAPHelperPurchaseNotification = "IAPHelperPurchaseNotification"
    fileprivate let productIdentifiers: Set<ProductIdentifier>
    fileprivate var purchasedProductIdentifiers = Set<ProductIdentifier>()
    fileprivate var productsRequest: SKProductsRequest?
    fileprivate var productsRequestCompletionHandler: ProductsRequestCompletionHandler?

    public init(productIds: Set<ProductIdentifier>) {
        productIdentifiers = productIds
        for productIdentifier in productIds {
            let purchased = UserDefaults.standard.bool(forKey: productIdentifier)
            if purchased {
                purchasedProductIdentifiers.insert(productIdentifier)
                print("Previously purchased: \(productIdentifier)")
            } else {
                print("Not purchased: \(productIdentifier)")
            }
        }
        super.init()
        SKPaymentQueue.default().add(self)
    }

}

// MARK: - StoreKit API

extension IAPHelper {

    public func requestProducts(completionHandler: @escaping ProductsRequestCompletionHandler) {
        productsRequest?.cancel()
        productsRequestCompletionHandler = completionHandler

        productsRequest = SKProductsRequest(productIdentifiers: productIdentifiers)
        productsRequest!.delegate = self
        productsRequest!.start()
    }

    public func buyProduct(_ product: SKProduct) {
        print("Buying \(product.productIdentifier)...")
        let payment = SKPayment(product: product)
        SKPaymentQueue.default().add(payment)
    }

    public func isProductPurchased(_ productIdentifier: ProductIdentifier) -> Bool {
        return purchasedProductIdentifiers.contains(productIdentifier)
    }

    public class func canMakePayments() -> Bool {
        return SKPaymentQueue.canMakePayments()
    }

    public func restorePurchases() {
        SKPaymentQueue.default().restoreCompletedTransactions()
    }
}

// MARK: - SKProductsRequestDelegate

extension IAPHelper: SKProductsRequestDelegate {

    public func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
        let products = response.products
        print("Loaded list of products...")
        productsRequestCompletionHandler?(true, products)
        clearRequestAndHandler()

        for p in products {
            print("Found product: \(p.productIdentifier) \(p.localizedTitle) \(p.price.floatValue)")
        }
    }

    public func request(_ request: SKRequest, didFailWithError error: Error) {
        print("Failed to load list of products.")
        print("Error: \(error.localizedDescription)")
        productsRequestCompletionHandler?(false, nil)
        clearRequestAndHandler()
    }

    private func clearRequestAndHandler() {
        productsRequest = nil
        productsRequestCompletionHandler = nil
    }
}

// MARK: - SKPaymentTransactionObserver

extension IAPHelper: SKPaymentTransactionObserver {

    public func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
        for transaction in transactions {
            switch (transaction.transactionState) {
            case .purchased:
                complete(transaction: transaction)
                break
            case .failed:
                fail(transaction: transaction)
                break
            case .restored:
                restore(transaction: transaction)
                break
            case .deferred:
                break
            case .purchasing:
                break
            }
        }
    }

    private func applyEffect(productIdentifier: String) {
        switch(productIdentifier) {
        case StackyChefProducts.smallCoinPackage:
            SKTAudio.sharedInstance.playSoundEffect("Content/purchase.wav")

            Chef.sharedInstance.money += 30000
            SceneCoordinator.shared.shopScene?.updateBalance()
            for item in SceneCoordinator.shared.shopScene!.endlessItems { item.updateUI() }
            for item in SceneCoordinator.shared.shopScene!.upgradeItems { item.updateUI() }
        case StackyChefProducts.mediumCoinPackage:
            SKTAudio.sharedInstance.playSoundEffect("Content/purchase.wav")

            Chef.sharedInstance.money += 90000
            SceneCoordinator.shared.shopScene?.updateBalance()
            for item in SceneCoordinator.shared.shopScene!.endlessItems { item.updateUI() }
            for item in SceneCoordinator.shared.shopScene!.upgradeItems { item.updateUI() }
        case StackyChefProducts.largeCoinPackage:
            SKTAudio.sharedInstance.playSoundEffect("Content/purchase.wav")

            Chef.sharedInstance.money += 150000
            SceneCoordinator.shared.shopScene?.updateBalance()
            for item in SceneCoordinator.shared.shopScene!.endlessItems { item.updateUI() }
            for item in SceneCoordinator.shared.shopScene!.upgradeItems { item.updateUI() }
        case StackyChefProducts.removeAdsProduct:
            if GameData.sharedInstance.adsOn {
                SKTAudio.sharedInstance.playSoundEffect("Content/purchase.wav")

                GameData.sharedInstance.adsOn = false
                MenuScene.removeAds.removeFromParent()
                MenuScene.bannerView.removeFromSuperview()
            }
        case StackyChefProducts.couponProduct:
            SKTAudio.sharedInstance.playSoundEffect("Content/purchase.wav")

            GameData.sharedInstance.coupons += 1
            SceneCoordinator.shared.grabBagScene?.updateCouponButton()
            SceneCoordinator.shared.grabBagScene?.updateIAPButtons()
        case StackyChefProducts.couponsProduct:
            SKTAudio.sharedInstance.playSoundEffect("Content/purchase.wav")

            GameData.sharedInstance.coupons += 3
            SceneCoordinator.shared.grabBagScene?.updateCouponButton()
            SceneCoordinator.shared.grabBagScene?.updateIAPButtons()
        default:
            print("applyEffect() shouldn't reach this")
        }
    }

    private func complete(transaction: SKPaymentTransaction) {
        print("complete...")
        deliverPurchaseNotificationFor(identifier: transaction.payment.productIdentifier)
        SKPaymentQueue.default().finishTransaction(transaction)

        applyEffect(productIdentifier: transaction.payment.productIdentifier)
    }

    private func restore(transaction: SKPaymentTransaction) {
        guard let productIdentifier = transaction.original?.payment.productIdentifier else { return }

        print("restore... \(productIdentifier)")
        deliverPurchaseNotificationFor(identifier: productIdentifier)
        SKPaymentQueue.default().finishTransaction(transaction)

        applyEffect(productIdentifier: transaction.payment.productIdentifier)
    }

    private func fail(transaction: SKPaymentTransaction) {
        print("fail...")
        if let transactionError = transaction.error as NSError? {
            if transactionError.code != SKErrorCode.paymentCancelled.rawValue {
                print("Transaction Error: \(String(describing: transaction.error?.localizedDescription))")
            }
        }

        SKPaymentQueue.default().finishTransaction(transaction)
    }

    private func deliverPurchaseNotificationFor(identifier: String?) {
        guard let identifier = identifier else { return }

        purchasedProductIdentifiers.insert(identifier)
        UserDefaults.standard.set(true, forKey: identifier)
        UserDefaults.standard.synchronize()
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: IAPHelper.IAPHelperPurchaseNotification), object: identifier)
    }
}

Does anyone have an idea of what could be causing this? What I think is happening is that constructPurchasePanel() gets called, and products array is empty, therefore causing the crash when I try to grab a title from one of the products. This mean something must be going wrong in requestProducts() I believe.

I know the products exist because this code works fine for me and others running iPhone 7s, and I can purchase an IAP with no trouble

EDIT:

After talking to some more users it doesn't seem like this is necessarily a device specific thing, so I'm not sure how it's crashing for some but working for others.


来源: stackexchange

问:
Find Textbox control
In my application i have 50 textboxes i want find all the textbox control using the code and i want to perform a color change in the textbox after doing certain validations. How can i acheive that? i used the following code but it doesnt work properly

```<code>foreach (Control cntrl in Page.Controls)
    {
        if (cntrl is TextBox)
        {
            //Do the operation
        }
    }
</code>```

<%@ Page Language="C#" MasterPageFile="~/HomePageMaster.master" AutoEventWireup="true"
    CodeFile="Default.aspx.cs" Inherits="Default" Title="Sample Page" %>

答: You will probably have to recursively go through each container. This article has one method of doing it.</p>

ContentLicense: CC BY-SA 2.5

Title: Find Textbox control

Body:
In my application i have 50 textboxes i want find all the textbox control using the code and i want to perform a color change in the textbox after doing certain validations. How can i acheive that? i used the following code but it doesnt work properly

foreach (Control cntrl in Page.Controls)
    {
        if (cntrl is TextBox)
        {
            //Do the operation
        }
    }

<%@ Page Language="C#" MasterPageFile="~/HomePageMaster.master" AutoEventWireup="true"
    CodeFile="Default.aspx.cs" Inherits="Default" Title="Sample Page" %>


问:
Array Insertion Postgres
I have a table item with attributes no(integer) and price(integer), also another table cart with attributes no(integer) and items(array of item).

I have some records in items.

When i tried :

```<code>INSERT INTO myschema.cart VALUES(1,'{SELECT item from myschema.item}')
</code>```

I'am getting error malformed record literal.

I expected this to insert all items from myschema.item into the cart record.

答:
It's hard to give you exact statement without the table structures and such, but you can select into an array:

```<code>INSERT INTO myschema.cart (id, item_ids)
SELECT 1, array(SELECT id from myschema.item)
</code>```

This will select the id's from the item table into an array.

You can test it out by writing:

select array(SELECT id from myschema.item)

ContentLicense: CC BY-SA 3.0

Title: Array Insertion Postgres

Body:
I have a table item with attributes no(integer) and price(integer), also another table cart with attributes no(integer) and items(array of item).

I have some records in items.

When i tried :

INSERT INTO myschema.cart VALUES(1,'{SELECT item from myschema.item}')

I'am getting error malformed record literal.

I expected this to insert all items from myschema.item into the cart record.

Body:
It's hard to give you exact statement without the table structures and such, but you can select into an array:

INSERT INTO myschema.cart (id, item_ids)
SELECT 1, array(SELECT id from myschema.item)

This will select the id's from the item table into an array.

You can test it out by writing:

select array(SELECT id from myschema.item)


问:
Active choices parameter
I have active choices parameter installed in my Jenkins. Here I have to choose a value from the text file stored locally and then display this as a multi select option to the user.
For example, my text file can have an entry 1 - abc, 2 - def. The user has to see both the entries and can select either of them or both of them. This text file is maintained manually. I can have a third entry 3 - ghi and when I trigger the Jenkins job, I should see all the 3 entries.

Can anyone please help me out here?

Thank you in advance,
Rohit

答:
You can use a groovy script to parse file and return options, something like:

```<code>def list = []
File textfile= new File("path-to-file")
textfile.eachline { line ->
    //assuming you want only text values without a number
    list.add(line.split('-')[1]) }
return list
</code>```

Also choose "choice type" for multiple values.

Title: Active choices parameter

Body:
You can use a groovy script to parse file and return options, something like:

def list = []
File textfile= new File("path-to-file")
textfile.eachline { line ->
    //assuming you want only text values without a number
    list.add(line.split('-')[1]) }
return list

Also choose "choice type" for multiple values.


问:
How to I set the Connection : Keep-Alive header to Close in the JsonServiceClient?
On occasion (not consistently), I'm receiving a "The underlying connection was closed: A connection that was expected to be kept alive was closed by the server" exception thrown by an instance of the JsonServiceClient.  I want to set the Http Connection Header to Close.

When I attempt client.Headers["Connection"] = "Close"; "I get a The 'Connection' header must be modified using the appropriate property or method.\r\nParameter name: name" exception.

答:
you can Just use this to close the connection
{Connection: close};</p>


问:
How pass variable to vue-router v-link
I have a vue component to render nav list, and pass nav list, each item includes title and link:

```<code><template>
  <ul>
    <li v-for="item in list"><a v-link="{{ path: item.link }}"></a></li>
  </ul>
</template>

<script>
  export default {
    props: ['list']
  }
</script>
</code>```

I try pass variable item.link to v-link path, but failed.

get this warn:

```<code>[Vue warn]: v-link="{{ path: item.link }}": attribute interpolation is not allowed in Vue.js directives and special attributes.
</code>```

what should i do if pass variable to v-link path?

thanks for reading :)

答:
I used the following with vue-router 2.x:

```<code><router-link :to="{path: '/applications/' + currentApplicationId}" class="nav-link">Overview</router-link>
</code>```

More documentation can be found here.

Title: How pass variable to vue-router v-link

Body:
I have a vue component to render nav list, and pass nav list, each item includes title and link:

<template>

</template>

I try pass variable item.link to v-link path, but failed.

get this warn:

[Vue warn]: v-link="{{ path: item.link }}": attribute interpolation is not allowed in Vue.js directives and special attributes.

what should i do if pass variable to v-link path?

thanks for reading :)

Body:
I used the following with vue-router 2.x:

<router-link :to="{path: '/applications/' + currentApplicationId}" class="nav-link">Overview</router-link>

More documentation can be found here.


问:
Designing models with multiple (optional?) inheritance in Entity Framework
I am struggling for the last couple of days on an idea of how to model these entities in EF. So I decided to ask the community to lend a hand. :-) The core classes are given below.

```<code>class BaseEntity
{
   long Id;
   DateTime DateCreated;
}

class Person : BaseEntity
{
   string Name;
   string Address;
}

class Taxpayer : Person
{
    string TaxpayerIdentificationNumber;
    double Income;
    Taxpayer(or Person) Spouse;
}

class Client : BaseEntity
{
    string CustomerId;
    string ContactNumber;
}

class Partnership : Client
{
    List<Taxpayer (or Person)> Partners;
}

class Company : Client
{
    string CompanyRegistrationNumber;
}
</code>```

The scenario is, a Client can be one of the 3 types i.e. Taxpayer, Partnership, Company (Specialization/IsA).

The problem is, in the case of the Taxpayer class he should inherit both the properties of Client and Person classes. (UPDATE: A taxpayer can be a client but not necessarily) Also in the other places Taxpayer class is used, most of the time it can be either a Person class or Taxpayer class.

Any ideas on how to proceed?

Thanks.

答:
you might need to give a thought to interfaces instead of classes. Following example could help a bit:</p>

```<code>interface IBaseEntity
    {
        long Id;
        DateTime DateCreated;
    }

    interface IPerson : IBaseEntity
    {
        string Name;
        string Address;
    }

    interface IClient : IBaseEntity
    {
        string CustomerId;
        string ContactNumber;
    }

    class Taxpayer : IClient, IPerson
    {
        string TaxpayerIdentificationNumber;
        double Income;
        Taxpayer Spouse;
    }

    class Partnership : IClient
    {
        List<Taxpayer> Partners;
    }

    class Company : IClient
    {
        string CompanyRegistrationNumber;
    }
</code>```

Body:
I am struggling for the last couple of days on an idea of how to model these entities in EF. So I decided to ask the community to lend a hand. :-) The core classes are given below.

class BaseEntity
{
   long Id;
   DateTime DateCreated;
}

class Person : BaseEntity
{
   string Name;
   string Address;
}

class Taxpayer : Person
{
    string TaxpayerIdentificationNumber;
    double Income;
    Taxpayer(or Person) Spouse;
}

class Client : BaseEntity
{
    string CustomerId;
    string ContactNumber;
}

class Partnership : Client
{
    List<Taxpayer (or Person)> Partners;
}

class Company : Client
{
    string CompanyRegistrationNumber;
}

The scenario is, a Client can be one of the 3 types i.e. Taxpayer, Partnership, Company (Specialization/IsA).

The problem is, in the case of the Taxpayer class he should inherit both the properties of Client and Person classes. (UPDATE: A taxpayer can be a client but not necessarily) Also in the other places Taxpayer class is used, most of the time it can be either a Person class or Taxpayer class.

Any ideas on how to proceed?

Thanks.

Body:
you might need to give a thought to interfaces instead of classes. Following example could help a bit:

interface IBaseEntity
    {
        long Id;
        DateTime DateCreated;
    }

    interface IPerson : IBaseEntity
    {
        string Name;
        string Address;
    }

    interface IClient : IBaseEntity
    {
        string CustomerId;
        string ContactNumber;
    }

    class Taxpayer : IClient, IPerson
    {
        string TaxpayerIdentificationNumber;
        double Income;
        Taxpayer Spouse;
    }

    class Partnership : IClient
    {
        List<Taxpayer> Partners;
    }

    class Company : IClient
    {
        string CompanyRegistrationNumber;
    }


问:
How to specify custom corpus path in Django for Chatterbot?
It seems one can use custom corpus json files by specify a path to the location. However, I'm confused by how that is done. The example provided by chatterbot isn't very clear.

http://chatterbot.readthedocs.io/en/stable/training.html

they do.

```<code>"./data/my_corpus/"
</code>```

does the ./ mean root with a folder named data inside? If so what is root? My django app?

And in the other line they directly refrence the .json file? They also seem to do .corpus.json? Is that the correct file name scheme? Do I need both lines? Its very confusing not a lot of clarity.

Is there a clear example of how to do this?

答:
Training data ( training_data ) accepts list of files. You can mention that file like this... <your_app or directory>/folders...

```<code>backend
|___ corbus/data/introduction.py
    |___ __init__.py

project
|___ settings.py
</code>```

then in your settings you can mention the training data file by

```<code>'training_data': [
    'chatterbot.corpus.english',
    'backend/corpus/data/introduction/'
]
</code>```

Body:
It seems one can use custom corpus json files by specify a path to the location. However, I'm confused by how that is done. The example provided by chatterbot isn't very clear.

http://chatterbot.readthedocs.io/en/stable/training.html

they do.

"./data/my_corpus/"

does the ./ mean root with a folder named data inside? If so what is root? My django app?

And in the other line they directly refrence the .json file? They also seem to do .corpus.json? Is that the correct file name scheme? Do I need both lines? Its very confusing not a lot of clarity.

Is there a clear example of how to do this?

Body:
Training data ( training_data ) accepts list of files. You can mention that file like this... <your_app or directory>/folders...

backend
|___ corbus/data/introduction.py
    |___ __init__.py

project
|___ settings.py

then in your settings you can mention the training data file by

'training_data': [
    'chatterbot.corpus.english',
    'backend/corpus/data/introduction/'
]


问:
Add image overlay to specific category thumbnails - wordpress
Aloha Stack overflow! so ive been trying many ways to add an image overlay to specific a category thumbnails in wordpress.

Pretty much i just want a banner image that lays diagonal across all the thumbnails of one particular category. I dont need this banner to show on any other category but that one.

Ive tried a couple of banner plugins etc, but none of them are able too add the banner overlay only to the one worpress category thumbnails.

Any tips on how i can go about implementing this?

I had this feature on my old theme, but now ive upgraded i cant work out how to get the same here.

I can provide any css or code needed. Would love to hear from some amazing folks on this one, stackoverflow never lets me down

答:
Try the following concept:

.thumbnail {
  position: relative;
}

.thumbnail:after {
  position: absolute;
  top: 0;
  left: 0;
  content: url('http://placehold.it/200/000');
  opacity: 0.5;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="thumbnail">
  <img src="http://placehold.it/200" />
</div></code>```

Body:
Try the following concept:

.thumbnail {
  position: relative;
}

.thumbnail:after {
  position: absolute;
  top: 0;
  left: 0;
  content: url('http://placehold.it/200/000');
  opacity: 0.5;
}

<div class="thumbnail">
  <img src="http://placehold.it/200" />
</div>


问:
How to Make Scipy Dendrogram Read Japanese Words/Terms
I am trying to conduct hierarchical clustering through Japanese words/terms and using scipy.cluster.hierarchy.dendrogram to plot the results. However, the plot cannot show the Japanese words/terms but instead use small rectangles. At first, I was thinking this may be because when I create the dictionary, the keys are unicode not Japanese (as the question I asked here). Then I was suggested to use Python3 to solve such issue and I finally make the dictionary key in Japanese words instead of unicode (as the question I ask here). However, it turns out that even if I feed the label parameter of scipy.cluster.hierarchy.dendrogram with Japanese words/terms, the plot still cannot show those words. I have checked several similar posts but it seems like there is still no clear solution. My codes are as follows:

```<code>import pandas as pd
import numpy as np
from sklearn import decomposition
from sklearn.cluster import AgglomerativeClustering as hicluster
from scipy.spatial.distance import cdist, pdist
from scipy import sparse as sp ## Sparse Matrix
from scipy.cluster.hierarchy import dendrogram
import matplotlib as mpl
import matplotlib.pyplot as plt
plt.style.use('ggplot')

## Import Data
allWrdMat10 = pd.read_csv("../../data/allWrdMat10.csv.gz",
    encoding='CP932')

## Set X as CSR Sparse Matrix
X = np.array(allWrdMat10)
X = sp.csr_matrix(X)

def plot_dendrogram(model, **kwargs):
    # Children of hierarchical clustering
    children = model.children_

    # Distances between each pair of children
    # Since we don't have this information, we can use a uniform one
      for plotting
    distance = np.arange(children.shape[0])

    # The number of observations contained in each cluster level
    no_of_observations = np.arange(2, children.shape[0]+2)

    # Create linkage matrix and then plot the dendrogram
    linkage_matrix = np.column_stack([children, distance,
        no_of_observations]).astype(float)

    # Plot the corresponding dendrogram
    dendrogram(linkage_matrix, **kwargs)

dict_index = {t:i for i,t in enumerate(allWrdMat10.columns)}

dictlist = []
temp = []
akey = []
avalue = []

for key, value in dict_index.items():
    akey.append(key)
    avalue.append(value)
    temp = [key,value]
    dictlist.append(temp)

avalue = np.array(avalue)

X_transform = X[:, avalue < 1000].transpose().toarray()

freq1000terms = akey
freq1000terms = np.array(freq1000terms)[avalue < 1000]

hicl_ward = hicluster(n_clusters=40,linkage='ward', compute_full_tree =
    False)
hiclwres = hicl_ward.fit(X_transform)

plt.rcParams["figure.figsize"] = (15,6)

model1 = hiclwres
plt.title('Hierarchical Clustering Dendrogram (Ward Linkage)')
plot_dendrogram(model1, p = 40, truncate_mode = 'lastp', orientation =
    'top', labels=freq1000terms[model1.labels_], color_threshold = 991)
plt.ylim(959,1000)
plt.show()
</code>```

答:
You need to give matplotlib a valid font to display Japanese characters with. You can find the available fonts from your system by using the following code:

```<code>import matplotlib.font_manager
matplotlib.font_manager.findSystemFonts(fontpaths=None)
</code>```

It will give you a list of system fonts that matplotlib can use:

```<code>['c:\\windows\\fonts\\seguisli.ttf',
 'C:\\WINDOWS\\Fonts\\BOD_R.TTF',
 'C:\\WINDOWS\\Fonts\\GILC____.TTF',
 'c:\\windows\\fonts\\segoewp-light.ttf',
 'c:\\windows\\fonts\\glsnecb.ttf',
 ...
 ...
 'c:\\windows\\fonts\\elephnti.ttf',
 'C:\\WINDOWS\\Fonts\\COPRGTB.TTF']
</code>```

Pick a font that supports Japanese character encoding, and give it as a parameter to matplotlib at the beginning of your code as following:

```<code>import matplotlib.pyplot as plt
plt.rcParams["font.family"] = "Yu Gothic" # I.E Yu Gothic, supports shift-jis
</code>```

This is a global parameter setting, other plots on the same project will also use the same font family. If you want to change it for a single text, you can use font properties of matplotlib text object.

Also: If you can't find/see an appropriate font you can download a font like code2000, install it and use it the same way. (For the font to show up at the list, you may need to clear matplotlib's cache)

Body:
I am trying to conduct hierarchical clustering through Japanese words/terms and using scipy.cluster.hierarchy.dendrogram to plot the results. However, the plot cannot show the Japanese words/terms but instead use small rectangles. At first, I was thinking this may be because when I create the dictionary, the keys are unicode not Japanese (as the question I asked here). Then I was suggested to use Python3 to solve such issue and I finally make the dictionary key in Japanese words instead of unicode (as the question I ask here). However, it turns out that even if I feed the label parameter of scipy.cluster.hierarchy.dendrogram with Japanese words/terms, the plot still cannot show those words. I have checked several similar posts but it seems like there is still no clear solution. My codes are as follows:

import pandas as pd
import numpy as np
from sklearn import decomposition
from sklearn.cluster import AgglomerativeClustering as hicluster
from scipy.spatial.distance import cdist, pdist
from scipy import sparse as sp ## Sparse Matrix
from scipy.cluster.hierarchy import dendrogram
import matplotlib as mpl
import matplotlib.pyplot as plt
plt.style.use('ggplot')

## Import Data
allWrdMat10 = pd.read_csv("../../data/allWrdMat10.csv.gz",
    encoding='CP932')

## Set X as CSR Sparse Matrix
X = np.array(allWrdMat10)
X = sp.csr_matrix(X)

def plot_dendrogram(model, **kwargs):
    # Children of hierarchical clustering
    children = model.children_

    # Distances between each pair of children
    # Since we don't have this information, we can use a uniform one
      for plotting
    distance = np.arange(children.shape[0])

    # The number of observations contained in each cluster level
    no_of_observations = np.arange(2, children.shape[0]+2)

    # Create linkage matrix and then plot the dendrogram
    linkage_matrix = np.column_stack([children, distance,
        no_of_observations]).astype(float)

    # Plot the corresponding dendrogram
    dendrogram(linkage_matrix, **kwargs)

dict_index = {t:i for i,t in enumerate(allWrdMat10.columns)}

dictlist = []
temp = []
akey = []
avalue = []

for key, value in dict_index.items():
    akey.append(key)
    avalue.append(value)
    temp = [key,value]
    dictlist.append(temp)

avalue = np.array(avalue)

X_transform = X[:, avalue < 1000].transpose().toarray()

freq1000terms = akey
freq1000terms = np.array(freq1000terms)[avalue < 1000]

hicl_ward = hicluster(n_clusters=40,linkage='ward', compute_full_tree =
    False)
hiclwres = hicl_ward.fit(X_transform)

plt.rcParams["figure.figsize"] = (15,6)

model1 = hiclwres
plt.title('Hierarchical Clustering Dendrogram (Ward Linkage)')
plot_dendrogram(model1, p = 40, truncate_mode = 'lastp', orientation =
    'top', labels=freq1000terms[model1.labels_], color_threshold = 991)
plt.ylim(959,1000)
plt.show()

Body:
You need to give matplotlib a valid font to display Japanese characters with. You can find the available fonts from your system by using the following code:

import matplotlib.font_manager
matplotlib.font_manager.findSystemFonts(fontpaths=None)

It will give you a list of system fonts that matplotlib can use:

['c:\\windows\\fonts\\seguisli.ttf',
 'C:\\WINDOWS\\Fonts\\BOD_R.TTF',
 'C:\\WINDOWS\\Fonts\\GILC____.TTF',
 'c:\\windows\\fonts\\segoewp-light.ttf',
 'c:\\windows\\fonts\\glsnecb.ttf',
 ...
 ...
 'c:\\windows\\fonts\\elephnti.ttf',
 'C:\\WINDOWS\\Fonts\\COPRGTB.TTF']

Pick a font that supports Japanese character encoding, and give it as a parameter to matplotlib at the beginning of your code as following:

import matplotlib.pyplot as plt
plt.rcParams["font.family"] = "Yu Gothic" # I.E Yu Gothic, supports shift-jis

This is a global parameter setting, other plots on the same project will also use the same font family. If you want to change it for a single text, you can use font properties of matplotlib text object.

Also: If you can't find/see an appropriate font you can download a font like code2000, install it and use it the same way. (For the font to show up at the list, you may need to clear matplotlib's cache)


问:
Autofill method of range class failed - help needed for my code
I've been trying to make this work. It worked fine on my x64 version of office but not the x86 on my colleagues' computers. Can anyone gimme a fix please?

The VBA engine highlighted Range("AV5").AutoFill Destination:=Range("AV5:AV" & NoOfClients) as the cause

```<code>Private Sub Check_Cases_Click()
Dim NoOfClients As Long

Application.DisplayAlerts = False
CO_Select = Application.InputBox("Please input the name of caseworker you would like to check on.", "Caseworker Name")
Range("A2").value = CO_Select

Application.ScreenUpdating = False
NoOfClients = Range("C2").value
CO_Name = Range("A2").value

CheckCaseMsg = MsgBox(CO_Name & ", there are " & NoOfClients & " clients under your name." & vbNewLine & vbNewLine & _
                    "System will now calculate all your active cases and display " & vbNewLine & _
                    "all the clients for your information." & vbNewLine & vbNewLine & _
                    "Confirm?", vbYesNo, "Case Checking")

If CheckCaseMsg = vbNo Then
Exit Sub
End If

If CheckCaseMsg = vbYes Then

'Remove the filters if one exists
'=========================================
If ActiveSheet.FilterMode Then
Selection.AutoFilter
End If

Clear
Startup_Formula

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

Range("AV5").AutoFill Destination:=Range("AV5:AV" & NoOfClients)

Application.Calculation = xlCalculationAutomatic

Range("GI_Table[[#All],[Client number]]").Copy
Range("GI_Table[[#All],[Client number]]").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False

Application.ScreenUpdating = True

ActiveSheet.ListObjects("GI_Table").Range.AutoFilter Field:=2, Criteria1:= _
        Array("ACTIVE", "INACTIVE", "RENEWED"), Operator:=xlFilterValues

GI_CustomSort
GI_CustomSort

MsgBox "Case Checking Ready", vbInformation, "Ready"
End If

Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
</code>```

答:
You will get the Autofill method of range class failed error if the value of NoOfClients is 5. The end row is the same as the start row. Here is a simple way to reproduce the error.

```<code>Sub Sample()
    NoOfClients = 5

    Range("AV5").AutoFill Destination:=Range("AV5:AV" & NoOfClients)
End Sub
</code>```

An alternative to .Autofill is to directly write to the range. For ex:

```<code>Range("AV5:AV" & NoOfClients).Formula = Range("AV5").Formula
</code>```

Body:
I've been trying to make this work. It worked fine on my x64 version of office but not the x86 on my colleagues' computers. Can anyone gimme a fix please?

The VBA engine highlighted Range("AV5").AutoFill Destination:=Range("AV5:AV" & NoOfClients) as the cause

Private Sub Check_Cases_Click()
Dim NoOfClients As Long

Application.DisplayAlerts = False
CO_Select = Application.InputBox("Please input the name of caseworker you would like to check on.", "Caseworker Name")
Range("A2").value = CO_Select

Application.ScreenUpdating = False
NoOfClients = Range("C2").value
CO_Name = Range("A2").value

CheckCaseMsg = MsgBox(CO_Name & ", there are " & NoOfClients & " clients under your name." & vbNewLine & vbNewLine & _
                    "System will now calculate all your active cases and display " & vbNewLine & _
                    "all the clients for your information." & vbNewLine & vbNewLine & _
                    "Confirm?", vbYesNo, "Case Checking")

If CheckCaseMsg = vbNo Then
Exit Sub
End If

If CheckCaseMsg = vbYes Then

'Remove the filters if one exists
'=========================================
If ActiveSheet.FilterMode Then
Selection.AutoFilter
End If

Clear
Startup_Formula

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

Range("AV5").AutoFill Destination:=Range("AV5:AV" & NoOfClients)

Application.Calculation = xlCalculationAutomatic

Range("GI_Table[[#All],[Client number]]").Copy
Range("GI_Table[[#All],[Client number]]").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False

Application.ScreenUpdating = True

ActiveSheet.ListObjects("GI_Table").Range.AutoFilter Field:=2, Criteria1:= _
        Array("ACTIVE", "INACTIVE", "RENEWED"), Operator:=xlFilterValues

GI_CustomSort
GI_CustomSort

MsgBox "Case Checking Ready", vbInformation, "Ready"
End If

Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub

Body:
You will get the Autofill method of range class failed error if the value of NoOfClients is 5. The end row is the same as the start row. Here is a simple way to reproduce the error.

Sub Sample()
    NoOfClients = 5

    Range("AV5").AutoFill Destination:=Range("AV5:AV" & NoOfClients)
End Sub

An alternative to .Autofill is to directly write to the range. For ex:

Range("AV5:AV" & NoOfClients).Formula = Range("AV5").Formula


问:
Update a table column using a mapping table?
I have three tables: a, b, c. Table b is a mapping table for table a and table c. I am trying to update table a column = table c column.

When implementing the update, I receive an error:

[S0001][4104] The multi-part identifier could not be bound

```<code>UPDATE table_a
SET table_a.Sector = table_c.Sector
FROM table_a
INNER JOIN table_b
  ON table_a.business_ID = cast(table_b.business_id as BIGINT)
INNER JOIN table_c
  ON table_b.ACARA_SML_ID = table_c.ACARA_SML_ID
WHERE a.State = 'ABC';
</code>```

答:
In your WHERE clause you are using a.State, here a was not set as table alias for any of the table.

Can you try this query with correct table alias:

```<code>UPDATE A
SET Sector = C.Sector
FROM table_a A
INNER JOIN table_b B ON A.business_ID = CAST(B.business_id AS BIGINT)
INNER JOIN table_c C ON B.ACARA_SML_ID = C.ACARA_SML_ID
WHERE A.[STATE] = 'ABC';
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have three tables: a, b, c. Table b is a mapping table for table a and table c. I am trying to update table a column = table c column.

When implementing the update, I receive an error:

[S0001][4104] The multi-part identifier could not be bound

UPDATE table_a
SET table_a.Sector = table_c.Sector
FROM table_a
INNER JOIN table_b
  ON table_a.business_ID = cast(table_b.business_id as BIGINT)
INNER JOIN table_c
  ON table_b.ACARA_SML_ID = table_c.ACARA_SML_ID
WHERE a.State = 'ABC';

Body:
In your WHERE clause you are using a.State, here a was not set as table alias for any of the table.

Can you try this query with correct table alias:

UPDATE A
SET Sector = C.Sector
FROM table_a A
INNER JOIN table_b B ON A.business_ID = CAST(B.business_id AS BIGINT)
INNER JOIN table_c C ON B.ACARA_SML_ID = C.ACARA_SML_ID
WHERE A.[STATE] = 'ABC';


问:
The final field cannot be assigned, for an interface
I have a class Product and an interface LargeProduct. Product implements LargeProduct.

LargeProduct has a variable height which has getter and setter methods which have to be implemented in the Product class.

The height variable in LargeProduct is defined like so:

```<code>public int height = null;
</code>```

The getter method works fine:

```<code>public int getHeight() {
    return height;
}
</code>```

But the setter method does not:

```<code>public void setHeight(int height) {
    this.height = height;
}
</code>```

Errors:

```<code>The final field LargeProduct.height cannot be assigned
The static field LargeProduct.height should be accessed in a static way
</code>```

I'm not sure which error it's actually giving.. I'm using Eclipse and when I hover it gives the first error, and at the bottom of the window it gives the second error.

答:
The height variable in LargeProduct is
  defined like so:

```<code>public int height = null;
</code>```

Variables defined in interfaces are implicitly static and final, i.e. constants. That's what the compiler complains about.

You cannot define an instance variable in an interface. Just leave it out - the get and set methods ensure that the classes can be used as intended. The actual variable is an implementation detail if the implementing classes.

Body:
I have a class Product and an interface LargeProduct. Product implements LargeProduct.

LargeProduct has a variable height which has getter and setter methods which have to be implemented in the Product class.

The height variable in LargeProduct is defined like so:

public int height = null;

The getter method works fine:

public int getHeight() {
    return height;
}

But the setter method does not:

public void setHeight(int height) {
    this.height = height;
}

Errors:

The final field LargeProduct.height cannot be assigned
The static field LargeProduct.height should be accessed in a static way

I'm not sure which error it's actually giving.. I'm using Eclipse and when I hover it gives the first error, and at the bottom of the window it gives the second error.

Body:
The height variable in LargeProduct is
  defined like so:

public int height = null;

Variables defined in interfaces are implicitly static and final, i.e. constants. That's what the compiler complains about.

You cannot define an instance variable in an interface. Just leave it out - the get and set methods ensure that the classes can be used as intended. The actual variable is an implementation detail if the implementing classes.


问:
Finding the longest border of a string
First, let me tell you what the border of a string is,

```<code>let x = "abacab"
let y = "ababab"
</code>```

The border of a string is a substring which is both a proper prefix and proper suffix of the string — "proper" meaning that the whole string does not count as a substring. The longest border of x is "ab". The longest border of y is "abab" (the prefix and suffix can overlap).

Another example:

In string "abcde hgrab abcde", then "abcde" is a prefix as well as suffix. Thus it is also the longest border of the string above.

How can I find the longest border of a string?

答:
I've made a solution using Python3 (works also with Python2), using Counter from collections module and max().

Here is my solution:

```<code>from collections import Counter

def get_seq(a):
    data = []
    for k in range(1, len(a)):
        data.append(a[:k])
        data.append(a[k:])

    return Counter(data)

def get_max_sublist(a):
    bb = [k for k in a.items() if k[1] > 1]
    try:
        k, j = max(bb, key= lambda x: len(x[0]))
        n, _ = max(a.items(), key= lambda x: x[1])

    except ValueError:
        return None

    else:
        return k if j > 1 else n

seq = ["abacab", "ababab", "abxyab", "abxyba", "abxyzf", "bacab"]

for k in seq:
    j = get_seq(k)
    print("longest border of {} is: {}".format(k, get_max_sublist(j)))
</code>```

Output:

```<code>longest border of abacab is: ab
longest border of ababab is: abab
longest border of abxyab is: ab
longest border of abxyba is: a
longest border of abxyzf is: None
longest border of bacab is: b
</code>```

Title: Finding the longest border of a string

Body:
First, let me tell you what the border of a string is,

let x = "abacab"
let y = "ababab"

The border of a string is a substring which is both a proper prefix and proper suffix of the string — "proper" meaning that the whole string does not count as a substring. The longest border of x is "ab". The longest border of y is "abab" (the prefix and suffix can overlap).

Another example:

In string "abcde hgrab abcde", then "abcde" is a prefix as well as suffix. Thus it is also the longest border of the string above.

How can I find the longest border of a string?

Body:
I've made a solution using Python3 (works also with Python2), using Counter from collections module and max().

Here is my solution:

from collections import Counter

def get_seq(a):
    data = []
    for k in range(1, len(a)):
        data.append(a[:k])
        data.append(a[k:])

    return Counter(data)

def get_max_sublist(a):
    bb = [k for k in a.items() if k[1] > 1]
    try:
        k, j = max(bb, key= lambda x: len(x[0]))
        n, _ = max(a.items(), key= lambda x: x[1])

    except ValueError:
        return None

    else:
        return k if j > 1 else n

seq = ["abacab", "ababab", "abxyab", "abxyba", "abxyzf", "bacab"]

for k in seq:
    j = get_seq(k)
    print("longest border of {} is: {}".format(k, get_max_sublist(j)))

Output:

longest border of abacab is: ab
longest border of ababab is: abab
longest border of abxyab is: ab
longest border of abxyba is: a
longest border of abxyzf is: None
longest border of bacab is: b


问:
how to use lambda expression for jdk 7 or older versions
what are the changes that I need to make if I am using jdk 7 and want to use lambda expression?
I am comparing 2 xml files and want to ignore specific nodes hence using this expression

```<code>final Diff documentDiff = DiffBuilder
            .compare(expectedSource)
            .withTest(actualSource)
            .withNodeFilter(node -> !node.getNodeName().equals(someName))
            .build();
</code>```

error: Syntax error on token '-',-- expected

答:
lambda expression can not be used in java 7. The syntax itself is only allowed in java8. However the functionality you can achieve by writing more code or with out using lamda expression. You need to write a filter method which checks the name of node with someName if it returns true then proceed with building document Difference. You will need to write multiple statement and if case to check name equality.

You can also achieve this using xslt. which is very fast for long xml files but then you will need to write a lot of code as xslt is declarative and based upon functional programming.

Body:
what are the changes that I need to make if I am using jdk 7 and want to use lambda expression?
I am comparing 2 xml files and want to ignore specific nodes hence using this expression

final Diff documentDiff = DiffBuilder
            .compare(expectedSource)
            .withTest(actualSource)
            .withNodeFilter(node -> !node.getNodeName().equals(someName))
            .build();

error: Syntax error on token '-',-- expected


问:
Swift : Save & Show selected indexPath in static Table View
I have a little problem with my static tableview. I have a PopOver which is shown as an option for my grid. I want to save the state(indexPath) of my static TableView but seems it doesnt work, below is my snippet code :

```<code> override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    var currSelected: IndexPath?

    let section = indexPath.section
    let numberOfRows = tableView.numberOfRows(inSection: section)
    for row in 0..<numberOfRows {
        if let cell = tableView.cellForRow(at: NSIndexPath(row: row, section: section) as IndexPath) {
            cell.accessoryType = row == indexPath.row ? .checkmark : .none
            tableView.deselectRow(at: indexPath, animated: false)
            currSelected = indexPath

            if section == 2 {
                tableView.deselectRow(at: indexPath, animated: false)
                cell.accessoryType = .none
            }
            else {
                delegate?.option(lastSelected: currSelected!)
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: "reload"), object: nil)

            }
        }
    }
}
</code>```

I'm trying to use delegate to throw the lastSelected (last indexPath) to previous controller and send it back to the Pop Over Controller and i got it. But i dont know to show the checkmark using this lastSelected. And the prepare for cell at function need a identifier for a reused cell but i dont use it.

I have read this for showing the checkmark but its not saving the state. I have read this too but its same too. Any suggestions/answer will help for me. Thanks in Advance

答:
```<code>func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
    if indexPath == lastSelected {
        cell.accessoryType = .Checkmark
    }
}
</code>```

Body:
I have a little problem with my static tableview. I have a PopOver which is shown as an option for my grid. I want to save the state(indexPath) of my static TableView but seems it doesnt work, below is my snippet code :

 override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    var currSelected: IndexPath?

    let section = indexPath.section
    let numberOfRows = tableView.numberOfRows(inSection: section)
    for row in 0..<numberOfRows {
        if let cell = tableView.cellForRow(at: NSIndexPath(row: row, section: section) as IndexPath) {
            cell.accessoryType = row == indexPath.row ? .checkmark : .none
            tableView.deselectRow(at: indexPath, animated: false)
            currSelected = indexPath

            if section == 2 {
                tableView.deselectRow(at: indexPath, animated: false)
                cell.accessoryType = .none
            }
            else {
                delegate?.option(lastSelected: currSelected!)
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: "reload"), object: nil)

            }
        }
    }
}

I'm trying to use delegate to throw the lastSelected (last indexPath) to previous controller and send it back to the Pop Over Controller and i got it. But i dont know to show the checkmark using this lastSelected. And the prepare for cell at function need a identifier for a reused cell but i dont use it.

I have read this for showing the checkmark but its not saving the state. I have read this too but its same too. Any suggestions/answer will help for me. Thanks in Advance


问:
JavaScript match any alphabetic character
In PHP I can use this regex to match any alphabetic character in a string

```<code>preg_match('/\pL+/', 'асд'); // int(1)
</code>```

However in JavaScript this is not available

```<code>/\pL+/.test('асд'); // false
</code>```

I would guess that this is due to different regular expression interpreters and in some browsers the \pL sequence may be available but in the ones I tried it seems that's not the case.

How can I match any character from any alphabet in JavaScript?

答:
Look for character ranges for different alphabets:

[a-za-ža-я一-龿]+

This matches words composed of chars from

Latin alphabet

Lithuanian alphabet

Russian alphabet

Japan Kanji alphabet

Body:
In PHP I can use this regex to match any alphabetic character in a string

preg_match('/\pL+/', 'асд'); // int(1)

However in JavaScript this is not available

/\pL+/.test('асд'); // false

I would guess that this is due to different regular expression interpreters and in some browsers the \pL sequence may be available but in the ones I tried it seems that's not the case.

How can I match any character from any alphabet in JavaScript?


问:
Printing top three repeated elements in LCD display
I have an array whose input is given by the user by using keypad. All the inputs are stored in an array named storeKeys. The index of the array is held by a variable storeKeysIndex is initialized to 0 and when a key is pressed, the value of pressed key is stored in storeKeys array and the value of storeKeysIndex is incremented. Let the storeKeys have values

```<code>storeKeys = {3,2,5,7,1,1,9,9,9,1,3,1};
</code>```

I want the lcd to display the top three repeated elements in the array. In above array, lcd should display 1,9,3 since value '1' is repeated four times in the above array, '9' is repeated three times, '3' is repeated two times. Other values should not be displayed by lcd.

I have tried to count the frequency of each element and store the frequencies in an array freq. I can display the frequency of each element in the serial monitor. But I'm not getting how to display the top three repeated numbers on the lcd (or in serial monitor). Here is the code:

```<code>for(int i=0; i<12; i++)
{
    freq[i] = -1;
}
for(int i=0; i<12; i++)
{
    count = 1;
    for(int j=i+1; j<12; j++)
    {
        if(storeKeys[i] == storeKeys[j])
        {
            count++;
            freq[j] = 0;
        }
    }

    if(freq[i]!=0)
    {
        freq[i] = count;
    }
}
for(int i=0; i<12; i++)
{
    if(freq[i]!=0 && storeKeys[i] != NULL)
    {
        Serial.println(storeKeys[i]);
        Serial.println(freq[i]);
        Serial.println("==========");
    }
}
</code>```

The above code works but displaying frequency of all elements. I want to display the top three repeated elements only.

Here is the link for simulator online:

https://circuits.io/circuits/5073094-the-unnamed-circuit/edit

Thanks.

答:
I got the answer! Thanks for the help

```<code>for (int i = 0; i < 10; i++)  // Loop to sort the storeKeys array according to freq array
{
   if(freq[i]!=0 && storeKeys[i] != NULL){
    for (int j = i + 1; j < 10; j++)
    {
        if (freq[i] < freq[j])
        {
            a = freq[i];
            freq[i] = freq[j];
            freq[j] = a;
            b = storeKeys[i];
            storeKeys[i] = storeKeys[j];
            storeKeys[j] = b;
        }
    }
   }
}
for(int i=0;i<10;i++) {
  if(storeKeys[i] != NULL && freq[i] != 0){
    // Serial.println(storeKeys[i]);
    while(c<3){
      mostPressed[c] = storeKeys[i];
      c=c+1;
      break;
    }
  }
  if(c==3){
    break;
  }
}
</code>```

Here I sorted the storeKeys array according to the frequency array and stored the top three results in a new array. I got it myself. Thanks for the help!

Body:
I have an array whose input is given by the user by using keypad. All the inputs are stored in an array named storeKeys. The index of the array is held by a variable storeKeysIndex is initialized to 0 and when a key is pressed, the value of pressed key is stored in storeKeys array and the value of storeKeysIndex is incremented. Let the storeKeys have values

storeKeys = {3,2,5,7,1,1,9,9,9,1,3,1};

I want the lcd to display the top three repeated elements in the array. In above array, lcd should display 1,9,3 since value '1' is repeated four times in the above array, '9' is repeated three times, '3' is repeated two times. Other values should not be displayed by lcd.

I have tried to count the frequency of each element and store the frequencies in an array freq. I can display the frequency of each element in the serial monitor. But I'm not getting how to display the top three repeated numbers on the lcd (or in serial monitor). Here is the code:

for(int i=0; i<12; i++)
{
    freq[i] = -1;
}
for(int i=0; i<12; i++)
{
    count = 1;
    for(int j=i+1; j<12; j++)
    {
        if(storeKeys[i] == storeKeys[j])
        {
            count++;
            freq[j] = 0;
        }
    }

    if(freq[i]!=0)
    {
        freq[i] = count;
    }
}
for(int i=0; i<12; i++)
{
    if(freq[i]!=0 && storeKeys[i] != NULL)
    {
        Serial.println(storeKeys[i]);
        Serial.println(freq[i]);
        Serial.println("==========");
    }
}

The above code works but displaying frequency of all elements. I want to display the top three repeated elements only.

Here is the link for simulator online:

https://circuits.io/circuits/5073094-the-unnamed-circuit/edit

Thanks.

Body:
I got the answer! Thanks for the help

for (int i = 0; i < 10; i++)  // Loop to sort the storeKeys array according to freq array
{
   if(freq[i]!=0 && storeKeys[i] != NULL){
    for (int j = i + 1; j < 10; j++)
    {
        if (freq[i] < freq[j])
        {
            a = freq[i];
            freq[i] = freq[j];
            freq[j] = a;
            b = storeKeys[i];
            storeKeys[i] = storeKeys[j];
            storeKeys[j] = b;
        }
    }
   }
}
for(int i=0;i<10;i++) {
  if(storeKeys[i] != NULL && freq[i] != 0){
    // Serial.println(storeKeys[i]);
    while(c<3){
      mostPressed[c] = storeKeys[i];
      c=c+1;
      break;
    }
  }
  if(c==3){
    break;
  }
}

Here I sorted the storeKeys array according to the frequency array and stored the top three results in a new array. I got it myself. Thanks for the help!


答: Exactly org.life.java! And you cannot modify a static final variable! Because it's the way to determine a constant in Java.</p>

Title: The final field cannot be assigned, for an interface


问:
I want to add list of buttons in the same line in Swift 3.0
What I want is to add list of buttons (the number come from the service) to a uiview programmatically, so I think is I have to check if the space between the last button and the end of UIView is enough to add button or I have to go to the next line? Right?

Could you please help me on that?

Thanks,

答:
The idea is using UICollectionView. You can implement it with following:

Subclass UICollectionViewCell to make your own cell which has the button

Subclass UICollectionViewFlowLayout, override
layoutAttributesForItem(at indexPath: IndexPath) which provides the attributes for each cell. You may need to pre-calculate the frame of button or cell in function prepare()

Create UICollectionView instance with the collectionviewLayout you just subclassed.


问:
Finding Android SDK on Mac and adding to PATH
I have installed Android Studio on my MacBook Air (OS Version 10.11 El Capitan) and have successfully written a small "hello, world" app and installed on device (Nexus 7) and ran on AVD.  All I want to do now is be able to build the app and install it on device from the command line as opposed to Android Studio.  I'm following the directions here:

http://developer.android.com/training/basics/firstapp/running-app.html

and the relevant line is:

Make sure the Android SDK platform-tools/ directory is included in your PATH environment variable, then execute:

The problem is I can't find the Android SDK on my machine!  I assume it's there because otherwise the program wouldn't compile and run through Android Studio?  Perhaps that's a bad assumption?  I'm new to Macs (I'm used to Windows) so I don't know the best way to search for the Android SDK.  So my questions:

How do I find Android SDK on my machine? Or prove to myself it's not there?

If it's not there how do I install it?

How do I change PATH to include Android SDK?

答:
Find the Android SDK location

```<code>Android Studio
  > Preferences
  > Appearance & Behaviour
  > System Settings
  > Android SDK
  > Android SDK Location
</code>```

Create a .bash_profile file for your environment variables

Open the Terminal app

Go to your home directory via cd ~

Create the file with touch .bash_profile

Add the PATH variable to your .bash_profile

Open the file via open .bash_profile

Add export PATH=$PATH: [your SDK location] /platform-tools to the file and hit ⌘s to save it. By default it's:

export PATH=$PATH:/Users/yourUserName/Library/Android/sdk/platform-tools

Go back to your Terminal App and load the variable with source ~/.bash_profile

Body:
Find the Android SDK location

Android Studio
  > Preferences
  > Appearance & Behaviour
  > System Settings
  > Android SDK
  > Android SDK Location

Create a .bash_profile file for your environment variables

Open the Terminal app

Go to your home directory via cd ~

Create the file with touch .bash_profile

Add the PATH variable to your .bash_profile

Open the file via open .bash_profile

Add export PATH=$PATH: [your SDK location] /platform-tools to the file and hit ⌘s to save it. By default it's:

export PATH=$PATH:/Users/yourUserName/Library/Android/sdk/platform-tools

Go back to your Terminal App and load the variable with source ~/.bash_profile


问:
Styling table generated by PHP foreach with jQuery
I am trying to style a
 generated by a PHP foreach() with jQuery, but everything I've tried only selects the first one, leaving the others intact. What can I do this? Simple example:

CSS:

```<code>td {border:1px solid black}
</code>```

TABLE:

```<code><table>
<tr>
  <td>DATE</td>
  <td>EXAM TITLE</td>
  <td>EXAM CODE</td>
</tr>
<tr>
  <td>TODAY</td>
  <td>RANDOM</td>
  <td>123</td>
</tr>
<tr>
  <td>BUTTON</td>
  <td>BUTTON</td>
  <td>BUTTON</td>
</tr>
<tr>
  <td colspan=3 id="options">
</tr>
</code>```

I have tried this jQuery code (among other):

```<code>$("table").find("#options").each(function(){
  $(this).css("border","0px");
});
</code>```

It only styles my first . How can I get all of them?
Sorry if it is a stupid question. Thanks for the help.

答:
convert id to classlike:- ..

and then you can use(Use Either-one)

CSS (standered way):-

```<code>td.options {border:1px solid black}
</code>```

Or jQuery(try to avoid as much as possible):-

```<code>$('.options').css("border","1px solid black"); // no need of each
</code>```

Example (both at same time):-

 $('.options').css("font-size","21px"); ```
<pre class="snippet-code-css lang-css prettyprint-override"><code>td.options {border:1px solid black}</code>```

  DATE
  EXAM TITLE
  EXAM CODE

  TODAY
  RANDOM
  123

  BUTTON
  BUTTON
  BUTTON

```

Body:
I am trying to style a
 generated by a PHP foreach() with jQuery, but everything I've tried only selects the first one, leaving the others intact. What can I do this? Simple example:

CSS:

td {border:1px solid black}

TABLE:

  DATE
  EXAM TITLE
  EXAM CODE

  TODAY
  RANDOM
  123

  BUTTON
  BUTTON
  BUTTON

I have tried this jQuery code (among other):

$("table").find("#options").each(function(){
  $(this).css("border","0px");
});

It only styles my first . How can I get all of them?
Sorry if it is a stupid question. Thanks for the help.

Body:
convert id to classlike:- <td class="options">..</td>

and then you can use(Use Either-one)

CSS (standered way):-

td.options {border:1px solid black}

Or jQuery(try to avoid as much as possible):-

$('.options').css("border","1px solid black"); // no need of each

Example (both at same time):-

 $('.options').css("font-size","21px");

td.options {border:1px solid black}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
  <td class="options">DATE</td>
  <td class="options">EXAM TITLE</td>
  <td class="options">EXAM CODE</td>
</tr>
<tr>
  <td class="options">TODAY</td>
  <td class="options">RANDOM</td>
  <td class="options">123</td>
</tr>
<tr>
  <td class="options">BUTTON</td>
  <td class="options">BUTTON</td>
  <td class="options">BUTTON</td>
</tr>
</table>


问:
Java: How can I read and store them in array by a new line in ArrayList?
Here is what my .txt file looks like (but more than 100 elements per line and more than 100 lines):

```<code>-0.89094    -0.86099    -0.82438    -0.78214    -0.73573    -0.68691    -0.63754
-0.42469    -0.3924     -0.36389    -0.33906    -0.31795    -0.30056    -0.28692
</code>```

What I want to do is read this .txt file and store them in Arryalist. The problem is when I read and store this data, they put all of this in the same array (I want them to store in 2 arrays split by a line).

Here is my code:

```<code>public class ReadStore {
    public static void main(String[] args) throws IOException {

    Scanner inFile = new Scanner(new File("Untitled.txt")).useDelimiter("\\s");
    ArrayList<Float> temps = new ArrayList<Float>();

    while (inFile.hasNextFloat()) {
      // find next line
      float token = inFile.nextFloat();
      temps.add(token);

    }

    inFile1.close();

    Float [] tempsArray = temps.toArray(new Float[0]);
    for (Float s : tempsArray) {
      System.out.println(s);
    }
  }
</code>```

Any suggestion for making this works?

答:
First read line by line, then for each line read each float.

Try This :

```<code>public static void main(String[] args) throws IOException {
    Scanner inFile = new Scanner(new File("Untitled.txt"));
    List<List<Float>> temps = new ArrayList<>();

    while (inFile.hasNextLine()) {
        List<Float> data = new ArrayList<>();

        Scanner inLine = new Scanner(inFile.nextLine());
        while (inLine.hasNextFloat()) {
            data.add(inLine.nextFloat());
        }
        inLine.close();

        temps.add(data);
    }

    inFile.close();

    Float[][] dataArray = new Float[temps.size()][];

    for (int i = 0; i < dataArray.length; i++) {
        dataArray[i] = temps.get(i).toArray(new Float[temps.get(i).size()]);
    }

    System.out.println(Arrays.deepToString(dataArray));
}
</code>```

Output :

```<code>[[-0.89094, -0.86099, -0.82438, -0.78214, -0.73573, -0.68691, -0.63754], [-0.42469, -0.3924, -0.36389, -0.33906, -0.31795, -0.30056, -0.28692]]
</code>```

Body:
Here is what my .txt file looks like (but more than 100 elements per line and more than 100 lines):

-0.89094    -0.86099    -0.82438    -0.78214    -0.73573    -0.68691    -0.63754
-0.42469    -0.3924     -0.36389    -0.33906    -0.31795    -0.30056    -0.28692

What I want to do is read this .txt file and store them in Arryalist. The problem is when I read and store this data, they put all of this in the same array (I want them to store in 2 arrays split by a line).

Here is my code:

public class ReadStore {
    public static void main(String[] args) throws IOException {

    Scanner inFile = new Scanner(new File("Untitled.txt")).useDelimiter("\\s");
    ArrayList<Float> temps = new ArrayList<Float>();

    while (inFile.hasNextFloat()) {
      // find next line
      float token = inFile.nextFloat();
      temps.add(token);

    }

    inFile1.close();

    Float [] tempsArray = temps.toArray(new Float[0]);
    for (Float s : tempsArray) {
      System.out.println(s);
    }
  }

Any suggestion for making this works?

Body:
First read line by line, then for each line read each float.

Try This :

public static void main(String[] args) throws IOException {
    Scanner inFile = new Scanner(new File("Untitled.txt"));
    List<List<Float>> temps = new ArrayList<>();

    while (inFile.hasNextLine()) {
        List<Float> data = new ArrayList<>();

        Scanner inLine = new Scanner(inFile.nextLine());
        while (inLine.hasNextFloat()) {
            data.add(inLine.nextFloat());
        }
        inLine.close();

        temps.add(data);
    }

    inFile.close();

    Float[][] dataArray = new Float[temps.size()][];

    for (int i = 0; i < dataArray.length; i++) {
        dataArray[i] = temps.get(i).toArray(new Float[temps.get(i).size()]);
    }

    System.out.println(Arrays.deepToString(dataArray));
}

Output :

[[-0.89094, -0.86099, -0.82438, -0.78214, -0.73573, -0.68691, -0.63754], [-0.42469, -0.3924, -0.36389, -0.33906, -0.31795, -0.30056, -0.28692]]


问:
Set 2nd row as header column in CSV to datatable conversion
I am trying to read CSV file and fetch the data in datatable in C#.

I have used the below code, which works fine:

```<code>public static System.Data.DataTable GetcsvExcelRecords(string csvPath, string CSVFileName)
        {
            string[] workSheetNames = new string[] { };
            System.Data.DataTable dtExcelData = new System.Data.DataTable();
            string SourceConstr  = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + csvPath + "';Extended Properties='Text;HDR=Yes;FMT=Delimited;'";

            using (OleDbConnection excelConn = new OleDbConnection(SourceConstr))
            {
                excelConn.Open();
                OleDbCommand excelCommand = new OleDbCommand();
                OleDbDataAdapter excelDataAdapter = new OleDbDataAdapter();
                excelCommand = new OleDbCommand("SELECT * FROM [" + CSVFileName + "]", excelConn);
                excelDataAdapter.SelectCommand = excelCommand;
                excelDataAdapter.Fill(dtExcelData);
                return dtExcelData;
            }

        }
</code>```

However, I want the 2nd row data to be the header column and then followed by the rows. How to achieve this?
Thanks

答:
You can rather use existing libraries instead of reinventing (reimplementing)... I have heard that FileHelpers might be of some use.

On any case, we like trying out something before realizing the need for library. In such a case...

If csv file size is small, you can try something dirty like this... this might sound trivial though.
Note that there is a need for file to be on disk to use OleDbConnection...
Don't forget to delete the file created...

```<code>public static System.Data.DataTable GetcsvExcelRecords(string csvPath, string CSVFileName)
{
    string modCSVFileName = CreateFileRemovingFirstLine(csvPath, CSVFileName);

    string[] workSheetNames = new string[] { };
    System.Data.DataTable dtExcelData = new System.Data.DataTable();
    string SourceConstr = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + csvPath + "';Extended Properties='Text;HDR=Yes;FMT=Delimited;'";

    using (OleDbConnection excelConn = new OleDbConnection(SourceConstr))
    {
        excelConn.Open();
        OleDbCommand excelCommand = new OleDbCommand();
        OleDbDataAdapter excelDataAdapter = new OleDbDataAdapter();
        excelCommand = new OleDbCommand("SELECT * FROM [" + modCSVFileName + "]", excelConn);
        excelDataAdapter.SelectCommand = excelCommand;
        excelDataAdapter.Fill(dtExcelData);
        return dtExcelData;
    }
}

private static string CreateFileRemovingFirstLine(string csvPath, string CSVFileName)
{
    string filePath = Path.Combine(csvPath, CSVFileName);
    string modifiedFileName = CSVFileName.Replace(".csv", "2.csv");
    using (StreamReader sr = new StreamReader(filePath))
    {
        string headerLine = sr.ReadLine();
        string str = sr.ReadToEnd();
        // use the appropriate encoding... for example I am using ASCII
        byte[] buffer = Encoding.ASCII.GetBytes(str);

        MemoryStream ms = new MemoryStream(buffer);
        // write to file... check for access permission to create file
        FileStream file = new FileStream(Path.Combine(csvPath, modifiedFileName), FileMode.Create, FileAccess.Write);
        ms.WriteTo(file);
        file.Close();
        ms.Close();
    }

    return modifiedFileName;
}
</code>```

Body:
I am trying to read CSV file and fetch the data in datatable in C#.

I have used the below code, which works fine:

public static System.Data.DataTable GetcsvExcelRecords(string csvPath, string CSVFileName)
        {
            string[] workSheetNames = new string[] { };
            System.Data.DataTable dtExcelData = new System.Data.DataTable();
            string SourceConstr  = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + csvPath + "';Extended Properties='Text;HDR=Yes;FMT=Delimited;'";

            using (OleDbConnection excelConn = new OleDbConnection(SourceConstr))
            {
                excelConn.Open();
                OleDbCommand excelCommand = new OleDbCommand();
                OleDbDataAdapter excelDataAdapter = new OleDbDataAdapter();
                excelCommand = new OleDbCommand("SELECT * FROM [" + CSVFileName + "]", excelConn);
                excelDataAdapter.SelectCommand = excelCommand;
                excelDataAdapter.Fill(dtExcelData);
                return dtExcelData;
            }

        }

However, I want the 2nd row data to be the header column and then followed by the rows. How to achieve this?
Thanks

Body:
You can rather use existing libraries instead of reinventing (reimplementing)... I have heard that FileHelpers might be of some use.

On any case, we like trying out something before realizing the need for library. In such a case...

If csv file size is small, you can try something dirty like this... this might sound trivial though.
Note that there is a need for file to be on disk to use OleDbConnection...
Don't forget to delete the file created...

public static System.Data.DataTable GetcsvExcelRecords(string csvPath, string CSVFileName)
{
    string modCSVFileName = CreateFileRemovingFirstLine(csvPath, CSVFileName);

    string[] workSheetNames = new string[] { };
    System.Data.DataTable dtExcelData = new System.Data.DataTable();
    string SourceConstr = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + csvPath + "';Extended Properties='Text;HDR=Yes;FMT=Delimited;'";

    using (OleDbConnection excelConn = new OleDbConnection(SourceConstr))
    {
        excelConn.Open();
        OleDbCommand excelCommand = new OleDbCommand();
        OleDbDataAdapter excelDataAdapter = new OleDbDataAdapter();
        excelCommand = new OleDbCommand("SELECT * FROM [" + modCSVFileName + "]", excelConn);
        excelDataAdapter.SelectCommand = excelCommand;
        excelDataAdapter.Fill(dtExcelData);
        return dtExcelData;
    }
}

private static string CreateFileRemovingFirstLine(string csvPath, string CSVFileName)
{
    string filePath = Path.Combine(csvPath, CSVFileName);
    string modifiedFileName = CSVFileName.Replace(".csv", "2.csv");
    using (StreamReader sr = new StreamReader(filePath))
    {
        string headerLine = sr.ReadLine();
        string str = sr.ReadToEnd();
        // use the appropriate encoding... for example I am using ASCII
        byte[] buffer = Encoding.ASCII.GetBytes(str);

        MemoryStream ms = new MemoryStream(buffer);
        // write to file... check for access permission to create file
        FileStream file = new FileStream(Path.Combine(csvPath, modifiedFileName), FileMode.Create, FileAccess.Write);
        ms.WriteTo(file);
        file.Close();
        ms.Close();
    }

    return modifiedFileName;
}


问:
Android: Notif push (FCM) doesn't receive properly when App is in background
I've updated from 'com.google.firebase:firebase-messaging:10.2.4' to '10.2.6', and since all notification push receive when my App is in background, don't catch in onMessageReceived().

On the official documentation (https://firebase.google.com/support/release-notes/android) I don't see informations about this.

Ps: in 10.2.4, all worked perfectly.

Could you help guys?

答:
If you want to receive the onMessageReceived in all cases you cannot use notification push messages. You can only use data payload in your FCM messages.

onMessageReceived is provided for most message types, with the following exceptions:

Notification messages delivered when your app is in the background. In this case, the notification is delivered to the device’s system tray. A user tap on a notification opens the app launcher by default.

Messages with both notification and data payload, both background and foreground. In this case, the notification is delivered to the device’s system tray, and the data payload is delivered in the extras of the intent of your launcher Activity.

Source: https://firebase.google.com/docs/cloud-messaging/android/receive


问:
Open embedded pdf to a certain page
I've embedded a PDF into my workbook, and I need a code which will open the embedded PDF to a certain page.

The PDF needs to be embedded in the worksheet as it must be sent outside the organisation; I don't want to send a ZIP file with worksheets and PDFs.

So far, this is what I have in order to open the embedded PDF, and this works fine at the moment.

"Object 2" is the name of the embedded PDF.

```<code> Sub Macro1()

    ActiveSheet.Shapes("Object 2").Select

    Selection.Verb Verb:=xlPrimary

 End Sub
</code>```

If someone could help for opening the PDF to a certain page that would be great.

答:
What about:

```<code>Public Sub InsertPdf(PdfFileName As String)
Dim b As OLEObject

    Set b = ActiveSheet.OLEObjects.Add(fileName:=PdfFileName, Link:=False, DisplayAsIcon:=False)
    b.Left = 0
    b.Top = 0

End Sub
</code>```

EDIT:
After careful reading once again I think here is the code you need:

```<code>Public Function OpenPdf(SheetName As String)
Dim ws As Worksheet
Dim shp As Shape

    Set ws = ActiveWorkbook.Sheets(SheetName)

    For Each shp In ws.Shapes
        If shp.Type = msoEmbeddedOLEObject Then
           shp.Select
           Selection.Verb Verb:=xlPrimary
           Exit For
        End If
    Next

End Function
</code>```

Usage:

```<code>OpenPdf("Sheet2")
</code>```

Title: Open embedded pdf to a certain page

Body:
I've embedded a PDF into my workbook, and I need a code which will open the embedded PDF to a certain page.

The PDF needs to be embedded in the worksheet as it must be sent outside the organisation; I don't want to send a ZIP file with worksheets and PDFs.

So far, this is what I have in order to open the embedded PDF, and this works fine at the moment.

"Object 2" is the name of the embedded PDF.

 Sub Macro1()

    ActiveSheet.Shapes("Object 2").Select

    Selection.Verb Verb:=xlPrimary

 End Sub

If someone could help for opening the PDF to a certain page that would be great.

Body:
What about:

Public Sub InsertPdf(PdfFileName As String)
Dim b As OLEObject

    Set b = ActiveSheet.OLEObjects.Add(fileName:=PdfFileName, Link:=False, DisplayAsIcon:=False)
    b.Left = 0
    b.Top = 0

End Sub

EDIT:
After careful reading once again I think here is the code you need:

Public Function OpenPdf(SheetName As String)
Dim ws As Worksheet
Dim shp As Shape

    Set ws = ActiveWorkbook.Sheets(SheetName)

    For Each shp In ws.Shapes
        If shp.Type = msoEmbeddedOLEObject Then
           shp.Select
           Selection.Verb Verb:=xlPrimary
           Exit For
        End If
    Next

End Function

Usage:

OpenPdf("Sheet2")


问:
Regex for a random set of chars and digits
I am looking for a regex that matches only when it sees a string that is randomly filled by digits and chars.

For example, adfak332arg3 is allowed but 332352 and fagaaah are not allowed. .*[^\\s] looks fine for strings with only chars but how to fix it to accepts the desired strings and refuses the other two types?

答:
To ensure that an input contains digits as well as characters, you could use this regex:

```<code>^(?:[A-Za-z]+\\d+|\\d+[A-Za-z]+)[A-Za-z\\d]*$
</code>```

The regex ensures that the input contains at least a number and a character, and allows only numbers or characters (no special characters etc.)

(?:[A-Za-z]+\d+|\d+[A-Za-z]+) ensures that it starts with one or more characters followed by digits or alternatively |\d+[A-Za-z]+ one or more digits followed by one or more characters

[A-Za-z\d]* allows any number of characters or digits after the previous check

^ and $ to match starting and ending anchor

Regex101 Demo

Hope this helps!

Body:
To ensure that an input contains digits as well as characters, you could use this regex:

^(?:[A-Za-z]+\\d+|\\d+[A-Za-z]+)[A-Za-z\\d]*$

The regex ensures that the input contains at least a number and a character, and allows only numbers or characters (no special characters etc.)

(?:[A-Za-z]+\d+|\d+[A-Za-z]+) ensures that it starts with one or more characters followed by digits or alternatively |\d+[A-Za-z]+ one or more digits followed by one or more characters

[A-Za-z\d]* allows any number of characters or digits after the previous check

^ and $ to match starting and ending anchor

Regex101 Demo

Hope this helps!


问:
How can I connect Android Studio with a local server database SQL Server 2008?
I have a Microsoft SQL Server 2008 database on my local server and I want to create an Android application to send and receive data from this database.

Do I have to upload my database to the cloud first? Where should I start?

答:
If you want to test your android application with localserver or local database you'll need to have an emulator device. (You can use Android Studio's provided default emulator, or you can also install Genymotion  that is way better than default emulator of Android studio in terms of speed, performance etc).

If you wan to test the application on real device then you have to upload your php files and databases to a live server.


问:
Jquery ui autocomplete not working in partial view
Admin controller

```<code>public ViewResult Products()

public PartialViewResult AddProduct()

public JsonResult AutoComplete(string prefix)
</code>```

View

```<code>Product.cshtml

AddProduct.cshtml - Partial View
</code>```

I'm loading a partial view(AddProduct.cshtml) in modal popup in main view.

In partial view I have a form and I'm trying to add jQuery UI autocomplete on input field but its not working.

```<code>$(function() {
        $("#txtProductName").autocomplete({
            source: function(request, response) {
                $.ajax({
                    url: '/Admin/AutoComplete/',
                    data: "{ 'prefix': '" + request.term + "'}",
                    dataType: "json",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    success: function(data) {
                        response($.map(data, function(item) {
                            return item;
                        }))
                    },
                    error: function(response) {
                        alert(response.responseText);
                    },
                    failure: function(response) {
                        alert(response.responseText);
                    }
                });
            },
            minLength: 1
        });
    });
</code>```

I have added this jquery code in partial view page itself, also when I'm trying to save form data using ajax that too not working

答:
Finally I was able to resolve this issue myself.

Here is my Controller code:

```<code>[HttpGet]
public ViewResult Products() - Listing all the products (used for main view)

[HttpGet]
public PartialViewResult AddProduct() - Add new product form (used for partial view)

[HttpPost]
public JsonResult AutoComplete(string prefix) - Fetching data from database for autocomplete
</code>```

View

```<code>Product.cshtml - Html for listing all the products (Main View)

AddProduct.cshtml - Html for add new product form (Partial View)
</code>```

So I have added all the jQuery refrence in the _Layout.cshtml (shared view) file and in partial view I have added the following jQuery code at bottom of the page

```<code>$("#txtProductName").autocomplete({
    rest of the logic and ajax hit goes here...
}); - used to show autocomplete suggestion when user types

$("#AddNewProduct").on("submit", "#AddNewProductForm", function (e) {
    $.ajax({
        rest of the logic goes here...
    });
}); - used to submit the form data
</code>```

Body:
Admin controller

public ViewResult Products()

public PartialViewResult AddProduct()

public JsonResult AutoComplete(string prefix)

View

Product.cshtml

AddProduct.cshtml - Partial View

I'm loading a partial view(AddProduct.cshtml) in modal popup in main view.

In partial view I have a form and I'm trying to add jQuery UI autocomplete on input field but its not working.

$(function() {
        $("#txtProductName").autocomplete({
            source: function(request, response) {
                $.ajax({
                    url: '/Admin/AutoComplete/',
                    data: "{ 'prefix': '" + request.term + "'}",
                    dataType: "json",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    success: function(data) {
                        response($.map(data, function(item) {
                            return item;
                        }))
                    },
                    error: function(response) {
                        alert(response.responseText);
                    },
                    failure: function(response) {
                        alert(response.responseText);
                    }
                });
            },
            minLength: 1
        });
    });

I have added this jquery code in partial view page itself, also when I'm trying to save form data using ajax that too not working

Body:
Finally I was able to resolve this issue myself.

Here is my Controller code:

[HttpGet]
public ViewResult Products() - Listing all the products (used for main view)

[HttpGet]
public PartialViewResult AddProduct() - Add new product form (used for partial view)

[HttpPost]
public JsonResult AutoComplete(string prefix) - Fetching data from database for autocomplete

View

Product.cshtml - Html for listing all the products (Main View)

AddProduct.cshtml - Html for add new product form (Partial View)

So I have added all the jQuery refrence in the _Layout.cshtml (shared view) file and in partial view I have added the following jQuery code at bottom of the page

$("#txtProductName").autocomplete({
    rest of the logic and ajax hit goes here...
}); - used to show autocomplete suggestion when user types

$("#AddNewProduct").on("submit", "#AddNewProductForm", function (e) {
    $.ajax({
        rest of the logic goes here...
    });
}); - used to submit the form data


答:
You can read line by line and split it by spaces . Working and tested code:

```<code>public static void main(String[] args) throws IOException {

        Scanner inFile = new Scanner(new File("C:\\Untitled.txt"));
        ArrayList<String[]> temps = new ArrayList<>();

        while (inFile.hasNextLine()) {
            // find next line
            String line = inFile.nextLine();
            String[] floats = line.split("\\s+");
            temps.add(floats);
        }

        inFile.close();

        temps.forEach(arr -> {
            System.out.println(Arrays.toString(arr));
        });
    }
</code>```

You can also read float values by regex.

```<code>Scanner inFile = new Scanner(new File("C:\\Untitled.txt"));
        ArrayList<Float> temps = new ArrayList<>();

        while (inFile.hasNext("-\\d\\.\\d+")) {
            // find next line
            String line = inFile.next();
            temps.add(Float.valueOf(line));
        }

        inFile.close();
</code>```

Title: Java: How can I read and store them in array by a new line in ArrayList?

Body:
You can read line by line and split it by spaces . Working and tested code:

public static void main(String[] args) throws IOException {

        Scanner inFile = new Scanner(new File("C:\\Untitled.txt"));
        ArrayList<String[]> temps = new ArrayList<>();

        while (inFile.hasNextLine()) {
            // find next line
            String line = inFile.nextLine();
            String[] floats = line.split("\\s+");
            temps.add(floats);
        }

        inFile.close();

        temps.forEach(arr -> {
            System.out.println(Arrays.toString(arr));
        });
    }

You can also read float values by regex.

Scanner inFile = new Scanner(new File("C:\\Untitled.txt"));
        ArrayList<Float> temps = new ArrayList<>();

        while (inFile.hasNext("-\\d\\.\\d+")) {
            // find next line
            String line = inFile.next();
            temps.add(Float.valueOf(line));
        }

        inFile.close();