I want to put the value of a variable (==i) in a textfield, so that its value is shown in the textfield, i.e., changing from 1 to 10.
def sb = new SwingBuilder()
def th = Thread.start {
for(i in 1..10) {
sleep 2000
}
}
def Pan = sb.panel(layout: new BorderLayout()) {
sb.panel(constraints: BorderLayout.NORTH){
gridLayout(cols: 2, rows: 3)
textField id:'tf', text: ?
}
}
You can do that with the doOutside method of SwingBuilder, which allows to run a closure outside the EDT. The code below does what you are trying to do (with a table layout instead of a grid layout).
import groovy.swing.SwingBuilder
import static javax.swing.JFrame.EXIT_ON_CLOSE
import java.awt.*
def swingBuilder = new SwingBuilder()
swingBuilder.edt {
def message
def setMessage = { String s -> message.setText(s) }
frame(title: 'Example', size: [200, 150], show: true, locationRelativeTo: null, defaultCloseOperation: EXIT_ON_CLOSE) {
borderLayout(vgap: 5)
panel(constraints: BorderLayout.CENTER, border: emptyBorder(10)) {
tableLayout(cellpadding: 5) {
tr {
td {
label 'Value' // text property is default, so it is implicit.
}
td {
message = textField(id: 'tf', columns: 5, text: '0')
}
}
}
}
}
doOutside {
for (i in 1..10) {
sleep 1000
edt { setMessage(String.valueOf(i)) }
}
}
}
Related
I have trained and deployed End Point of a custom object detection model using new Vertex AI in google cloud. When I test the model on cloud I see perfect bounding boxes on a image. But when I send request to the end point using python, the bounding boxes gotten in response seems to be incorrect.
Please note I am multiplying with width and height.
My code:-
import base64
from google.cloud import aiplatform
import cv2
from google.cloud.aiplatform.gapic.schema import predict
import os
os.environ["GOOGLE_APPLICATION_CREDENTIALS"]="C:\\Users\\tarunmis\\Downloads\\first-cascade-315219-ccaaa402f837.json"
IMAGE_PATH = "C:\\Users\\tarunmis\\Desktop\\p2.jpg"
def predict_image_object_detection_sample(
project: str="MY STR",
endpoint_id: str="MY ID",
filename: str=IMAGE_PATH,
location: str = "us-central1",
api_endpoint: str = "us-central1-aiplatform.googleapis.com",
):
# The AI Platform services require regional API endpoints.
client_options = {"api_endpoint": api_endpoint}
# Initialize client that will be used to create and send requests.
# This client only needs to be created once, and can be reused for multiple requests.
client = aiplatform.gapic.PredictionServiceClient(client_options=client_options)
with open(filename, "rb") as f:
file_content = f.read()
# The format of each instance should conform to the deployed model's prediction input schema.
encoded_content = base64.b64encode(file_content).decode("utf-8")
instance = predict.instance.ImageObjectDetectionPredictionInstance(
content=encoded_content,
).to_value()
instances = [instance]
# See gs://google-cloud-aiplatform/schema/predict/params/image_object_detection_1.0.0.yaml for the format of the parameters.
parameters = predict.params.ImageObjectDetectionPredictionParams(
confidence_threshold=0.5, max_predictions=10,
).to_value()
endpoint = client.endpoint_path(
project=project, location=location, endpoint=endpoint_id
)
response = client.predict(
endpoint=endpoint, instances=instances, parameters=parameters
)
print("response")
print(" deployed_model_id:", response.deployed_model_id)
# See gs://google-cloud-aiplatform/schema/predict/prediction/image_object_detection.yaml for the format of the predictions.
predictions = response.predictions
preds = list()
print(response)
for prediction in predictions:
preds.append(dict(prediction))
return preds
# [END aiplatform_predict_image_object_detection_sample]
predictions = predict_image_object_detection_sample()
prediction = predictions[0]
image = cv2.imread(IMAGE_PATH,1)
h,w,c = image.shape
boxes = prediction['bboxes']
confs = prediction["confidences"]
for box,conf in zip(boxes,confs):
x1 = int(w*box[0])
y1 = int(h*box[1])
x2 = int(w*box[2])
y2 = int(h*box[3])
if conf>0.1:
cv2.circle(image,(x1,y1),5,(0,0,255),cv2.FILLED)
cv2.circle(image, (x2, y2), 5, (255, 0, 0), cv2.FILLED)
cv2.rectangle(image,(x1,y1),(x2,y2),(0,255,0))
cv2.imshow("img",image)
cv2.waitKey()
And the response is:-
predictions {
struct_value {
fields {
key: "bboxes"
value {
list_value {
values {
list_value {
values {
number_value: 0.678395331
}
values {
number_value: 0.779298723
}
values {
number_value: 0.645786881
}
values {
number_value: 0.683837295
}
}
}
values {
list_value {
values {
number_value: 0.18701905
}
values {
number_value: 0.287654519
}
values {
number_value: 0.627796173
}
values {
number_value: 0.669630647
}
}
}
}
}
}
fields {
key: "confidences"
value {
list_value {
values {
number_value: 0.813014865
}
values {
number_value: 0.748636127
}
}
}
}
fields {
key: "displayNames"
value {
list_value {
values {
string_value: "plate"
}
values {
string_value: "plate"
}
}
}
}
fields {
key: "ids"
value {
list_value {
values {
string_value: "66451184247898112"
}
values {
string_value: "66451184247898112"
}
}
}
}
}
}
deployed_model_id: "1371469231836626944"
h and w should be the other way round and so should x2 and y1:
w,h,c = img.shape
...
x1 = int(w*boxes[0])
x2 = int(w*boxes[1])
y1 = int(h*boxes[2])
y2 = int(h*boxes[3])
I am using a quill editor with my angular8 project. On the same there is an option to add url with the help of 'link'. Could I know, is there any way to validate the url which I will enter for the 'link' textbox as shown images below. Following are my codes
quill editor module
editorConfig= {
formula: true,
toolbar: [
[{ header: [1, 2, false] }],
['bold', 'italic', 'underline'],
['link']
]
};
html
<quill-editor [modules]="editorConfig" [style]="{height: '200px'}"></quill-editor>
How to validate links inside the textbox which is marked on the image above.
Yeah I find a way to resolve this question
First we need two function to override the default link handler and the function of snowtooltip save
import Emitter from 'quill/core/emitter';
import { message } from 'antd';
/**
* override Snow tooltip save
*/
export function SnowTooltipSave() {
const { value } = this.textbox;
const linkValidityRegex = /^(http|https)/;
switch (this.root.getAttribute('data-mode')) {
case 'link': {
if (!linkValidityRegex.test(value)) {
message.error('链接格式错误,请输入链接 http(s)://...');
return;
}
const { scrollTop } = this.quill.root;
if (this.linkRange) {
this.quill.formatText(this.linkRange, 'link', value, Emitter.sources.USER);
delete this.linkRange;
} else {
this.restoreFocus();
this.quill.format('link', value, Emitter.sources.USER);
}
this.quill.root.scrollTop = scrollTop;
break;
}
default:
}
this.textbox.value = '';
this.hide();
}
export function SnowThemeLinkHandler(value) {
if (value) {
const range = this.quill.getSelection();
if (range == null || range.length === 0) return;
let preview = this.quill.getText(range);
if (/^\S+#\S+\.\S+$/.test(preview) && preview.indexOf('mailto:') !== 0) {
preview = `mailto:${preview}`;
}
const { tooltip } = this.quill.theme;
tooltip.save = DtysSnowTooltipSave;
tooltip.edit('link', preview);
} else {
this.quill.format('link', false);
}
}
then use these function in editor
const SnowTheme = Quill.import('themes/snow');
SnowTheme.DEFAULTS.modules.toolbar.handlers.link = SnowThemeLinkHandler;
I'm developing an application for the hololens that generates multiple canvases with a panel with UI/Image elements. I have 1 JSON string:
{
"PC_Station":[
{
"PLC_0":{
"DB1":{
"test123":0
},
"STOP":false,
"Frap":false,
"START":false,
"Start_1":false,
"Stop_1":false,
"Led1":true,
"Led2":false,
"Led3":true,
"Counter":4002,
"Sliderval":0
}
},
{
"PLC_1":{
"DB1":{
"test123":55
},
"STOP":false,
"START":false,
"Start_1":false,
"Stop_1":false,
"Led1":true,
"Led2":false,
"Led3":true,
"Counter":4002,
"Sliderval":0
}
}
]
}
This JSON string has 2 JSON objects inside a JSON array called PLC_1 and PLC_0. PLC_1 has the same variables as PLC_0.
I've made the following function that appends the JSON and changes the color of the UI/Image objects:
IEnumerator updateTags()
{
string json = "{\"PC_Station\": [{\"PLC_1\": {\"DB1\": {\"test123\": 30}, \"STOP\": false, \"START\": true, \"Start_1\": false, \"Stop_1\": true, \"Led1\": false, \"Led2\": false, \"Led3\": false, \"Counter\": 3880, \"Sliderval\": 60}}]}";
string json1 = "{\"PC_Station\": [{\"PLC_0\": {\"DB1\": {\"test123\": 0}, \"STOP\": false,\"Frap\": false, \"START\": false, \"Start_1\": false, \"Stop_1\": false, \"Led1\": true, \"Led2\": false, \"Led3\": true, \"Counter\": 4002, \"Sliderval\": 0}},{\"PLC_1\": {\"DB1\": {\"test123\": 55}, \"STOP\": false, \"START\": false, \"Start_1\": false, \"Stop_1\": false, \"Led1\": true, \"Led2\": false, \"Led3\": true, \"Counter\": 4002, \"Sliderval\": 0}}]}";
var data = JToken.Parse(json1);
while (true)
{
foreach (var value in data)
{
foreach(JArray arr in value)
{
for (int i = 0; i < arr.Count; i++)
{
foreach (var item in arr[i])
{
var itemproperties = item.Parent;
foreach (JToken token in itemproperties)
{
var prop = token as JProperty;
var plc = (JObject)prop.Value;
foreach (KeyValuePair<string, JToken> val in plc)
{
if(val.Value is JObject)
{
JObject nestedobj = (JObject)val.Value;
foreach (JProperty nestedvariables in nestedobj.Properties())
{
string varkey = nestedvariables.Name;
string varvalue = nestedvariables.Value.ToString();
GameObject test = GameObject.Find(varkey+"value");
test.GetComponent<Text>().text = varvalue;
}
}
else
{
for(int v = 0; v < abc.Count; v++)
{
Debug.Log(v);
foreach(KeyValuePair<string, string> variab in abc[v])
{
string varkey = val.Key;
string varvalue = val.Value.ToString();
GameObject test = GameObject.Find(varkey);
if(varvalue == "True")
{
test.GetComponent<Image>().color = Color.green;
}
if(varvalue == "False")
{
test.GetComponent<Image>().color = Color.red;
}
if(varvalue != "True" && varvalue != "False")
{
GameObject text = GameObject.Find(varkey + "value");
text.GetComponent<Text>().text = varvalue;
}
}
}
}
}
}
}
}
}
}
yield return new WaitForSeconds(0.5f);
}
}
When I run the programme, it looks like this:
As you can see, the function properly adds color to the UI/Images.
Now, for my question:
How can I make it so that the UI/Images on both canvases get filled with color despite having the same name?
There are no obvious solutions as GameObject referenes do not serialize easily, you couls reference objects by their position in the current branch of the tree (transform.GetSiblingIndex()) but that will not work if you move stuff around.
You could also just rename your objects.
Managed to fix it by using transform.find. I used it to find items in the hierarchy.
The code now functions like I want it to.
First I make a new gameobject:
public GameObject upd4;
Then I use it in my code as follows:
upd4 = transform.Find("Canvas" + i + "/Panel/" + plcvvobj.Key + "/" + plcvvobj.Key + "value").gameObject;
BTW, my hierarchy is as follows:
Hello I am new in Griffon Framework I want to add Login feature in my application. Follow are my model,view and controller:
SignInModel.groovy
#ArtifactProviderFor(GriffonModel)
#griffon.transform.Validateable
class SignInModel {
#Bindable String userName
#Bindable String password
static CONSTRAINTS = {
userName(blank: false,nullable: false)
password(blank: false, nullable: false)
}
}
SignInView.groovy
#ArtifactProviderFor(GriffonView)
class SignInView {
FactoryBuilderSupport builder
SignInModel model
SignInController controller
void initUI() {
builder.with {
application{
frame(title: 'Login', size: [330, 230],
show: true,resizable:false,locationRelativeTo: null,
defaultCloseOperation: EXIT_ON_CLOSE) {
panel(constraints: BorderLayout.CENTER,
border: compoundBorder([emptyBorder(10),titledBorder('Welcome To Tracker')])) {
tableLayout() {
tr {
td {
label(text: "Username")
}
td {
textField(id: "usernameTxt", columns: 15, text: bind(target: model, 'userName', mutual: true))
}
}
tr{
td{
label(text:"Password")
}
td{
passwordField(id:"passwordTxt",columns:15,text:bind(target:model,'password',mutual:true))
}
}
}
}
panel(constraints: BorderLayout.SOUTH) {
button text: 'Login', actionPerformed: {
model?.getErrors()?.clearAllErrors()
controller.signIn()
}
}
}
}
}
}
}
}
SignInController.groovy
#ArtifactProviderFor(GriffonController)
class SignInController {
SignInModel model
SignInView view
void signIn(){
try {
if (model?.validate()) {
println("No Error Found..")
} else {
println("Error Found..")
}
}catch (Exception ex){
println("Exception Generated:>>>>>>>>>>>>>>"+ex?.getMessage())
}
}
}
I want to update my SignIn View If username and password are empty with error message. I am able to get error message in my model but my view not update so Please help me.
#Note: I have added griffon validation plugin
You must process the errors property of the validateable (the model instance). This property contains a list of messages that can be used to display information back to the user, however you must choose which messages, as there may be many. Your current code is one step away from this as it has already triggered validation; now you just need to consume the messages and present them in the UI.
I'm trying to make a really simple text input field (to replicate later for a more complex purpose). Using IDEA 14 CE, not sure it matters. I wrote this code:
import groovy.swing.SwingBuilder
import groovy.beans.Bindable
import static javax.swing.JFrame.EXIT_ON_CLOSE
import java.awt.*
String word
#Bindable
class UserInput {
String word
//String toString() { "$word" }
}
def userInput = new UserInput(word: null)
def swingBuilder = new SwingBuilder()
swingBuilder.edt {
lookAndFeel 'nimbus'
// frame size
def width = 350
def height = 230
frame (
title: 'Input',
size: [width, height],
show: true,
locationRelativeTo: null,
defaultCloseOperation: EXIT_ON_CLOSE ) {
borderLayout(vgap: 5)
panel(constraints:
BorderLayout.CENTER,
border: compoundBorder([emptyBorder(10), titledBorder('Input:')]))
{
tableLayout {
tr {
td { label 'Input: ' }
td { textField userInput.word, id: userInput.word, columns: 20 }
}
}
}
panel(constraints: BorderLayout.SOUTH) {
button text: 'Print word', actionPerformed: {
println """Word: ${userInput.word}"""
}
}
}
}
When I run it, I get this Swing box:
No matter what I input, when I click Print Word it always prints:
Word: null
What am I doing wrong? Seems like I am failing to assign user input to a parameter or something like that, but I cannot figure it out.
Right, you need to use bean binding to get the text property of the textField bound to your model. This works:
import groovy.swing.SwingBuilder
import groovy.beans.Bindable
import static javax.swing.JFrame.EXIT_ON_CLOSE
import java.awt.*
String word
#Bindable
class UserInput {
String word
}
def userInput = new UserInput(word: null)
def swingBuilder = new SwingBuilder().edt {
lookAndFeel 'nimbus'
// frame size
def width = 350
def height = 230
frame (title: 'Input',
size: [width, height],
show: true,
locationRelativeTo: null ) {
borderLayout(vgap: 5)
panel(constraints: BorderLayout.CENTER,
border: compoundBorder([emptyBorder(10), titledBorder('Input:')])) {
tableLayout {
tr {
td { label 'Input: ' }
td { textField id:'input', columns: 20 }
}
}
}
panel(constraints: BorderLayout.SOUTH) {
button text: 'Print word', actionPerformed: {
println """Word: ${userInput.word}"""
}
}
// Bind the text field to the bean
bean userInput, word: bind { input.text }
}
}