问:
need a help for the error Unknown record property / related component "permissions" on "sfGuardUser"
i am develping a project using symfony1.4.16 and Doctrine and for authentication i am using sfDoctrineGuardPlugin. In my localhost it was working fine. when i moved my project on a shared host i am getting this error(Unknown record property / related component "permissions" on "sfGuardUser") while login. when i search for this error in Google many people are recommending for delete all SFGuard Forms from lib/form/doctrine/base and reinstalling the plugin.How do i reinstall it on my sharedhost? what are the procedure should i take for uninstalling it on my sharedhost? whether i need to reinstall it in my localhost and upload it to my server or for should i use the command symfony plugin:uninstall sfDoctrineGuardPlugin or simply delete the files in lib/form/doctrine/base and upload it again to my server.The other modules which is not related to sfDoctrineGuardPlugin is working fine.Any one please help me...

More Information

when i login i am getting the error Unknown record property / related component "permissions" on "sfGuardUser" and when i refresh the page error is gone and i am redirecting to home page. In home page i have links for

add user,group,permission

edit user,group,permission

list user,group,permission
when i am trying to access add or edit portion i am getting error like this. List and delete portion is working fine

here i am attaching the screen shots of error and error log.

1.error page
2.error log

**

BaseSfGuardUser.class

**

```<code><?php
// Connection Component Binding
Doctrine_Manager::getInstance()->bindComponent('SfGuardUser', 'doctrine');

/**
 * BaseSfGuardUser
 *
 * This class has been auto-generated by the Doctrine ORM Framework
 *
 * @property integer $id
 * @property string $first_name
 * @property string $last_name
 * @property string $email_address
 * @property string $username
 * @property string $algorithm
 * @property string $salt
 * @property string $password
 * @property integer $is_active
 * @property integer $is_super_admin
 * @property timestamp $last_login
 * @property timestamp $created_at
 * @property timestamp $updated_at
 * @property Doctrine_Collection $SfGuardForgotPassword
 * @property Doctrine_Collection $SfGuardRememberKey
 * @property Doctrine_Collection $SfGuardUserGroup
 * @property Doctrine_Collection $SfGuardUserPermission
 *
 * @method integer             getId()                    Returns the current record's "id" value
 * @method string              getFirstName()             Returns the current record's "first_name" value
 * @method string              getLastName()              Returns the current record's "last_name" value
 * @method string              getEmailAddress()          Returns the current record's "email_address" value
 * @method string              getUsername()              Returns the current record's "username" value
 * @method string              getAlgorithm()             Returns the current record's "algorithm" value
 * @method string              getSalt()                  Returns the current record's "salt" value
 * @method string              getPassword()              Returns the current record's "password" value
 * @method integer             getIsActive()              Returns the current record's "is_active" value
 * @method integer             getIsSuperAdmin()          Returns the current record's "is_super_admin" value
 * @method timestamp           getLastLogin()             Returns the current record's "last_login" value
 * @method timestamp           getCreatedAt()             Returns the current record's "created_at" value
 * @method timestamp           getUpdatedAt()             Returns the current record's "updated_at" value
 * @method Doctrine_Collection getSfGuardForgotPassword() Returns the current record's "SfGuardForgotPassword" collection
 * @method Doctrine_Collection getSfGuardRememberKey()    Returns the current record's "SfGuardRememberKey" collection
 * @method Doctrine_Collection getSfGuardUserGroup()      Returns the current record's "SfGuardUserGroup" collection
 * @method Doctrine_Collection getSfGuardUserPermission() Returns the current record's "SfGuardUserPermission" collection
 * @method SfGuardUser         setId()                    Sets the current record's "id" value
 * @method SfGuardUser         setFirstName()             Sets the current record's "first_name" value
 * @method SfGuardUser         setLastName()              Sets the current record's "last_name" value
 * @method SfGuardUser         setEmailAddress()          Sets the current record's "email_address" value
 * @method SfGuardUser         setUsername()              Sets the current record's "username" value
 * @method SfGuardUser         setAlgorithm()             Sets the current record's "algorithm" value
 * @method SfGuardUser         setSalt()                  Sets the current record's "salt" value
 * @method SfGuardUser         setPassword()              Sets the current record's "password" value
 * @method SfGuardUser         setIsActive()              Sets the current record's "is_active" value
 * @method SfGuardUser         setIsSuperAdmin()          Sets the current record's "is_super_admin" value
 * @method SfGuardUser         setLastLogin()             Sets the current record's "last_login" value
 * @method SfGuardUser         setCreatedAt()             Sets the current record's "created_at" value
 * @method SfGuardUser         setUpdatedAt()             Sets the current record's "updated_at" value
 * @method SfGuardUser         setSfGuardForgotPassword() Sets the current record's "SfGuardForgotPassword" collection
 * @method SfGuardUser         setSfGuardRememberKey()    Sets the current record's "SfGuardRememberKey" collection
 * @method SfGuardUser         setSfGuardUserGroup()      Sets the current record's "SfGuardUserGroup" collection
 * @method SfGuardUser         setSfGuardUserPermission() Sets the current record's "SfGuardUserPermission" collection
 *
 * @package    ticketsystem
 * @subpackage model
 * @author     Your name here
 * @version    SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $
 */
abstract class BaseSfGuardUser extends sfDoctrineRecord
{
    public function setTableDefinition()
    {
        $this->setTableName('sf_guard_user');
        $this->hasColumn('id', 'integer', 8, array(
             'type' => 'integer',
             'fixed' => 0,
             'unsigned' => false,
             'primary' => true,
             'autoincrement' => true,
             'length' => 8,
             ));
        $this->hasColumn('first_name', 'string', 255, array(
             'type' => 'string',
             'fixed' => 0,
             'unsigned' => false,
             'primary' => false,
             'notnull' => false,
             'autoincrement' => false,
             'length' => 255,
             ));
        $this->hasColumn('last_name', 'string', 255, array(
             'type' => 'string',
             'fixed' => 0,
             'unsigned' => false,
             'primary' => false,
             'notnull' => false,
             'autoincrement' => false,
             'length' => 255,
             ));
        $this->hasColumn('email_address', 'string', 255, array(
             'type' => 'string',
             'fixed' => 0,
             'unsigned' => false,
             'primary' => false,
             'notnull' => true,
             'autoincrement' => false,
             'length' => 255,
             ));
        $this->hasColumn('username', 'string', 128, array(
             'type' => 'string',
             'fixed' => 0,
             'unsigned' => false,
             'primary' => false,
             'notnull' => true,
             'autoincrement' => false,
             'length' => 128,
             ));
        $this->hasColumn('algorithm', 'string', 128, array(
             'type' => 'string',
             'fixed' => 0,
             'unsigned' => false,
             'primary' => false,
             'default' => 'sha1',
             'notnull' => true,
             'autoincrement' => false,
             'length' => 128,
             ));
        $this->hasColumn('salt', 'string', 128, array(
             'type' => 'string',
             'fixed' => 0,
             'unsigned' => false,
             'primary' => false,
             'notnull' => false,
             'autoincrement' => false,
             'length' => 128,
             ));
        $this->hasColumn('password', 'string', 128, array(
             'type' => 'string',
             'fixed' => 0,
             'unsigned' => false,
             'primary' => false,
             'notnull' => false,
             'autoincrement' => false,
             'length' => 128,
             ));
        $this->hasColumn('is_active', 'integer', 1, array(
             'type' => 'integer',
             'fixed' => 0,
             'unsigned' => false,
             'primary' => false,
             'default' => '1',
             'notnull' => false,
             'autoincrement' => false,
             'length' => 1,
             ));
        $this->hasColumn('is_super_admin', 'integer', 1, array(
             'type' => 'integer',
             'fixed' => 0,
             'unsigned' => false,
             'primary' => false,
             'default' => '0',
             'notnull' => false,
             'autoincrement' => false,
             'length' => 1,
             ));
        $this->hasColumn('last_login', 'timestamp', 25, array(
             'type' => 'timestamp',
             'fixed' => 0,
             'unsigned' => false,
             'primary' => false,
             'notnull' => false,
             'autoincrement' => false,
             'length' => 25,
             ));
        $this->hasColumn('created_at', 'timestamp', 25, array(
             'type' => 'timestamp',
             'fixed' => 0,
             'unsigned' => false,
             'primary' => false,
             'notnull' => true,
             'autoincrement' => false,
             'length' => 25,
             ));
        $this->hasColumn('updated_at', 'timestamp', 25, array(
             'type' => 'timestamp',
             'fixed' => 0,
             'unsigned' => false,
             'primary' => false,
             'notnull' => true,
             'autoincrement' => false,
             'length' => 25,
             ));
    }

    public function setUp()
    {
        parent::setUp();
        $this->hasMany('SfGuardForgotPassword', array(
             'local' => 'id',
             'foreign' => 'user_id',
             'onDelete' => 'CASCADE'));

        $this->hasMany('SfGuardRememberKey', array(
             'local' => 'id',
             'foreign' => 'user_id',
             'onDelete' => 'CASCADE'));

        $this->hasMany('SfGuardUserGroup', array(
             'local' => 'id',
             'foreign' => 'user_id',
             'onDelete' => 'CASCADE'));

        $this->hasMany('SfGuardUserPermission', array(
             'local' => 'id',
             'foreign' => 'user_id',
             'onDelete' => 'CASCADE'));
    }
}
</code>```

**

BaseSfGuardUserForm.class

**

