问:
Program that tracks mouse coordinates and allows to draw lines in a window
The program should do the following:

Open a window. Get the Location of the mouse in the Window (x and y coordinates) and set these as the title of the window.

If you click and hold the left mouse button you should be able to draw a line.

The problem is when I run the program no. 1 works, but not no. 2. Upon resizing the Window the coordinates freeze, but I can draw lines.

Hope someone can help with this.

```<code>import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Point;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main extends JPanel {

    private Point lastPoint;

    public Main() {
        addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                lastPoint = new Point(e.getX(), e.getY());
            }
        });
        addMouseMotionListener(new MouseMotionAdapter() {
            public void mouseDragged(MouseEvent e) {
                Graphics g = getGraphics();
                g.drawLine(lastPoint.x, lastPoint.y, e.getX(), e.getY());
                lastPoint = new Point(e.getX(), e.getY());
                g.dispose();
            }
        });
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(800, 600);
        frame.setResizable(true);
        frame.setVisible(true);
        frame.getContentPane().add(new Main(), BorderLayout.CENTER);
        frame.addMouseMotionListener(new MouseMotionAdapter() {
            public void mouseMoved(MouseEvent e) {
                int x = e.getX();
                int y = e.getY();
                String xstring = String.valueOf(x);
                String ystring = String.valueOf(y);
                frame.setTitle(xstring + ", " +  ystring);
        }
        });
        }

}
</code>```

答:
Several things here :

When you want to customize the painting of a Component, override its paintComponent method, don't attempt to get its Graphics object with getGraphics.

Use repaint() to have your Component be repainted (i.e paintComponent will get called) .

Make your JFrame visible only once all the other components have been added.

Here is how your code could be changed:

```<code>import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main extends JPanel {

    private Point lastPoint = new Point();
    private Point currentPoint = new Point();

    public Main() {
        addMouseListener(new MouseAdapter() {
            public void mousePressed(final MouseEvent e) {
                lastPoint = new Point(e.getX(), e.getY());
            }
        });
        addMouseMotionListener(new MouseMotionAdapter() {
            public void mouseDragged(final MouseEvent e) {

                currentPoint = new Point(e.getX(), e.getY());
                repaint();

            }
        });
    }

    @Override
    public void paintComponent(final Graphics g) {

        super.paintComponent(g);

        g.drawLine(lastPoint.x, lastPoint.y, currentPoint.x, currentPoint.y);

    }

    public static void main(final String[] args) {
        // TODO Auto-generated method stub
        final JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(800, 600);
        frame.setResizable(true);

        frame.getContentPane().add(new Main(), BorderLayout.CENTER);
        frame.addMouseMotionListener(new MouseMotionAdapter() {
            public void mouseMoved(final MouseEvent e) {
                int x = e.getX();
                int y = e.getY();
                String xstring = String.valueOf(x);
                String ystring = String.valueOf(y);
                frame.setTitle(xstring + ", " + ystring);
            }
        });
        frame.setVisible(true);
    }

}
</code>```

Body:
The program should do the following:

Open a window. Get the Location of the mouse in the Window (x and y coordinates) and set these as the title of the window.

If you click and hold the left mouse button you should be able to draw a line.

The problem is when I run the program no. 1 works, but not no. 2. Upon resizing the Window the coordinates freeze, but I can draw lines.

Hope someone can help with this.

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Point;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main extends JPanel {

    private Point lastPoint;

    public Main() {
        addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                lastPoint = new Point(e.getX(), e.getY());
            }
        });
        addMouseMotionListener(new MouseMotionAdapter() {
            public void mouseDragged(MouseEvent e) {
                Graphics g = getGraphics();
                g.drawLine(lastPoint.x, lastPoint.y, e.getX(), e.getY());
                lastPoint = new Point(e.getX(), e.getY());
                g.dispose();
            }
        });
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(800, 600);
        frame.setResizable(true);
        frame.setVisible(true);
        frame.getContentPane().add(new Main(), BorderLayout.CENTER);
        frame.addMouseMotionListener(new MouseMotionAdapter() {
            public void mouseMoved(MouseEvent e) {
                int x = e.getX();
                int y = e.getY();
                String xstring = String.valueOf(x);
                String ystring = String.valueOf(y);
                frame.setTitle(xstring + ", " +  ystring);
        }
        });
        }

}

Body:
Several things here :

When you want to customize the painting of a Component, override its paintComponent method, don't attempt to get its Graphics object with getGraphics.

Use repaint() to have your Component be repainted (i.e paintComponent will get called) .

Make your JFrame visible only once all the other components have been added.

Here is how your code could be changed:

import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main extends JPanel {

    private Point lastPoint = new Point();
    private Point currentPoint = new Point();

    public Main() {
        addMouseListener(new MouseAdapter() {
            public void mousePressed(final MouseEvent e) {
                lastPoint = new Point(e.getX(), e.getY());
            }
        });
        addMouseMotionListener(new MouseMotionAdapter() {
            public void mouseDragged(final MouseEvent e) {

                currentPoint = new Point(e.getX(), e.getY());
                repaint();

            }
        });
    }

    @Override
    public void paintComponent(final Graphics g) {

        super.paintComponent(g);

        g.drawLine(lastPoint.x, lastPoint.y, currentPoint.x, currentPoint.y);

    }

    public static void main(final String[] args) {
        // TODO Auto-generated method stub
        final JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(800, 600);
        frame.setResizable(true);

        frame.getContentPane().add(new Main(), BorderLayout.CENTER);
        frame.addMouseMotionListener(new MouseMotionAdapter() {
            public void mouseMoved(final MouseEvent e) {
                int x = e.getX();
                int y = e.getY();
                String xstring = String.valueOf(x);
                String ystring = String.valueOf(y);
                frame.setTitle(xstring + ", " + ystring);
            }
        });
        frame.setVisible(true);
    }

}


来源: stackexchange

问:
How to guarantee message queue/order in Erlang?
If one server receives multiple requests from one process by using pid ! Msg, but the process time for each request is different, then how to guarantee the sender receives the reply in order?</p>

答:
From the Erlang FAQ:

10.8  Is the order of message reception guaranteed?

Yes, but only within one process.

If there is a live process and you send it message A and then message B, it's guaranteed that if message B arrived, message A arrived before it.

On the other hand, imagine processes P, Q and R. P sends message A to Q, and then message B to R. There is no guarantee that A arrives before B. (Distributed Erlang would have a pretty tough time if this was required!)

That is, if the server processes the requests in the order they arrive, and sends the responses in the order the requests were processed, then the sender will receive the responses in order.

ContentLicense: CC BY-SA 3.0


问:
AWS cloudformation : how to properly create a redis cache cluster
I want to create an elasticache instance using redis.

I think that I should use it "cluster mode disabled" because everything will fit into one server.
In order to not have a SPOF, I want to create a read replica that will be promoted by AWS in case of a failure of the master.
If possible, it would be great to balance the read only operations between master and slave, but it is not mandatory.

I created a functioning master/read-replica using the aws console then used cloudformer to create the cloudformation json conf. Cloudformer has created me two unlinked  AWS::ElastiCache::CacheCluster, but by reading the doc. I don't understand how to link them... For now I have this configuration :

```<code>{
    "cachehubcache001": {
      "Type": "AWS::ElastiCache::CacheCluster",
      "Properties": {
        "AutoMinorVersionUpgrade": "true",
        "AZMode": "single-az",
        "CacheNodeType": "cache.t2.small",
        "Engine": "redis",
        "EngineVersion": "3.2.4",
        "NumCacheNodes": "1",
        "PreferredAvailabilityZone": { "Fn::FindInMap" : [ "RegionMap", { "Ref" : "AWS::Region" }, "Az1B"]},
        "PreferredMaintenanceWindow": "sun:04:00-sun:05:00",
        "CacheSubnetGroupName": {
          "Ref": "cachesubnethubprivatecachesubnetgroup"
        },
        "VpcSecurityGroupIds": [
          {
            "Fn::GetAtt": [
              "sgiHubCacheSG",
              "GroupId"
            ]
          }
        ]
      }
    },
    "cachehubcache002": {
      "Type": "AWS::ElastiCache::CacheCluster",
      "Properties": {
        "AutoMinorVersionUpgrade": "true",
        "AZMode": "single-az",
        "CacheNodeType": "cache.t2.small",
        "Engine": "redis",
        "EngineVersion": "3.2.4",
        "NumCacheNodes": "1",
        "PreferredAvailabilityZone": { "Fn::FindInMap" : [ "RegionMap", { "Ref" : "AWS::Region" }, "Az1A"]},
        "PreferredMaintenanceWindow": "sun:02:00-sun:03:00",
        "CacheSubnetGroupName": {
          "Ref": "cachesubnethubprivatecachesubnetgroup"
        },
        "VpcSecurityGroupIds": [
          {
            "Fn::GetAtt": [
              "sgiHubCacheSG",
              "GroupId"
            ]
          }
        ]
      }
    },
}
</code>```

I know that it is wrong, but I can't figure out how to create a correct replica. I can't understand the AWS doc, for a start I can't figure out wich Type I should use between :

http://docs.aws.amazon.com/fr_fr/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html

http://docs.aws.amazon.com/fr_fr/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-cache-cluster.html

Since cloudformer created AWS::ElastiCache::CacheCluster I'll go with it, but I've got the feeling that it should have created only one resource, and used the NumCacheNodes parameter in order to create two resources.

redis can't use :

NumCacheNodes

AZMode and PreferredAvailabilityZones

so I don't know how to make this solution multi-AZ...

