问:
How to check if user has paid for an Auto Renewal Subscription In App Purchase in Swift
I currently have a Non-Consumable and an Auto Renewal Subscription In App Purchase set in iTunesConnect.  My problem is that I'm not sure how to check if content can be unlock for user for the Auto Renewal Subscription. I have no problems with the Non-Consumables In App Purchases, I validate them by checkinging if the product ID exists in UserDefaults, if it does, I unlock the content otherwise I notify the user but this method doesn't work with Auto Renewal Subscription In App Purchases. When I test it, I can make the purchase transation through the App store but when I try to see if the product ID exists in UserDefaults it returns false. In fact, I manually checked if the key exists and it doesn't, it only shows keys for Non-Consumable purchases.

Here is the code I'm using.

Here is the working code I have been using for years to validate Non-Consumable in app purchases.

Here is the In App Manager class I'm using.

```<code>import UIKit
import StoreKit

protocol IAPManagerDelegate {
    func managerDidRestorePurchases()
}

class IAPManager: NSObject, SKProductsRequestDelegate, SKPaymentTransactionObserver, SKRequestDelegate {
    static let sharedInstance = IAPManager()
    var request:SKProductsRequest!
    var products:NSArray!
    var delegate:IAPManagerDelegate?

    func setupInAppPurchases(){
        self.validateProductIdentifiers(self.getProductIdentifiersFromMainBundle())

        SKPaymentQueue.default().add(self)
    }

    func getProductIdentifiersFromMainBundle() -> NSArray {
        var identifiers = NSArray()
        if let url = Bundle.main.url(forResource: "iap_product_ids", withExtension: "plist"){
            identifiers = NSArray(contentsOf: url)!
        }
        return identifiers
    }

    func validateProductIdentifiers(_ identifiers:NSArray) {
        let productIdentifiers = NSSet(array: identifiers as [AnyObject])
        let productRequest = SKProductsRequest(productIdentifiers: productIdentifiers as! Set<String>)
        self.request = productRequest
        productRequest.delegate = self
        productRequest.start()
    }

    func createPaymentRequestForProduct(_ product:SKProduct){
        let payment = SKMutablePayment(product: product)
        payment.quantity = 1
        SKPaymentQueue.default().add(payment)
    }

    func verifyReceipt(_ transaction:SKPaymentTransaction?){
        let receiptURL = Bundle.main.appStoreReceiptURL!
        if let receipt = try? Data(contentsOf: receiptURL){

            let requestContents = ["receipt-data" : receipt.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))]

            do {
                let requestData = try JSONSerialization.data(withJSONObject: requestContents, options: JSONSerialization.WritingOptions(rawValue: 0))
                //  PRODUCTION URL
                // let storeURL = URL(string: "https://buy.itunes.apple.com/verifyReceipt")
                //  TESTING URL: Uncomment for testing InAppPurchases
                let storeURL = URL(string: "https:/sandbox.itunes.apple.com/verifyReceipt")

                var request = URLRequest(url: storeURL!)
                request.httpMethod = "Post"
                request.httpBody = requestData

                let session = URLSession.shared
                let task = session.dataTask(with: request,
                                            completionHandler: { (responseData, response, error) -> Void in
                    do {
                        let json = try JSONSerialization.jsonObject(with: responseData!, options: .mutableLeaves) as! NSDictionary
                        if (json.object(forKey: "status") as! NSNumber) == 0 {
                            if let latest_receipt = json["latest_receipt_info"]{
                                self.validatePurchaseArray(latest_receipt as! NSArray)
                            } else {
                                let receipt_dict = json["receipt"] as! NSDictionary
                                if let purchases = receipt_dict["in_app"] as? NSArray{
                                    self.validatePurchaseArray(purchases)
                                }
                            }
                            if transaction != nil {
                                SKPaymentQueue.default().finishTransaction(transaction!)
                            }
                            DispatchQueue.main.sync(execute: { () -> Void in
                                self.delegate?.managerDidRestorePurchases()
                            })
                        } else {
                            print(json.object(forKey: "status") as! NSNumber)
                        }
                    } catch {
                        print(error)
                    }
                })
                task.resume()
            } catch {
                print(error)
            }
        } else {
            print("No Receipt")
        }
    }

    func validatePurchaseArray(_ purchases:NSArray){
        for purchase in purchases as! [NSDictionary]{
            self.unlockPurchasedFunctionalityForProductIdentifier(purchase["product_id"] as! String)
        }
    }

    func unlockPurchasedFunctionalityForProductIdentifier(_ productIdentifier:String){
        UserDefaults.standard.set(true, forKey: productIdentifier)
        UserDefaults.standard.synchronize()
        DispatchQueue.main.async {
            UIApplication.shared.isNetworkActivityIndicatorVisible = false
        }
    }

    func lockPurchasedFunctionalityForProductIdentifier(_ productIdentifier:String){
        UserDefaults.standard.set(false, forKey: productIdentifier)
        UserDefaults.standard.synchronize()
        UIApplication.shared.isNetworkActivityIndicatorVisible = false
    }

    func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
        let inAppPurchases = response.products
        // Sort the items
        self.products = inAppPurchases.reversed() as NSArray
    }

    func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
        for transaction in transactions as [SKPaymentTransaction]{
            switch transaction.transactionState{
            case .purchasing:
                print("Purchasing")
                UIApplication.shared.isNetworkActivityIndicatorVisible = true
            case .deferred:
                print("Deferrred")
                UIApplication.shared.isNetworkActivityIndicatorVisible = false
            case .failed:
                print("Failed")
                //print(transaction.error?.localizedDescription)
                UIApplication.shared.isNetworkActivityIndicatorVisible = false
                SKPaymentQueue.default().finishTransaction(transaction)
            case.purchased:
                print("Purchased")
                self.verifyReceipt(transaction)
            case .restored:
                print("Restored")

            }
        }
    }

    func restorePurchases(){
        let request = SKReceiptRefreshRequest()
        request.delegate = self
        request.start()
    }

    func requestDidFinish(_ request: SKRequest) {
        self.verifyReceipt(nil)
    }
}
</code>```

Here is how I'm presenting the In App Purchases in a UITableView.

```<code>class StoreTableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, IAPManagerDelegate {
    @IBOutlet weak var premiumFeaturesTable: UITableView!
    @IBOutlet weak var buttonClose: UIButton!
    @IBOutlet weak var buttonRestore: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()
        IAPManager.sharedInstance.delegate = self
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return IAPManager.sharedInstance.products.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell =  tableView.dequeueReusableCell(withIdentifier: "cellInAppPurchase")as! CustomCellForInAppPurchasesTableViewCell
        let product = IAPManager.sharedInstance.products.object(at: indexPath.row) as! SKProduct

         cell.labelIAppItem.text = product.localizedTitle
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        IAPManager.sharedInstance.createPaymentRequestForProduct(IAPManager.sharedInstance.products.object(at: indexPath.row) as! SKProduct)
    }

    @IBAction func closeViewController(_ sender: AnyObject) {
        self.presentingViewController!.dismiss(animated: true, completion: nil)
    }

    @IBAction func restorePurchases(_ sender: AnyObject) {
        IAPManager.sharedInstance.restorePurchases()
    }
}
</code>```

Here is how I'm unlocking content

```<code>if NSUserDefaults.standardUserDefaults().boolForKey("com.theAppID.app"){
    // Unlock content.
}else{
    // Notify user.
}
</code>```

Again, everything works for Non-Consumables but for Auto Renewal Subscriptions I'm not sure how to unlock content after the user made purchased.

What am I missing, what is the correct way to check if the user has paid for an Auto Renewal Subscription based on the above code?

EDIT: The simplest answer is... use RevenueCat for your subscription based apps, it makes your life easier.

答:
Please check this link for auto-renewal subscription.

You can use the below function from your In-App manager class.

```<code>func verifyReceipt(_ transaction:SKPaymentTransaction?)
</code>```

after validate you will get below response code and details for your last date for the subscription. Please check this link.

Note: Don't forget to pass the "password" field in receipt validation for the auto-renewal subscription.

Body:
I currently have a Non-Consumable and an Auto Renewal Subscription In App Purchase set in iTunesConnect.  My problem is that I'm not sure how to check if content can be unlock for user for the Auto Renewal Subscription. I have no problems with the Non-Consumables In App Purchases, I validate them by checkinging if the product ID exists in UserDefaults, if it does, I unlock the content otherwise I notify the user but this method doesn't work with Auto Renewal Subscription In App Purchases. When I test it, I can make the purchase transation through the App store but when I try to see if the product ID exists in UserDefaults it returns false. In fact, I manually checked if the key exists and it doesn't, it only shows keys for Non-Consumable purchases.

Here is the code I'm using.

Here is the working code I have been using for years to validate Non-Consumable in app purchases.

Here is the In App Manager class I'm using.

import UIKit
import StoreKit

protocol IAPManagerDelegate {
    func managerDidRestorePurchases()
}

class IAPManager: NSObject, SKProductsRequestDelegate, SKPaymentTransactionObserver, SKRequestDelegate {
    static let sharedInstance = IAPManager()
    var request:SKProductsRequest!
    var products:NSArray!
    var delegate:IAPManagerDelegate?

    func setupInAppPurchases(){
        self.validateProductIdentifiers(self.getProductIdentifiersFromMainBundle())

        SKPaymentQueue.default().add(self)
    }

    func getProductIdentifiersFromMainBundle() -> NSArray {
        var identifiers = NSArray()
        if let url = Bundle.main.url(forResource: "iap_product_ids", withExtension: "plist"){
            identifiers = NSArray(contentsOf: url)!
        }
        return identifiers
    }

    func validateProductIdentifiers(_ identifiers:NSArray) {
        let productIdentifiers = NSSet(array: identifiers as [AnyObject])
        let productRequest = SKProductsRequest(productIdentifiers: productIdentifiers as! Set<String>)
        self.request = productRequest
        productRequest.delegate = self
        productRequest.start()
    }

    func createPaymentRequestForProduct(_ product:SKProduct){
        let payment = SKMutablePayment(product: product)
        payment.quantity = 1
        SKPaymentQueue.default().add(payment)
    }

    func verifyReceipt(_ transaction:SKPaymentTransaction?){
        let receiptURL = Bundle.main.appStoreReceiptURL!
        if let receipt = try? Data(contentsOf: receiptURL){

            let requestContents = ["receipt-data" : receipt.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))]