```<code><?php

/**
 * SfGuardUser form base class.
 *
 * @method SfGuardUser getObject() Returns the current form's model object
 *
 * @package    ticketsystem
 * @subpackage form
 * @author     Your name here
 * @version    SVN: $Id: sfDoctrineFormGeneratedTemplate.php 29553 2010-05-20 14:33:00Z Kris.Wallsmith $
 */
abstract class BaseSfGuardUserForm extends BaseFormDoctrine
{
  public function setup()
  {
    $this->setWidgets(array(
      'id'               => new sfWidgetFormInputHidden(),
      'first_name'       => new sfWidgetFormInputText(),
      'last_name'        => new sfWidgetFormInputText(),
      'email_address'    => new sfWidgetFormInputText(),
      'username'         => new sfWidgetFormInputText(),
      'algorithm'        => new sfWidgetFormInputText(),
      'salt'             => new sfWidgetFormInputText(),
      'password'         => new sfWidgetFormInputText(),
      'is_active'        => new sfWidgetFormInputCheckbox(),
      'is_super_admin'   => new sfWidgetFormInputCheckbox(),
      'last_login'       => new sfWidgetFormDateTime(),
      'created_at'       => new sfWidgetFormDateTime(),
      'updated_at'       => new sfWidgetFormDateTime(),
      'groups_list'      => new sfWidgetFormDoctrineChoice(array('multiple' => true, 'model' => 'sfGuardGroup')),
      'permissions_list' => new sfWidgetFormDoctrineChoice(array('multiple' => true, 'model' => 'sfGuardPermission')),
    ));

    $this->setValidators(array(
      'id'               => new sfValidatorChoice(array('choices' => array($this->getObject()->get('id')), 'empty_value' => $this->getObject()->get('id'), 'required' => false)),
      'first_name'       => new sfValidatorString(array('max_length' => 255, 'required' => false)),
      'last_name'        => new sfValidatorString(array('max_length' => 255, 'required' => false)),
      'email_address'    => new sfValidatorString(array('max_length' => 255)),
      'username'         => new sfValidatorString(array('max_length' => 128)),
      'algorithm'        => new sfValidatorString(array('max_length' => 128, 'required' => false)),
      'salt'             => new sfValidatorString(array('max_length' => 128, 'required' => false)),
      'password'         => new sfValidatorString(array('max_length' => 128, 'required' => false)),
      'is_active'        => new sfValidatorBoolean(array('required' => false)),
      'is_super_admin'   => new sfValidatorBoolean(array('required' => false)),
      'last_login'       => new sfValidatorDateTime(array('required' => false)),
      'created_at'       => new sfValidatorDateTime(),
      'updated_at'       => new sfValidatorDateTime(),
      'groups_list'      => new sfValidatorDoctrineChoice(array('multiple' => true, 'model' => 'sfGuardGroup', 'required' => false)),
      'permissions_list' => new sfValidatorDoctrineChoice(array('multiple' => true, 'model' => 'sfGuardPermission', 'required' => false)),
    ));

    $this->validatorSchema->setPostValidator(
      new sfValidatorAnd(array(
        new sfValidatorDoctrineUnique(array('model' => 'SfGuardUser', 'column' => array('email_address'))),
        new sfValidatorDoctrineUnique(array('model' => 'SfGuardUser', 'column' => array('username'))),
      ))
    );

    $this->widgetSchema->setNameFormat('sf_guard_user[%s]');

    $this->errorSchema = new sfValidatorErrorSchema($this->validatorSchema);

    $this->setupInheritance();

    parent::setup();
  }

  public function getModelName()
  {
    return 'SfGuardUser';
  }

  public function updateDefaultsFromObject()
  {
    parent::updateDefaultsFromObject();

    if (isset($this->widgetSchema['groups_list']))
    {
      $this->setDefault('groups_list', $this->object->Groups->getPrimaryKeys());
    }

    if (isset($this->widgetSchema['permissions_list']))
    {
      $this->setDefault('permissions_list', $this->object->Permissions->getPrimaryKeys());
    }

  }

  protected function doSave($con = null)
  {
    $this->saveGroupsList($con);
    $this->savePermissionsList($con);

    parent::doSave($con);
  }

  public function saveGroupsList($con = null)
  {
    if (!$this->isValid())
    {
      throw $this->getErrorSchema();
    }

    if (!isset($this->widgetSchema['groups_list']))
    {
      // somebody has unset this widget
      return;
    }

    if (null === $con)
    {
      $con = $this->getConnection();
    }

    $existing = $this->object->Groups->getPrimaryKeys();
    $values = $this->getValue('groups_list');
    if (!is_array($values))
    {
      $values = array();
    }

    $unlink = array_diff($existing, $values);
    if (count($unlink))
    {
      $this->object->unlink('Groups', array_values($unlink));
    }

    $link = array_diff($values, $existing);
    if (count($link))
    {
      $this->object->link('Groups', array_values($link));
    }
  }

  public function savePermissionsList($con = null)
  {
    if (!$this->isValid())
    {
      throw $this->getErrorSchema();
    }

    if (!isset($this->widgetSchema['permissions_list']))
    {
      // somebody has unset this widget
      return;
    }

    if (null === $con)
    {
      $con = $this->getConnection();
    }

    $existing = $this->object->Permissions->getPrimaryKeys();
    $values = $this->getValue('permissions_list');
    if (!is_array($values))
    {
      $values = array();
    }

    $unlink = array_diff($existing, $values);
    if (count($unlink))
    {
      $this->object->unlink('Permissions', array_values($unlink));
    }

    $link = array_diff($values, $existing);
    if (count($link))
    {
      $this->object->link('Permissions', array_values($link));
    }
  }

}
</code>```

here i am attaching my database schema too

**

schema.yml

**

```<code>SfGuardForgotPassword:
  connection: doctrine
  tableName: sf_guard_forgot_password
  columns:
    id:
      type: integer(8)
      fixed: false
      unsigned: false
      primary: true
      autoincrement: true
    user_id:
      type: integer(8)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
    unique_key:
      type: string(255)
      fixed: false
      unsigned: false
      primary: false
      notnull: false
      autoincrement: false
    expires_at:
      type: timestamp(25)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
    created_at:
      type: timestamp(25)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
    updated_at:
      type: timestamp(25)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
  relations:
    SfGuardUser:
      local: user_id
      foreign: id
      type: one
SfGuardGroup:
  connection: doctrine
  tableName: sf_guard_group
  columns:
    id:
      type: integer(8)
      fixed: false
      unsigned: false
      primary: true
      autoincrement: true
    name:
      type: string(255)
      fixed: false
      unsigned: false
      primary: false
      notnull: false
      autoincrement: false
    description:
      type: string()
      fixed: false
      unsigned: false
      primary: false
      notnull: false
      autoincrement: false
    created_at:
      type: timestamp(25)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
    updated_at:
      type: timestamp(25)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
  relations:
    SfGuardGroupPermission:
      local: id
      foreign: group_id
      type: many
    SfGuardUserGroup:
      local: id
      foreign: group_id
      type: many
SfGuardGroupPermission:
  connection: doctrine
  tableName: sf_guard_group_permission
  columns:
    group_id:
      type: integer(8)
      fixed: false
      unsigned: false
      primary: true
      autoincrement: false
    permission_id:
      type: integer(8)
      fixed: false
      unsigned: false
      primary: true
      autoincrement: false
    created_at:
      type: timestamp(25)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
    updated_at:
      type: timestamp(25)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
  relations:
    SfGuardGroup:
      local: group_id
      foreign: id
      type: one
    SfGuardPermission:
      local: permission_id
      foreign: id
      type: one
SfGuardPermission:
  connection: doctrine
  tableName: sf_guard_permission
  columns:
    id:
      type: integer(8)
      fixed: false
      unsigned: false
      primary: true
      autoincrement: true
    name:
      type: string(255)
      fixed: false
      unsigned: false
      primary: false
      notnull: false
      autoincrement: false
    description:
      type: string()
      fixed: false
      unsigned: false
      primary: false
      notnull: false
      autoincrement: false
    created_at:
      type: timestamp(25)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
    updated_at:
      type: timestamp(25)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
  relations:
    SfGuardGroupPermission:
      local: id
      foreign: permission_id
      type: many
    SfGuardUserPermission:
      local: id
      foreign: permission_id
      type: many
SfGuardRememberKey:
  connection: doctrine
  tableName: sf_guard_remember_key
  columns:
    id:
      type: integer(8)
      fixed: false
      unsigned: false
      primary: true
      autoincrement: true
    user_id:
      type: integer(8)
      fixed: false
      unsigned: false
      primary: false
      notnull: false
      autoincrement: false
    remember_key:
      type: string(32)
      fixed: false
      unsigned: false
      primary: false
      notnull: false
      autoincrement: false
    ip_address:
      type: string(50)
      fixed: false
      unsigned: false
      primary: false
      notnull: false
      autoincrement: false
    created_at:
      type: timestamp(25)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
    updated_at:
      type: timestamp(25)
      fixed: false
      unsigned: false
      primary: false

      notnull: true
      autoincrement: false
  relations:
    SfGuardUser:
      local: user_id
      foreign: id
      type: one
SfGuardUser:
  connection: doctrine
  tableName: sf_guard_user
  columns:
    id:
      type: integer(8)
      fixed: false
      unsigned: false
      primary: true
      autoincrement: true
    first_name:
      type: string(255)
      fixed: false
      unsigned: false
      primary: false
      notnull: false
      autoincrement: false
    last_name:
      type: string(255)
      fixed: false
      unsigned: false
      primary: false
      notnull: false
      autoincrement: false
    email_address:
      type: string(255)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
    username:
      type: string(128)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
    algorithm:
      type: string(128)
      fixed: false
      unsigned: false
      primary: false
      default: sha1
      notnull: true
      autoincrement: false
    salt:
      type: string(128)
      fixed: false
      unsigned: false
      primary: false
      notnull: false
      autoincrement: false
    password:
      type: string(128)
      fixed: false
      unsigned: false
      primary: false
      notnull: false
      autoincrement: false
    is_active:
      type: integer(1)
      fixed: false
      unsigned: false
      primary: false
      default: '1'
      notnull: false
      autoincrement: false
    is_super_admin:
      type: integer(1)
      fixed: false
      unsigned: false
      primary: false
      default: '0'
      notnull: false
      autoincrement: false
    last_login:
      type: timestamp(25)
      fixed: false
      unsigned: false
      primary: false
      notnull: false
      autoincrement: false
    created_at:
      type: timestamp(25)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
    updated_at:
      type: timestamp(25)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
  relations:
    SfGuardForgotPassword:
      local: id
      foreign: user_id
      type: many
    SfGuardRememberKey:
      local: id
      foreign: user_id
      type: many
    SfGuardUserGroup:
      local: id
      foreign: user_id
      type: many
    SfGuardUserPermission:
      local: id
      foreign: user_id
      type: many
SfGuardUserGroup:
  connection: doctrine
  tableName: sf_guard_user_group
  columns:
    user_id:
      type: integer(8)
      fixed: false
      unsigned: false
      primary: true
      autoincrement: false
    group_id:
      type: integer(8)
      fixed: false
      unsigned: false
      primary: true
      autoincrement: false
    created_at:
      type: timestamp(25)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
    updated_at:
      type: timestamp(25)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
  relations:
    SfGuardGroup:
      local: group_id
      foreign: id
      type: one
    SfGuardUser:
      local: user_id
      foreign: id
      type: one
SfGuardUserPermission:
  connection: doctrine
  tableName: sf_guard_user_permission
  columns:
    user_id:
      type: integer(8)
      fixed: false
      unsigned: false
      primary: true
      autoincrement: false
    permission_id:
      type: integer(8)
      fixed: false
      unsigned: false
      primary: true
      autoincrement: false
    created_at:
      type: timestamp(25)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
    updated_at:
      type: timestamp(25)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
  relations:
    SfGuardPermission:
      local: permission_id
      foreign: id
      type: one
    SfGuardUser:
      local: user_id
      foreign: id
      type: one
</code>```

Thank you

答: During I server migration, I was seeing this same error for a different reason.  The new server was running PHP 7.0, but I got it working by downgrading to PHP 5.6 (following the instructions here).</p>

