问:
Hiding javaFX ColorPicker causes NullPointerException
In my fractal image generating program I allow the user to edit the colours of the onscreen image by displaying a javafx.scene.control.ColorPicker, as shown in the code below.

At the top I set up an event handler allowing the user to hide the ColorPicker and the GridPane wrapping it.   This works, in the sense that the intended behaviour occurs, but at the same time the JVM throws a NullPointerException.  The stack trace refers mainly to javafx classes and not at all to my executing class.

I have played around with the code and searched stackoverflow and beyond, but this one is stumping me.

Can anyone help me diagnose the cause please?   (Code and stack trace follow.)

```<code>scene.setOnKeyPressed(ev2 -> {
    if (ev2.getCode().equals(KeyCode.ENTER)) {
        System.out.println("\nEnter pressed, panel should hide...");
        huePanel.setVisible(false);     // press Enter to kill panel
        huePanel.getChildren().clear();
        root.getChildren().removeAll(huePanel);
    }
});

huePanel = new GridPane();
huePanel.setAlignment(Pos.TOP_CENTER);
root.getChildren().addAll(huePanel);
int cl = colours[colourscheme].length;
Rectangle[] squares = new Rectangle[cl];
ColorPicker[] pickers = new ColorPicker[cl];

for (int i = 0; i < cl; i++) {
    int squareSize = width / 20;
    squares[i] = new Rectangle(squareSize, squareSize, colours[colourscheme][i]);
    squares[i].setStroke(BLACK);
    squares[i].setStrokeWidth(2.0);
    GridPane.setRowIndex(squares[i], (i / 8) * 2);
    GridPane.setColumnIndex(squares[i], i % 8);

    pickers[i] = new ColorPicker(colours[colourscheme][i]);
    GridPane.setRowIndex(pickers[i], (i / 8) * 2 + 1);
    GridPane.setColumnIndex(pickers[i], i % 8);

    huePanel.getChildren().addAll(squares[i], pickers[i]);
}
for (int j = 0; j < cl; j++) {
    indexOfColourToModify = j;
    pickers[j].setOnAction(ev1 -> {
            ColorPicker cp = (ColorPicker)(ev1.getSource());
            int k = huePanel.getChildren().indexOf(cp) / 2;     // really (idx-1)/2, as idx is odd
                                                                // due to squares[]
            Color c = cp.getValue();
            colours[colourscheme][k] = c;
            huePanel.requestLayout();
            System.out.println("\ncolours[" + colourscheme + "][" + k + "] set to " + c);
            paintImage(screenImage[screenImageIndex], realMinIts, realMaxIts);
        }
    );
}
</code>```

=========================================================================

```<code>Enter pressed, panel should hide...
Exception in thread "JavaFX Application Thread" java.lang.NullPointerException
    at com.sun.javafx.scene.control.skin.ComboBoxPopupControl.positionAndShowPopup(ComboBoxPopupControl.java:197)
    at com.sun.javafx.scene.control.skin.ComboBoxPopupControl.show(ComboBoxPopupControl.java:170)
    at com.sun.javafx.scene.control.skin.ColorPickerSkin.show(ColorPickerSkin.java:464)
    at com.sun.javafx.scene.control.skin.ComboBoxBaseSkin.handleControlPropertyChanged(ComboBoxBaseSkin.java:127)
    at com.sun.javafx.scene.control.skin.ColorPickerSkin.handleControlPropertyChanged(ColorPickerSkin.java:470)
    at com.sun.javafx.scene.control.skin.BehaviorSkinBase.lambda$registerChangeListener$61(BehaviorSkinBase.java:197)
    at com.sun.javafx.scene.control.MultiplePropertyChangeListenerHandler$1.changed(MultiplePropertyChangeListenerHandler.java:55)
    at javafx.beans.value.WeakChangeListener.changed(WeakChangeListener.java:89)
    at com.sun.javafx.binding.ExpressionHelper$SingleChange.fireValueChangedEvent(ExpressionHelper.java:182)
    at com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:81)
    at javafx.beans.property.ReadOnlyBooleanPropertyBase.fireValueChangedEvent(ReadOnlyBooleanPropertyBase.java:72)
    at javafx.beans.property.ReadOnlyBooleanWrapper.fireValueChangedEvent(ReadOnlyBooleanWrapper.java:103)
    at javafx.beans.property.BooleanPropertyBase.markInvalid(BooleanPropertyBase.java:110)
    at javafx.beans.property.BooleanPropertyBase.set(BooleanPropertyBase.java:144)
    at javafx.scene.control.ComboBoxBase.setShowing(ComboBoxBase.java:185)
    at javafx.scene.control.ComboBoxBase.show(ComboBoxBase.java:391)
    at com.sun.javafx.scene.control.behavior.ComboBoxBaseBehavior.show(ComboBoxBaseBehavior.java:286)
    at com.sun.javafx.scene.control.behavior.ColorPickerBehavior.callAction(ColorPickerBehavior.java:82)
    at com.sun.javafx.scene.control.behavior.BehaviorBase.callActionForEvent(BehaviorBase.java:218)
    at com.sun.javafx.scene.control.behavior.ComboBoxBaseBehavior.callActionForEvent(ComboBoxBaseBehavior.java:136)
    at com.sun.javafx.scene.control.behavior.BehaviorBase.lambda$new$74(BehaviorBase.java:135)
    at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Scene$KeyHandler.process(Scene.java:3964)
    at javafx.scene.Scene$KeyHandler.access$1800(Scene.java:3910)
    at javafx.scene.Scene.impl_processKeyEvent(Scene.java:2040)
    at javafx.scene.Scene$ScenePeerListener.keyEvent(Scene.java:2501)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$KeyEventNotification.run(GlassViewEventHandler.java:217)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$KeyEventNotification.run(GlassViewEventHandler.java:149)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleKeyEvent$353(GlassViewEventHandler.java:248)
    at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleKeyEvent(GlassViewEventHandler.java:247)
    at com.sun.glass.ui.View.handleKeyEvent(View.java:546)
    at com.sun.glass.ui.View.notifyKey(View.java:966)
    at com.sun.glass.ui.gtk.GtkApplication._runLoop(Native Method)
    at com.sun.glass.ui.gtk.GtkApplication.lambda$null$49(GtkApplication.java:139)
    at java.lang.Thread.run(Thread.java:745)
</code>```

答:
From what I can guess - I don't see much from the stack and your code other than it's attempting to:

```<code>_popup.show(comboBoxBase.getScene().getWindow(),
                snapPosition(p.getX()),
                snapPosition(p.getY()));
</code>```

This likely may be due to the propagating event.

If your ColorPicker has focus, Enter will act on it, but at this point, it's been removed from the scene.

Try:

```<code>scene.setOnKeyPressed(ev2 -> {
    if (ev2.getCode().equals(KeyCode.ENTER)) {
        System.out.println("\nEnter pressed, panel should hide...");
        huePanel.setVisible(false);     // press Enter to kill panel
        huePanel.getChildren().clear();
        root.getChildren().removeAll(huePanel);
        ev2.consume();
    }
});
</code>```

Body:
In my fractal image generating program I allow the user to edit the colours of the onscreen image by displaying a javafx.scene.control.ColorPicker, as shown in the code below.

At the top I set up an event handler allowing the user to hide the ColorPicker and the GridPane wrapping it.   This works, in the sense that the intended behaviour occurs, but at the same time the JVM throws a NullPointerException.  The stack trace refers mainly to javafx classes and not at all to my executing class.

I have played around with the code and searched stackoverflow and beyond, but this one is stumping me.

Can anyone help me diagnose the cause please?   (Code and stack trace follow.)

scene.setOnKeyPressed(ev2 -> {
    if (ev2.getCode().equals(KeyCode.ENTER)) {
        System.out.println("\nEnter pressed, panel should hide...");
        huePanel.setVisible(false);     // press Enter to kill panel
        huePanel.getChildren().clear();
        root.getChildren().removeAll(huePanel);
    }
});

huePanel = new GridPane();
huePanel.setAlignment(Pos.TOP_CENTER);
root.getChildren().addAll(huePanel);
int cl = colours[colourscheme].length;
Rectangle[] squares = new Rectangle[cl];
ColorPicker[] pickers = new ColorPicker[cl];

for (int i = 0; i < cl; i++) {
    int squareSize = width / 20;
    squares[i] = new Rectangle(squareSize, squareSize, colours[colourscheme][i]);
    squares[i].setStroke(BLACK);
    squares[i].setStrokeWidth(2.0);
    GridPane.setRowIndex(squares[i], (i / 8) * 2);
    GridPane.setColumnIndex(squares[i], i % 8);

    pickers[i] = new ColorPicker(colours[colourscheme][i]);
    GridPane.setRowIndex(pickers[i], (i / 8) * 2 + 1);
    GridPane.setColumnIndex(pickers[i], i % 8);

    huePanel.getChildren().addAll(squares[i], pickers[i]);
}
for (int j = 0; j < cl; j++) {
    indexOfColourToModify = j;
    pickers[j].setOnAction(ev1 -> {
            ColorPicker cp = (ColorPicker)(ev1.getSource());
            int k = huePanel.getChildren().indexOf(cp) / 2;     // really (idx-1)/2, as idx is odd
                                                                // due to squares[]
            Color c = cp.getValue();
            colours[colourscheme][k] = c;
            huePanel.requestLayout();
            System.out.println("\ncolours[" + colourscheme + "][" + k + "] set to " + c);
            paintImage(screenImage[screenImageIndex], realMinIts, realMaxIts);
        }
    );
}

=========================================================================