答:
I managed to do this using AWS::ElastiCache::ReplicationGroup, the NumCacheClusters parameter provide the possibility to have numerous servers. Beware : it seem that you have to handle the connection to master/slave yourself (but in case of a master's failure, aws should normally detect it and change the dns of a slave to permit you point do not change your configuration). here is a sample :

```<code>"hubElastiCacheReplicationGroup" : {
      "Type" : "AWS::ElastiCache::ReplicationGroup",
      "Properties" : {
        "ReplicationGroupDescription" : "Hub WebServer redis cache cluster",
        "AutomaticFailoverEnabled" : "false",
        "AutoMinorVersionUpgrade" : "true",
        "CacheNodeType" : "cache.t2.small",
        "CacheParameterGroupName" : "default.redis3.2",
        "CacheSubnetGroupName" :  { "Ref": "cachesubnethubprivatecachesubnetgroup" },
        "Engine" : "redis",
        "EngineVersion" : "3.2.4",
        "NumCacheClusters" : { "Ref" : "ElasticacheRedisNumCacheClusters" },
        "PreferredMaintenanceWindow" : "sun:04:00-sun:05:00",
        "SecurityGroupIds" : [ { "Fn::GetAtt": ["sgHubCacheSG",  "GroupId"] } ]
      }
    },
</code>```

Body:
I want to create an elasticache instance using redis.

I think that I should use it "cluster mode disabled" because everything will fit into one server.
In order to not have a SPOF, I want to create a read replica that will be promoted by AWS in case of a failure of the master.
If possible, it would be great to balance the read only operations between master and slave, but it is not mandatory.

I created a functioning master/read-replica using the aws console then used cloudformer to create the cloudformation json conf. Cloudformer has created me two unlinked  AWS::ElastiCache::CacheCluster, but by reading the doc. I don't understand how to link them... For now I have this configuration :

{
    "cachehubcache001": {
      "Type": "AWS::ElastiCache::CacheCluster",
      "Properties": {
        "AutoMinorVersionUpgrade": "true",
        "AZMode": "single-az",
        "CacheNodeType": "cache.t2.small",
        "Engine": "redis",
        "EngineVersion": "3.2.4",
        "NumCacheNodes": "1",
        "PreferredAvailabilityZone": { "Fn::FindInMap" : [ "RegionMap", { "Ref" : "AWS::Region" }, "Az1B"]},
        "PreferredMaintenanceWindow": "sun:04:00-sun:05:00",
        "CacheSubnetGroupName": {
          "Ref": "cachesubnethubprivatecachesubnetgroup"
        },
        "VpcSecurityGroupIds": [
          {
            "Fn::GetAtt": [
              "sgiHubCacheSG",
              "GroupId"
            ]
          }
        ]
      }
    },
    "cachehubcache002": {
      "Type": "AWS::ElastiCache::CacheCluster",
      "Properties": {
        "AutoMinorVersionUpgrade": "true",
        "AZMode": "single-az",
        "CacheNodeType": "cache.t2.small",
        "Engine": "redis",
        "EngineVersion": "3.2.4",
        "NumCacheNodes": "1",
        "PreferredAvailabilityZone": { "Fn::FindInMap" : [ "RegionMap", { "Ref" : "AWS::Region" }, "Az1A"]},
        "PreferredMaintenanceWindow": "sun:02:00-sun:03:00",
        "CacheSubnetGroupName": {
          "Ref": "cachesubnethubprivatecachesubnetgroup"
        },
        "VpcSecurityGroupIds": [
          {
            "Fn::GetAtt": [
              "sgiHubCacheSG",
              "GroupId"
            ]
          }
        ]
      }
    },
}

I know that it is wrong, but I can't figure out how to create a correct replica. I can't understand the AWS doc, for a start I can't figure out wich Type I should use between :

http://docs.aws.amazon.com/fr_fr/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html

http://docs.aws.amazon.com/fr_fr/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-cache-cluster.html

Since cloudformer created AWS::ElastiCache::CacheCluster I'll go with it, but I've got the feeling that it should have created only one resource, and used the NumCacheNodes parameter in order to create two resources.

redis can't use :

NumCacheNodes

AZMode and PreferredAvailabilityZones

so I don't know how to make this solution multi-AZ...

Body:
I managed to do this using AWS::ElastiCache::ReplicationGroup, the NumCacheClusters parameter provide the possibility to have numerous servers. Beware : it seem that you have to handle the connection to master/slave yourself (but in case of a master's failure, aws should normally detect it and change the dns of a slave to permit you point do not change your configuration). here is a sample :

"hubElastiCacheReplicationGroup" : {
      "Type" : "AWS::ElastiCache::ReplicationGroup",
      "Properties" : {
        "ReplicationGroupDescription" : "Hub WebServer redis cache cluster",
        "AutomaticFailoverEnabled" : "false",
        "AutoMinorVersionUpgrade" : "true",
        "CacheNodeType" : "cache.t2.small",
        "CacheParameterGroupName" : "default.redis3.2",
        "CacheSubnetGroupName" :  { "Ref": "cachesubnethubprivatecachesubnetgroup" },
        "Engine" : "redis",
        "EngineVersion" : "3.2.4",
        "NumCacheClusters" : { "Ref" : "ElasticacheRedisNumCacheClusters" },
        "PreferredMaintenanceWindow" : "sun:04:00-sun:05:00",
        "SecurityGroupIds" : [ { "Fn::GetAtt": ["sgHubCacheSG",  "GroupId"] } ]
      }
    },

ContentLicense: CC BY-SA 4.0


问:
Parse HTML string in Angular 2 and extract and update values
I just started working on an Angular project but am a bit stuck. I have a component that receives an HTML string from a (trusted) external source. I want to extract and update values from this string, and dispay it in my component.

Now displaying the string is easily done with the following code:

```<code><div [innerHTML]="displayString"></div>
</code>```

My input string has some  elements with the data-card-text element attached as identifier. Is it possible to extract this value, and update it whenever my component wants?

Example:
let displayString:string = "<svg><text data-card-text>Value I want to update</text></svg>"

Are operations like these even possible in Angular 2?

答:
In you component you can just define variable displayString as a public and then you can use it in html

```<code>public displayString:string = "<svg><text data-card-text>Value I want to update</text></svg>";
</code>```

Body:
I just started working on an Angular project but am a bit stuck. I have a component that receives an HTML string from a (trusted) external source. I want to extract and update values from this string, and dispay it in my component.

Now displaying the string is easily done with the following code:

My input string has some  elements with the data-card-text element attached as identifier. Is it possible to extract this value, and update it whenever my component wants?

Example:
let displayString:string = "<svg><text data-card-text>Value I want to update</text></svg>"

Are operations like these even possible in Angular 2?

Body:
In you component you can just define variable displayString as a public and then you can use it in html

public displayString:string = "<svg><text data-card-text>Value I want to update</text></svg>";


问:
How to update a docker swarm service with no replication with zero downtime?
I want to update docker swarm service without down-time. The problem is that I don't have enough resources to have service replication. Is there anyway to do this?</p>

答:
The type of deploy you want to do is called blue-green deployment. I recommend following the steps of this blog to do it.

https://technologyconversations.com/2017/01/31/blue-green-deployments-with-docker-services-running-inside-a-swarm-cluster/


问:
Solr join for multiple collection with each collection have multiple shards
I have two collections:

CollectionOne with two shards (shard1, shard2) have id, name, and Address fields

CollectionTwo with shards (shard1,shard2) have c_id, code, and State fields.

I want the result from two collection on id=c_id base using join.

Please provide me full help! I am using Solr version 6.1.0.

答:
https://wiki.apache.org/solr/DistributedSearch - Distributed Search doesn't support join.
So SolrCloud can do join only when index is not splited to shards.</p>


问:
SQL returning aggregated results from one table as a column in a query
Say I have the following setup

```<code>---Posts---
|id
|Title
-----------

---Comments---
|id
|postid
|comment
-----------
</code>```

Some Mock Data

```<code>Posts
ID        Title
1         Hello World
2         Good Bye
3         Pepsi

Comments
ID      postid      comment
 1        1         comment 1
 2        2         comment 2
 3        2         comment 3
</code>```

I want to return back the Title from the Posts table and all the comments related to it via the id in the comments Table.

Something like.

```<code>Title           Comment
Hello World     comment1
Good Bye        comment2
                comment3
Pepsi           null
</code>```

Is this possible just using SQL?

答:
SELECT posts.title, comments.comment
FROM posts JOIN comments ON posts.id = comments.postid</p>

ContentLicense: CC BY-SA 2.5

Body:
Say I have the following setup

---Posts---
|id
|Title
-----------

---Comments---
|id
|postid
|comment
-----------

Some Mock Data

Posts
ID        Title
1         Hello World
2         Good Bye
3         Pepsi

Comments
ID      postid      comment
 1        1         comment 1
 2        2         comment 2
 3        2         comment 3

I want to return back the Title from the Posts table and all the comments related to it via the id in the comments Table.

Something like.

Title           Comment
Hello World     comment1
Good Bye        comment2
                comment3
Pepsi           null

Is this possible just using SQL?


问:
How to select integer from an object?
I know it's probably a dumb question but I'm unable to go over this.

I have this Object array which looks like this

```<code>stdClass Object
(
[1] => stdClass Object
    (
        [Product] => Brand Manual
        [Type] => Custom
        [Width_(inches)] => 11
        [Depth_(inches)] => 8.5
        [Color_Type] => B/W
        [Artistic_Discretion] => Full Artistic Discretion(AD3)
        [Brief/Instructions] => edasd
         Product Dimension - 8.5" x 11"

        [Copy_Translation] => No
        [Additional_Versions] => 0
    )
 )
</code>```

I want the Brand Manual so I do this $myValue = $myObject->1->Product; It doesn't work. The integer '1' seems to be the problem. I tried adding quotes too but it doesn't work either.Please help.

答:
If your object variable is not cast from an array, you can access such properties with curly brace syntax.

```<code>$myObject->{'1'}->Product;
</code>```

I strongly reconmend you read this great post

Title: How to select integer from an object?

Body:
I know it's probably a dumb question but I'm unable to go over this.

I have this Object array which looks like this

stdClass Object
(
[1] => stdClass Object
    (
        [Product] => Brand Manual
        [Type] => Custom
        [Width_(inches)] => 11
        [Depth_(inches)] => 8.5
        [Color_Type] => B/W
        [Artistic_Discretion] => Full Artistic Discretion(AD3)
        [Brief/Instructions] => edasd
         Product Dimension - 8.5" x 11"

        [Copy_Translation] => No
        [Additional_Versions] => 0
    )
 )

I want the Brand Manual so I do this $myValue = $myObject->1->Product; It doesn't work. The integer '1' seems to be the problem. I tried adding quotes too but it doesn't work either.Please help.

Body:
If your object variable is not cast from an array, you can access such properties with curly brace syntax.

$myObject->{'1'}->Product;

I strongly reconmend you read this great post


问:
How to customize android picker button in react native
I'm trying to implement picker inside my app, everything is ok with IOS, but with android it show the button that open the picker like this :

and I can't customize the button style ( I want it to be like below ).

So how to change the button style, I can't find any thing in the official documentation.

答:
You can use native base to customize the button style

Refer the below link
http://nativebase.io/docs/v0.5.2/customize#themeButton


问:
Can Python's Tkinter show both text and image in a Button widget?
For practice, I am using Python's Tkinter to copy/recreate the "Options" section of another software's GUI. This is my model GUI:

At this juncture, I have coded as follows:

```<code>import tkinter as tk
import tkinter.ttk as ttk
import random
from PIL import Image, ImageTk

class Options(tk.Frame):

    def __init__(self, parent):

        random_numbers = lambda: [random.random() for i in range(4)]
        text_font_icon = r"D:\Dropbox\coding\python\experiments\6 - tkinter\icons\icon_mail.gif"

        labelframe_general     = tk.LabelFrame(parent, text="General")
        labelframe_general.pack()

        tk.Label(labelframe_general, text="Startup tab", justify=tk.LEFT).grid(column=0, row=0, sticky=tk.W)
        ttk.OptionMenu(labelframe_general, tk.StringVar(), random_numbers()[0], *random_numbers()).grid(column=1, row=0)

        tk.Label(labelframe_general, text="Episode display format", justify=tk.LEFT).grid(column=0, row=1, sticky=tk.W)
        ttk.OptionMenu(labelframe_general, tk.StringVar(), random_numbers()[0], *random_numbers()).grid(column=1, row=1)

        tk.Label(labelframe_general, text="Number of banner images to\ndownload per series", justify=tk.LEFT).grid(column=0, row=2, sticky=tk.W)
        ttk.OptionMenu(labelframe_general, tk.StringVar(), random_numbers()[0], *random_numbers()).grid(column=1, row=2)

        tk.Checkbutton(labelframe_general, text="Automatically scroll episode list to bottom", variable=tk.StringVar()).grid(column=0, row=3, columnspan=2, sticky=tk.W)
        tk.Checkbutton(labelframe_general, text='Move "The" to the end of series name', variable=tk.StringVar()).grid(column=0, row=4, columnspan=2, sticky=tk.W)
        tk.Checkbutton(labelframe_general, text="Close epCheck with the <Esc> key", variable=tk.StringVar()).grid(column=0, row=5, columnspan=2, sticky=tk.W)

        _photo = tk.PhotoImage(file=text_font_icon)
        b = ttk.Button(labelframe_general, text="List & Overview font (right-click for default", image=_photo)
        b.image = _photo
        b.grid(sticky=tk.NSEW, columnspan=2)

class Gui(tk.Tk):

    def __init__(self):

        super().__init__()
        Options(self)

        self.bind('<Escape>', lambda event: self.destroy())

gui = Gui()
gui.mainloop()[![enter image description here][2]][2]
</code>```

The above produces this:

My problem lies only with ttk.Button (all the other widgets are behaving as I expect them to).

The Button only shows the icon, but does not state the text "List & Overview font". My questions:

Why has the text disappeared from the the Button when an image is used?

Can Tkinter display an icon together with, or next to, texts in Buttons (like in the model GUI above)?

Are Tkinter 'toolbars' or widgets able to display icons together with text, or am I constrained to choose text-only Buttons and Image-only buttons?

I have experimented with Menubutton and tested code from other sources, but to no avail. Would appreciate the help.

答:
You need to specify a value for compound option of ttk.Button.

If you provide both image and text options, the compound option
  specifies the position of the image relative to the text. The value
  may be tk.TOP (image above text), tk.BOTTOM (image below text),
  tk.LEFT (image to the left of the text), or tk.RIGHT (image to the
  right of the text).

When you provide both image and text options but don't specify a
  compound option, the image will appear and the text will not.

Body:
For practice, I am using Python's Tkinter to copy/recreate the "Options" section of another software's GUI. This is my model GUI:

At this juncture, I have coded as follows:

import tkinter as tk
import tkinter.ttk as ttk
import random
from PIL import Image, ImageTk

class Options(tk.Frame):

    def __init__(self, parent):

        random_numbers = lambda: [random.random() for i in range(4)]
        text_font_icon = r"D:\Dropbox\coding\python\experiments\6 - tkinter\icons\icon_mail.gif"

        labelframe_general     = tk.LabelFrame(parent, text="General")
        labelframe_general.pack()

        tk.Label(labelframe_general, text="Startup tab", justify=tk.LEFT).grid(column=0, row=0, sticky=tk.W)
        ttk.OptionMenu(labelframe_general, tk.StringVar(), random_numbers()[0], *random_numbers()).grid(column=1, row=0)

        tk.Label(labelframe_general, text="Episode display format", justify=tk.LEFT).grid(column=0, row=1, sticky=tk.W)
        ttk.OptionMenu(labelframe_general, tk.StringVar(), random_numbers()[0], *random_numbers()).grid(column=1, row=1)

        tk.Label(labelframe_general, text="Number of banner images to\ndownload per series", justify=tk.LEFT).grid(column=0, row=2, sticky=tk.W)
        ttk.OptionMenu(labelframe_general, tk.StringVar(), random_numbers()[0], *random_numbers()).grid(column=1, row=2)

        tk.Checkbutton(labelframe_general, text="Automatically scroll episode list to bottom", variable=tk.StringVar()).grid(column=0, row=3, columnspan=2, sticky=tk.W)
        tk.Checkbutton(labelframe_general, text='Move "The" to the end of series name', variable=tk.StringVar()).grid(column=0, row=4, columnspan=2, sticky=tk.W)
        tk.Checkbutton(labelframe_general, text="Close epCheck with the <Esc> key", variable=tk.StringVar()).grid(column=0, row=5, columnspan=2, sticky=tk.W)

        _photo = tk.PhotoImage(file=text_font_icon)
        b = ttk.Button(labelframe_general, text="List & Overview font (right-click for default", image=_photo)
        b.image = _photo
        b.grid(sticky=tk.NSEW, columnspan=2)

class Gui(tk.Tk):

    def __init__(self):

        super().__init__()
        Options(self)

        self.bind('<Escape>', lambda event: self.destroy())

gui = Gui()
gui.mainloop()[![enter image description here][2]][2]

The above produces this:

My problem lies only with ttk.Button (all the other widgets are behaving as I expect them to).

The Button only shows the icon, but does not state the text "List & Overview font". My questions:

Why has the text disappeared from the the Button when an image is used?

Can Tkinter display an icon together with, or next to, texts in Buttons (like in the model GUI above)?

Are Tkinter 'toolbars' or widgets able to display icons together with text, or am I constrained to choose text-only Buttons and Image-only buttons?

I have experimented with Menubutton and tested code from other sources, but to no avail. Would appreciate the help.


问:
Cannot convert value of type NSAttributedString.DocumentAttributeKey to .DocumentReadingOptionKey
I found this string extension somewhere on SO that allows me to turn html code into an attributed string:

```<code>func html2AttributedString() -> NSAttributedString {
    return try! NSAttributedString(data: self.data(using: String.Encoding.unicode, allowLossyConversion: true)!, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
}
</code>```

It worked fine in Swift 3, but with Swift 4, Xcode complains:

Cannot convert value of type 'NSAttributedString.DocumentAttributeKey' to expected dictionary key type 'NSAttributedString.DocumentReadingOptionKey'

How do I fix this?

答:
You need to pass one of the available NSAttributedString DocumentType options:

Hypertext Markup Language (HTML) document.

```<code>static let html: NSAttributedString.DocumentType
</code>```

Plain text document.

```<code>static let plain: NSAttributedString.DocumentType
</code>```

Rich text format document.

```<code>static let rtf: NSAttributedString.DocumentType
</code>```

Rich text format with attachments document.

```<code>static let rtfd: NSAttributedString.DocumentType
</code>```

In this case you will need to pass the first one (html)  NSAttributedString.DocumentType.html

So the extension updated to Swift 4 should look like this:

```<code>extension NSAttributedString {
    convenience init(data: Data, documentType: DocumentType, encoding: String.Encoding = .utf8) throws {
        try self.init(data: data,
                      options: [.documentType: documentType,
                                .characterEncoding: encoding.rawValue],
                      documentAttributes: nil)
    }
    convenience init(html data: Data) throws {
        try self.init(data: data, documentType: .html)
    }
    convenience init(txt data: Data) throws {
        try self.init(data: data, documentType: .plain)
    }
    convenience init(rtf data: Data) throws {
        try self.init(data: data, documentType: .rtf)
    }
    convenience init(rtfd data: Data) throws {
        try self.init(data: data, documentType: .rtfd)
    }
}
</code>```

```<code>extension StringProtocol {
    var data: Data { return Data(utf8) }
    var htmlToAttributedString: NSAttributedString? {
        do {
            return try .init(html: data)
        } catch {
            print("html error:", error)
            return nil
        }
    }
    var htmlDataToString: String? {
        return htmlToAttributedString?.string
    }
}
</code>```

```<code>extension Data {
    var htmlToAttributedString: NSAttributedString? {
        do {
            return try .init(html: self)
        } catch {
            print("html error:", error)
            return nil
        }

    }
}
</code>```

Playground Testing

```<code>let htmlString = "<style type=\"text/css\">#red{color:#F00}#green{color:#0F0}#blue{color: #00F; font-weight: Bold; font-size: 32}</style><span id=\"red\" >Red</span><span id=\"green\" > Green </span><span id=\"blue\">Blue</span>"

let htmlData = Data(htmlString.utf8)

htmlString.htmlToAttributedString
htmlData.htmlToAttributedString
</code>```

Discussion The HTML importer should not be called from a background
  thread (that is, the options dictionary includes documentType with a
  value of html). It will try to synchronize with the main thread, fail,
  and time out. Calling it from the main thread works (but can still
  time out if the HTML contains references to external resources, which
  should be avoided at all costs). The HTML import mechanism is meant
  for implementing something like markdown (that is, text styles,
  colors, and so on), not for general HTML import

Body:
I found this string extension somewhere on SO that allows me to turn html code into an attributed string:

func html2AttributedString() -> NSAttributedString {
    return try! NSAttributedString(data: self.data(using: String.Encoding.unicode, allowLossyConversion: true)!, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
}

It worked fine in Swift 3, but with Swift 4, Xcode complains:

Cannot convert value of type 'NSAttributedString.DocumentAttributeKey' to expected dictionary key type 'NSAttributedString.DocumentReadingOptionKey'

How do I fix this?

Body:
You need to pass one of the available NSAttributedString DocumentType options:

Hypertext Markup Language (HTML) document.

static let html: NSAttributedString.DocumentType

Plain text document.

static let plain: NSAttributedString.DocumentType

Rich text format document.

static let rtf: NSAttributedString.DocumentType

Rich text format with attachments document.

static let rtfd: NSAttributedString.DocumentType

In this case you will need to pass the first one (html)  NSAttributedString.DocumentType.html

So the extension updated to Swift 4 should look like this:

extension NSAttributedString {
    convenience init(data: Data, documentType: DocumentType, encoding: String.Encoding = .utf8) throws {
        try self.init(data: data,
                      options: [.documentType: documentType,
                                .characterEncoding: encoding.rawValue],
                      documentAttributes: nil)
    }
    convenience init(html data: Data) throws {
        try self.init(data: data, documentType: .html)
    }
    convenience init(txt data: Data) throws {
        try self.init(data: data, documentType: .plain)
    }
    convenience init(rtf data: Data) throws {
        try self.init(data: data, documentType: .rtf)
    }
    convenience init(rtfd data: Data) throws {
        try self.init(data: data, documentType: .rtfd)
    }
}

extension StringProtocol {
    var data: Data { return Data(utf8) }
    var htmlToAttributedString: NSAttributedString? {
        do {
            return try .init(html: data)
        } catch {
            print("html error:", error)
            return nil
        }
    }
    var htmlDataToString: String? {
        return htmlToAttributedString?.string
    }
}

extension Data {
    var htmlToAttributedString: NSAttributedString? {
        do {
            return try .init(html: self)
        } catch {
            print("html error:", error)
            return nil
        }

    }
}

Playground Testing

let htmlString = "<style type=\"text/css\">#red{color:#F00}#green{color:#0F0}#blue{color: #00F; font-weight: Bold; font-size: 32}</style><span id=\"red\" >Red</span><span id=\"green\" > Green </span><span id=\"blue\">Blue</span>"

let htmlData = Data(htmlString.utf8)

htmlString.htmlToAttributedString
htmlData.htmlToAttributedString

Discussion The HTML importer should not be called from a background
  thread (that is, the options dictionary includes documentType with a
  value of html). It will try to synchronize with the main thread, fail,
  and time out. Calling it from the main thread works (but can still
  time out if the HTML contains references to external resources, which
  should be avoided at all costs). The HTML import mechanism is meant
  for implementing something like markdown (that is, text styles,
  colors, and so on), not for general HTML import


问:
Dynamic Linq Expression for IEnumerable<int>.contains(MemberExpression)
I want to create an expression using the Linq Expression tree to simulate this:

```<code>List<int> ids = new List<int>();

// Fill ids with data

db.Where(a => ids.Contains(a.Id));
</code>```

This is where I have gotten, but I am still missing something:

```<code>MemberExpression me = Expression.Property(pe, typeof(T).GetProperty(property));

Expression callContains = Expression.Call(typeof(System.Linq.Enumerable), "Contains", new Type[] { me.Type }, me);
</code>```

How can I do what I want to do properly?

答:
In complementary of @p-s-w-g answer, the DynamicNotContains is :

```<code>    public static IQueryable<T> DynamicNotContains<T, TProperty>(this IQueryable<T> query, string property, IEnumerable<TProperty> items)
    {
        var pe = Expression.Parameter(typeof(T));
        var me = Expression.Property(pe, property);
        var ce = Expression.Constant(items);
        var call = Expression.Call(typeof(Enumerable), "Contains", new[] { me.Type }, ce, me);
        var lambda = Expression.Lambda<Func<T, bool>>(Expression.Not(call), pe);

        return query.Where(lambda);
    }
db.DynamicNotContains("Id", ids);
</code>```

Body:
I want to create an expression using the Linq Expression tree to simulate this:

List<int> ids = new List<int>();

// Fill ids with data

db.Where(a => ids.Contains(a.Id));

This is where I have gotten, but I am still missing something:

MemberExpression me = Expression.Property(pe, typeof(T).GetProperty(property));

Expression callContains = Expression.Call(typeof(System.Linq.Enumerable), "Contains", new Type[] { me.Type }, me);

How can I do what I want to do properly?

Body:
In complementary of @p-s-w-g answer, the DynamicNotContains is :

    public static IQueryable<T> DynamicNotContains<T, TProperty>(this IQueryable<T> query, string property, IEnumerable<TProperty> items)
    {
        var pe = Expression.Parameter(typeof(T));
        var me = Expression.Property(pe, property);
        var ce = Expression.Constant(items);
        var call = Expression.Call(typeof(Enumerable), "Contains", new[] { me.Type }, ce, me);
        var lambda = Expression.Lambda<Func<T, bool>>(Expression.Not(call), pe);

        return query.Where(lambda);
    }
db.DynamicNotContains("Id", ids);


问:
Strip the last hyphen(-) from phone number
Strip the last hyphen(-) from phone number

I want 647-484-3839 to become 647-4843839

```<code>var phoneNumberInput = "647-484-3839";

var newStr = phoneNumberInput .replace(/[^-]+-$/,"");
</code>```

答:
You can:</p>

```<code>var pos = phoneNumberInput.lastIndexOf("-");
phoneNumberInput = phoneNumberInput.substr(0, pos) + phoneNumberInput.substr(pos + 1);
</code>```

Body:
Strip the last hyphen(-) from phone number

I want 647-484-3839 to become 647-4843839

var phoneNumberInput = "647-484-3839";

var newStr = phoneNumberInput .replace(/[^-]+-$/,"");

Body:
You can:

var pos = phoneNumberInput.lastIndexOf("-");
phoneNumberInput = phoneNumberInput.substr(0, pos) + phoneNumberInput.substr(pos + 1);


问:
Three.js - centroid of boxHelper
I have used the following to calculate the centroid of an imported model;

```<code>geometry.computeBoundingBox();
var centroid = new THREE.Vector3();
centroid.addVectors( geometry.boundingBox.min, geometry.boundingBox.max );
centroid.multiplyScalar( - 0.5 );
centroid.applyMatrix4( mesh.matrixWorld );
</code>```

https://stackoverflow.com/a/25269787

It works well, but I think BoundingBox has been deprecated.
Should I be using boxHelper? How do I find centroid of boxHelper?

答:
1) BoundingBoxHelper was deprecated, not the boundingBox property.

2) Don't use BoxHelper to find the centroid. Just use the boundingBox property.

2.5) The boundingBox property is a Box3 object, which has a getCenter method, which gives you what you're calculating.