            do {
                let requestData = try JSONSerialization.data(withJSONObject: requestContents, options: JSONSerialization.WritingOptions(rawValue: 0))
                //  PRODUCTION URL
                // let storeURL = URL(string: "https://buy.itunes.apple.com/verifyReceipt")
                //  TESTING URL: Uncomment for testing InAppPurchases
                let storeURL = URL(string: "https:/sandbox.itunes.apple.com/verifyReceipt")

                var request = URLRequest(url: storeURL!)
                request.httpMethod = "Post"
                request.httpBody = requestData

                let session = URLSession.shared
                let task = session.dataTask(with: request,
                                            completionHandler: { (responseData, response, error) -> Void in
                    do {
                        let json = try JSONSerialization.jsonObject(with: responseData!, options: .mutableLeaves) as! NSDictionary
                        if (json.object(forKey: "status") as! NSNumber) == 0 {
                            if let latest_receipt = json["latest_receipt_info"]{
                                self.validatePurchaseArray(latest_receipt as! NSArray)
                            } else {
                                let receipt_dict = json["receipt"] as! NSDictionary
                                if let purchases = receipt_dict["in_app"] as? NSArray{
                                    self.validatePurchaseArray(purchases)
                                }
                            }
                            if transaction != nil {
                                SKPaymentQueue.default().finishTransaction(transaction!)
                            }
                            DispatchQueue.main.sync(execute: { () -> Void in
                                self.delegate?.managerDidRestorePurchases()
                            })
                        } else {
                            print(json.object(forKey: "status") as! NSNumber)
                        }
                    } catch {
                        print(error)
                    }
                })
                task.resume()
            } catch {
                print(error)
            }
        } else {
            print("No Receipt")
        }
    }

    func validatePurchaseArray(_ purchases:NSArray){
        for purchase in purchases as! [NSDictionary]{
            self.unlockPurchasedFunctionalityForProductIdentifier(purchase["product_id"] as! String)
        }
    }

    func unlockPurchasedFunctionalityForProductIdentifier(_ productIdentifier:String){
        UserDefaults.standard.set(true, forKey: productIdentifier)
        UserDefaults.standard.synchronize()
        DispatchQueue.main.async {
            UIApplication.shared.isNetworkActivityIndicatorVisible = false
        }
    }

    func lockPurchasedFunctionalityForProductIdentifier(_ productIdentifier:String){
        UserDefaults.standard.set(false, forKey: productIdentifier)
        UserDefaults.standard.synchronize()
        UIApplication.shared.isNetworkActivityIndicatorVisible = false
    }

    func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
        let inAppPurchases = response.products
        // Sort the items
        self.products = inAppPurchases.reversed() as NSArray
    }

    func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
        for transaction in transactions as [SKPaymentTransaction]{
            switch transaction.transactionState{
            case .purchasing:
                print("Purchasing")
                UIApplication.shared.isNetworkActivityIndicatorVisible = true
            case .deferred:
                print("Deferrred")
                UIApplication.shared.isNetworkActivityIndicatorVisible = false
            case .failed:
                print("Failed")
                //print(transaction.error?.localizedDescription)
                UIApplication.shared.isNetworkActivityIndicatorVisible = false
                SKPaymentQueue.default().finishTransaction(transaction)
            case.purchased:
                print("Purchased")
                self.verifyReceipt(transaction)
            case .restored:
                print("Restored")

            }
        }
    }

    func restorePurchases(){
        let request = SKReceiptRefreshRequest()
        request.delegate = self
        request.start()
    }

    func requestDidFinish(_ request: SKRequest) {
        self.verifyReceipt(nil)
    }
}

Here is how I'm presenting the In App Purchases in a UITableView.

class StoreTableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, IAPManagerDelegate {
    @IBOutlet weak var premiumFeaturesTable: UITableView!
    @IBOutlet weak var buttonClose: UIButton!
    @IBOutlet weak var buttonRestore: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()
        IAPManager.sharedInstance.delegate = self
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return IAPManager.sharedInstance.products.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell =  tableView.dequeueReusableCell(withIdentifier: "cellInAppPurchase")as! CustomCellForInAppPurchasesTableViewCell
        let product = IAPManager.sharedInstance.products.object(at: indexPath.row) as! SKProduct

         cell.labelIAppItem.text = product.localizedTitle
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        IAPManager.sharedInstance.createPaymentRequestForProduct(IAPManager.sharedInstance.products.object(at: indexPath.row) as! SKProduct)
    }

    @IBAction func closeViewController(_ sender: AnyObject) {
        self.presentingViewController!.dismiss(animated: true, completion: nil)
    }

    @IBAction func restorePurchases(_ sender: AnyObject) {
        IAPManager.sharedInstance.restorePurchases()
    }
}

Here is how I'm unlocking content

if NSUserDefaults.standardUserDefaults().boolForKey("com.theAppID.app"){
    // Unlock content.
}else{
    // Notify user.
}

Again, everything works for Non-Consumables but for Auto Renewal Subscriptions I'm not sure how to unlock content after the user made purchased.

What am I missing, what is the correct way to check if the user has paid for an Auto Renewal Subscription based on the above code?

EDIT: The simplest answer is... use RevenueCat for your subscription based apps, it makes your life easier.

Body:
Please check this link for auto-renewal subscription.

You can use the below function from your In-App manager class.

func verifyReceipt(_ transaction:SKPaymentTransaction?)

after validate you will get below response code and details for your last date for the subscription. Please check this link.

Note: Don't forget to pass the "password" field in receipt validation for the auto-renewal subscription.


来源: stackexchange

问:
Trying to get property 'email' of non-object
I am getting following error from my code written in Codeigniter when i enter a wrong E-mail.

A PHP Error was encountered Severity: Notice

Message: Trying to get property 'email' of non-object

Filename: controllers/forms.php

Line Number: 26

Backtrace:

File:
  E:\Software\XAMPP\xampp\htdocs\ciauth\application\controllers\forms.php
  Line: 26 Function: _error_handler

File: E:\Software\XAMPP\xampp\htdocs\ciauth\index.php Line: 315
  Function: require_once

Below is the controller

```<code><?php
class Forms extends CI_Controller
{
    public function __construct()
    {

        parent::__construct();
        $this->load->database();
        $this->load->library('session');
        $this->load->helper('url');
        $this->load->model('user_model', 'auth');
    }

   public function forgot_pass()
    {
        if($this->input->post('forgot_pass'))
        {
            $email=$this->input->post('email');
            $this->load->model('user_model', 'auth');
            $this->load->library('form_validation');
            $this->form_validation->set_rules('email', 'E-mail', 'required');

            if ($this->form_validation->run() == TRUE) {
            $que=$this->db->query("select password,email from users where email='$email'");
            $row=$que->row();
            $user_email=$row->email;
            if((!strcmp($email, $user_email)))
            {
                $pass=$row->password;
                $to = $user_email;
                $subject = "Password";
                $txt = "Your password is $pass .";
                $headers = "From: user@testdomain.com" . "\r\n" . "CC: hamza_zon@outlook.com ";
                mail($to,$subject,$txt,$headers);
                $this->load->view('user/header');
                $this->load->view('user/confirm');
                $this->load->view('user/footer');
                }
            else{
            $data['error']="Invalid Email ID !";
            }
        }
            else{
                $data['error']="Email ID is required !";
            }
    }
            $this->load->view('user/header');
            $this->load->view('user/forgot_pass',@$data);
            $this->load->view('user/footer');

   }
}
?>
</code>```

答:
$row=$que->row();

$row is probably being returned as NULL or a falsy value.

var_dump($row) to check.

```<code>if(!$row)
{
    die("user not found");
}
</code>```

or

```<code>if(empty($row))
{
    die("user not found");
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am getting following error from my code written in Codeigniter when i enter a wrong E-mail.

A PHP Error was encountered Severity: Notice

Message: Trying to get property 'email' of non-object

Filename: controllers/forms.php

Line Number: 26

Backtrace:

File:
  E:\Software\XAMPP\xampp\htdocs\ciauth\application\controllers\forms.php
  Line: 26 Function: _error_handler

File: E:\Software\XAMPP\xampp\htdocs\ciauth\index.php Line: 315
  Function: require_once

Below is the controller

<?php
class Forms extends CI_Controller
{
    public function __construct()
    {

        parent::__construct();
        $this->load->database();
        $this->load->library('session');
        $this->load->helper('url');
        $this->load->model('user_model', 'auth');
    }

   public function forgot_pass()
    {
        if($this->input->post('forgot_pass'))
        {
            $email=$this->input->post('email');
            $this->load->model('user_model', 'auth');
            $this->load->library('form_validation');
            $this->form_validation->set_rules('email', 'E-mail', 'required');

            if ($this->form_validation->run() == TRUE) {
            $que=$this->db->query("select password,email from users where email='$email'");
            $row=$que->row();
            $user_email=$row->email;
            if((!strcmp($email, $user_email)))
            {
                $pass=$row->password;
                $to = $user_email;
                $subject = "Password";
                $txt = "Your password is $pass .";
                $headers = "From: user@testdomain.com" . "\r\n" . "CC: hamza_zon@outlook.com ";
                mail($to,$subject,$txt,$headers);
                $this->load->view('user/header');
                $this->load->view('user/confirm');
                $this->load->view('user/footer');
                }
            else{
            $data['error']="Invalid Email ID !";
            }
        }
            else{
                $data['error']="Email ID is required !";
            }
    }
            $this->load->view('user/header');
            $this->load->view('user/forgot_pass',@$data);
            $this->load->view('user/footer');

   }
}
?>

Body:
$row=$que->row();

$row is probably being returned as NULL or a falsy value.

var_dump($row) to check.

if(!$row)
{
    die("user not found");
}

or

if(empty($row))
{
    die("user not found");
}


问:
How to give a space along with printing result
So, i want to create a function. If i use 4 as input number, then it will give a result:

```<code>****
 ***
  **
   *
</code>```

I use code like this.

```<code>def print_pattern(input_number):
    for i in reversed(range(input_number)):
        integer = (i+1)
        if integer == input_number:
            output = (integer * '*')
        elif integer < input_number:
            output = " " + (integer * '*')
        print(output)

print_pattern(6)
</code>```

But, the result only show the first looping like this.

```<code>****
 ***
 **
 *
</code>```

what should i do?

答:
Using str.rjust

Ex:

```<code>def print_pattern(input_number):
    num = input_number+1
    for i in reversed(range(num)):
        print(("*"*i).rjust(input_number, " "))

print_pattern(4)
</code>```

Output:

```<code>****
 ***
  **
   *
