问:
Symfony3 "SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'catId' cannot be null "
I'm trying to save data with ManyToOne relations in a DataFixtures class. And I get this error on saving data.

Please, help me.

Sources:

Entity/DealsCategory.php:

```<code><?php

namespace AppBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;

/**
 * DealsCategory
 *
 * @ORM\Table(name="deals_category")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\DealsCategoryRepository")
 */
class DealsCategory
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="alias", type="string", length=50, nullable=true)
     */
    private $alias;

    /**
     * @ORM\OneToMany(targetEntity="DealsCategoryLang", mappedBy="category")
     */
    protected $categoryLang;

    /**
     * @return mixed
     */
    public function getCategoryLang()
    {
        return $this->categoryLang;
    }

    /**
     * @param DealsCategoryLang $categoryLang
     */
    public function setCategoryLang(DealsCategoryLang $categoryLang = null)
    {
        $this->categoryLang = $categoryLang;
    }

    /**
     * @param DealsCategoryLang $categoryLang
     */
    public function setOneCategoryLang(DealsCategoryLang $categoryLang)
    {
        $this->categoryLang[] = $categoryLang;
    }

    /**
     * DealsCategory constructor.
     */
    public function __construct()
    {
        $this->categoryLang = new ArrayCollection();
    }

    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set alias
     *
     * @param string $alias
     *
     * @return DealsCategory
     */
    public function setAlias($alias)
    {
        $this->alias = $alias;

        return $this;
    }

    /**
     * Get alias
     *
     * @return string
     */
    public function getAlias()
    {
        return $this->alias;
    }
}
</code>```

Entity/DealsCategoryLang.php:

```<code><?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * DealsCategoryLang
 *
 * @ORM\Table(name="deals_category_lang")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\DealsCategoryLangRepository")
 */
class DealsCategoryLang
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var int
     *
     * @ORM\Column(name="catId", type="integer")
     */
    private $catId;

    /**
     * @var string
     *
     * @ORM\Column(name="lang", type="string", length=10)
     */
    private $lang;

    /**
     * @var string
     *
     * @ORM\Column(name="title", type="string", length=70)
     */
    private $title;

    /**
     * @ORM\ManyToOne(targetEntity="DealsCategory", inversedBy="categoryLang", cascade={"persist"})
     * @ORM\JoinColumn(name="catId", referencedColumnName="id")
     *
     */
    protected $category;

    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set catId
     *
     * @param integer $catId
     *
     * @return DealsCategoryLang
     */
//    public function setCatId($catId)
//    {
//        $this->catId = $catId;
//
//        return $this;
//    }

    /**
     * Get catId
     *
     * @return int
     */
    public function getCatId()
    {
        return $this->catId;
    }

    /**
     * Set lang
     *
     * @param string $lang
     *
     * @return DealsCategoryLang
     */
    public function setLang($lang)
    {
        $this->lang = $lang;

        return $this;
    }

    /**
     * Get lang
     *
     * @return string
     */
    public function getLang()
    {
        return $this->lang;
    }

    /**
     * Set title
     *
     * @param string $title
     *
     * @return DealsCategoryLang
     */
    public function setTitle($title)
    {
        $this->title = $title;

        return $this;
    }

    /**
     * Get title
     *
     * @return string
     */
    public function getTitle()
    {
        return $this->title;
    }
}
</code>```

DataFixtures/ORM/LoadCategories.php

```<code><?php
namespace AppBundle\DataFixtures\ORM;

use AppBundle\Entity\DealsCategory;
use AppBundle\Entity\DealsCategoryLang;
use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

class LoadCategories implements FixtureInterface, ContainerAwareInterface
{

    private $container;
    /**
     * Load data fixtures with the passed EntityManager
     *
     * @param ObjectManager $manager
     */
    public function load(ObjectManager $manager)
    {
        $category = new DealsCategory();
        $categoryLang = new DealsCategoryLang();
        $categoryLang->setLang('en');
        $categoryLang->setTitle('Food and Drinks');
        $category->setOneCategoryLang($categoryLang);

        $manager->persist($category);
        $manager->persist($categoryLang);
        $manager->flush();
    }

    public function setContainer(ContainerInterface $container = null)
    {
        $this->container = $container;
    }
}
</code>```

I've tried it in different ways, but it's still not working. Tell me please, what i am doing wrong?

UPD:
my errors are:

[Doctrine\DBAL\Exception\NotNullConstraintViolationException]

    An exception occurred while executing 'INSERT INTO deals_category_lang (catId, lang, title) VALUES (?, ?, ?)' with params [null, "en", "Food and Drinks"]:

  SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'catId' cannot be null

[Doctrine\DBAL\Driver\PDOException]

    SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'catId' cannot be null

PDOException]

    SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'catId' cannot be null

I am running the fixtures through the command line:

```<code>php bin/console doctrine:fixtures:load --append
</code>```

答:
Ok, I resolved it...
The problem was in my Fixture class:

Instead of

```<code>$category->setOneCategoryLang($categoryLang);
</code>```

I should put the

```<code>$categoryLang->setCategory($category);
</code>```

,respecting the hierarchy of my entities' relations :(

Body:
I'm trying to save data with ManyToOne relations in a DataFixtures class. And I get this error on saving data.

Please, help me.

Sources:

Entity/DealsCategory.php:

<?php

namespace AppBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;

/**
 * DealsCategory
 *
 * @ORM\Table(name="deals_category")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\DealsCategoryRepository")
 */
class DealsCategory
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="alias", type="string", length=50, nullable=true)
     */
    private $alias;

    /**
     * @ORM\OneToMany(targetEntity="DealsCategoryLang", mappedBy="category")
     */
    protected $categoryLang;

    /**
     * @return mixed
     */
    public function getCategoryLang()
    {
        return $this->categoryLang;
    }

    /**
     * @param DealsCategoryLang $categoryLang
     */
    public function setCategoryLang(DealsCategoryLang $categoryLang = null)
    {
        $this->categoryLang = $categoryLang;
    }

    /**
     * @param DealsCategoryLang $categoryLang
     */
    public function setOneCategoryLang(DealsCategoryLang $categoryLang)
    {
        $this->categoryLang[] = $categoryLang;
    }

    /**
     * DealsCategory constructor.
     */
    public function __construct()
    {
        $this->categoryLang = new ArrayCollection();
    }

    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set alias
     *
     * @param string $alias
     *
     * @return DealsCategory
     */
    public function setAlias($alias)
    {
        $this->alias = $alias;

        return $this;
    }

    /**
     * Get alias
     *
     * @return string
     */
    public function getAlias()
    {
        return $this->alias;
    }
}

Entity/DealsCategoryLang.php:

<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * DealsCategoryLang
 *
 * @ORM\Table(name="deals_category_lang")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\DealsCategoryLangRepository")
 */
class DealsCategoryLang
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var int
     *
     * @ORM\Column(name="catId", type="integer")
     */
    private $catId;

    /**
     * @var string
     *
     * @ORM\Column(name="lang", type="string", length=10)
     */
    private $lang;

    /**
     * @var string
     *
     * @ORM\Column(name="title", type="string", length=70)
     */
    private $title;

    /**
     * @ORM\ManyToOne(targetEntity="DealsCategory", inversedBy="categoryLang", cascade={"persist"})
     * @ORM\JoinColumn(name="catId", referencedColumnName="id")
     *
     */
    protected $category;

    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set catId
     *
     * @param integer $catId
     *
     * @return DealsCategoryLang
     */
//    public function setCatId($catId)
//    {
//        $this->catId = $catId;
//
//        return $this;
//    }

    /**
     * Get catId
     *
     * @return int
     */
    public function getCatId()
    {
        return $this->catId;
    }

    /**
     * Set lang
     *
     * @param string $lang
     *
     * @return DealsCategoryLang
     */
    public function setLang($lang)
    {
        $this->lang = $lang;

        return $this;
    }

    /**
     * Get lang
     *
     * @return string
     */
    public function getLang()
    {
        return $this->lang;
    }

    /**
     * Set title
     *
     * @param string $title
     *
     * @return DealsCategoryLang
     */
    public function setTitle($title)
    {
        $this->title = $title;

        return $this;
    }

    /**
     * Get title
     *
     * @return string
     */
    public function getTitle()
    {
        return $this->title;
    }
}

DataFixtures/ORM/LoadCategories.php

<?php
namespace AppBundle\DataFixtures\ORM;

use AppBundle\Entity\DealsCategory;
use AppBundle\Entity\DealsCategoryLang;
use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

class LoadCategories implements FixtureInterface, ContainerAwareInterface
{

    private $container;
    /**
     * Load data fixtures with the passed EntityManager
     *
     * @param ObjectManager $manager
     */
    public function load(ObjectManager $manager)
    {
        $category = new DealsCategory();
        $categoryLang = new DealsCategoryLang();
        $categoryLang->setLang('en');
        $categoryLang->setTitle('Food and Drinks');
        $category->setOneCategoryLang($categoryLang);

        $manager->persist($category);
        $manager->persist($categoryLang);
        $manager->flush();
    }

    public function setContainer(ContainerInterface $container = null)
    {
        $this->container = $container;
    }
}

I've tried it in different ways, but it's still not working. Tell me please, what i am doing wrong?

UPD:
my errors are:

[Doctrine\DBAL\Exception\NotNullConstraintViolationException]

    An exception occurred while executing 'INSERT INTO deals_category_lang (catId, lang, title) VALUES (?, ?, ?)' with params [null, "en", "Food and Drinks"]:

  SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'catId' cannot be null

[Doctrine\DBAL\Driver\PDOException]

    SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'catId' cannot be null

PDOException]

    SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'catId' cannot be null

I am running the fixtures through the command line:

php bin/console doctrine:fixtures:load --append

Body:
Ok, I resolved it...
The problem was in my Fixture class:

Instead of

$category->setOneCategoryLang($categoryLang);

I should put the

$categoryLang->setCategory($category);

,respecting the hierarchy of my entities' relations :(


来源: stackexchange

问:
What algorithm is used in Set to avoid duplicates?
May I know What algorithm is used in Set to avoid duplicates ?<br>
I want to know just What is the name of the algorithm used to avoid the duplicates and If possible the same algorithm implementation as well. </p>

答:
The algorithm is found here;
https://homepages.inf.ed.ac.uk/wadler/gj/doc/java.util.Set.html#add(A)

Adds the specified element to this Set if it is not already present (optional operation). More formally, adds the specified element, o, to the Set if the Set contains no element e such that (o==null ? e==null : o.equals(e)). If the Set already contains the specified element, the call leaves the Set unchanged (and returns false). In combination with the restriction on constructors, this ensures that Sets never contain duplicate elements.

ContentLicense: CC BY-SA 3.0

Body:
May I know What algorithm is used in Set to avoid duplicates ?

I want to know just What is the name of the algorithm used to avoid the duplicates and If possible the same algorithm implementation as well.