```<code>geometry.computeBoundingBox();
var centroid = geometry.boundingBox.getCenter();
centroid.applyMatrix4( mesh.matrixWorld );
</code>```

Title: Three.js - centroid of boxHelper

Body:
I have used the following to calculate the centroid of an imported model;

geometry.computeBoundingBox();
var centroid = new THREE.Vector3();
centroid.addVectors( geometry.boundingBox.min, geometry.boundingBox.max );
centroid.multiplyScalar( - 0.5 );
centroid.applyMatrix4( mesh.matrixWorld );

https://stackoverflow.com/a/25269787

It works well, but I think BoundingBox has been deprecated.
Should I be using boxHelper? How do I find centroid of boxHelper?

Body:
1) BoundingBoxHelper was deprecated, not the boundingBox property.

2) Don't use BoxHelper to find the centroid. Just use the boundingBox property.

2.5) The boundingBox property is a Box3 object, which has a getCenter method, which gives you what you're calculating.

geometry.computeBoundingBox();
var centroid = geometry.boundingBox.getCenter();
centroid.applyMatrix4( mesh.matrixWorld );


问:
Use VectorDrawables in a Bitmap XML and tint them
We are trying to move all our app icon resources to VectorDrawables to reduce the size of the app and manage the app icon kit easily.