</code>```

Body:
So, i want to create a function. If i use 4 as input number, then it will give a result:

****
 ***
  **
   *

I use code like this.

def print_pattern(input_number):
    for i in reversed(range(input_number)):
        integer = (i+1)
        if integer == input_number:
            output = (integer * '*')
        elif integer < input_number:
            output = " " + (integer * '*')
        print(output)

print_pattern(6)

But, the result only show the first looping like this.

****
 ***
 **
 *

what should i do?

Body:
Using str.rjust

Ex:

def print_pattern(input_number):
    num = input_number+1
    for i in reversed(range(num)):
        print(("*"*i).rjust(input_number, " "))

print_pattern(4)

Output:

****
 ***
  **
   *


问:
How can I add particular component(like Input component) in Ag-grid by Row wise or how can i remove component by Row in Ag-grid?
How can I add a particular component (like Checkbox, Input , select, dropdown component) in a particular row? Whenever I add a component into columns, it comes in every row. How can I remove the component from a particular row?

 this.columnDefs1 = [
    {
         headerName: "M1",
         field: "m1",
         width: 90,
         cellRendererFramework: InputComponent,
         controlData: {
             type: 'text'
         },
    },
]

this.rowData1 = [
    {
        m1: "50",
    },
    {
        m1: "30",
    },
    {
        m1: "",
        //If I don't want input component in this row, how can I remove?
        //I have tried by not giving m1
        //also but its coming in whole column or every row.
    },
    {
        m1: "20",
    },
]
```

You can see in the linked image for reference, I don't want the last 4 select components, but I need those rows blank:

答:
You can use colDef.cellRendererSelector which is a function that selects the renderer based on the row data

headerName: "M1",
field: "m1",
width: 90,
cellRendererSelector: function (params) {
    if (params.data.m1) {
       return InputComponent;
    } else {
       return null;
    }
},
controlData: {
    type: 'text'
}
```

You can read more about it here - https://www.ag-grid.com/javascript-grid-cell-rendering/#many-renderers-one-column

Body:
How can I add a particular component (like Checkbox, Input , select, dropdown component) in a particular row? Whenever I add a component into columns, it comes in every row. How can I remove the component from a particular row?

 this.columnDefs1 = [
    {
         headerName: "M1",
         field: "m1",
         width: 90,
         cellRendererFramework: InputComponent,
         controlData: {
             type: 'text'
         },
    },
]

this.rowData1 = [
    {
        m1: "50",
    },
    {
        m1: "30",
    },
    {
        m1: "",
        //If I don't want input component in this row, how can I remove?
        //I have tried by not giving m1
        //also but its coming in whole column or every row.
    },
    {
        m1: "20",
    },
]

You can see in the linked image for reference, I don't want the last 4 select components, but I need those rows blank:

Body:
You can use colDef.cellRendererSelector which is a function that selects the renderer based on the row data

headerName: "M1",
field: "m1",
width: 90,
cellRendererSelector: function (params) {
    if (params.data.m1) {
       return InputComponent;
    } else {
       return null;
    }
},
controlData: {
    type: 'text'
}

You can read more about it here - https://www.ag-grid.com/javascript-grid-cell-rendering/#many-renderers-one-column


问:
Cannot prevent a file from direct URL Access in wordpress
I'm trying to block my direct pdf url but unfortunately my pdfs are accessible directly from the url. I have already edit my htaccess file in which is stored in /opt/bitnami/apps/wordpress/htdocs

And my pfds are stored in /opt/bitnami/apps/wordpress/htdocs/wp-content/uploads/securepdfs

I have gone through these urls:

Wordpress protect file if not logged in

https://wordpress.stackexchange.com/questions/37144/how-to-protect-uploads-if-user-is-not-logged-in

```<code>RewriteCond %{REQUEST_FILENAME} ^.*(pdf)$
RewriteRule ^(.*)$ /wp-content/download.php?file=$1 [L]

require_once('/path/to/wp-config.php');
require_once('/path/to/wp-includes/wp-db.php');
require_once('/path/to/wp-includes/pluggable.php');

if (!is_user_logged_in()) {
    // redirect to login page or show the message + login form
    die; // or exit, wp_redirect etc
}

header("Content-Type: application/octet-stream");

$file = $_GET["file"] .".pdf";
header("Content-Disposition: attachment; filename=" . urlencode($file));
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
header("Content-Length: " . filesize($file));
flush(); // this doesn't really matter.
$fp = fopen($file, "r");
while (!feof($fp))
{
    echo fread($fp, 65536);
    flush(); // this is essential for large downloads
}
fclose($fp); ```

All pdfs urls are public accessible
https://abc/wp-content/uploads/securepdfs/2019/05/Testing-pdf-1.pdf
```

答:
You can use below code in the .htaccess file to block directory access from URL.</p>

```<code>Options -Indexes
</code>```

Body:
I'm trying to block my direct pdf url but unfortunately my pdfs are accessible directly from the url. I have already edit my htaccess file in which is stored in /opt/bitnami/apps/wordpress/htdocs

And my pfds are stored in /opt/bitnami/apps/wordpress/htdocs/wp-content/uploads/securepdfs

I have gone through these urls:

Wordpress protect file if not logged in

https://wordpress.stackexchange.com/questions/37144/how-to-protect-uploads-if-user-is-not-logged-in

RewriteCond %{REQUEST_FILENAME} ^.*(pdf)$
RewriteRule ^(.*)$ /wp-content/download.php?file=$1 [L]

require_once('/path/to/wp-config.php');
require_once('/path/to/wp-includes/wp-db.php');
require_once('/path/to/wp-includes/pluggable.php');

if (!is_user_logged_in()) {
    // redirect to login page or show the message + login form
    die; // or exit, wp_redirect etc
}

header("Content-Type: application/octet-stream");

$file = $_GET["file"] .".pdf";
header("Content-Disposition: attachment; filename=" . urlencode($file));
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
header("Content-Length: " . filesize($file));
flush(); // this doesn't really matter.
$fp = fopen($file, "r");
while (!feof($fp))
{
    echo fread($fp, 65536);
    flush(); // this is essential for large downloads
}
fclose($fp); ```

All pdfs urls are public accessible
https://abc/wp-content/uploads/securepdfs/2019/05/Testing-pdf-1.pdf

Body:
You can use below code in the .htaccess file to block directory access from URL.

Options -Indexes


问:
Problem creating a frequency array of a given array
I am trying to create a frequency array of a given array on Fortran 95. For instance if I have an array (\1 2 4 2 4 2 5), the frequency array should be the number of times each item appears; (\1 3 2 3 2 3 1). So because there are only 1 of 5s in the original array, the last entry in the new array is 1 and because there are 3 of 2s in the original array, the corresponding entries on the new array is a 2.

Below is a sample of the code I have, but I keep getting errors. I was wondering if anyone would be willing to give me some guidance and help on what I could be doing wrong. It would be very much appreciated.

I haven't included the part of the code that generates my original array because I'm pretty sure it is correct so here is just the subroutine for the frequency array. Also the original array was sorted in ascending order outside this subroutine. Perhaps I didn't pass the original array, num(i) correctly??

```<code>INTEGER, DIMENSION(100)::num(100)
    INTEGER, DIMENSION(100)::freq(100)
    INTEGER:: i=0, k=0, numinteger, count=0

CALL FreqArray(num, numinteger,freq)

SUBROUTINE FreqArray(num, numinteger, freq)

INTEGER, INTENT(IN):: num(100), numinteger
INTEGER, INTENT(OUT):: freq(100)

DO i=1,9
    count=0
    DO k=1, numinteger
        IF (num(k)==i)THEN
            count=count+1
        END IF
    END DO
    freq(i)=count
END DO

PRINT*, "Frequency of Digits"
PRINT*, " "
WRITE(*,'(1X,A,T35,A)'),"Digit","Frequency"
WRITE(*,'(1X,I1,T35,I1)'),num(i),freq(i)

END SUBROUTINE
</code>```

Thanks so much for your time.

答:
I guess that the "(9)" is overriding the "DIMENSION(100)" making "freq" an array of length 9.  Thus for the third argument the actual argument is length 9, while the dummy is length 100.   Which causes your error message "actual argument ... is smaller than dummy size".

Other suggestions: you could make the subroutine more general using declarations "..., dimension (:) ::  num".    Then use the "size" intrinsic to determine the size of the num.   freq could be fixed to 9 since there are always 9 digits.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to create a frequency array of a given array on Fortran 95. For instance if I have an array (\1 2 4 2 4 2 5), the frequency array should be the number of times each item appears; (\1 3 2 3 2 3 1). So because there are only 1 of 5s in the original array, the last entry in the new array is 1 and because there are 3 of 2s in the original array, the corresponding entries on the new array is a 2.

Below is a sample of the code I have, but I keep getting errors. I was wondering if anyone would be willing to give me some guidance and help on what I could be doing wrong. It would be very much appreciated.

I haven't included the part of the code that generates my original array because I'm pretty sure it is correct so here is just the subroutine for the frequency array. Also the original array was sorted in ascending order outside this subroutine. Perhaps I didn't pass the original array, num(i) correctly??

INTEGER, DIMENSION(100)::num(100)
    INTEGER, DIMENSION(100)::freq(100)
    INTEGER:: i=0, k=0, numinteger, count=0

CALL FreqArray(num, numinteger,freq)

SUBROUTINE FreqArray(num, numinteger, freq)

INTEGER, INTENT(IN):: num(100), numinteger
INTEGER, INTENT(OUT):: freq(100)

DO i=1,9
    count=0
    DO k=1, numinteger
        IF (num(k)==i)THEN
            count=count+1
        END IF
    END DO
    freq(i)=count
END DO

PRINT*, "Frequency of Digits"
PRINT*, " "
WRITE(*,'(1X,A,T35,A)'),"Digit","Frequency"
WRITE(*,'(1X,I1,T35,I1)'),num(i),freq(i)

END SUBROUTINE

Thanks so much for your time.


问:
How to group categorical column followed by numerical column, and based on this group to bin the numerical values
I have a dataset, in which the column "Type" is basically shapes, and corresponding to that, the column "Volume" consists of volume to that shape

Now I need to do the following task:

Group-by shape

And for each shape, group-by volume

And for each shape and volume, define a range and form bins

Input:

```<code> Type             Volume

 Cylinder          100
 Square            300
 Cylinder          200
 Oval              100
 Square            320
 Cylinder          150
 Oval              600
 Round             1000
 Square            900
 Round             1500
</code>```

Output:

```<code> Type              Volume       Bin

 Cylinder          100            1
 Cylinder          150            1
 Cylinder          200            2
 Oval              100            1
 Oval              600            3
 Round             1000           1
 Round             1500           2
 Square            300            1
 Square            320            1
 Square            900            3
</code>```

The bin would be as below:

1.Cylinder -> Bin1(100-200), Bin2(201-300) ....

2.Oval -> Bin1(100-200), ..... Bin3(500-600)....
....

Code:

```<code>  grouped=df_dim.groupby('Type', as_index=False)
  def test(group):
     return group.reset_index()
  def group_vol(group):
     groupedVol =
         group.groupby(pd.cut(group["Target_BrimVol"],
         np.arange(0,5000,200)),as_index=False)

     return groupedVol.apply(test)

  gr = grouped.apply(group_vol)
  print(gr)
