问:
How I can feed to ElasticSearch with Logstash or curl?
I am trying to import all the json into my elasticsearch. I have tried curl command for that purpose, but of no use as it start giving parsing errors.

This is what I tried:

```<code>curl -XPOST "http://localhost:9200/test" -d "@test.json"
curl -XPOST "http://localhost:9200/test/_bulk" -d "@test.json"
curl -XPOST "http://localhost:9200/test/_bulk" --data-binary "@test.json"
curl -s -XPOST "http://localhost:9200/test/_bulk" --data-binary "@test.json"
</code>```

And many other attempts. But What I got is Parsing error. Hence would like to know what is the way out to feed to elasticsearch all my records?

Also, if someone can help me solve it with logstash then it will be a great help. Kindly, let me know the best possible suggestion.

Here is the sample data in a JSON and it is separated with a newline, probably. Sample Data

Here is the error:

```<code>{
  "error" : {
    "root_cause" : [
      {
        "type" : "parse_exception",
        "reason" : "Failed to derive xcontent"
      }
    ],
    "type" : "parse_exception",
    "reason" : "Failed to derive xcontent"
  },
  "status" : 400
}
</code>```

答:
You need to change your json like this:

```<code>{ "index" : { "_index" : "test", "_type" : "type" } }
{"data":...}
{ "index" : { "_index" : "test", "_type" : "type" } }
{"data":...}
{ "index" : { "_index" : "test", "_type" : "type" } }
{"data":...}
</code>```

Then you can run:

```<code>curl -s -H "Content-Type: application/x-ndjson" -XPOST localhost:9200/_bulk --data-binary "@test.json"
</code>```

Read more about Bulk API.

If you wish to do that with Logstash, you can use a stdin input with a json filter, then an elasticsearch output. Something like (not tested):

```<code>input {
  stdin { }
}

filter {
  json {
    source => "message"
  }

  mutate {
    remove_field => [ "message" ]
  }
}

output {
  elasticsearch {
  }
}
</code>```

Then launch:

```<code>cat test.json | bin/logstash -f logstash.conf
</code>```

I hope this helps.

Body:
I am trying to import all the json into my elasticsearch. I have tried curl command for that purpose, but of no use as it start giving parsing errors.

This is what I tried:

curl -XPOST "http://localhost:9200/test" -d "@test.json"
curl -XPOST "http://localhost:9200/test/_bulk" -d "@test.json"
curl -XPOST "http://localhost:9200/test/_bulk" --data-binary "@test.json"
curl -s -XPOST "http://localhost:9200/test/_bulk" --data-binary "@test.json"

And many other attempts. But What I got is Parsing error. Hence would like to know what is the way out to feed to elasticsearch all my records?

Also, if someone can help me solve it with logstash then it will be a great help. Kindly, let me know the best possible suggestion.

Here is the sample data in a JSON and it is separated with a newline, probably. Sample Data

Here is the error:

{
  "error" : {
    "root_cause" : [
      {
        "type" : "parse_exception",
        "reason" : "Failed to derive xcontent"
      }
    ],
    "type" : "parse_exception",
    "reason" : "Failed to derive xcontent"
  },
  "status" : 400
}

Body:
You need to change your json like this:

{ "index" : { "_index" : "test", "_type" : "type" } }
{"data":...}
{ "index" : { "_index" : "test", "_type" : "type" } }
{"data":...}
{ "index" : { "_index" : "test", "_type" : "type" } }
{"data":...}

Then you can run:

curl -s -H "Content-Type: application/x-ndjson" -XPOST localhost:9200/_bulk --data-binary "@test.json"

Read more about Bulk API.

If you wish to do that with Logstash, you can use a stdin input with a json filter, then an elasticsearch output. Something like (not tested):

input {
  stdin { }
}

filter {
  json {
    source => "message"
  }

  mutate {
    remove_field => [ "message" ]
  }
}

output {
  elasticsearch {
  }
}

Then launch:

cat test.json | bin/logstash -f logstash.conf

I hope this helps.


来源: stackexchange

问:
custom validation in yii2 model
I am trying to add custom rule to form. I have added a custom function in model but it's not working for me.</p>

```<code>class BackendUser extends ActiveRecord implements IdentityInterface
{
public function rules()
{

    return [

        ['username','validateUsername','params'=>'username'=>'username']],

    ];
}

public function validateUsername($attribute, $params)
{
    if (preg_match('/[^a-z])/i', $this->$attribute)) {
        $this->addError($attribute, 'Username should only contain
    alphabets');
    }

}}
</code>```

答:
There are few typos in your code. Try using $this->{$attribute} in dynamic attributes and also params key should be an array while calling inline validation.

```<code>class BackendUser extends ActiveRecord implements IdentityInterface
{
public function rules()
{

return [
    ['username','validateUsername','params'=>['username'=>'username']],
 ];
}

public function validateUsername($attribute, $params)
{
 if (preg_match('/[^a-z])/i', $this->{$attribute})) {
    $this->addError($attribute, 'Username should only contain alphabets');
  }
 }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: custom validation in yii2 model

Body:
I am trying to add custom rule to form. I have added a custom function in model but it's not working for me.

class BackendUser extends ActiveRecord implements IdentityInterface
{
public function rules()
{

    return [

        ['username','validateUsername','params'=>'username'=>'username']],

    ];
}

public function validateUsername($attribute, $params)
{
    if (preg_match('/[^a-z])/i', $this->$attribute)) {
        $this->addError($attribute, 'Username should only contain
    alphabets');
    }

}}

Body:
There are few typos in your code. Try using $this->{$attribute} in dynamic attributes and also params key should be an array while calling inline validation.

class BackendUser extends ActiveRecord implements IdentityInterface
{
public function rules()
{

return [
    ['username','validateUsername','params'=>['username'=>'username']],
 ];
}

public function validateUsername($attribute, $params)
{
 if (preg_match('/[^a-z])/i', $this->{$attribute})) {
    $this->addError($attribute, 'Username should only contain alphabets');
  }
 }
}


问:
Tesseract or any other OCR lib
I'm looking for an explanation / API doc / examples of how to use (and train?) Tesseract in C++, nothing useful on the google Tesseract page, and yet to find something over the web.

Anyone useful sources, experiences would be more than welcome, as I have no idea how to begin with it.

P.S:

I'm open for suggestions on other
libraries.

Only FREE libraries

答:
I have some experience with Tesseract...
a simple google of 'training tesseract' reveals this page:
http://code.google.com/p/tesseract-ocr/wiki/TrainingTesseract
where you must choose which version of tesseract you wish to train..
While 3 is the latest version, it's brand new and thus people are still ironing out any issues - im still using version 2.4. Anyways, you'll see there are about 9 steps in training tesseract for a particular 'language' (or what should have been called 'fonts' or 'character-sets'). You could also just use the existing 'eng' language - but it depends on your application. For example, in my application I would have to do the document analysis and take a particular region and want to OCR a 13-character string of numbers - and I needed high accuracy - and I didn't want it reading '5' as 'S' and '0' as 'O' etc, so it was logical to create a particular 'language' of my particular font-set consisting only of the characters 0..9, whereas you might not care if you get extra 'noise</p>

Title: Tesseract or any other OCR lib

ContentLicense: CC BY-SA 2.5


问:
How to create custom array adapter when items defined dynamically
I have a custom adapter which is supposed to contain image buttons. However, I am bit confused on the implementation of the override for the getView() method. Since my image buttons are defined dynamically, I am able to recover an image button by using the code

```<code>@Override
public View getView(int i, View view, ViewGroup viewGroup){
    ImageButton ibutton = (ImageButton) getItem(i);
</code>```

How do I return its view? I have not specifically created an xml file for it since it is just an ImageButton (not in combination with anything else), but is it necessary to create an xml for it? Or is there a way to easily get the view from the imagebutton itself.

When I try this for getView(), the imagebutton is not clickable for some reason.

```<code>@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ImageButton imageButton = getItem(position);
    return imageButton ;
}
</code>```

答:
Try to build you adapter something like this:</p>

```<code>public class ImageButtonAdapter extends BaseAdapter {
   private Context mContext;

   // Constructor
   public ImageButtonAdapter(Context c) {
      mContext = c;
   }

   public int getCount() {
      return listCount;
   }

   public Object getItem(int position) {
      return null;
   }

   public long getItemId(int position) {
      return 0;
   }

   // create a new ImageButton for each item referenced by the Adapter
   public View getView(int position, View convertView, ViewGroup parent) {
      ImageButton imageButton ;

      if (convertView == null) {
         imageButton = new ImageButton (mContext);
         imageButton.setLayoutParams(lp);
      }
      else
      {
         imageButton = (ImageButton ) convertView;
      }
      imageButton.setBackgroundColor(Color.TRANSPARENT)
      return imageButton ;
   }

}
</code>```

Body:
I have a custom adapter which is supposed to contain image buttons. However, I am bit confused on the implementation of the override for the getView() method. Since my image buttons are defined dynamically, I am able to recover an image button by using the code

@Override
public View getView(int i, View view, ViewGroup viewGroup){
    ImageButton ibutton = (ImageButton) getItem(i);

How do I return its view? I have not specifically created an xml file for it since it is just an ImageButton (not in combination with anything else), but is it necessary to create an xml for it? Or is there a way to easily get the view from the imagebutton itself.

When I try this for getView(), the imagebutton is not clickable for some reason.

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ImageButton imageButton = getItem(position);
    return imageButton ;
}

Body:
Try to build you adapter something like this:

public class ImageButtonAdapter extends BaseAdapter {
   private Context mContext;

   // Constructor
   public ImageButtonAdapter(Context c) {
      mContext = c;
   }

   public int getCount() {
      return listCount;
   }

   public Object getItem(int position) {
      return null;
   }

   public long getItemId(int position) {
      return 0;
   }

   // create a new ImageButton for each item referenced by the Adapter
   public View getView(int position, View convertView, ViewGroup parent) {
      ImageButton imageButton ;

      if (convertView == null) {
         imageButton = new ImageButton (mContext);
         imageButton.setLayoutParams(lp);
      }
      else
      {
         imageButton = (ImageButton ) convertView;
      }
      imageButton.setBackgroundColor(Color.TRANSPARENT)
      return imageButton ;
   }

}


问:
How do I activate the debugger in CS-Cart?
How do I activate the debugger in CS Cart?

I've done this:

http://docs.cs-cart.com/4.2.x/tools/debugger.html#activate-debug-mode

i.e added the debug term while logged into the Administrator panel.

Update:

actually I'm using v 4.1.4 but the documentation is still the same.

No joy.

What else do I have to do?

答:
If you set DEBUG_MODE to true in your config.php, and clear the cache, it will enable the debug bar.

Did you clear your cache? (path-to-your-site.com/your-admin.php?cc&ctpl)


问:
php echo result from mysql and datetime selection
MySQL database Start = "2017-03-29 01:30:00"

The problem is:

I print the $SQL and search the record in MySQL database, it can search the record. However, I need to debug and test if there is no result, it will be expected to echo "No". But, it always to echo "Yes" no matter I can get the record in MySQL or not.

How can I fixed it.

Main purpose: Get the record if there are and Echo "No" if there don't have record

```<code>  <?php
    $serverName = "localhost";
    $username = "root";
    $password = "";
    $dbName = "fyp";
    $tbName = "events";

    $String_start = '2017-03-29 01:28:00';
    $String_end = '2017-03-29 01:32:00';

    $conn = new mysqli($serverName, $username, $password, $dbName);

    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    //$staffID =  $_SESSION['userID'];
    $staff_ID = '15207800';

    $sql = "SELECT *
                    FROM `$tbName`
                    WHERE  `start` BETWEEN ('$String_start') AND ('$String_end')";

    echo $sql;
    $result=mysqli_query($conn,$sql);

    if($result)
    {
        echo "Yes";
    }
    else{
        echo "no";
    }

    ?>
