问:
Docker Devmapper space issue - increase size
I have the same issue as in space issue on docker devmapper and CentOS7

It only specifies to clean up but not how I can increase the space and I dont have any images to clean. I tried several things with dm.min_free_space but nothing worked and want to increase the space.

OS Version/build: Red Hat Enterprise Linux Server release 7.3 (Maipo)

App version:

```<code>Client:
 Version:         1.12.6
 API version:     1.24
 Package version: docker-common-1.12.6-11.el7.centos.x86_64
 Go version:      go1.7.4
 Git commit:      96d83a5/1.12.6
 Built:           Tue Mar  7 09:23:34 2017
 OS/Arch:         linux/amd64

Server:
 Version:         1.12.6
 API version:     1.24
 Package version: docker-common-1.12.6-11.el7.centos.x86_64
 Go version:      go1.7.4
 Git commit:      96d83a5/1.12.6
 Built:           Tue Mar  7 09:23:34 2017
 OS/Arch:         linux/amd64
</code>```

Steps to reproduce

I have no containers running currently and have some docker images pertaining to Kubernetes which will be used by the Kubernetes service.

```<code>sudo docker ps -a
    CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
    [kubeuser4@kubenode4 Employee]$ sudo docker images
    REPOSITORY                                            TAG                 IMAGE ID            CREATED             SIZE
    docker.io/busybox                                     latest              00f017a8c2a6        5 days ago          1.11 MB
    registry.access.redhat.com/rhel7/pod-infrastructure   latest              34d3450d733b        6 weeks ago         205 MB
    docker.io/java                                        8                   d23bdf5b1b1b        8 weeks ago         643.1 MB
    gcr.io/google_containers/heapster_grafana             v2.6.0-2            b43443930626        12 months ago       230 MB
</code>```

When I try to create a docker image of my application that needs to be used, I get the below error.

```<code>devmapper: Thin Pool has 8783 free data blocks which is less than minimum required 163840 free data blocks. Create more free space in thin pool or use dm.min_free_space option to change behavior
</code>```

I tried the cleaning up as mentioned in the other forums, but not helped much and getting the same error. When I tried to run with this sudo docker --storage-opt dm.min_free_space=0%, seems like it starts as a daemon, but still it failed with another error "docker-runc not installed on system" and also I dont want to run it as a daemon.

Below are some command outputs

```<code>sudo dmsetup status
localvg00-lv_home: 0 20971520 linear
localvg00-lv_home: 20971520 20971520 linear
docker-251:5-134039-pool: 0 209715200 thin-pool 924 848/524288 1629226/1638400 - rw discard_passdown queue_if_no_space
localvg00-lv_tmp: 0 4194304 linear
localvg00-lv_swap: 0 8388608 linear
localvg00-lv_root: 0 2097152 linear
localvg00-lv_root: 2097152 20971520 linear
localvg00-lv_usr: 0 16777216 linear
localvg00-lv_var: 0 8388608 linear
localvg00-lv_var: 8388608 62914560 linear

sudo docker info
Containers: 0
 Running: 0
 Paused: 0
 Stopped: 0
Images: 4
Server Version: 1.12.6
Storage Driver: devicemapper
 Pool Name: docker-251:5-134039-pool
 Pool Blocksize: 65.54 kB
 Base Device Size: 10.74 GB
 Backing Filesystem: xfs
 Data file: /dev/loop0
 Metadata file: /dev/loop1
 Data Space Used: 106.8 GB
 Data Space Total: 107.4 GB
 Data Space Available: 601.2 MB
 Metadata Space Used: 3.473 MB
 Metadata Space Total: 2.147 GB
 Metadata Space Available: 2.144 GB
 Thin Pool Minimum Free Space: 10.74 GB
 Udev Sync Supported: true
 Deferred Removal Enabled: false
 Deferred Deletion Enabled: false
 Deferred Deleted Device Count: 0
 Data loop file: /var/lib/docker/devicemapper/devicemapper/data
 WARNING: Usage of loopback devices is strongly discouraged for production use. Use `--storage-opt dm.thinpooldev` to specify a custom block storage device.
 Metadata loop file: /var/lib/docker/devicemapper/devicemapper/metadata
 Library Version: 1.02.135-RHEL7 (2016-11-16)
Logging Driver: journald
Cgroup Driver: systemd
Plugins:
 Volume: local
 Network: overlay null bridge host
Swarm: inactive
Runtimes: runc docker-runc
Default Runtime: docker-runc
Security Options: seccomp
Kernel Version: 4.1.12-61.1.28.el7uek.x86_64
Operating System: Oracle Linux Server 7.3
OSType: linux
Architecture: x86_64
Number of Docker Hooks: 2
CPUs: 2
Total Memory: 7.545 GiB
Name: kubenode4
</code>```

I had also tried increasing all the physical volume size and logical volume size(lv_var) on my linux machine, but still it doesnt work.

```<code>sudo lvs
[sudo] password for kubeuser4:
  LV      VG        Attr       LSize  Pool Origin Data%  Meta%  Move Log Cpy%Sync Convert
  lv_home localvg00 -wi-ao---- 20.00g
  lv_root localvg00 -wi-ao---- 11.00g
  lv_swap localvg00 -wi-ao----  4.00g
  lv_tmp  localvg00 -wi-ao----  2.00g
  lv_usr  localvg00 -wi-ao----  8.00g
  lv_var  localvg00 -wi-ao---- 34.00g

 sudo ls -lsh /var/lib/docker/devicemapper/devicemapper/data
2.3G -rw------- 1 root root 100G Mar 14 22:16 /var/lib/docker/devicemapper/devicemapper/data
</code>```

Someone please let me know how it can be done.

Thanks,

答:
It is better move away from devicemapper for a few reasons.

devicemapper in loopback unrecoverable storage issue: https://github.com/docker/docker/issues/3182 "devicemapper not recommended for production use".

I found it easy enough to switch to overlay storage driver, YMMV of course but hopefully not too much. 'rm -rf /var/lib/docker' is somewhat optional when switching but easy and I would highly recommend it as long as you can load your images back in.  http://www.projectatomic.io/blog/2015/06/notes-on-fedora-centos-and-docker-storage-drivers/

```<code>systemctl stop docker
rm -rf /var/lib/docker

# if these files do not already exist . . . create them, otherwise you need to edit by hand, you can also just add -s overlay in the systemctl docker script
ls /etc/sysconfig/docker /etc/sysconfig/docker-storage
[[ $? != 0 ]] && {
    echo OPTIONS='--selinux-enabled=false' > /etc/sysconfig/docker
    echo "DOCKER_STORAGE_OPTIONS= -s overlay" > /etc/sysconfig/docker-storage
}
systemctl start docker
systemctl status docker
docker images
</code>```

more reading:
https://docs.docker.com/engine/userguide/storagedriver/selectadriver/
https://integratedcode.us/2016/08/30/storage-drivers-in-docker-a-deep-dive/

Body:
I have the same issue as in space issue on docker devmapper and CentOS7

It only specifies to clean up but not how I can increase the space and I dont have any images to clean. I tried several things with dm.min_free_space but nothing worked and want to increase the space.

OS Version/build: Red Hat Enterprise Linux Server release 7.3 (Maipo)

App version:

Client:
 Version:         1.12.6
 API version:     1.24
 Package version: docker-common-1.12.6-11.el7.centos.x86_64
 Go version:      go1.7.4
 Git commit:      96d83a5/1.12.6
 Built:           Tue Mar  7 09:23:34 2017
 OS/Arch:         linux/amd64

Server:
 Version:         1.12.6
 API version:     1.24
 Package version: docker-common-1.12.6-11.el7.centos.x86_64
 Go version:      go1.7.4
 Git commit:      96d83a5/1.12.6
 Built:           Tue Mar  7 09:23:34 2017
 OS/Arch:         linux/amd64

Steps to reproduce

I have no containers running currently and have some docker images pertaining to Kubernetes which will be used by the Kubernetes service.

sudo docker ps -a
    CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
    [kubeuser4@kubenode4 Employee]$ sudo docker images
    REPOSITORY                                            TAG                 IMAGE ID            CREATED             SIZE
    docker.io/busybox                                     latest              00f017a8c2a6        5 days ago          1.11 MB
    registry.access.redhat.com/rhel7/pod-infrastructure   latest              34d3450d733b        6 weeks ago         205 MB
    docker.io/java                                        8                   d23bdf5b1b1b        8 weeks ago         643.1 MB
    gcr.io/google_containers/heapster_grafana             v2.6.0-2            b43443930626        12 months ago       230 MB

When I try to create a docker image of my application that needs to be used, I get the below error.

devmapper: Thin Pool has 8783 free data blocks which is less than minimum required 163840 free data blocks. Create more free space in thin pool or use dm.min_free_space option to change behavior

I tried the cleaning up as mentioned in the other forums, but not helped much and getting the same error. When I tried to run with this sudo docker --storage-opt dm.min_free_space=0%, seems like it starts as a daemon, but still it failed with another error "docker-runc not installed on system" and also I dont want to run it as a daemon.

Below are some command outputs

sudo dmsetup status
localvg00-lv_home: 0 20971520 linear
localvg00-lv_home: 20971520 20971520 linear
docker-251:5-134039-pool: 0 209715200 thin-pool 924 848/524288 1629226/1638400 - rw discard_passdown queue_if_no_space
localvg00-lv_tmp: 0 4194304 linear
localvg00-lv_swap: 0 8388608 linear
localvg00-lv_root: 0 2097152 linear
localvg00-lv_root: 2097152 20971520 linear
localvg00-lv_usr: 0 16777216 linear
localvg00-lv_var: 0 8388608 linear
localvg00-lv_var: 8388608 62914560 linear

sudo docker info
Containers: 0
 Running: 0
 Paused: 0
 Stopped: 0
Images: 4
Server Version: 1.12.6
Storage Driver: devicemapper
 Pool Name: docker-251:5-134039-pool
 Pool Blocksize: 65.54 kB
 Base Device Size: 10.74 GB
 Backing Filesystem: xfs
 Data file: /dev/loop0
 Metadata file: /dev/loop1
 Data Space Used: 106.8 GB
 Data Space Total: 107.4 GB
 Data Space Available: 601.2 MB
 Metadata Space Used: 3.473 MB
 Metadata Space Total: 2.147 GB
 Metadata Space Available: 2.144 GB
 Thin Pool Minimum Free Space: 10.74 GB
 Udev Sync Supported: true
 Deferred Removal Enabled: false
 Deferred Deletion Enabled: false
 Deferred Deleted Device Count: 0
 Data loop file: /var/lib/docker/devicemapper/devicemapper/data
 WARNING: Usage of loopback devices is strongly discouraged for production use. Use `--storage-opt dm.thinpooldev` to specify a custom block storage device.
 Metadata loop file: /var/lib/docker/devicemapper/devicemapper/metadata
 Library Version: 1.02.135-RHEL7 (2016-11-16)
Logging Driver: journald
Cgroup Driver: systemd
Plugins:
 Volume: local
 Network: overlay null bridge host