Enter pressed, panel should hide...
Exception in thread "JavaFX Application Thread" java.lang.NullPointerException
    at com.sun.javafx.scene.control.skin.ComboBoxPopupControl.positionAndShowPopup(ComboBoxPopupControl.java:197)
    at com.sun.javafx.scene.control.skin.ComboBoxPopupControl.show(ComboBoxPopupControl.java:170)
    at com.sun.javafx.scene.control.skin.ColorPickerSkin.show(ColorPickerSkin.java:464)
    at com.sun.javafx.scene.control.skin.ComboBoxBaseSkin.handleControlPropertyChanged(ComboBoxBaseSkin.java:127)
    at com.sun.javafx.scene.control.skin.ColorPickerSkin.handleControlPropertyChanged(ColorPickerSkin.java:470)
    at com.sun.javafx.scene.control.skin.BehaviorSkinBase.lambda$registerChangeListener$61(BehaviorSkinBase.java:197)
    at com.sun.javafx.scene.control.MultiplePropertyChangeListenerHandler$1.changed(MultiplePropertyChangeListenerHandler.java:55)
    at javafx.beans.value.WeakChangeListener.changed(WeakChangeListener.java:89)
    at com.sun.javafx.binding.ExpressionHelper$SingleChange.fireValueChangedEvent(ExpressionHelper.java:182)
    at com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:81)
    at javafx.beans.property.ReadOnlyBooleanPropertyBase.fireValueChangedEvent(ReadOnlyBooleanPropertyBase.java:72)
    at javafx.beans.property.ReadOnlyBooleanWrapper.fireValueChangedEvent(ReadOnlyBooleanWrapper.java:103)
    at javafx.beans.property.BooleanPropertyBase.markInvalid(BooleanPropertyBase.java:110)
    at javafx.beans.property.BooleanPropertyBase.set(BooleanPropertyBase.java:144)
    at javafx.scene.control.ComboBoxBase.setShowing(ComboBoxBase.java:185)
    at javafx.scene.control.ComboBoxBase.show(ComboBoxBase.java:391)
    at com.sun.javafx.scene.control.behavior.ComboBoxBaseBehavior.show(ComboBoxBaseBehavior.java:286)
    at com.sun.javafx.scene.control.behavior.ColorPickerBehavior.callAction(ColorPickerBehavior.java:82)
    at com.sun.javafx.scene.control.behavior.BehaviorBase.callActionForEvent(BehaviorBase.java:218)
    at com.sun.javafx.scene.control.behavior.ComboBoxBaseBehavior.callActionForEvent(ComboBoxBaseBehavior.java:136)
    at com.sun.javafx.scene.control.behavior.BehaviorBase.lambda$new$74(BehaviorBase.java:135)
    at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Scene$KeyHandler.process(Scene.java:3964)
    at javafx.scene.Scene$KeyHandler.access$1800(Scene.java:3910)
    at javafx.scene.Scene.impl_processKeyEvent(Scene.java:2040)
    at javafx.scene.Scene$ScenePeerListener.keyEvent(Scene.java:2501)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$KeyEventNotification.run(GlassViewEventHandler.java:217)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$KeyEventNotification.run(GlassViewEventHandler.java:149)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleKeyEvent$353(GlassViewEventHandler.java:248)
    at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleKeyEvent(GlassViewEventHandler.java:247)
    at com.sun.glass.ui.View.handleKeyEvent(View.java:546)
    at com.sun.glass.ui.View.notifyKey(View.java:966)
    at com.sun.glass.ui.gtk.GtkApplication._runLoop(Native Method)
    at com.sun.glass.ui.gtk.GtkApplication.lambda$null$49(GtkApplication.java:139)
    at java.lang.Thread.run(Thread.java:745)

Body:
From what I can guess - I don't see much from the stack and your code other than it's attempting to:

_popup.show(comboBoxBase.getScene().getWindow(),
                snapPosition(p.getX()),
                snapPosition(p.getY()));

This likely may be due to the propagating event.

If your ColorPicker has focus, Enter will act on it, but at this point, it's been removed from the scene.

Try:

scene.setOnKeyPressed(ev2 -> {
    if (ev2.getCode().equals(KeyCode.ENTER)) {
        System.out.println("\nEnter pressed, panel should hide...");
        huePanel.setVisible(false);     // press Enter to kill panel
        huePanel.getChildren().clear();
        root.getChildren().removeAll(huePanel);
        ev2.consume();
    }
});


来源: stackexchange

问:
How to properly center the text?
I'm trying to center the text in the middle of JQM page, vertically and horizontally. Using 1.4.5, default theme.

In my .css I have:

```<code>.splashDiv {
    position: absolute;
    top: 50%;
    height: 50%;
    width: 100%;
    text-align: center;
    padding:0;
}
</code>```

HTML

```<code><div class="splashDiv" data-role="page">
    Please wait...
</div>
</code>```

The result is:

The text is vertically centered only if I remove top: 0 directive in developer tools(although not perfectly centered).

My question is what is the proper way according to JQM architecture to have what I want? I am not looking for quick/dirty workaround, unless there is no other way.

UPDATE

答:
You need to use the following css:</p>

```<code>top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to properly center the text?

Body:
I'm trying to center the text in the middle of JQM page, vertically and horizontally. Using 1.4.5, default theme.

In my .css I have:

.splashDiv {
    position: absolute;
    top: 50%;
    height: 50%;
    width: 100%;
    text-align: center;
    padding:0;
}

HTML

    Please wait...

The result is:

The text is vertically centered only if I remove top: 0 directive in developer tools(although not perfectly centered).

My question is what is the proper way according to JQM architecture to have what I want? I am not looking for quick/dirty workaround, unless there is no other way.

UPDATE

Body:
You need to use the following css:

top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;


问:
How to make two horizontally aligned tables?
Every time I create a HTML table, it starts on a new paragraph. Is it possible to override this behaviour, so that I have two tables on the same row?

I'm using also CSS.

答:
jsfiddle

If you need the horizontally aligned tables to fill 100% width, you need:
display:inline-table; and float:left;

ContentLicense: CC BY-SA 4.0


问:
Kendo UI File Structure : Proper use of view model, datasource, data binding
I am using Kendo UI framework for Front End development. Can anyone help as how to arrange file structure when it comes to complex project?</p>

答:
I feel I find supportive resource for Project Structure in Kendo UI here.

If anyone knows any better way of project structuring in Kendo, I would appreciate that.


问:
how can i disable unique constraints when savechanges in entity framework
I have come across an interesting problem in Entity Framework 6 and SQL Server.

We have a table with a Composite Key.  Here is an example;

```<code>ID  Col1  Col2
--  ----  ----
1   1     1
2   1     2
3   2     1
4   2     2
5   2     3
</code>```

So, Col2 is unique for each Col1.  I have a requirement to swap 2 values to produce this desired result...

```<code>ID  Col1  Col2
--  ----  ----
1   1     2
2   1     1
</code>```

I am using Entity Framework, load the object from the database, make my change, and call SaveChanges.

I Receive the exception: "Violation of UNIQUE KEY constraint 'UQ_TableA_Constraint1'. Cannot insert duplicate key in object 'dbo.TableA'."

Supposedly, SaveChanges is called in a transaction.  The EF Source seems to indicate it is, and the fact that a failed update is atomic would indicate this is working.  However, it also appears that updates are completed ROW BY ROW, even inside the transaction.  Thus that EF first performs an update to record 1 which temporarily produces a duplicate unique key.

Is there a manner to mitigate this?  I would rather not update to a temp value, call savechanges, and then update to the correct value as this potentially could fail and leave the data in an incorrect state.

Are there any options?

答:
I hope I understand your question.

Contraints must be satisfied also inside a transaction, this is a SQL Server (and other DBMSs) behaviour not an EF behaviour.

You can use a temporary value inside a transaction to be sure that everything went well.

If you need to run update queries (on multiple records), you can use an external library https://github.com/loresoft/EntityFramework.Extended (but if I understand your question, you won't solve contraint issues).

Body:
I have come across an interesting problem in Entity Framework 6 and SQL Server.

We have a table with a Composite Key.  Here is an example;

ID  Col1  Col2
--  ----  ----
1   1     1
2   1     2
3   2     1
4   2     2
5   2     3

So, Col2 is unique for each Col1.  I have a requirement to swap 2 values to produce this desired result...

ID  Col1  Col2
--  ----  ----
1   1     2
2   1     1

I am using Entity Framework, load the object from the database, make my change, and call SaveChanges.

I Receive the exception: "Violation of UNIQUE KEY constraint 'UQ_TableA_Constraint1'. Cannot insert duplicate key in object 'dbo.TableA'."

Supposedly, SaveChanges is called in a transaction.  The EF Source seems to indicate it is, and the fact that a failed update is atomic would indicate this is working.  However, it also appears that updates are completed ROW BY ROW, even inside the transaction.  Thus that EF first performs an update to record 1 which temporarily produces a duplicate unique key.

Is there a manner to mitigate this?  I would rather not update to a temp value, call savechanges, and then update to the correct value as this potentially could fail and leave the data in an incorrect state.

Are there any options?


问:
UWP MapControl and Parcel Boundaries
Is it possible to overlay parcel (property) lines on the UWP Map Control?  I found this blog article about Bing maps which the Map Control uses, but I could not find anything about UWP.  Further, once they are overlaid, I would like to allow the user to select a parcel and store it for later.

https://blogs.bing.com/maps/2010/07/12/overlaying-parcel-boundaries-on-bing-maps

Any help would be greatly appreciated.

Thanks

答:
It's possible to overlay parcel data on the UWP map control using similar methods to what you would use for the web control.
First you will need to find a source of the parcel data. The blog links to the DMP source data that provides a raster tile layer. You would need to register with DMP to use this service. Once you have access to the tile layer you would just add it to the map control using the Tile Layer API:
https://learn.microsoft.com/en-us/windows/uwp/maps-and-location/overlay-tiled-images
Note that a raster layer is basically static an non-interactive and so you wouldn't be able to do things like select it which you mentioned.
If you have other sources of parcel data you could add the parcels to the map as lines or polygons. See this reference under the section for lines and polygons:
https://learn.microsoft.com/en-us/windows/uwp/maps-and-location/display-poi
For example if you have a provider that gives you parcel shapes as GeoJSON you can parse that file and create polygons to add to the map.</p>

Title: UWP MapControl and Parcel Boundaries


问:
Is google OAuth 2.0 for service account part of the OAuth 2.0 standard?
Google API Authentication has a  OAuth 2.0 for service account
https://developers.google.com/identity/protocols/OAuth2ServiceAccount

Is that really part of OAuth 2.0 standard, or just google's own customized schema?

答:
That flow uses the so-called "JSON Web Token (JWT) Profile for OAuth 2.0 Authorization Grants" that is defined in https://www.rfc-editor.org/rfc/rfc7523. The relevant section of that RFC is: https://www.rfc-editor.org/rfc/rfc7523#section-2.1

It is an extension of the core OAuth 2.0 standard grant types defined in https://www.rfc-editor.org/rfc/rfc6749 but standardized in the IETF and thus an official part of the OAuth 2.0 eco-system.


问:
Management UI for Spring Boot or Node js Applications
We are considering migrating various integration services from vendor based solutions like TIBCO BW, WSO2 ESB, WebSphere Message Broker etc into custom Java (potentially SpringBoot) or Node.js.

Whilst it is relatively straight forward to migrate the service logic, e.g. get message from JMS, run XSLT, send to HTTP request, the missing piece that these vendor solutions provided was a Management UI which allowed you to:

view the version deployed

deploy new versions

view current configuration (ports, queues, url's etc)

start and stop services

perhaps enable logging

view processing statistics

etc

I may have a few hundred different JVM's / Spring Boot applications or Node.js instances, that I would like to provide a Management UI for.

What free open source management UI solutions exist in this space.

Or do I need to containerise all of these and use some container management technology like Kubernetes.

Or should I be using something like Nagios for this management task, which is more of a monitoring tool, but perhaps could be used as a Management UI.

答:
i had a similar use case couple of months ago. i chose the following technology stack and i was successful delivering a product in 2 months

Confluent Kafka

patternfly UI

Drools for rules engine rather than XSLT

Docker & Kubernates

Spring boot microservices

Netflix hysrix tubine dashboard

Spring cloud config server

MongoDB

All are opensource technologies, we didn't spent any $$$ but saved around 250K USD on vendor based licensed software


问:
Conditionally set a object property
Its possible to remove the .where clause if queryString is null?

I have tried ternary operator in the middle of expression, but doesn't work.

Also the equals expression dont allow: null, undefined or empty String.

```<code>CashierHistory
            .scan()
            .where('userId').equals(path['userId'])
            .where('status').equals(queryString['status']) # remove all this line in case of queryString['status'] is null
            .limit(10)
            .startKey(queryString)
            .exec(function (err, acc) {
                if (err == null) {
                    console.log(acc);
                    return cb(null, Api.response(acc));
                } else {
                    console.log(err['message']);
                    return cb(null, Api.errors(200, {5: err['message']}));
                }
            });