</code>```

答:
I think you can try the code below.

testdf = df.groupby('Type',as_index=False).apply(lambda x: x.groupby(pd.cut(x["Vol"],np.arange(x["Volume"].min(),x["Volume"].max(),200)),as_index=False).apply(test))
```

<p>What is happening here is, the first <code>groupby</code> basically groups the Dataframe into "Type" category and then you want to group it based on the ranges. For this you can group it again using the lambda function using <code>pd.cut</code> function to make small cuts of interval based on your range. In this case I am just taking the max and min value and cutting it in intervals of 200. After this , if you want to merge the outputs back together forming a Dataframe again, using one more apply to merge them back.
like this,</p>

<pre class="lang-python prettyprint-override"><code>def test(group):
   #Write your function here. Whatever you want to perform.
   return group.merge(group)
</code>```

And I am using as_index=False to reset the index here so that the dataframe is rearranged as per the new index.

Hope this helps.

Edit:-
For bins, you do not have to worry because each groupby creates a new index, which you can use for your purpose. As in,

Index1  Index2  Type  Volume
0 0 Cylinder  100
0 0 Cylinder  140
0 1 Cylinder  250
1 0 Oval  154
1 4 Oval 999
2 1 Circle  328
```

Body:
I have a dataset, in which the column "Type" is basically shapes, and corresponding to that, the column "Volume" consists of volume to that shape

Now I need to do the following task:

Group-by shape

And for each shape, group-by volume

And for each shape and volume, define a range and form bins

Input:

 Type             Volume

 Cylinder          100
 Square            300
 Cylinder          200
 Oval              100
 Square            320
 Cylinder          150
 Oval              600
 Round             1000
 Square            900
 Round             1500

Output:

 Type              Volume       Bin

 Cylinder          100            1
 Cylinder          150            1
 Cylinder          200            2
 Oval              100            1
 Oval              600            3
 Round             1000           1
 Round             1500           2
 Square            300            1
 Square            320            1
 Square            900            3

The bin would be as below:

1.Cylinder -> Bin1(100-200), Bin2(201-300) ....

2.Oval -> Bin1(100-200), ..... Bin3(500-600)....
....

Code:

  grouped=df_dim.groupby('Type', as_index=False)
  def test(group):
     return group.reset_index()
  def group_vol(group):
     groupedVol =
         group.groupby(pd.cut(group["Target_BrimVol"],
         np.arange(0,5000,200)),as_index=False)

     return groupedVol.apply(test)

  gr = grouped.apply(group_vol)
  print(gr)

Body:
I think you can try the code below.

testdf = df.groupby('Type',as_index=False).apply(lambda x: x.groupby(pd.cut(x["Vol"],np.arange(x["Volume"].min(),x["Volume"].max(),200)),as_index=False).apply(test))

What is happening here is, the first groupby basically groups the Dataframe into "Type" category and then you want to group it based on the ranges. For this you can group it again using the lambda function using pd.cut function to make small cuts of interval based on your range. In this case I am just taking the max and min value and cutting it in intervals of 200. After this , if you want to merge the outputs back together forming a Dataframe again, using one more apply to merge them back.
like this,

def test(group):
   #Write your function here. Whatever you want to perform.
   return group.merge(group)

And I am using as_index=False to reset the index here so that the dataframe is rearranged as per the new index.

Hope this helps.

Edit:-
For bins, you do not have to worry because each groupby creates a new index, which you can use for your purpose. As in,

Index1  Index2  Type  Volume
0 0 Cylinder  100
0 0 Cylinder  140
0 1 Cylinder  250
1 0 Oval  154
1 4 Oval 999
2 1 Circle  328


问:
How to solve this CSS is not a function error
I have a small jQuery code but it gives me some errors. Can anybody help me with this error?

Code:

```<code><input type="checkbox">
<input type="checkbox" checked>
<input type="checkbox">
<input type="checkbox" checked>
<input type="checkbox">
</code>```

JS

```<code>$(function() {
  var checkboxes = $("input[type=checkbox]")
      checkboxes.is(':checked').css('background-color', 'red')
      checkboxes.on('change', function() {
    var checkbox = $(this)
    checkbox.css('background-color', checkbox.is(':checked') ? 'blue' : 'transparent')
  })
})
</code>```

CSS

```<code>  input[type='checkbox'] {
   -webkit-appearance: none;
    width: 20px;
    height: 20px;
   background: grey;
 }

input[type='checkbox']:checked {
  background: red;}
</code>```

Also here is link:
    https://jsfiddle.net/3y9Lvobc/2/

Error in console is:

```<code> checkboxes.is(...).css is not a function
</code>```

答:
.is returns a boolean value and not a jquery object. So it doesnt have .css method.

You can instead use .filter

```<code>checkboxes.filter(':checked').css('background-color', 'red')
</code>```

.filter will return all the checkboxes which are :checked.

Or alternatively, you can use an if condition, like below:

```<code>if(checkboxes.is(':checked')) {
   checkboxes.css('background-color', 'red');
}
</code>```

Body:
I have a small jQuery code but it gives me some errors. Can anybody help me with this error?

Code:

<input type="checkbox">
<input type="checkbox" checked>
<input type="checkbox">
<input type="checkbox" checked>
<input type="checkbox">

JS

$(function() {
  var checkboxes = $("input[type=checkbox]")
      checkboxes.is(':checked').css('background-color', 'red')
      checkboxes.on('change', function() {
    var checkbox = $(this)
    checkbox.css('background-color', checkbox.is(':checked') ? 'blue' : 'transparent')
  })
})

CSS

  input[type='checkbox'] {
   -webkit-appearance: none;
    width: 20px;
    height: 20px;
   background: grey;
 }

input[type='checkbox']:checked {
  background: red;}

Also here is link:
    https://jsfiddle.net/3y9Lvobc/2/

Error in console is:

 checkboxes.is(...).css is not a function

Body:
.is returns a boolean value and not a jquery object. So it doesnt have .css method.

You can instead use .filter

checkboxes.filter(':checked').css('background-color', 'red')

.filter will return all the checkboxes which are :checked.

Or alternatively, you can use an if condition, like below:

if(checkboxes.is(':checked')) {
   checkboxes.css('background-color', 'red');
}


问:
Turn off autosuggest for EditText?
Is there a way to programmatically turn off that autosuggest list which pops up as you type in EditText?</p>

答:
For the android version 8.0 or above this code is not working
and for the autocomplete textview also this code not working so i will suggest you to use below code for the Disable the auto suggestions in 8.0 or above android vesrion use this property of edittext  android:importantForAutofill="no"

```<code>                   <EditText
                            android:id="@+id/name"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:enabled="false"
                            android:focusable="false"
                            android:imeOptions="actionDone"
                            android:maxLength="80"
                            android:maxLines="1"
                            android:textColor="@color/colorBlack"
                            android:textColorHint="@color/colorBlack"
                            android:importantForAutofill="no"
                            android:textSize="@dimen/_12sdp"
                            app:bFontsEdt="light" />
</code>```

and for the AutoComplete textview like this use this Field to Disable Auto suggestion android:importantForAutofill="no" :

```<code>      <AutoCompleteTextView
                        android:id="@+id/autocompleteEditTextView"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="@dimen/_3sdp"
                        android:layout_marginTop="@dimen/_5sdp"
                        android:background="@null"
                        android:imeOptions="actionDone"
                        android:singleLine="true"
                        android:text=""
                        android:textColor="@color/colorBlack"
                        android:textColorHint="@color/colorGrayDark"
                        android:importantForAutofill="no"
                        android:textSize="@dimen/_12sdp" />
</code>```

ContentLicense: CC BY-SA 2.5

Title: Turn off autosuggest for EditText?

Body:
For the android version 8.0 or above this code is not working
and for the autocomplete textview also this code not working so i will suggest you to use below code for the Disable the auto suggestions in 8.0 or above android vesrion use this property of edittext  android:importantForAutofill="no"

                   <EditText
                            android:id="@+id/name"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:enabled="false"
                            android:focusable="false"
                            android:imeOptions="actionDone"
                            android:maxLength="80"
                            android:maxLines="1"
                            android:textColor="@color/colorBlack"
                            android:textColorHint="@color/colorBlack"
                            android:importantForAutofill="no"
                            android:textSize="@dimen/_12sdp"
                            app:bFontsEdt="light" />

and for the AutoComplete textview like this use this Field to Disable Auto suggestion android:importantForAutofill="no" :

      <AutoCompleteTextView
                        android:id="@+id/autocompleteEditTextView"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="@dimen/_3sdp"
                        android:layout_marginTop="@dimen/_5sdp"
                        android:background="@null"
                        android:imeOptions="actionDone"
                        android:singleLine="true"
                        android:text=""
                        android:textColor="@color/colorBlack"
                        android:textColorHint="@color/colorGrayDark"
                        android:importantForAutofill="no"
                        android:textSize="@dimen/_12sdp" />


问:
React Router with Path Params Not working
I have a react BrowserRouter with the following configuration.

```<code><BrowserRouter>
        <div>
            <Switch>
                <Route path={`/`} component={Home} exact/>
                <Route path={`/about`} render={(props) => <About {...props}/>} exact/>
                <Route path={`/products/:id/:slug`} render={(props) => <Products {...props}/>} exact/>
            </Switch>
        </div>
</code>```

In the About Page there are products with the following  tag. If I click a link, the url changes and Product page is getting rendered correctly.

```<code><Link to={'/products/' + product.id + '/' + product.slug>{product.name }</Link>
</code>```

But when I directly Land to Product page using the exact URL. rendering won't work.

```<code> e.g localhost:3000/products/123/books
</code>```

Any idea what's causing the issue?

答: I believe you issue is you get error CANNOT GET when you tru the direct url. Try setting historyApiFallback: true in your webpack.config.js

Body:
I have a react BrowserRouter with the following configuration.

<BrowserRouter>

            <Switch>
                <Route path={`/`} component={Home} exact/>
                <Route path={`/about`} render={(props) => <About {...props}/>} exact/>
                <Route path={`/products/:id/:slug`} render={(props) => <Products {...props}/>} exact/>
            </Switch>

In the About Page there are products with the following  tag. If I click a link, the url changes and Product page is getting rendered correctly.