Swarm: inactive
Runtimes: runc docker-runc
Default Runtime: docker-runc
Security Options: seccomp
Kernel Version: 4.1.12-61.1.28.el7uek.x86_64
Operating System: Oracle Linux Server 7.3
OSType: linux
Architecture: x86_64
Number of Docker Hooks: 2
CPUs: 2
Total Memory: 7.545 GiB
Name: kubenode4

I had also tried increasing all the physical volume size and logical volume size(lv_var) on my linux machine, but still it doesnt work.

sudo lvs
[sudo] password for kubeuser4:
  LV      VG        Attr       LSize  Pool Origin Data%  Meta%  Move Log Cpy%Sync Convert
  lv_home localvg00 -wi-ao---- 20.00g
  lv_root localvg00 -wi-ao---- 11.00g
  lv_swap localvg00 -wi-ao----  4.00g
  lv_tmp  localvg00 -wi-ao----  2.00g
  lv_usr  localvg00 -wi-ao----  8.00g
  lv_var  localvg00 -wi-ao---- 34.00g

 sudo ls -lsh /var/lib/docker/devicemapper/devicemapper/data
2.3G -rw------- 1 root root 100G Mar 14 22:16 /var/lib/docker/devicemapper/devicemapper/data

Someone please let me know how it can be done.

Thanks,

Body:
It is better move away from devicemapper for a few reasons.

devicemapper in loopback unrecoverable storage issue: https://github.com/docker/docker/issues/3182 "devicemapper not recommended for production use".

I found it easy enough to switch to overlay storage driver, YMMV of course but hopefully not too much. 'rm -rf /var/lib/docker' is somewhat optional when switching but easy and I would highly recommend it as long as you can load your images back in.  http://www.projectatomic.io/blog/2015/06/notes-on-fedora-centos-and-docker-storage-drivers/

systemctl stop docker
rm -rf /var/lib/docker

# if these files do not already exist . . . create them, otherwise you need to edit by hand, you can also just add -s overlay in the systemctl docker script
ls /etc/sysconfig/docker /etc/sysconfig/docker-storage
[[ $? != 0 ]] && {
    echo OPTIONS='--selinux-enabled=false' > /etc/sysconfig/docker
    echo "DOCKER_STORAGE_OPTIONS= -s overlay" > /etc/sysconfig/docker-storage
}
systemctl start docker
systemctl status docker
docker images

more reading:
https://docs.docker.com/engine/userguide/storagedriver/selectadriver/
https://integratedcode.us/2016/08/30/storage-drivers-in-docker-a-deep-dive/


来源: stackexchange

问:
How to add print dialog to the printpreviewdialog?
My boss wants me to create the window form that has printing function, but he wants to print the datagridview after preview.

So now I encourage the problem, I cannot print multiple set of paper or choose the printer or make any changes when click the print button on printpreviewdialog.When I click the button, it will direct print the paper. So I wish to join the printpreviewdialog and printdialog.

Why the printpreviewdialog and printdialog can only be used in different buttons? It's lack of usibility when needed to click one button to preview and click another button to print multiple set and make changes of printer.

Any one can help me?

printdialog

```<code>DialogResult result = printDialog1.ShowDialog();
            // If the result is OK then print the document.
            if (result == DialogResult.OK)
            {
                position = 0;
                pageno = 1;
                printDocument2.DefaultPageSettings.Margins = new Margins(20, 20, 20, 20);
                printDocument2.OriginAtMargins = true;
                printPreviewDialog1.Document = printDocument2;
                printPreviewDialog1.ShowDialog();
            }
</code>```

printpreviewdialog

```<code>printDocument3.DefaultPageSettings.Margins = new Margins(20, 20, 20, 20);
            printDocument3.OriginAtMargins = true;
            //((ToolStripButton)((ToolStrip)printPreviewDialog1.Controls[1]).Items[0]).Enabled = false;
            printPreviewDialog1.Document = printDocument3;
            printPreviewDialog1.ShowDialog();
</code>```

答:
Works good...
Have one tip...
You can re-use the current icon by:

```<code>this.ToolStripButton.Image = ((System.Windows.Forms.ToolStrip)(printPreviewDialog.Controls[1])).ImageList.Images[0];
</code>```

The rest of the snippet:

```<code>        {
        this.ToolStripButton = new System.Windows.Forms.ToolStripButton();
        this.ToolStripButton.Image = ((System.Windows.Forms.ToolStrip)(printPreviewDialog.Controls[1])).ImageList.Images[0];
        this.ToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
        this.ToolStripButton.Click += new System.EventHandler(this.printPreview_PrintClick);
        ((System.Windows.Forms.ToolStrip)(printPreviewDialog.Controls[1])).Items.RemoveAt(0);
        ((System.Windows.Forms.ToolStrip)(printPreviewDialog.Controls[1])).Items.Insert(0, ToolStripButton);
    }
    private void printPreview_PrintClick(object sender, System.EventArgs ee)
    {
        try
        {
            this.printDialog.Document = printDocument;
            if (printDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                printDocument.Print();
            }
        }
        catch (System.Exception ex)
        {
            System.Windows.MessageBox.Show(ex.Message, ToString());
        }
    }
    private System.Windows.Forms.ToolStripButton ToolStripButton;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
My boss wants me to create the window form that has printing function, but he wants to print the datagridview after preview.

So now I encourage the problem, I cannot print multiple set of paper or choose the printer or make any changes when click the print button on printpreviewdialog.When I click the button, it will direct print the paper. So I wish to join the printpreviewdialog and printdialog.

Why the printpreviewdialog and printdialog can only be used in different buttons? It's lack of usibility when needed to click one button to preview and click another button to print multiple set and make changes of printer.

Any one can help me?

printdialog

DialogResult result = printDialog1.ShowDialog();
            // If the result is OK then print the document.
            if (result == DialogResult.OK)
            {
                position = 0;
                pageno = 1;
                printDocument2.DefaultPageSettings.Margins = new Margins(20, 20, 20, 20);
                printDocument2.OriginAtMargins = true;
                printPreviewDialog1.Document = printDocument2;
                printPreviewDialog1.ShowDialog();
            }

printpreviewdialog

printDocument3.DefaultPageSettings.Margins = new Margins(20, 20, 20, 20);
            printDocument3.OriginAtMargins = true;
            //((ToolStripButton)((ToolStrip)printPreviewDialog1.Controls[1]).Items[0]).Enabled = false;
            printPreviewDialog1.Document = printDocument3;
            printPreviewDialog1.ShowDialog();

Body:
Works good...
Have one tip...
You can re-use the current icon by:

this.ToolStripButton.Image = ((System.Windows.Forms.ToolStrip)(printPreviewDialog.Controls[1])).ImageList.Images[0];

The rest of the snippet:

        {
        this.ToolStripButton = new System.Windows.Forms.ToolStripButton();
        this.ToolStripButton.Image = ((System.Windows.Forms.ToolStrip)(printPreviewDialog.Controls[1])).ImageList.Images[0];
        this.ToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
        this.ToolStripButton.Click += new System.EventHandler(this.printPreview_PrintClick);
        ((System.Windows.Forms.ToolStrip)(printPreviewDialog.Controls[1])).Items.RemoveAt(0);
        ((System.Windows.Forms.ToolStrip)(printPreviewDialog.Controls[1])).Items.Insert(0, ToolStripButton);
    }
    private void printPreview_PrintClick(object sender, System.EventArgs ee)
    {
        try
        {
            this.printDialog.Document = printDocument;
            if (printDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                printDocument.Print();
            }
        }
        catch (System.Exception ex)
        {
            System.Windows.MessageBox.Show(ex.Message, ToString());
        }
    }
    private System.Windows.Forms.ToolStripButton ToolStripButton;


问:
How to draw shapes like circles, oval, ractangles dynamically in iOS?
I have a UICollectionView of showing shapes like circles, oval, ractangles. So when I clicked on Cell I need to draw same shape on UIView and after I need to move and resize that view which was drawn by clicking in Cell. How it can achieve in iOS ? Thanks in advance. </p>

答:
If you use a UICollectionView, your reusable cell will have the "layer" to draw on.

What to do?

1. Create a UIView subclass and place it inside your reusable cell.

2. Override drawRect(_:) method, you'll do all the drawing inside.

3. Add your shape/line drawing code to drawRect method.

For example use UIBezierPath class for lines, arcs etc. You'll be able to create all sorts of shapes.

You should read the CoreGraphics API Ref:

https://developer.apple.com/reference/coregraphics

also learn about Layers, Contexts and drawRect:

A very basic example of a circle:

```<code>class CircleView: UIView {
    override func draw(_ rect: CGRect) {
        guard let context = UIGraphicsGetCurrentContext() else {
            return
        }
        context.addEllipse(in: rect)
        context.setFillColor(.red.cgColor)
        context.fillPath()
    }
}
</code>```

and drawing lines (rects, stars etc.) with UIBezier paths:

```<code>override func drawRect(rect: CGRect) {
      var path = UIBezierPath()
      path.moveToPoint(CGPoint(x:<point x>, y:<point y>))
      path.addLineToPoint(CGPoint(x:<next point x>, y:<next point y>))
      point.closePath()

      UIColor.redColor().set()
      point.stroke()
      point.fill()
}
</code>```

Body:
If you use a UICollectionView, your reusable cell will have the "layer" to draw on.

What to do?

1. Create a UIView subclass and place it inside your reusable cell.

2. Override drawRect(_:) method, you'll do all the drawing inside.

3. Add your shape/line drawing code to drawRect method.

For example use UIBezierPath class for lines, arcs etc. You'll be able to create all sorts of shapes.

You should read the CoreGraphics API Ref:

https://developer.apple.com/reference/coregraphics

also learn about Layers, Contexts and drawRect:

A very basic example of a circle:

class CircleView: UIView {
    override func draw(_ rect: CGRect) {
        guard let context = UIGraphicsGetCurrentContext() else {
            return
        }
        context.addEllipse(in: rect)
        context.setFillColor(.red.cgColor)
        context.fillPath()
    }
}

and drawing lines (rects, stars etc.) with UIBezier paths:

override func drawRect(rect: CGRect) {
      var path = UIBezierPath()
      path.moveToPoint(CGPoint(x:<point x>, y:<point y>))
      path.addLineToPoint(CGPoint(x:<next point x>, y:<next point y>))
      point.closePath()

      UIColor.redColor().set()
      point.stroke()
      point.fill()
}


问:
How to verify openjpa enhancing entities happened successfully
We are enhancing entities at build time in our project. We are getting build successful when running enhancer build. However when we add

```<code>openjpa.RuntimeUnenhancedClasses=unsupported
</code>```

we get an error saying

This configuration disallows runtime optimization, but the following listed types were not enhanced at build time or at class load time
  with a javaagent

and
lists all our entities.
All these things started when we are getting outofmemory(memory leak) error when loading our api's. Using openjpa 1.2.2, java 1.7
Any suggestions?

答:
In your adapter if you are making use of OpenJPA provided by MFP server, and making modifications to it or performing configuration changes, you should not. This OpenJPA layer is used by MFP server for its working and any changes you make to it can cause runtime issues.

You could try packaging your own version of OpenJPA for use within your adapter and do the enhancements there.

Body:
We are enhancing entities at build time in our project. We are getting build successful when running enhancer build. However when we add

openjpa.RuntimeUnenhancedClasses=unsupported

we get an error saying

This configuration disallows runtime optimization, but the following listed types were not enhanced at build time or at class load time
  with a javaagent

and
lists all our entities.
All these things started when we are getting outofmemory(memory leak) error when loading our api's. Using openjpa 1.2.2, java 1.7
Any suggestions?


问:
Identity Server + resource owner credentials + authenticator
I'm working on setting up a new SSO application. I would like to use ASP.NET Identity as a database to store the users data. I have a ReactJs application hosted on Node.JS and a .Net Web Api2 application. I want to protect thsi Web Api 2 using Identity Server with users from its database. In further development I'm going to create a mobile application.
I'm able to create an asp.net identity database with some users and use Resource Owner credentials, but I have couple of questions if anyone could help:

Why is Resource Owner Credentials not recommended? My current workflow is to hit the api with client&user&password and obtain a token which I store in web layer and  use in Web Api requests. Web Api validates the tokens and identify the user. I read on IS page that's not recommended then what's the recommended scenario to authenticate the user?

How can I create an authenticator for mobile? Should I create my own certificate issue, store it in database as a thumbprint and use access token for that?

Thanks

答:
In short, Resource Owner requires the credentials to be passed through the application itself, also RO doesn't give you SSO. Here's a longer answer. The recommended scenario is to use hybrid flow with PKCE enabled.

Look up TOTP. I believe it is implemented in AspNetCore.Identity with some examples.


问:
Yii Framework 2.0 -findModel returns an empty object
I am trying to show the form values which I have stored in the database.But it's not happening and also returning the empty values.I have added whatever I did.

Controller

```<code>protected function findModel($id)
    {
        if (($model = UserRegistration::find($id)->one()) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
</code>```

Model

this is my model.I have declared all variables as public.Is that a problem? If I remove im getting error also.

```<code>class UserRegistration extends ActiveRecord
{
    public $username;
    public $firstname;
    public $lastname;
    public $email;
    public $Country;
    public $State;
    public $City;
    public $phone_number;
    public $about_me;
    public $password;
    public $verify_password;
    public $photo;

    public static function tableName()
    {
        return 'user';
    }

    public function rules()
    {
        return [
            [['username','password', 'email'], 'required'],
            [['status', 'created_at', 'updated_at', 'teespring_id'], 'integer'],
            [['username','lastname','firstname', 'password_hash', 'password_reset_token', 'email','about_me'], 'string', 'max' => 255],
            [['auth_key'], 'string', 'max' => 32],
            [['role'], 'string', 'max' => 10],
            [['email','username'],'email'],
            [['email','username','password_reset_token'], 'unique'],
            ['phone_number','string','length'=>10],
            [['Country','State','City'],'string'],
            ['verify_password','compare','compareAttribute'=>'password'],
            [['photo'],'file', 'extensions' => 'png, jpg']
        ];
    }
}
</code>```

Update: I have tried $model = UserRegistration::findOne($id) also.no luck
Please help me.

答:
Finally i got the solution.I have created two findModel and rendered to the form.

```<code>public function actionProfile(){

            $model      = $this->findModel(Yii::$app->user->identity->id);
            $profile    = $this->findProfileModel(Yii::$app->user->identity->id);
            return $this->render('/userregister/update', [
                'model' => $model,
                'profile'=>$profile,
            ]);
    }
</code>```

Thanks for all.

Body:
I am trying to show the form values which I have stored in the database.But it's not happening and also returning the empty values.I have added whatever I did.

Controller

protected function findModel($id)
    {
        if (($model = UserRegistration::find($id)->one()) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

Model

this is my model.I have declared all variables as public.Is that a problem? If I remove im getting error also.

class UserRegistration extends ActiveRecord
{
    public $username;
    public $firstname;
    public $lastname;
    public $email;
    public $Country;
    public $State;
    public $City;
    public $phone_number;
    public $about_me;
    public $password;
    public $verify_password;
    public $photo;

    public static function tableName()
    {
        return 'user';
    }

    public function rules()
    {
        return [
            [['username','password', 'email'], 'required'],
            [['status', 'created_at', 'updated_at', 'teespring_id'], 'integer'],
            [['username','lastname','firstname', 'password_hash', 'password_reset_token', 'email','about_me'], 'string', 'max' => 255],
            [['auth_key'], 'string', 'max' => 32],
            [['role'], 'string', 'max' => 10],
            [['email','username'],'email'],
            [['email','username','password_reset_token'], 'unique'],
            ['phone_number','string','length'=>10],
            [['Country','State','City'],'string'],
            ['verify_password','compare','compareAttribute'=>'password'],
            [['photo'],'file', 'extensions' => 'png, jpg']
        ];
    }
}

Update: I have tried $model = UserRegistration::findOne($id) also.no luck
Please help me.

Body:
Finally i got the solution.I have created two findModel and rendered to the form.

public function actionProfile(){

            $model      = $this->findModel(Yii::$app->user->identity->id);
            $profile    = $this->findProfileModel(Yii::$app->user->identity->id);
            return $this->render('/userregister/update', [
                'model' => $model,
                'profile'=>$profile,
            ]);
    }

Thanks for all.


问:
css menu naming convention
I'm stuck with a problem. It is good practice to create classnames that are describing. For example, content-nav and widget-area. I've this menu at the top of the site that has the following links:

Home

English (language dependant)

Contact

Sitemap

Terms & conditions

Disclaimer

How would you semantically call such a menu? In previous projects I referred to it as an top-menu, but that name is related to graphical presentation and not good practice in my opinion.

Thanks in advance!

答: I usually go with secondary-navigation or secondary-menu to complement the primary-navigation/primary-menu

ContentLicense: CC BY-SA 2.5

Title: css menu naming convention


问:
error not found: type > and type mismatch play
The following code involves an http request in the play framework. I am including the errors in the code...

```<code>def requestWebservice(drug: String) : String = {
    val drugEntry = "search" -> drug
    var a = 100
    val request = ws.url(apiUrl).withQueryString(apiKey, drugEntry,
    apiLimit, apiSkip).get()
    val jsonresults = Await.result(request, 10 seconds).json
    val countEntries: Int = (jsonresults \ "meta" \ "results" \
    "total").as[Int]
    //error "not found: type >"

    while (countEntries: Int > a) {
    // type mismatch; found : Unit, required: String (countEntries)
        skip = skip + 100;
        request;
        jsonresults;
        a = a + 100;

    }
}
</code>```

I am new to scala and the play framework and I have a problem probably trivial for someone with some experience. I am doing an http request to a web server that returns 100 results at a time. I have tried to point to a number that gives the total of the results so that I can repeat the request with a while loop if the total is more than 100. The structure of the jsonresults is the following

```<code>"meta": {
    "disclaimer": "",
    "terms": "",
    "license": "",
    "last_updated": "",
"results": {
    "skip": 0,
    "limit": 100,
    "total": 1742
}
</code>```

I know that Unit means that nothing comes back and that probably I am not pointing to the right field correctly, but how else could I point to the total? And why do I get the first error, where scala doesn't recognise the operator ">"? I would be grateful for some help.

答:
You need to remove the : Int in the while, as the type of countEntries is automatically inferred - this means the compiler automatically figures out that the type of countEntries is an Int:

while (countEntries > a) {
  ...
}
```

<p>Also, if you want to check the official <code>while</code> specification in Scala, it's here. You can keep the type specification if you want, just make sure you wrap it between braces:</p>

<pre class="lang-scala prettyprint-override"><code>while ((countEntries: Int) > a) {
  ...
}
</code>```

Body:
The following code involves an http request in the play framework. I am including the errors in the code...

def requestWebservice(drug: String) : String = {
    val drugEntry = "search" -> drug
    var a = 100
    val request = ws.url(apiUrl).withQueryString(apiKey, drugEntry,
    apiLimit, apiSkip).get()
    val jsonresults = Await.result(request, 10 seconds).json
    val countEntries: Int = (jsonresults \ "meta" \ "results" \
    "total").as[Int]
    //error "not found: type >"

    while (countEntries: Int > a) {
    // type mismatch; found : Unit, required: String (countEntries)
        skip = skip + 100;
        request;
        jsonresults;
        a = a + 100;

    }
}

I am new to scala and the play framework and I have a problem probably trivial for someone with some experience. I am doing an http request to a web server that returns 100 results at a time. I have tried to point to a number that gives the total of the results so that I can repeat the request with a while loop if the total is more than 100. The structure of the jsonresults is the following

"meta": {
    "disclaimer": "",
    "terms": "",
    "license": "",
    "last_updated": "",
"results": {
    "skip": 0,
    "limit": 100,
    "total": 1742
}

I know that Unit means that nothing comes back and that probably I am not pointing to the right field correctly, but how else could I point to the total? And why do I get the first error, where scala doesn't recognise the operator ">"? I would be grateful for some help.

Body:
You need to remove the : Int in the while, as the type of countEntries is automatically inferred - this means the compiler automatically figures out that the type of countEntries is an Int:

while (countEntries > a) {
  ...
}

Also, if you want to check the official while specification in Scala, it's here. You can keep the type specification if you want, just make sure you wrap it between braces:

while ((countEntries: Int) > a) {
  ...
}


问:
How to do a partial look up in excel and get the data in next column till four rows in VBA
I have  sheet 1 with Column name: Main task

MainTask

And, I have Sheet 2 where the Sub-tasks are given based on the characters between 1st and 2nd hyphen(-) of the Data in Main Task for eg: Under the main task column there is "Pyramid - IoT Forecast - Latin America - Argentina - 2017". So, based on the string " IoT Forecast" the sub tasks are given as in the below image.

Out Put:

Now In sheet 3  I need every title from the main task should be copied and pasted from the Sheet 1 and look for relevant sub tasks and pasted in the next column like the below image.

I have used, Wild cards, partial V-look up with Mid Function but only single sub task is populating. Please help me provide code in VBA.

答:
If you are open to a VBA solution, you may try something like this.
The following code assumes that there are three sheets in the workbook named as "Sheet1", "Sheet2" and "Sheet3".

If the sheet names are different in your original workbook, please change them in the code in following lines before testing the code.

```<code>Set ws1 = Sheets("Sheet1")
Set ws2 = Sheets("Sheet2")
Set ws3 = Sheets("Sheet3")
</code>```

Place the following code on a Standard Module and run the code to get the desired output on Sheet3.

```<code>Sub LookupData()
Dim ws1 As Worksheet, ws2 As Worksheet, ws3 As Worksheet
Dim rng As Range, cell As Range, MainTask As Range
Dim lr2 As Long, lr3 As Long
Dim MainTaskStr As String, wht As String
Application.ScreenUpdating = False
Set ws1 = Sheets("Sheet1")
Set ws2 = Sheets("Sheet2")
Set ws3 = Sheets("Sheet3")
lr2 = ws2.Cells(Rows.Count, 1).End(xlUp).Row
Set rng = ws2.Range("A2:A" & lr2)

ws3.Cells.Clear
ws3.Range("A1:B1").Value = Array("Main Task", "Sub-Task")

If ws2.FilterMode Then ws2.ShowAllData

For Each cell In rng
    If cell.Value <> MainTaskStr Then
        MainTaskStr = cell.Value
        lr3 = ws3.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row + 1
        wht = "- " & cell.Value & " -"
        Set MainTask = ws1.Range("A:A").Find(what:=wht, LookIn:=xlValues, lookat:=xlPart, MatchCase:=False)
        If Not MainTask Is Nothing Then
            With ws2.Rows(1)
                .AutoFilter field:=1, Criteria1:=MainTaskStr
                ws3.Range("A" & lr3) = MainTask.Value
                ws2.Range("B2:B" & lr2).SpecialCells(xlCellTypeVisible).Copy ws3.Range("B" & lr3)
            End With
        End If
    End If
Next cell

If ws2.FilterMode Then ws2.AutoFilterMode = False

ws3.UsedRange.Columns.AutoFit

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

Body:
If you are open to a VBA solution, you may try something like this.
The following code assumes that there are three sheets in the workbook named as "Sheet1", "Sheet2" and "Sheet3".

If the sheet names are different in your original workbook, please change them in the code in following lines before testing the code.

Set ws1 = Sheets("Sheet1")
Set ws2 = Sheets("Sheet2")
Set ws3 = Sheets("Sheet3")

Place the following code on a Standard Module and run the code to get the desired output on Sheet3.

Sub LookupData()
Dim ws1 As Worksheet, ws2 As Worksheet, ws3 As Worksheet
Dim rng As Range, cell As Range, MainTask As Range
Dim lr2 As Long, lr3 As Long
Dim MainTaskStr As String, wht As String
Application.ScreenUpdating = False
Set ws1 = Sheets("Sheet1")
Set ws2 = Sheets("Sheet2")
Set ws3 = Sheets("Sheet3")
lr2 = ws2.Cells(Rows.Count, 1).End(xlUp).Row
Set rng = ws2.Range("A2:A" & lr2)

ws3.Cells.Clear
ws3.Range("A1:B1").Value = Array("Main Task", "Sub-Task")

If ws2.FilterMode Then ws2.ShowAllData

For Each cell In rng
    If cell.Value <> MainTaskStr Then
        MainTaskStr = cell.Value
        lr3 = ws3.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row + 1
        wht = "- " & cell.Value & " -"
        Set MainTask = ws1.Range("A:A").Find(what:=wht, LookIn:=xlValues, lookat:=xlPart, MatchCase:=False)
        If Not MainTask Is Nothing Then
            With ws2.Rows(1)
                .AutoFilter field:=1, Criteria1:=MainTaskStr
                ws3.Range("A" & lr3) = MainTask.Value
                ws2.Range("B2:B" & lr2).SpecialCells(xlCellTypeVisible).Copy ws3.Range("B" & lr3)
            End With
        End If
    End If
Next cell

If ws2.FilterMode Then ws2.AutoFilterMode = False

ws3.UsedRange.Columns.AutoFit

Application.ScreenUpdating = True
End Sub


问:
PouchDB sync not giving a complete event
My PouchDB sync code is not producing a complete event.

I do get change and active and paused events (in that order), and the databases do eventually sync (after a very long wait even though there is not much data).

I need the complete event so I know when the remote CouchDB data is available locally to be used.

My code looks like this:

  init(localDBName, remoteDBName)
  // Initialises the database - Called every time the App starts or the user logs in or registers
  // If remoteDBName is false we don't want to sync data to the server
  {

    // Create a new database or open it if it already exists
    this._DB = new PouchDB(localDBName);
    this.remote = remoteDBName;          // If remoteDBName is false we don't sync data to the server

    console.log('Data: init(): PouchDB database opened for localDBName = ' + localDBName + ' : ' + this._DB + ', remoteDBName = ' + this.remote);

    // Sync to remote DB if we have been asked to
    if (this.remote)
    {
      // Insert the url for the CouchDB server into the remoteDBName returned by PouchDB
      var realRemoteDB = this.remote.replace("localhost:5984", COUCHDB_SERVER_URL);

      console.log('Data: init: remoteDB path being used is: ' + realRemoteDB);

      let options = {
        live: true,
        retry: true,
        continuous: true
      };

      return this._syncHandler = this._DB.sync(realRemoteDB, options)
        .on('complete', (info) => {
          console.log('***** DATA: init() Complete: Handling syncing complete');
          console.dir(info);
        })
        .on('change', (info) => {
          console.log('***** DATA: init() Change: Handling syncing change');
          console.dir(info);
        })
        .on('paused', (info) => {
          console.log('***** DATA: init() Paused: Handling syncing pause');
          console.dir(info);
        })
        .on('active', (info) => {
          console.log('***** DATA: init() Active: Handling syncing resumption');
          console.dir(info);
        })
        .on('error', (err) => {
          console.log('***** DATA: init() Error: Handling syncing error');
          console.dir(err);
        })
        .on('denied', (err) => {
          console.log('***** DATA: init() Denied: Handling syncing denied');
          console.dir(err);
        });
    }
    else {
      this.syncHandler = null;
    }
  }```

The last event I get is the paused event which fires just after change event shows the data has been pulled from the server.

答:
This is actually the way it should work ;)

The sync method behaves differently depending on the options you specify:

Without live option: In a normal syncronisation (without the live option) the complete event will work just as you thought it would: It will trigger once the syncronisation completes.

With live option: In a live replication/synchronisation the syncronisation will never complete as it is continuous. The complete event will only be triggered if the replication is cancelled. See the docs here (I highlighted the important part):

complete (info) - This event fires when replication is completed or cancelled. In a live replication, only cancelling the replication should trigger this event.

To solve your problem you could initially do a synchronisation without the live option. If this synchronisation completes your remote data should be available locally.

Now in the complete event handler, you can start a live replication to start your continuous synchronisation.

The code might look like this:

```<code>this._DB.sync(realRemoteDB) //No options here -> One time sync
        .on('complete', (info) => {
          this._DB.sync(realRemoteDB, options); //Continous sync with options
        });
</code>```

Body:
My PouchDB sync code is not producing a complete event.

I do get change and active and paused events (in that order), and the databases do eventually sync (after a very long wait even though there is not much data).

I need the complete event so I know when the remote CouchDB data is available locally to be used.

My code looks like this:

  init(localDBName, remoteDBName)
  // Initialises the database - Called every time the App starts or the user logs in or registers
  // If remoteDBName is false we don't want to sync data to the server
  {

    // Create a new database or open it if it already exists
    this._DB = new PouchDB(localDBName);
    this.remote = remoteDBName;          // If remoteDBName is false we don't sync data to the server

    console.log('Data: init(): PouchDB database opened for localDBName = ' + localDBName + ' : ' + this._DB + ', remoteDBName = ' + this.remote);

    // Sync to remote DB if we have been asked to
    if (this.remote)
    {
      // Insert the url for the CouchDB server into the remoteDBName returned by PouchDB
      var realRemoteDB = this.remote.replace("localhost:5984", COUCHDB_SERVER_URL);

      console.log('Data: init: remoteDB path being used is: ' + realRemoteDB);

      let options = {
        live: true,
        retry: true,
        continuous: true
      };

      return this._syncHandler = this._DB.sync(realRemoteDB, options)
        .on('complete', (info) => {
          console.log('***** DATA: init() Complete: Handling syncing complete');
          console.dir(info);
        })
        .on('change', (info) => {
          console.log('***** DATA: init() Change: Handling syncing change');
          console.dir(info);
        })
        .on('paused', (info) => {
          console.log('***** DATA: init() Paused: Handling syncing pause');
          console.dir(info);
        })
        .on('active', (info) => {
          console.log('***** DATA: init() Active: Handling syncing resumption');
          console.dir(info);
        })
        .on('error', (err) => {
          console.log('***** DATA: init() Error: Handling syncing error');
          console.dir(err);
        })
        .on('denied', (err) => {
          console.log('***** DATA: init() Denied: Handling syncing denied');
          console.dir(err);
        });
    }
    else {
      this.syncHandler = null;
    }
  }

The last event I get is the paused event which fires just after change event shows the data has been pulled from the server.

Body:
This is actually the way it should work ;)

The sync method behaves differently depending on the options you specify:

Without live option: In a normal syncronisation (without the live option) the complete event will work just as you thought it would: It will trigger once the syncronisation completes.

With live option: In a live replication/synchronisation the syncronisation will never complete as it is continuous. The complete event will only be triggered if the replication is cancelled. See the docs here (I highlighted the important part):

complete (info) - This event fires when replication is completed or cancelled. In a live replication, only cancelling the replication should trigger this event.

To solve your problem you could initially do a synchronisation without the live option. If this synchronisation completes your remote data should be available locally.

Now in the complete event handler, you can start a live replication to start your continuous synchronisation.

The code might look like this:

this._DB.sync(realRemoteDB) //No options here -> One time sync
        .on('complete', (info) => {
          this._DB.sync(realRemoteDB, options); //Continous sync with options
        });

ContentLicense: CC BY-SA 4.0


问:
How to access Google Spreadsheets with a service account credentials?
I have created a server side application in PHP that's supposed to work with Google Spreadsheets.

I'm able to authenticate successfully with OAuth 2.0 authentication, but when requesting the list of the spreadsheets from Google, I only get the spreadsheets shared with the service account by the spreadsheet owner.

Is there a way that service account could retrieve all the spreadsheets owned by my main account not the service one, including those not explicitly shared with the service account?

Also I still want to keep the spreadsheets private so noone can access them without my permission, but I need the service account to have full access to both existing and new spreadsheets.

Any advice is appreciated.

答:
Here is a sample script that uses a service account to read the contents of a Google Spreadsheet's sheet. Have a look at the README for instructions to set it up:

https://github.com/juampynr/google-spreadsheet-reader


问:
How to resolve ambiguous column names when retrieving results?
I have two tables in my database:

NEWS table with columns:

id - the news id

user - the user id of the author)

USERS table with columns:

id - the user id

I want to execute this SQL:

```<code>SELECT * FROM news JOIN users ON news.user = user.id
</code>```

When I get the results in PHP I would like to get associative array and get column names by $row['column-name']. How do I get the news ID and the user ID, having the same column name?

答:
You can set aliases for the columns that you are selecting:</p>

```<code>$query = 'SELECT news.id AS newsId, user.id AS userId, [OTHER FIELDS HERE] FROM news JOIN users ON news.user = user.id'
</code>```

OwnerDisplayName: Dan

Body:
I have two tables in my database:

NEWS table with columns:

id - the news id

user - the user id of the author)

USERS table with columns:

id - the user id

I want to execute this SQL:

SELECT * FROM news JOIN users ON news.user = user.id

When I get the results in PHP I would like to get associative array and get column names by $row['column-name']. How do I get the news ID and the user ID, having the same column name?

LastEditorDisplayName: Dan

Body:
You can set aliases for the columns that you are selecting:

$query = 'SELECT news.id AS newsId, user.id AS userId, [OTHER FIELDS HERE] FROM news JOIN users ON news.user = user.id'

OwnerDisplayName: CMS


问:
MacGDBp, but better?
For debugging php code I use MacGDBp but it has its quirks: it shows only the top frame variables of the stack, it sometimes refuses to display any variable at all and last version has decorates the source text with non ascii characters.
Is there any alternative that is native OS X? (ie. not Eclipse, I can't stand it).

答:
For Linux users - http://protoeditor.sourceforge.net/ has a nice lightweight client for Xdebug which is also available as a plugin for Kate (this is not mentioned on the Xdebug site)

Xdebug also runs happily with XAMPP - if you figure out where to put the compiled .so file ;)

There also is an article describing on how to install Xdebug on Linux w/ XAMPP on the SaniSoft blog: http://www.sanisoft.com/blog/2007/06/23/how-to-install-xdebug-php-extension-for-xampp-on-linux/

Title: MacGDBp, but better?


问:
Set state of BottomSheetDialogFragment to expanded
How do you set the state of a fragment extending BottomSheetDialogFragment to expanded using BottomSheetBehavior#setState(STATE_EXPANDED) using the Android Support Design Library (v23.2.1)?

https://code.google.com/p/android/issues/detail?id=202396 says:

Bottom sheets are set to STATE_COLLAPSED at first. Call BottomSheetBehavior#setState(STATE_EXPANDED) if you want to expand it. Note that you cannot call the method before view layouts.

The suggested practice requires a view to be inflated first, but I'm not sure how I'll set the BottomSheetBehaviour onto a fragment (BottomSheetDialogFragment).

```<code>View bottomSheet = coordinatorLayout.findViewById(R.id.bottom_sheet);
BottomSheetBehavior behavior = BottomSheetBehavior.from(bottomSheet);
</code>```

答:
All results with using onShow() cause random render bug when soft keyboard is displayed. See screenshot bellow - BottomSheet dialog is not at bottom of the screen but is placed like the keyboard was displayed. This problem does not occur always but quite often.

UPDATE

My solution with the reflection of the private members is unnecessary. Using postDelayed (with about 100 ms) for creating and showing dialog after hiding the soft keyboard is a better solution. Then the above solutions with onShow() are ok.

```<code>Utils.hideSoftKeyboard(this);
mView.postDelayed(new Runnable() {
    @Override
    public void run() {
        MyBottomSheetDialog dialog = new MyBottomSheetDialog();
        dialog.setListener(MyActivity.this);
        dialog.show(getSupportFragmentManager(), TAG_BOTTOM_SHEET_DLG);
    }
}, 100);
</code>```

So I implement another solution, but it requires using reflection because BottomSheetDialog has all members as private. But it solves render bugs. BottomSheetDialogFragment class is only AppCompatDialogFragment with onCreateDialog method which create BottomSheetDialog. I create own child of AppCompatDialogFragment which create my class extends BottomSheetDialog and which solves access to private behavior member and set it in onStart method to STATE_EXPANDED state.

```<code>public class ExpandedBottomSheetDialog extends BottomSheetDialog {

    protected BottomSheetBehavior<FrameLayout> mBehavior;

    public ExpandedBottomSheetDialog(@NonNull Context context, @StyleRes int theme) {
        super(context, theme);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        try {
            Field privateField = BottomSheetDialog.class.getDeclaredField("mBehavior");
            privateField.setAccessible(true);
            mBehavior = (BottomSheetBehavior<FrameLayout>) privateField.get(this);
        } catch (NoSuchFieldException e) {
            // do nothing
        } catch (IllegalAccessException e) {
            // do nothing
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (mBehavior != null) {
            mBehavior.setSkipCollapsed(true);
            mBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
        }
    }
}

public class AddAttachmentBottomSheetDialog extends AppCompatDialogFragment {

    ....

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        return new ExpandedBottomSheetDialog(getContext(), getTheme());
    }

    ....
}
</code>```

Body:
How do you set the state of a fragment extending BottomSheetDialogFragment to expanded using BottomSheetBehavior#setState(STATE_EXPANDED) using the Android Support Design Library (v23.2.1)?

https://code.google.com/p/android/issues/detail?id=202396 says:

Bottom sheets are set to STATE_COLLAPSED at first. Call BottomSheetBehavior#setState(STATE_EXPANDED) if you want to expand it. Note that you cannot call the method before view layouts.

The suggested practice requires a view to be inflated first, but I'm not sure how I'll set the BottomSheetBehaviour onto a fragment (BottomSheetDialogFragment).

View bottomSheet = coordinatorLayout.findViewById(R.id.bottom_sheet);
BottomSheetBehavior behavior = BottomSheetBehavior.from(bottomSheet);

Body:
All results with using onShow() cause random render bug when soft keyboard is displayed. See screenshot bellow - BottomSheet dialog is not at bottom of the screen but is placed like the keyboard was displayed. This problem does not occur always but quite often.

UPDATE

My solution with the reflection of the private members is unnecessary. Using postDelayed (with about 100 ms) for creating and showing dialog after hiding the soft keyboard is a better solution. Then the above solutions with onShow() are ok.

Utils.hideSoftKeyboard(this);
mView.postDelayed(new Runnable() {
    @Override
    public void run() {
        MyBottomSheetDialog dialog = new MyBottomSheetDialog();
        dialog.setListener(MyActivity.this);
        dialog.show(getSupportFragmentManager(), TAG_BOTTOM_SHEET_DLG);
    }
}, 100);

So I implement another solution, but it requires using reflection because BottomSheetDialog has all members as private. But it solves render bugs. BottomSheetDialogFragment class is only AppCompatDialogFragment with onCreateDialog method which create BottomSheetDialog. I create own child of AppCompatDialogFragment which create my class extends BottomSheetDialog and which solves access to private behavior member and set it in onStart method to STATE_EXPANDED state.

public class ExpandedBottomSheetDialog extends BottomSheetDialog {

    protected BottomSheetBehavior<FrameLayout> mBehavior;

    public ExpandedBottomSheetDialog(@NonNull Context context, @StyleRes int theme) {
        super(context, theme);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        try {
            Field privateField = BottomSheetDialog.class.getDeclaredField("mBehavior");
            privateField.setAccessible(true);
            mBehavior = (BottomSheetBehavior<FrameLayout>) privateField.get(this);
        } catch (NoSuchFieldException e) {
            // do nothing
        } catch (IllegalAccessException e) {
            // do nothing
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (mBehavior != null) {
            mBehavior.setSkipCollapsed(true);
            mBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
        }
    }
}

public class AddAttachmentBottomSheetDialog extends AppCompatDialogFragment {

    ....

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        return new ExpandedBottomSheetDialog(getContext(), getTheme());
    }

    ....
}


问:
jQuery hasClass Uncaught SyntaxError: Unexpected token )
I got this error in console log but can't determine what's wrong. I would like to hide an element when the button is collapsed </p>

```<code>$(".navbar-toggle").click(function() {
if(".navbar-toggle").hasClass("collapsed")
    $(".country-flags-container").hide();
else
    $(".country-flags-container").show();
)}
</code>```

<p>I appreciate your help for my learnings. </p>

答:
You are using this code :

```<code>if(".navbar-toggle").hasClass("collapsed")
</code>```

and

```<code>".navbar-toggle"
</code>```

is not a selector, also if you use this :

```<code>$(".navbar-toggle")
</code>```

it return an array of elements having class 'navbar-toggle'

try this :

```<code>$(".navbar-toggle").click(function() {
if( $(this).hasClass("collapsed") )
    $(".country-flags-container").hide();
else
    $(".country-flags-container").show();
)}
</code>```

also you have to think about removing the "collapsed" class after checking it, it's a flag ;)

Body:
I got this error in console log but can't determine what's wrong. I would like to hide an element when the button is collapsed

$(".navbar-toggle").click(function() {
if(".navbar-toggle").hasClass("collapsed")
    $(".country-flags-container").hide();
else
    $(".country-flags-container").show();
)}

I appreciate your help for my learnings.

Body:
You are using this code :

if(".navbar-toggle").hasClass("collapsed")

and

".navbar-toggle"

is not a selector, also if you use this :

$(".navbar-toggle")

it return an array of elements having class 'navbar-toggle'

try this :

$(".navbar-toggle").click(function() {
if( $(this).hasClass("collapsed") )
    $(".country-flags-container").hide();
else
    $(".country-flags-container").show();
)}

also you have to think about removing the "collapsed" class after checking it, it's a flag ;)


问:
Getting data periodically from PostgreSQL and sent it to ActiveMQ
Basically, i've a data table in PostgreSQL.
I want to get all the data, and sent it become message to ActiveMQ (1 message for 1 row in table).

But the data table automatically updated every 5 second. So there is some new data in table for every 5 second.

How to sending the new data without double sending the data that was sent?
And i think i must use the Thread.sleep(5000) for made it endless looping?

This all i got:

```<code>package testcode;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

public class ProducerClear2 {

    public static String vardbserver;
    public static String vardbuser;
    public static String vardbpassword;
    public static String vardbname;

    public static void main (String[] args){
        vardbserver = "TestDBtoMQ";
        vardbuser = "postgresql";
        vardbpassword = "admin";

        ConnectionFactory factory = null;
        javax.jms.Connection connection = null;
        Session session = null;
        Destination destination = null;
        MessageProducer producer = null;
        Connection c = null;
        Statement stmt = null;
        try {
            Class.forName("org.postgresql.Driver");
            c = DriverManager.getConnection("jdbc:postgresql://localhost:5432/"+vardbserver, vardbuser, vardbpassword);
            c.setAutoCommit(false);
            System.out.println("----------------------------");

            stmt = c.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT * FROM MESSAGES;");
            while (rs.next()) {
                String  message = rs.getString("MESSAGE");
                System.out.println("Message = " + message);
                try {
                    factory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_BROKER_URL);
                    connection = factory.createConnection();
                    connection.start();
                    session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
                    destination = session.createQueue("TestQueue");
                    producer = session.createProducer(destination);
                    TextMessage mssg = session.createTextMessage(message);
                    System.out.println("Sent: " + mssg.getText());
                    producer.send(mssg);
                }
                catch (JMSException e) {
                    e.printStackTrace();
                }
            }

            rs.close();
            stmt.close();
            c.close();

        }
        catch (Exception e) {
            System.err.println(e.getClass().getName()+": "+ e.getMessage());
        }finally {
            if (session != null) {
                try {
                    session.close();
                } catch (JMSException ex) {
                    // ignore
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (JMSException ex) {
                    // ignore
                }
            }
        }
        System.out.println("----------------------------");
        System.out.println("Message sent successfully");
    }
}
</code>```

The answer check here

答:
In order to fetch only the new data from postgres, you can use the xmin system column on each row that stores the transaction id for that particular row.

```<code>select xmin::varchar::bigint as xrow, * from messages;
</code>```

Then you can keep track of the last transaction fetched so next time you run the query you can use that value as a limit

```<code>select xmin::varchar::bigint as xrow, * from messages
    where xmin::varchar::bigint > :last_transaction_id_from_previous_run;
</code>```

If you are using postgres 9.4 or newer, you have also the possibility to use logical replication in order to stream data directly from the database.

For more information about the logical replication: https://www.postgresql.org/docs/current/static/logicaldecoding.html

Update:

The sample code in the question can be rewritten like this, I excluded everything outside the first try statement for brevity

```<code>// Moved all the setup for the ActiveMQ connection outside the loops
// Otherwise they would create a new connection/sessions for each iteration without being closed
factory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_BROKER_URL);
connection = factory.createConnection();
connection.start();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
destination = session.createQueue("TestQueue");
producer = session.createProducer(destination);

Class.forName("org.postgresql.Driver");
System.out.println("----------------------------");

// Made a try-with-resources block in order to auto close everything in case of failure, no need to remember to close them manually.
// Using prepared statements so that the query itself doesn't have to be parsed for each iteration
try (Connection c = DriverManager.getConnection("jdbc:postgresql://localhost:5432/" + vardbserver, vardbuser, vardbpassword);
     PreparedStatement stmt = c.prepareStatement("SELECT * FROM MESSAGES where xmin::varchar::bigint > ? and xmin::varchar::bigint < ? ");
     PreparedStatement max = c.prepareStatement("select max(xmin::varchar::bigint) as txid from messages")
) {
    c.setAutoCommit(false);

    // Keep track of the previous and next transaction id in order to provide windowed results
    Long previousTxId = 0L;
    Long nextTxId = 0L;

    while (true) { // Enter an infinite loop
        stmt.clearParameters(); // Remove any set parameters in the fetch query

        // Fetch the next transaction id by executing the prepared statement in max
        try (ResultSet rs = max.executeQuery()) {
            if (rs.next()) {
                nextTxId = rs.getLong(1);
            }
        }

        // Set the window in the messages query.
        // Since the query has already been prepared, we only need to set the parameters
        stmt.setLong(1, previousTxId);
        stmt.setLong(2, nextTxId + 1);

        // Execute the statment fetching all messages that were created between previousTxId and nextTxId
        try (ResultSet rs = stmt.executeQuery()) {
            while (rs.next()) {
                String message = rs.getString("MESSAGE");
                System.out.println("Message = " + message);
                TextMessage mssg = session.createTextMessage(message);
                System.out.println("Sent: " + mssg.getText());
                producer.send(mssg);
            }
            // Update previousTxId for the next iteration
            previousTxId = nextTxId;
        }
        Thread.sleep(5000);
    }
}
</code>```

Body:
Basically, i've a data table in PostgreSQL.
I want to get all the data, and sent it become message to ActiveMQ (1 message for 1 row in table).

But the data table automatically updated every 5 second. So there is some new data in table for every 5 second.

How to sending the new data without double sending the data that was sent?
And i think i must use the Thread.sleep(5000) for made it endless looping?

This all i got:

package testcode;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

public class ProducerClear2 {

    public static String vardbserver;
    public static String vardbuser;
    public static String vardbpassword;
    public static String vardbname;

    public static void main (String[] args){
        vardbserver = "TestDBtoMQ";
        vardbuser = "postgresql";
        vardbpassword = "admin";

        ConnectionFactory factory = null;
        javax.jms.Connection connection = null;
        Session session = null;
        Destination destination = null;
        MessageProducer producer = null;
        Connection c = null;
        Statement stmt = null;
        try {
            Class.forName("org.postgresql.Driver");
            c = DriverManager.getConnection("jdbc:postgresql://localhost:5432/"+vardbserver, vardbuser, vardbpassword);
            c.setAutoCommit(false);
            System.out.println("----------------------------");

            stmt = c.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT * FROM MESSAGES;");
            while (rs.next()) {
                String  message = rs.getString("MESSAGE");
                System.out.println("Message = " + message);
                try {
                    factory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_BROKER_URL);
                    connection = factory.createConnection();
                    connection.start();
                    session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
                    destination = session.createQueue("TestQueue");
                    producer = session.createProducer(destination);
                    TextMessage mssg = session.createTextMessage(message);
                    System.out.println("Sent: " + mssg.getText());
                    producer.send(mssg);
                }
                catch (JMSException e) {
                    e.printStackTrace();
                }
            }

            rs.close();
            stmt.close();
            c.close();

        }
        catch (Exception e) {
            System.err.println(e.getClass().getName()+": "+ e.getMessage());
        }finally {
            if (session != null) {
                try {
                    session.close();
                } catch (JMSException ex) {
                    // ignore
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (JMSException ex) {
                    // ignore
                }
            }
        }
        System.out.println("----------------------------");
        System.out.println("Message sent successfully");
    }
}

The answer check here

Body:
In order to fetch only the new data from postgres, you can use the xmin system column on each row that stores the transaction id for that particular row.

select xmin::varchar::bigint as xrow, * from messages;

Then you can keep track of the last transaction fetched so next time you run the query you can use that value as a limit

select xmin::varchar::bigint as xrow, * from messages
    where xmin::varchar::bigint > :last_transaction_id_from_previous_run;

If you are using postgres 9.4 or newer, you have also the possibility to use logical replication in order to stream data directly from the database.

For more information about the logical replication: https://www.postgresql.org/docs/current/static/logicaldecoding.html

Update:

The sample code in the question can be rewritten like this, I excluded everything outside the first try statement for brevity

// Moved all the setup for the ActiveMQ connection outside the loops
// Otherwise they would create a new connection/sessions for each iteration without being closed
factory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_BROKER_URL);
connection = factory.createConnection();
connection.start();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
destination = session.createQueue("TestQueue");
producer = session.createProducer(destination);

Class.forName("org.postgresql.Driver");
System.out.println("----------------------------");

// Made a try-with-resources block in order to auto close everything in case of failure, no need to remember to close them manually.
// Using prepared statements so that the query itself doesn't have to be parsed for each iteration
try (Connection c = DriverManager.getConnection("jdbc:postgresql://localhost:5432/" + vardbserver, vardbuser, vardbpassword);
     PreparedStatement stmt = c.prepareStatement("SELECT * FROM MESSAGES where xmin::varchar::bigint > ? and xmin::varchar::bigint < ? ");
     PreparedStatement max = c.prepareStatement("select max(xmin::varchar::bigint) as txid from messages")
) {
    c.setAutoCommit(false);

    // Keep track of the previous and next transaction id in order to provide windowed results
    Long previousTxId = 0L;
    Long nextTxId = 0L;

    while (true) { // Enter an infinite loop
        stmt.clearParameters(); // Remove any set parameters in the fetch query

        // Fetch the next transaction id by executing the prepared statement in max
        try (ResultSet rs = max.executeQuery()) {
            if (rs.next()) {
                nextTxId = rs.getLong(1);
            }
        }

        // Set the window in the messages query.
        // Since the query has already been prepared, we only need to set the parameters
        stmt.setLong(1, previousTxId);
        stmt.setLong(2, nextTxId + 1);

        // Execute the statment fetching all messages that were created between previousTxId and nextTxId
        try (ResultSet rs = stmt.executeQuery()) {
            while (rs.next()) {
                String message = rs.getString("MESSAGE");
                System.out.println("Message = " + message);
                TextMessage mssg = session.createTextMessage(message);
                System.out.println("Sent: " + mssg.getText());
                producer.send(mssg);
            }
            // Update previousTxId for the next iteration
            previousTxId = nextTxId;
        }
        Thread.sleep(5000);
    }
}


问:
Faking logins with Laravel Auth
On our service there's admins and other users. I'm using the basic Laravel Auth package for handling registrations, logins etc.

What would be the best way to implement a feature, where an admin user could "fake login" as a regular user, without knowing the actual user's password?

答:
This should work:</p>

```<code>Auth::loginUsingId($userId, true);
</code>```

Title: Faking logins with Laravel Auth

Body:
This should work:

Auth::loginUsingId($userId, true);


问:
Access to functions from extended classes
I have a parent class and two classes that are extending it. The question is how to call a function from one extended class that is in other extended class?

code is below:

```<code>    // PARENT CLASS
class Controller {
    function __construct() {
        try {
            $this->db = new Database(); // WORKS FINE
        } catch (PDOException $e) {
            die('Database connection could not be established.');
        }
    }
}
class Api extends Controller {
    function __construct() {
        parent::__construct();
    }
    function RenderForm() {
        // from here I want to call function that is inside Forms class
    }
}

class Forms extends Controller {
    function __construct() {
        parent::__construct();
    }
    function ReturnForm() {
        $this->db->query("SOME QUERY");

        // code here builds a form for output and stores it as $HTML;

        return $HTML;

    }
}
</code>```

答:
You'll have to make an instance of the forms class like so:

```<code>class Api extends Controller {

    function RenderForm() {
       $form = new Forms(); //Create instance of your forms class
       $form->ReturnForm(); //Use function from your forms class

    }
}
</code>```

Body:
I have a parent class and two classes that are extending it. The question is how to call a function from one extended class that is in other extended class?

code is below:

    // PARENT CLASS
class Controller {
    function __construct() {
        try {
            $this->db = new Database(); // WORKS FINE
        } catch (PDOException $e) {
            die('Database connection could not be established.');
        }
    }
}
class Api extends Controller {
    function __construct() {
        parent::__construct();
    }
    function RenderForm() {
        // from here I want to call function that is inside Forms class
    }
}

class Forms extends Controller {
    function __construct() {
        parent::__construct();
    }
    function ReturnForm() {
        $this->db->query("SOME QUERY");

        // code here builds a form for output and stores it as $HTML;

        return $HTML;

    }
}

Body:
You'll have to make an instance of the forms class like so:

class Api extends Controller {

    function RenderForm() {
       $form = new Forms(); //Create instance of your forms class
       $form->ReturnForm(); //Use function from your forms class

    }
}


问:
Pass arguments in ruby method
I want to send 2 params from CLI when I start rake task. I tried this code:

```<code>namespace :tnx do

  require_relative "transactions.rb"
  include Cnp_transactions_modes

  task :generate, [:clean_all] => [:environment]  do |t, args|

    if args[: clean_all] == 'true'
      // something
    end

    if args[:times].empty?
      Cnp_transactions_modes.create_transactions(args[:times])
    end
  end
end
</code>```

But I get error:

```<code>rake aborted!
NoMethodError: undefined method `empty?' for nil:NilClass
</code>```

How I can solve this Issue?

答:
The error comes from the fact that if args[:times] is nil, empty? cannot be called on args[:times] because empty? isn't defined for nil object. In Rails, you could use blank? to check if it's nil or empty.

This should be enough :

```<code>if args[:times]
</code>```

You don't need to check if args[:times] is empty, you need to check it's defined.

Note that it's the opposite of your condition, but it's probably more logical that way.

Title: Pass arguments in ruby method

Body:
I want to send 2 params from CLI when I start rake task. I tried this code:

namespace :tnx do

  require_relative "transactions.rb"
  include Cnp_transactions_modes

  task :generate, [:clean_all] => [:environment]  do |t, args|

    if args[: clean_all] == 'true'
      // something
    end

    if args[:times].empty?
      Cnp_transactions_modes.create_transactions(args[:times])
    end
  end
end

But I get error:

rake aborted!
NoMethodError: undefined method `empty?' for nil:NilClass

How I can solve this Issue?

Body:
The error comes from the fact that if args[:times] is nil, empty? cannot be called on args[:times] because empty? isn't defined for nil object. In Rails, you could use blank? to check if it's nil or empty.

This should be enough :

if args[:times]

You don't need to check if args[:times] is empty, you need to check it's defined.

Note that it's the opposite of your condition, but it's probably more logical that way.


问:
How to show and close plot in matplitlib.pyplot?
I have a real-time updating pandas dataframe with two columns of coordinates. I want to use geopandas to insert a shapefile map in jupyter notebook as a background, and plot the real time coordinates in the map in every 5 seconds, without closing and opening the background map every time. Here are the simplified codes.

```<code>geo_data.plot(alpha=0,figsize=(12, 12))

plt.ion()
while True:
    plt.figure()
    for i in range(len(paths)):
        plt.plot(paths.ix[i:i+1,'z'],paths.ix[i:i+1,'x'])
    plt.show()
    time.sleep(5)
    plt.close()
</code>```

However the "close" doesn't work. It plots one graph after one. I also tried to change the places of "ion", "show", "sleep" and "close" in and out side the "while" loop. None of them is working.

In a word, the geopandas map should be static in the plot. And the real-time coordinates data refreshes on top of the map every five seconds.

答: Try plt.clf() instead of plt.close(). It keeps the plot open but clears it so it can be used for a new plot.</p>

Body:
I have a real-time updating pandas dataframe with two columns of coordinates. I want to use geopandas to insert a shapefile map in jupyter notebook as a background, and plot the real time coordinates in the map in every 5 seconds, without closing and opening the background map every time. Here are the simplified codes.

geo_data.plot(alpha=0,figsize=(12, 12))

plt.ion()
while True:
    plt.figure()
    for i in range(len(paths)):
        plt.plot(paths.ix[i:i+1,'z'],paths.ix[i:i+1,'x'])
    plt.show()
    time.sleep(5)
    plt.close()

However the "close" doesn't work. It plots one graph after one. I also tried to change the places of "ion", "show", "sleep" and "close" in and out side the "while" loop. None of them is working.

In a word, the geopandas map should be static in the plot. And the real-time coordinates data refreshes on top of the map every five seconds.


问:
PHP convert Array to Object
var_dump($response);

outputs:

```<code> array(1) { ["metafields"]=> array(1) { [13]=> array(10) { ["id"]=> int(32616923206) ["namespace"]=> string(7) "ly26638" } } }
 array(1) { ["metafields"]=> array(1) { [13]=> array(10) { ["id"]=> int(32641864774) ["namespace"]=> string(7) "ly26638" } } }
</code>```

how can I convert $response to an object to operate it like in the following code:

```<code>echo $response->metafields[0]->id;
</code>```

I've tried the code below, but without any result :/

```<code>$object = json_decode(json_encode($response));
</code>```

答:
If you want to access your "metafields's id" like $response->metafields[13][id] then you need to cast your response array to object.

Ex.

```<code>$response = (object) array(
    'metafields' => array(
            '13' => (object) array(
                    'id' => 32616923206,
                    'namespace' => "ly26638"
                )
        )
);
</code>```

Then you can use syntax like $response->metafields[13]->id to access the "id" value.

Title: PHP convert Array to Object

Body:
var_dump($response);

outputs:

 array(1) { ["metafields"]=> array(1) { [13]=> array(10) { ["id"]=> int(32616923206) ["namespace"]=> string(7) "ly26638" } } }
 array(1) { ["metafields"]=> array(1) { [13]=> array(10) { ["id"]=> int(32641864774) ["namespace"]=> string(7) "ly26638" } } }

how can I convert $response to an object to operate it like in the following code:

echo $response->metafields[0]->id;

I've tried the code below, but without any result :/

$object = json_decode(json_encode($response));

Body:
If you want to access your "metafields's id" like $response->metafields[13][id] then you need to cast your response array to object.

Ex.

$response = (object) array(
    'metafields' => array(
            '13' => (object) array(
                    'id' => 32616923206,
                    'namespace' => "ly26638"
                )
        )
);

Then you can use syntax like $response->metafields[13]->id to access the "id" value.


问:
Rails controller caching when using docker container (dev)
I have docker running an app container (rails app) and a db container running postgres

I have volume mounted my local working directory to my app container so I can work locally and the changes reflected in the app container.

In doing this everything seems to work fine except I seem to get some strange caching behaviour on my controllers

for example

route:

```<code>get '/something', to: 'something#show'
</code>```

controller

```<code>class SomethingController < ApplicationController
    def show
        render text: "Hello 1"
    end
end
</code>```

When I go to myapp/something I get Hello 1 perfect!

Then I edit my controller to:

```<code>class SomethingController < ApplicationController
    def show
        render text: "Hello 2"
    end
end
</code>```

When I go to myapp/something I still get Hello 1?

If I return a html view, it updates just fine, so why is my changes in my controller not being reflected?

The only way I can get these changes to reflect is by making a change in my routes file and saving, this seems to refresh whatever is being cached.

note: I am not caching in the browser, I have caching turned off and Im doing a hard reload each time.

Can anyone shed any light on this? Im trying to follow this tutorial: https://www.youtube.com/watch?v=NEdDa3Zqu7s&list=PLbG4OyfwIxjEe5Y3hQCiQjYnSgRH051iJ&index=3

Thanks

答:
How did you define your development.rb?

Make sure you have the caching options set to false:

```<code>config.reload_classes_only_on_change = false
config.cache_classes = false
</code>```

If this doesn't work you might want to read the Rails docs about caching:
http://guides.rubyonrails.org/caching_with_rails.html

Body:
I have docker running an app container (rails app) and a db container running postgres

I have volume mounted my local working directory to my app container so I can work locally and the changes reflected in the app container.

In doing this everything seems to work fine except I seem to get some strange caching behaviour on my controllers

for example

route:

get '/something', to: 'something#show'

controller

class SomethingController < ApplicationController
    def show
        render text: "Hello 1"
    end
end

When I go to myapp/something I get Hello 1 perfect!

Then I edit my controller to:

class SomethingController < ApplicationController
    def show
        render text: "Hello 2"
    end
end

When I go to myapp/something I still get Hello 1?

If I return a html view, it updates just fine, so why is my changes in my controller not being reflected?

The only way I can get these changes to reflect is by making a change in my routes file and saving, this seems to refresh whatever is being cached.

note: I am not caching in the browser, I have caching turned off and Im doing a hard reload each time.

Can anyone shed any light on this? Im trying to follow this tutorial: https://www.youtube.com/watch?v=NEdDa3Zqu7s&list=PLbG4OyfwIxjEe5Y3hQCiQjYnSgRH051iJ&index=3

Thanks

Body:
How did you define your development.rb?

Make sure you have the caching options set to false:

config.reload_classes_only_on_change = false
config.cache_classes = false

If this doesn't work you might want to read the Rails docs about caching:
http://guides.rubyonrails.org/caching_with_rails.html


问:
Why this url pattern is not working?
```<code>from views import login
from django.conf.urls.defaults import *

urlpatterns = patterns('',
  ***  (r'([a-zA-Z0-9]+)/login/$', login, name='login'),

)
</code>```

showing me the syntax error in line ***.

http://localhost:8000/{{ slug }}/login/ is the action url in form. I want to make it using Django { % url slug login % } tag. But it also not working.

答:
tuple literals don't have named arguments. Try url() instead.

```<code>    url(r'([a-zA-Z0-9]+)/login/$', login, name='login'),
</code>```

Title: Why this url pattern is not working?

Body:
from views import login
from django.conf.urls.defaults import *

urlpatterns = patterns('',
  ***  (r'([a-zA-Z0-9]+)/login/$', login, name='login'),

)

showing me the syntax error in line ***.

http://localhost:8000/{{ slug }}/login/ is the action url in form. I want to make it using Django { % url slug login % } tag. But it also not working.

Body:
tuple literals don't have named arguments. Try url() instead.

    url(r'([a-zA-Z0-9]+)/login/$', login, name='login'),


答:
Because you are missing brackets for if condition. You also missed $ from (".navbar-toggle"). This should be $(".navbar-toggle"). Please try the following:

```<code>$(".navbar-toggle").click(function() {
   if($(".navbar-toggle").hasClass("collapsed")){
      $(".country-flags-container").hide();
   }
   else{
      $(".country-flags-container").show();
   }
});
</code>```

You can replace $(".navbar-toggle").hasClass("collapsed") by the following as well:

```<code>$(this).hasClass("collapsed")
</code>```

Title: jQuery hasClass Uncaught SyntaxError: Unexpected token )

Body:
Because you are missing brackets for if condition. You also missed $ from (".navbar-toggle"). This should be $(".navbar-toggle"). Please try the following:

$(".navbar-toggle").click(function() {
   if($(".navbar-toggle").hasClass("collapsed")){
      $(".country-flags-container").hide();
   }
   else{
      $(".country-flags-container").show();
   }
});

You can replace $(".navbar-toggle").hasClass("collapsed") by the following as well:

$(this).hasClass("collapsed")


问:
Spring Boot Application deployment on remote server
I have a Java Spring Boot Application, and I build it with Maven. With
spring-boot-maven-plugin,

I can create fat, executable jar file.

Then I copy it to the remote server and run. But sometimes,

I change only one line or event one word in my code and I had to do whole build/copy step again. I'm sure that I'm doing it wrong, but I couldn't find another way that more efficient (Like capistrano in Rails).

At this point, I'm planning to clone source code to server, push from local, pull from remote, build and run approach. What is the correct (or elegant) way of doing this deployment?

答: For automatic build and deployment process (continuous integration), you can use Jenkins. Refer this documentation for more details: https://jenkins.io/doc/


问:
Oracle : Error while Extracting Year and Month from TimeStamp
I have time stamp values such as 30/05/06 11:40:34.000000000 AM in the column. I need to extract Year (i.e. 2006) and the month (i.e. 05) from this value. Below is my SQL.

```<code>SELECT EXTRACT(YEAR FROM TO_DATE('19/10/09 10:45:44.000000000 AM')) FROM DUAL;
</code>```

After running above SQL, I get an error APPROVED_PROPOSALS.

So, I tried to provide the format as below,

```<code>SELECT EXTRACT(YEAR FROM TO_DATE('19/10/09 10:45:44.000000000 AM','HH12:MI:SS.FF')) FROM DUAL;
</code>```

However, still getting some errors. I am pretty sure that, the format I am providing is not correct.

ORA-01821: date format not recognized

Please help me, to get Year and Month form such values.

Kiran.

答:
Thank you guys. It was a great help, appreciate it . I used the following queries,

Get year :

select EXTRACT(YEAR FROM(TO_DATE(TO_CHAR(TO_TIMESTAMP
('15/10/09 11:07:28.999900 AM', 'DD/YY/MM HH:MI:SS.FF a.m.'),'DD/YY/MM HH24:MI:SS'),
'DD/YY/MM HH24:MI:SS'))) DT
FROM DUAL;

Month

select EXTRACT(MONTH FROM(TO_DATE(TO_CHAR(TO_TIMESTAMP
('15/10/09 11:07:28.999900 AM', 'DD/YY/MM HH:MI:SS.FF a.m.'),'DD/YY/MM HH24:MI:SS'),
'DD/YY/MM HH24:MI:SS'))) DT
FROM DUAL;

Body:
I have time stamp values such as 30/05/06 11:40:34.000000000 AM in the column. I need to extract Year (i.e. 2006) and the month (i.e. 05) from this value. Below is my SQL.

SELECT EXTRACT(YEAR FROM TO_DATE('19/10/09 10:45:44.000000000 AM')) FROM DUAL;

After running above SQL, I get an error APPROVED_PROPOSALS.

So, I tried to provide the format as below,

SELECT EXTRACT(YEAR FROM TO_DATE('19/10/09 10:45:44.000000000 AM','HH12:MI:SS.FF')) FROM DUAL;

However, still getting some errors. I am pretty sure that, the format I am providing is not correct.

ORA-01821: date format not recognized

Please help me, to get Year and Month form such values.

Kiran.


问:
Translate detected rectangle from portrait CIImage to landscape CIImage
I am modifying code found here. In the code we are capturing video from the phone camera using AVCaptureSession and using CIDetector to detect a rectangle in the image feed. The feed has an image which is 640x842  (iphone5 in portrait). We then do an overlay on the image so the user can see the detected rectangle (actually it's a trapezoid most of the time).

When the user presses a button on the UI, we capture an image from the video and re-run the rectangle detection on this larger image (3264x2448) which as you can see is landscape. We then do a perspective transform on the detected rectangle and crop on the image.

This is working pretty well but the issue I have is say 1 out of 5 captures the detected rectangle on the larger image is different to the one detected (and presented to the user) from the smaller image. Even though I only capture when I detect the phone is (relatively) still, the final image then does not represent the rectangle the user expected.

To resolve this my idea is to use the coordinates of the originally captured rectangle and translate them to a rectangle on the captured still image. This is where I'm struggling.

I tried this with the detected rectangle:

```<code>CGFloat radians = -90 * (M_PI/180);
CGAffineTransform rotation = CGAffineTransformMakeRotation(radians);

CGRect rect = CGRectMake(detectedRect.bounds.origin.x, detectedRect.bounds.origin.y, detectedRect.bounds.size.width, detectedRect.bounds.size.height);

CGRect rotatedRect = CGRectApplyAffineTransform(rect, rotation);
</code>```

So given a detected rect:

TopLeft: 88.213425, 632.31329
TopRight: 545.59302, 632.15546
BottomRight: 575.57819, 369.22321
BottomLeft: 49.973862, 369.40466

I now have this rotated rect:

origin = (x = 369.223206, y = -575.578186)
size = (width = 263.090088, height = 525.604309)

How do I translate the rotated rectangle coordinates in the smaller portrait image to coordinates to the 3264x2448 image?

Edit
Duh.. reading my own approach realised that creating a rectangle out of a trapezoid will not solve my problem!

Supporting code to detect the rectangle etc...

```<code>// In this method we detect a rect from the video feed and overlay

-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection
{
    CVPixelBufferRef pixelBuffer = (CVPixelBufferRef)CMSampleBufferGetImageBuffer(sampleBuffer);

    CIImage *image = [CIImage imageWithCVPixelBuffer:pixelBuffer];

   // image is 640x852 on iphone5

    NSArray *rects = [[CIDetector detectorOfType:CIDetectorTypeRectangle context:nil options:@{CIDetectorAccuracy : CIDetectorAccuracyHigh}] featuresInImage:image];

    CIRectangleFeature *detectedRect = rects[0];

    // draw overlay on image code....
}
</code>```

This is a summarized version of how the still image is obtained:

```<code>// code block to handle output from AVCaptureStillImageOutput
[self.stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler: ^(CMSampleBufferRef imageSampleBuffer, NSError *error)
     {
         NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageSampleBuffer];
         CIImage *enhancedImage = [[CIImage alloc] initWithData:imageData options:@{kCIImageColorSpace:[NSNull null]}];
             imageData = nil;

         CIRectangleFeature *rectangleFeature = [self getDetectedRect:[[self highAccuracyRectangleDetector] featuresInImage:enhancedImage]];

         if (rectangleFeature) {
             enhancedImage = [self   correctPerspectiveForImage:enhancedImage withTopLeft:rectangleFeature.topLeft andTopRight:rectangleFeature.topRight andBottomRight:rectangleFeature.bottomRight andBottomLeft:rectangleFeature.bottomLeft];
         }
    }
</code>```

Thank you.

答:
I had the same issue while doing this kind of stuff.I have resolved it by doing below code in swift. Take a look if it can help you. </p>

```<code> if let videoConnection = stillImageOutput.connection(withMediaType: AVMediaTypeVideo) {
            stillImageOutput.captureStillImageAsynchronously(from: videoConnection) {
                (imageDataSampleBuffer, error) -> Void in
                let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer)
                var img = UIImage(data: imageData!)!

                let outputRect = self.previewLayer?.metadataOutputRectOfInterest(for: (self.previewLayer?.bounds)!)
                let takenCGImage = img.cgImage
                let width = (takenCGImage?.width)!
                let height = (takenCGImage?.height)!
                let cropRect = CGRect(x: (outputRect?.origin.x)! * CGFloat(width), y: (outputRect?.origin.y)! * CGFloat(height), width: (outputRect?.size.width)! * CGFloat(width), height: (outputRect?.size.height)! * CGFloat(height))
                let cropCGImage = takenCGImage!.cropping(to: cropRect)
                img = UIImage(cgImage: cropCGImage!, scale: 1, orientation: img.imageOrientation)

                let cropViewController = TOCropViewController(image: self.cropToBounds(image: img))
                cropViewController.delegate = self
                self.navigationController?.pushViewController(cropViewController, animated: true)
            }
        }
</code>```

Body:
I am modifying code found here. In the code we are capturing video from the phone camera using AVCaptureSession and using CIDetector to detect a rectangle in the image feed. The feed has an image which is 640x842  (iphone5 in portrait). We then do an overlay on the image so the user can see the detected rectangle (actually it's a trapezoid most of the time).

When the user presses a button on the UI, we capture an image from the video and re-run the rectangle detection on this larger image (3264x2448) which as you can see is landscape. We then do a perspective transform on the detected rectangle and crop on the image.

This is working pretty well but the issue I have is say 1 out of 5 captures the detected rectangle on the larger image is different to the one detected (and presented to the user) from the smaller image. Even though I only capture when I detect the phone is (relatively) still, the final image then does not represent the rectangle the user expected.

To resolve this my idea is to use the coordinates of the originally captured rectangle and translate them to a rectangle on the captured still image. This is where I'm struggling.

I tried this with the detected rectangle:

CGFloat radians = -90 * (M_PI/180);
CGAffineTransform rotation = CGAffineTransformMakeRotation(radians);

CGRect rect = CGRectMake(detectedRect.bounds.origin.x, detectedRect.bounds.origin.y, detectedRect.bounds.size.width, detectedRect.bounds.size.height);

CGRect rotatedRect = CGRectApplyAffineTransform(rect, rotation);

So given a detected rect:

TopLeft: 88.213425, 632.31329
TopRight: 545.59302, 632.15546
BottomRight: 575.57819, 369.22321
BottomLeft: 49.973862, 369.40466

I now have this rotated rect:

origin = (x = 369.223206, y = -575.578186)
size = (width = 263.090088, height = 525.604309)

How do I translate the rotated rectangle coordinates in the smaller portrait image to coordinates to the 3264x2448 image?

Edit
Duh.. reading my own approach realised that creating a rectangle out of a trapezoid will not solve my problem!

Supporting code to detect the rectangle etc...

// In this method we detect a rect from the video feed and overlay

-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection
{
    CVPixelBufferRef pixelBuffer = (CVPixelBufferRef)CMSampleBufferGetImageBuffer(sampleBuffer);

    CIImage *image = [CIImage imageWithCVPixelBuffer:pixelBuffer];

   // image is 640x852 on iphone5

    NSArray *rects = [[CIDetector detectorOfType:CIDetectorTypeRectangle context:nil options:@{CIDetectorAccuracy : CIDetectorAccuracyHigh}] featuresInImage:image];

    CIRectangleFeature *detectedRect = rects[0];

    // draw overlay on image code....
}

This is a summarized version of how the still image is obtained:

// code block to handle output from AVCaptureStillImageOutput
[self.stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler: ^(CMSampleBufferRef imageSampleBuffer, NSError *error)
     {
         NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageSampleBuffer];
         CIImage *enhancedImage = [[CIImage alloc] initWithData:imageData options:@{kCIImageColorSpace:[NSNull null]}];
             imageData = nil;

         CIRectangleFeature *rectangleFeature = [self getDetectedRect:[[self highAccuracyRectangleDetector] featuresInImage:enhancedImage]];

         if (rectangleFeature) {
             enhancedImage = [self   correctPerspectiveForImage:enhancedImage withTopLeft:rectangleFeature.topLeft andTopRight:rectangleFeature.topRight andBottomRight:rectangleFeature.bottomRight andBottomLeft:rectangleFeature.bottomLeft];
         }
    }

Thank you.

Body:
I had the same issue while doing this kind of stuff.I have resolved it by doing below code in swift. Take a look if it can help you.

 if let videoConnection = stillImageOutput.connection(withMediaType: AVMediaTypeVideo) {
            stillImageOutput.captureStillImageAsynchronously(from: videoConnection) {
                (imageDataSampleBuffer, error) -> Void in
                let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer)
                var img = UIImage(data: imageData!)!

                let outputRect = self.previewLayer?.metadataOutputRectOfInterest(for: (self.previewLayer?.bounds)!)
                let takenCGImage = img.cgImage
                let width = (takenCGImage?.width)!
                let height = (takenCGImage?.height)!
                let cropRect = CGRect(x: (outputRect?.origin.x)! * CGFloat(width), y: (outputRect?.origin.y)! * CGFloat(height), width: (outputRect?.size.width)! * CGFloat(width), height: (outputRect?.size.height)! * CGFloat(height))
                let cropCGImage = takenCGImage!.cropping(to: cropRect)
                img = UIImage(cgImage: cropCGImage!, scale: 1, orientation: img.imageOrientation)

                let cropViewController = TOCropViewController(image: self.cropToBounds(image: img))
                cropViewController.delegate = self
                self.navigationController?.pushViewController(cropViewController, animated: true)
            }
        }