We already have an Icon Kit with all the icons of our app, all in a black color and the idea is to use them and tint in each usage with the appropriate color. This works (more or less) perfectly until you try to made the same in a layer-list/selector/similar, where you need to include an item with a <bitmap> or similar and... I don't find how to tint a VectorDrawable that also works in <21 devices

The pre-requisite is to not need to make it programmatically, I know that is possible but made it programmatically breaks all the easy usage of the icons and, also, not has sense.

In resume, Is there any form to use VectorDrawable in a <Bitmap> XML and tint it working in <21 devices and not programmatically?

答:
The short answer: No, you can't do that.

The extended version:

Copy the SVG and apply color:

```<code>icon_a.xml
icon_b.xml (with color changed)
</code>```

Body:
The short answer: No, you can't do that.

The extended version:

Copy the SVG and apply color:

icon_a.xml
icon_b.xml (with color changed)


问:
Is this a new way to extend an object in JavaScript?
While upgrading a private yeoman generator I stumpled upon this statement while looking through the official generator-webapp:

```<code>const { features } = answers;
</code>```

I wasn't able to find anything about this, aside from the fact that it only works on node >=6.

What does this statement do? Where is this defined?

答:
It's destructuring assignment. It's equivalent to:

```<code>const features = answers.features;
</code>```

It was introduced in ES2015.

Body:
While upgrading a private yeoman generator I stumpled upon this statement while looking through the official generator-webapp:

const { features } = answers;

I wasn't able to find anything about this, aside from the fact that it only works on node >=6.

What does this statement do? Where is this defined?