</code>```

答:
Mysql query only return fails if there is an issue, for successful execution it returns TRUE even if there is no record. You can achieve with follwing way</p>

```<code><?php
    $serverName = "localhost";
    $username = "root";
    $password = "";
    $dbName = "fyp";
    $tbName = "events";

    $String_start = '2017-03-29 01:28:00';
    $String_end = '2017-03-29 01:32:00';

    $conn = new mysqli($serverName, $username, $password, $dbName);

    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    //$staffID =  $_SESSION['userID'];
    $staff_ID = '15207800';

    $sql = "SELECT *
                    FROM `$tbName`
                    WHERE  `start` BETWEEN ('$String_start') AND ('$String_end')";

    echo $sql;
    $result=mysqli_query($conn,$sql);
    $num_rows = mysqli_num_rows($result);

    if($num_rows > 0)
    {
        echo "Yes";
    }
    else{
        echo "no";
    }

    ?>
</code>```

Body:
MySQL database Start = "2017-03-29 01:30:00"

The problem is:

I print the $SQL and search the record in MySQL database, it can search the record. However, I need to debug and test if there is no result, it will be expected to echo "No". But, it always to echo "Yes" no matter I can get the record in MySQL or not.

How can I fixed it.

Main purpose: Get the record if there are and Echo "No" if there don't have record

  <?php
    $serverName = "localhost";
    $username = "root";
    $password = "";
    $dbName = "fyp";
    $tbName = "events";

    $String_start = '2017-03-29 01:28:00';
    $String_end = '2017-03-29 01:32:00';

    $conn = new mysqli($serverName, $username, $password, $dbName);

    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    //$staffID =  $_SESSION['userID'];
    $staff_ID = '15207800';

    $sql = "SELECT *
                    FROM `$tbName`
                    WHERE  `start` BETWEEN ('$String_start') AND ('$String_end')";

    echo $sql;
    $result=mysqli_query($conn,$sql);

    if($result)
    {
        echo "Yes";
    }
    else{
        echo "no";
    }

    ?>

Body:
Mysql query only return fails if there is an issue, for successful execution it returns TRUE even if there is no record. You can achieve with follwing way

<?php
    $serverName = "localhost";
    $username = "root";
    $password = "";
    $dbName = "fyp";
    $tbName = "events";

    $String_start = '2017-03-29 01:28:00';
    $String_end = '2017-03-29 01:32:00';

    $conn = new mysqli($serverName, $username, $password, $dbName);

    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    //$staffID =  $_SESSION['userID'];
    $staff_ID = '15207800';

    $sql = "SELECT *
                    FROM `$tbName`
                    WHERE  `start` BETWEEN ('$String_start') AND ('$String_end')";

    echo $sql;
    $result=mysqli_query($conn,$sql);
    $num_rows = mysqli_num_rows($result);

    if($num_rows > 0)
    {
        echo "Yes";
    }
    else{
        echo "no";
    }

    ?>


问:
Initiating NSManagedObjectContext gives fatal error?
I am working on the last leg of my app and this seems to be the last portion I'm having issue with. Fingers crossed for that, anyway.

I have CoreData all set up and ready to be displayed in a table (hopefully, I can't really view it in a table yet to verify).

The issue I'm having right now is that when the views that implement CoreData load, there is a fatal error that occurs when it initiates my NSManagedObjectContext. Please note that I use two separate ViewControllers to get data in addition to the TableViewController, therefore I have declared a total of 3 NSManagedContextObjects in my app - which I'm not sure if that's the issue or not. The line that is causing it is in my viewDidLoad function. See the code below.

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

        managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    }
</code>```

I'm not entirely sure how to tackle this, for I was following a tutorial for the whole process.

EDIT: I am going to add all the code that is affected by CoreData so maybe it'll help the problem be solved.

Here is a screenshot of my core data model

AppDelegate

```<code>import UIKit
import CoreData

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    return true
}

func applicationWillResignActive(_ application: UIApplication) {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}

func applicationDidEnterBackground(_ application: UIApplication) {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

func applicationWillEnterForeground(_ application: UIApplication) {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}

func applicationDidBecomeActive(_ application: UIApplication) {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

func applicationWillTerminate(_ application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    //self.saveContext()
}

// MARK: - Core Data Stack
lazy var persistentContainer: NSPersistentContainer = {
    /*
     The persistent container for the application. This implementation
     creates and returns a container, having loaded the store for the
     application to it. This property is optional since there are legitimate
     error conditions that could cause the creation of the store to fail.
     */
    let container = NSPersistentContainer(name: "RSDB_1_0_COREDATA")
    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error as NSError? {
            // Replace this implementation with code to handle the error appropriately.
            // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

            /*
             Typical reasons for an error here include:
             * The parent directory does not exist, cannot be created, or disallows writing.
             * The persistent store is not accessible, due to permissions or data protection when the device is locked.
             * The device is out of space.
             * The store could not be migrated to the current model version.
             Check the error message to determine what the actual problem was.
             */
            fatalError("Unresolved error \(error), \(error.userInfo)")
        }
    })
    return container
}()

// MARK: - Core Data Saving support

func saveContext () {
    let context = persistentContainer.viewContext
    if context.hasChanges {
        do {
            try context.save()
        } catch {
            // Replace this implementation with code to handle the error appropriately.
            // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            let nserror = error as NSError
            fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
        }
    }
}
</code>```

}

First View Controller

```<code>let newInfo = GeneralInfo(context:managedObjectContext1)
        newInfo.courseNumber = studCourse
        newInfo.scenarioNumber = studScen

        do {
            try self.managedObjectContext1.save()
        }catch {
            print("Could not save data \(error.localizedDescription)")
        }

        performSegue(withIdentifier: "segue3", sender: self)
</code>```

Different View Controller

```<code> let newEvaluation = GeneralEvaluation(context:managedObjectContext)
        newEvaluation.idScore = String(ID)
        newEvaluation.washScore = String(WASH)
        newEvaluation.totalScore = String(total)

        do {
            try self.managedObjectContext.save()
        }catch {
            print("Could not save data \(error.localizedDescription)")
        }

        performSegue(withIdentifier: "segue4", sender: self)
</code>```

TableViewController

```<code>let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TheTableViewCell

   let info = courseInfo[indexPath.row]
   let score = scores[indexPath.row]

    cell.CLASS.text = info.courseNumber
    cell.SCENARIO.text = info.scenarioNumber

    cell.WASH.text = score.washScore
    cell.ID.text = score.idScore
    cell.TOTAL.text = score.totalScore
</code>```