Body:
i am develping a project using symfony1.4.16 and Doctrine and for authentication i am using sfDoctrineGuardPlugin. In my localhost it was working fine. when i moved my project on a shared host i am getting this error(Unknown record property / related component "permissions" on "sfGuardUser") while login. when i search for this error in Google many people are recommending for delete all SFGuard Forms from lib/form/doctrine/base and reinstalling the plugin.How do i reinstall it on my sharedhost? what are the procedure should i take for uninstalling it on my sharedhost? whether i need to reinstall it in my localhost and upload it to my server or for should i use the command symfony plugin:uninstall sfDoctrineGuardPlugin or simply delete the files in lib/form/doctrine/base and upload it again to my server.The other modules which is not related to sfDoctrineGuardPlugin is working fine.Any one please help me...

More Information

when i login i am getting the error Unknown record property / related component "permissions" on "sfGuardUser" and when i refresh the page error is gone and i am redirecting to home page. In home page i have links for

add user,group,permission

edit user,group,permission

list user,group,permission
when i am trying to access add or edit portion i am getting error like this. List and delete portion is working fine

here i am attaching the screen shots of error and error log.

1.error page
2.error log

**

BaseSfGuardUser.class

**

<?php
// Connection Component Binding
Doctrine_Manager::getInstance()->bindComponent('SfGuardUser', 'doctrine');

/**
 * BaseSfGuardUser
 *
 * This class has been auto-generated by the Doctrine ORM Framework
 *
 * @property integer $id
 * @property string $first_name
 * @property string $last_name
 * @property string $email_address
 * @property string $username
 * @property string $algorithm
 * @property string $salt
 * @property string $password
 * @property integer $is_active
 * @property integer $is_super_admin
 * @property timestamp $last_login
 * @property timestamp $created_at
 * @property timestamp $updated_at
 * @property Doctrine_Collection $SfGuardForgotPassword
 * @property Doctrine_Collection $SfGuardRememberKey
 * @property Doctrine_Collection $SfGuardUserGroup
 * @property Doctrine_Collection $SfGuardUserPermission
 *
 * @method integer             getId()                    Returns the current record's "id" value
 * @method string              getFirstName()             Returns the current record's "first_name" value
 * @method string              getLastName()              Returns the current record's "last_name" value
 * @method string              getEmailAddress()          Returns the current record's "email_address" value
 * @method string              getUsername()              Returns the current record's "username" value
 * @method string              getAlgorithm()             Returns the current record's "algorithm" value
 * @method string              getSalt()                  Returns the current record's "salt" value
 * @method string              getPassword()              Returns the current record's "password" value
 * @method integer             getIsActive()              Returns the current record's "is_active" value
 * @method integer             getIsSuperAdmin()          Returns the current record's "is_super_admin" value
 * @method timestamp           getLastLogin()             Returns the current record's "last_login" value
 * @method timestamp           getCreatedAt()             Returns the current record's "created_at" value
 * @method timestamp           getUpdatedAt()             Returns the current record's "updated_at" value
 * @method Doctrine_Collection getSfGuardForgotPassword() Returns the current record's "SfGuardForgotPassword" collection
 * @method Doctrine_Collection getSfGuardRememberKey()    Returns the current record's "SfGuardRememberKey" collection
 * @method Doctrine_Collection getSfGuardUserGroup()      Returns the current record's "SfGuardUserGroup" collection
 * @method Doctrine_Collection getSfGuardUserPermission() Returns the current record's "SfGuardUserPermission" collection
 * @method SfGuardUser         setId()                    Sets the current record's "id" value
 * @method SfGuardUser         setFirstName()             Sets the current record's "first_name" value
 * @method SfGuardUser         setLastName()              Sets the current record's "last_name" value
 * @method SfGuardUser         setEmailAddress()          Sets the current record's "email_address" value
 * @method SfGuardUser         setUsername()              Sets the current record's "username" value
 * @method SfGuardUser         setAlgorithm()             Sets the current record's "algorithm" value
 * @method SfGuardUser         setSalt()                  Sets the current record's "salt" value
 * @method SfGuardUser         setPassword()              Sets the current record's "password" value
 * @method SfGuardUser         setIsActive()              Sets the current record's "is_active" value
 * @method SfGuardUser         setIsSuperAdmin()          Sets the current record's "is_super_admin" value
 * @method SfGuardUser         setLastLogin()             Sets the current record's "last_login" value
 * @method SfGuardUser         setCreatedAt()             Sets the current record's "created_at" value
 * @method SfGuardUser         setUpdatedAt()             Sets the current record's "updated_at" value
 * @method SfGuardUser         setSfGuardForgotPassword() Sets the current record's "SfGuardForgotPassword" collection
 * @method SfGuardUser         setSfGuardRememberKey()    Sets the current record's "SfGuardRememberKey" collection
 * @method SfGuardUser         setSfGuardUserGroup()      Sets the current record's "SfGuardUserGroup" collection
 * @method SfGuardUser         setSfGuardUserPermission() Sets the current record's "SfGuardUserPermission" collection
 *
 * @package    ticketsystem
 * @subpackage model
 * @author     Your name here
 * @version    SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $
 */
abstract class BaseSfGuardUser extends sfDoctrineRecord
{
    public function setTableDefinition()
    {
        $this->setTableName('sf_guard_user');
        $this->hasColumn('id', 'integer', 8, array(
             'type' => 'integer',
             'fixed' => 0,
             'unsigned' => false,
             'primary' => true,
             'autoincrement' => true,
             'length' => 8,
             ));
        $this->hasColumn('first_name', 'string', 255, array(
             'type' => 'string',
             'fixed' => 0,
             'unsigned' => false,
             'primary' => false,
             'notnull' => false,
             'autoincrement' => false,
             'length' => 255,
             ));
        $this->hasColumn('last_name', 'string', 255, array(
             'type' => 'string',
             'fixed' => 0,
             'unsigned' => false,
             'primary' => false,
             'notnull' => false,
             'autoincrement' => false,
             'length' => 255,
             ));
        $this->hasColumn('email_address', 'string', 255, array(
             'type' => 'string',
             'fixed' => 0,
             'unsigned' => false,
             'primary' => false,
             'notnull' => true,
             'autoincrement' => false,
             'length' => 255,
             ));
        $this->hasColumn('username', 'string', 128, array(
             'type' => 'string',
             'fixed' => 0,
             'unsigned' => false,
             'primary' => false,
             'notnull' => true,
             'autoincrement' => false,
             'length' => 128,
             ));
        $this->hasColumn('algorithm', 'string', 128, array(
             'type' => 'string',
             'fixed' => 0,
             'unsigned' => false,
             'primary' => false,
             'default' => 'sha1',
             'notnull' => true,
             'autoincrement' => false,
             'length' => 128,
             ));
        $this->hasColumn('salt', 'string', 128, array(
             'type' => 'string',
             'fixed' => 0,
             'unsigned' => false,
             'primary' => false,
             'notnull' => false,
             'autoincrement' => false,
             'length' => 128,
             ));
        $this->hasColumn('password', 'string', 128, array(
             'type' => 'string',
             'fixed' => 0,
             'unsigned' => false,
             'primary' => false,
             'notnull' => false,
             'autoincrement' => false,
             'length' => 128,
             ));
        $this->hasColumn('is_active', 'integer', 1, array(
             'type' => 'integer',
             'fixed' => 0,
             'unsigned' => false,
             'primary' => false,
             'default' => '1',
             'notnull' => false,
             'autoincrement' => false,
             'length' => 1,
             ));
        $this->hasColumn('is_super_admin', 'integer', 1, array(
             'type' => 'integer',
             'fixed' => 0,
             'unsigned' => false,
             'primary' => false,
             'default' => '0',
             'notnull' => false,
             'autoincrement' => false,
             'length' => 1,
             ));
        $this->hasColumn('last_login', 'timestamp', 25, array(
             'type' => 'timestamp',
             'fixed' => 0,
             'unsigned' => false,
             'primary' => false,
             'notnull' => false,
             'autoincrement' => false,
             'length' => 25,
             ));
        $this->hasColumn('created_at', 'timestamp', 25, array(
             'type' => 'timestamp',
             'fixed' => 0,
             'unsigned' => false,
             'primary' => false,
             'notnull' => true,
             'autoincrement' => false,
             'length' => 25,
             ));
        $this->hasColumn('updated_at', 'timestamp', 25, array(
             'type' => 'timestamp',
             'fixed' => 0,
             'unsigned' => false,
             'primary' => false,
             'notnull' => true,
             'autoincrement' => false,
             'length' => 25,
             ));
    }

    public function setUp()
    {
        parent::setUp();
        $this->hasMany('SfGuardForgotPassword', array(
             'local' => 'id',
             'foreign' => 'user_id',
             'onDelete' => 'CASCADE'));

        $this->hasMany('SfGuardRememberKey', array(
             'local' => 'id',
             'foreign' => 'user_id',
             'onDelete' => 'CASCADE'));

        $this->hasMany('SfGuardUserGroup', array(
             'local' => 'id',
             'foreign' => 'user_id',
             'onDelete' => 'CASCADE'));

        $this->hasMany('SfGuardUserPermission', array(
             'local' => 'id',
             'foreign' => 'user_id',
             'onDelete' => 'CASCADE'));
    }
}

**

BaseSfGuardUserForm.class

**

<?php

/**
 * SfGuardUser form base class.
 *
 * @method SfGuardUser getObject() Returns the current form's model object
 *
 * @package    ticketsystem
 * @subpackage form
 * @author     Your name here
 * @version    SVN: $Id: sfDoctrineFormGeneratedTemplate.php 29553 2010-05-20 14:33:00Z Kris.Wallsmith $
 */