Body:
It's destructuring assignment. It's equivalent to:

const features = answers.features;

It was introduced in ES2015.


问:
ASP NET MVC RAZOR Upload Multiple Images FileList
I'm new in asp net and I have a List of images and I want to send through javascript to the controller.

I'm using FileList and here is an example.
.Create.cshtml

```<code><div class="form-group">
    @Html.LabelFor(model => model.description, "Escolha as Imagens", htmlAttributes: new { @class = "control-label col-md-2" })
    <input id="files" type="file" name="files[]" />
    <br>
    <div id="preview"></div>
</div>
@section Scripts{
    <script type="text/javascript">
        function handleFileSelect(evt) {

            var files = evt.target.files;
            var f = files[0];
            //kiem tra co fai file anh
            if (f.type.match('image.*')) {
                var reader = new FileReader();

                reader.onload = (function(theFile) {
                    return function(e) {
                        var span = document.createElement('span');
                        span.innerHTML = [
                            '<img class="thumb" src="', e.target.result, '" title="', escape(theFile.name),
                            '"/><span class="remove_img_preview"></span>'
                        ].join('');
                        document.getElementById('preview').insertBefore(span, null);
                    };
                })(f);

                reader.readAsDataURL(f);
            }
        }

        $('#files').change(function(evt) {
            handleFileSelect(evt);
        });
        $('#preview').on('click',
            '.remove_img_preview',
            function() {
                $(this).parent('span').remove();
            });

        $('#btnSave').click(function() {

            $.ajax({
                url: '/Dishes/Create',
                data: { files: files },
                type: "POST",
                cache: false,
                datatype: "html",
                success: function(data) {
                    console.log(data);
                },
                error: function(jqXhr, textStatus, errorThrown) {
                    //do your own thing
                    alert("fail");
                }
            });
        });

    </script>
}
</fieldset>
<div class="form-group">
    <div class="footer text-center">
        <button class="btn btn-fill btn-info" name="btnSave" id="btnSave">Inserir novo</button>
    </div>
</div>
</code>```

Controller.cs

```<code>public ActionResult Create()
    {
        ViewBag.idTypeDish = new SelectList(db.TypeDish, "idTypeDish", "name");
        return View();
    }

    // POST: Dishes/Create
    [HttpPost]
    public ActionResult Create(IEnumerable<HttpPostedFileBase> files)
    {

        return View();

    }
</code>```

In the controller, files are always null.
I'm using that example, http://jsfiddle.net/Lwczca6p/1/, I just adapt to my project.

答:
Try this, first create a model for your view:

```<code>public class FileModel
{
    [Required(ErrorMessage ="Please select file.")]
    [Display(Name ="Browse File")]
    public HttpPostedFileBase[] files { get; set; }

}
</code>```

Then, edit your view to this (to enable upload many files you need to put multiple="multiple" in your element):

```<code>@model Models.FileModel

@using (Html.BeginForm("Create", "YourController", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.files, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.TextBoxFor(model => model.files, "", new { @type = "file", @multiple = "multiple" })
                @Html.ValidationMessageFor(model => model.files, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit"  value="Upload" class="btn btn-primary" />
            </div>
        </div>

        </div>
}
</code>```

Body:
I'm new in asp net and I have a List of images and I want to send through javascript to the controller.

I'm using FileList and here is an example.
.Create.cshtml

    @Html.LabelFor(model => model.description, "Escolha as Imagens", htmlAttributes: new { @class = "control-label col-md-2" })
    <input id="files" type="file" name="files[]" />

@section Scripts{

}
</fieldset>

        <button class="btn btn-fill btn-info" name="btnSave" id="btnSave">Inserir novo</button>

Controller.cs

public ActionResult Create()
    {
        ViewBag.idTypeDish = new SelectList(db.TypeDish, "idTypeDish", "name");
        return View();
    }

    // POST: Dishes/Create
    [HttpPost]
    public ActionResult Create(IEnumerable<HttpPostedFileBase> files)
    {

        return View();

    }

In the controller, files are always null.
I'm using that example, http://jsfiddle.net/Lwczca6p/1/, I just adapt to my project.

Body:
Try this, first create a model for your view:

public class FileModel
{
    [Required(ErrorMessage ="Please select file.")]
    [Display(Name ="Browse File")]
    public HttpPostedFileBase[] files { get; set; }

}

Then, edit your view to this (to enable upload many files you need to put multiple="multiple" in your element):

@model Models.FileModel