答: Looks like you're throwing an error in your lazy var persistentContainer. That's good. That means you can rule out the view controllers as the cause. Can we see a screenshot of the files section of Xcode (command-1)? </p>

Body:
I am working on the last leg of my app and this seems to be the last portion I'm having issue with. Fingers crossed for that, anyway.

I have CoreData all set up and ready to be displayed in a table (hopefully, I can't really view it in a table yet to verify).

The issue I'm having right now is that when the views that implement CoreData load, there is a fatal error that occurs when it initiates my NSManagedObjectContext. Please note that I use two separate ViewControllers to get data in addition to the TableViewController, therefore I have declared a total of 3 NSManagedContextObjects in my app - which I'm not sure if that's the issue or not. The line that is causing it is in my viewDidLoad function. See the code below.

override func viewDidLoad() {
        super.viewDidLoad()

        managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    }

I'm not entirely sure how to tackle this, for I was following a tutorial for the whole process.

EDIT: I am going to add all the code that is affected by CoreData so maybe it'll help the problem be solved.

Here is a screenshot of my core data model

AppDelegate

import UIKit
import CoreData

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    return true
}

func applicationWillResignActive(_ application: UIApplication) {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}

func applicationDidEnterBackground(_ application: UIApplication) {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

func applicationWillEnterForeground(_ application: UIApplication) {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}

func applicationDidBecomeActive(_ application: UIApplication) {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

func applicationWillTerminate(_ application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    //self.saveContext()
}

// MARK: - Core Data Stack
lazy var persistentContainer: NSPersistentContainer = {
    /*
     The persistent container for the application. This implementation
     creates and returns a container, having loaded the store for the
     application to it. This property is optional since there are legitimate
     error conditions that could cause the creation of the store to fail.
     */
    let container = NSPersistentContainer(name: "RSDB_1_0_COREDATA")
    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error as NSError? {
            // Replace this implementation with code to handle the error appropriately.
            // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

            /*
             Typical reasons for an error here include:
             * The parent directory does not exist, cannot be created, or disallows writing.
             * The persistent store is not accessible, due to permissions or data protection when the device is locked.
             * The device is out of space.
             * The store could not be migrated to the current model version.
             Check the error message to determine what the actual problem was.
             */
            fatalError("Unresolved error \(error), \(error.userInfo)")
        }
    })
    return container
}()

// MARK: - Core Data Saving support

func saveContext () {
    let context = persistentContainer.viewContext
    if context.hasChanges {
        do {
            try context.save()
        } catch {
            // Replace this implementation with code to handle the error appropriately.
            // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            let nserror = error as NSError
            fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
        }
    }
}

}

First View Controller

let newInfo = GeneralInfo(context:managedObjectContext1)
        newInfo.courseNumber = studCourse
        newInfo.scenarioNumber = studScen

        do {
            try self.managedObjectContext1.save()
        }catch {
            print("Could not save data \(error.localizedDescription)")
        }

        performSegue(withIdentifier: "segue3", sender: self)

Different View Controller

 let newEvaluation = GeneralEvaluation(context:managedObjectContext)
        newEvaluation.idScore = String(ID)
        newEvaluation.washScore = String(WASH)
        newEvaluation.totalScore = String(total)

        do {
            try self.managedObjectContext.save()
        }catch {
            print("Could not save data \(error.localizedDescription)")
        }

        performSegue(withIdentifier: "segue4", sender: self)

TableViewController

let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TheTableViewCell

   let info = courseInfo[indexPath.row]
   let score = scores[indexPath.row]

    cell.CLASS.text = info.courseNumber
    cell.SCENARIO.text = info.scenarioNumber

    cell.WASH.text = score.washScore
    cell.ID.text = score.idScore
    cell.TOTAL.text = score.totalScore


问:
Time starts reading in minus, while the end message still shows
My countdown timer I want to put on a site is having some issues. Countdown is normal, everything is fine, but at the end of the timer, instead of it to clear the timer and display the end message or a call back, it will rather display the end message by the side while time continues to read in the negative.

Can anyone show me what went wrong?

This is my code:

    // Set the date we're counting down to
    var countDownDate = new Date("March 31, 2017 09:35:00 PM").getTime();
    // Update the count down every 1 second

    var x = setInterval(function() {

        // Get todays date and time
        var now = new Date().getTime();

        // Find the distance between now an the count down date
        var distance = countDownDate - now;

        // Time calculations for days, hours, minutes and seconds
        var days = Math.floor(distance / (1000 * 60 * 60 * 24));
        var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        var seconds = Math.floor((distance % (1000 * 60)) / 1000);

       // Output the result in an element with id="demo"

        document.getElementById("days").innerHTML = days;
        document.getElementById("hours").innerHTML = hours;
        document.getElementById("minutes").innerHTML = minutes;
        document.getElementById("seconds").innerHTML = seconds;

        // If the count down is over, write some text
     if (distance < 0) {
            clearInterval(x);
            document.getElementById("endmessage").innerHTML = "EXPIRED";

        }

    }, 1000);
    ```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
       background: #f6f6f6;
      }

      .countdownContainer{
       position: absolute;;
       top: 50%;
       left: 50%;
       transform : translateX(-50%) translateY(-50%);
       text-align: center;
       background: #ddd;
       border: 1px solid #999;
       padding: 10px;
       box-shadow: 0 0 5px 3px #ccc;
      }

      .info {
       font-size: 80px;
      }</code>```

<!DOCTYPE HTML>

        Countdown to April fool

        00
        00
        00
        00

        Days
        Hours
        Minutes
        Seconds

    ```

答:
I have made some changes to your code. Please find it below,

<!DOCTYPE HTML>

                Countdown to April fool

                00
                00
                00
                00

                Days
                Hours
                Minutes
                Seconds

```

Each time the countdown is printed, it should be done only if the difference is greater than 0. So moved that part inside the else condition of your IF. Adjust the date accordingly to test your countdown.

Body:
My countdown timer I want to put on a site is having some issues. Countdown is normal, everything is fine, but at the end of the timer, instead of it to clear the timer and display the end message or a call back, it will rather display the end message by the side while time continues to read in the negative.

Can anyone show me what went wrong?

This is my code:

    // Set the date we're counting down to
    var countDownDate = new Date("March 31, 2017 09:35:00 PM").getTime();
    // Update the count down every 1 second

    var x = setInterval(function() {

        // Get todays date and time
        var now = new Date().getTime();

        // Find the distance between now an the count down date
        var distance = countDownDate - now;

        // Time calculations for days, hours, minutes and seconds
        var days = Math.floor(distance / (1000 * 60 * 60 * 24));
        var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        var seconds = Math.floor((distance % (1000 * 60)) / 1000);

       // Output the result in an element with id="demo"

        document.getElementById("days").innerHTML = days;
        document.getElementById("hours").innerHTML = hours;
        document.getElementById("minutes").innerHTML = minutes;
        document.getElementById("seconds").innerHTML = seconds;

        // If the count down is over, write some text
     if (distance < 0) {
            clearInterval(x);
            document.getElementById("endmessage").innerHTML = "EXPIRED";

        }

    }, 1000);

body {
       background: #f6f6f6;
      }

      .countdownContainer{
       position: absolute;;
       top: 50%;
       left: 50%;
       transform : translateX(-50%) translateY(-50%);
       text-align: center;
       background: #ddd;
       border: 1px solid #999;
       padding: 10px;
       box-shadow: 0 0 5px 3px #ccc;
      }

      .info {
       font-size: 80px;
      }

<!DOCTYPE HTML>

        Countdown to April fool

        00
        00
        00
        00

        Days
        Hours
        Minutes
        Seconds

Body:
I have made some changes to your code. Please find it below,

<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
        body {
            background: #f6f6f6;
        }

        .countdownContainer{
            position: absolute;;
            top: 50%;
            left: 50%;
            transform : translateX(-50%) translateY(-50%);
            text-align: center;
            background: #ddd;
            border: 1px solid #999;
            padding: 10px;
            box-shadow: 0 0 5px 3px #ccc;
        }

        .info {
            font-size: 80px;
        }
        </style>
</head>
<body>
<table class="countdownContainer">
            <tr class="info">
                <td colspan="4">Countdown to April fool</td>
            </tr>
            <tr class="info">
                <td id="days">00</td>
                <td id="hours">00</td>
                <td id="minutes">00</td>
                <td id="seconds">00</td>

                <td id="endmessage"></td>
            </tr>
            <tr>
                <td>Days</td>
                <td>Hours</td>
                <td>Minutes</td>
                <td>Seconds</td>
            </tr>
        </table>

<p id="demo"></p>

<script>

// Set the date we're counting down to
var countDownDate = new Date("April 01, 2017 12:00:30 PM").getTime();
// Update the count down every 1 second

var x = setInterval(function() {

    // Get todays date and time
    var now = new Date().getTime();

    // Find the distance between now an the count down date
    var distance = countDownDate - now;

    // Time calculations for days, hours, minutes and seconds
    var days = Math.floor(distance / (1000 * 60 * 60 * 24));
    var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    var seconds = Math.floor((distance % (1000 * 60)) / 1000);

    // If the count down is over, write some text
    if (distance < 0) {
        clearInterval(x);
        document.getElementById("endmessage").innerHTML = "EXPIRED";

    }
    else{
   // Output the result in an element with id="demo"

    document.getElementById("days").innerHTML = days;
    document.getElementById("hours").innerHTML = hours;
    document.getElementById("minutes").innerHTML = minutes;
    document.getElementById("seconds").innerHTML = seconds;
    }

}, 1000);