abstract class BaseSfGuardUserForm extends BaseFormDoctrine
{
  public function setup()
  {
    $this->setWidgets(array(
      'id'               => new sfWidgetFormInputHidden(),
      'first_name'       => new sfWidgetFormInputText(),
      'last_name'        => new sfWidgetFormInputText(),
      'email_address'    => new sfWidgetFormInputText(),
      'username'         => new sfWidgetFormInputText(),
      'algorithm'        => new sfWidgetFormInputText(),
      'salt'             => new sfWidgetFormInputText(),
      'password'         => new sfWidgetFormInputText(),
      'is_active'        => new sfWidgetFormInputCheckbox(),
      'is_super_admin'   => new sfWidgetFormInputCheckbox(),
      'last_login'       => new sfWidgetFormDateTime(),
      'created_at'       => new sfWidgetFormDateTime(),
      'updated_at'       => new sfWidgetFormDateTime(),
      'groups_list'      => new sfWidgetFormDoctrineChoice(array('multiple' => true, 'model' => 'sfGuardGroup')),
      'permissions_list' => new sfWidgetFormDoctrineChoice(array('multiple' => true, 'model' => 'sfGuardPermission')),
    ));

    $this->setValidators(array(
      'id'               => new sfValidatorChoice(array('choices' => array($this->getObject()->get('id')), 'empty_value' => $this->getObject()->get('id'), 'required' => false)),
      'first_name'       => new sfValidatorString(array('max_length' => 255, 'required' => false)),
      'last_name'        => new sfValidatorString(array('max_length' => 255, 'required' => false)),
      'email_address'    => new sfValidatorString(array('max_length' => 255)),
      'username'         => new sfValidatorString(array('max_length' => 128)),
      'algorithm'        => new sfValidatorString(array('max_length' => 128, 'required' => false)),
      'salt'             => new sfValidatorString(array('max_length' => 128, 'required' => false)),
      'password'         => new sfValidatorString(array('max_length' => 128, 'required' => false)),
      'is_active'        => new sfValidatorBoolean(array('required' => false)),
      'is_super_admin'   => new sfValidatorBoolean(array('required' => false)),
      'last_login'       => new sfValidatorDateTime(array('required' => false)),
      'created_at'       => new sfValidatorDateTime(),
      'updated_at'       => new sfValidatorDateTime(),
      'groups_list'      => new sfValidatorDoctrineChoice(array('multiple' => true, 'model' => 'sfGuardGroup', 'required' => false)),
      'permissions_list' => new sfValidatorDoctrineChoice(array('multiple' => true, 'model' => 'sfGuardPermission', 'required' => false)),
    ));

    $this->validatorSchema->setPostValidator(
      new sfValidatorAnd(array(
        new sfValidatorDoctrineUnique(array('model' => 'SfGuardUser', 'column' => array('email_address'))),
        new sfValidatorDoctrineUnique(array('model' => 'SfGuardUser', 'column' => array('username'))),
      ))
    );

    $this->widgetSchema->setNameFormat('sf_guard_user[%s]');

    $this->errorSchema = new sfValidatorErrorSchema($this->validatorSchema);

    $this->setupInheritance();

    parent::setup();
  }

  public function getModelName()
  {
    return 'SfGuardUser';
  }

  public function updateDefaultsFromObject()
  {
    parent::updateDefaultsFromObject();

    if (isset($this->widgetSchema['groups_list']))
    {
      $this->setDefault('groups_list', $this->object->Groups->getPrimaryKeys());
    }

    if (isset($this->widgetSchema['permissions_list']))
    {
      $this->setDefault('permissions_list', $this->object->Permissions->getPrimaryKeys());
    }

  }

  protected function doSave($con = null)
  {
    $this->saveGroupsList($con);
    $this->savePermissionsList($con);

    parent::doSave($con);
  }

  public function saveGroupsList($con = null)
  {
    if (!$this->isValid())
    {
      throw $this->getErrorSchema();
    }

    if (!isset($this->widgetSchema['groups_list']))
    {
      // somebody has unset this widget
      return;
    }

    if (null === $con)
    {
      $con = $this->getConnection();
    }

    $existing = $this->object->Groups->getPrimaryKeys();
    $values = $this->getValue('groups_list');
    if (!is_array($values))
    {
      $values = array();
    }

    $unlink = array_diff($existing, $values);
    if (count($unlink))
    {
      $this->object->unlink('Groups', array_values($unlink));
    }

    $link = array_diff($values, $existing);
    if (count($link))
    {
      $this->object->link('Groups', array_values($link));
    }
  }

  public function savePermissionsList($con = null)
  {
    if (!$this->isValid())
    {
      throw $this->getErrorSchema();
    }

    if (!isset($this->widgetSchema['permissions_list']))
    {
      // somebody has unset this widget
      return;
    }

    if (null === $con)
    {
      $con = $this->getConnection();
    }

    $existing = $this->object->Permissions->getPrimaryKeys();
    $values = $this->getValue('permissions_list');
    if (!is_array($values))
    {
      $values = array();
    }

    $unlink = array_diff($existing, $values);
    if (count($unlink))
    {
      $this->object->unlink('Permissions', array_values($unlink));
    }

    $link = array_diff($values, $existing);
    if (count($link))
    {
      $this->object->link('Permissions', array_values($link));
    }
  }

}

here i am attaching my database schema too

**

schema.yml

**

SfGuardForgotPassword:
  connection: doctrine
  tableName: sf_guard_forgot_password
  columns:
    id:
      type: integer(8)
      fixed: false
      unsigned: false
      primary: true
      autoincrement: true
    user_id:
      type: integer(8)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
    unique_key:
      type: string(255)
      fixed: false
      unsigned: false
      primary: false
      notnull: false
      autoincrement: false
    expires_at:
      type: timestamp(25)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
    created_at:
      type: timestamp(25)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
    updated_at:
      type: timestamp(25)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
  relations:
    SfGuardUser:
      local: user_id
      foreign: id
      type: one
SfGuardGroup:
  connection: doctrine
  tableName: sf_guard_group
  columns:
    id:
      type: integer(8)
      fixed: false
      unsigned: false
      primary: true
      autoincrement: true
    name:
      type: string(255)
      fixed: false
      unsigned: false
      primary: false
      notnull: false
      autoincrement: false
    description:
      type: string()
      fixed: false
      unsigned: false
      primary: false
      notnull: false
      autoincrement: false
    created_at:
      type: timestamp(25)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
    updated_at:
      type: timestamp(25)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
  relations:
    SfGuardGroupPermission:
      local: id
      foreign: group_id
      type: many
    SfGuardUserGroup:
      local: id
      foreign: group_id
      type: many
SfGuardGroupPermission:
  connection: doctrine
  tableName: sf_guard_group_permission
  columns:
    group_id:
      type: integer(8)
      fixed: false
      unsigned: false
      primary: true
      autoincrement: false
    permission_id:
      type: integer(8)
      fixed: false
      unsigned: false
      primary: true
      autoincrement: false
    created_at:
      type: timestamp(25)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
    updated_at:
      type: timestamp(25)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
  relations:
    SfGuardGroup:
      local: group_id
      foreign: id
      type: one
    SfGuardPermission:
      local: permission_id
      foreign: id
      type: one
SfGuardPermission:
  connection: doctrine
  tableName: sf_guard_permission
  columns:
    id:
      type: integer(8)
      fixed: false
      unsigned: false
      primary: true
      autoincrement: true
    name:
      type: string(255)
      fixed: false
      unsigned: false
      primary: false
      notnull: false
      autoincrement: false
    description:
      type: string()
      fixed: false
      unsigned: false
      primary: false
      notnull: false
      autoincrement: false
    created_at:
      type: timestamp(25)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
    updated_at:
      type: timestamp(25)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
  relations:
    SfGuardGroupPermission:
      local: id
      foreign: permission_id
      type: many
    SfGuardUserPermission:
      local: id
      foreign: permission_id
      type: many
SfGuardRememberKey:
  connection: doctrine
  tableName: sf_guard_remember_key
  columns:
    id:
      type: integer(8)
      fixed: false
      unsigned: false
      primary: true
      autoincrement: true
    user_id:
      type: integer(8)
      fixed: false
      unsigned: false
      primary: false
      notnull: false
      autoincrement: false
    remember_key:
      type: string(32)
      fixed: false
      unsigned: false
      primary: false
      notnull: false
      autoincrement: false
    ip_address:
      type: string(50)
      fixed: false
      unsigned: false
      primary: false
      notnull: false
      autoincrement: false
    created_at:
      type: timestamp(25)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
    updated_at:
      type: timestamp(25)
      fixed: false
      unsigned: false
      primary: false

      notnull: true
      autoincrement: false
  relations:
    SfGuardUser:
      local: user_id
      foreign: id
      type: one
SfGuardUser:
  connection: doctrine
  tableName: sf_guard_user
  columns:
    id:
      type: integer(8)
      fixed: false
      unsigned: false
      primary: true
      autoincrement: true
    first_name:
      type: string(255)
      fixed: false
      unsigned: false
      primary: false
      notnull: false
      autoincrement: false
    last_name:
      type: string(255)
      fixed: false
      unsigned: false
      primary: false
      notnull: false
      autoincrement: false
    email_address:
      type: string(255)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
    username:
      type: string(128)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
    algorithm:
      type: string(128)
      fixed: false
      unsigned: false
      primary: false
      default: sha1
      notnull: true
      autoincrement: false
    salt:
      type: string(128)
      fixed: false
      unsigned: false
      primary: false
      notnull: false
      autoincrement: false
    password:
      type: string(128)
      fixed: false
      unsigned: false
      primary: false
      notnull: false
      autoincrement: false
    is_active:
      type: integer(1)
      fixed: false
      unsigned: false
      primary: false
      default: '1'
      notnull: false
      autoincrement: false
    is_super_admin:
      type: integer(1)
      fixed: false
      unsigned: false
      primary: false
      default: '0'
      notnull: false
      autoincrement: false
    last_login:
      type: timestamp(25)
      fixed: false
      unsigned: false
      primary: false
      notnull: false
      autoincrement: false
    created_at:
      type: timestamp(25)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
    updated_at:
      type: timestamp(25)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
  relations:
    SfGuardForgotPassword:
      local: id
      foreign: user_id
      type: many
    SfGuardRememberKey:
      local: id
      foreign: user_id
      type: many
    SfGuardUserGroup:
      local: id
      foreign: user_id
      type: many
    SfGuardUserPermission:
      local: id
      foreign: user_id
      type: many
SfGuardUserGroup:
  connection: doctrine
  tableName: sf_guard_user_group
  columns:
    user_id:
      type: integer(8)
      fixed: false
      unsigned: false
      primary: true
      autoincrement: false
    group_id:
      type: integer(8)
      fixed: false
      unsigned: false
      primary: true
      autoincrement: false
    created_at:
      type: timestamp(25)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
    updated_at:
      type: timestamp(25)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
  relations:
    SfGuardGroup:
      local: group_id
      foreign: id
      type: one
    SfGuardUser:
      local: user_id
      foreign: id
      type: one
SfGuardUserPermission:
  connection: doctrine
  tableName: sf_guard_user_permission
  columns:
    user_id:
      type: integer(8)
      fixed: false
      unsigned: false
      primary: true
      autoincrement: false
    permission_id:
      type: integer(8)
      fixed: false
      unsigned: false
      primary: true
      autoincrement: false
    created_at:
      type: timestamp(25)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
    updated_at:
      type: timestamp(25)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
  relations:
    SfGuardPermission:
      local: permission_id
      foreign: id
      type: one
    SfGuardUser:
      local: user_id
      foreign: id
      type: one

Thank you


来源: stackexchange