@using (Html.BeginForm("Create", "YourController", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.files, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.TextBoxFor(model => model.files, "", new { @type = "file", @multiple = "multiple" })
                @Html.ValidationMessageFor(model => model.files, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit"  value="Upload" class="btn btn-primary" />
            </div>
        </div>

        </div>
}


问:
How to get the difference between 2 int arrays as a percentage
Mathematically we can solve it like Given Amount / Total Amount * 100 to get the percentage difference. But what I need is to compare 2 Integer Arrays (in C# Win App) and get the percentage of the difference.
Like :

```<code>1 -----> -2
2 ----->  3
3 ----->  7
4 ----->  456
5 ----->  13
</code>```

These two columns are 2 Integer Arrays and I should get the difference between them.

How can I get this? A mathematical answer or an algorithm, whatever can be used to solve the problem.

答:
try this</p>

```<code>var i1 = Enumerable.Range(0, 10).ToArray();
var i2 = Enumerable.Range(20, 10).ToArray();
var result = i1.Select((n, i) => n * 100 / i2[i]);
</code>```

Body:
Mathematically we can solve it like Given Amount / Total Amount * 100 to get the percentage difference. But what I need is to compare 2 Integer Arrays (in C# Win App) and get the percentage of the difference.
Like :

1 -----> -2
2 ----->  3
3 ----->  7
4 ----->  456
5 ----->  13

These two columns are 2 Integer Arrays and I should get the difference between them.

How can I get this? A mathematical answer or an algorithm, whatever can be used to solve the problem.

Body:
try this

var i1 = Enumerable.Range(0, 10).ToArray();
var i2 = Enumerable.Range(20, 10).ToArray();
var result = i1.Select((n, i) => n * 100 / i2[i]);


问:
Why are the input boxes completely overflowing their bounding divs?
I intend to line up 4 input text boxes housed in 4 equal sized columns in one row of the form. Making use of Bootstrap's grid column classes, I assigned  col--3 for medium and large screen sizes to those four input divs.
Likewise for small and extra small sizes, I assigned them col--12  so that the inputs occupy their own whole row. Then my guide wanted those input boxes sizes reduced. I added offset class to the four input and reduced their column span to 6 columns. These were centered appropriately.

However, this change screwed up my small screen layout. Now there are only two inputs in each row, while the other two in the next row.

/* button modification*/

#button-wrapper {
  width: 40%;
  min-width: 200px;
  margin: 0 auto;
}

#ebook-download-button {
  margin: auto 0.5em;
}

.inner {
  margin: 0 auto 0 auto;
  width: 150px;
  padding: 0;
  /* center the block element*/
}

img {
  min-width: 100%;
}

input {
  height: 60%;
  margin: 0px;
}

/* square boxes*/

.square-elem {
  border-radius: 0px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

<body>

  <form id="registration-form" class="">
    <!--<div class="col-md-12 col-sm-12">-->
    <div class="row">
      <div class="col-lg-3 col-md-3 col-sm-6 col-sm-offset-3 col-xs-6 col-xs-offset-3 ">
        <div class="form-group">
          <input type="input" class="form-control square-elem" id="first-name" placeholder="First Name">
        </div>
      </div>

      <div class="col-lg-3 col-md-3 col-sm-6 col-sm-offset-3 col-xs-6 col-xs-offset-3">
        <div class="form-group">
          <input type="input" class="form-control square-elem" id="last-name" placeholder="Last Name">
        </div>
      </div>

      <div class="col-lg-3 col-md-3 col-sm-6 col-sm-offset-3 col-xs-6 col-xs-offset-3">
        <div class="form-group">
          <input type="input" class="form-control square-elem" id="company" placeholder="Company">
        </div>
      </div>

      <div class="col-lg-3 col-md-3 col-sm-6 col-sm-offset-3 col-xs-6 col-xs-offset-3">
        <div class="form-group">
          <input type="input" class="form-control square-elem" id="email" placeholder="Email">
        </div>
      </div>
    </div>
    <div class="row">
      <div id="button-wrapper" style="">
        <div id="ebook-download-button" class="col-md-12 col-sm-12 col-xs-12 text-center">
           DOWNLOAD EBOOK
        </div>
      </div>
    </div>
    <!-- </div>
  -->
  </form>

</body></code>```

Here's the JSFiddle(Drag the frame) too. It seems the inputs(in each form group div) have completely positioned outside their bounding div box.The intended output should be the four inputs lined side by side in one row.
What can possibly be the issue here?

答: You can also use "form-inline" class on <form> for horizontal form display.

Body:
I intend to line up 4 input text boxes housed in 4 equal sized columns in one row of the form. Making use of Bootstrap's grid column classes, I assigned  col--3 for medium and large screen sizes to those four input divs.
Likewise for small and extra small sizes, I assigned them col--12  so that the inputs occupy their own whole row. Then my guide wanted those input boxes sizes reduced. I added offset class to the four input and reduced their column span to 6 columns. These were centered appropriately.

However, this change screwed up my small screen layout. Now there are only two inputs in each row, while the other two in the next row.

/* button modification*/

#button-wrapper {
  width: 40%;
  min-width: 200px;
  margin: 0 auto;
}

#ebook-download-button {
  margin: auto 0.5em;
}

.inner {
  margin: 0 auto 0 auto;
  width: 150px;
  padding: 0;
  /* center the block element*/
}

img {
  min-width: 100%;
}

input {
  height: 60%;
  margin: 0px;
}

/* square boxes*/

.square-elem {
  border-radius: 0px;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

  <form id="registration-form" class="">

          <input type="input" class="form-control square-elem" id="first-name" placeholder="First Name">

          <input type="input" class="form-control square-elem" id="last-name" placeholder="Last Name">

          <input type="input" class="form-control square-elem" id="company" placeholder="Company">

          <input type="input" class="form-control square-elem" id="email" placeholder="Email">

           DOWNLOAD EBOOK

  </form>

Here's the JSFiddle(Drag the frame) too. It seems the inputs(in each form group div) have completely positioned outside their bounding div box.The intended output should be the four inputs lined side by side in one row.
What can possibly be the issue here?


问:
How to chain multiple java method calls in a single statement?
I am trying to make something that
Instead of having to do

```<code>MyClass myclass = new MyClass();

myclass.params(url,body);
myclass.request();
myclass.response();
</code>```

to call the functions inside that class

I want it to be like

```<code>MyClass myclass = new MyClass();

myclass.params(url,body).request().response();
</code>```

if that is even possible.

答:
This is a perfectly valid question, and yes: it is possible.

The type of api style is called Fluent interface. From wikipedia:

A fluent interface is normally implemented by using method cascading (concretely method chaining) to relay the instruction context of a subsequent call

To implement this for your use case, just declare your methods like this:

```<code>public MyClass params(String url, String body) {
    // your code here
    return this;
}
</code>```

instead of that:

```<code>public void params(String url, String body) {
    // your code here
}
</code>```

Body:
I am trying to make something that
Instead of having to do

MyClass myclass = new MyClass();

myclass.params(url,body);
myclass.request();
myclass.response();

to call the functions inside that class

I want it to be like

MyClass myclass = new MyClass();

myclass.params(url,body).request().response();

if that is even possible.

Body:
This is a perfectly valid question, and yes: it is possible.

The type of api style is called Fluent interface. From wikipedia:

A fluent interface is normally implemented by using method cascading (concretely method chaining) to relay the instruction context of a subsequent call

To implement this for your use case, just declare your methods like this:

public MyClass params(String url, String body) {
    // your code here
    return this;
}

instead of that:

public void params(String url, String body) {
    // your code here
}


问:
SSRS Export to Excel results in (500) Server Error
I have an SSRS report (SSRS 2012) that when I try to export to Excel, always crashes after a minute or so with a 500 server error.

The report itself runs successfully.  And I can successfully export the result to CSV, which actually only takes a few seconds to do after the report itself has rendered.

I am experiencing this on result sets greater than around 20000 records; my current example has 36000 records - it crashes the Excel export but the CSV export is successful.

I've tried checking the SSRS logs (C:\Program Files\Microsoft SQL Server\MSRS11.SQL2012\Reporting Services\LogFiles) no errors are shown in there, just a couple entries for RenderForNewSession and RenderFromSession pointing to my report.

The Event Viewer Application log shows a Warning entry for ASP.NET 2.0:

Exception information:
    Exception type: COMException
    Exception message: This network connection does not exist. (Exception from HRESULT: 0x800708CA)

Is there any place else I might find useful debugging information? I'd really rather not have to direct the client to "not export large reports to Excel, use CSV instead" if I don't have to. Or are there any known issues or quirks when exporting to Excel from the SSRS web report viewer?

EDIT:

After some further digging, I've found some more info but have yet to find an actual solution.  I did find where I could turn up the debugging level in the logs - in the ReportingSErvicesService.exe.config file there are two settings, DefaultTraceSwitch and Components underneath an RSTrace tag. They have default values of 3 but bumping each to 4 provides what appears to be a verbose logging output.

That was interesting, but didn't really point me to anything new other than confirming that it looks like the client execution is timing out.

Next I've come across a TechNet article that at least seems to describe the various places I might be able to set an SSRS timeout.  From what I can tell it seems like the Excel export renderer is hitting an execution timeout somewhere, but all of the SSRS settings appear to cover plenty of headroom for running anything.

Should the web.config httpRuntime executionTimeout setting override the machine.config settings? The TechNet article implies that the machine.config settings seems to line up with the timeout I'm seeing when exporting, but the ReportServer web.config has an executionTimeout setting much larger than the ASP.NET default setting.

答:
Not sure if this is the same problem, but I've had trouble with exports to Excel that have too many characters in a cell. The entire export crashes if it encounters just 1 cell that has more than 32745 characters.

I've had to start adding truncate code to my text boxes to truncate the cell text upon export to Excel, and that fixed the issue for me -- that's not always a viable option though, so just a suggestion.

```<code>IIf(Globals!RenderFormat.Name= "EXCELOPENXML" OR Globals!RenderFormat.Name = "EXCEL",
          Left(Join(Fields!FieldA.Value, chr(10)),32745) + "...Truncated for Excel",
Join(Fields!FieldA.Value, chr(10) ))
</code>```

Otherwise, here's  a link that shows some of the limitations of exports to Excel from Reporting Services:  https://learn.microsoft.com/en-us/sql/reporting-services/report-builder/exporting-to-microsoft-excel-report-builder-and-ssrs

Body:
Not sure if this is the same problem, but I've had trouble with exports to Excel that have too many characters in a cell. The entire export crashes if it encounters just 1 cell that has more than 32745 characters.

I've had to start adding truncate code to my text boxes to truncate the cell text upon export to Excel, and that fixed the issue for me -- that's not always a viable option though, so just a suggestion.

IIf(Globals!RenderFormat.Name= "EXCELOPENXML" OR Globals!RenderFormat.Name = "EXCEL",
          Left(Join(Fields!FieldA.Value, chr(10)),32745) + "...Truncated for Excel",
Join(Fields!FieldA.Value, chr(10) ))

Otherwise, here's  a link that shows some of the limitations of exports to Excel from Reporting Services:  https://learn.microsoft.com/en-us/sql/reporting-services/report-builder/exporting-to-microsoft-excel-report-builder-and-ssrs


问:
TWS MakePlan failure with AWSJDB818E
TWS MakePlan is failing with error message: AWSJDB818E
"AWSJDB818E An internal error has occurred while connecting to the

database. The internal error message is: "CWTE_NORMAL_J2CA1009"." cannot
 be obtained from the database, or is incorrect.

Which is the root cause?

答:
in that case the error message
"AWSJDB818E An internal error has occurred while connecting to the

database. The internal error message is: "CWTE_NORMAL_J2CA1009"." cannot
 be obtained from the database, or is incorrect.

With "internal error message: CWTE_NORMAL_J2CA1009" is an indicator that no DB connections are available.

For TWS 9.4

Edit the file:

/WAS/TWSProfile/config/cells/TWSNodeCell/nodes/TWSNode/servers
/PSLITE-TIV01/resources.xml

In the "DB2 Universal Type 4 JDBC Driver DataSource"

change the value minConnections="1" maxConnections="30" to

minConnections="0" maxConnections="100"

A restart of the WAS is required

thanks.

Title: TWS MakePlan failure with AWSJDB818E


问:
Schedule R scripts without using Task Scheduler
I have RStudio installed on my Windows 7 machine however I am unable to access Windows Task Scheduler to automate some R scripts. Are there any alternatives in this situation? I have explored taskscheduleR however found out that this is just a wrapper of Task Scheduler. Open to ideas using VB scripts - basically any hack will do.

答:
I would suggest VBA for your task and you need to learn how to use Application.OnTime;

You need other subs that triggers and stops this one as you desire; first one can start the schedule.

```<code>Public stop_running As Boolean
Public sTime As String

Sub Start(input As String)

    stop_running = True 'This controls schedule in Application.Ontime
    sTime = input
    Application.OnTime TimeValue(sTime), "Rscript", Schedule:=stop_running

End Sub
</code>```

Whenever you want to stop running this macro, the you run this one;

```<code>Sub Finish()

    stop_running = False 'Set the schedule to false to stop the macro
    Application.OnTime TimeValue(sTime), "Rscript", Schedule:=stop_running

End Sub
</code>```

Then this is the sub that runs your r-script:

```<code>Sub Rscript()
'runs R script through cmd

    If Not stop_running Exit Sub

Dim shell As Object
Set shell = VBA.CreateObject("WScript.Shell")
Dim waitTillComplete As Boolean: waitTillComplete = True
Dim style As Integer: style = 1
Dim errorCode As Integer
Dim path As String

path = "RScript C:\R\myscript.R"
errorCode = shell.Run(path, style, waitTillComplete)

End Sub
</code>```

You can call the macro Start from immediate window like this:

```<code>Call Start(TimeValue("14:00:00 pm"))
</code>```

And your macro will run at 2 p.m. Everyday.

Body:
I would suggest VBA for your task and you need to learn how to use Application.OnTime;

You need other subs that triggers and stops this one as you desire; first one can start the schedule.

Public stop_running As Boolean
Public sTime As String

Sub Start(input As String)

    stop_running = True 'This controls schedule in Application.Ontime
    sTime = input
    Application.OnTime TimeValue(sTime), "Rscript", Schedule:=stop_running

End Sub

Whenever you want to stop running this macro, the you run this one;

Sub Finish()

    stop_running = False 'Set the schedule to false to stop the macro
    Application.OnTime TimeValue(sTime), "Rscript", Schedule:=stop_running

End Sub

Then this is the sub that runs your r-script:

Sub Rscript()
'runs R script through cmd

    If Not stop_running Exit Sub

Dim shell As Object
Set shell = VBA.CreateObject("WScript.Shell")
Dim waitTillComplete As Boolean: waitTillComplete = True
Dim style As Integer: style = 1
Dim errorCode As Integer
Dim path As String

path = "RScript C:\R\myscript.R"
errorCode = shell.Run(path, style, waitTillComplete)

End Sub

You can call the macro Start from immediate window like this:

Call Start(TimeValue("14:00:00 pm"))

And your macro will run at 2 p.m. Everyday.


问:
org.apache.axis2.AxisFault: Axis2 Can't find Spring's ApplicationContext with in .aar file
I am using Axis2, Spring and Hibernate. I created .aar file using the following command.

```<code>jar cvf someName.aar *
</code>```

My .aar file looks as below:

```<code> _ classFilesWithInPackage (E.g. com/test/.../fileName.java)
|_ META-INF/(MANIFEST.MF and services.xml)
|_ applicationContext.xml
|_ lib/required jars
</code>```

And my services.xml is

```<code><serviceGroup>
    <service name="SpringInitializationService" class="com.test.service.SpringInitService">
        <description>
            This web service initializes Spring.
        </description>
        <parameter name="ServiceClass">com.test.service.SpringInitService
        </parameter>
        <parameter name="ServiceTCCL">composite</parameter>
        <parameter name="load-on-startup">true</parameter>
    </service>
    <service name="TestService">
        <Description>
            Policy Web Service
        </Description>
        <messageReceivers>
            <messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-only"
                class="org.apache.axis2.rpc.receivers.RPCInOnlyMessageReceiver" />
            <messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-out"
                class="org.apache.axis2.rpc.receivers.RPCMessageReceiver" />
        </messageReceivers>
        <parameter name="ServiceClass" locked="false">com.test.service.TestService
        </parameter>
        <parameter name="ServiceObjectSupplier">
            org.apache.axis2.extensions.spring.receivers.SpringAppContextAwareObjectSupplier
        </parameter>
        <parameter name="SpringBeanName">axis2SpringIntegrationService</parameter>
        <parameter name="SpringContextLocation">applicationContext.xml</parameter>
    </service>
</serviceGroup>
</code>```

I have implemented the interface ServiceLifeCycle and override the following methods as well. Reference site http://fazlansabar.blogspot.com.es/2012/04/apache-axis2-tutorial-integrating-with.html.

```<code>public class SpringInitService implements ServiceLifeCycle {

    ClassLoader classLoader = null;
    ClassPathXmlApplicationContext appCtx = null;

    @Override
    public void shutDown(ConfigurationContext configContext, AxisService axisService) {
        appCtx = null;
        classLoader = null;
    }

    @Override
    public void startUp(ConfigurationContext configContext, AxisService axisService) {

        System.out.println("Inside Spring Init");

        try {
            classLoader = axisService.getClassLoader();
            appCtx = new ClassPathXmlApplicationContext(new String[] {"classpath:**applicationContext.xml"}, false);
            appCtx.setClassLoader(classLoader);
            appCtx.refresh();
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("Out of Spring Init");
    }

}
</code>```

When I create .aar file out of it and deploy in WSO2 server, it deployed successfully and com.test.service.SpringInitService class also initialized at start up without error since I have implemented ServiceLifeCycle interface. But When I invoke any service available in TestService (2nd service in services.xml) I ended up in error.

```<code>org.apache.axis2.AxisFault: Axis2 Can't find Spring's ApplicationContext
</code>```

Someone please tell me what I am doing wrong.

Also clarify,

```<code>Whether my .aar folder structure is right?
Can we have more than one service in services.xml as above?
What is the best way to have Axis2, Spring and Hibernate together?
</code>```

Update:

   I tried following the below reference from Axis2 site, but has no luck in getting it worked.

http://axis.apache.org/axis2/java/core/docs/spring.html

Any help is Appreciated.
Thanks in Advance.

答:
Implement your own ApplicationContextHolder

```<code>import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class ApplicationContextHolder implements ApplicationContextAware {

    private static ApplicationContext appCtx;

    public ApplicationContextHolder() {}

    /** Spring supplied interface method for injecting app context. */
    public void setApplicationContext(ApplicationContext applicationContext)
        throws BeansException {
        appCtx = applicationContext;
    }

    /** Access to spring wired beans. */
    public static ApplicationContext getContext() {
        return appCtx;
    }

}
</code>```

Use it in settings.xml

```<code><bean id="applicationContext"
class="org.ravinda.service.spring.ApplicationContextHolder" />
</code>```

Body:
I am using Axis2, Spring and Hibernate. I created .aar file using the following command.

jar cvf someName.aar *

My .aar file looks as below:

 _ classFilesWithInPackage (E.g. com/test/.../fileName.java)
|_ META-INF/(MANIFEST.MF and services.xml)
|_ applicationContext.xml
|_ lib/required jars

And my services.xml is

<serviceGroup>
    <service name="SpringInitializationService" class="com.test.service.SpringInitService">
        <description>
            This web service initializes Spring.
        </description>
        <parameter name="ServiceClass">com.test.service.SpringInitService
        </parameter>
        <parameter name="ServiceTCCL">composite</parameter>
        <parameter name="load-on-startup">true</parameter>
    </service>
    <service name="TestService">
        <Description>
            Policy Web Service
        </Description>
        <messageReceivers>
            <messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-only"
                class="org.apache.axis2.rpc.receivers.RPCInOnlyMessageReceiver" />
            <messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-out"
                class="org.apache.axis2.rpc.receivers.RPCMessageReceiver" />
        </messageReceivers>
        <parameter name="ServiceClass" locked="false">com.test.service.TestService
        </parameter>
        <parameter name="ServiceObjectSupplier">
            org.apache.axis2.extensions.spring.receivers.SpringAppContextAwareObjectSupplier
        </parameter>
        <parameter name="SpringBeanName">axis2SpringIntegrationService</parameter>
        <parameter name="SpringContextLocation">applicationContext.xml</parameter>
    </service>
</serviceGroup>

I have implemented the interface ServiceLifeCycle and override the following methods as well. Reference site http://fazlansabar.blogspot.com.es/2012/04/apache-axis2-tutorial-integrating-with.html.

public class SpringInitService implements ServiceLifeCycle {

    ClassLoader classLoader = null;
    ClassPathXmlApplicationContext appCtx = null;

    @Override
    public void shutDown(ConfigurationContext configContext, AxisService axisService) {
        appCtx = null;
        classLoader = null;
    }

    @Override
    public void startUp(ConfigurationContext configContext, AxisService axisService) {

        System.out.println("Inside Spring Init");

        try {
            classLoader = axisService.getClassLoader();
            appCtx = new ClassPathXmlApplicationContext(new String[] {"classpath:**applicationContext.xml"}, false);
            appCtx.setClassLoader(classLoader);
            appCtx.refresh();
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("Out of Spring Init");
    }

}

When I create .aar file out of it and deploy in WSO2 server, it deployed successfully and com.test.service.SpringInitService class also initialized at start up without error since I have implemented ServiceLifeCycle interface. But When I invoke any service available in TestService (2nd service in services.xml) I ended up in error.

org.apache.axis2.AxisFault: Axis2 Can't find Spring's ApplicationContext

Someone please tell me what I am doing wrong.

Also clarify,

Whether my .aar folder structure is right?
Can we have more than one service in services.xml as above?
What is the best way to have Axis2, Spring and Hibernate together?

Update:

   I tried following the below reference from Axis2 site, but has no luck in getting it worked.

http://axis.apache.org/axis2/java/core/docs/spring.html

Any help is Appreciated.
Thanks in Advance.

Body:
Implement your own ApplicationContextHolder

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class ApplicationContextHolder implements ApplicationContextAware {

    private static ApplicationContext appCtx;

    public ApplicationContextHolder() {}

    /** Spring supplied interface method for injecting app context. */
    public void setApplicationContext(ApplicationContext applicationContext)
        throws BeansException {
        appCtx = applicationContext;
    }

    /** Access to spring wired beans. */
    public static ApplicationContext getContext() {
        return appCtx;
    }

}

Use it in settings.xml

<bean id="applicationContext"
class="org.ravinda.service.spring.ApplicationContextHolder" />


问:
Use ternary alike method for calling methods
As we all now, you can use ternary operators like this:

```<code>String testString = "test";
int myInt = testString.equals("test") ? 1 : 2;
</code>```

However, how can I do so with methods?
Assume I have the following:

```<code>String testString = "test";
if (testString.equals("test") {
    doSomething();
} else {
    doSomethingElse();
}
</code>```

Is there something where you can combine this like the following manner:

```<code>testString.equals("test") ? doSomething() : doSomethingElse();
</code>```

When using it in Android studio, it results in saying "not a statement"

Edit
It can be done by initializing a local variable, but it is a bit unusual.

```<code>public void test() {
    String testString = "test";
    boolean test = testString.equals("test") ? doSomething() : doSomethingElse();
}

public boolean doSomething() {
    return true;
}

public boolean doSomethingElse() {
    return false;
}
</code>```

答:
You can only write

testString.equals("test") ? doSomething() : doSomethingElse();

if doSomething() and doSomethingElse() both return something, and those somethings have either exactly the same type, or are covariant types. Setting both functions to return a boolean would be sufficient.

This is because the entire thing is an expression, and an expression has a value as well as a well-defined type.

If you are not wanting to do anything with the return value, then use an if statement.

Body:
As we all now, you can use ternary operators like this:

String testString = "test";
int myInt = testString.equals("test") ? 1 : 2;

However, how can I do so with methods?
Assume I have the following:

String testString = "test";
if (testString.equals("test") {
    doSomething();
} else {
    doSomethingElse();
}

Is there something where you can combine this like the following manner:

testString.equals("test") ? doSomething() : doSomethingElse();

When using it in Android studio, it results in saying "not a statement"

Edit
It can be done by initializing a local variable, but it is a bit unusual.

public void test() {
    String testString = "test";
    boolean test = testString.equals("test") ? doSomething() : doSomethingElse();
}

public boolean doSomething() {
    return true;
}

public boolean doSomethingElse() {
    return false;
}


问:
EWS body plain text
I use EWS to get exchange emails, but how can i get plain text from email body, without html?<br>
Now i use this:   </p>

```<code>EmailMessage item = (EmailMessage)outbox.Items[i];
item.Load();
item.Body.Text
</code>```

答:
The shortest way to do it is like this:

```<code>item.Load(new PropertySet(BasePropertySet.IdOnly, ItemSchema.TextBody, EmailMessageSchema.Body));
</code>```

This has got the advantage that you get both, text-body and html-body.

Title: EWS body plain text

Body:
I use EWS to get exchange emails, but how can i get plain text from email body, without html?

Now i use this:

EmailMessage item = (EmailMessage)outbox.Items[i];
item.Load();
item.Body.Text

Body:
The shortest way to do it is like this:

item.Load(new PropertySet(BasePropertySet.IdOnly, ItemSchema.TextBody, EmailMessageSchema.Body));

This has got the advantage that you get both, text-body and html-body.


问:
Not able to click dropdown
I am a new learner in selenium and try to click on a dropdown to populate list but it keeps on giving me runtime exception:

Exception in thread "main" org.openqa.selenium.ElementNotVisibleException:
    Element is not currently visible and so may not be interacted with )

Please help. Below is my code that I am executing.

```<code>    WebDriver dr=new FirefoxDriver();
    dr.get("https://jqueryui.com/selectmenu/");
    dr.manage().window().maximize();
    dr.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    dr.switchTo().frame(dr.findElement(By.className("demo-frame")));
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("speed-       menu"))).click();
</code>```

答:
To click on the Dropdown Select a speed, here is your own code with minimal changes:

```<code>    System.setProperty("webdriver.gecko.driver", "C:\\your_directory\\geckodriver.exe");
    WebDriver dr=new FirefoxDriver();
    dr.get("https://jqueryui.com/selectmenu/");
    dr.manage().window().maximize();
    dr.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    dr.switchTo().frame(dr.findElement(By.className("demo-frame")));
    dr.findElement(By.xpath("//*[@id='speed-button']/span[@class='ui-selectmenu-text']")).click();
</code>```

Let me know if this Answers your Question.

Title: Not able to click dropdown

Body:
I am a new learner in selenium and try to click on a dropdown to populate list but it keeps on giving me runtime exception:

Exception in thread "main" org.openqa.selenium.ElementNotVisibleException:
    Element is not currently visible and so may not be interacted with )

Please help. Below is my code that I am executing.

    WebDriver dr=new FirefoxDriver();
    dr.get("https://jqueryui.com/selectmenu/");
    dr.manage().window().maximize();
    dr.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    dr.switchTo().frame(dr.findElement(By.className("demo-frame")));
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("speed-       menu"))).click();

Body:
To click on the Dropdown Select a speed, here is your own code with minimal changes:

    System.setProperty("webdriver.gecko.driver", "C:\\your_directory\\geckodriver.exe");
    WebDriver dr=new FirefoxDriver();
    dr.get("https://jqueryui.com/selectmenu/");
    dr.manage().window().maximize();
    dr.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    dr.switchTo().frame(dr.findElement(By.className("demo-frame")));
    dr.findElement(By.xpath("//*[@id='speed-button']/span[@class='ui-selectmenu-text']")).click();

Let me know if this Answers your Question.


问:
Opening serial port with Qt
I am having problems with opening serial port in Qt. The error message I receive after failed attempt to open the port is UnsupportedOperationError. I would like to point out couple things:

The port I am trying to open is implemented in an ARM MCU using USB (CDC),

I can open the port in other application (like teraterm or realterm),

I was able to open the port in my Qt application just a minute a go. I added some code in the ARM device (not concerning the USB functionality at all) and I couldnt open the port in Qt anymore.

I tested that I can send/ receive the data on the port opened in other program (ie. realterm),

The port works in other applications, but not Qt (tried the terminal example from Qt creator and it cannot open the port as well),

I have come across this behaviour in the past, but did not have time to go further into it. Now it is blocking me. What could be the case here with opening the port? Does qt put any additional requirements to it? I would really appreciate all help.
I am running qt on windows machine.

Edit: This is a part of the Terminal example from Qt creator responsible for opening the port.

```<code>void MainWindow::openSerialPort()
{
    SettingsDialog::Settings p = settings->settings();
    serial->setPortName(p.name);
    serial->setBaudRate(p.baudRate);
    serial->setDataBits(p.dataBits);
    serial->setParity(p.parity);
    serial->setStopBits(p.stopBits);
    serial->setFlowControl(p.flowControl);
    if (serial->open(QIODevice::ReadWrite)) {
        console->setEnabled(true);
        console->setLocalEchoEnabled(p.localEchoEnabled);
        ui->actionConnect->setEnabled(false);
        ui->actionDisconnect->setEnabled(true);
        ui->actionConfigure->setEnabled(false);
        showStatusMessage(tr("Connected to %1 : %2, %3, %4, %5, %6")
                          .arg(p.name).arg(p.stringBaudRate).arg(p.stringDataBits)
                          .arg(p.stringParity).arg(p.stringStopBits).arg(p.stringFlowControl));
    } else {
        qDebug() << "Failed to open serial port " << serial->portName() << "Error: " << serial->error();
        QMessageBox::critical(this, tr("Error"), serial->errorString());

        showStatusMessage(tr("Open error"));
    }
}
</code>```

I have added the line qith qDebug in order to show the error message. Its is the same as in my Qt program.

答:
You're facing a bug or an overly exclusionary behavior in Qt. There is unlikely to be anything you can do to fix it in your own code.

It's also impossible to debug without a debug build of Qt. Use a debug build and you can pin-point exactly where in the implementation of QSerialPort it fails. You'll then know what's going on, and be able to file a Qt bug report based on that. Since you'll be set up to build Qt, you can fix the bug yourself and get going quickly that way.

Title: Opening serial port with Qt

Body:
I am having problems with opening serial port in Qt. The error message I receive after failed attempt to open the port is UnsupportedOperationError. I would like to point out couple things:

The port I am trying to open is implemented in an ARM MCU using USB (CDC),

I can open the port in other application (like teraterm or realterm),

I was able to open the port in my Qt application just a minute a go. I added some code in the ARM device (not concerning the USB functionality at all) and I couldnt open the port in Qt anymore.

I tested that I can send/ receive the data on the port opened in other program (ie. realterm),

The port works in other applications, but not Qt (tried the terminal example from Qt creator and it cannot open the port as well),

I have come across this behaviour in the past, but did not have time to go further into it. Now it is blocking me. What could be the case here with opening the port? Does qt put any additional requirements to it? I would really appreciate all help.
I am running qt on windows machine.

Edit: This is a part of the Terminal example from Qt creator responsible for opening the port.

void MainWindow::openSerialPort()
{
    SettingsDialog::Settings p = settings->settings();
    serial->setPortName(p.name);
    serial->setBaudRate(p.baudRate);
    serial->setDataBits(p.dataBits);
    serial->setParity(p.parity);
    serial->setStopBits(p.stopBits);
    serial->setFlowControl(p.flowControl);
    if (serial->open(QIODevice::ReadWrite)) {
        console->setEnabled(true);
        console->setLocalEchoEnabled(p.localEchoEnabled);
        ui->actionConnect->setEnabled(false);
        ui->actionDisconnect->setEnabled(true);
        ui->actionConfigure->setEnabled(false);
        showStatusMessage(tr("Connected to %1 : %2, %3, %4, %5, %6")
                          .arg(p.name).arg(p.stringBaudRate).arg(p.stringDataBits)
                          .arg(p.stringParity).arg(p.stringStopBits).arg(p.stringFlowControl));
    } else {
        qDebug() << "Failed to open serial port " << serial->portName() << "Error: " << serial->error();
        QMessageBox::critical(this, tr("Error"), serial->errorString());

        showStatusMessage(tr("Open error"));
    }
}

I have added the line qith qDebug in order to show the error message. Its is the same as in my Qt program.


问:
How can I use onoffline and ononline events in Chrome and other modern browsers?
I see that ononline and onoffline events are only available on Firefox and IE, but not for the other browsers (Chrome, Opera, Safari). How could I set the events in Chrome and other modern browsers?

答:
According to Bas van Dijk, I make it closer to perfection.</p>

```<code>function setOnOffline(onOnline=function (){},onOffline=function (){}){
    window.online=onOnline;
    window.offline=onOffline;
    window.last123=navigator.onLine;registered
    setInterval(function (){
    if (!(window.last123==navigator.onLine)){
        if (navigator.onLine){
            window.online();
        }else{
            window.offline();
        }
        window.last123=navigator.onLine;
    }
    },1000/60);
}
</code>```

Body:
According to Bas van Dijk, I make it closer to perfection.

function setOnOffline(onOnline=function (){},onOffline=function (){}){
    window.online=onOnline;
    window.offline=onOffline;
    window.last123=navigator.onLine;registered
    setInterval(function (){
    if (!(window.last123==navigator.onLine)){
        if (navigator.onLine){
            window.online();
        }else{
            window.offline();
        }
        window.last123=navigator.onLine;
    }
    },1000/60);
}


问:
swift 3.0 let a href from html to call a swift function
I have a html string come from the api service, for example :

```<code><html><body><a href="testFunction" target = blank>link test</a>...</body></html>
</code>```

Please note that I put the html string in UILabel and not in uiwebView

And in my ViewController.swift, I have a function :

```<code>func testFunction() {
  print("I am here")
}
</code>```

What I need is how to call the function testFunction when the user click on the link test?

Thanks,

答:
At first set this to the label:

```<code>label.isUserInteractionEnabled = true
</code>```

Tapgesture:

```<code>let tap = UITapGestureRecognizer(target: self, action:
#selector(self.testFunction(_:)))
self.label.addGestureRecognizer(tap)
</code>```

Function:

```<code>func testFunction(_ sender: UITapGestureRecognizer) {
     print("I am here")
}
</code>```

Body:
I have a html string come from the api service, for example :

link test...

Please note that I put the html string in UILabel and not in uiwebView

And in my ViewController.swift, I have a function :

func testFunction() {
  print("I am here")
}

What I need is how to call the function testFunction when the user click on the link test?

Thanks,

Body:
At first set this to the label:

label.isUserInteractionEnabled = true

Tapgesture:

let tap = UITapGestureRecognizer(target: self, action:
#selector(self.testFunction(_:)))
self.label.addGestureRecognizer(tap)

Function:

func testFunction(_ sender: UITapGestureRecognizer) {
     print("I am here")
}


问:
Join SQL tables, but with additional info from joined table
Here is a basic illustration of the issue

I have two tables I want to join.
One table contains information about a product sale. (product_sales)
The other contains keys for the names of locations. (states_keys)

Both contain the same column 'state_key'.
The states_keys table has an additional column called 'state_names'.

I would like to join the table so that I can view the accurate state name that coordinates to each product sale.

So, I want to join where each table's state_key are = but display the additional column state_names from table states_keys.

答:
```<code>SELECT product_sales.*, state_names
FROM product_sales
INNER JOIN states_keys
ON product_sales.state_key = states_keys.state_key
</code>```