</code>```

Edit: I am using Dynogels (An ORM for Dynamodb)

答:
As dandavis said you can break your query into two parts</p>

```<code>var query = CashierHistory
        .scan()
        .where('userId').equals(path['userId']);

if (queryString['status']) {
    query = query.where('status').equals(queryString['status']);
}

return query.limit(10)
        .startKey(queryString)
        .exec(function (err, acc) {
            if (err == null) {
                console.log(acc);
                return cb(null, Api.response(acc));
            } else {
                console.log(err['message']);
                return cb(null, Api.errors(200, {5: err['message']}));
            }
        });
</code>```

Title: Conditionally set a object property

Body:
Its possible to remove the .where clause if queryString is null?

I have tried ternary operator in the middle of expression, but doesn't work.

Also the equals expression dont allow: null, undefined or empty String.

CashierHistory
            .scan()
            .where('userId').equals(path['userId'])
            .where('status').equals(queryString['status']) # remove all this line in case of queryString['status'] is null
            .limit(10)
            .startKey(queryString)
            .exec(function (err, acc) {
                if (err == null) {
                    console.log(acc);
                    return cb(null, Api.response(acc));
                } else {
                    console.log(err['message']);
                    return cb(null, Api.errors(200, {5: err['message']}));
                }
            });

Edit: I am using Dynogels (An ORM for Dynamodb)

Body:
As dandavis said you can break your query into two parts

var query = CashierHistory
        .scan()
        .where('userId').equals(path['userId']);

if (queryString['status']) {
    query = query.where('status').equals(queryString['status']);
}

return query.limit(10)
        .startKey(queryString)
        .exec(function (err, acc) {
            if (err == null) {
                console.log(acc);
                return cb(null, Api.response(acc));
            } else {
                console.log(err['message']);
                return cb(null, Api.errors(200, {5: err['message']}));
            }
        });


问:
Buttons not working with onclick and JavaScript
I am trying to make buttons that adds 10, 100, and 1000 to an input and that can clear the input field, but i can't get it to work. I have tried alle the different ways i know to add the script to my document(inline and external) but i can't seem to crack the code. The debug console tells me that The functions is not defined

EDIT:

The problem seems to be that when clicking the buttons the site redirects to the index file

var bet = document.getElementById('coincredits');
var cur = document.getElementById('coincredits').value;
var coins = document.getElementById('coins').value;

function clear() {
 bet.value = "";
}
function ten() {
 bet.value = cur + 10;
}
function hundred() {
 bet.value = cur + 100;
}
function thousand() {
 bet.value = cur + 1000;
}
function xtwo() {
 bet.value = cur * 2;
}
function max() {
 bet.value = coins;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h4>Coins:</h4><p id="coins">123456789</p>

<input type="number" name="coincredits" id="coincredits" required="" parsley-type="text" data-parsley-id="40">

<div>
  <button onclick="clear()">Clear</button>
  <button onclick="ten()">+10</button>
  <button onclick="hundred()">+100</button>
  <button onclick="thousand()">+1000</button>
  <button onclick="xtwo()">x2</button>
  <button onclick="max()">Max</button>
</div></code>```

答:
You have two problems here. One is you are setting  the bet and cur variables once on page load and not the latest value.
The second is that you need to get the value of coins by doing an innerHTML of the tag.

I fixed one of your functions, this will help you fix the rest.

```<code>function max() {
    var bet = document.getElementById('coincredits');
    var cur = document.getElementById('coincredits').value;
    var coinsTag = document.getElementById('coins');
    var coins= coinsTag.innerHTML;

    bet.value = coins;
}
</code>```

Body:
I am trying to make buttons that adds 10, 100, and 1000 to an input and that can clear the input field, but i can't get it to work. I have tried alle the different ways i know to add the script to my document(inline and external) but i can't seem to crack the code. The debug console tells me that The functions is not defined

EDIT:

The problem seems to be that when clicking the buttons the site redirects to the index file

var bet = document.getElementById('coincredits');
var cur = document.getElementById('coincredits').value;
var coins = document.getElementById('coins').value;

function clear() {
 bet.value = "";
}
function ten() {
 bet.value = cur + 10;
}
function hundred() {
 bet.value = cur + 100;
}
function thousand() {
 bet.value = cur + 1000;
}
function xtwo() {
 bet.value = cur * 2;
}
function max() {
 bet.value = coins;
}

Coins:

123456789

<input type="number" name="coincredits" id="coincredits" required="" parsley-type="text" data-parsley-id="40">

  <button onclick="clear()">Clear</button>
  <button onclick="ten()">+10</button>
  <button onclick="hundred()">+100</button>
  <button onclick="thousand()">+1000</button>
  <button onclick="xtwo()">x2</button>
  <button onclick="max()">Max</button>

Body:
You have two problems here. One is you are setting  the bet and cur variables once on page load and not the latest value.
The second is that you need to get the value of coins by doing an innerHTML of the tag.

I fixed one of your functions, this will help you fix the rest.

function max() {
    var bet = document.getElementById('coincredits');
    var cur = document.getElementById('coincredits').value;
    var coinsTag = document.getElementById('coins');
    var coins= coinsTag.innerHTML;

    bet.value = coins;
}


问:
Handler in subdirectory of AWS Lambda function not running
I'm getting an awfully unfortunate error on Lambda:

```<code>Unable to import module 'lib/index': Error
at require (internal/module.js:20:19)
</code>```

Which is strange because there is definitely a function called handler getting exported from lib/index...not sure if the whole subdirectory thing has been an issue for others so I wanted to ask.

sam-template.yaml

```<code>AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: Does something crazy
Resources:
  SomeFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: lib/index.handler
      Role: arn:aws:iam::...:role/lambda-role
      Runtime: nodejs6.10
      Timeout: 10
      Events:
        Timer:
          Type: Schedule
          Properties:
            Schedule: rate(1 minute)
</code>```

Module structure

```<code>|-- lib
|     `-- index.js
`-- src
      `-- index.js
</code>```

I have nested it here because I'm transpiling ES6 during my build process using the following, excerpt from package.json:
"build": "babel src -d lib"

buildspec.yaml

```<code>version: 0.1
phases:
    install:
        commands:
            - npm install
            - aws cloudformation package --template-file sam-template.yaml --s3-bucket some-bucket --output-template-file compiled-sam-template.yaml
    build:
        commands:
            - npm run build
    post_build:
        commands:
            - npm prune --production
artifacts:
    files:
        - 'node_modules/**/*'
        - 'lib/**/*'
        - 'compiled-template.yaml'
</code>```

答:
You are trying to import lib/index which will try to find a package named lib as if you did npm install --save lib but you are most likely trying to import a file relative to your own project and you are not giving it a relative path in your import.

Change 'lib/index' to './lib/index' - or '../lib/index' etc. - depending where it is and see if it helps.

By the way, if you're trying to import the file lib/index.js and not a directory lib/import/ then you may use a shorter ./lib path, as in:

```<code>const lib = require('./lib');
</code>```

Of course you didn't show even a single line of your code so I can only guess what you're doing.

Body:
I'm getting an awfully unfortunate error on Lambda:

Unable to import module 'lib/index': Error
at require (internal/module.js:20:19)

Which is strange because there is definitely a function called handler getting exported from lib/index...not sure if the whole subdirectory thing has been an issue for others so I wanted to ask.

sam-template.yaml

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: Does something crazy
Resources:
  SomeFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: lib/index.handler
      Role: arn:aws:iam::...:role/lambda-role
      Runtime: nodejs6.10
      Timeout: 10
      Events:
        Timer:
          Type: Schedule
          Properties:
            Schedule: rate(1 minute)

Module structure

|-- lib
|     `-- index.js
`-- src
      `-- index.js

I have nested it here because I'm transpiling ES6 during my build process using the following, excerpt from package.json:
"build": "babel src -d lib"

buildspec.yaml

version: 0.1
phases:
    install:
        commands:
            - npm install
            - aws cloudformation package --template-file sam-template.yaml --s3-bucket some-bucket --output-template-file compiled-sam-template.yaml
    build:
        commands:
            - npm run build
    post_build:
        commands:
            - npm prune --production
artifacts:
    files:
        - 'node_modules/**/*'
        - 'lib/**/*'
        - 'compiled-template.yaml'