问:
Centered DIV with extra content on one side
I have an inner div centered horizontally within a container div, and I need to add another div within that container, to the right of the centered div? How can I do so without disturbing the position of the centered div (i.e. it should still be centered in the container, not between the left edge of the container and the left edge of the other div?

```<code><div id="container">
    <div id="inner"></div>
    <div id="right"></div>
</div>

div#container {
    width: 960px;
}
div#inner {
    width: 400px;
    margin: 0 auto;
}
div#right {
    width: 100px;
    float: right;
    /* what else? */
}
</code>```

Ideally, I would even want to specify the position of div#right as a distance from the right edge of div#inner, rather than using float:right.

(The only solution I've thought of so far is to add another div on the left with the same width as div#right and set visible:none. Is there a better way?)

答:
I would try absolute positioning within the parent
:

```<code>div#container
{
  width: 960px;
  position: relative;
}

div#inner
{
  width: 400px;
  margin: 0px auto;
}

div#right
{
  position: absolute;
  width: 100px;
  right: 0px;
  top: 0px;
}
</code>```

No guarantees on whether this will work out-of-the-box, but I would try something like this.

ContentLicense: CC BY-SA 2.5

Body:
I have an inner div centered horizontally within a container div, and I need to add another div within that container, to the right of the centered div? How can I do so without disturbing the position of the centered div (i.e. it should still be centered in the container, not between the left edge of the container and the left edge of the other div?

div#container {
    width: 960px;
}
div#inner {
    width: 400px;
    margin: 0 auto;
}
div#right {
    width: 100px;
    float: right;
    /* what else? */
}

Ideally, I would even want to specify the position of div#right as a distance from the right edge of div#inner, rather than using float:right.

(The only solution I've thought of so far is to add another div on the left with the same width as div#right and set visible:none. Is there a better way?)

Body:
I would try absolute positioning within the parent <div>:

div#container
{
  width: 960px;
  position: relative;
}

div#inner
{
  width: 400px;
  margin: 0px auto;
}

div#right
{
  position: absolute;
  width: 100px;
  right: 0px;
  top: 0px;
}

No guarantees on whether this will work out-of-the-box, but I would try something like this.


问:
Python Distribution Fitting with Sum of Square Error (SSE)
I am trying to find an optimal distribution curve fit to my data consisting of

```<code>y-axis = [0, 0, 0, 0, 0.24, 0.53, 0.49, 0.64, 0.54, 0.78, 0.59, 0.44,
          0.34, 0.88, 0.2, 0.49, 0.39, 0.39, 0.29, 0.2, 0.05, 0.05,
          0.25, 0.05, 0.1, 0.15, 0.1, 0.1, 0.1, 0, 0, 0, 0, 0]
</code>```

y-axis are probabilities of an event occurring in x-axis time bins:

```<code>x-axis = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0,
          12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0, 21.0,
          22.0, 23.0, 24.0, 25.0, 26.0, 27.0, 28.0, 29.0, 30.0, 31.0,
          32.0, 33.0, 34.0]
</code>```

I am doing this in python following example provided on Fitting empirical distribution to theoretical ones with Scipy (Python)?

Specifically I am attempting to recreate the part called 'Distribution Fitting with Sum of Square Error (SSE)', where you run through the different distributions to find the right fit to the data.

How can I modify that example in order to make this work on my data inputs? answered

Update version based on Bill's response, but now trying to plot the fitted curve against the data and seeing something off:

```<code>%matplotlib inline
import matplotlib.pyplot as plt
import scipy
import scipy.stats
import numpy as np
from scipy.stats import gamma, lognorm, loglaplace
from scipy.optimize import curve_fit

x_axis = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 23.0, 24.0, 25.0, 26.0, 27.0, 28.0, 29.0, 30.0, 31.0, 32.0, 33.0, 34.0]
y_axis = [0, 0, 0, 0, 0.24, 0.53, 0.49, 0.64, 0.54, 0.78, 0.59, 0.44, 0.34, 0.88, 0.2, 0.49, 0.39, 0.39, 0.29, 0.2, 0.05, 0.05, 0.25, 0.05, 0.1, 0.15, 0.1, 0.1, 0.1, 0, 0, 0, 0, 0]

matplotlib.rcParams['figure.figsize'] = (16.0, 12.0)
matplotlib.style.use('ggplot')

def f(x, a, loc, scale):
    return gamma.pdf(x, a, loc, scale)

result, pcov = curve_fit(f, x_axis, y_axis)

# get curve shape, location, scale
shape = result[:-2]
loc = result[-2]
scale = result[-1]

# construct the curve
x = np.linspace(0, 36, 100)
y = f(x, *result)

plt.bar(x_axis, y_axis, width, alpha=0.75)
plt.plot(x, y, c='g')
</code>```

答:
Your situation is not the same as that in the one treated in the question you cited. You have both the ordinates and the abscissae of the data points, rather than the usual i.i.d. sample. I would suggest that you use scipy curve_fit. Here's a sample.

```<code>x_axis = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 23.0, 24.0, 25.0, 26.0, 27.0, 28.0, 29.0, 30.0, 31.0, 32.0, 33.0, 34.0]
y_axis = [0, 0, 0, 0, 0.24, 0.53, 0.49, 0.64, 0.54, 0.78, 0.59, 0.44, 0.34, 0.88, 0.2, 0.49, 0.39, 0.39, 0.29, 0.2, 0.05, 0.05, 0.25, 0.05, 0.1, 0.15, 0.1, 0.1, 0.1, 0, 0, 0, 0, 0]

## y_axis values must be normalised
sum_ys = sum(y_axis)
y_axis = [_/sum_ys for _ in y_axis]
print (sum(y_axis))

from scipy.stats import gamma, norm
from scipy.optimize import curve_fit

def gamma_f(x, a, loc, scale):
    return gamma.pdf(x, a, loc, scale)

def norm_f(x, loc, scale):
    return norm.pdf(x, loc, scale)

fitting = norm_f

result = curve_fit(fitting, x_axis, y_axis)
print (result)

import matplotlib.pyplot as plt

plt.plot(x_axis, y_axis, 'ro')
plt.plot(x_axis, [fitting(_, *result[0]) for _ in x_axis], 'b-')
plt.axis([0,35,0,.5])
plt.show()
</code>```

This version shows how to do one plot, for the normal fit to the data. (The gamma provides a poor fit.) Only two parameters are needed for the normal. In general you would need only the first part of the output results, the estimates of the parameters, shape, location and scale.

```<code>(array([  2.3352639 ,  -3.08105104,  10.15024823]), array([[   5954.86532869,  -27818.92220973,  -19675.22421994],
       [ -27818.92220973,  133161.76500251,   90741.43608615],
       [ -19675.22421994,   90741.43608615,   66054.79087992]]))
</code>```

Notice that the pdf of the gamma distribution is also available in scipy, as are the others that you need, I think, saving you the work of coding them.

The most important thing I omitted from the first code was the need to normalise the y-values, that is, to make them sum to one, since they should approximate histogram heights.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to find an optimal distribution curve fit to my data consisting of

y-axis = [0, 0, 0, 0, 0.24, 0.53, 0.49, 0.64, 0.54, 0.78, 0.59, 0.44,
          0.34, 0.88, 0.2, 0.49, 0.39, 0.39, 0.29, 0.2, 0.05, 0.05,
          0.25, 0.05, 0.1, 0.15, 0.1, 0.1, 0.1, 0, 0, 0, 0, 0]

y-axis are probabilities of an event occurring in x-axis time bins:

x-axis = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0,
          12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0, 21.0,
          22.0, 23.0, 24.0, 25.0, 26.0, 27.0, 28.0, 29.0, 30.0, 31.0,
          32.0, 33.0, 34.0]

I am doing this in python following example provided on Fitting empirical distribution to theoretical ones with Scipy (Python)?

Specifically I am attempting to recreate the part called 'Distribution Fitting with Sum of Square Error (SSE)', where you run through the different distributions to find the right fit to the data.

How can I modify that example in order to make this work on my data inputs? answered

Update version based on Bill's response, but now trying to plot the fitted curve against the data and seeing something off:

%matplotlib inline
import matplotlib.pyplot as plt
import scipy
import scipy.stats
import numpy as np
from scipy.stats import gamma, lognorm, loglaplace
from scipy.optimize import curve_fit

x_axis = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 23.0, 24.0, 25.0, 26.0, 27.0, 28.0, 29.0, 30.0, 31.0, 32.0, 33.0, 34.0]
y_axis = [0, 0, 0, 0, 0.24, 0.53, 0.49, 0.64, 0.54, 0.78, 0.59, 0.44, 0.34, 0.88, 0.2, 0.49, 0.39, 0.39, 0.29, 0.2, 0.05, 0.05, 0.25, 0.05, 0.1, 0.15, 0.1, 0.1, 0.1, 0, 0, 0, 0, 0]

matplotlib.rcParams['figure.figsize'] = (16.0, 12.0)
matplotlib.style.use('ggplot')

def f(x, a, loc, scale):
    return gamma.pdf(x, a, loc, scale)

result, pcov = curve_fit(f, x_axis, y_axis)

# get curve shape, location, scale
shape = result[:-2]
loc = result[-2]
scale = result[-1]

# construct the curve
x = np.linspace(0, 36, 100)
y = f(x, *result)

plt.bar(x_axis, y_axis, width, alpha=0.75)
plt.plot(x, y, c='g')

Body:
Your situation is not the same as that in the one treated in the question you cited. You have both the ordinates and the abscissae of the data points, rather than the usual i.i.d. sample. I would suggest that you use scipy curve_fit. Here's a sample.

x_axis = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 23.0, 24.0, 25.0, 26.0, 27.0, 28.0, 29.0, 30.0, 31.0, 32.0, 33.0, 34.0]
y_axis = [0, 0, 0, 0, 0.24, 0.53, 0.49, 0.64, 0.54, 0.78, 0.59, 0.44, 0.34, 0.88, 0.2, 0.49, 0.39, 0.39, 0.29, 0.2, 0.05, 0.05, 0.25, 0.05, 0.1, 0.15, 0.1, 0.1, 0.1, 0, 0, 0, 0, 0]

## y_axis values must be normalised
sum_ys = sum(y_axis)
y_axis = [_/sum_ys for _ in y_axis]
print (sum(y_axis))

from scipy.stats import gamma, norm
from scipy.optimize import curve_fit

def gamma_f(x, a, loc, scale):
    return gamma.pdf(x, a, loc, scale)

def norm_f(x, loc, scale):
    return norm.pdf(x, loc, scale)

fitting = norm_f

result = curve_fit(fitting, x_axis, y_axis)
print (result)

import matplotlib.pyplot as plt

plt.plot(x_axis, y_axis, 'ro')
plt.plot(x_axis, [fitting(_, *result[0]) for _ in x_axis], 'b-')
plt.axis([0,35,0,.5])
plt.show()

This version shows how to do one plot, for the normal fit to the data. (The gamma provides a poor fit.) Only two parameters are needed for the normal. In general you would need only the first part of the output results, the estimates of the parameters, shape, location and scale.

(array([  2.3352639 ,  -3.08105104,  10.15024823]), array([[   5954.86532869,  -27818.92220973,  -19675.22421994],
       [ -27818.92220973,  133161.76500251,   90741.43608615],
       [ -19675.22421994,   90741.43608615,   66054.79087992]]))

Notice that the pdf of the gamma distribution is also available in scipy, as are the others that you need, I think, saving you the work of coding them.

The most important thing I omitted from the first code was the need to normalise the y-values, that is, to make them sum to one, since they should approximate histogram heights.