</script>

</body>

</html>

Each time the countdown is printed, it should be done only if the difference is greater than 0. So moved that part inside the else condition of your IF. Adjust the date accordingly to test your countdown.


问:
Jquery exclude element that not have  inside
how can I exclude from this selection element that not have a href="#" inside of it?
I want my stuff is executed only for .leading that have a href="#"...
thank you

```<code>//js
$(".leading").hover(function(){
// do stuff
}

//DOM
<div class=".leading"><div ><a href="#"> <img src="img1.jpg" /> jquery affected </a></div></div>
<div class=".leading"><div ><img src="img2.jpg" /> jquery not affected </div></div>
</code>```

答:
$("div.leading div a[href='#']")

... will select only those anchor tags with a href attribute set to the value #.

You can then use .parent().parent() to walk up to the div.leading element.

Also in your example HTML you are using .leading as a class name which is invalid, it should be leading.

Title: Jquery exclude element that not have <a href="#"> inside

Body:
how can I exclude from this selection element that not have a href="#" inside of it?
I want my stuff is executed only for .leading that have a href="#"...
thank you

//js
$(".leading").hover(function(){
// do stuff
}

//DOM

  jquery affected

 jquery not affected


问:
Check input data and its sequence by MySQL
i want a drag and drop question and its options in  to be fetched from mysql table and make all options in a correct sequence. how to check my sequence to table correct sequence. i have this drag and drop code.

in this example we know correct sequence is 1,2,3,4,5,6,7. when we will drag all in correct order and submit it, how we match submitted sequence with correct sequence automatically. this is a kind of education test game.

```<code><style>
  body {
    font-family: arial;
    background: rgb(242, 244, 246);
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
  }

  h3 {
    color: rgb(199, 204, 209);
    font-size: 28px;
    text-align: center;
  }

  #elements-container {
    text-align: center;
  }

  .draggable-element {
    display: inline-block;
    width: 200px;
    height: 200px;
    background: white;
    border: 1px solid rgb(196, 196, 196);
    line-height: 200px;
    text-align: center;
    margin: 10px;
    color: rgb(51, 51, 51);
    font-size: 30px;
    cursor: move;
  }

  .drag-list {
    width: 400px;
    margin: 0 auto;
  }

  .drag-list > li {
    list-style: none;
    background: rgb(255, 255, 255);
    border: 1px solid rgb(196, 196, 196);
    margin: 5px 0;
    font-size: 24px;
  }

  .drag-list .title {
    display: inline-block;
    width: 130px;
    padding: 6px 6px 6px 12px;
    vertical-align: top;
  }

  .drag-list .drag-area {
    display: inline-block;
    background: rgb(158, 211, 179);
    width: 60px;
    height: 40px;
    vertical-align: top;
    float: right;
    cursor: move;
  }

  .code {
    background: rgb(255, 255, 255);
    border: 1px solid rgb(196, 196, 196);
    width: 600px;
    margin: 22px auto;
    position: relative;
  }

  .code::before {
    content: 'Code';
    background: rgb(80, 80, 80);
    width: 96%;
    position: absolute;
    padding: 8px 2%;
    color: rgb(255, 255, 255);
  }

  .code pre {
    margin-top: 50px;
    padding: 0 13px;
    font-size: 1em;
  }

</style>
</code>```

```<code>    <section class="showcase showcase-2">
      <h3>Example 2</h3>
      <ul class="drag-list">
        <li><span class="title">list 6</span><span class="drag-area"></span></li>
        <li><span class="title">list 4</span><span class="drag-area"></span></li>
        <li><span class="title">list 5</span><span class="drag-area"></span></li>
        <li><span class="title">list 1</span><span class="drag-area"></span></li>
        <li><span class="title">list 3</span><span class="drag-area"></span></li>
        <li><span class="title">list 2</span><span class="drag-area"></span></li>
        <li><span class="title">list 7</span><span class="drag-area"></span></li>
      </ul>
    </section>

    <section class="code">
      ```
$('li').arrangeable({dragSelector: '.drag-area'});
      ```
    </section>

    <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
    <script type="text/javascript" src="drag-arrange.js"></script>

    <script type="text/javascript">
      $(function() {
          $('.draggable-element').arrangeable();
          $('li').arrangeable({dragSelector: '.drag-area'});
      });
    </script>
</code>```

答:
You can do it by using javaScript like this:

First, you need to take the reference of the question's id somewhere. To make it simple just assign it to the id attribute of your
 tag.

```<code>var sort_order = [];

jQuery('.drag-list li').each(function(index){
     sort_order[index] = this.id;
});
</code>```

Now, the sort_order will have your question ids along with their sequence.

Hope you get the logic. Now you can tweak it according to your requirements.

Body:
i want a drag and drop question and its options in  to be fetched from mysql table and make all options in a correct sequence. how to check my sequence to table correct sequence. i have this drag and drop code.

in this example we know correct sequence is 1,2,3,4,5,6,7. when we will drag all in correct order and submit it, how we match submitted sequence with correct sequence automatically. this is a kind of education test game.

Example 2

list 6

list 4

list 5

list 1

list 3

list 2

list 7

$('li').arrangeable({dragSelector: '.drag-area'});

Body:
You can do it by using javaScript like this:

First, you need to take the reference of the question's id somewhere. To make it simple just assign it to the id attribute of your <li> tag.

var sort_order = [];

jQuery('.drag-list li').each(function(index){
     sort_order[index] = this.id;
});

Now, the sort_order will have your question ids along with their sequence.

Hope you get the logic. Now you can tweak it according to your requirements.


问:
Assertion failure : size.width>0 && size.height>0 in function imshow
i am using opencv2 and python on raspberry pi. and i am new with python and opencv. i tried to read a jpeg image and display image it shows the following error: </p>

```<code>/home/pi/opencv-2.4.9/modules/highgui/src/window.cpp:269: \
  error: (-215) size.width>0 &&  size.height>0 in function imshow.
</code>```

<p>and the code is: </p>

```<code>import cv2
# windows to display image
cv2.namedWindow("Image")
# read image
image = cv2.imread('home/pi/bibek/book/test_set/bbb.jpeg')
# show image
cv2.imshow("Image", image)
# exit at closing of window
cv2.waitKey(0)
cv2.destroyAllWindows()
</code>```

答:
While using Raspbian in Rpi 3 I had the same problem when trying to read qrcodes. The error is because cv2 was not able to read the image. If using png image install pypng module.</p>

```<code>sudo pip install pypng
</code>```

Body:
i am using opencv2 and python on raspberry pi. and i am new with python and opencv. i tried to read a jpeg image and display image it shows the following error:

/home/pi/opencv-2.4.9/modules/highgui/src/window.cpp:269: \
  error: (-215) size.width>0 &&  size.height>0 in function imshow.

and the code is:

import cv2
# windows to display image
cv2.namedWindow("Image")
# read image
image = cv2.imread('home/pi/bibek/book/test_set/bbb.jpeg')
# show image
cv2.imshow("Image", image)
# exit at closing of window
cv2.waitKey(0)
cv2.destroyAllWindows()

Body:
While using Raspbian in Rpi 3 I had the same problem when trying to read qrcodes. The error is because cv2 was not able to read the image. If using png image install pypng module.

sudo pip install pypng


问:
Show every qr code scan result as listview in another activity
I am making a scanner where scan result will be saved in another activity. So, i used intent putextra in scanner activity & string getextra in another activity. In another activity, scan result will be displayed in listview.. So i have declared an arraylist for strings. First result is coming in another activity without problem. But when second result comes, the first result is replaced. I want to show every result in listview as like history. What I need to do?? Please help..</p>

答:
When You scan QR code scan time and Navigate to result activity, it means all the variable of Result Activity are initialized again and store updated one, that's why previous entries are not showing.

So You can use shared Preference for this, Store array list in string Shared Preference, and get same array list on Result Activity

You can declare Array List as static variable


问:
Display Filters in Datatables with just 2 decimals
I'm trying to do a filter based on this for DataTables: https://datatables.net/examples/api/multi_filter.html, the filter works fine but I need that the column searching filters for only what the table is displaying, for example:

ColumnB 2.312364 0.256899 8.858943

I'm using the FormatRound function so the table only shows 2 decimals so the column is being seen like this:

ColumnB 2.31 0.23 8.86

I need that the filter for the column searching, only filters for the data displaying in the table, currently if I filter i.e, the number 6, is showing the third and the first value which before the round also has a 6.

Any ideas would be appreciated.

答:
Round the data before you put it into DataTables:</p>

```<code>round(ColumnB, digits=2)
</code>```

Body:
Round the data before you put it into DataTables:

round(ColumnB, digits=2)


问:
List view comes over the toolbar when I test it on lollipop and higher Api
Here is my Layout with list view and Navigation as the list view overlaps and makes the navigation Bar inaccessible.I switched the list view in the layout tried different solutions but was unable to set it right. Here is how it appears when i run it.

```<code> <?xml version="1.0" encoding="utf-8"?>
        <RelativeLayout        xmlns:android="http://schemas.android.com/apk/res/android"
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
          <android.support.v4.widget.DrawerLayout
              android:id="@+id/drawer_layout"
              android:layout_height="match_parent"
              android:layout_width="fill_parent"
              android:fitsSystemWindows="true">
            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">
              <include
                  layout="@layout/toolbar" />

                </RelativeLayout>
              <ListView
                       android:id="@+id/listview"
                       android:layout_width="match_parent"
                       android:layout_height="match_parent"
                       android:dividerHeight="1px"
                       android:layout_weight="1"
                       android:layout_marginTop="100dp"
                       android:divider="#000000"
                       android:layout_marginLeft="10dp"
                       android:layout_marginRight="10dp"
                       android:paddingLeft="5dp" />
            <android.support.design.widget.NavigationView
                    android:id="@+id/nav_view"
                    android:layout_height="match_parent"
                    android:layout_width="wrap_content"
                    android:layout_gravity="end"
                    android:fitsSystemWindows="true"
                 />
          </android.support.v4.widget.DrawerLayout>
          <android.support.design.widget.FloatingActionButton
                    android:id="@+id/fab"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="bottom|right"
                    android:src="@drawable/ic_edit"
                    android:layout_marginRight="15dp"
                    android:layout_marginBottom="15dp"
                   android:layout_alignParentBottom="true"
                  android:layout_alignParentRight="true" />

        </RelativeLayout>

Can anybody help.

Thank you.
</code>```

答:
Using a CoordinatorLayout solved my issue.</p>

```<code> <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
  <android.support.v4.widget.DrawerLayout xmlns:app="http://schemas.android.com/apk/res-auto"
      android:id="@+id/drawer_layout"
      android:layout_height="match_parent"
      android:layout_width="fill_parent"
      android:fitsSystemWindows="true">
    <android.support.design.widget.CoordinatorLayout
        android:id="@+id/coordinatorLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

      <FrameLayout
          android:id="@+id/content_frame"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          app:layout_behavior="@string/appbar_scrolling_view_behavior" />
    <android.support.design.widget.AppBarLayout
      android:id="@+id/appbar"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
      <include
          layout="@layout/toolbar" />

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

    <ListView
        android:id="@+id/lvTenant"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:dividerHeight="1px"
        android:layout_marginTop="50dp"
        android:divider="#000000"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:paddingLeft="5dp" />
    </android.support.design.widget.CoordinatorLayout>
    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_height="match_parent"
        android:layout_width="240dp"
        android:layout_gravity="start"
        android:fitsSystemWindows="true" />
  </android.support.v4.widget.DrawerLayout>
  <android.support.design.widget.FloatingActionButton
      android:id="@+id/fab"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_gravity="bottom|right"
      android:src="@drawable/ic_edit"
      android:layout_marginRight="15dp"
      android:layout_marginBottom="15dp"
      android:layout_alignParentBottom="true"
      android:layout_alignParentRight="true"
      layout_anchor="@id/lvTenant"`enter code here`
            layout_anchorGravity="bottom|right|end"
            layout_behavior="helpers.FABCoordinatorBehavior" />
</RelativeLayout>
</code>```

Body:
Here is my Layout with list view and Navigation as the list view overlaps and makes the navigation Bar inaccessible.I switched the list view in the layout tried different solutions but was unable to set it right. Here is how it appears when i run it.

 <?xml version="1.0" encoding="utf-8"?>
        <RelativeLayout        xmlns:android="http://schemas.android.com/apk/res/android"
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
          <android.support.v4.widget.DrawerLayout
              android:id="@+id/drawer_layout"
              android:layout_height="match_parent"
              android:layout_width="fill_parent"
              android:fitsSystemWindows="true">
            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">
              <include
                  layout="@layout/toolbar" />

                </RelativeLayout>
              <ListView
                       android:id="@+id/listview"
                       android:layout_width="match_parent"
                       android:layout_height="match_parent"
                       android:dividerHeight="1px"
                       android:layout_weight="1"
                       android:layout_marginTop="100dp"
                       android:divider="#000000"
                       android:layout_marginLeft="10dp"
                       android:layout_marginRight="10dp"
                       android:paddingLeft="5dp" />
            <android.support.design.widget.NavigationView
                    android:id="@+id/nav_view"
                    android:layout_height="match_parent"
                    android:layout_width="wrap_content"
                    android:layout_gravity="end"
                    android:fitsSystemWindows="true"
                 />
          </android.support.v4.widget.DrawerLayout>
          <android.support.design.widget.FloatingActionButton
                    android:id="@+id/fab"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="bottom|right"
                    android:src="@drawable/ic_edit"
                    android:layout_marginRight="15dp"
                    android:layout_marginBottom="15dp"
                   android:layout_alignParentBottom="true"
                  android:layout_alignParentRight="true" />

        </RelativeLayout>

Can anybody help.

Thank you.

Body:
Using a CoordinatorLayout solved my issue.

 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
  <android.support.v4.widget.DrawerLayout xmlns:app="http://schemas.android.com/apk/res-auto"
      android:id="@+id/drawer_layout"
      android:layout_height="match_parent"
      android:layout_width="fill_parent"
      android:fitsSystemWindows="true">
    <android.support.design.widget.CoordinatorLayout
        android:id="@+id/coordinatorLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

      <FrameLayout
          android:id="@+id/content_frame"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          app:layout_behavior="@string/appbar_scrolling_view_behavior" />
    <android.support.design.widget.AppBarLayout
      android:id="@+id/appbar"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
      <include
          layout="@layout/toolbar" />

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

    <ListView
        android:id="@+id/lvTenant"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:dividerHeight="1px"
        android:layout_marginTop="50dp"
        android:divider="#000000"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:paddingLeft="5dp" />
    </android.support.design.widget.CoordinatorLayout>
    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_height="match_parent"
        android:layout_width="240dp"
        android:layout_gravity="start"
        android:fitsSystemWindows="true" />
  </android.support.v4.widget.DrawerLayout>
  <android.support.design.widget.FloatingActionButton
      android:id="@+id/fab"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_gravity="bottom|right"
      android:src="@drawable/ic_edit"
      android:layout_marginRight="15dp"
      android:layout_marginBottom="15dp"
      android:layout_alignParentBottom="true"
      android:layout_alignParentRight="true"
      layout_anchor="@id/lvTenant"`enter code here`
            layout_anchorGravity="bottom|right|end"
            layout_behavior="helpers.FABCoordinatorBehavior" />
</RelativeLayout>


问:
Why are git repos so much smaller than SVN repos?
I have recently converted a huge SVN repository with 500k commits to several hundred git repos.

The git repos are tiny in comparison to SVN. My manager thinks I haven't done it properly! I used svn2git and I think it worked perfectly.

Just wondering what are the main reasons why it would be smaller?

答:
svnvsgit.com answers your question:

Subversion and Git repositories with equivalent data will have approximately the same size. Except for the case of storing a lot of binary files, when Subversion repositories could be significantly smaller than Git ones (because Subversion’s xdelta delta compression algorithm works both for binary and text files).

Under Repository Site Benchmarks he compares SVN and Git and sees that:

the difference of repository size is truly insignificant because the Git repository is only 10% smaller than the corresponding Subversion one

In conlussion:

Git has an overall smaller repository size

SVN will be smaller if you have a lot of binary files

If your Git repos compared size is significantly smaller (more than 20%) there is a real possibility that something went wrong.


问:
How to accept this alert in appium?
Appium v1.6.4-beta
Xcode 8.2
macOs Sierra 10.12

I want to automate to save photo in my device.
But in first time I have to give permission.
I have used "accept alert", but cannot accept the alert for allow to access the photo library.
It shows the test passed in green , when I execute the test, but this popup still appear in view and photo is not saved.

This is my script

```<code>//Check Save
driver.findElement(By.id("Save")).click();
driver.switchTo().alert().accept();
</code>```

Capabilities also used ,

```<code> capabilities.setCapability("autoAcceptAlerts", true);
</code>```

This is what I want to allow

How to accept this alert?
I have tried with xpath sa well, but no luck

答:
Below code will work.Give it a try with "OK" and "Ok". This is because if you want to try to identify the element with the text you can use accessibilityID or ID.

```<code>driver.findElement(By.id("OK")).click();
</code>```

Below code won't work for alerts coming in mobile automation like web alerts.

```<code>driver.switchTo().alert().accept();
</code>```

Title: How to accept this alert in appium?

Body:
Appium v1.6.4-beta
Xcode 8.2
macOs Sierra 10.12

I want to automate to save photo in my device.
But in first time I have to give permission.
I have used "accept alert", but cannot accept the alert for allow to access the photo library.
It shows the test passed in green , when I execute the test, but this popup still appear in view and photo is not saved.

This is my script

//Check Save
driver.findElement(By.id("Save")).click();
driver.switchTo().alert().accept();

Capabilities also used ,

 capabilities.setCapability("autoAcceptAlerts", true);

This is what I want to allow

How to accept this alert?
I have tried with xpath sa well, but no luck

Body:
Below code will work.Give it a try with "OK" and "Ok". This is because if you want to try to identify the element with the text you can use accessibilityID or ID.

driver.findElement(By.id("OK")).click();

Below code won't work for alerts coming in mobile automation like web alerts.

driver.switchTo().alert().accept();


问:
App crash on E/cutils-trace: Error opening trace file: No such file or directory (2)
There are many Q&A's on StackOverflow concerning the "Error opening trace file" error message. But it looks like my case is different.

My App crashes when this error-message appears.

Here is the logcat:

```<code>03-06 20:07:35.142 3033-16751/? W/photo.fastid.printservice.utilities.DownloadFile: Starting download......from https://example.com/download
03-06 20:07:37.052 3033-16775/? W/photo.fastid.printservice.utilities.DownloadFile: Starting download......from https://example.com/download
03-06 20:07:38.622 16792-16792/? E/cutils-trace: Error opening trace file: No such file or directory (2)
03-06 20:07:38.832 16792-16792/? E/memtrack: Couldn't load memtrack module (No such file or directory)
03-06 20:07:38.832 16792-16792/? E/android.os.Debug: failed to load memtrack module: -2
03-06 20:07:40.402 545-2066/? W/ContextImpl: Calling a method in the system process without a qualified user: android.app.ContextImpl.sendBroadcast:1162 com.android.server.am.ActivityManagerService.onVideoPlayerCrashed:3689 com.android.server.am.ActivityManagerService.handleAppDiedLocked:3719 com.android.server.am.ActivityManagerService.removeProcessLocked:4887 com.android.server.am.ActivityManagerService.killPackageProcessesLocked:4696
</code>```

The App polls a server for a (photo) download and has been doing this for a couple of hours.

Then, Logcat shows the "Error opening trace file" message.

After this message, my app no longer polls the server.

However, other activities on the UI (like opening a menu or changing a setting) work fine.

There is nothing else in the logcat, no exceptions and print-stacks...

My questions:

How is the polling related to this error?

What can I do to get my polling stable again?

Note: this App is old but the error is new. Meanwhile, the code has not (significantly) changed. Can this be caused by AndroidStudio updating my SDK?

My gradle:

```<code>compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
    applicationId "openbook.pub.photosprint"
    minSdkVersion 19
    targetSdkVersion 25
    versionCode 2
    versionName "1.1"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
</code>```

答:
I never truly resolved this issue, but after adding

```<code><application
    android:largeHeap=["true"]
    . . .
</application>
</code>```

to the Manifest, I have not seen this crash re-occur...

Body:
There are many Q&A's on StackOverflow concerning the "Error opening trace file" error message. But it looks like my case is different.

My App crashes when this error-message appears.

Here is the logcat:

03-06 20:07:35.142 3033-16751/? W/photo.fastid.printservice.utilities.DownloadFile: Starting download......from https://example.com/download
03-06 20:07:37.052 3033-16775/? W/photo.fastid.printservice.utilities.DownloadFile: Starting download......from https://example.com/download
03-06 20:07:38.622 16792-16792/? E/cutils-trace: Error opening trace file: No such file or directory (2)
03-06 20:07:38.832 16792-16792/? E/memtrack: Couldn't load memtrack module (No such file or directory)
03-06 20:07:38.832 16792-16792/? E/android.os.Debug: failed to load memtrack module: -2
03-06 20:07:40.402 545-2066/? W/ContextImpl: Calling a method in the system process without a qualified user: android.app.ContextImpl.sendBroadcast:1162 com.android.server.am.ActivityManagerService.onVideoPlayerCrashed:3689 com.android.server.am.ActivityManagerService.handleAppDiedLocked:3719 com.android.server.am.ActivityManagerService.removeProcessLocked:4887 com.android.server.am.ActivityManagerService.killPackageProcessesLocked:4696

The App polls a server for a (photo) download and has been doing this for a couple of hours.

Then, Logcat shows the "Error opening trace file" message.

After this message, my app no longer polls the server.

However, other activities on the UI (like opening a menu or changing a setting) work fine.

There is nothing else in the logcat, no exceptions and print-stacks...

My questions:

How is the polling related to this error?

What can I do to get my polling stable again?

Note: this App is old but the error is new. Meanwhile, the code has not (significantly) changed. Can this be caused by AndroidStudio updating my SDK?

My gradle:

compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
    applicationId "openbook.pub.photosprint"
    minSdkVersion 19
    targetSdkVersion 25
    versionCode 2
    versionName "1.1"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}