Body:
You are trying to import lib/index which will try to find a package named lib as if you did npm install --save lib but you are most likely trying to import a file relative to your own project and you are not giving it a relative path in your import.

Change 'lib/index' to './lib/index' - or '../lib/index' etc. - depending where it is and see if it helps.

By the way, if you're trying to import the file lib/index.js and not a directory lib/import/ then you may use a shorter ./lib path, as in:

const lib = require('./lib');

Of course you didn't show even a single line of your code so I can only guess what you're doing.


问:
Php fopen is not creating files in the desired directory
if my script successfully creates a directory using mkdir($d, 0777, true) but the same script fails to create a file in the new directory using fopen($d.'/'.$f, 'w')

Could the mode of the directory holding both the script and the new directory be a culprit?

all is well on my windows appserve environment but my webserver doesn't generate the required file only the directory.

答: the trouble is my hosting plan not allowing something dompdf wants to do so I'm looking to update to a dedicated host, which will cost more.</p>


问:
Changing the default intro.js tooltip placement
I am using intro.js to set up a tour of my website, and I would like to set the default placement of the tooltip (when not attached to any element) near the top of the page instead of the vertical center.

It doesn't look like there is an option to set it directly, but is there a way to do it changing the CSS? (or by editing the source, although that's kind of a last resort).

答:
I looked into the intro.js documentation. you should be able to just add this line of code to your script.</p>

```<code>introJs().setOption("tooltipPosition", "top");
</code>```

Body:
I looked into the intro.js documentation. you should be able to just add this line of code to your script.

introJs().setOption("tooltipPosition", "top");


问:
How to deal with space input comparing word inverse C++
We are taking user input and reversing it in the background and asking the user what is the reverse. Then we compare realreverse and userreverse and say that it's correct or how many mistakes were made.  Also we are counting sentences with using dots, and the user should end his input with @.

For example:

```<code>hi. how are you doing. @
</code>```

or

```<code>hi bro how are u.
im good. @
</code>```

The problem is my program is only working if the input doesn't contain any spaces.

```<code>hihowareyoudoing. thanksimfinebro @
</code>```

If the input is like that, it's working.
it works

```<code>hihowareyoudoing.
thanksimfinebro. @
</code>```

This 2 column also working

code:
(program shows correct inverse for testing)

```<code>#include <iostream>
#include <string>
using namespace std;
void Comparison(string reverseReal, string reverseUser) {
    int wrongCount = 0;
    if (reverseReal.length() != reverseUser.length()) {
        cout << "These strings are not comparable." << endl;
    }
    else {
        for (int i = 0; i < reverseReal.length(); i++) {
            if (reverseReal.substr(i, 1) != reverseUser.substr(i, 1)) {
                wrongCount++;
            }
        }
        cout << "Number of mistakes: " << wrongCount << endl;
        if (wrongCount == 0){
            cout << "gj correct reverse" << endl;
        }
    }
}
string getReverse(string sentence) {

    string reverseResult = "";
    for (int i = sentence.length() - 1; i >= 0; i--) {
        reverseResult += sentence.substr(i, 1);
    }
    return reverseResult;
}
int findsnumber(string snumber)
{
    unsigned int sentences = 0, index = 0, length;
    string searchPattern = ".";
    length = snumber.length();
    while (index < length)
    {
        index = snumber.find(searchPattern, index);
        if (index != string::npos)
        {
            index += searchPattern.length();
            sentences++;
        }
    }
    return sentences;
}

// Gets the string until it finds a dot in it
string getOneSentence(string sentence) {
    while (sentence.find(".") != string::npos) {
        int dotFinder = 0;
        string sub = "";
        dotFinder = sentence.find(".");
        sub = sentence.substr(0, dotFinder);
        return sub;
    }
    return "";
}

int main() {

    string input = "";
    string result = "";
    string reverseReal = "";
    int i = 1;
    cout << "Welcome to my cancer c++ programme." << endl;
    cout << "Enter the paragraph with @ at the end to end it:" << endl;
    while (cin >> input && input != "@") {
        result += input + " ";
    }
    int sentnumber = findsnumber(result);
    cout << "Number of sentences in the given string " << sentnumber << endl;
    while (result.find(".") != string::npos) {
        string sub = "";
        string subReverse = "";
        string reverse = "";
        string reverseson = "";
        cout << i << "/" << sentnumber << endl;
        sub = getOneSentence(result);
        subReverse = getReverse(sub);
        cout << "reverse of the sub " << subReverse << endl;
        cout << "Sentence " << i << " : " << sub << endl;
        cout << "Enter the reverse of your sentence" << endl;
        while (cin >> reverse && reverse != "@"){
            reverseson += reverse + "";
        }
        Comparison(subReverse, reverseson);
        result = result.substr(result.find(".") + 2, result.length());
        i++;
    }
    cin.ignore();
    cin.get();
}
</code>```

答:
cin does not support input string with spaces.
 So, to input a string containing spaces you need to use getline()

The correct syntax is std::getline(std::cin, input);

Body:
We are taking user input and reversing it in the background and asking the user what is the reverse. Then we compare realreverse and userreverse and say that it's correct or how many mistakes were made.  Also we are counting sentences with using dots, and the user should end his input with @.

For example:

hi. how are you doing. @

or

hi bro how are u.
im good. @

The problem is my program is only working if the input doesn't contain any spaces.

hihowareyoudoing. thanksimfinebro @

If the input is like that, it's working.
it works

hihowareyoudoing.
thanksimfinebro. @

This 2 column also working

code:
(program shows correct inverse for testing)

#include <iostream>
#include <string>
using namespace std;
void Comparison(string reverseReal, string reverseUser) {
    int wrongCount = 0;
    if (reverseReal.length() != reverseUser.length()) {
        cout << "These strings are not comparable." << endl;
    }
    else {
        for (int i = 0; i < reverseReal.length(); i++) {
            if (reverseReal.substr(i, 1) != reverseUser.substr(i, 1)) {
                wrongCount++;
            }
        }
        cout << "Number of mistakes: " << wrongCount << endl;
        if (wrongCount == 0){
            cout << "gj correct reverse" << endl;
        }
    }
}
string getReverse(string sentence) {

    string reverseResult = "";
    for (int i = sentence.length() - 1; i >= 0; i--) {
        reverseResult += sentence.substr(i, 1);
    }
    return reverseResult;
}
int findsnumber(string snumber)
{
    unsigned int sentences = 0, index = 0, length;
    string searchPattern = ".";
    length = snumber.length();
    while (index < length)
    {
        index = snumber.find(searchPattern, index);
        if (index != string::npos)
        {
            index += searchPattern.length();
            sentences++;
        }
    }
    return sentences;
}

// Gets the string until it finds a dot in it
string getOneSentence(string sentence) {
    while (sentence.find(".") != string::npos) {
        int dotFinder = 0;
        string sub = "";
        dotFinder = sentence.find(".");
        sub = sentence.substr(0, dotFinder);
        return sub;
    }
    return "";
}

int main() {

    string input = "";
    string result = "";
    string reverseReal = "";
    int i = 1;
    cout << "Welcome to my cancer c++ programme." << endl;
    cout << "Enter the paragraph with @ at the end to end it:" << endl;
    while (cin >> input && input != "@") {
        result += input + " ";
    }
    int sentnumber = findsnumber(result);
    cout << "Number of sentences in the given string " << sentnumber << endl;
    while (result.find(".") != string::npos) {
        string sub = "";
        string subReverse = "";
        string reverse = "";
        string reverseson = "";
        cout << i << "/" << sentnumber << endl;
        sub = getOneSentence(result);
        subReverse = getReverse(sub);
        cout << "reverse of the sub " << subReverse << endl;
        cout << "Sentence " << i << " : " << sub << endl;
        cout << "Enter the reverse of your sentence" << endl;
        while (cin >> reverse && reverse != "@"){
            reverseson += reverse + "";
        }
        Comparison(subReverse, reverseson);
        result = result.substr(result.find(".") + 2, result.length());
        i++;
    }
    cin.ignore();
    cin.get();
}


问:
Preg capture the first apostrophe
I've mysql function from lib like this PREG_CAPTURE('/id\=\'(.*)\'/i', xml, 1, 1) , and I trying capture element from this log

```<code>"xml":id='t6e8u-73' type='chat'><body>\uD83D\uDE31</body><thread>fU9ie4T0mIaz</thread><active xmlns='http://jabber.org/protocol/chatstates'/><request xmlns='urn:xmpp:receipts'/></message>"
</code>```

The result is a captured all of them, but i need capture only first element like this id=t6e8u-73 Thank you

答:
Try using lazy quantifier:

```<code>id\=\'(.*?)\'
</code>```

Demo

Title: Preg capture the first apostrophe

Body:
I've mysql function from lib like this PREG_CAPTURE('/id\=\'(.*)\'/i', xml, 1, 1) , and I trying capture element from this log

"xml":id='t6e8u-73' type='chat'>\uD83D\uDE31<thread>fU9ie4T0mIaz</thread><active xmlns='http://jabber.org/protocol/chatstates'/><request xmlns='urn:xmpp:receipts'/></message>"

The result is a captured all of them, but i need capture only first element like this id=t6e8u-73 Thank you

Body:
Try using lazy quantifier:

id\=\'(.*?)\'

Demo


问:
Passing parameter to Route in React Router
I have defined a route which cannot be accessed unless the user has logged in. The code for this is as follows:

```<code>    const App = ({ userLoggedIn }) => {
return (
        <Router>
          <div className="App">
            <Header userLoggedIn={ userLoggedIn }/>
            <ProtectedRoute path='/content' component={ Day } userLoggedIn={ userLoggedIn } />
            <Footer />
          </div>
        </Router>
      );
    }
</code>```

I am passing the userLoggedIn as parameter as the App is keeping the state of it. I am defining ProtectedRoute in a similar way as the Auth example in React Router documentation.

```<code>const ProtectedRoute = ({ userLoggedIn, component, ...rest }) => (
  <Route {...rest} render={ props => (
    userLoggedIn ? (
      React.createElement(component, props)
    ) : (
      <Redirect to={{
        pathname: '/login',
        state: { from: props.location }
      }}/>
    )
  )}/>
)
</code>```

But userLoggedIn is always null (even when the value is not null before calling the ProtectedRoute).

I have created a simpler example which I'm testing in the App. I have added the following line:

```<code><TestRoute path='/test' userLoggedIn={ userLoggedIn }/>
</code>```

And created the TestRoute component as follows:

```<code>    const TestRoute = ({ userLoggedIn }) => {
  console.log(userLoggedIn);
  return (
    <Redirect to={{
      pathname: userLoggedIn ? '/yes' : '/no'
    }}/>
  )
}
</code>```

What I see now is than in the console appears null twice and then the real value for userLoggedIn... I guess the first time the component receives the null redirects to /no so when the real value "arrives" it doesn't go to /yes as it should...

How can I access the userLoggedIn param I'm passing? Does anyone has a similar example?

Thanks

答:
Ok, after trying several options I found something that works for me an it's even simpler than what I was trying to do.

In the App part where I have the Router I have created a Route that uses conditional coding:

```<code><Route path='/content' component={ userLoggedIn ? Day : LoginPage } />
</code>```

And that's all I need. If the user is logged in it renders the Day component, if it is not logged in then it redirects to the LoginPage. Maybe it's not the best solution but it works for me.

If someone has a better solution, please let me know.

Body:
I have defined a route which cannot be accessed unless the user has logged in. The code for this is as follows:

    const App = ({ userLoggedIn }) => {
return (
        <Router>

            <ProtectedRoute path='/content' component={ Day } userLoggedIn={ userLoggedIn } />

        </Router>
      );
    }

I am passing the userLoggedIn as parameter as the App is keeping the state of it. I am defining ProtectedRoute in a similar way as the Auth example in React Router documentation.

const ProtectedRoute = ({ userLoggedIn, component, ...rest }) => (
  <Route {...rest} render={ props => (
    userLoggedIn ? (
      React.createElement(component, props)
    ) : (
      <Redirect to={{
        pathname: '/login',
        state: { from: props.location }
      }}/>
    )
  )}/>
)

But userLoggedIn is always null (even when the value is not null before calling the ProtectedRoute).

I have created a simpler example which I'm testing in the App. I have added the following line:

<TestRoute path='/test' userLoggedIn={ userLoggedIn }/>

And created the TestRoute component as follows:

    const TestRoute = ({ userLoggedIn }) => {
  console.log(userLoggedIn);
  return (
    <Redirect to={{
      pathname: userLoggedIn ? '/yes' : '/no'
    }}/>
  )
}

What I see now is than in the console appears null twice and then the real value for userLoggedIn... I guess the first time the component receives the null redirects to /no so when the real value "arrives" it doesn't go to /yes as it should...

How can I access the userLoggedIn param I'm passing? Does anyone has a similar example?

Thanks

Body:
Ok, after trying several options I found something that works for me an it's even simpler than what I was trying to do.

In the App part where I have the Router I have created a Route that uses conditional coding:

<Route path='/content' component={ userLoggedIn ? Day : LoginPage } />

And that's all I need. If the user is logged in it renders the Day component, if it is not logged in then it redirects to the LoginPage. Maybe it's not the best solution but it works for me.

If someone has a better solution, please let me know.


问:
Protractor: stop do while loop once element is found
In non-Angular page using Protractor I have a situation where I have to loop trough some list of elements on the page and once I find the element I'm looking for, I have to stop the loop and click on that element.

Page object file:

```<code>var homePage = function() {
    this.elementLists = browser.element(by.id('list')).all(by.css('div.list'));
    this.elementLink = browser.element(by.id('list')).element(by.css('div[data-code="GAA"]'));
    this.paginationRight = browser.element(by.css('.navi-right'));
    ...
}
module.exports = homePage;
</code>```

Spec file:

```<code>// page objects
var homePage = require('../home_page/home_page.js');

// variables
var maxLoopCount = '';
var i = 0;

describe(...
    it(...
        // initialize page object
        var home = new homePage();

        // store number of listsinto a variable
        home.elementLists.count().then(function(num) {
            maxLoopCount = num;

            // click on right paginator arrow until element is displayed in the list
            while (i < maxLoopCount) {
                home.paginationRight.click();
                browser.sleep(1500);
                if (expect(home.elementLink.isPresent()).toBeTruthy()) {
                    break;
                }
                i++;
            };
    });
});
</code>```

I know I should use if (elementFound === true), but how can I do that?

答:
I'd suggest something a little more recursive.

protractor.expectedCondition is also a gold mind when waiting for things to happen

```<code>// page objects
var homePage = require('../home_page/home_page.js');

// variables
var maxLoopCount = '';
var i = 0;

describe(...
  it(...
    // initialize page object
    var home = new homePage();

    // store number of listsinto a variable
    home.elementLists.count().then(function(num) {
        maxLoopCount = num;

        // click on right paginator arrow until element is displayed in the list
        nextPageAndCheck(1, maxLoopCount);
    });
 });

nextPageAndCheck = function(page, pageCount) {
  if(page <= pageCount) {
    home.paginationRight.click();
    browser.wait(protractor.expectedCondition.visibilityOf(home.elementLink),1500, "not on this page").then(
       function(passed){return passed},
       function(error) {
          nextPageAndCheck(page++, pageCount);
       })
  } else {
       throw("couldn't find it error")
  }
 }
</code>```

Body:
In non-Angular page using Protractor I have a situation where I have to loop trough some list of elements on the page and once I find the element I'm looking for, I have to stop the loop and click on that element.

Page object file:

var homePage = function() {
    this.elementLists = browser.element(by.id('list')).all(by.css('div.list'));
    this.elementLink = browser.element(by.id('list')).element(by.css('div[data-code="GAA"]'));
    this.paginationRight = browser.element(by.css('.navi-right'));
    ...
}
module.exports = homePage;

Spec file:

// page objects
var homePage = require('../home_page/home_page.js');

// variables
var maxLoopCount = '';
var i = 0;

describe(...
    it(...
        // initialize page object
        var home = new homePage();

        // store number of listsinto a variable
        home.elementLists.count().then(function(num) {
            maxLoopCount = num;

            // click on right paginator arrow until element is displayed in the list
            while (i < maxLoopCount) {
                home.paginationRight.click();
                browser.sleep(1500);
                if (expect(home.elementLink.isPresent()).toBeTruthy()) {
                    break;
                }
                i++;
            };
    });
});

I know I should use if (elementFound === true), but how can I do that?

Body:
I'd suggest something a little more recursive.

protractor.expectedCondition is also a gold mind when waiting for things to happen

// page objects
var homePage = require('../home_page/home_page.js');

// variables
var maxLoopCount = '';
var i = 0;

describe(...
  it(...
    // initialize page object
    var home = new homePage();

    // store number of listsinto a variable
    home.elementLists.count().then(function(num) {
        maxLoopCount = num;

        // click on right paginator arrow until element is displayed in the list
        nextPageAndCheck(1, maxLoopCount);
    });
 });

nextPageAndCheck = function(page, pageCount) {
  if(page <= pageCount) {
    home.paginationRight.click();
    browser.wait(protractor.expectedCondition.visibilityOf(home.elementLink),1500, "not on this page").then(
       function(passed){return passed},
       function(error) {
          nextPageAndCheck(page++, pageCount);
       })
  } else {
       throw("couldn't find it error")
  }
 }


问:
How to open the Save as ..dialog on click of the image?
Here is the code.

On click of the link , the save as dialog should open

```<code><a href="http://www.experts-exchange.com/xp/images/newNavLogo.png" target="_new">
<img src="http://www.experts-exchange.com/xp/images/newNavLogo.png" align="left" alt="" />
</a>
</code>```

How can we achive this using jQuery, or javaScript?

答:
```<code>$("#img").click(function() {
 document.execCommand('SaveAs','1','give img location here');
});
</code>```

If that doesnt works use this jquery plugins for cross browser function "Cross-browser designMode"

http://plugins.jquery.com/project/designMode

ContentLicense: CC BY-SA 2.5

Body:
Here is the code.

On click of the link , the save as dialog should open

How can we achive this using jQuery, or javaScript?

Body:
$("#img").click(function() {
 document.execCommand('SaveAs','1','give img location here');
});

If that doesnt works use this jquery plugins for cross browser function "Cross-browser designMode"

http://plugins.jquery.com/project/designMode


问:
Parsing csv file in scala
How can i parse this csv file in Scala, to extract an object Data contain (date,time,longitude,latitude)

*M…….:Dy4.5

*N……….:14_540

*V…..:N

*S….:1.2.1

*yyyy/mm/dd;hh:mm:ss;long;lat

2016/05/09;12:50:19;-122.45006;38.47320

2016/05/09;13:04:10;-122.45011;38.47317

i already wrote this function but it just read the file, i don't know how to transform it into object

```<code>def readData(fileName:String): Vector[Array[String]] = {
      for {
        line <- Source.fromFile(fileName).getLines().toVector
        values = line.split(";").map(_.trim)
      } yield values
    }
</code>```

答:
Assuming you have class Data

```<code>case class Data(date: String, time: String, longitude: String, latitude: String)
</code>```

(date and time are strings just for simplifying example).

The code below will give you a vector of Data objects

```<code>def readData(fileName:String): Vector[Data] = {
  for {
    line <- Source.fromFile(fileName).getLines().toVector
    values = line.split(",").map(_.trim)
    date = Date(values(0), values(1), values(2), values(3))
  } yield date
}
</code>```

Title: Parsing csv file in scala

Body:
How can i parse this csv file in Scala, to extract an object Data contain (date,time,longitude,latitude)

*M…….:Dy4.5

*N……….:14_540

*V…..:N

*S….:1.2.1

*yyyy/mm/dd;hh:mm:ss;long;lat

2016/05/09;12:50:19;-122.45006;38.47320

2016/05/09;13:04:10;-122.45011;38.47317

i already wrote this function but it just read the file, i don't know how to transform it into object

def readData(fileName:String): Vector[Array[String]] = {
      for {
        line <- Source.fromFile(fileName).getLines().toVector
        values = line.split(";").map(_.trim)
      } yield values
    }

Body:
Assuming you have class Data

case class Data(date: String, time: String, longitude: String, latitude: String)

(date and time are strings just for simplifying example).

The code below will give you a vector of Data objects

def readData(fileName:String): Vector[Data] = {
  for {
    line <- Source.fromFile(fileName).getLines().toVector
    values = line.split(",").map(_.trim)
    date = Date(values(0), values(1), values(2), values(3))
  } yield date
}