问:
Why don't Info level messages get logged when minimum level is Debug?
I have the following code in my C# application using Nlog. The messages with 'Debug' get logged, but 'Info' do not. I had assumed that since minLevel is set to 'Debug' in app.config, the 'Info' messages will also get logged, since Debug has higher priority over 'Info'. But they do not get logged. Where am i wrong ?

Thanks.

```<code>if (logger.IsDebugEnabled) logger.Debug(logMessage) else if (logger.IsInfoEnabled)log.Info(logMessage);
</code>```

This is the app.config setting

```<code><nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

<targets>
  <target name="file" xsi:type="File" fileName="E:/Logoutputs/Remissol-Nlog.txt" />
</targets>

<rules>
  <logger name="*" minlevel="Debug" writeTo="file" />
</rules>
</code>```

答:
This isn't really a different answer than @Nobby, because he is right about how to the levels.  I will say that you don't have to do the IfXXXXEnabled check before logging.

This is what you currently have in your C# code in your question for your logging call site:

```<code>if (logger.IsDebugEnabled) logger.Debug(logMessage) else if (logger.IsInfoEnabled)log.Info(logMessage);
</code>```

@Nobby suggests, this could be made cleaner by doing this:

```<code>if (logger.IsDebugEnabled) logger.Debug(logMessage);
if (logger.IsInfoEnabled) logger.Info(logMessage);
</code>```

I don't think that is really true.  With your original code, ONLY the Debug message OR the Info message will be logged.  If you remove the nesting, then, depending on the logging level that is enabled, you could get BOTH messages logged.

I think you should be logging this way:

```<code>logger.Debug(logMessage);
logger.Info(logMessage);
</code>```

The logging methods (logger.Debug, logger.Info, etc) already do an IsXXXEnabled check and won't log if that logging level is not enabled.  You can save a log of typing (and confusion) by just making the logging call directly rather than protecting it with the if check.

There are times when you want to use the IsXXXEnabled check.  Such as if you have some work to do to calculate the value(s) to be logged and you only want do that calculation if you are logging:

```<code>if (logger.IsDebugEnabled)
{
  int value1 = DoSomeExpensiveCalculation();
  int value2 = DoSomeOtherExpensiveCalculation();
  logger.DebugFormat("v1 = {0}, v2 = {1}", value1, value2);
}
</code>```

This way you are not paying the price of the calculations unless you are actually going to log them.

Finally, in NLog 2.0 you have access to lambda syntax that would allow you to defer potentially expensive operations unless the message is actually logged:

```<code>logger.Debug(() => string.Format("v1 = {0}, v2 = {1}", DoSomeExpensiveCalculation(), DoSomeOtherExpensiveCalculation()));

logger.Debug(() => "message" + i + ", " + j + "," + k);
</code>```

In both cases, the expression that is being passed to NLog will not be evaluated unless the DEBUG level is enabled.

Body:
I have the following code in my C# application using Nlog. The messages with 'Debug' get logged, but 'Info' do not. I had assumed that since minLevel is set to 'Debug' in app.config, the 'Info' messages will also get logged, since Debug has higher priority over 'Info'. But they do not get logged. Where am i wrong ?

Thanks.

if (logger.IsDebugEnabled) logger.Debug(logMessage) else if (logger.IsInfoEnabled)log.Info(logMessage);

This is the app.config setting

<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

<targets>
  <target name="file" xsi:type="File" fileName="E:/Logoutputs/Remissol-Nlog.txt" />
</targets>

<rules>
  <logger name="*" minlevel="Debug" writeTo="file" />
</rules>

Body:
This isn't really a different answer than @Nobby, because he is right about how to the levels.  I will say that you don't have to do the IfXXXXEnabled check before logging.

This is what you currently have in your C# code in your question for your logging call site:

if (logger.IsDebugEnabled) logger.Debug(logMessage) else if (logger.IsInfoEnabled)log.Info(logMessage);

@Nobby suggests, this could be made cleaner by doing this:

if (logger.IsDebugEnabled) logger.Debug(logMessage);
if (logger.IsInfoEnabled) logger.Info(logMessage);

I don't think that is really true.  With your original code, ONLY the Debug message OR the Info message will be logged.  If you remove the nesting, then, depending on the logging level that is enabled, you could get BOTH messages logged.

I think you should be logging this way:

logger.Debug(logMessage);
logger.Info(logMessage);

The logging methods (logger.Debug, logger.Info, etc) already do an IsXXXEnabled check and won't log if that logging level is not enabled.  You can save a log of typing (and confusion) by just making the logging call directly rather than protecting it with the if check.

There are times when you want to use the IsXXXEnabled check.  Such as if you have some work to do to calculate the value(s) to be logged and you only want do that calculation if you are logging:

if (logger.IsDebugEnabled)
{
  int value1 = DoSomeExpensiveCalculation();
  int value2 = DoSomeOtherExpensiveCalculation();
  logger.DebugFormat("v1 = {0}, v2 = {1}", value1, value2);
}

This way you are not paying the price of the calculations unless you are actually going to log them.

Finally, in NLog 2.0 you have access to lambda syntax that would allow you to defer potentially expensive operations unless the message is actually logged:

logger.Debug(() => string.Format("v1 = {0}, v2 = {1}", DoSomeExpensiveCalculation(), DoSomeOtherExpensiveCalculation()));

logger.Debug(() => "message" + i + ", " + j + "," + k);

In both cases, the expression that is being passed to NLog will not be evaluated unless the DEBUG level is enabled.


问:
Form Google Maps URL that searches for a specific places near specific coordinates
I have the longitude and latitude and the name of the place I want to look for. How do I edit the Google Maps URL so that I obtain all the places (name of the places) near a set of coordinates?

I know I could do this using Google Map API, but just for a link seems a lot of trouble.

答:
As of Jan 2018 (update: still works in May 2023) the latest URL is:

https://google.com/maps/search/*your search string* (address, landmark, city, etc. Spaces are ok)

Examples:

https://google.com/maps/search/empire state building

https://google.com/maps/search/1600 Pennsylvania Ave NW, Washington, DC 20500

ContentLicense: CC BY-SA 4.0


问:
Matrix of random permutations
I want to create a matrix of x columns of random permutations from 1 to 10, say. The command randperm(10) works great, yet I would like to create x of those.

Is there a way to do it without a loop?
Thanks,

答:
If what you're after is a one-liner, I suppose you could use arrayfun

```<code>x = 10;
cell2mat (arrayfun (@(n) randperm (10).', [1:x], 'UniformOutput', false))
</code>```

Note that this does not guarantee unique permutations however, nor is it necessarily faster than a for loop.

Title: Matrix of random permutations

Body:
If what you're after is a one-liner, I suppose you could use arrayfun