Body:
I never truly resolved this issue, but after adding

<application
    android:largeHeap=["true"]
    . . .
</application>

to the Manifest, I have not seen this crash re-occur...


问:
How do I unhook an action? My current method does not seem to be working
I am working on a WordPress website, with WooCommerce functionality.
I am currently trying to remove the social sharing feature, which is displayed on the Product Pages.  I am trying to achieve this through the removal of the Action from its Hook, by placing the following code in the functions.php file:

```<code><?php
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_sharing', 50 );
?>
</code>```

Said functions.php is placed within the Child Theme I have created.

Unfortunately, this is not removing the social sharing feature.  Does anyone know why?  To see if there was an issue with the Hooks, I added an Action to the same Hook, to which this worked.

Could it be possible that the Social Sharing feature has been placed in some parent folder which overrides/has higher priority over the functions.php file in the Child theme?  If this is the case, what would be my options in getting said feature removed.  I can only think of placing the affected file in the Child theme and then manually removing the relevant coding.  This is a last resort as it may cause problems, at a later date, when parent files are updated etc.

答:
You could use https://codex.wordpress.org/Function_Reference/remove_all_actions</p>

```<code>add_action('plugins_loaded', function(){
   remove_all_actions('woocommerce_share_hook');
});
</code>```

Body:
I am working on a WordPress website, with WooCommerce functionality.
I am currently trying to remove the social sharing feature, which is displayed on the Product Pages.  I am trying to achieve this through the removal of the Action from its Hook, by placing the following code in the functions.php file:

<?php
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_sharing', 50 );
?>

Said functions.php is placed within the Child Theme I have created.

Unfortunately, this is not removing the social sharing feature.  Does anyone know why?  To see if there was an issue with the Hooks, I added an Action to the same Hook, to which this worked.

Could it be possible that the Social Sharing feature has been placed in some parent folder which overrides/has higher priority over the functions.php file in the Child theme?  If this is the case, what would be my options in getting said feature removed.  I can only think of placing the affected file in the Child theme and then manually removing the relevant coding.  This is a last resort as it may cause problems, at a later date, when parent files are updated etc.

Body:
You could use https://codex.wordpress.org/Function_Reference/remove_all_actions

add_action('plugins_loaded', function(){
   remove_all_actions('woocommerce_share_hook');
});


问:
SSIS - Data Conversion from DT_STR to int
How to apply the below transformation in SSIS data flow task

```<code>cast(gift_amount as int)/100
</code>```

In Derived Column Transformation Editor, I am unable to change the data type. It gives 0xC0049064 error upon giving typecast function.

答:
You can acieve this using a script component

Add a Script Component

Mark gift_amount as input column

Add an output column of type Decimal or float (ex outColumn)

Add the following code: (using vb.net)

```<code>If Not Row.giftamount_IsNull AndAlso
   Not String.IsNullOrEmpty(Row.giftamount) Then

    Row.outColumn = CDec(CInt(Row.giftamount) / 100)

Else

    Row.outColumn_IsNull = True

End If
</code>```

Body:
How to apply the below transformation in SSIS data flow task

cast(gift_amount as int)/100

In Derived Column Transformation Editor, I am unable to change the data type. It gives 0xC0049064 error upon giving typecast function.

Body:
You can acieve this using a script component

Add a Script Component

Mark gift_amount as input column

Add an output column of type Decimal or float (ex outColumn)

Add the following code: (using vb.net)

If Not Row.giftamount_IsNull AndAlso
   Not String.IsNullOrEmpty(Row.giftamount) Then

    Row.outColumn = CDec(CInt(Row.giftamount) / 100)

Else

    Row.outColumn_IsNull = True

End If


问:
How do I access the HTTP request header fields via JavaScript?
I want to capture the HTTP request header fields, primarily the Referer and User-Agent, within my client-side JavaScript.  How may I access them?

Google Analytics manages to get the data via JavaScript that they have you embed in you pages, so it is definitely possible.

Related:

  Accessing the web page's HTTP Headers in JavaScript

答:
This can be accessed through Javascript because it's a property of the loaded document, not of its parent.

Here's a quick example:

```<code><script type="text/javascript">
document.write(document.referrer);
</script>
</code>```

The same thing in PHP would be:

```<code><?php echo $_SERVER["HTTP_REFERER"]; ?>
</code>```

OwnerDisplayName: dacracot

LastEditorDisplayName: dacracot

Body:
This can be accessed through Javascript because it's a property of the loaded document, not of its parent.

Here's a quick example:

<script type="text/javascript">
document.write(document.referrer);
</script>

The same thing in PHP would be:

<?php echo $_SERVER["HTTP_REFERER"]; ?>


答:
Use mysqli_num_rows that will return total results returned by the query. If total > 0 then results found else no results.

To fetch rows from MySQL result set, use mysqli_fetch_assoc