问:
PHP Script does not seem to work
I run a script on my webspace which is used for an android application. Though, it does not seem to work. On some webspaces I get a blank site when I try reaching it, on others I receive a 500 Internal Server Error. Though this script should work properly because it used to do so.

It is supposed to get all information from a table and echo it after some INNER JOINs. I could not track the error even after some mysqli_error checks and some echos to check variables etc.

The variable $con does exist, the connection should work properly. I just removed it for stack overflow ^^.

```<code> <?php

$subId = 1;

$sql = "SELECT articles.a_id, sciences.science, articles.title, articles.content, login.username, articles.date, articles.viewed, articles.timestamp FROM articles
                INNER JOIN sciences ON articles.s_id = sciences.s_id
                INNER JOIN login ON articles.author = login.id
                WHERE articles.s_id = ".$subId."
                ORDER BY timestamp DESC";

if (!$res = mysqli_query($con,$sql)) {
    echo "FAIL";
    echo mysqli_error($con);
}
else {

$result = array();

while($row = mysqli_fetch_array($res)){
array_push($result,
array('a_id'=>$row[0],
'science'=>$row[1],
'title'=>$row[2],
'content'=>$row[3],
'author'=>$row[4],
'date'=>$row[5],
'viewed'=>$row[6],
'timestamp'=>$row[7]
));
}

echo json_encode(array("result"=>$result));
}
mysqli_close($con);

?>
</code>```

EDIT: I updated my code:

```<code>    <?php

$subId = 1;

$con = mysqli_connect("HOST", "USER", "PASSWORD", "DATABASE");

if (!$con)
{
echo "Cant't connect to MySQL.<br>";
echo "Debug: " . mysqli_connect_errno()
}

$sql = "SELECT articles.a_id, sciences.science, articles.title, articles.content, login.username, articles.date, articles.viewed, articles.timestamp FROM articles
INNER JOIN sciences ON articles.s_id = sciences.s_id
INNER JOIN login ON articles.author = login.id
WHERE articles.s_id = ".$subId."
ORDER BY timestamp DESC";

if (!$res = $con->query($sql))
{
    echo "FAIL";
}
else
{

    $result = array();

    while($row = $con->fetchArray($res))
    {
        array_push($result); //use the query to rename fields, if needed
    }

    echo json_encode(array("result"=>$result));
}

?>
</code>```

答:
Apparently you forgot

$con = mysqli_connect("localhost","my_user","my_password","my_db");

at the start of your script.

Title: PHP Script does not seem to work

Body:
I run a script on my webspace which is used for an android application. Though, it does not seem to work. On some webspaces I get a blank site when I try reaching it, on others I receive a 500 Internal Server Error. Though this script should work properly because it used to do so.

It is supposed to get all information from a table and echo it after some INNER JOINs. I could not track the error even after some mysqli_error checks and some echos to check variables etc.

The variable $con does exist, the connection should work properly. I just removed it for stack overflow ^^.

 <?php

$subId = 1;

$sql = "SELECT articles.a_id, sciences.science, articles.title, articles.content, login.username, articles.date, articles.viewed, articles.timestamp FROM articles
                INNER JOIN sciences ON articles.s_id = sciences.s_id
                INNER JOIN login ON articles.author = login.id
                WHERE articles.s_id = ".$subId."
                ORDER BY timestamp DESC";

if (!$res = mysqli_query($con,$sql)) {
    echo "FAIL";
    echo mysqli_error($con);
}
else {

$result = array();

while($row = mysqli_fetch_array($res)){
array_push($result,
array('a_id'=>$row[0],
'science'=>$row[1],
'title'=>$row[2],
'content'=>$row[3],
'author'=>$row[4],
'date'=>$row[5],
'viewed'=>$row[6],
'timestamp'=>$row[7]
));
}

echo json_encode(array("result"=>$result));
}
mysqli_close($con);

?>

EDIT: I updated my code:

    <?php

$subId = 1;

$con = mysqli_connect("HOST", "USER", "PASSWORD", "DATABASE");

if (!$con)
{
echo "Cant't connect to MySQL.
";
echo "Debug: " . mysqli_connect_errno()
}

$sql = "SELECT articles.a_id, sciences.science, articles.title, articles.content, login.username, articles.date, articles.viewed, articles.timestamp FROM articles
INNER JOIN sciences ON articles.s_id = sciences.s_id
INNER JOIN login ON articles.author = login.id
WHERE articles.s_id = ".$subId."
ORDER BY timestamp DESC";

if (!$res = $con->query($sql))
{
    echo "FAIL";
}
else
{

    $result = array();

    while($row = $con->fetchArray($res))
    {
        array_push($result); //use the query to rename fields, if needed
    }

    echo json_encode(array("result"=>$result));
}

?>


问:
The return value of methods when adding a COM Reference generated proxy stub in C#
I have this method in my ATL project which exposes a COM object (snippet taken from my *.idl file):

```<code>[id(1)] HRESULT Create([in, string] CHAR* location, [out] CerberusErrorDetails* details);
</code>```

After registering my object and adding a reference to it from my managed C# code, it generates the following proxy stub C# code for this method:

```<code>[DispId(1)]
void Create(string location, out CerberusErrorDetails details);
</code>```

There are a few problems with this stub for me which I have been unable to sort out. Firstly, it does not return an int value (with respect to the returned HRESULT) in managed code to tell me what error has actually occurred. Secondly, the method will throw an exception instead of returning the error code. Is there a way to have the function return an int such that I can then parse the details object if it does not return 0, or are there any alternatives to get the behavior I want? Any help is greatly appreciated. If you need more details, feel free to ask and I'll update the question. Thank you!

答:
Yes, it's possible to bypass the default exception translation behavior of the COM interop layer. However, you'll have to redefine your native COM interface and decorate all methods with the PreserveSig attribute:

```<code>[ComImport]
[Guid("xxx-yyy-zzz")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface ICOMInterfaceImp
{
     [PreserveSig]
     int Create(string location, out CerberusErrorDetails details);
}
</code>```

You can then use this interface in your client:

```<code>ICOMInterfaceImp obj = (ICOMInterfaceImp)new CoClassImpl();
</code>```

As an alternative, you may also use the updated type library importer (tlbimp.exe) from here and pass the /PreserveSig flag.

Body:
I have this method in my ATL project which exposes a COM object (snippet taken from my *.idl file):

[id(1)] HRESULT Create([in, string] CHAR* location, [out] CerberusErrorDetails* details);

After registering my object and adding a reference to it from my managed C# code, it generates the following proxy stub C# code for this method:

[DispId(1)]
void Create(string location, out CerberusErrorDetails details);

There are a few problems with this stub for me which I have been unable to sort out. Firstly, it does not return an int value (with respect to the returned HRESULT) in managed code to tell me what error has actually occurred. Secondly, the method will throw an exception instead of returning the error code. Is there a way to have the function return an int such that I can then parse the details object if it does not return 0, or are there any alternatives to get the behavior I want? Any help is greatly appreciated. If you need more details, feel free to ask and I'll update the question. Thank you!

Body:
Yes, it's possible to bypass the default exception translation behavior of the COM interop layer. However, you'll have to redefine your native COM interface and decorate all methods with the PreserveSig attribute:

[ComImport]
[Guid("xxx-yyy-zzz")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface ICOMInterfaceImp
{
     [PreserveSig]
     int Create(string location, out CerberusErrorDetails details);
}

You can then use this interface in your client:

ICOMInterfaceImp obj = (ICOMInterfaceImp)new CoClassImpl();

As an alternative, you may also use the updated type library importer (tlbimp.exe) from here and pass the /PreserveSig flag.


问:
Using JetBrain's MPS to create an editor plugin
Can I use MPS to create a "conventional" language plugin for IntelliJ?

It looks like MPS' core feature is the transcription from a DSL to Java. However I just want to define the DSL syntax and editor to ship it as a standalone language plugin via the JetBrain plugin repository.

I am uncertain whether that is the purpose of MPS or I have to use the Grammar-Kit to create the plugin as it is described here.

答:
Yes, MPS allows you to create IDEA plugins, just like the Grammar-Kit does. Take the MPS route, if you need any of its core features - projectional editor, modular languages or multi-stage code generator.

Vaclav


问:
C Split Char Array into an Array of Arrays
how do i convert

```<code>char* string = "test test test test";
</code>```

into

```<code>char* array = ["test","test","test","test"];
</code>```

if the length of the array is unknown?

Ty guys

答:
If you're allowed to modify the memory, then you can do this:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *get_next_start(char *str, char delim, int terminate) {
    char *p;
    p = strchr(str, delim);
    if (p != NULL) {
        if (terminate) {
            /* only nul-terminate the string on the second pass */
            *p = '\0';
        }
        p += 1;
    }
    return p;
}