x = 10;
cell2mat (arrayfun (@(n) randperm (10).', [1:x], 'UniformOutput', false))

Note that this does not guarantee unique permutations however, nor is it necessarily faster than a for loop.


问:
Java scrabble game unexpected error
On the line where I commented "ERROR HERE" I am getting an error stating "non static variable this cannot be referenced from a non-static context".  But when I remove static from my methods, it runs and I get "Error: Main method is not static in class scrabble.Scrabble, please define the main method as:
   public static void main(String[] args)".  Not sure what is causing this.</p>

```<code> package scrabble;

public class Scrabble {

class Tile{
   int value;
   char letter;

public Tile (char letter, int value) {
this.letter=letter;
this.value=value;
}
}
private static void printTile(Tile letter) {
    System.out.print("Letter is: " + letter.letter);
    System.out.println(" and the value is " + letter.value);

}

public static void testTile() {
    Tile L1 = new Tile('z', 10); //ERROR HERE
    printTile(L1);
}
public static void main(String[] args) {
testTile();
}

}
</code>```

答:
put the Title class in a separated file Title.java in the same package

package scrable

and make it public. that will work for you. :)

Title: Java scrabble game unexpected error

Body:
On the line where I commented "ERROR HERE" I am getting an error stating "non static variable this cannot be referenced from a non-static context".  But when I remove static from my methods, it runs and I get "Error: Main method is not static in class scrabble.Scrabble, please define the main method as:
   public static void main(String[] args)".  Not sure what is causing this.

 package scrabble;

public class Scrabble {

class Tile{
   int value;
   char letter;

public Tile (char letter, int value) {
this.letter=letter;
this.value=value;
}
}
private static void printTile(Tile letter) {
    System.out.print("Letter is: " + letter.letter);
    System.out.println(" and the value is " + letter.value);

}

public static void testTile() {
    Tile L1 = new Tile('z', 10); //ERROR HERE
    printTile(L1);
}
public static void main(String[] args) {
testTile();
}

}


问:
Expand a random range from 1–5 to 1–7
Given a function which produces a random integer in the range 1 to 5, write a function which produces a random integer in the range 1 to 7.</p>

答:
What is a simple solution? (rand5() + rand5()) % 7 + 1

What is an effective solution to reduce memory usage or run on a slower CPU? Yes, this is effective as it calls rand5() only twice and have O(1) space complexity

Consider rand5() gives out random numbers from 1 to 5(inclusive).

(1 + 1) % 7 + 1 = 3

(1 + 2) % 7 + 1 = 4

(1 + 3) % 7 + 1 = 5

(1 + 4) % 7 + 1 = 6

(1 + 5) % 7 + 1 = 7

(2 + 1) % 7 + 1 = 4

(2 + 2) % 7 + 1 = 5

(2 + 3) % 7 + 1 = 6

(2 + 4) % 7 + 1 = 7

(2 + 5) % 7 + 1 = 1

...

(5 + 1) % 7 + 1 = 7

(5 + 2) % 7 + 1 = 1

(5 + 3) % 7 + 1 = 2

(5 + 4) % 7 + 1 = 3

(5 + 5) % 7 + 1 = 4

...

and so on

OwnerDisplayName: praveen chettypally

Title: Expand a random range from 1–5 to 1–7

LastEditorDisplayName: Roger Pate


问:
Wordpress header modifications acting up
I'm trying to modify the twentyfifteen theme to have the basic lay-out like in the picture here:
With the top bar with the logo and image at the top and the menu on the side below the top bar. My attempt was to add a div straight at the opening of the body tag in the header to see if the placement would work. It is visible but it doesn't "push down" the side menu like I want it to be (like in the picture.

This is my header.php:

```<code><!DOCTYPE html>
<html <?php language_attributes(); ?> class="no-js">
<head>
    <meta charset="<?php bloginfo( 'charset' ); ?>">
    <meta name="viewport" content="width=device-width">
    <link rel="profile" href="http://gmpg.org/xfn/11">
    <link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>">
    <!--[if lt IE 9]>
    <script src="<?php echo esc_url( get_template_directory_uri() ); ?>/js/html5.js"></script>
    <![endif]-->
    <?php wp_head(); ?>
</head>

<body <?php body_class(); ?>>
<div style="background-color: black; width: 100%; height: 100px;"></div>
<div id="page" class="hfeed site">
    <a class="skip-link screen-reader-text" href="#content"><?php _e( 'Skip to content', 'twentyfifteen' ); ?></a>

    <div id="sidebar" class="sidebar">
        <header id="masthead" class="site-header" role="banner">
            <div class="site-branding">
                <?php
                    twentyfifteen_the_custom_logo();

                    if ( is_front_page() && is_home() ) : ?>
                        <h1 class="site-title"><a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?></a></h1>
                    <?php else : ?>
                        <p class="site-title"><a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?></a></p>
                    <?php endif;

                    $description = get_bloginfo( 'description', 'display' );
                    if ( $description || is_customize_preview() ) : ?>
                        <p class="site-description"><?php echo $description; ?></p>
                    <?php endif;
                ?>
                <button class="secondary-toggle"><?php _e( 'Menu and widgets', 'twentyfifteen' ); ?></button>
            </div><!-- .site-branding -->
        </header><!-- .site-header -->

        <?php get_sidebar(); ?>
    </div><!-- .sidebar -->

    <div id="content" class="site-content">
</code>```

In case it is relevant I also attached the theme's stylesheet here.

With my modifications this is how the div shows up:

The black bar should be above the menu on the left and push it down.

答: It is because you insert it into the sidebar div and not outside of it, create another div before "sidebar"</p>

Body:
I'm trying to modify the twentyfifteen theme to have the basic lay-out like in the picture here:
With the top bar with the logo and image at the top and the menu on the side below the top bar. My attempt was to add a div straight at the opening of the body tag in the header to see if the placement would work. It is visible but it doesn't "push down" the side menu like I want it to be (like in the picture.

This is my header.php:

<!DOCTYPE html>
<html <?php language_attributes(); ?> class="no-js">

    <meta charset="<?php bloginfo( 'charset' ); ?>">
    <meta name="viewport" content="width=device-width">
    <link rel="profile" href="http://gmpg.org/xfn/11">
    <link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>">

    <?php wp_head(); ?>

<body <?php body_class(); ?>>

    <?php _e( 'Skip to content', 'twentyfifteen' ); ?>

                <?php
                    twentyfifteen_the_custom_logo();

                    if ( is_front_page() && is_home() ) : ?>

<a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?>

                    <?php else : ?>

<a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?>

                    <?php endif;

                    $description = get_bloginfo( 'description', 'display' );
                    if ( $description || is_customize_preview() ) : ?>

<?php echo $description; ?>

                    <?php endif;
                ?>
                <button class="secondary-toggle"><?php _e( 'Menu and widgets', 'twentyfifteen' ); ?></button>

        <?php get_sidebar(); ?>

In case it is relevant I also attached the theme's stylesheet here.

With my modifications this is how the div shows up:

The black bar should be above the menu on the left and push it down.


问:
Change an Insert statement to an update statement in PHP/MySQL
I'm making an Android app that connects to a database online and lets the user edit the database from the application, I'm new to PHP and MySql but from my research I think I  should be using an UPDATE statement, I've written the code below to register new users on the site from a tutorial, but I'd like to change the INSERT statement to an UPDATE statement so that instead of registering a new user, the App updates existing data that I have entered in PHPMYADMIN, could someone show me how to do this? Also, if you require the code for the app mention it in the comments and I'll add it to the question, I don't want to post too much unneccessary code. Thanks in advance.

```<code><?php
    require "conn.php";

    $patient_name = $_POST["patient_name"];
    $check_in_date = $_POST["check_in_date"];
    $room_number = $_POST["room_number"];
    $bed_number = $_POST["bed_number"];
    $notes = $_POST["notes"];

    $mysql_qry = "insert into patients(patient_name, check_in_date, room_number, bed_number, notes) values ('$patient_name', '$check_in_date', '$room_number', '$bed_number', '$notes')";

    if($conn->query($mysql_qry) === TRUE) {
        echo "Insert successful";
    }
    else{
        echo "Error: " . $mysql_qry . "<br>" . $conn->error;
    }
    $conn->close();
?>
</code>```

EDIT

The fixed code is below, it now updates records already in the database rather than adding new data.

```<code><?php
    require "conn.php";

    $patient_name = $_POST["patient_name"];
    $check_in_date = $_POST["check_in_date"];
    $room_number = $_POST["room_number"];
    $bed_number = $_POST["bed_number"];
    $notes = $_POST["notes"];

    $mysql_qry = "UPDATE patients SET notes='$notes' WHERE patient_name='$patient_name'";

    if($conn->query($mysql_qry) === TRUE) {
        echo "Insert successful";
    }
    else{
        echo "Error: " . $mysql_qry . "<br>" . $conn->error;
    }
    $conn->close();
?>
</code>```

答:
You can also use REPLACE INTO, then you don't have to change the SQL statement. Let MySQL do the work for you.

https://dev.mysql.com/doc/refman/5.7/en/replace.html

```<code><?php
require "conn.php";

$patient_name = $_POST["patient_name"];
$check_in_date = $_POST["check_in_date"];
$room_number = $_POST["room_number"];
$bed_number = $_POST["bed_number"];
$notes = $_POST["notes"];

$mysql_qry = "REPLACE INTO patients(patient_name, check_in_date, room_number, bed_number, notes) VALUES ('$patient_name', '$check_in_date', '$room_number', '$bed_number', '$notes')";

if($conn->query($mysql_qry) === TRUE) {
    echo "Insert successful";
}
else{
    echo "Error: " . $mysql_qry . "<br>" . $conn->error;
}
$conn->close();
</code>```

Also, you should really take a look at using PDO with prepared statements and parameters.

https://secure.php.net/manual/en/pdo.prepare.php

Body:
I'm making an Android app that connects to a database online and lets the user edit the database from the application, I'm new to PHP and MySql but from my research I think I  should be using an UPDATE statement, I've written the code below to register new users on the site from a tutorial, but I'd like to change the INSERT statement to an UPDATE statement so that instead of registering a new user, the App updates existing data that I have entered in PHPMYADMIN, could someone show me how to do this? Also, if you require the code for the app mention it in the comments and I'll add it to the question, I don't want to post too much unneccessary code. Thanks in advance.

<?php
    require "conn.php";

    $patient_name = $_POST["patient_name"];
    $check_in_date = $_POST["check_in_date"];
    $room_number = $_POST["room_number"];
    $bed_number = $_POST["bed_number"];
    $notes = $_POST["notes"];

    $mysql_qry = "insert into patients(patient_name, check_in_date, room_number, bed_number, notes) values ('$patient_name', '$check_in_date', '$room_number', '$bed_number', '$notes')";

    if($conn->query($mysql_qry) === TRUE) {
        echo "Insert successful";
    }
    else{
        echo "Error: " . $mysql_qry . "
" . $conn->error;
    }
    $conn->close();
?>

EDIT

The fixed code is below, it now updates records already in the database rather than adding new data.

<?php
    require "conn.php";

    $patient_name = $_POST["patient_name"];
    $check_in_date = $_POST["check_in_date"];
    $room_number = $_POST["room_number"];
    $bed_number = $_POST["bed_number"];
    $notes = $_POST["notes"];

    $mysql_qry = "UPDATE patients SET notes='$notes' WHERE patient_name='$patient_name'";

    if($conn->query($mysql_qry) === TRUE) {
        echo "Insert successful";
    }
    else{
        echo "Error: " . $mysql_qry . "
" . $conn->error;
    }
    $conn->close();
?>

Body:
You can also use REPLACE INTO, then you don't have to change the SQL statement. Let MySQL do the work for you.

https://dev.mysql.com/doc/refman/5.7/en/replace.html

<?php
require "conn.php";

$patient_name = $_POST["patient_name"];
$check_in_date = $_POST["check_in_date"];
$room_number = $_POST["room_number"];
$bed_number = $_POST["bed_number"];
$notes = $_POST["notes"];

$mysql_qry = "REPLACE INTO patients(patient_name, check_in_date, room_number, bed_number, notes) VALUES ('$patient_name', '$check_in_date', '$room_number', '$bed_number', '$notes')";

if($conn->query($mysql_qry) === TRUE) {
    echo "Insert successful";
}
else{
    echo "Error: " . $mysql_qry . "<br>" . $conn->error;
}
$conn->close();

Also, you should really take a look at using PDO with prepared statements and parameters.

https://secure.php.net/manual/en/pdo.prepare.php


问:
Upgrading from Ansi to Unicode version of Inno Setup (any disadvantages)
Are there any disadvantages of the Inno Setup Unicode version compared to the Ansi version?

Or what is the reason that still both versions are offered in parallel and not only the Unicode one is left?

Are there any potentials problems, when using the Unicode version for my existing Inno Setup project developed with the Ansi version?

答:
There are no real disadvantages. There are mostly advantages. Obviously the fact that the Unicode version is not limited to legacy Ansi character set. See below for details.

If you are starting new Inno Setup project, always use the Unicode version. There is no reason to use the Ansi version for new projects. Actually there's no Ansi version for the latest Inno Setup 6 anymore.

The reason, why Ansi version of Inno Setup was still available for long time, was that the Pascal Script code of Ansi and Unicode versions are not 100% compatible. Mostly they are, but there are differences.

So if your existing installer script does not have any Pascal Script code (there's no [Code] section in your .iss), you can (and should) switch to the Unicode version straight away.

If you have some Pascal Script code, you should be more careful. See below for details.

Why you want to use Unicode version

For example of problems with the Ansi version, if you run Japanese-only installer built with Ansi version of Inno Setup on English system, you will get:

See also Inno Setup installator has wrong text encoding.

For the same reason, the Ansi version will not be able to create files with names containing characters, that are not present in the legacy Ansi character set of the target machine.

The Unicode version does not have these problems, as documented in the Unicode Inno Setup article:

Key features of Unicode Inno Setup are its ability to display any language on any system regardless of the system code page, and its ability to work with Unicode filenames. One could consider Unicode Inno Setup as the new standard Inno Setup and Non Unicode Inno Setup as an old special Inno Setup for those who want the very smallest size possible.

Also for Inno Setup 6, there is no Ansi version at all, so if you want to use the latest version of Inno Setup with all its new features, you need to switch to the Unicode version along.

Additionally there are some small improvements in the Unicode version Pascal Script. They are documented in the Unicode Inno Setup article. On top of that, there are few undocumented improvements:

Inc/Dec functions/statements. See Inc function Inno Setup.

Better Variant support. For example, see Inno Setup: Iterate through array of type Variant (from OleObject) or Is there a way to read the system's information in Inno Setup.

Better high-DPI (and non-standard screen in general) support. For example, see Inno Setup taskbar icon blurred or Inno Setup Installer has squished window on XP?

Ranges in case statement: "colon (':') expected" compiler error on character range in case statement in Inno Setup Pascal script.

in operator with a constant set: It seems that in Ansi version, you always get "Type mismatch" error, unless you store the set into a set of variable first.

Note, that while the Unicode version does support the in operator with a constant set, it does not support ranges in the set expression, so X in [1, 2, 3] is possible, but X in [1..3] is not possible, you will get "Closing square bracket (']') expected."

TLabel has transparent background in the Unicode version. See Inno Setup - Transparency under text in page name and description labels

Calling standard event handlers of some custom wizard pages is not possible in Ansi version, while is work fine in Unicode version. What can be useful for things like Inno Setup event that is generated when folder is browsed on TInputDirWizardPage?

Better support for RTF. See How to add clickable links to custom page in Inno Setup using RichEditViewer?

Possible problems in Pascal Script code

There are few areas, where problems can emerge in the Pascal Script code:

Any calls to DLL functions that take string parameters - string and PChar types.  AnsiString should be ok, as it's the same in the Unicode version.

In Unicode version, PChar was renamed to PAnsiChar.

If you invoke any Windows API function that uses strings, you should switch to its Wide version. E.g. use GetFileAttributesW, instead of GetFileAttributesA. There's no PWideChar type. So if your declaration used PChar type in Ansi version, and you switch to Wide version of the function, you have to use string type instead. Inno Setup will automatically marshal it to the LPCTSTR (or similar), aka the PWideChar.

The declaration below is correct in Ansi version, but wrong in Unicode version, as the GetFileAttributesA takes PAnsiChar, but the string marshals to PWideChar in the Unicode version.

function GetFileAttributes(lpFileName: string): DWORD;
  external 'GetFileAttributesA@kernel32.dll stdcall';
```
<p>For a full example and solution, see Inno Setup FileExists unable to find existing file.</p>
<p>In rare cases, that you are calling a function that has an out <code>PWideChar</code> parameter (<code>var S: PWideChar</code>), it's very tricky to use it, without the actual <code>PWideChar</code> type, as in this case you cannot use the <code>string</code> marshaling. But it's doable, see Constant for AppData\LocalLow in Inno Setup?</p>
<p>Similarly to Windows API, some 3rd party libraries also provide a separate Unicode version with Unicode strings in its API. For example ISSkin has <code>ISSkinU.dll</code>. See Getting ISSkin to work with latest Inno Setup Unicode.</p>
</li>
<li><p>Any code that uses <code>string</code> type as byte array (as in Unicode version, the <code>string</code> is wide char (2-byte) array). That's mostly concern, only if your code uses <code>TStream</code> class methods like:</p>
<pre class="lang-pascal prettyprint-override"><code>function Read(Buffer: String; Count: Longint): Longint;
function Write(Buffer: String; Count: Longint): Longint;
procedure ReadBuffer(Buffer: String; Count: Longint);
procedure WriteBuffer(Buffer: String; Count: Longint);
</code>```

These methods should have really been re-declared with AnsiString. Looks like a bug to me.

To make these methods usable in Unicode version, use BufferToAnsi function by @TLama that is used in many existing answers, like:

Inno Setup LoadStringFromFile fails when file is open in another process

Read bytes from file at desired position with Inno Setup

For another approach, see see Writing binary file in Inno Setup

Unicode version does not allow set of char variable (as set is not allowed for multi-byte types). Though interestingly it supports set of char constants in expressions. See "Type mismatch" error on "set of char" in Pascal Script of the Inno Setup Unicode version.

FloatToStr uses a locale specific decimal separator in Ansi version, while always a dot in Unicode version.

Unicode version is more strict about use of semicolons. The Ansi version tolerates some missing semicolons, so it can compile even code that is not 100% syntactically correct in this respect.

If your code does not use any of the above, and you have your semicolons right, you should not have any problems with the Unicode version.

Last minor thing is that the Unicode version creates slightly larger installers. And Inno Setup 6 yet bit larger. See Why is installer compiled in Inno Setup 6 one MB larger than in Inno Setup 5

Body:
There are no real disadvantages. There are mostly advantages. Obviously the fact that the Unicode version is not limited to legacy Ansi character set. See below for details.

If you are starting new Inno Setup project, always use the Unicode version. There is no reason to use the Ansi version for new projects. Actually there's no Ansi version for the latest Inno Setup 6 anymore.

The reason, why Ansi version of Inno Setup was still available for long time, was that the Pascal Script code of Ansi and Unicode versions are not 100% compatible. Mostly they are, but there are differences.

So if your existing installer script does not have any Pascal Script code (there's no [Code] section in your .iss), you can (and should) switch to the Unicode version straight away.

If you have some Pascal Script code, you should be more careful. See below for details.

Why you want to use Unicode version

For example of problems with the Ansi version, if you run Japanese-only installer built with Ansi version of Inno Setup on English system, you will get:

See also Inno Setup installator has wrong text encoding.

For the same reason, the Ansi version will not be able to create files with names containing characters, that are not present in the legacy Ansi character set of the target machine.

The Unicode version does not have these problems, as documented in the Unicode Inno Setup article:

Key features of Unicode Inno Setup are its ability to display any language on any system regardless of the system code page, and its ability to work with Unicode filenames. One could consider Unicode Inno Setup as the new standard Inno Setup and Non Unicode Inno Setup as an old special Inno Setup for those who want the very smallest size possible.

Also for Inno Setup 6, there is no Ansi version at all, so if you want to use the latest version of Inno Setup with all its new features, you need to switch to the Unicode version along.

Additionally there are some small improvements in the Unicode version Pascal Script. They are documented in the Unicode Inno Setup article. On top of that, there are few undocumented improvements:

Inc/Dec functions/statements. See Inc function Inno Setup.

Better Variant support. For example, see Inno Setup: Iterate through array of type Variant (from OleObject) or Is there a way to read the system's information in Inno Setup.

Better high-DPI (and non-standard screen in general) support. For example, see Inno Setup taskbar icon blurred or Inno Setup Installer has squished window on XP?

Ranges in case statement: "colon (':') expected" compiler error on character range in case statement in Inno Setup Pascal script.

in operator with a constant set: It seems that in Ansi version, you always get "Type mismatch" error, unless you store the set into a set of variable first.

Note, that while the Unicode version does support the in operator with a constant set, it does not support ranges in the set expression, so X in [1, 2, 3] is possible, but X in [1..3] is not possible, you will get "Closing square bracket (']') expected."

TLabel has transparent background in the Unicode version. See Inno Setup - Transparency under text in page name and description labels

Calling standard event handlers of some custom wizard pages is not possible in Ansi version, while is work fine in Unicode version. What can be useful for things like Inno Setup event that is generated when folder is browsed on TInputDirWizardPage?

Better support for RTF. See How to add clickable links to custom page in Inno Setup using RichEditViewer?

Possible problems in Pascal Script code

There are few areas, where problems can emerge in the Pascal Script code:

Any calls to DLL functions that take string parameters - string and PChar types.  AnsiString should be ok, as it's the same in the Unicode version.

In Unicode version, PChar was renamed to PAnsiChar.

If you invoke any Windows API function that uses strings, you should switch to its Wide version. E.g. use GetFileAttributesW, instead of GetFileAttributesA. There's no PWideChar type. So if your declaration used PChar type in Ansi version, and you switch to Wide version of the function, you have to use string type instead. Inno Setup will automatically marshal it to the LPCTSTR (or similar), aka the PWideChar.

The declaration below is correct in Ansi version, but wrong in Unicode version, as the GetFileAttributesA takes PAnsiChar, but the string marshals to PWideChar in the Unicode version.

function GetFileAttributes(lpFileName: string): DWORD;
  external 'GetFileAttributesA@kernel32.dll stdcall';

For a full example and solution, see Inno Setup FileExists unable to find existing file.

In rare cases, that you are calling a function that has an out PWideChar parameter (var S: PWideChar), it's very tricky to use it, without the actual PWideChar type, as in this case you cannot use the string marshaling. But it's doable, see Constant for AppData\LocalLow in Inno Setup?

Similarly to Windows API, some 3rd party libraries also provide a separate Unicode version with Unicode strings in its API. For example ISSkin has ISSkinU.dll. See Getting ISSkin to work with latest Inno Setup Unicode.

Any code that uses string type as byte array (as in Unicode version, the string is wide char (2-byte) array). That's mostly concern, only if your code uses TStream class methods like:

function Read(Buffer: String; Count: Longint): Longint;
function Write(Buffer: String; Count: Longint): Longint;
procedure ReadBuffer(Buffer: String; Count: Longint);
procedure WriteBuffer(Buffer: String; Count: Longint);

These methods should have really been re-declared with AnsiString. Looks like a bug to me.

To make these methods usable in Unicode version, use BufferToAnsi function by @TLama that is used in many existing answers, like:

Inno Setup LoadStringFromFile fails when file is open in another process

Read bytes from file at desired position with Inno Setup

For another approach, see see Writing binary file in Inno Setup

Unicode version does not allow set of char variable (as set is not allowed for multi-byte types). Though interestingly it supports set of char constants in expressions. See "Type mismatch" error on "set of char" in Pascal Script of the Inno Setup Unicode version.

FloatToStr uses a locale specific decimal separator in Ansi version, while always a dot in Unicode version.

Unicode version is more strict about use of semicolons. The Ansi version tolerates some missing semicolons, so it can compile even code that is not 100% syntactically correct in this respect.

If your code does not use any of the above, and you have your semicolons right, you should not have any problems with the Unicode version.

Last minor thing is that the Unicode version creates slightly larger installers. And Inno Setup 6 yet bit larger. See Why is installer compiled in Inno Setup 6 one MB larger than in Inno Setup 5


问:
Label ranges and colors in Python plot
In the following I'm trying to plot points with color and label that changes for every j. What I'm getting is different color and one label in the legend for every couple (i, j):

```<code>import itertools
import numpy as np
import matplotlib.pyplot as plt

color_list = ["blue", "brown", "red", "black"]
g = itertools.cycle(color_list)

primes = (139,149,151,157,163,167)
for j in range(50, 300, 10):
    col = next(g)
    for k in (primes):
        for l in range(10000, 20000, 500):
            start = time.time()
            generator(j, k, l)
            end = time.time()
            plt.plot(l, end - start, linewidth = 2, marker='o', color=col)
</code>```

Edit: Updated the code with my original problem as I couldn't figure out if the solution from Ernest + Arya can work in this case.

答: You can use the matplotlib cycler. Set up the list of colors you want to iterate over, then inside the j-loop, get a color with my_cycle.next(). Then pass that color into your call to plt.plot.

Title: Label ranges and colors in Python plot

Body:
In the following I'm trying to plot points with color and label that changes for every j. What I'm getting is different color and one label in the legend for every couple (i, j):

import itertools
import numpy as np
import matplotlib.pyplot as plt

color_list = ["blue", "brown", "red", "black"]
g = itertools.cycle(color_list)

primes = (139,149,151,157,163,167)
for j in range(50, 300, 10):
    col = next(g)
    for k in (primes):
        for l in range(10000, 20000, 500):
            start = time.time()
            generator(j, k, l)
            end = time.time()
            plt.plot(l, end - start, linewidth = 2, marker='o', color=col)

Edit: Updated the code with my original problem as I couldn't figure out if the solution from Ernest + Arya can work in this case.