```<code>$result = mysqli_query($conn,$sql);

// $result contains result set and will return `TRUE` if query was successfully executed
// and will return `FALSE` only in case of error

$total = mysqli_num_rows($result);
if($total > 0)
{
    echo "Yes";
    // Fetch rows from mysql result set
    while($row=mysqli_fetch_assoc($result))
    {
        print_r($row);
    }
}
else
{
    echo "no";
}
</code>```

Title: php echo result from mysql and datetime selection

Body:
MySQL database Start = "2017-03-29 01:30:00"

The problem is:

I print the $SQL and search the record in MySQL database, it can search the record. However, I need to debug and test if there is no result, it will be expected to echo "No". But, it always to echo "Yes" no matter I can get the record in MySQL or not.

How can I fixed it.

Main purpose: Get the record if there are and Echo "No" if there don't have record

  <?php
    $serverName = "localhost";
    $username = "root";
    $password = "";
    $dbName = "fyp";
    $tbName = "events";

    $String_start = '2017-03-29 01:28:00';
    $String_end = '2017-03-29 01:32:00';

    $conn = new mysqli($serverName, $username, $password, $dbName);

    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    //$staffID =  $_SESSION['userID'];
    $staff_ID = '15207800';

    $sql = "SELECT *
                    FROM `$tbName`
                    WHERE  `start` BETWEEN ('$String_start') AND ('$String_end')";

    echo $sql;
    $result=mysqli_query($conn,$sql);

    if($result)
    {
        echo "Yes";
    }
    else{
        echo "no";
    }

    ?>

Body:
Use mysqli_num_rows that will return total results returned by the query. If total > 0 then results found else no results.

To fetch rows from MySQL result set, use mysqli_fetch_assoc

$result = mysqli_query($conn,$sql);

// $result contains result set and will return `TRUE` if query was successfully executed
// and will return `FALSE` only in case of error

$total = mysqli_num_rows($result);
if($total > 0)
{
    echo "Yes";
    // Fetch rows from mysql result set
    while($row=mysqli_fetch_assoc($result))
    {
        print_r($row);
    }
}
else
{
    echo "no";
}


问:
Image preloading techniques (for use as hover state CSS background images) don't seem to work on Chrome
I'm using the following technique to pre-load images that are applied as CSS background images when hovering buttons:

```<code>#preload_area {
  background-image:
    url(../images/image1.svg),
    url(../images/image2.svg);
  width: 0px;
  height: 0px;
  display: inline;
}
</code>```

Also tried to pre-load just one image, this way:

```<code>#preload_area {
  background: url(../images/image1.svg) -9999px -9999px no-repeat;
}
</code>```

None of this works: after hard refresh, when hovering my button the first time, I still see a blink (corresponding to loading the hover image). Obviously after that first time there's no blink any more.

Why is not working on Chrome? (it does work on Firefox)

答:
Live Demo:
http://blackmiaool.com/soa/43093224/

No one promise that invisible images will be loaded. Browsers have right to not preload your invisible images, so the css approach in your question may not work in some browsers. The demo above is written by myself. It actually renders image on the screen to guarantee the image is loaded.

HTML:

```<code><!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <title>test</title>

</head>

<body>
    <h1 style="color:white;text-align:center;">Try to hover</h1>
    <div class="show-area"></div>
    <link rel="stylesheet" href="style.css">

    <script src="../js/jquery.min.js"></script>
    <script>
        function preloadImage(src, cb) {
            //create a image
            const $dom = $("<img />", {
                src: src
            });

            //check whether the image is already loaded
            if ($dom[0].naturalWidth) {
                cb && cb();
                return;
            }

            //Put the image at the left bottom of the screen, and set its opacity to 0.01 to keep it from people eyes.
            //Since it's actually rendered on the screen, the browser must load the image
            $dom.css({
                opacity: 0.01,
                position: 'fixed',
                bottom: 0,
                left: 0,
                height: 1,
                width: 1,
                'z-index': 10000,
                'pointer-events': 'none',
            });

            $(document.body).append($dom);

            //listen its `load` event to remove it and invoke callback
            $dom.on("load", function() {
                $dom.remove();
                cb && cb();
            });
        }

        //try to get the urls in the css file, and preload them
        $("link").each(function() {
            const href = $(this).attr("href");
            $.get(href, function(style) {
                const urls = [];
                let match = style.match(/url\([\s\S]+?\)/g);

                match.forEach(function(str) {
                    str = str.replace(/\s/g, "")
                        .replace(/^url\(/, "")
                        .replace(/\)$/, "");
                    let url = str.match(/^["']?([\S]+?)["']?$/);
                    if (!url || !url[1]) {
                        console.warn("Can't find url of " + str);
                    } else {
                        url = url[1];
                        preloadImage(url);
                    }
                });
            });
        });
    </script>

</body>

</html>
</code>```

css:

```<code>body{
    margin: 0;
    background-color: black;
}
.show-area {
    height: 100px;
    width: 300px;
    margin: auto;
    margin-top: 100px;
    background: url( ./1.jpg) no-repeat center;
    background-size: contain;
}

.show-area:hover {
    background-image: url("./2.jpg ");
}
</code>```

Body:
I'm using the following technique to pre-load images that are applied as CSS background images when hovering buttons:

#preload_area {
  background-image:
    url(../images/image1.svg),
    url(../images/image2.svg);
  width: 0px;
  height: 0px;
  display: inline;
}

Also tried to pre-load just one image, this way:

#preload_area {
  background: url(../images/image1.svg) -9999px -9999px no-repeat;
}

None of this works: after hard refresh, when hovering my button the first time, I still see a blink (corresponding to loading the hover image). Obviously after that first time there's no blink any more.

Why is not working on Chrome? (it does work on Firefox)

Body:
Live Demo:
http://blackmiaool.com/soa/43093224/

No one promise that invisible images will be loaded. Browsers have right to not preload your invisible images, so the css approach in your question may not work in some browsers. The demo above is written by myself. It actually renders image on the screen to guarantee the image is loaded.

HTML:

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <title>test</title>

</head>