int main(void) {
    char string[] = "test test test test";
    char **string_list;
    char *p;
    size_t i;

    /* count the elements... */
    i = 0;
    for (p = string; p != NULL; p = get_next_start(p, ' ', 0)) {
        i += 1;
    }
    printf("items: %zd\n", i);

    /* get some memory for the table */
    string_list = malloc(sizeof(string_list) * (i + 1));

    /* populate the table */
    i = 0;
    for (p = string; p != NULL; p = get_next_start(p, ' ', 1)) {
        string_list[i] = p; /* store the next item... */
        i += 1;
    }
    string_list[i] = NULL; /* terminate the list with NULL */

    /* print the table */
    for (i = 0; string_list[i] != NULL; i++) {
        printf("%3zd: [%s]\n", i, string_list[i]);
    }

    /* free the memory */
    free(string_list);

    return 0;
}
```

Note the declaration of string...

char string[] = "test test test test" places the data on the stack

char *string = "test test test test" places the data in read-only memory

If you're not allowed to modify the memory, and want a single pass, then you can use strndup() to duplicate the strings, and realloc() to allocate and resize the table.

Body:
how do i convert

char* string = "test test test test";

into

char* array = ["test","test","test","test"];

if the length of the array is unknown?

Ty guys

Body:
If you're allowed to modify the memory, then you can do this:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *get_next_start(char *str, char delim, int terminate) {
    char *p;
    p = strchr(str, delim);
    if (p != NULL) {
        if (terminate) {
            /* only nul-terminate the string on the second pass */
            *p = '\0';
        }
        p += 1;
    }
    return p;
}

int main(void) {
    char string[] = "test test test test";
    char **string_list;
    char *p;
    size_t i;

    /* count the elements... */
    i = 0;
    for (p = string; p != NULL; p = get_next_start(p, ' ', 0)) {
        i += 1;
    }
    printf("items: %zd\n", i);

    /* get some memory for the table */
    string_list = malloc(sizeof(string_list) * (i + 1));

    /* populate the table */
    i = 0;
    for (p = string; p != NULL; p = get_next_start(p, ' ', 1)) {
        string_list[i] = p; /* store the next item... */
        i += 1;
    }
    string_list[i] = NULL; /* terminate the list with NULL */

    /* print the table */
    for (i = 0; string_list[i] != NULL; i++) {
        printf("%3zd: [%s]\n", i, string_list[i]);
    }

    /* free the memory */
    free(string_list);

    return 0;
}

Note the declaration of string...

char string[] = "test test test test" places the data on the stack

char *string = "test test test test" places the data in read-only memory

If you're not allowed to modify the memory, and want a single pass, then you can use strndup() to duplicate the strings, and realloc() to allocate and resize the table.


问:
SSL Enabled Storm Kafka Spout
I wated to know is there any Kafka Spout which supports Secure Kafka Brokers.
KafkaSpout from apache storm is not having any support for SSL Kafka.

```<code>public KafkaSpout(SpoutConfig spoutConf) {
    _spoutConfig = spoutConf;
}
</code>```

Below mentioned Kafka not taking in any parameters for SSL Kafka producer/consumer support.

```<code>public KafkaConfig(BrokerHosts hosts, String topic) {
        this(hosts, topic, kafka.api.OffsetRequest.DefaultClientId());
    }

    public KafkaConfig(BrokerHosts hosts, String topic, String clientId) {
        this.hosts = hosts;
        this.topic = topic;
        this.clientId = clientId;
    }
</code>```

Please let me know is there any way we can achive the secure Kafka Message Stream Processing with storm topology.

答:
Storm's old kafka-spout uses simple consumer API for which security is not supported. If you are looking to use SSL with kafka consumer you should be using
https://github.com/apache/storm/tree/master/external/storm-kafka-client
Here are the details
https://github.com/apache/storm/blob/master/docs/storm-kafka-client.md

To enable SSL its similar to what you would do regular kafka-consumer, you can follow the details in here
http://kafka.apache.org/documentation.html#security_ssl

Title: SSL Enabled Storm Kafka Spout

Body:
I wated to know is there any Kafka Spout which supports Secure Kafka Brokers.
KafkaSpout from apache storm is not having any support for SSL Kafka.

public KafkaSpout(SpoutConfig spoutConf) {
    _spoutConfig = spoutConf;
}

Below mentioned Kafka not taking in any parameters for SSL Kafka producer/consumer support.

public KafkaConfig(BrokerHosts hosts, String topic) {
        this(hosts, topic, kafka.api.OffsetRequest.DefaultClientId());
    }

    public KafkaConfig(BrokerHosts hosts, String topic, String clientId) {
        this.hosts = hosts;
        this.topic = topic;
        this.clientId = clientId;
    }

Please let me know is there any way we can achive the secure Kafka Message Stream Processing with storm topology.


问:
How can I pass arguments off a QFile to other function on QT?
I have this code, and i want to pass the directory off the file selected on the "void MainWindow::on_pushButton_2_clicked() " function to the " char* videoName ". How can I do it?

 I dont know how to do it, please help me!!!!1

```<code>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <opencv2/opencv.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/imgproc.hpp>
#include <iostream>
#include <QFileDialog>
#include <QMessageBox>
using namespace std;
using namespace cv;
char arg1;
int stop;

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{

ui->setupUi(this);

}

MainWindow::~MainWindow()
{

delete ui;
}

void MainWindow::on_pushButton_clicked()
{
   char* videoName = ???
   Mat FrameAtual, suave_image;
   vector<Vec3f> circles;

   namedWindow("Video Processado", CV_WINDOW_AUTOSIZE);

   VideoCapture capture(videoName);
   if (!capture.isOpened())
       printf ("1");

           bool stop(false);

                                                                             //Condi��o de parada se usu�rio pressionar alguma tecla durante execu��o

   double FrameRate = capture.get(CV_CAP_PROP_FPS);                                   //Obter taxa de quadros do v�deo a ser processado
   int Delay = 1000 / FrameRate;
   //cout << "Delay = " << Delay;

   while (!stop) {
       if (!capture.read(FrameAtual))                                                   //L� pr�ximo frame, se existir; se n�o existe sai da execu��o
           break;

       cvtColor(FrameAtual, FrameAtual, CV_BGR2GRAY);

       GaussianBlur(FrameAtual, suave_image, Size(5, 5), 1.0);
       HoughCircles(suave_image, circles, CV_HOUGH_GRADIENT, 2, 230, 120,    100, 25, 80);
       vector<Vec3f>::const_iterator itc = circles.begin();
       while (itc != circles.end()) {
           circle(FrameAtual, Point((*itc)[0], (*itc)[1]), (*itc)[2],  Scalar(255), 2);
           ++itc;
       }

       imshow("Video Processado", FrameAtual);

       if (cv::waitKey(Delay) >= 0)                                                 //Introduz delay antes de passar ao prox frame ou interrompe se usu�rio pressionar tecla
           stop = true;
   }

}

void MainWindow::on_pushButton_2_clicked()
{
QString filename=QFileDialog::getOpenFileName(

            this,
            tr("Open File"),
            "/home/pi",
            "All Files (*.*);;"

            );
QMessageBox::information(this,tr("File Name"),filename);

}
</code>```

答:
There are many ways:

you are using the variable in same "mainwindow" class it self.

And also based on function name, I assume you are trying to use the "videoname" in another slot.

so just declare "videoname" as a class private variable.

and assign the filename/dirctory name to your "char*" using "qStr.toLatin1().data()"

Pseudo code below:

```<code>  void MainWindow::on_pushButton_2_clicked()
    {

    //if you want file name
 QString filename  = QFileDialog::getOpenFileName(

                this,
                tr("Open File"),
                "/home/pi",
                "All Files (*.*);;"

                );

    _videoname = filename.toLatin1().data(); //_videoname (const char*) is your class private variable. you can use any where with in the class.

    //Similary if you want directory name

    QString dir = QFileDialog::getExistingDirectory(this, tr("Open Directory"),
                                                    "/home/pi",
                                                    QFileDialog::ShowDirsOnly
                                                    | QFileDialog::DontResolveSymlinks);

    _dirname = dir.toLatin1().data();//_dirname (const char*) is your class private variable. you can use any where in the class.

    QMessageBox::information(this,tr("File Name"),filename);

    }
</code>```

Body:
I have this code, and i want to pass the directory off the file selected on the "void MainWindow::on_pushButton_2_clicked() " function to the " char* videoName ". How can I do it?

 I dont know how to do it, please help me!!!!1

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <opencv2/opencv.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/imgproc.hpp>
#include <iostream>
#include <QFileDialog>
#include <QMessageBox>
using namespace std;
using namespace cv;
char arg1;
int stop;

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{

ui->setupUi(this);

}

MainWindow::~MainWindow()
{

delete ui;
}

void MainWindow::on_pushButton_clicked()
{
   char* videoName = ???
   Mat FrameAtual, suave_image;
   vector<Vec3f> circles;

   namedWindow("Video Processado", CV_WINDOW_AUTOSIZE);

   VideoCapture capture(videoName);
   if (!capture.isOpened())
       printf ("1");

           bool stop(false);

                                                                             //Condi��o de parada se usu�rio pressionar alguma tecla durante execu��o

   double FrameRate = capture.get(CV_CAP_PROP_FPS);                                   //Obter taxa de quadros do v�deo a ser processado
   int Delay = 1000 / FrameRate;
   //cout << "Delay = " << Delay;

   while (!stop) {
       if (!capture.read(FrameAtual))                                                   //L� pr�ximo frame, se existir; se n�o existe sai da execu��o
           break;

       cvtColor(FrameAtual, FrameAtual, CV_BGR2GRAY);

       GaussianBlur(FrameAtual, suave_image, Size(5, 5), 1.0);
       HoughCircles(suave_image, circles, CV_HOUGH_GRADIENT, 2, 230, 120,    100, 25, 80);
       vector<Vec3f>::const_iterator itc = circles.begin();
       while (itc != circles.end()) {
           circle(FrameAtual, Point((*itc)[0], (*itc)[1]), (*itc)[2],  Scalar(255), 2);
           ++itc;
       }

       imshow("Video Processado", FrameAtual);

       if (cv::waitKey(Delay) >= 0)                                                 //Introduz delay antes de passar ao prox frame ou interrompe se usu�rio pressionar tecla
           stop = true;
   }

}

void MainWindow::on_pushButton_2_clicked()
{
QString filename=QFileDialog::getOpenFileName(

            this,
            tr("Open File"),
            "/home/pi",
            "All Files (*.*);;"

            );
QMessageBox::information(this,tr("File Name"),filename);

}

Body:
There are many ways:

you are using the variable in same "mainwindow" class it self.

And also based on function name, I assume you are trying to use the "videoname" in another slot.

so just declare "videoname" as a class private variable.

and assign the filename/dirctory name to your "char*" using "qStr.toLatin1().data()"

Pseudo code below:

  void MainWindow::on_pushButton_2_clicked()
    {

    //if you want file name
 QString filename  = QFileDialog::getOpenFileName(

                this,
                tr("Open File"),
                "/home/pi",
                "All Files (*.*);;"

                );

    _videoname = filename.toLatin1().data(); //_videoname (const char*) is your class private variable. you can use any where with in the class.

    //Similary if you want directory name

    QString dir = QFileDialog::getExistingDirectory(this, tr("Open Directory"),
                                                    "/home/pi",
                                                    QFileDialog::ShowDirsOnly
                                                    | QFileDialog::DontResolveSymlinks);

    _dirname = dir.toLatin1().data();//_dirname (const char*) is your class private variable. you can use any where in the class.

    QMessageBox::information(this,tr("File Name"),filename);

    }


问:
How can I count number of clicks anywhere on screen in C#?
I am trying to have a C# program running in the background on Windows that will print "Hello!" after seeing that the user has clicked his or her mouse 10 times. But not just in the console window, anywhere on the screen.

The following event handler for click-tracking is from msdn.microsoft.com:

```<code>private void OnMouseDownClickCount(object sender, MouseButtonEventArgs e) {
    // Checks the number of clicks.
    if (e.ClickCount == 1) {
        // Single Click occurred.
        lblClickCount.Content = "Single Click";
    }
    if (e.ClickCount == 2) {
        // Double Click occurred.
        lblClickCount.Content = "Double Click";
    }
    if (e.ClickCount >= 3) {
        // Triple Click occurred.
        lblClickCount.Content = "Triple Click";
    }
}
</code>```

But, I'm not sure how to actually use this. When I add this function anywhere, the MouseButtonEventArgs type is undefined.

What "using" statements do I need? How do I actually get this code to run properly -- do I call it once from main? What do I do to call it?

EDIT: Here is a picture showing Visual Studio not understanding MouseButtonEventArgs:

答:
I'm not entirely sure what you're trying to accomplish but..
To track user clicks I hooked up the "MouseDown" event on a form in a Windows Forms applications.
From there I check click counts in the event handler.</p>

```<code>using System;
using System.Windows.Forms;