问:
Firebase Data Posting
I am trying to post data on a particular structure in firebase database but not able to get the expected result. Need the structure like:

```<code>ABC->DEVICE_ID-COORDINATES->DATE->PUSHKEY (EX:-KSHJDWFQ)->NOW CHILD LATITUDE AND LONGITUDE.
</code>```

I am not able to push the child to date as the expected pattern.

Expected pattern:

```<code>        {
          "ABC" : {
            "1_861645036247906" : {  ///device id
              "co-ordinates" : {     ///coordinates
                "15-11-2017" : {     ///date
                  "KSHJDWFQ" : {     ///push key
                    "latitude" : 4564564,
                    "longitude" : 45454545
                  },
                  "khgjhkhjk" : {
                    "latitude" : 456456456,
                    "longitude" : 435345345
                  }
                },
                "16-11-2017" : {
                  "KSHJDWFQ" : {
                    "latitude" : 4564564,
                    "longitude" : 45454545
                  },
                  "khgjhkhjk" : {
                    "latitude" : 456456456,
                    "longitude" : 435345345
                  }
                }
              },
              "driver_details" : {
                "driver_id" : 1,
                "driver_name" : "avik"
              }
            }
          },
        }
</code>```

My result is coming like this:

```<code>        {
          "ABC" : {
            "2_861645036247906" : {
              "-Kz8lFh9B86pCj62gcN3" : {
                "coordinates" : {
                  "17-11-2017" : {
                    "latitude" : "22.5735875",
                    "longitude" : "88.431699"
                  }
                }
              },
              "-Kz8ldboHvGS5QabIVZY" : {
                "coordinates" : {
                  "17-11-2017" : {
                    "latitude" : "22.5735875",
                    "longitude" : "88.431699"
                  }
                }
              }
            }
          }
        }
</code>```

This is the code I have done:

```<code>    Driver driver = new Driver();
    String child_node = KPUtils.get_driver_IdPreference(mContext) + "_" + KPUtils.getdeviceid(mContext);
    Firebase ref = new Firebase("https://pool------").child(child_node);

    String date = new SimpleDateFormat("dd-MM-yyyy").format(new Date());
    Map<String, String> m_coordinates = new HashMap<>();
    m_coordinates.put("latitude", st_latitude);
    m_coordinates.put("longitude", st_longitude);
    Map<String, Map<String, String>> gens = new HashMap<>();
    gens.put(date, m_coordinates);

    Map<String, String> m_driverdetails = new HashMap<>();
    m_driverdetails.put("driver_id", "1");
    m_driverdetails.put("driver_name", "Avik");

    driver.setCoordinates(gens);
    //driver.setDriver_details(m_driverdetails);
    ref.push().setValue(driver);
</code>```

答:
You may try this...</p>

```<code>ref.child("abc")
    .child("device id")
    .child("coordinates")
    .child(date)
    .push()
    .setValue(m_coordinates);
</code>```

Title: Firebase Data Posting

Body:
I am trying to post data on a particular structure in firebase database but not able to get the expected result. Need the structure like:

ABC->DEVICE_ID-COORDINATES->DATE->PUSHKEY (EX:-KSHJDWFQ)->NOW CHILD LATITUDE AND LONGITUDE.

I am not able to push the child to date as the expected pattern.

Expected pattern:

        {
          "ABC" : {
            "1_861645036247906" : {  ///device id
              "co-ordinates" : {     ///coordinates
                "15-11-2017" : {     ///date
                  "KSHJDWFQ" : {     ///push key
                    "latitude" : 4564564,
                    "longitude" : 45454545
                  },
                  "khgjhkhjk" : {
                    "latitude" : 456456456,
                    "longitude" : 435345345
                  }
                },
                "16-11-2017" : {
                  "KSHJDWFQ" : {
                    "latitude" : 4564564,
                    "longitude" : 45454545
                  },
                  "khgjhkhjk" : {
                    "latitude" : 456456456,
                    "longitude" : 435345345
                  }
                }
              },
              "driver_details" : {
                "driver_id" : 1,
                "driver_name" : "avik"
              }
            }
          },
        }

My result is coming like this:

        {
          "ABC" : {
            "2_861645036247906" : {
              "-Kz8lFh9B86pCj62gcN3" : {
                "coordinates" : {
                  "17-11-2017" : {
                    "latitude" : "22.5735875",
                    "longitude" : "88.431699"
                  }
                }
              },
              "-Kz8ldboHvGS5QabIVZY" : {
                "coordinates" : {
                  "17-11-2017" : {
                    "latitude" : "22.5735875",
                    "longitude" : "88.431699"
                  }
                }
              }
            }
          }
        }

This is the code I have done:

    Driver driver = new Driver();
    String child_node = KPUtils.get_driver_IdPreference(mContext) + "_" + KPUtils.getdeviceid(mContext);
    Firebase ref = new Firebase("https://pool------").child(child_node);

    String date = new SimpleDateFormat("dd-MM-yyyy").format(new Date());
    Map<String, String> m_coordinates = new HashMap<>();
    m_coordinates.put("latitude", st_latitude);
    m_coordinates.put("longitude", st_longitude);
    Map<String, Map<String, String>> gens = new HashMap<>();
    gens.put(date, m_coordinates);

    Map<String, String> m_driverdetails = new HashMap<>();
    m_driverdetails.put("driver_id", "1");
    m_driverdetails.put("driver_name", "Avik");

    driver.setCoordinates(gens);
    //driver.setDriver_details(m_driverdetails);
    ref.push().setValue(driver);

Body:
You may try this...

ref.child("abc")
    .child("device id")
    .child("coordinates")
    .child(date)
    .push()
    .setValue(m_coordinates);


问:
Create custom file type and extension using Blob()