<body>
    <h1 style="color:white;text-align:center;">Try to hover</h1>
    <div class="show-area"></div>
    <link rel="stylesheet" href="style.css">

    <script src="../js/jquery.min.js"></script>
    <script>
        function preloadImage(src, cb) {
            //create a image
            const $dom = $("<img />", {
                src: src
            });

            //check whether the image is already loaded
            if ($dom[0].naturalWidth) {
                cb && cb();
                return;
            }

            //Put the image at the left bottom of the screen, and set its opacity to 0.01 to keep it from people eyes.
            //Since it's actually rendered on the screen, the browser must load the image
            $dom.css({
                opacity: 0.01,
                position: 'fixed',
                bottom: 0,
                left: 0,
                height: 1,
                width: 1,
                'z-index': 10000,
                'pointer-events': 'none',
            });

            $(document.body).append($dom);

            //listen its `load` event to remove it and invoke callback
            $dom.on("load", function() {
                $dom.remove();
                cb && cb();
            });
        }

        //try to get the urls in the css file, and preload them
        $("link").each(function() {
            const href = $(this).attr("href");
            $.get(href, function(style) {
                const urls = [];
                let match = style.match(/url\([\s\S]+?\)/g);

                match.forEach(function(str) {
                    str = str.replace(/\s/g, "")
                        .replace(/^url\(/, "")
                        .replace(/\)$/, "");
                    let url = str.match(/^["']?([\S]+?)["']?$/);
                    if (!url || !url[1]) {
                        console.warn("Can't find url of " + str);
                    } else {
                        url = url[1];
                        preloadImage(url);
                    }
                });
            });
        });
    </script>

</body>

</html>

css:

body{
    margin: 0;
    background-color: black;
}
.show-area {
    height: 100px;
    width: 300px;
    margin: auto;
    margin-top: 100px;
    background: url( ./1.jpg) no-repeat center;
    background-size: contain;
}

.show-area:hover {
    background-image: url("./2.jpg ");
}


问:
ExpressJS does not seem to work with ajax calls
I'm trying to figure out Node.js to use as an api to do GET, POST, etc. I've been stuck trying to figure out why this post is not working.

My ajax call:

```<code>$.ajax({
        method: "POST",
        contentType: 'application/json',
        dataType: 'json',
        url: "localhost:8000/login",
        data: JSON.stringify({user:"john", pass:"123"}),
        error: function () {
            alert('error');
        },
        success: function (data) {
            alert('success');
        }
    });
</code>```

In my express:

```<code>var express = require('express');
var app = express();
var bodyParser = require('body-parser');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.post('/login', function (req, res) {
  var user = req.body.user;
  var password = req.body.pass;
  if(user == 'john' && password == '123') {
    res.status(200);
  } else {
    res.status(401);
  }
});

app.listen(8000, function () {
  console.log('Example app listening on port 8000!');
});
</code>```

Any help is greatly appreciated.

答:
you should return some response from your express code, also response should be ended especially in case of just sending only the status code like res.status(401);

```<code>app.post('/login', function (req, res) {
    var user = req.body.user;
    var password = req.body.pass;
    if(user == 'john' && password == '123') {
        res.status(200).json({t:1});
    } else {
        res.status(401);
    }

    res.end();
});
</code>```

Body:
I'm trying to figure out Node.js to use as an api to do GET, POST, etc. I've been stuck trying to figure out why this post is not working.

My ajax call:

$.ajax({
        method: "POST",
        contentType: 'application/json',
        dataType: 'json',
        url: "localhost:8000/login",
        data: JSON.stringify({user:"john", pass:"123"}),
        error: function () {
            alert('error');
        },
        success: function (data) {
            alert('success');
        }
    });

In my express:

var express = require('express');
var app = express();
var bodyParser = require('body-parser');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.post('/login', function (req, res) {
  var user = req.body.user;
  var password = req.body.pass;
  if(user == 'john' && password == '123') {
    res.status(200);
  } else {
    res.status(401);
  }
});

app.listen(8000, function () {
  console.log('Example app listening on port 8000!');
});

Any help is greatly appreciated.

Body:
you should return some response from your express code, also response should be ended especially in case of just sending only the status code like res.status(401);

app.post('/login', function (req, res) {
    var user = req.body.user;
    var password = req.body.pass;
    if(user == 'john' && password == '123') {
        res.status(200).json({t:1});
    } else {
        res.status(401);
    }

    res.end();
});


问:
Execute program as normal user (while being root)
I'm working on Debian 8 (Jessie) (64 bits). I want to run program as normal user, without creating and switching accounts to normal user.

I am running the main program from bash script:

```<code>screen ./run
</code>```

where run contains:

```<code>#!/bin/bash
ulimit -c unlimited
while true; do ./tfs --log-file "output.txt" "error.txt" | tee out.txt; done
</code>```

I want to run the 'tfs' as normal user

答:
I suggest:</p>

```<code>su - -c "screen /path/to/run" username
</code>```

Body:
I'm working on Debian 8 (Jessie) (64 bits). I want to run program as normal user, without creating and switching accounts to normal user.

I am running the main program from bash script:

screen ./run

where run contains:

#!/bin/bash
ulimit -c unlimited
while true; do ./tfs --log-file "output.txt" "error.txt" | tee out.txt; done

I want to run the 'tfs' as normal user

Body:
I suggest:

su - -c "screen /path/to/run" username


问:
Issue of undefined index while using ajax and php
I have four different files

index.php

select.php

insert.php

edit.php

delete.php

In my backend I have created a database named 'ecc'

Database 'ecc' has atable named 'task'

The table task has following fields

id, name, category, cost

Datatype for  id set to int and index as primary also id field is on auto increment

My issue :( ! ) Notice: Undefined index: id in C:\wamp\www\select.php on line 38

and same for lines 39, 40, 41,

each of the error is displayed twice on the page.

index.php

```<code><html>
      <head>
           <title>Live Table Data Edit</title>
           <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
           <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
           <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
      </head>
      <body>
           <div class="container">
                <br />
                <br />
                <br />
                <div class="table-responsive">
                     <h3 align="center">Live Table Add Edit Delete using Ajax Jquery in PHP Mysql</h3><br />
                     <div id="live_data"></div>
                </div>
           </div>
      </body>
 </html>
 <script>
 $(document).ready(function(){
      function fetch_data()
      {
           $.ajax({
                url:"select.php",
                method:"POST",
                success:function(data){
                     $('#live_data').html(data);
                }
           });
      }
      fetch_data();
      $(document).on('click', '#btn_add', function(){
           var name = $('#name').text();
           var category = $('#category').text();
           if(name == '')
           {
                alert("Enter service Name");
                return false;
           }
           if(category == '')
           {
                alert("Enter category");
                return false;
           }
           $.ajax({
                url:"insert.php",
                method:"POST",
                data:{name:name, category:category},
                dataType:"text",
                success:function(data)
                {
                     alert(data);
                     fetch_data();
                }
           })
      });
      function edit_data(id, text, column_name)
      {
           $.ajax({
                url:"edit.php",
                method:"POST",
                data:{id:id, text:text, column_name:column_name},
                dataType:"text",
                success:function(data){
                     alert(data);
                }
           });
      }
      $(document).on('blur', '.name', function(){
           var id = $(this).data("id1");
           var name = $(this).text();
           edit_data(id, name, "name");
      });
      $(document).on('blur', '.category', function(){
           var id = $(this).data("id2");
           var category = $(this).text();
           edit_data(id,category, "category");
      });
      $(document).on('click', '.btn_delete', function(){
           var id=$(this).data("id3");
           if(confirm("Are you sure you want to delete this?"))
           {
                $.ajax({
                     url:"delete.php",
                     method:"POST",
                     data:{id:id},
                     dataType:"text",
                     success:function(data){
                          alert(data);
                          fetch_data();
                     }
                });
           }
      });
 });
 </script>
</code>```

select.php

```<code><?php

 $connect = mysqli_connect('localhost', 'root', '','ecc');
    mysqli_select_db($connect,'ecc');

                if(!$connect){
                    echo "yes";
                }else{
                    echo "no";
                }

 $output = '';

 $sql = "SELECT name, category FROM addservices ORDER BY id DESC";

 $result = mysqli_query($connect, $sql);

 $output .= '
      <div class="table-responsive">
           <table class="table table-bordered">
                <tr>
                     <th width="10%">Id</th>
                     <th width="40%">Service Name</th>
                     <th width="40%">Category</th>
                     <th width="10%">Delete</th>
                </tr>';

 if(mysqli_num_rows($result) > 0)
 {
      while($row = mysqli_fetch_array($result))
      {
           $output .= '
                <tr>
                     <td>'.$row["id"].'</td>
                     <td class="name" data-id1="'.$row["id"].'" contenteditable>'.$row["name"].'</td>
                     <td class="category" data-id2="'.$row["id"].'" contenteditable>'.$row["category"].'</td>
                     <td><button type="button" name="delete_btn" data-id3="'.$row["id"].'" class="btn btn-xs btn-danger btn_delete">x</button></td>
                </tr>
           ';
      }
      $output .= '
           <tr>
                <td></td>
                <td id="name" contenteditable></td>
                <td id="category" contenteditable></td>
                <td><button type="button" name="btn_add" id="btn_add" class="btn btn-xs btn-success">+</button></td>
           </tr>
      ';
 }
 else
 {
      $output .= '<tr>
                          <td colspan="4">Data not Found</td>
                     </tr>';
 }
 $output .= '</table>
      </div>';
 echo $output;
 ?>
</code>```

答:
You are getting this error Undefined index: id

Because you have not put id in select query

```<code>$sql = "SELECT id,name, category FROM addservices ORDER BY id DESC";
</code>```

Body:
I have four different files

index.php

select.php

insert.php

edit.php

delete.php

In my backend I have created a database named 'ecc'

Database 'ecc' has atable named 'task'

The table task has following fields

id, name, category, cost

Datatype for  id set to int and index as primary also id field is on auto increment

My issue :( ! ) Notice: Undefined index: id in C:\wamp\www\select.php on line 38

and same for lines 39, 40, 41,

each of the error is displayed twice on the page.

index.php

           <title>Live Table Data Edit</title>
           <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />

Live Table Add Edit Delete using Ajax Jquery in PHP Mysql

select.php

<?php

 $connect = mysqli_connect('localhost', 'root', '','ecc');
    mysqli_select_db($connect,'ecc');

                if(!$connect){
                    echo "yes";
                }else{
                    echo "no";
                }

 $output = '';

 $sql = "SELECT name, category FROM addservices ORDER BY id DESC";

 $result = mysqli_query($connect, $sql);

 $output .= '

                     Id
                     Service Name
                     Category
                     Delete

';

 if(mysqli_num_rows($result) > 0)
 {
      while($row = mysqli_fetch_array($result))
      {
           $output .= '

                     '.$row["id"].'
                     '.$row["name"].'
                     '.$row["category"].'
                     <button type="button" name="delete_btn" data-id3="'.$row["id"].'" class="btn btn-xs btn-danger btn_delete">x</button>

           ';
      }
      $output .= '

                <button type="button" name="btn_add" id="btn_add" class="btn btn-xs btn-success">+</button>

      ';
 }
 else
 {
      $output .= '

                          Data not Found

';
 }
 $output .= '

';
 echo $output;
 ?>

Body:
You are getting this error Undefined index: id

Because you have not put id in select query

$sql = "SELECT id,name, category FROM addservices ORDER BY id DESC";


问:
Any portable bit trick to select the positive maximum of 2 numbers in C++98?
I have a function

```<code>template< class T>
T MaxMagnitudeOf2( const T a, const T b)
{
    T a = a<0? -a: a;
    T b = b<0? -b: b;
    return a>b? a: b;
}
</code>```

Can it be implemented more efficiently for all C++ basic types (at least 16/32 bit types) using some bit trick?

答:
Don't overthink:

```<code>return std::max(std::abs(a), std::abs(b));
</code>```

Make sure you include both <cstdlib> and <cmath> to get the integer and floating point overloads. Thank C for that detail.

Body:
I have a function

template< class T>
T MaxMagnitudeOf2( const T a, const T b)
{
    T a = a<0? -a: a;
    T b = b<0? -b: b;
    return a>b? a: b;
}

Can it be implemented more efficiently for all C++ basic types (at least 16/32 bit types) using some bit trick?

Body:
Don't overthink:

return std::max(std::abs(a), std::abs(b));

Make sure you include both <cstdlib> and <cmath> to get the integer and floating point overloads. Thank C for that detail.