<Link to={'/products/' + product.id + '/' + product.slug>{product.name }</Link>

But when I directly Land to Product page using the exact URL. rendering won't work.

 e.g localhost:3000/products/123/books

Any idea what's causing the issue?


问:
Pagination in cassandra with Spring-data
I'm trying to get paginated results in cassandra using springboot, but I'm not getting desired results. Here is my code.

```<code>  Slice<User> usersByNameSlice =
      userRepository.findAll(CassandraPageRequest.first(10));
  while (usersByNameSlice .hasNext()) {
//.. process
    usersByNameSlice = userRepository.findAll(usersByNameSlice.nextPageable());
  }
</code>```

I have around 35 users. This while loop works 3 times covering 30 users, but it comes out of the while loop after 30. How to solve this problem?

答:
I think that you need to change the condition of the while loop to usersByNameSlice.hasContent() to check if there is content in the slice at all.

(Or maybe to combine it with check isPaged() even - because nextPageable on the last page will return unpaged state).

Body:
I'm trying to get paginated results in cassandra using springboot, but I'm not getting desired results. Here is my code.

  Slice<User> usersByNameSlice =
      userRepository.findAll(CassandraPageRequest.first(10));
  while (usersByNameSlice .hasNext()) {
//.. process
    usersByNameSlice = userRepository.findAll(usersByNameSlice.nextPageable());
  }

I have around 35 users. This while loop works 3 times covering 30 users, but it comes out of the while loop after 30. How to solve this problem?


问:
print!() executes after the input is entered
i want to know why the print!() macro here executes after the read_line

```<code>// ./src/main.rs
use std::io;

fn main() {
    print!("Input : ");
    let stdin = io::stdin();
    let mut input = String::new();
    stdin.read_line(&mut input).expect("Couldn't read_line");
}
</code>```

This code prints out :

```<code>   heyy
   Input :
</code>```

But i expect :

```<code>Input : heyy
</code>```

答:
This is how I solved the problem(thanks to Vaughan Hills) :</p>

```<code>// Returns the input for a given message - msg
fn input(msg : &str) -> String {
    let mut input = String::new();
    print!("{}", msg);
    io::stdout().flush().unwrap();
    io::stdin().read_line(&mut input).unwrap();
    input.trim().to_string()
}
</code>```

Body:
i want to know why the print!() macro here executes after the read_line

// ./src/main.rs
use std::io;

fn main() {
    print!("Input : ");
    let stdin = io::stdin();
    let mut input = String::new();
    stdin.read_line(&mut input).expect("Couldn't read_line");
}

This code prints out :

   heyy
   Input :

But i expect :

Input : heyy

Body:
This is how I solved the problem(thanks to Vaughan Hills) :

// Returns the input for a given message - msg
fn input(msg : &str) -> String {
    let mut input = String::new();
    print!("{}", msg);
    io::stdout().flush().unwrap();
    io::stdin().read_line(&mut input).unwrap();
    input.trim().to_string()
}


问:
How to verify context.data against a model schema in feathersjs?
For a complex service in feathersjs which requires validation on multiple models what is the way forward?

Assume a service named uploads which needs to verify the POST data against an existing mongoose model. How do we achieve it?

答: I managed to do this by calling the service which uses the mongoose model to validate its create method. I guess my question is a bit confusing and now my answer seems to be another layer of confusion. Here is a drawing.


问:
Sort array of days in ascending order
I have an array that contains unique strings of day names. The day names will be in random order. - eg:

```<code>["Sun 10am", "Sat 4pm", "Sat 10am", "Wed 3pm", "Sun 4pm"]
</code>```

I want to use javascript to sort that array so that it will be in ascending order.

```<code>["Wed 3pm", "Sat 10am", "Sat 4pm", "Sun 10am", "Sun 4pm"]
</code>```

Can anybody suggest the best way to do that?

Thank you

答:
You could take an object for the values of the day and sort by the time.

const
    getTime = string => {
        var [day, hour, meridian] = string.match(/^(\D{3}) (\d+)(am|pm)/).slice(1),
            days = { Mon: 1, Tue: 2, Wed: 3, Thu: 4, Fri: 5, Sat: 6, Sun: 7 };

        return days[day] * 24 + +hour + (meridian === 'pm' && 12) + (hour === '12' && -12);
    };
var array = ["Sun 10am", "Sat 4pm", "Sat 10am", "Wed 3pm", "Sun 4pm", "Sat 12pm", "Sat 12am"];

array.sort((a, b) => getTime(a) - getTime(b));

console.log(array);```

Title: Sort array of days in ascending order

Body:
I have an array that contains unique strings of day names. The day names will be in random order. - eg:

["Sun 10am", "Sat 4pm", "Sat 10am", "Wed 3pm", "Sun 4pm"]

I want to use javascript to sort that array so that it will be in ascending order.

["Wed 3pm", "Sat 10am", "Sat 4pm", "Sun 10am", "Sun 4pm"]

Can anybody suggest the best way to do that?

Thank you


问:
How to source a file having environment variables
I have a source file having environment variables (few environmental variables are conditional based as well).
source file is like (filename: global_setup)

```<code>if( -f /tools/tool/bin) then
    setenv SHELL /bin/csh
endif

setenv LICENCE_FILE 2457@abc
setenv ...........
</code>```

I want to source this file using python script. Code is like this:

```<code>import subprocess
import os

if os.path.isfile('global_setup'):
    subprocess.call(['/bin/csh', '-c', 'source ~/global_setup'], shell=True)
else:
    print("file not found");
</code>```

But this is not working. Showing error as:

/home/global_setup: line 53: syntax error: unexpected end of file

Also, I tried to remove this EOF error by changing file format to Unix.
Even it works, i doubt setup will be done in some other terminal as i am using subprocess.call() in python.

答:
Instead of doing it this way, you should be doing one of two things:

Source your files in the linux shell before invoking your script.

Convert your file into a dotenv file that Python can read using the Python-dotenv module.

Sourcing it before is easier IMO, instead of sourcing it during runtime using subprocess.

Body:
I have a source file having environment variables (few environmental variables are conditional based as well).
source file is like (filename: global_setup)

if( -f /tools/tool/bin) then
    setenv SHELL /bin/csh
endif

setenv LICENCE_FILE 2457@abc
setenv ...........

I want to source this file using python script. Code is like this:

import subprocess
import os

if os.path.isfile('global_setup'):
    subprocess.call(['/bin/csh', '-c', 'source ~/global_setup'], shell=True)
else:
    print("file not found");

But this is not working. Showing error as:

/home/global_setup: line 53: syntax error: unexpected end of file

Also, I tried to remove this EOF error by changing file format to Unix.
Even it works, i doubt setup will be done in some other terminal as i am using subprocess.call() in python.


答:
Because is returns a Boolean. Use find:

```<code>checkboxes.find(':checked').css('background-color', 'red')
</code>```

Title: How to solve this CSS is not a function error

Body:
Because is returns a Boolean. Use find:

checkboxes.find(':checked').css('background-color', 'red')


问:
Oracle Reports 10g Crash When I Change Fonts of Text
When I change fonts of text items (When I changed about 5-6 of it), Oracle Reports Crashes. It gives error message "Not Responding". Why? How can I solve it?

Device OS: Windows 10 Pro
RAM: 8 GB
64-bit

答:
Unlike Forms (which is a fine piece of software), Reports is one of most unstable tools I've ever worked with. Yes, it tends to crash without a reason. It isn't even "don't do this because it'll crash" so that you could create your own "don't do it" list. It happens for any reason - in your current case, when you change a font.

So, what to do?

check My Oracle Support (previously called Metalink) to see whether there's a patch for your Reports (i.e. Developer Suite) version

save frequently so that changes you've made aren't lost (and you'll have to do everything again)

reboot sometimes helps

I've installed Developer Suite 10g onto a virtual machine that runs under Windows XP (which is/was a certified combination). Have a look at certification matrices; if operating system + Reports version isn't certified, there's really no guarantee that it'll work.

as I've told you - even if it is certified, it crashes anyway

Unfortunately, I don't have a magic wand to solve your problems. Be patient as much as you can. Good luck, I sympathize with you.


问:
How to play video in HTML page
I am trying to play a mp4 video on my HTML page, I have searched the web and found that in HTML5 I can do this with video tag like this below

```<code><video width="320" height="240" autoplay>
  <source src="movie.mp4" type="video/mp4">
</video>
</code>```

Issue I am facing

My main issue is my video is stored in my local computer in some location, So how can I call that from that path

In my system it is located in D drive so I want to call it from there

I am new to this so I don't know if I am doing it the right way; is my approach correct?

My requirement is to auto-play video on my web page

I am doing like this

```<code><video width="320" height="240" autoplay>
  <source src="D:\Video\samplevideo.mp4" type="video/mp4">
</video>
</code>```

D:\Video\samplevideo.mp4 is the path of my file and samplevideo.mp4 is the name of the video

On Chrome it show error Not allowed to load local resource: file:///D:/Video/samplevideo.mp4

And on Firefox All candidate resources failed to load. Media load paused.

Edit

My main focus is to play video on webpage.

I need to play a video on the web (HTML page) when page is loaded I have that video in my system at D:\Video\samplevideo.mp4 this path, how can I play that video when page is loaded.

答:
For the very basics of getting this working move D:/Video/samplevideo.mp4 to the same location as your html file.

Then change your code to:

```<code><video width="320" height="240" autoplay>
  <source src="samplevideo.mp4" type="video/mp4">
</video>
</code>```

Make sure Tomcat is set up to server the .mp4 mimetype or extention.

Next you should read up on how paths work in HTML.

Title: How to play video in HTML page

Body:
I am trying to play a mp4 video on my HTML page, I have searched the web and found that in HTML5 I can do this with video tag like this below

<video width="320" height="240" autoplay>
  <source src="movie.mp4" type="video/mp4">
</video>

Issue I am facing

My main issue is my video is stored in my local computer in some location, So how can I call that from that path

In my system it is located in D drive so I want to call it from there

I am new to this so I don't know if I am doing it the right way; is my approach correct?

My requirement is to auto-play video on my web page

I am doing like this

<video width="320" height="240" autoplay>
  <source src="D:\Video\samplevideo.mp4" type="video/mp4">
</video>

D:\Video\samplevideo.mp4 is the path of my file and samplevideo.mp4 is the name of the video

On Chrome it show error Not allowed to load local resource: file:///D:/Video/samplevideo.mp4

And on Firefox All candidate resources failed to load. Media load paused.

Edit

My main focus is to play video on webpage.

I need to play a video on the web (HTML page) when page is loaded I have that video in my system at D:\Video\samplevideo.mp4 this path, how can I play that video when page is loaded.

Body:
For the very basics of getting this working move D:/Video/samplevideo.mp4 to the same location as your html file.

Then change your code to:

<video width="320" height="240" autoplay>
  <source src="samplevideo.mp4" type="video/mp4">
</video>

Make sure Tomcat is set up to server the .mp4 mimetype or extention.

Next you should read up on how paths work in HTML.


问:
What does the "declare a static final serialVersionUID" warning mean and how to fix?

Possible Duplicate:

  What does it mean: The serializable class does not declare a static final serialVersionUID field?

Java compiler warning: The serializable class [*****] does not declare a static final serialVersionUID field of type long.

Why? How to fix it?

答:
just add

```<code>private static final long serialVersionUID = 1L;//or some long
</code>```

Docs describe it pretty well

The serialization runtime associates
  with each serializable class a version
  number, called a serialVersionUID,
  which is used during deserialization
  to verify that the sender and receiver
  of a serialized object have loaded
  classes for that object that are
  compatible with respect to
  serialization. If the receiver has
  loaded a class for the object that has
  a different serialVersionUID than that
  of the corresponding sender's class,
  then deserialization will result in an
  InvalidClassException. A serializable
  class can declare its own
  serialVersionUID explicitly by
  declaring a field named
  "serialVersionUID" that must be
  static, final, and of type long:

```<code>ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L;
</code>```

If a
  serializable class does not explicitly
  declare a serialVersionUID, then the
  serialization runtime will calculate a
  default serialVersionUID value for
  that class based on various aspects of
  the class, as described in the
  Java(TM) Object Serialization
  Specification. However, it is strongly
  recommended that all serializable
  classes explicitly declare
  serialVersionUID values, since the
  default serialVersionUID computation
  is highly sensitive to class details
  that may vary depending on compiler
  implementations, and can thus result
  in unexpected InvalidClassExceptions
  during deserialization. Therefore, to
  guarantee a consistent
  serialVersionUID value across
  different java compiler
  implementations, a serializable class
  must declare an explicit
  serialVersionUID value. It is also
  strongly advised that explicit
  serialVersionUID declarations use the
  private modifier where possible, since
  such declarations apply only to the
  immediately declaring
  class--serialVersionUID fields are not
  useful as inherited members.

Also See

why-should-i-bother-about-serialversionuid

Body:
just add

private static final long serialVersionUID = 1L;//or some long

Docs describe it pretty well

The serialization runtime associates
  with each serializable class a version
  number, called a serialVersionUID,
  which is used during deserialization
  to verify that the sender and receiver
  of a serialized object have loaded
  classes for that object that are
  compatible with respect to
  serialization. If the receiver has
  loaded a class for the object that has
  a different serialVersionUID than that
  of the corresponding sender's class,
  then deserialization will result in an
  InvalidClassException. A serializable
  class can declare its own
  serialVersionUID explicitly by
  declaring a field named
  "serialVersionUID" that must be
  static, final, and of type long:

ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L;

If a
  serializable class does not explicitly
  declare a serialVersionUID, then the
  serialization runtime will calculate a
  default serialVersionUID value for
  that class based on various aspects of
  the class, as described in the
  Java(TM) Object Serialization
  Specification. However, it is strongly
  recommended that all serializable
  classes explicitly declare
  serialVersionUID values, since the
  default serialVersionUID computation
  is highly sensitive to class details
  that may vary depending on compiler
  implementations, and can thus result
  in unexpected InvalidClassExceptions
  during deserialization. Therefore, to
  guarantee a consistent
  serialVersionUID value across
  different java compiler
  implementations, a serializable class
  must declare an explicit
  serialVersionUID value. It is also
  strongly advised that explicit
  serialVersionUID declarations use the
  private modifier where possible, since
  such declarations apply only to the
  immediately declaring
  class--serialVersionUID fields are not
  useful as inherited members.

Also See

why-should-i-bother-about-serialversionuid


问:
How can I change the style of a control (CListBox) initialized with DDX_Control, before DDX_Control is called
I'm modifying an existing project and a dialog has controls I am subclassing to theme differently in some cases (in other cases I will leave it entirely alone).  By the time DDX_Control() is called during DoDataExchange(), the hwnd for the ListBox already has styles applied.  Specifically, at this time even if I do SetWindowLongPtr(), the LBS_OWNERDRAWFIXED does not work.  By "does not work," I mean that although the style is applied, owner draw messages are not received by the CListBox.

Conversely, if I avoid the DDX_Control() and simply do a create, the ListBox does receive the messages and can be ownerdrawn.  But if I do this there are now two HWND, only one of which is returned by GetDlgItem().  I believe I can make this work if necessary, but I wondered if there is a secret to intercept the HWND creation of the controls in the dialog (actually a CPropertyPage).

Below is code that doesn't work, with more commented code that "works" but isn't the way I wanted it to work, if possible.

```<code>void CMyPropertySheet::DoDataExchange(CDataExchange* pDX)
{
    HWND hWndCtrl;
    pDX->m_pDlgWnd->GetDlgItem(IDC_LIST1, &hWndCtrl);

    if (themed) {
        DWORD style = GetWindowLongPtr(hWndCtrl, GWL_STYLE) | LBS_OWNERDRAWFIXED;
        SetWindowLongPtr(hWndCtrl, GWL_STYLE, style);
        DDX_Control(pDX, IDC_LIST1, m_listbox);
        //RECT wr;
        //::GetWindowRect(hWndCtrl, &wr);
        //m_listbox.Create(style, wr, this, IDC_LIST1);
    } else {
        DDX_Control(pDX, IDC_LIST1, m_listbox);
    }
</code>```

I should probably add I tried subclassing the window, but it didn't help, and CMyPropertySheet::PreSubclassWindow wasn't soon enough, either.

答:
Some creation flags like LBS_OWNERDRAWFIXED and LBS_SORT are cached and modifying them afterwards have no effect. You have to change the template, or just make a duplicate of the listbox. Copy the style of the old listbox, then hide that listbox, change its ID, and create a new listbox based on the old one. You then have to remove DDX_Control(pDX, IDC_LIST1, m_listbox)

The example below starts with a standard list which has its sort flag set. It duplicates the listbox and disables the sort option.

For simplicity this example avoids LBS_OWNERDRAWFIXED, it uses LBS_SORT instead.

```<code>class CMyPropertyPage : public CPropertyPage
{
public:
    CListBox m_listbox;
    int m_listbox_index;

    CMyPropertyPage(int idd) : CPropertyPage(idd)
    {
        m_listbox_index = 1;
    }

    void DoDataExchange(CDataExchange* pDX)
    {
        //This function is automatically called before
        //CPropertyPage::OnInitDialog is complete
        //On the first call, IDC_LIST1 will point to the template listbox
        if(m_listbox.m_hWnd)
        {
            //m_listbox is ready,
            //IDC_LIST1 will refer to the new listbox
            DDX_LBIndex(pDX, IDC_LIST1, m_listbox_index);
        }
    }

    BOOL OnInitDialog()
    {
        CPropertyPage::OnInitDialog();

        CListBox* old_listbox = (CListBox*)GetDlgItem(IDC_LIST1);
        if(old_listbox)
        {
            DWORD style = ~LBS_SORT & GetWindowLongPtr(old_listbox->m_hWnd, GWL_STYLE);
            CRect rc;
            old_listbox->GetWindowRect(&rc);
            ScreenToClient(&rc);
            old_listbox->SetDlgCtrlID(0);//change the old ID to something unused
            old_listbox->ShowWindow(SW_HIDE); //hide the old listbox
            m_listbox.Create(style | WS_BORDER, rc, this, IDC_LIST1);
            m_listbox.SetFont(GetFont());
        }

        ASSERT(m_listbox.GetDlgCtrlID() == IDC_LIST1);
        m_listbox.AddString(L"2");
        m_listbox.AddString(L"1");
        m_listbox.AddString(L"0");

        UpdateData(FALSE);

        return TRUE;
    }
};

class CMyWinApp : public CWinApp
{
    BOOL InitInstance()
    {
        CWinApp::InitInstance();
        CPropertySheet sh;
        CMyPropertyPage page(IDD_PAGE1);
        sh.AddPage(&page);
        sh.DoModal();
        return TRUE;
    }
} myapp;
</code>```

Body:
I'm modifying an existing project and a dialog has controls I am subclassing to theme differently in some cases (in other cases I will leave it entirely alone).  By the time DDX_Control() is called during DoDataExchange(), the hwnd for the ListBox already has styles applied.  Specifically, at this time even if I do SetWindowLongPtr(), the LBS_OWNERDRAWFIXED does not work.  By "does not work," I mean that although the style is applied, owner draw messages are not received by the CListBox.

Conversely, if I avoid the DDX_Control() and simply do a create, the ListBox does receive the messages and can be ownerdrawn.  But if I do this there are now two HWND, only one of which is returned by GetDlgItem().  I believe I can make this work if necessary, but I wondered if there is a secret to intercept the HWND creation of the controls in the dialog (actually a CPropertyPage).

Below is code that doesn't work, with more commented code that "works" but isn't the way I wanted it to work, if possible.

void CMyPropertySheet::DoDataExchange(CDataExchange* pDX)
{
    HWND hWndCtrl;
    pDX->m_pDlgWnd->GetDlgItem(IDC_LIST1, &hWndCtrl);

    if (themed) {
        DWORD style = GetWindowLongPtr(hWndCtrl, GWL_STYLE) | LBS_OWNERDRAWFIXED;
        SetWindowLongPtr(hWndCtrl, GWL_STYLE, style);
        DDX_Control(pDX, IDC_LIST1, m_listbox);
        //RECT wr;
        //::GetWindowRect(hWndCtrl, &wr);
        //m_listbox.Create(style, wr, this, IDC_LIST1);
    } else {
        DDX_Control(pDX, IDC_LIST1, m_listbox);
    }

I should probably add I tried subclassing the window, but it didn't help, and CMyPropertySheet::PreSubclassWindow wasn't soon enough, either.

Body:
Some creation flags like LBS_OWNERDRAWFIXED and LBS_SORT are cached and modifying them afterwards have no effect. You have to change the template, or just make a duplicate of the listbox. Copy the style of the old listbox, then hide that listbox, change its ID, and create a new listbox based on the old one. You then have to remove DDX_Control(pDX, IDC_LIST1, m_listbox)

The example below starts with a standard list which has its sort flag set. It duplicates the listbox and disables the sort option.

For simplicity this example avoids LBS_OWNERDRAWFIXED, it uses LBS_SORT instead.

class CMyPropertyPage : public CPropertyPage
{
public:
    CListBox m_listbox;
    int m_listbox_index;

    CMyPropertyPage(int idd) : CPropertyPage(idd)
    {
        m_listbox_index = 1;
    }

    void DoDataExchange(CDataExchange* pDX)
    {
        //This function is automatically called before
        //CPropertyPage::OnInitDialog is complete
        //On the first call, IDC_LIST1 will point to the template listbox
        if(m_listbox.m_hWnd)
        {
            //m_listbox is ready,
            //IDC_LIST1 will refer to the new listbox
            DDX_LBIndex(pDX, IDC_LIST1, m_listbox_index);
        }
    }

    BOOL OnInitDialog()
    {
        CPropertyPage::OnInitDialog();

        CListBox* old_listbox = (CListBox*)GetDlgItem(IDC_LIST1);
        if(old_listbox)
        {
            DWORD style = ~LBS_SORT & GetWindowLongPtr(old_listbox->m_hWnd, GWL_STYLE);
            CRect rc;
            old_listbox->GetWindowRect(&rc);
            ScreenToClient(&rc);
            old_listbox->SetDlgCtrlID(0);//change the old ID to something unused
            old_listbox->ShowWindow(SW_HIDE); //hide the old listbox
            m_listbox.Create(style | WS_BORDER, rc, this, IDC_LIST1);
            m_listbox.SetFont(GetFont());
        }

        ASSERT(m_listbox.GetDlgCtrlID() == IDC_LIST1);
        m_listbox.AddString(L"2");
        m_listbox.AddString(L"1");
        m_listbox.AddString(L"0");

        UpdateData(FALSE);

        return TRUE;
    }
};

class CMyWinApp : public CWinApp
{
    BOOL InitInstance()
    {
        CWinApp::InitInstance();
        CPropertySheet sh;
        CMyPropertyPage page(IDD_PAGE1);
        sh.AddPage(&page);
        sh.DoModal();
        return TRUE;
    }
} myapp;


问:
Passing multiple parameters from url to html.actionlink
I'm fairly new to MVC and am struggling with routing when I try to pass multiple parameters via the URL.

From a page with the URL: /PersonCAFDetail/Index/3?memberid=4

...I'm trying to get an Html.ActionLink set to point to the Create action such that the id=3 and the memberid=4.

Having read a number of similar posts it seems that the following should work:

```<code>@Html.ActionLink("Create New", "Create", null, new { memberid = "memberid" })
</code>```

However, this results in a URL being created as follows:

```<code><a href="/PersonCAFDetail/Create/3" memberid="memberid">Create New</a>
</code>```

I have a route set up as:

```<code>    routes.MapRoute(
        name: "PersonCAFDetail",
        url: "PersonCAFDetail/Create/{id}/{memberid}",
        defaults: new { controller = "PersonCAFDetail", action = "Create", id = "@\d+", memberid = @"\d+" }
        );
</code>```

The controller accepts two parameters as follows:

```<code> public ActionResult Create(int id, int memberid)
        {
            int cafID = id;
            int personID = memberid;
            ViewBag.detailTypeID = new SelectList(db.tCAFDetailTypes, "detailTypeID", "detailType");
            ViewBag.cafID = new SelectList(db.tFamilyCAFs, "cafID", "issues");
            ViewBag.personID = new SelectList(db.tPersons, "personID", "forename");
            return View();
        }
</code>```

Any help appreciated.

-------edit for model----------

```<code>namespace WhatWorks.Models
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using System.ComponentModel.DataAnnotations;

    public partial class tPersonCAFDetail
    {
        [Key, HiddenInput(DisplayValue=false)]
        public int cafID { get; set; }

        [Key, HiddenInput(DisplayValue = false)]
        public int personID { get; set; }

        [Key, HiddenInput(DisplayValue = false)]
        public int detailTypeID { get; set; }

        [Required, DataType(DataType.MultilineText)]
        public string notes { get; set; }

        public string FullName
        {
            get
            {
                return tPerson.forename + " " + tPerson.surname;
            }
        }

        public virtual tCAFDetailType tCAFDetailType { get; set; }
        public virtual tFamilyCAF tFamilyCAF { get; set; }
        public virtual tPerson tPerson { get; set; }
    }
}
</code>```

答:
You should create an ActionLink which has an overloaded method

```<code>MvcHtmlString HtmlHelper.ActionLink(
    string linkText,
    string actionName,
    string controllerName,
    object routeValues,
    object htmlAttributes
)
</code>```

In your case :

```<code>@Html.ActionLink("Create New", "Create", PersonCAFDetail, new { id = "id", memberid = "memberid" })
</code>```

Body:
I'm fairly new to MVC and am struggling with routing when I try to pass multiple parameters via the URL.

From a page with the URL: /PersonCAFDetail/Index/3?memberid=4

...I'm trying to get an Html.ActionLink set to point to the Create action such that the id=3 and the memberid=4.

Having read a number of similar posts it seems that the following should work:

@Html.ActionLink("Create New", "Create", null, new { memberid = "memberid" })

However, this results in a URL being created as follows:

Create New

I have a route set up as:

    routes.MapRoute(
        name: "PersonCAFDetail",
        url: "PersonCAFDetail/Create/{id}/{memberid}",
        defaults: new { controller = "PersonCAFDetail", action = "Create", id = "@\d+", memberid = @"\d+" }
        );

The controller accepts two parameters as follows:

 public ActionResult Create(int id, int memberid)
        {
            int cafID = id;
            int personID = memberid;
            ViewBag.detailTypeID = new SelectList(db.tCAFDetailTypes, "detailTypeID", "detailType");
            ViewBag.cafID = new SelectList(db.tFamilyCAFs, "cafID", "issues");
            ViewBag.personID = new SelectList(db.tPersons, "personID", "forename");
            return View();
        }

Any help appreciated.

-------edit for model----------

namespace WhatWorks.Models
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using System.ComponentModel.DataAnnotations;

    public partial class tPersonCAFDetail
    {
        [Key, HiddenInput(DisplayValue=false)]
        public int cafID { get; set; }

        [Key, HiddenInput(DisplayValue = false)]
        public int personID { get; set; }

        [Key, HiddenInput(DisplayValue = false)]
        public int detailTypeID { get; set; }

        [Required, DataType(DataType.MultilineText)]
        public string notes { get; set; }

        public string FullName
        {
            get
            {
                return tPerson.forename + " " + tPerson.surname;
            }
        }

        public virtual tCAFDetailType tCAFDetailType { get; set; }
        public virtual tFamilyCAF tFamilyCAF { get; set; }
        public virtual tPerson tPerson { get; set; }
    }
}

Body:
You should create an ActionLink which has an overloaded method

MvcHtmlString HtmlHelper.ActionLink(
    string linkText,
    string actionName,
    string controllerName,
    object routeValues,
    object htmlAttributes
)

In your case :

@Html.ActionLink("Create New", "Create", PersonCAFDetail, new { id = "id", memberid = "memberid" })


问:
how can I fill absent points in a series with average of its two neighbor points
I’ve got two series in my chart. I have data coming every day. I register two kinds of information for every data in both  series. There are five points in the first series but four in the second one.  It is vital for both to have a point for every data. I want the absent point in the second series to be filled by the average of its two neighbor points.

Does highstock have any solution for that?

example:

```<code><script src="jquery.js"></script>
<script src="highstock.js"></script>

<script type="text/javascript">
jQuery(function(){
    var $ = jQuery;

    Highcharts.stockChart('chart', {
        chart: {
            panning: false,
        },
        plotOptions:{
            series:{
                dataGrouping: {
                    forced: true,
                    units: [['day', [1]]]
                },
            }
        },
        series: [{
            type: 'line',
            color:'#23bdbd',
            data: [
                [1558224000000,8197.68969113999992259778082370758056640625],
                [1558310400000,7978.3090724399999089655466377735137939453125],
                [1558396800000,7963.3277791099999376456253230571746826171875],
                [1558483200000,7680.06654589000027044676244258880615234375],
                [1558569600000,7881.846721050000269315205514430999755859375]
            ],
        },
        {
            type: 'line',
            color:'#ff5d5d',
            data: [
                [1558224000000,100],
                [1558310400000,150],
                [1558483200000,2300],
                [1558569600000,5500]
            ],
        }],
    });

});
</script>
<div id="chart"></div>
</code>```

答:
You can achieve it by adding additional logic in the load event callback. Filter the data and find absent points, then add absent points using series.addPoint(). Check the code and demo posted below.

Code:

```<code>  chart: {
    panning: false,
    events: {
      load: function() {
        const chart = this;
        const absentPoints = chart.series[0].xData.filter(
          data => chart.series[1].xData.indexOf(data) === -1
        );

        absentPoints.forEach(absentPoint => {
          const index = chart.series[0].xData.indexOf(absentPoint);
          const value =
            (chart.series[1].yData[index] +
              chart.series[1].yData[index - 1]) /
            2;

          chart.series[1].addPoint([absentPoint, value], false);
        });

        chart.redraw(false);
      }
    }
  }
</code>```

Demo:

https://jsfiddle.net/BlackLabel/91ntpmyr/

API reference:

https://api.highcharts.com/class-reference/Highcharts.Series#addPoint

Body:
You can achieve it by adding additional logic in the load event callback. Filter the data and find absent points, then add absent points using series.addPoint(). Check the code and demo posted below.

Code:

  chart: {
    panning: false,
    events: {
      load: function() {
        const chart = this;
        const absentPoints = chart.series[0].xData.filter(
          data => chart.series[1].xData.indexOf(data) === -1
        );

        absentPoints.forEach(absentPoint => {
          const index = chart.series[0].xData.indexOf(absentPoint);
          const value =
            (chart.series[1].yData[index] +
              chart.series[1].yData[index - 1]) /
            2;

          chart.series[1].addPoint([absentPoint, value], false);
        });

        chart.redraw(false);
      }
    }
  }

Demo:

https://jsfiddle.net/BlackLabel/91ntpmyr/

API reference:

https://api.highcharts.com/class-reference/Highcharts.Series#addPoint


问:
How to retrieve a value from key value pair in XML via SQL Query?
I have a column with name attributes in my database table which is a clob object storing XML data as below. Using SQL, I am trying to retrieve the values of key accountExpires which should give me the value of 123456789L as output.

I tried using nodes(Xquery) and CROSS APPLY etc but I am only fetching those which are typically in Value format like the IIQDisabled or accountFlags etc but I want to retrieve entry key and value pairs. Appreciate your help.

```<code><Attributes>
  <Map>
    <entry key="Division" value="TRAINING"/>
    <entry key="IIQDisabled">
      <value>
        <Boolean>true</Boolean>
      </value>
    </entry>
    <entry key="accountExpires" value="123456789L"/>
    <entry key="accountFlags">
      <value>
        <List>
          <String>Normal User Account</String>
          <String>User Account is Disabled</String>
        </List>
      </value>
    </entry>
    <entry key="department" value="LOYALTY CLUB"/>
    <entry key="distinguishedName" value="CN=Account02\,TM_Test02,OU=SailpointQA,OU=Users...."/>
    <entry key="employeeID" value="333223"/>
    <entry key="givenName" value="TM_Test02"/>
    <entry key="memberOf"/>
    <entry key="mobile" value="9"/>
    <entry key="sAMAccountName" value="TM_Test02.Account02"/>
    <entry key="sAMAccountType" value="805306368"/>
    <entry key="sn" value="Account02"/>
    <entry key="userAccountControl" value="514"/>
  </Map>
</Attributes>

select a.id as id
,pref.value('(@accountExpires)[1]', 'varchar(50)') as accountExpires
,pref.value('.', 'varchar(50)') as test
FROM (
select
         id,CONVERT(XML, attributes, 1) xmlCol
from [identityiq].[identityiq].[spt_work_item_archive]) a
CROSS APPLY xmlCol.nodes('//Attributes/Map') AS ApprovalItem(pref)
</code>```

Expected results :

```<code>id       accountExpires
-----------------
someid   123456789L
</code>```

But actually i am getting true Normal User Account  User Account is Disabled  if use pref.value('.', 'varchar(50)')  in the output as test column.

答:
You can try using the EXTRACTVALUE function and the XPATH</p>

```<code>SELECT EXTRACTVALUE( xmlCol,  '//Map/entry [@key='accountExpires']/@value')

  AS accountExpires

from [identityiq].[identityiq].[spt_work_item_archive])