function download(){
  var fileName = 'testDemo';
  var type = 'xyz';
  var data = 'Hello world';
  var file = new Blob([data], {
    type: type
  });
  if (window.navigator.msSaveOrOpenBlob) // IE10+
    window.navigator.msSaveOrOpenBlob(file, fileName);
  else { // Others
    var a = document.createElement("a"),
      url = URL.createObjectURL(file);
    a.href = url;
    a.download = fileName + '.' +type;
    document.body.appendChild(a);
    a.click();
    setTimeout(function() {
      document.body.removeChild(a);
      window.URL.revokeObjectURL(url);
    }, 100);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button onclick='download()'>Download</button></code>```

Here I am setting type and extension as .xyz but still it shows plain text document (text/plain) in property and can't read the file type also which shows a empty string. How can I create a custom extension and type?

答:
You are passing an extension instead of useful mime type at the time of instantiating blob object.

```<code> var fileName = 'testDemo';
 var type = 'application/pdf';
 var data = 'Hello world';
 var file = new Blob([data], {
            type: type
           });
</code>```

Refer other useful mime types here :
mime types

Body:
function download(){
  var fileName = 'testDemo';
  var type = 'xyz';
  var data = 'Hello world';
  var file = new Blob([data], {
    type: type
  });
  if (window.navigator.msSaveOrOpenBlob) // IE10+
    window.navigator.msSaveOrOpenBlob(file, fileName);
  else { // Others
    var a = document.createElement("a"),
      url = URL.createObjectURL(file);
    a.href = url;
    a.download = fileName + '.' +type;
    document.body.appendChild(a);
    a.click();
    setTimeout(function() {
      document.body.removeChild(a);
      window.URL.revokeObjectURL(url);
    }, 100);
  }
}

<button onclick='download()'>Download</button>

Here I am setting type and extension as .xyz but still it shows plain text document (text/plain) in property and can't read the file type also which shows a empty string. How can I create a custom extension and type?

Body:
You are passing an extension instead of useful mime type at the time of instantiating blob object.

 var fileName = 'testDemo';
 var type = 'application/pdf';
 var data = 'Hello world';
 var file = new Blob([data], {
            type: type
           });

Refer other useful mime types here :
mime types


问:
Turning off dimming by UIPopoverController
In iOS7, a popover causes the rest of the screen to be dimmed. As per the Apple docs:

The popover content is layered on top of your existing content and the background is dimmed automatically.

This is nice in most cases, but I have an app where the screen rearranges itself when the popover opens and stays responsive, so the dimming only causes confusion. Anyone knows if dimming can be disabled?

答:
This is the swift version to remove the dimming of UIPopoverController</p>

```<code>let allSubViews: [UIView] = (UIApplication.shared.keyWindow?.subviews.last?.subviews)!

        for index in 0...allSubViews.count - 1 {
            allSubViews[index].removeFromSuperview()
                        if NSStringFromClass(allSubViews[index].classForCoder) == "_UIMirrorNinePatchView"
                        {
                            allSubViews[index].backgroundColor = UIColor.clear

                            let arrayofImages = allSubViews[index].subviews as! [UIImageView]

                            for imageIndex in 0...arrayofImages.count - 1 {
                                arrayofImages[imageIndex].image = nil
                            }
                        }
        }
</code>```

Body:
This is the swift version to remove the dimming of UIPopoverController

let allSubViews: [UIView] = (UIApplication.shared.keyWindow?.subviews.last?.subviews)!

        for index in 0...allSubViews.count - 1 {
            allSubViews[index].removeFromSuperview()
                        if NSStringFromClass(allSubViews[index].classForCoder) == "_UIMirrorNinePatchView"
                        {
                            allSubViews[index].backgroundColor = UIColor.clear

                            let arrayofImages = allSubViews[index].subviews as! [UIImageView]

                            for imageIndex in 0...arrayofImages.count - 1 {
                                arrayofImages[imageIndex].image = nil
                            }
                        }
        }


问:
How to show order list in alphabatic order dynamically?
code:

```<code><table width="100%" cellspacing="0" cellpadding="0" border="0" style="line-height: 1.7;">
    <tbody>
        <?php
            $this->db->select('*');
            $this->db->from('cm_options');
            $where = "qid = '$qid'";
            $this->db->where($where);
            $sql = $this->db->get();
            //echo $this->db->last_query();
            $res = $sql->result_array();
            foreach($res as $rows)
            {
                $option = $rows['q_option'];
        ?>
        <tr>
            <ol type="A">
                <td width="5%">
                    <li><a href="javascript:void(0)"><input type="radio" name="radio_btn"></a></li>
                </td>
            </ol>
            <td width="99%"><?php echo $option; ?></td>
        </tr>
        <?php
            }
        ?>
    </tbody>
</table>
</code>```

In this code I have created objective type question form where option are display perfectly. Now, I want to show all option in alphabet order like A,B,C,D but now, It display dots instead of A,B,C,D. So, How can I display my option in alphabetically order ?Please help me.

Thank You

答:
What about using the order by (also changed the $this->db->where() to avoid sql injection):

```<code><table width="100%" cellspacing="0" cellpadding="0" border="0" style="line-height: 1.7;">
    <tbody>
        <?php
            $this->db->select('*');
            $this->db->from('cm_options');
            $this->db->where('qid', $qid);
            $this->db->order_by('q_option', 'ASC');
            $sql = $this->db->get();
            //echo $this->db->last_query();
            $res = $sql->result_array();
            foreach($res as $rows)
            {
                $option = $rows['q_option'];
        ?>
        <tr>
            <ol type="A">
                <td width="5%">
                    <li><a href="javascript:void(0)"><input type="radio" name="radio_btn"></a></li>
                </td>
            </ol>
            <td width="99%"><?php echo $option; ?></td>
        </tr>
        <?php
            }
        ?>
    </tbody>
</table>
</code>```

Body:
code:

        <?php
            $this->db->select('*');
            $this->db->from('cm_options');
            $where = "qid = '$qid'";
            $this->db->where($where);
            $sql = $this->db->get();
            //echo $this->db->last_query();
            $res = $sql->result_array();
            foreach($res as $rows)
            {
                $option = $rows['q_option'];
        ?>

<input type="radio" name="radio_btn">

            <?php echo $option; ?>

        <?php
            }
        ?>

In this code I have created objective type question form where option are display perfectly. Now, I want to show all option in alphabet order like A,B,C,D but now, It display dots instead of A,B,C,D. So, How can I display my option in alphabetically order ?Please help me.

Thank You

Body:
What about using the order by (also changed the $this->db->where() to avoid sql injection):

<table width="100%" cellspacing="0" cellpadding="0" border="0" style="line-height: 1.7;">
    <tbody>
        <?php
            $this->db->select('*');
            $this->db->from('cm_options');
            $this->db->where('qid', $qid);
            $this->db->order_by('q_option', 'ASC');
            $sql = $this->db->get();
            //echo $this->db->last_query();
            $res = $sql->result_array();
            foreach($res as $rows)
            {
                $option = $rows['q_option'];
        ?>
        <tr>
            <ol type="A">
                <td width="5%">
                    <li><a href="javascript:void(0)"><input type="radio" name="radio_btn"></a></li>
                </td>
            </ol>
            <td width="99%"><?php echo $option; ?></td>
        </tr>
        <?php
            }
        ?>
    </tbody>
</table>


问:
How to get numbers out of string into array
I have strings like

'156p1m2s10c'

'15p13m22s3c'

'1644p31m142s3c'

out of which I want to get all numerics separately.

An array will also work like:

```<code>156
--
1
--
2
--
33
</code>```

How to do it using Jquery. I tried code mentioned below, but it's all going wrong.

```<code>function myFunction() {
    var str = "156p1m2s33c";
    var prodId = cust_code.substring(0, url.indexOf('p'));
    var metalId = cust_code.substring(url.indexOf('p') + 1, url.indexOf('m'));
    var prodId = cust_code.substring(url.indexOf('m') + 1, url.indexOf('s'));
}
</code>```

What is wrong in the code?

答:
You can use String#match with a RegExp. You can use Array#map afterwards to convert the strings to numbers if needed.

var str = '156p1m2s33c';

var numbers = str.match(/\d+/g);

console.log(numbers);```
</div>
</div>
</p>

<p>What's wrong in your code:</p>

<ol>
<li><code>cust_code</code> and <code>url</code> are not part of the function. Refer to <code>str</code>.</li>
<li>You declare <code>prodId</code> twice.</li>
<li>You don't handle the number between "s" and "c".</li>
<li>You are doing a lot of duplicated search (index of p, index of m, etc...).</li>
<li>Your function doesn't return anything, or do anything with the results.</li>
<li>Using regular expressions is more fitting for this case.</li>
</ol>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function myFunction() {
    var str = "156p1m2s33c";
    var pI = str.indexOf('p');
    var mI = str.indexOf('m');
    var sI = str.indexOf('s');
    var cI = str.indexOf('c');

    var prodId = str.substring(0, pI);
    var metalId = str.substring(pI + 1, mI);
    var anotherId1 = str.substring(mI + 1, sI);
    var anotherId2 = str.substring(sI + 1, cI);

    return [prodId, metalId, anotherId1, anotherId2];
}

console.log(myFunction());</code>```

Body:
I have strings like

'156p1m2s10c'

'15p13m22s3c'

'1644p31m142s3c'

out of which I want to get all numerics separately.

An array will also work like:

156
--
1
--
2
--
33

How to do it using Jquery. I tried code mentioned below, but it's all going wrong.

function myFunction() {
    var str = "156p1m2s33c";
    var prodId = cust_code.substring(0, url.indexOf('p'));
    var metalId = cust_code.substring(url.indexOf('p') + 1, url.indexOf('m'));
    var prodId = cust_code.substring(url.indexOf('m') + 1, url.indexOf('s'));
}

What is wrong in the code?

Body:
You can use String#match with a RegExp. You can use Array#map afterwards to convert the strings to numbers if needed.

var str = '156p1m2s33c';

var numbers = str.match(/\d+/g);

console.log(numbers);

What's wrong in your code:

cust_code and url are not part of the function. Refer to str.

You declare prodId twice.

You don't handle the number between "s" and "c".

You are doing a lot of duplicated search (index of p, index of m, etc...).

Your function doesn't return anything, or do anything with the results.

Using regular expressions is more fitting for this case.

function myFunction() {
    var str = "156p1m2s33c";
    var pI = str.indexOf('p');
    var mI = str.indexOf('m');
    var sI = str.indexOf('s');
    var cI = str.indexOf('c');

    var prodId = str.substring(0, pI);
    var metalId = str.substring(pI + 1, mI);
    var anotherId1 = str.substring(mI + 1, sI);
    var anotherId2 = str.substring(sI + 1, cI);

    return [prodId, metalId, anotherId1, anotherId2];
}

console.log(myFunction());


问:
making numpy.savez deterministic
I was surprised to find that if you save the same numpy object to file using numpy.savez, the file created is not deterministic.
For example,

```<code>import numpy
x = numpy.random.rand(1000, 1000)
numpy.savez('foo.npz', x)
numpy.savez('bar.npz', x)
</code>```

And then

```<code>md5sum foo.npz bar.npz

d1b8b7d2000055b8bf62dddc4a5c77b5  foo.npz
1c6e13bb9efca3ec144e81b88b6cdc75  bar.npz
</code>```

Reading this it looks like it has something to do with the time stamp in the npz zip file.

For testing purposes, I want to verify that the data files that my code creates are identical. I usually do this with a checksum on pickle files, e.g.

```<code>import cPickle as pickle
with open('foo.pkl', 'wb') as f:
    pickle.dump(x, f, protocol=2)

with open('bar.pkl', 'wb') as f:
    pickle.dump(x, f, protocol=2)
</code>```

And then

```<code> md5sum foo.pkl bar.pkl
 3139d9142d57bdde0970013f39b4854f  foo.pkl
 3139d9142d57bdde0970013f39b4854f  bar.pkl
</code>```

Is there any workaround for doing the same thing with numpy.savez?

答:
In case you're indeed not passing keyword arguments to np.savez (i.e. indeed only serializing your data, without wanting to reference the items later based on keys), you can get away with dumping multiple arrays into the same file with np.save:

```<code>import numpy as np
import time

def mysavez(outfile,*args):
    with open(outfile,'wb') as outf:
        for arg in args:
            np.save(outf,arg)

x = np.random.rand(1000,1000)

# control group
np.savez('foo.npz', *[x]*5)
time.sleep(2) # make sure there's a difference in timestamp
np.savez('bar.npz', *[x]*5)

# new one
mysavez('foo.nopz', *[x]*5)
time.sleep(2) # make sure there's a difference in timestamp
mysavez('bar.nopz', *[x]*5)
</code>```

The resulting new files have the same hash, and they even have the exact same size as the originals:

$ md5sum foo.npz bar.npz
4d21c47903b4ffab945f619ad5b6f471  foo.npz
f9af863c6178765d6dc32a5fa2f63623  bar.npz
$ md5sum foo.nopz bar.nopz
c8504f0d8cc53956100912efb02573b0  foo.nopz
c8504f0d8cc53956100912efb02573b0  bar.nopz
$ du {foo,bar}.n*pz
39064   foo.nopz
39064   foo.npz
39064   bar.nopz
39064   bar.npz
```

As long as you're sequentially reading variables from the file you won't notice a functional difference. Of course you'll need a myload to go with it that yields the saved arrays until they're all gone (or be extra fancy and save an initial integer header telling you the number of arrays saved to the file). This approach is admittedly kludgy, but it might cut it depending on your exact use case.

In case you do want to access your saved variables using keys, you could still consider writing an auxiliary function for testing which reads the "production" .npz files, iterates over their ordered keys, saves them sequentially using the above mysavez function, then computes the hash of these "flattened" pickle files. Of course you might not need np.save for this: pickle can do the same for you (although cpickle might not).

Title: making numpy.savez deterministic

Body:
I was surprised to find that if you save the same numpy object to file using numpy.savez, the file created is not deterministic.
For example,

import numpy
x = numpy.random.rand(1000, 1000)
numpy.savez('foo.npz', x)
numpy.savez('bar.npz', x)

And then

md5sum foo.npz bar.npz

d1b8b7d2000055b8bf62dddc4a5c77b5  foo.npz
1c6e13bb9efca3ec144e81b88b6cdc75  bar.npz

Reading this it looks like it has something to do with the time stamp in the npz zip file.

For testing purposes, I want to verify that the data files that my code creates are identical. I usually do this with a checksum on pickle files, e.g.

import cPickle as pickle
with open('foo.pkl', 'wb') as f:
    pickle.dump(x, f, protocol=2)

with open('bar.pkl', 'wb') as f:
    pickle.dump(x, f, protocol=2)

And then

 md5sum foo.pkl bar.pkl
 3139d9142d57bdde0970013f39b4854f  foo.pkl
 3139d9142d57bdde0970013f39b4854f  bar.pkl

Is there any workaround for doing the same thing with numpy.savez?

Body:
In case you're indeed not passing keyword arguments to np.savez (i.e. indeed only serializing your data, without wanting to reference the items later based on keys), you can get away with dumping multiple arrays into the same file with np.save:

import numpy as np
import time

def mysavez(outfile,*args):
    with open(outfile,'wb') as outf:
        for arg in args:
            np.save(outf,arg)

x = np.random.rand(1000,1000)

# control group
np.savez('foo.npz', *[x]*5)
time.sleep(2) # make sure there's a difference in timestamp
np.savez('bar.npz', *[x]*5)

# new one
mysavez('foo.nopz', *[x]*5)
time.sleep(2) # make sure there's a difference in timestamp
mysavez('bar.nopz', *[x]*5)

The resulting new files have the same hash, and they even have the exact same size as the originals:

$ md5sum foo.npz bar.npz
4d21c47903b4ffab945f619ad5b6f471  foo.npz
f9af863c6178765d6dc32a5fa2f63623  bar.npz
$ md5sum foo.nopz bar.nopz
c8504f0d8cc53956100912efb02573b0  foo.nopz
c8504f0d8cc53956100912efb02573b0  bar.nopz
$ du {foo,bar}.n*pz
39064   foo.nopz
39064   foo.npz
39064   bar.nopz
39064   bar.npz

As long as you're sequentially reading variables from the file you won't notice a functional difference. Of course you'll need a myload to go with it that yields the saved arrays until they're all gone (or be extra fancy and save an initial integer header telling you the number of arrays saved to the file). This approach is admittedly kludgy, but it might cut it depending on your exact use case.

In case you do want to access your saved variables using keys, you could still consider writing an auxiliary function for testing which reads the "production" .npz files, iterates over their ordered keys, saves them sequentially using the above mysavez function, then computes the hash of these "flattened" pickle files. Of course you might not need np.save for this: pickle can do the same for you (although cpickle might not).


问:
Single shot time not working inside pyqt4 QThread
I am trying to use single shot timer inside QThread but it's not working. Following is the code I am using:

```<code>class thread1((QtCore.QThread):
    def __init__(self,parent):
        QtCore.QThread.__init__(self, parent)
        self.Timer1 = None

    def __del__(self):
        self.wait()

    def timerPINNo(self):
        print "Timer completed"

    def run(self):
        tempVal0 = getData()
        if tempVal0 == 0:
            self.Timer1 = QtCore.QTimer()
            self.Timer1.timeout.connect(self.timerPINNo)
            self.Timer1.setSingleShot(True)
            self.Timer1.start(5000)
        else: pass
</code>```

The problem I am facing is that after time out the timerPINNo function never gets called. The single shot is working when using normally but not when I am calling it from QThread. Where I am making mistake ?

答:
The problem is caused because if the run method finishes executing the thread finishes its execution and therefore it is eliminated and consequently the timer also. The solution is to keep the run method running for it, QEventLoop must be used.

```<code>import sys
from PyQt4 import QtCore

class thread1(QtCore.QThread):
    def __init__(self,*args, **kwargs):
        QtCore.QThread.__init__(self, *args, **kwargs)
        self.Timer1 = None

    def __del__(self):
        self.wait()

    def timerPINNo(self):
        print("Timer completed")

    def run(self):
        tempVal0 = getData()
        if tempVal0 == 0:
            self.Timer1 = QtCore.QTimer()
            self.Timer1.timeout.connect(self.timerPINNo)
            self.Timer1.setSingleShot(True)
            self.Timer1.start(5000)
            loop = QtCore.QEventLoop()
            loop.exec_()

if __name__ == "__main__":
   app = QtCore.QCoreApplication(sys.argv)
   th = thread1()
   th.start()
   sys.exit(app.exec_())
</code>```

Body:
I am trying to use single shot timer inside QThread but it's not working. Following is the code I am using:

class thread1((QtCore.QThread):
    def __init__(self,parent):
        QtCore.QThread.__init__(self, parent)
        self.Timer1 = None

    def __del__(self):
        self.wait()

    def timerPINNo(self):
        print "Timer completed"

    def run(self):
        tempVal0 = getData()
        if tempVal0 == 0:
            self.Timer1 = QtCore.QTimer()
            self.Timer1.timeout.connect(self.timerPINNo)
            self.Timer1.setSingleShot(True)
            self.Timer1.start(5000)
        else: pass

The problem I am facing is that after time out the timerPINNo function never gets called. The single shot is working when using normally but not when I am calling it from QThread. Where I am making mistake ?

Body:
The problem is caused because if the run method finishes executing the thread finishes its execution and therefore it is eliminated and consequently the timer also. The solution is to keep the run method running for it, QEventLoop must be used.

import sys
from PyQt4 import QtCore

class thread1(QtCore.QThread):
    def __init__(self,*args, **kwargs):
        QtCore.QThread.__init__(self, *args, **kwargs)
        self.Timer1 = None

    def __del__(self):
        self.wait()

    def timerPINNo(self):
        print("Timer completed")

    def run(self):
        tempVal0 = getData()
        if tempVal0 == 0:
            self.Timer1 = QtCore.QTimer()
            self.Timer1.timeout.connect(self.timerPINNo)
            self.Timer1.setSingleShot(True)
            self.Timer1.start(5000)
            loop = QtCore.QEventLoop()
            loop.exec_()

if __name__ == "__main__":
   app = QtCore.QCoreApplication(sys.argv)
   th = thread1()
   th.start()
   sys.exit(app.exec_())


问:
Adding all the tk.Button objects to a list to config
So I'd like to add all the tk.Button(and entry) objects in an entire program to a list. (so that I can change the colours of every button though iterate and config)

I'm creating a bunch of tkinter frames like this:

```<code>class AppClass(tk.Tk):

    def __init__(self, *args, **kwargs):

        # Initialising Tkinter
        tk.Tk.__init__(self, *args, **kwargs)
        tk.Tk.wm_title(self, 'test-program')
        tk.Tk.geometry(self, '800x480')

        container = tk.Frame(self)
        container.pack(fill='both', expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.background_theme = '2'
        self.background_theme_to_be_written_to_file  = '2'

        self.frames = {}

        for F in (HomePage,
                  SecondName,
                  ThirdName):

            frame = F(container, self)

            self.frames[F] = frame

            frame.grid(row=0, column=0, sticky="nsew")

            frame.configure(background=background_page)

        self.show_frame(HomePage)
</code>```

...

```<code>app = AppClass()

app.mainloop()
app = None
exit()
</code>```

Ideas? I know .winfo_children() can select all the objects in a page - can we select all the objects in the program?

**

at the moment I'm trying to make something like this work - oddly it's only changing one button on the screen (There are 4):

```<code>parent.list_of_objects_in_parent = tk.Button.winfo_children(parent)

print(parent.list_of_objects_in_parent)

for entry in parent.list_of_objects_in_parent:
    entry.config(bg="pink")
</code>```

**quick update:

I kind of have a partial solution:

```<code>self.bind("<<ShowFrame>>", self.on_show_frame)
</code>```

...

```<code>def on_show_frame(self, event):
    self.list_of_objects_in_parent = tk.Button.winfo_children(self)
    print(self.list_of_objects_in_parent)
    for entry in self.list_of_objects_in_parent:
        if type(entry) == type(self.button_to_go_to_home_page):
            entry.config(bg="pink")
            print("working")
</code>```

答:
Yes, this is possible.

You can simply call .winfo_children() on the Tk() window which will return a list of all widgets in the top level of the window which you can iterate over, see below:

```<code>from tkinter import *

root = Tk()

def command():
    for i in root.winfo_children():
        i.configure(bg="pink")

entry = Entry(root)
button = Button(root, text="Ok", command=command)

entry.pack()
button.pack()

root.mainloop()
</code>```

If you have multiple layers of widgets (IE, Frames containing widgets, Toplevel widgets) then you need to add some sort of recursion in order to get ALL of the widgets in your program, we can do this with something like the below:

```<code>from tkinter import *

root = Tk()

def command():
    x = root.winfo_children()
    for i in x:
        if i.winfo_children():
            x.extend(i.winfo_children())
        i.configure(bg="pink")

entry = Entry(root)
button = Button(root, text="Ok", command=command)

frame = Frame(root)
entry2 = Entry(frame)

top = Toplevel(root)
entry3 = Entry(top)

entry.pack()
entry2.pack()
entry3.pack()
button.pack()
frame.pack()

root.mainloop()
</code>```

Body:
So I'd like to add all the tk.Button(and entry) objects in an entire program to a list. (so that I can change the colours of every button though iterate and config)

I'm creating a bunch of tkinter frames like this:

class AppClass(tk.Tk):

    def __init__(self, *args, **kwargs):

        # Initialising Tkinter
        tk.Tk.__init__(self, *args, **kwargs)
        tk.Tk.wm_title(self, 'test-program')
        tk.Tk.geometry(self, '800x480')

        container = tk.Frame(self)
        container.pack(fill='both', expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.background_theme = '2'
        self.background_theme_to_be_written_to_file  = '2'

        self.frames = {}

        for F in (HomePage,
                  SecondName,
                  ThirdName):

            frame = F(container, self)

            self.frames[F] = frame

            frame.grid(row=0, column=0, sticky="nsew")

            frame.configure(background=background_page)

        self.show_frame(HomePage)

...

app = AppClass()

app.mainloop()
app = None
exit()

Ideas? I know .winfo_children() can select all the objects in a page - can we select all the objects in the program?

**

at the moment I'm trying to make something like this work - oddly it's only changing one button on the screen (There are 4):

parent.list_of_objects_in_parent = tk.Button.winfo_children(parent)

print(parent.list_of_objects_in_parent)

for entry in parent.list_of_objects_in_parent:
    entry.config(bg="pink")

**quick update:

I kind of have a partial solution:

self.bind("<<ShowFrame>>", self.on_show_frame)

...

def on_show_frame(self, event):
    self.list_of_objects_in_parent = tk.Button.winfo_children(self)
    print(self.list_of_objects_in_parent)
    for entry in self.list_of_objects_in_parent:
        if type(entry) == type(self.button_to_go_to_home_page):
            entry.config(bg="pink")
            print("working")

Body:
Yes, this is possible.

You can simply call .winfo_children() on the Tk() window which will return a list of all widgets in the top level of the window which you can iterate over, see below:

from tkinter import *

root = Tk()

def command():
    for i in root.winfo_children():
        i.configure(bg="pink")

entry = Entry(root)
button = Button(root, text="Ok", command=command)

entry.pack()
button.pack()

root.mainloop()

If you have multiple layers of widgets (IE, Frames containing widgets, Toplevel widgets) then you need to add some sort of recursion in order to get ALL of the widgets in your program, we can do this with something like the below:

from tkinter import *

root = Tk()

def command():
    x = root.winfo_children()
    for i in x:
        if i.winfo_children():
            x.extend(i.winfo_children())
        i.configure(bg="pink")

entry = Entry(root)
button = Button(root, text="Ok", command=command)

frame = Frame(root)
entry2 = Entry(frame)

top = Toplevel(root)
entry3 = Entry(top)

entry.pack()
entry2.pack()
entry3.pack()
button.pack()
frame.pack()

root.mainloop()


问:
Loading a C Module in Lua
I am trying to load the example lproc program (described on Programming Lua, Chapter 30) into Lua and fouling up somehow. I am following this - http://www.lua.org/pil/26.2.html to get my c module into lua. Following are the steps that I've taken:

I have an lproc.h and lproc.c (containing exactly the functions laid out in Chapter 30 of the book). I am compiling lproc.c as --- gcc -c lproc.c -DLUA-USERCONFIG=\"lproc.h\"

I made a library out of lproc.o, named the same.

And then compiled lua.c as instructed. My header files contain the macro LUA_EXTRALIBS and the method declarations.

Went to the Lua interpreter and it gave the following errors:

```
> require "lproc"
stdin:1: module 'lproc' not found:
    no field package.preload['lproc']
    no file './lproc.lua'
    no file '/opt/local/share/lua/5.1/lproc.lua'
    no file '/opt/local/share/lua/5.1/lproc/init.lua'
    no file '/opt/local/lib/lua/5.1/lproc.lua'
    no file '/opt/local/lib/lua/5.1/lproc/init.lua'
    no file './lproc.so'
    no file '/opt/local/lib/lua/5.1/lproc.so'
    no file '/opt/local/lib/lua/5.1/loadall.so'
stack traceback:
    [C]: in function 'require'
    stdin:1: in main chunk
    [C]: ?
```

It seems that the module did not get registered, what would I need to do from Lua? Time is short and I am doing something horrendously wrong, any direction would be welcome.

Thanks,

Sayan

答:
Here is a complete and fully portable minimal example of building a C library for Lua (works in Lua 5.1-5.3 and LuaJIT, for any platform):

With this example.c:

```<code>#include <lua.h>

int example_hello(lua_State* L) {
   lua_pushliteral(L, "Hello, world!");
   return 1;
}

int luaopen_example(lua_State* L) {
   lua_newtable(L);
   lua_pushcfunction(L, example_hello);
   lua_setfield(L, -2, "hello");
   return 1;
}
</code>```

Put this rockspec file in the same directory, named example-1.0-1.rockspec:

```<code>package = "example"
version = "1.0-1"
source = {
   url = "." -- not online yet!
}
build = {
   type = "builtin",
   modules = {
      example = "example.c"
   }
}
</code>```

Then, run luarocks make. It will build the C code with the correct flags for your platform.

Your module is now ready to use!

```<code>Lua 5.3.3  Copyright (C) 1994-2016 Lua.org, PUC-Rio
> example = require("example")
> print(example.hello())
Hello, world!
>
</code>```

ContentLicense: CC BY-SA 2.5

Title: Loading a C Module in Lua

Body:
I am trying to load the example lproc program (described on Programming Lua, Chapter 30) into Lua and fouling up somehow. I am following this - http://www.lua.org/pil/26.2.html to get my c module into lua. Following are the steps that I've taken:

I have an lproc.h and lproc.c (containing exactly the functions laid out in Chapter 30 of the book). I am compiling lproc.c as --- gcc -c lproc.c -DLUA-USERCONFIG=\"lproc.h\"

I made a library out of lproc.o, named the same.

And then compiled lua.c as instructed. My header files contain the macro LUA_EXTRALIBS and the method declarations.

Went to the Lua interpreter and it gave the following errors:

> require "lproc"
stdin:1: module 'lproc' not found:
    no field package.preload['lproc']
    no file './lproc.lua'
    no file '/opt/local/share/lua/5.1/lproc.lua'
    no file '/opt/local/share/lua/5.1/lproc/init.lua'
    no file '/opt/local/lib/lua/5.1/lproc.lua'
    no file '/opt/local/lib/lua/5.1/lproc/init.lua'
    no file './lproc.so'
    no file '/opt/local/lib/lua/5.1/lproc.so'
    no file '/opt/local/lib/lua/5.1/loadall.so'
stack traceback:
    [C]: in function 'require'
    stdin:1: in main chunk
    [C]: ?

It seems that the module did not get registered, what would I need to do from Lua? Time is short and I am doing something horrendously wrong, any direction would be welcome.

Thanks,

Sayan

Body:
Here is a complete and fully portable minimal example of building a C library for Lua (works in Lua 5.1-5.3 and LuaJIT, for any platform):

With this example.c:

#include <lua.h>

int example_hello(lua_State* L) {
   lua_pushliteral(L, "Hello, world!");
   return 1;
}

int luaopen_example(lua_State* L) {
   lua_newtable(L);
   lua_pushcfunction(L, example_hello);
   lua_setfield(L, -2, "hello");
   return 1;
}

Put this rockspec file in the same directory, named example-1.0-1.rockspec:

package = "example"
version = "1.0-1"
source = {
   url = "." -- not online yet!
}
build = {
   type = "builtin",
   modules = {
      example = "example.c"
   }
}

Then, run luarocks make. It will build the C code with the correct flags for your platform.

Your module is now ready to use!

Lua 5.3.3  Copyright (C) 1994-2016 Lua.org, PUC-Rio
> example = require("example")
> print(example.hello())
Hello, world!
>


问:
Socket.io - Prevent server crash if "client" emit wrong data
Currently im working on a project using node.js and socket.io.

If wonder if there is any way to automatically validate data the client emitted to the server. I don't want to validate the data by using if (!...) return; for each variable I want to use in the ongoing function.

for example I have the following code on server.js

```<code>socket.on('haveData', function(data) {
    db.query('SELECT * FROM user WHERE userid = ? LIMIT 1', [data.userid], function(errData, results, fields) {
        if (!errData && results.length) {
            ...
        }
    });
});
</code>```

but now, if I type socket.emit('haveData'); in the console of my browser, the socket.io server is crashing - sure, there is no data emitted

```<code>TypeError: Cannot read property 'userid' of undefined
</code>```

答:
You can use Joi https://github.com/hapijs/joi.

Joi allows you to  define schema for input data and validate it with Joi.validate method (Example : https://github.com/hapijs/joi#example).

Socket.on('event',function(data,callback){}) accepts a callback function, it can be used to pass the error message back to client.

Example code :

```<code>const Joi = require('joi');

socket.on('data',function(data,callback){

    const schema = Joi.object().keys({
        userid : Joi.string().trim().required()
    })

    Joi.validate(data, schema, function (err, value) {
        if(err){
            //Error will be sent back to the client who emitted the event
            callback(err)
        }else{
            //Do  your stuff
        }
    })
})
</code>```

Body:
Currently im working on a project using node.js and socket.io.

If wonder if there is any way to automatically validate data the client emitted to the server. I don't want to validate the data by using if (!...) return; for each variable I want to use in the ongoing function.

for example I have the following code on server.js

socket.on('haveData', function(data) {
    db.query('SELECT * FROM user WHERE userid = ? LIMIT 1', [data.userid], function(errData, results, fields) {
        if (!errData && results.length) {
            ...
        }
    });
});

but now, if I type socket.emit('haveData'); in the console of my browser, the socket.io server is crashing - sure, there is no data emitted

TypeError: Cannot read property 'userid' of undefined

Body:
You can use Joi https://github.com/hapijs/joi.

Joi allows you to  define schema for input data and validate it with Joi.validate method (Example : https://github.com/hapijs/joi#example).

Socket.on('event',function(data,callback){}) accepts a callback function, it can be used to pass the error message back to client.

Example code :

const Joi = require('joi');

socket.on('data',function(data,callback){

    const schema = Joi.object().keys({
        userid : Joi.string().trim().required()
    })

    Joi.validate(data, schema, function (err, value) {
        if(err){
            //Error will be sent back to the client who emitted the event
            callback(err)
        }else{
            //Do  your stuff
        }
    })
})


问:
Convert the date time stamp to local epoch datatime
Assume this is my date time stamp list:

```<code>[datetime.datetime(2017, 11, 17, 9, 33, 11), datetime.datetime(2017, 11, 17, 9, 33, 36), datetime.datetime(2017, 11, 17, 9, 33, 48)]
</code>```

A lot of examples have been given for converting these values to epoch, but the values are in GMT.
How do we convert it to Epoch Local time?

To put it in simpler words. The general epoch conversion coverts the given date into epoch considering that the datetime given is in GMT. But the given date time is localtime!

答:
You can try arrow lib:</p>

```<code>import arrow
import datetime

x = datetime.datetime(2017, 11, 17, 9, 33, 36)
time = arrow.get(x, 'local').shift(hours=-6)  // here you can change hours to what you want

print time
>>2017-11-17T03:33:36+00:00

time = time.format('YYYY-MM-DD HH:mm:ss')
print time
>>2017-11-17 03:33:36
</code>```

Body:
Assume this is my date time stamp list:

[datetime.datetime(2017, 11, 17, 9, 33, 11), datetime.datetime(2017, 11, 17, 9, 33, 36), datetime.datetime(2017, 11, 17, 9, 33, 48)]

A lot of examples have been given for converting these values to epoch, but the values are in GMT.
How do we convert it to Epoch Local time?

To put it in simpler words. The general epoch conversion coverts the given date into epoch considering that the datetime given is in GMT. But the given date time is localtime!

Body:
You can try arrow lib:

import arrow
import datetime

x = datetime.datetime(2017, 11, 17, 9, 33, 36)
time = arrow.get(x, 'local').shift(hours=-6)  // here you can change hours to what you want

print time
>>2017-11-17T03:33:36+00:00

time = time.format('YYYY-MM-DD HH:mm:ss')
print time
>>2017-11-17 03:33:36


问:
Get specific edge with boost::graph
I'm using boost::graph and I have two vertex_descriptors. What is the quickest way to get the edge between them, without iterating over all the edges?

答:
Ok, I found it out. boost::edge(u,v,g) returns pair<edge_descriptor, bool> where the bool is whether the edge exists. So in my case I know it does, so I use the expression:

```<code>boost::edge(u,v,g).first
</code>```

Title: Get specific edge with boost::graph

Body:
Ok, I found it out. boost::edge(u,v,g) returns pair<edge_descriptor, bool> where the bool is whether the edge exists. So in my case I know it does, so I use the expression:

boost::edge(u,v,g).first


问:
C# Code closes without completing the code
That's the code. What happens is the console prints out

```<code>Enter a number(a) :

2

Enter a number(b) :

Enter a number(c) :

a + b + c =73

Press any key to continue...
</code>```

P.S - This is my solution to an exercise I had. The exercise tells me to enter 3 values from the console using integrals.

```<code>class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Enter a number(a) : ");
        int a = Console.Read();
        Console.WriteLine("Enter a number(b) : ");
        int b = Console.Read();
        Console.WriteLine("Enter a number(c) : ");
        int c = Console.Read();
        Console.WriteLine("a + b + c =" + (a + b + c));
    }
}
</code>```

答: Add Console.ReadLine(); as the last line of the Main function

Body:
That's the code. What happens is the console prints out

Enter a number(a) :

2

Enter a number(b) :

Enter a number(c) :

a + b + c =73

Press any key to continue...

P.S - This is my solution to an exercise I had. The exercise tells me to enter 3 values from the console using integrals.

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Enter a number(a) : ");
        int a = Console.Read();
        Console.WriteLine("Enter a number(b) : ");
        int b = Console.Read();
        Console.WriteLine("Enter a number(c) : ");
        int c = Console.Read();
        Console.WriteLine("a + b + c =" + (a + b + c));
    }
}


问:
Visual Studio hot keys change occasionally, specifically F6 vs Ctrl-Shift-B for building. WHY?
I always press F6 to build my project.  Suddenly some of my Visual Studio instances are wanting me to use Ctrl-Shift-B.  It's not keyboard related - the actual text of the menu option changes from "F6" to "Ctrl-Shift-B".

Any answers as to how to fix, and what causes this?

答:
Tools -> Options -> Environment -> Keyboard

search this command: "ClassViewContextMenus.ClassViewProjectBuild"

Assign F6


问:
TypeError: Object of type 'Entities' is not JSON serializable IBM Cloud natural language understanding
```<code>import json
from watson_developer_cloud import NaturalLanguageUnderstandingV1
import watson_developer_cloud.natural_language_understanding.features.v1 \
as Features

natural_language_understanding = NaturalLanguageUnderstandingV1(
username="username",
password="password",
version="2017-02-27")

response = natural_language_understanding.analyze(
text="IBM is an American multinational technology company headquartered \
in Armonk, New York, United States, with operations in over 170 \
countries.",
features=[
Features.Entities(
  emotion=True,
  sentiment=True,
  limit=2
),
Features.Keywords(
  emotion=True,
  sentiment=True,
  limit=2
)
 ]
 )

print(json.dumps(response, indent=2))
</code>```

I am new to IBM watson API .....i was trying this sample code provided by them by I was getting this error

TypeError: Object of type 'Entities' is not JSON serializable

答:
All depends on what you insert in your text parameter. Do you use the same text?

I used the example from the API reference with the same phrase for this answer... but, JSON knows only how to handle Unicode strings, not byte sequences. Either transform into Unicode (json.dumps(response.decode("utf-8"), indent=2)), or if is one integer array (json.dumps(list(response))). You also can try print(json.dumps(list(response.values()))).

So, this is one step-by-step for using the NLU service with Python.

IBM Cloud (New name for IBM Bluemix)

Create one account (Now, you can create without a credit card and use the LITE plan for Watson and other Services!)

Catalog -> Watson -> Natural Language Understanding service -> Create -> Service Credentials

In your PC, after installed Python, try to run the command in the CMD/Terminal:

```<code>pip install --upgrade watson-developer-cloud
</code>```

Using the same code provided from the API reference:

```<code>import json
from watson_developer_cloud import NaturalLanguageUnderstandingV1
import watson_developer_cloud.natural_language_understanding.features.v1 \
  as Features

natural_language_understanding = NaturalLanguageUnderstandingV1(
  username="username from the NLU -> Service Credentials",
  password="passoword from the NLU -> Service Credentials",
  version="2017-02-27")

response = natural_language_understanding.analyze(
  text="IBM is an American multinational technology company headquartered \
    in Armonk, New York, United States, with operations in over 170 \
    countries.",
  features=[
    Features.Entities(
      emotion=True,
      sentiment=True,
      limit=2
    ),
    Features.Keywords(
      emotion=True,
      sentiment=True,
      limit=2
    )
  ]
)

print(json.dumps(response, indent=2))
</code>```

And the return when I run the command python NLUAnalyze.py in CMD is:

```<code>{
  "usage": {
    "text_units": 1,
    "text_characters": 148,
    "features": 2
  },
  "language": "en",
  "keywords": [
    {
      "text": "American multinational technology",
      "sentiment": {
        "score": 0.0,
        "label": "neutral"
      },
      "relevance": 0.993518,
      "emotion": {
        "sadness": 0.085259,
        "joy": 0.026169,
        "fear": 0.02454,
        "disgust": 0.088711,
        "anger": 0.033078
      }
    },
    {
      "text": "New York",
      "sentiment": {
        "score": 0.0,
        "label": "neutral"
      },
      "relevance": 0.613816,
      "emotion": {
        "sadness": 0.166741,
        "joy": 0.228903,
        "fear": 0.057987,
        "disgust": 0.050965,
        "anger": 0.054653
      }
    }
  ],
  "entities": [
    {
      "type": "Company",
      "text": "IBM",
      "sentiment": {
        "score": 0.0,
        "label": "neutral"
      },
      "relevance": 0.33,
      "emotion": {
        "sadness": 0.085259,
        "joy": 0.026169,
        "fear": 0.02454,
        "disgust": 0.088711,
        "anger": 0.033078
      },
      "disambiguation": {
        "subtype": [
          "SoftwareLicense",
          "OperatingSystemDeveloper",
          "ProcessorManufacturer",
          "SoftwareDeveloper",
          "CompanyFounder",
          "ProgrammingLanguageDesigner",
          "ProgrammingLanguageDeveloper"
        ],
        "name": "IBM",
        "dbpedia_resource": "http://dbpedia.org/resource/IBM"
      },
      "count": 1
    }
  ]
}
</code>```

See the Official API Reference using Python.

See the Official Documentation for using Natural Language Understanding.

ContentLicense: CC BY-SA 4.0

Body:
import json
from watson_developer_cloud import NaturalLanguageUnderstandingV1
import watson_developer_cloud.natural_language_understanding.features.v1 \
as Features

natural_language_understanding = NaturalLanguageUnderstandingV1(
username="username",
password="password",
version="2017-02-27")

response = natural_language_understanding.analyze(
text="IBM is an American multinational technology company headquartered \
in Armonk, New York, United States, with operations in over 170 \
countries.",
features=[
Features.Entities(
  emotion=True,
  sentiment=True,
  limit=2
),
Features.Keywords(
  emotion=True,
  sentiment=True,
  limit=2
)
 ]
 )

print(json.dumps(response, indent=2))

I am new to IBM watson API .....i was trying this sample code provided by them by I was getting this error

TypeError: Object of type 'Entities' is not JSON serializable

Body:
All depends on what you insert in your text parameter. Do you use the same text?

I used the example from the API reference with the same phrase for this answer... but, JSON knows only how to handle Unicode strings, not byte sequences. Either transform into Unicode (json.dumps(response.decode("utf-8"), indent=2)), or if is one integer array (json.dumps(list(response))). You also can try print(json.dumps(list(response.values()))).

So, this is one step-by-step for using the NLU service with Python.

IBM Cloud (New name for IBM Bluemix)

Create one account (Now, you can create without a credit card and use the LITE plan for Watson and other Services!)

Catalog -> Watson -> Natural Language Understanding service -> Create -> Service Credentials

In your PC, after installed Python, try to run the command in the CMD/Terminal:

pip install --upgrade watson-developer-cloud

Using the same code provided from the API reference:

import json
from watson_developer_cloud import NaturalLanguageUnderstandingV1
import watson_developer_cloud.natural_language_understanding.features.v1 \
  as Features

natural_language_understanding = NaturalLanguageUnderstandingV1(
  username="username from the NLU -> Service Credentials",
  password="passoword from the NLU -> Service Credentials",
  version="2017-02-27")

response = natural_language_understanding.analyze(
  text="IBM is an American multinational technology company headquartered \
    in Armonk, New York, United States, with operations in over 170 \
    countries.",
  features=[
    Features.Entities(
      emotion=True,
      sentiment=True,
      limit=2
    ),
    Features.Keywords(
      emotion=True,
      sentiment=True,
      limit=2
    )
  ]
)

print(json.dumps(response, indent=2))

And the return when I run the command python NLUAnalyze.py in CMD is:

{
  "usage": {
    "text_units": 1,
    "text_characters": 148,
    "features": 2
  },
  "language": "en",
  "keywords": [
    {
      "text": "American multinational technology",
      "sentiment": {
        "score": 0.0,
        "label": "neutral"
      },
      "relevance": 0.993518,
      "emotion": {
        "sadness": 0.085259,
        "joy": 0.026169,
        "fear": 0.02454,
        "disgust": 0.088711,
        "anger": 0.033078
      }
    },
    {
      "text": "New York",
      "sentiment": {
        "score": 0.0,
        "label": "neutral"
      },
      "relevance": 0.613816,
      "emotion": {
        "sadness": 0.166741,
        "joy": 0.228903,
        "fear": 0.057987,
        "disgust": 0.050965,
        "anger": 0.054653
      }
    }
  ],
  "entities": [
    {
      "type": "Company",
      "text": "IBM",
      "sentiment": {
        "score": 0.0,
        "label": "neutral"
      },
      "relevance": 0.33,
      "emotion": {
        "sadness": 0.085259,
        "joy": 0.026169,
        "fear": 0.02454,
        "disgust": 0.088711,
        "anger": 0.033078
      },
      "disambiguation": {
        "subtype": [
          "SoftwareLicense",
          "OperatingSystemDeveloper",
          "ProcessorManufacturer",
          "SoftwareDeveloper",
          "CompanyFounder",
          "ProgrammingLanguageDesigner",
          "ProgrammingLanguageDeveloper"
        ],
        "name": "IBM",
        "dbpedia_resource": "http://dbpedia.org/resource/IBM"
      },
      "count": 1
    }
  ]
}

See the Official API Reference using Python.

See the Official Documentation for using Natural Language Understanding.


问:
What's the best way to determine at runtime if a browser is too slow to gracefully handle complex JavaScript/CSS?
I'm toying with the idea of progressively enabling/disabling JavaScript (and CSS) effects on a page - depending on how fast/slow the browser seems to be.

I'm specifically thinking about low-powered mobile devices and old desktop computers -- not just IE6 :-)

Are there any examples of this sort of thing being done?

What would be the best ways to measure this - accounting for things, like temporary slowdowns on busy CPUs?

Notes:

I'm not interested in browser/OS detection.

At the moment, I'm not interested in bandwidth measurements - only browser/cpu performance.

Things that might be interesting to measure:

Base JavaScript

DOM manipulation

DOM/CSS rendering

I'd like to do this in a way that affects the page's render-speed as little as possible.

BTW: In order to not confuse/irritate users with inconsistent behavior - this would, of course, require on-screen notifications to allow users to opt in/out of this whole performance-tuning process.

[Update: there's a related question that I missed: Disable JavaScript function based on user's computer's performance. Thanks Andrioid!]

答:
Not to be a killjoy here, but this is not a feat that is currently possible in any meaningful way in my opinion.

There are several reasons for this, the main ones being:

Whatever measurement you do, if it is to have any meaning, will have to test the maximum potential of the browser/cpu, which you cannot do and maintain any kind of reasonable user experience

Even if you could, it would be a meaningless snapshot since you have no idea what kind of load the cpu is under from other applications than the browser while your test is running, and weather or not that situation will continue while the user is visiting your website.

Even if you could do that, every browser has their own strengths and weaknesses, which means, you'd have to test every dom manipulation function to know how fast the browser would complete it, there is no "general" or "average" that makes sense here in my experience, and even if there was, the speed with which dom manipulation commands execute, is based on the context of what is currently in the dom, which changes when you manipulate it.

The best you can do is to either

Let your users decide what they want, and enable them to easily change that decision if they regret it

or better yet

Choose to give them something that you can be reasonably sure that the greater part of your target audience will be able to enjoy.

Slightly off topic, but following this train of thought: if your users are not techleaders in their social circles (like most users in here are, but most people in the world are not) don't give them too much choice, ie. any choice that is not absolutely nescessary - they don't want it and they  don't understand the technical consequences of their decision before it is too late.


问:
Undo local commit in Git
I know this question has been asked thousands of time and I tried all solutions and none worked.

I committed to my local 2-3 files and now I want to undo the commit. How can I do that: This is also the first ever commit.

```<code>git reset HEAD^
fatal: ambiguous argument 'HEAD^': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'
</code>```

UPDATE:

```<code>git reset --soft HEAD~1
fatal: ambiguous argument 'HEAD~1': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'
</code>```

UPDATE 2:

```<code>git reset --hard HEAD~1
fatal: ambiguous argument 'HEAD~1': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'
</code>```

答:
Since this is first commit best approach is update your index to the state  you what to achieve and then

```<code>git commit --amend
</code>```

https://nathanhoad.net/git-amend-your-last-commit

Title: Undo local commit in Git

Body:
I know this question has been asked thousands of time and I tried all solutions and none worked.

I committed to my local 2-3 files and now I want to undo the commit. How can I do that: This is also the first ever commit.

git reset HEAD^
fatal: ambiguous argument 'HEAD^': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'

UPDATE:

git reset --soft HEAD~1
fatal: ambiguous argument 'HEAD~1': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'

UPDATE 2:

git reset --hard HEAD~1
fatal: ambiguous argument 'HEAD~1': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'

Body:
Since this is first commit best approach is update your index to the state  you what to achieve and then

git commit --amend

https://nathanhoad.net/git-amend-your-last-commit


问:
I would like that the value of an Int variable is equal to the number of items inside an array of different type (Swift)
I would like that the var numberPlaces of type Int get the same value of filteredList

```<code>list = NearbyPlaces.getCategories()

filteredList = list.filter { _ in
    arc4random() % 2 == 0
}
</code>```

but filteredList is of type QCategoryyso how can i do? Because i want that numberPlaces Int value is egual to the number of items inside filteredList.

UPDATE

numberPlaces is in my next viewController

```<code>var numberPlaces = 0
</code>```

and in the previous controller in my prepare function

```<code> if let np = segue.destination as? CourseClass2 {

            np.categories = filteredList
            np.numberPlaces = //here the number of items of filteredList
            np.radius = Int(stepperRadius.value)
        }
</code>```

答:
I'd wager your filteredList is not of type QCategoryy. It might be of type [QCategoryy], an array of QCategoryy objects.

You should be able to just:

```<code>np.numberPlaces = filteredList.count
</code>```

Body:
I would like that the var numberPlaces of type Int get the same value of filteredList

list = NearbyPlaces.getCategories()

filteredList = list.filter { _ in
    arc4random() % 2 == 0
}

but filteredList is of type QCategoryyso how can i do? Because i want that numberPlaces Int value is egual to the number of items inside filteredList.

UPDATE

numberPlaces is in my next viewController

var numberPlaces = 0

and in the previous controller in my prepare function

 if let np = segue.destination as? CourseClass2 {

            np.categories = filteredList
            np.numberPlaces = //here the number of items of filteredList
            np.radius = Int(stepperRadius.value)
        }

Body:
I'd wager your filteredList is not of type QCategoryy. It might be of type [QCategoryy], an array of QCategoryy objects.

You should be able to just:

np.numberPlaces = filteredList.count


问:
Angularjs & PHP Login
I'm new to angularjs, I'm bit confused about Login Process.

Everytime I log in I'm redirected to the specific page. Which is set already in the code.

I just want to check if the user is logged in. If yes then redirect to --Home--
if not logged in redirect to --Login Again--

What should I use for this?

I heard about local storage. SessionStorage, I'm not familiar with them.
Tell me which way I can manage Login?

Here is my controller for Login

```<code>app.controller('AngularLoginController', ['$scope', '$http', function($scope, $http) {
    $scope.loginForm = function() {
            $http.post("login.php", {
            'email' :$scope.inputData.email,
            'password':$scope.inputData.password
            }).success(function(data) {
                console.log(data);
                if ( data == 'correct') {
                window.location.href = 'welcome_dashboard.php';
                }
            else {
                $scope.errorMsg = "Invalid Email and Password";
            }
        })
        }
}]);
</code>```

答:
You can use $cookieStore of angular js

after successfull login you can put login true

```<code>$cookieStore.put('login', true);
</code>```

and check in your dashboard controller if $cookieStore.get('login') undefined than redirect on login page

When you logout you need to remove this cookie $cookieStore.remove('login')

if you user routerprovider than use resolve it's easy to check login or not here one simple example of resolve

```<code>function ($routeProvider) {
    $routeProvider.
        when('/', {
            controller: 'dashboardController',
            templateUrl: 'app/views/dashboard.html',
            resolve:{loggedIn:onlyLoggedIn}
         })
 }

var onlyLoggedIn = function ($location,$q,$cookieStore,$rootScope) {
    var deferred = $q.defer();
    if (typeof ($cookieStore.get("login")) === "undefined") {
        deferred.reject();
        window.location.href = 'login.html';
    }else{
        $rootScope.display = true;
        deferred.resolve();
    }
    return deferred.promise;

};
</code>```

Title: Angularjs & PHP Login

Body:
I'm new to angularjs, I'm bit confused about Login Process.

Everytime I log in I'm redirected to the specific page. Which is set already in the code.

I just want to check if the user is logged in. If yes then redirect to --Home--
if not logged in redirect to --Login Again--

What should I use for this?

I heard about local storage. SessionStorage, I'm not familiar with them.
Tell me which way I can manage Login?

Here is my controller for Login

app.controller('AngularLoginController', ['$scope', '$http', function($scope, $http) {
    $scope.loginForm = function() {
            $http.post("login.php", {
            'email' :$scope.inputData.email,
            'password':$scope.inputData.password
            }).success(function(data) {
                console.log(data);
                if ( data == 'correct') {
                window.location.href = 'welcome_dashboard.php';
                }
            else {
                $scope.errorMsg = "Invalid Email and Password";
            }
        })
        }
}]);

Body:
You can use $cookieStore of angular js

after successfull login you can put login true

$cookieStore.put('login', true);

and check in your dashboard controller if $cookieStore.get('login') undefined than redirect on login page

When you logout you need to remove this cookie $cookieStore.remove('login')

if you user routerprovider than use resolve it's easy to check login or not here one simple example of resolve

function ($routeProvider) {
    $routeProvider.
        when('/', {
            controller: 'dashboardController',
            templateUrl: 'app/views/dashboard.html',
            resolve:{loggedIn:onlyLoggedIn}
         })
 }

var onlyLoggedIn = function ($location,$q,$cookieStore,$rootScope) {
    var deferred = $q.defer();
    if (typeof ($cookieStore.get("login")) === "undefined") {
        deferred.reject();
        window.location.href = 'login.html';
    }else{
        $rootScope.display = true;
        deferred.resolve();
    }
    return deferred.promise;

};


问:
Using Spark RDD over multiple iterations
I am new to Spark and pardon me if this question is too basic.
I have a real time scenario where data is continuously pushed to a queue and an analysis needs to run on this data.
Spark pulls this data from queue Analysis is multi stage and RDD is iterated over and over again with intermediate updates from every stage and  finally we get some mapping which are updated in the RDD itself.
Analysis needs to be repeated every n minutes and it should work on the previous final state of RDD + new data . These jobs are always run sequentially and next job never run till previous job is completed.

I can always post data from a run to an external storage or cache and then populate RDD again in next cycle but this will introduce unnecessary overhead and will result in performance impact.

Please suggest the best approach for this scenario.Is cache or persist RDD is the solution? I am not sure how cache/persist work for Spark. Is it local or available to all nodes. Ideal scenario would be when every node retain its chunk of data and for next iteration we have practically no delay in processing.

答:
It seems you're working with a plain Spark project, getting the information from a queue and updating it. If it is so, a better aproach could be use Spark streaming that automatees this kind of iteration through window operations. Spark streaming also gives you a couple of operations such as updateStateByKey that I think could be useful to you.

In your case, you could define a stream that pulls from your queue, perform some operations in a window and update a state when completed.

Hope that helps you!

Edit

Well, keeping it simple...
There are two main scenarios where you can use Spark. In one hand you have batch processes, that works over RDDs. An example could be "I need to get a daily summary of how many people buy from a store by genre". That is what I mean with "plain Spark", the core Spark API.

In the other hand, the nature of the information, and the way you are going to access this information is continuous. For example, "I want show in real time how many people, by genre, come to my store to show it as a gauge".

Spark Streaming is an extension of the core Spark API that enables scalable, high-throughput, fault-tolerant stream processing of live data streams

The first thing you must know is which one is your scenario to choose an aproach. Do you need real time?

Persist and cache don't work as you think. As you know there is two kinds of functions in Spark, transformation and actions. Those methods are used to performing the same operation more than once. As is checkpointing in your code. You should read this.

You could share information between executions storing the resultant RDD as a file in HDFS (i.e.) and loading it as a data source at the beginning of each iteration.

Hope it helps you.


问:
Responsive HTML email - Gmail adding classes
I am testing a very basic responsive HTML email template and Gmail (Android) is ignoring the media query.

Here's my very basic test markup:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
  <meta name="format-detection" content="telephone=no">
  <meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=no;">
  <meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE" />
  <style type="text/css">@media screen and (max-width:580px) {
    *[class="mob-column"] {float: none!important; width: 100%!important;}
    *[class="hide"] {display:none!important;}
    *[class="100p"] {width:100%!important; height:auto!important;}
  }</style>
  <title>Website</title>
</head>

<body>
  <table class="100p" width="100%" cellpadding="10" cellspacing="0" bgcolor='#ffffff'>
    <tr>
      <td valign="top" align="center">
        <table class="100p" width="650" cellpadding="0" cellspacing="0" bgcolor="#ffffff">
          <tr>
            <td class="mob-column" width="325" align="left" valign="middle">
              <img src="https://www.website.com/img/logo.png" alt="website" width="200" height="26" border="0"/></td>
            <td class="hide" width="325" valign="middle" align="right">
              <span style="font-size:12px;color:#c5c5c5;font-family:Helvetica,Arial,sans-serif;">Having trouble viewing this email? <a style="color:#666666; text-decoration:none;" href="#">click here</a></span>
            </td>
          </tr>
          <tr>
            <td class="mob-column" align="left" valign="middle" colspan="2" height="30" style="padding-left: 15px;">
              <span style="font-size:12px; font-family:Helvetica,Arial,sans-serif;"><a style="color:#c5c5c5; text-decoration:none;" href="tel:111111111">111111111</a><span style="color: #c5c5c5;"> | </span><a style="color:#c5c5c5; text-decoration:none;" href="tel:111111111">111111111</a></span>
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
</body>
</html>
</code>```

So class mob-column should stack the table cells, and hide should hide the table cell. Yet this is being completely ignored in Gmail on Android.

When I inspect the HTML in Gmail on desktop I can see that the classes have been altered like so:

mob-column is changed to m_1371211720454434058mob-column
hide is changed to m_1371211720454434058hide

I've followed a tutorial on Litmus (https://litmus.com/community/learning/24-how-to-code-a-responsive-email-from-scratch) and I am using https://putsmail.com for testing.

Where am I going wrong with this?

答:
I'd recommend changing your mob-column class to something like this

```<code>.mob-column {width: 100% !important; display: block !important}
</code>```

We don't have to use attribute selectors anymore and Gmail and Yahoo both support standard class & id selectors these days.

Body:
I am testing a very basic responsive HTML email template and Gmail (Android) is ignoring the media query.

Here's my very basic test markup:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
  <meta name="format-detection" content="telephone=no">
  <meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=no;">
  <meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE" />

  <title>Website</title>

              Having trouble viewing this email? click here

              111111111 | 111111111

So class mob-column should stack the table cells, and hide should hide the table cell. Yet this is being completely ignored in Gmail on Android.

When I inspect the HTML in Gmail on desktop I can see that the classes have been altered like so:

mob-column is changed to m_1371211720454434058mob-column
hide is changed to m_1371211720454434058hide

I've followed a tutorial on Litmus (https://litmus.com/community/learning/24-how-to-code-a-responsive-email-from-scratch) and I am using https://putsmail.com for testing.

Where am I going wrong with this?

Body:
I'd recommend changing your mob-column class to something like this

.mob-column {width: 100% !important; display: block !important}

We don't have to use attribute selectors anymore and Gmail and Yahoo both support standard class & id selectors these days.


答:
You'd only use localStorage or sessionStorage if you had a token, for example if you were authenticating using OAuth.

In your case you'll probably be using cookies and sessions. So for this scenario you'd want to have someway of checking if you're authenticated (as your session or cookie might have expired).

I'd create a new endpoint e.g. current_user.php that returns true or false (or even the current user details) if you're logged in or not. And then you'd want to call this before any requests that expect the user to be authenticated).

You'll also want to handle any requests that return data that require the user to be authenticated with a fail callback that also redirect the user should you get a 401 back.

Title: Angularjs & PHP Login


问:
How to transfer databases and site contents
I own a website with 20 GB data on it Now I decided to change the Hosting compnay .
I'm Moving to Russian VPS so is there a way to transfer the contents of my website to the Russian VPS without uploading them again .

Is there a service that does this.
I heard that there is a way to do this using shell access (BUT what is shell access and how it works)
thanx in advance guys

答: If you have access to the server itself, you can ftp into your old site from the new server, and download all the data from the new server, without having to download to a personal computer.</p>

OwnerDisplayName: umtoz

OwnerDisplayName: Andrei Krotkov


问:
Equivalent replacement for ListProperty(db.Key) in djangoappengine
I and trying to use djangoappengine, but I am unsure how can I write model to incorporate standard

```<code>ListProperty(db.Key)
</code>```

I know that djangotoolbox provides this field types but I am unable to figure out the exact syntax.

答:
db.ListProperty(db.Key) stores a list of any entity's keys.

models:

```<code>class Profile(db.Model):
data_list=db.ListProperty(db.Key)

class Data(db.Model):
name=db.StringProperty()
</code>```

views:

```<code>prof=Profile()
data=Data.all()

for data in data:
    prof.data_list.append(data)

/// Here data_list stores the keys of Data entity

Data.get(prof.data_list) will get all the Data entities whose key are in the data_list attribute
</code>```

Body:
I and trying to use djangoappengine, but I am unsure how can I write model to incorporate standard

ListProperty(db.Key)

I know that djangotoolbox provides this field types but I am unable to figure out the exact syntax.

Body:
db.ListProperty(db.Key) stores a list of any entity's keys.

models:

class Profile(db.Model):
data_list=db.ListProperty(db.Key)

class Data(db.Model):
name=db.StringProperty()

views:

prof=Profile()
data=Data.all()

for data in data:
    prof.data_list.append(data)

/// Here data_list stores the keys of Data entity

Data.get(prof.data_list) will get all the Data entities whose key are in the data_list attribute


问:
Filter for the List<List<String>>
I am trying to write a method that would filter the duplicate inputs in a list of lists of Strings. The problem is that by duplicates I mean also the lists that have the same elemets buts in a different order. So I would like that if the input list is :

```<code>[["1", "2","3"], ["2","1","3"],["3","1","2"]]
</code>```

it would return only

```<code>[["1","2","3"]]
</code>```

I tried to do something like:

```<code>public List<List<String>> filter (List<List<String>> list){
    List<List<String>> filteredList = new LinkedList<>();
    filteredList.addAll(list);
    for(List<String> i:list){
        for(List<String> j:list){
            if (!i.equals(j)&&i.containsAll(j)){
                filteredList.remove(j);
            }
        }
    }
    return filteredList;
}
</code>```

but it would remove too much cause it would still iterate through the whole original list and would find that element "a" is duplicate of element "b" and vice versa. On the other side when I try to do that on the same list (without a temp) I get ConcurrentModificationException cause I can't modify and iterate over the same collection at the same time. Adding the list to a Set would not solve the issue because they are not exact duplicates (.equals would return false). Is there any possible solution to achieve at?

答: You're trying to implement a Set, a set is already part of the java API, here is the link Set (Java API)</p>

Title: Filter for the List<List<String>>

Body:
I am trying to write a method that would filter the duplicate inputs in a list of lists of Strings. The problem is that by duplicates I mean also the lists that have the same elemets buts in a different order. So I would like that if the input list is :

[["1", "2","3"], ["2","1","3"],["3","1","2"]]

it would return only

[["1","2","3"]]

I tried to do something like:

public List<List<String>> filter (List<List<String>> list){
    List<List<String>> filteredList = new LinkedList<>();
    filteredList.addAll(list);
    for(List<String> i:list){
        for(List<String> j:list){
            if (!i.equals(j)&&i.containsAll(j)){
                filteredList.remove(j);
            }
        }
    }
    return filteredList;
}

but it would remove too much cause it would still iterate through the whole original list and would find that element "a" is duplicate of element "b" and vice versa. On the other side when I try to do that on the same list (without a temp) I get ConcurrentModificationException cause I can't modify and iterate over the same collection at the same time. Adding the list to a Set would not solve the issue because they are not exact duplicates (.equals would return false). Is there any possible solution to achieve at?


问:
How can I make a file "permanent" in a Linux live version?
I am working with a live Linux version. If I create a user and that user creates a file, how can I make that file visible for that user after I have restarted the system? (Normally it would be erased)</p>

答:
You can save the file in the device's hard drive, if you are using a CD/DVD.

In case you are using a flash drive, you can save the file in the root / folder.

Note: Be careful with name given in root folder, try to avoid things like boot or other names found in that folder. They are used to start the live system and boot manager usually recognize them based only in file names


问:
How to show order list in alphabatic order dynamically?
code:

```<code><table width="100%" cellspacing="0" cellpadding="0" border="0" style="line-height: 1.7;">
    <tbody>
        <?php
            $this->db->select('*');
            $this->db->from('cm_options');
            $where = "qid = '$qid'";
            $this->db->where($where);
            $sql = $this->db->get();
            //echo $this->db->last_query();
            $res = $sql->result_array();
            foreach($res as $rows)
            {
                $option = $rows['q_option'];
        ?>
        <tr>
            <ol type="A">
                <td width="5%">
                    <li><a href="javascript:void(0)"><input type="radio" name="radio_btn"></a></li>
                </td>
            </ol>
            <td width="99%"><?php echo $option; ?></td>
        </tr>
        <?php
            }
        ?>
    </tbody>
</table>
</code>```

In this code I have created objective type question form where option are display perfectly. Now, I want to show all option in alphabet order like A,B,C,D but now, It display dots instead of A,B,C,D. So, How can I display my option in alphabetically order ?Please help me.

Thank You

答:
This is accomplished in CSS with the list-style-type of upper-alpha on the list element.

https://developer.mozilla.org/en-US/docs/Web/CSS/list-style-type

You should also be aware that the only valid direct descendent of an
 (or
 for that matter) is
, so what you have going on with your table mingled in there is not good markup.

For example:

ol {
  list-style-type: upper-alpha;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ol>
  <li>Answer 1</li>
  <li>Answer 2</li>
  <li>Answer 3</li>
</ol></code>```

You also need to make sure your opening and closing ordered list tags are outside your foreach loop or you'll end up with a new list each iteration of the loop and all items will have 'A' because technically you'll have a bunch of lists with a single item each.

```<code><ol>
<?php foreach($res as $rows) {   ?>
    <li>...</li>
<?php } ?>
</ol>
</code>```

Body:
code:

        <?php
            $this->db->select('*');
            $this->db->from('cm_options');
            $where = "qid = '$qid'";
            $this->db->where($where);
            $sql = $this->db->get();
            //echo $this->db->last_query();
            $res = $sql->result_array();
            foreach($res as $rows)
            {
                $option = $rows['q_option'];
        ?>

<input type="radio" name="radio_btn">

            <?php echo $option; ?>

        <?php
            }
        ?>

In this code I have created objective type question form where option are display perfectly. Now, I want to show all option in alphabet order like A,B,C,D but now, It display dots instead of A,B,C,D. So, How can I display my option in alphabetically order ?Please help me.

Thank You

Body:
This is accomplished in CSS with the list-style-type of upper-alpha on the list element.

https://developer.mozilla.org/en-US/docs/Web/CSS/list-style-type

You should also be aware that the only valid direct descendent of an <ol> (or <ul> for that matter) is <li>, so what you have going on with your table mingled in there is not good markup.

For example:

ol {
  list-style-type: upper-alpha;
}

<ol>
  <li>Answer 1</li>
  <li>Answer 2</li>
  <li>Answer 3</li>
</ol>

You also need to make sure your opening and closing ordered list tags are outside your foreach loop or you'll end up with a new list each iteration of the loop and all items will have 'A' because technically you'll have a bunch of lists with a single item each.

<ol>
<?php foreach($res as $rows) {   ?>
    <li>...</li>
<?php } ?>
</ol>


问:
What algorithm is used in Set to avoid duplicates?
May I know What algorithm is used in Set to avoid duplicates ?<br>
I want to know just What is the name of the algorithm used to avoid the duplicates and If possible the same algorithm implementation as well. </p>

答:
The HashSet implementation have a HashMap as the data.

You can see that add(E e) will call map.put(e, DUMMY) where the HashMap implementation relies on the obejct hashCode() and equals() methods for its key uniquiness so any object with returns trues for equals will replace the previous one.

The implementation of this Set can be seen here:
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/HashSet.java

Body:
May I know What algorithm is used in Set to avoid duplicates ?

I want to know just What is the name of the algorithm used to avoid the duplicates and If possible the same algorithm implementation as well.