namespace WindowsFormsApplicationTest
{
public partial class Form1 : Form
{
   public Form1()
    {
        InitializeComponent( );
        this.MouseDown += Form1_MouseDown;
    }

    private void Form1_MouseDown( object sender, MouseEventArgs e )
    {
        // Count clicks
    }
}
}
</code>```

Body:
I am trying to have a C# program running in the background on Windows that will print "Hello!" after seeing that the user has clicked his or her mouse 10 times. But not just in the console window, anywhere on the screen.

The following event handler for click-tracking is from msdn.microsoft.com:

private void OnMouseDownClickCount(object sender, MouseButtonEventArgs e) {
    // Checks the number of clicks.
    if (e.ClickCount == 1) {
        // Single Click occurred.
        lblClickCount.Content = "Single Click";
    }
    if (e.ClickCount == 2) {
        // Double Click occurred.
        lblClickCount.Content = "Double Click";
    }
    if (e.ClickCount >= 3) {
        // Triple Click occurred.
        lblClickCount.Content = "Triple Click";
    }
}

But, I'm not sure how to actually use this. When I add this function anywhere, the MouseButtonEventArgs type is undefined.

What "using" statements do I need? How do I actually get this code to run properly -- do I call it once from main? What do I do to call it?

EDIT: Here is a picture showing Visual Studio not understanding MouseButtonEventArgs:

Body:
I'm not entirely sure what you're trying to accomplish but..
To track user clicks I hooked up the "MouseDown" event on a form in a Windows Forms applications.
From there I check click counts in the event handler.

using System;
using System.Windows.Forms;

namespace WindowsFormsApplicationTest
{
public partial class Form1 : Form
{
   public Form1()
    {
        InitializeComponent( );
        this.MouseDown += Form1_MouseDown;
    }

    private void Form1_MouseDown( object sender, MouseEventArgs e )
    {
        // Count clicks
    }
}
}


问:
jQuery ID Return is undefined although HTML ID is defined
I'm trying to retrieve the ID of one element, store it as a variable and then use that ID value to interact with other elements in that section with the same ID.

```<code><div class="mainContent">
<div class="articleContent">
     <h1>header1</h1>
     <p class="articlePara" id="one">para1</p>
</div>
<div class="articleFooter" id="one" onclick="readMore()">
</div>
</div>

<div class="mainContent">
<div class="articleContent">
     <h1>header2</h1>
     <p class="articlePara" id="two">para2</p>
</div>
<div class="articleFooter" id="two" onclick="readMore()">
</div>
</div>
</code>```

And then the JS/jQuery

```<code>function readMore() {
var subID = event.target.id;

var newTarget = document.getElementById(subID).getElementsByClassName("articlePara");

alert(newTarget.id);
}
</code>```

At this point I'm only trying to display the ID of the selected element but it is returning undefined and in most cases people seem to notice that jQuery is getting confused because of the differences between DOM variables and jQuery ones.

jsfiddle: https://jsfiddle.net/dr0f2nu3/

To be completely clear, I want to be able to click on one element, retrieve the ID and then select an element in the family of that clicked element using that ID value.

答:
if you're using Jquery:</p>

```<code>$(function () {
    $('div.articleFooter').click(function () {
        var para = $(this).prev().find('p.articlePara').text();
        alert('T:' + para);
    });
})
</code>```

Body:
I'm trying to retrieve the ID of one element, store it as a variable and then use that ID value to interact with other elements in that section with the same ID.

header1

para1

header2

para2

And then the JS/jQuery

function readMore() {
var subID = event.target.id;

var newTarget = document.getElementById(subID).getElementsByClassName("articlePara");

alert(newTarget.id);
}

At this point I'm only trying to display the ID of the selected element but it is returning undefined and in most cases people seem to notice that jQuery is getting confused because of the differences between DOM variables and jQuery ones.

jsfiddle: https://jsfiddle.net/dr0f2nu3/

To be completely clear, I want to be able to click on one element, retrieve the ID and then select an element in the family of that clicked element using that ID value.

Body:
if you're using Jquery:

$(function () {
    $('div.articleFooter').click(function () {
        var para = $(this).prev().find('p.articlePara').text();
        alert('T:' + para);
    });
})


问:
Laravel FatalErrorException
I created a new view, route and controller in laravel and when i go to access the view i get an error, all other views are fine.

Error
FatalErrorException in shopsalescontroller.php line 11: syntax error, unexpected 'class' (T_CLASS), expecting ',' or ';'

this is my shop sales controller:

```<code>   <?php
   namespace App\Http\Controllers;
   use Illuminate\Http\Request;
   use App\Http\Requests;
   use App\shopsales

   class shopsalescontroller extends Controller : (line 11)
    {
     public function index()
      {
       $storeNum = request('storeNum');
       $results = shopsales::where('StoreNumber','=',$storeNum)->get();
       return view('shopSales',compact('results'));
      }
    }
</code>```

PHP version 5.6.3
Zend engine v2.6.0

Laravel framework version 5.2.45

答:
Just remove the : (line 11) text from your code</p>

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;

use App\shopsales

class shopsalescontroller extends Controller {

    public function index() {
        $storeNum = request('storeNum');
        $results = shopsales::where('StoreNumber', '=', $storeNum)->get();
        return view('shopSales', compact('results'));
    }

}
</code>```

Title: Laravel FatalErrorException

Body:
I created a new view, route and controller in laravel and when i go to access the view i get an error, all other views are fine.

Error
FatalErrorException in shopsalescontroller.php line 11: syntax error, unexpected 'class' (T_CLASS), expecting ',' or ';'

this is my shop sales controller:

   <?php
   namespace App\Http\Controllers;
   use Illuminate\Http\Request;
   use App\Http\Requests;
   use App\shopsales

   class shopsalescontroller extends Controller : (line 11)
    {
     public function index()
      {
       $storeNum = request('storeNum');
       $results = shopsales::where('StoreNumber','=',$storeNum)->get();
       return view('shopSales',compact('results'));
      }
    }

PHP version 5.6.3
Zend engine v2.6.0

Laravel framework version 5.2.45

Body:
Just remove the : (line 11) text from your code

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;

use App\shopsales

class shopsalescontroller extends Controller {

    public function index() {
        $storeNum = request('storeNum');
        $results = shopsales::where('StoreNumber', '=', $storeNum)->get();
        return view('shopSales', compact('results'));
    }

}


问:
MATLAB Java referencing problem
I have a MATLAB class which contains a reference to a java object

```<code>classdef MyClass
  properties
    j = myJavaClass
  end
  methods
...
  end
end
</code>```

and after I use it (using clear, scope exit or explicitly setting myClass = 0; ) the java object is still alive - even after calling Runtime.gc.

I see in the dump that the object is still in the JVM heap for the MATLAB process (using jmap -histo pID) and thus I assume MATLAB itself is still referencing the object - despite calling to clear, clear JAVA, clear classes, etc. - nothing helps

Any ideas?

答:
The workaround gnovice suggested seem to work - adding to the destructor the line

```<code>function delete( obj )
  ...
  jObject = 0;
end
</code>```

Caused the object not to be present in MATLAB's JVM heap.

It look like a bug in MATLAB that causes the referencing of the JAVA objects in unreferenced MCOS classes.

OwnerDisplayName: Dani

Title: MATLAB Java referencing problem

Body:
I have a MATLAB class which contains a reference to a java object

classdef MyClass
  properties
    j = myJavaClass
  end
  methods
...
  end
end

and after I use it (using clear, scope exit or explicitly setting myClass = 0; ) the java object is still alive - even after calling Runtime.gc.

I see in the dump that the object is still in the JVM heap for the MATLAB process (using jmap -histo pID) and thus I assume MATLAB itself is still referencing the object - despite calling to clear, clear JAVA, clear classes, etc. - nothing helps

Any ideas?

Body:
The workaround gnovice suggested seem to work - adding to the destructor the line

function delete( obj )
  ...
  jObject = 0;
end

Caused the object not to be present in MATLAB's JVM heap.

It look like a bug in MATLAB that causes the referencing of the JAVA objects in unreferenced MCOS classes.


问:
What does the jsr keyword mean?
I'm looking at some Java code, and I've noticed the following:

```<code>if (!foo(bar, baz, qux)) {
    i = 0; jsr 433;
}
</code>```

javac chokes on it, saying it's not a statement and that a semicolon is expected after the keyword jsr.

I did some Googling, and I found some code containing the same thing, which leads me to believe it's there intentionally (even though they weren't able to get it to compile either). So what does jsr do? How does one get code containing it to compile?

答:
I'm close to sure that this code is coming from a Java decompiler.

The JSR 432 smells like a decompiler note, where the decompiler found a "jump" code but doesn't have a clue on how to express it in java language.

Title: What does the jsr keyword mean?

Body:
I'm looking at some Java code, and I've noticed the following:

if (!foo(bar, baz, qux)) {
    i = 0; jsr 433;
}

javac chokes on it, saying it's not a statement and that a semicolon is expected after the keyword jsr.

I did some Googling, and I found some code containing the same thing, which leads me to believe it's there intentionally (even though they weren't able to get it to compile either). So what does jsr do? How does one get code containing it to compile?