</code>```

Body:
I have a column with name attributes in my database table which is a clob object storing XML data as below. Using SQL, I am trying to retrieve the values of key accountExpires which should give me the value of 123456789L as output.

I tried using nodes(Xquery) and CROSS APPLY etc but I am only fetching those which are typically in Value format like the IIQDisabled or accountFlags etc but I want to retrieve entry key and value pairs. Appreciate your help.

<Attributes>
  <Map>
    <entry key="Division" value="TRAINING"/>
    <entry key="IIQDisabled">
      <value>
        <Boolean>true</Boolean>
      </value>
    </entry>
    <entry key="accountExpires" value="123456789L"/>
    <entry key="accountFlags">
      <value>
        <List>
          <String>Normal User Account</String>
          <String>User Account is Disabled</String>
        </List>
      </value>
    </entry>
    <entry key="department" value="LOYALTY CLUB"/>
    <entry key="distinguishedName" value="CN=Account02\,TM_Test02,OU=SailpointQA,OU=Users...."/>
    <entry key="employeeID" value="333223"/>
    <entry key="givenName" value="TM_Test02"/>
    <entry key="memberOf"/>
    <entry key="mobile" value="9"/>
    <entry key="sAMAccountName" value="TM_Test02.Account02"/>
    <entry key="sAMAccountType" value="805306368"/>
    <entry key="sn" value="Account02"/>
    <entry key="userAccountControl" value="514"/>
  </Map>
</Attributes>

select a.id as id
,pref.value('(@accountExpires)[1]', 'varchar(50)') as accountExpires
,pref.value('.', 'varchar(50)') as test
FROM (
select
         id,CONVERT(XML, attributes, 1) xmlCol
from [identityiq].[identityiq].[spt_work_item_archive]) a
CROSS APPLY xmlCol.nodes('//Attributes/Map') AS ApprovalItem(pref)

Expected results :

id       accountExpires
-----------------
someid   123456789L

But actually i am getting true Normal User Account  User Account is Disabled  if use pref.value('.', 'varchar(50)')  in the output as test column.

Body:
You can try using the EXTRACTVALUE function and the XPATH

SELECT EXTRACTVALUE( xmlCol,  '//Map/entry [@key='accountExpires']/@value')

  AS accountExpires

from [identityiq].[identityiq].[spt_work_item_archive])


问:
Formatting an Integer using ISO-prefixes for kB,MB,GB,... and kiB,MiB,GiB,
I looking for the function that prints file size on the mode-line in size-indication-mode. I have searched for size-indication-mode in the source but cannot find a code-references to it. So where is the function that prints for example
22k

when file is approximately 22 kilobytes big?

What about difference between
- kilobytes (kB), 1000 bytes, and
- kibibytes (KiB), 1024 bytes, as defined at

Shouldn't Emacs support both?

This is of course not that hard to write but why reinvent the wheel?

http://en.wikipedia.org/wiki/Kibibyte

答:
I noticed that emacs dev (bzr) just go a new function, file-size-human-readable() defined. It does just what I asked for.

Some emacs developer must have heard my call :)


答:
Sourcing a file with subprocess.call() won't have an effect on the environment variables in Python, since subprocess runs, well, a subprocess.

You will need to parse the file yourself if you wish to affect os.environ within your Python interpreter.

Since your file is csh-style, the otherwise very nice envparse module won't do here.

Something you could do, though, is invoke

```<code>env = subprocess.check_output(['/bin/csh', '-c', 'source ~/global_setup; printenv'], shell=True)
</code>```

and parse the resulting env variable line by line and add the contents into os.environ. This way the conditionals within global_setup would also work as expected.

Title: How to source a file having environment variables

Body:
Sourcing a file with subprocess.call() won't have an effect on the environment variables in Python, since subprocess runs, well, a subprocess.

You will need to parse the file yourself if you wish to affect os.environ within your Python interpreter.

Since your file is csh-style, the otherwise very nice envparse module won't do here.

Something you could do, though, is invoke

env = subprocess.check_output(['/bin/csh', '-c', 'source ~/global_setup; printenv'], shell=True)

and parse the resulting env variable line by line and add the contents into os.environ. This way the conditionals within global_setup would also work as expected.


问:
Programmatically using Crashlytics to satisfy GDPR
I'm about to release a scientific iOS app into the App store, for the first time in a few since years. Since I last released an app, GDPR has happened and I'm wondering about the programming mechanics developers are using to satisfy it:

Give the users a choice of enabling Crashlytics/Fabric

Turn off Crashlytics without restarting the iOS app? Is that even possible

Providing a user button to delete the user's data programmatically - is anyone actually using Crashlytics API to do this

The app's backend is Azure based - I don't collect any user data but apparently even Azure collecting IP addresses in a log is sufficient to make my one-person company liable to a fine. Any suggestions how I would programmatically tackle that?

My sense at the moment is to not make my (free) app available in EU territories - Has anyone else given up on EU distribution because of GDPR?

答:
Actually i dont have answer to all your questions, but here are some.

If you want to give user a choice to enable crashlytics or fabric.

First of all, for initialising crashlytics, you use below code normally as :

```<code>Crashlytics.start(withAPIKey: kCrashlyticsFabricKey)
Fabric.with([Crashlytics.self])
</code>```

Now, run this code in selector method of the button that you will provide to enable this in your app.

As per my knowledge, turning of Crashlytics is not possible without restarting app. As crashlytics is never used by "Users" of app, it is used by developer of app to get crash data, so it is simple that developer never wants it to turn off, so Crashltics have provided method as start(withAPIKey:) but no any stop method, and i think there are very less chance that they will provide such methods in near future.

But yes, you have way to stop submitting report. You can subscribe to CrashlyticsDelegate, in which it will give you callback for this method - (void)crashlyticsDidDetectReportForLastExecution:(CLSReport *)report completionHandler:(void (^)(BOOL submit))completionHandler, here in completionHandler if you provide submit = false, then it will ignore that crash Report.
So, if user have disabled it, then you can stop submitting reports in this way.

No idea about this.

No idea about this too.

Body:
Actually i dont have answer to all your questions, but here are some.

If you want to give user a choice to enable crashlytics or fabric.

First of all, for initialising crashlytics, you use below code normally as :

Crashlytics.start(withAPIKey: kCrashlyticsFabricKey)
Fabric.with([Crashlytics.self])

Now, run this code in selector method of the button that you will provide to enable this in your app.

As per my knowledge, turning of Crashlytics is not possible without restarting app. As crashlytics is never used by "Users" of app, it is used by developer of app to get crash data, so it is simple that developer never wants it to turn off, so Crashltics have provided method as start(withAPIKey:) but no any stop method, and i think there are very less chance that they will provide such methods in near future.

But yes, you have way to stop submitting report. You can subscribe to CrashlyticsDelegate, in which it will give you callback for this method - (void)crashlyticsDidDetectReportForLastExecution:(CLSReport *)report completionHandler:(void (^)(BOOL submit))completionHandler, here in completionHandler if you provide submit = false, then it will ignore that crash Report.
So, if user have disabled it, then you can stop submitting reports in this way.

No idea about this.

No idea about this too.


问:
Kendo UI Window overlay opacity
How can I set overlay opacity with CSS. I tried  .k-overlay { opacity:0.9; } but it wont work. Can anyone help me? here I provide a simple demo

答:
.k-widget would be a too broad selection. You can set the opacity for that very window once the window will be shown:

```<code><script>
function onOpen() {
  setTimeout(function(){ $("#dialog").parent().css("opacity", 0.2); }, 10);
}

$("#dialog").kendoWindow({
  modal: true,
  open: onOpen
});
</script>
</code>```

Title: Kendo UI Window overlay opacity

Body:
.k-widget would be a too broad selection. You can set the opacity for that very window once the window will be shown:

<script>
function onOpen() {
  setTimeout(function(){ $("#dialog").parent().css("opacity", 0.2); }, 10);
}

$("#dialog").kendoWindow({
  modal: true,
  open: onOpen
});
</script>


问:
How to solve this CSS is not a function error
I have a small jQuery code but it gives me some errors. Can anybody help me with this error?

Code:

```<code><input type="checkbox">
<input type="checkbox" checked>
<input type="checkbox">
<input type="checkbox" checked>
<input type="checkbox">
</code>```

JS

```<code>$(function() {
  var checkboxes = $("input[type=checkbox]")
      checkboxes.is(':checked').css('background-color', 'red')
      checkboxes.on('change', function() {
    var checkbox = $(this)
    checkbox.css('background-color', checkbox.is(':checked') ? 'blue' : 'transparent')
  })
})
</code>```

CSS

```<code>  input[type='checkbox'] {
   -webkit-appearance: none;
    width: 20px;
    height: 20px;
   background: grey;
 }

input[type='checkbox']:checked {
  background: red;}
</code>```

Also here is link:
    https://jsfiddle.net/3y9Lvobc/2/

Error in console is:

```<code> checkboxes.is(...).css is not a function
</code>```

答:
That is because it returns true/false

Check here

Returns true if there is at least one match from the given argument, and false if not.

Body:
I have a small jQuery code but it gives me some errors. Can anybody help me with this error?

Code:

<input type="checkbox">
<input type="checkbox" checked>
<input type="checkbox">
<input type="checkbox" checked>
<input type="checkbox">

JS

$(function() {
  var checkboxes = $("input[type=checkbox]")
      checkboxes.is(':checked').css('background-color', 'red')
      checkboxes.on('change', function() {
    var checkbox = $(this)
    checkbox.css('background-color', checkbox.is(':checked') ? 'blue' : 'transparent')
  })
})

CSS

  input[type='checkbox'] {
   -webkit-appearance: none;
    width: 20px;
    height: 20px;
   background: grey;
 }

input[type='checkbox']:checked {
  background: red;}

Also here is link:
    https://jsfiddle.net/3y9Lvobc/2/

Error in console is:

 checkboxes.is(...).css is not a function