Try to track down Blazor Client side Exception - exception

We have been using RadzenBlazor for a while now with good success. Recently, the Filtering is causing an exception. The actual exception is not forthcoming to me so I am wondering how to better read it. I know Blazor client side errors are not so great. Most of the time, when it is code I have written you get a variable or something to point me in the direction of the cause, but not in this case as near as I can tell. I can select items and unselect items with no issue. The second I type in a letter to filter down the list, I get the exception below. I am just trying to figure out if it is Radzen or something else.
I have tried implementing this from the Microsoft Docs but no extra info was shown.
First, here is the code, for the DropDown
<RadzenDropDown Multiple="true"
AllowClear="true"
AllowFiltering="true"
FilterCaseSensitivity="FilterCaseSensitivity.CaseInsensitive"
Placeholder="Select Claim(s)..."
#bind-Value="SelectedClaimIds"
Data="availablePerformanceClaims"
TextProperty="Name"
ValueProperty="Id"
TValue="IEnumerable<int>"
Class="w-100 items-inline">
</RadzenDropDown>
[Inject]
private ISomeService someService { get; set; }
[Inject]
private IMapper mapper { get; set; }
public IEnumerable<PerformanceClaimMinimalModel> availablePerformanceClaims { get; set; } = new List<PerformanceClaimMinimalModel>();
public IEnumerable<int> SelectedClaimIds = Array.Empty<int>();
protected override async Task OnInitializedAsync()
{
availablePerformanceClaims = mapper.Map<IEnumerable<SelectablePerformanceClaimMinimalModel>>(
await someService .GetPerformanceClaimsAsync(new PerformanceClaimSearchModel
{
ValidUntilEnd = null,
})
)
.OrderBy(x => x.Issuer)
.ThenBy(x => x.Name)
.ThenBy(x => x.Version);
}
And here is the exception
crit: Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
Unhandled exception rendering component: Object reference not set to an instance of an object.
System.NullReferenceException: Object reference not set to an instance of an object.
at System.Linq.Dynamic.Core.Parser.KeywordsHelper..ctor(ParsingConfig config)
at System.Linq.Dynamic.Core.Parser.ExpressionParser..ctor(ParameterExpression[] parameters, String expression, Object[] values, ParsingConfig parsingConfig)
at System.Linq.Dynamic.Core.DynamicExpressionParser.ParseLambda(Type delegateType, ParsingConfig parsingConfig, Boolean createParameterCtor, ParameterExpression[] parameters, Type resultType, String expression, Object[] values)
at System.Linq.Dynamic.Core.DynamicExpressionParser.ParseLambda(ParsingConfig parsingConfig, Boolean createParameterCtor, ParameterExpression[] parameters, Type resultType, String expression, Object[] values)
at System.Linq.Dynamic.Core.DynamicExpressionParser.ParseLambda(ParsingConfig parsingConfig, Boolean createParameterCtor, Type itType, Type resultType, String expression, Object[] values)
at System.Linq.Dynamic.Core.DynamicQueryableExtensions.Where(IQueryable source, ParsingConfig config, String predicate, Object[] args)
at System.Linq.Dynamic.Core.DynamicQueryableExtensions.Where(IQueryable source, String predicate, Object[] args)
at Radzen.DropDownBase`1[[System.Collections.Generic.IEnumerable`1[[System.Int32, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].get_View()
at Radzen.Blazor.RadzenDropDown`1[[System.Collections.Generic.IEnumerable`1[[System.Int32, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].BuildRenderTree(RenderTreeBuilder __builder)
at Microsoft.AspNetCore.Components.ComponentBase.<.ctor>b__6_0(RenderTreeBuilder builder)
at Microsoft.AspNetCore.Components.Rendering.ComponentState.RenderIntoBatch(RenderBatchBuilder batchBuilder, RenderFragment renderFragment, Exception& renderFragmentException)
window.Module.s.printErr # blazor.webassembly.js:1
Te._internal.dotNetCriticalError # blazor.webassembly.js:1
Rt # blazor.webassembly.js:1
_mono_wasm_invoke_js_blazor # dotnet.6.0.4.dckq00jdfr.js:1
$func219 # 00970c26:0x1a0fb
$func167 # 00970c26:0xcac9
$func166 # 00970c26:0xb9dc
$func2810 # 00970c26:0xabb22
$func1615 # 00970c26:0x6f935
$func1619 # 00970c26:0x6ffa2
$mono_wasm_invoke_method # 00970c26:0x969b
Module._mono_wasm_invoke_method # dotnet.6.0.4.dckq00jdfr.js:1
managed__Microsoft_AspNetCore_Components_WebAssembly__Microsoft_AspNetCore_Components_WebAssembly_Services_DefaultWebAssemblyJSRuntime_EndInvokeJS # managed__Microsoft_A…time_EndInvokeJS:16
endInvokeJSFromDotNet # blazor.webassembly.js:1
(anonymous) # blazor.webassembly.js:1
Promise.then (async)
beginInvokeJSFromDotNet # blazor.webassembly.js:1
Rt # blazor.webassembly.js:1
_mono_wasm_invoke_js_blazor # dotnet.6.0.4.dckq00jdfr.js:1
$func219 # 00970c26:0x1a0fb
$func167 # 00970c26:0xcac9
$func166 # 00970c26:0xb9dc
$func2810 # 00970c26:0xabb22
$func1615 # 00970c26:0x6f935
$func1619 # 00970c26:0x6ffa2
$func3213 # 00970c26:0xc4abd
$mono_background_exec # 00970c26:0x93f6d
Module._mono_background_exec # dotnet.6.0.4.dckq00jdfr.js:1
pump_message # dotnet.6.0.4.dckq00jdfr.js:1
setTimeout (async)
_schedule_background_exec # dotnet.6.0.4.dckq00jdfr.js:1
$func2387 # 00970c26:0x93f1e
$func3212 # 00970c26:0xc4a4d
$func219 # 00970c26:0x1a163
$func167 # 00970c26:0xcac9
$func166 # 00970c26:0xb9dc
$func2810 # 00970c26:0xabb22
$func1615 # 00970c26:0x6f935
$func1619 # 00970c26:0x6ffa2
$mono_set_timeout_exec # 00970c26:0xc49ba
Module._mono_set_timeout_exec # dotnet.6.0.4.dckq00jdfr.js:1
mono_wasm_set_timeout_exec # dotnet.6.0.4.dckq00jdfr.js:1
mono_wasm_set_timeout_exec # dotnet.6.0.4.dckq00jdfr.js:1
setTimeout (async)
_mono_set_timeout # dotnet.6.0.4.dckq00jdfr.js:1
$func3211 # 00970c26:0xc4a45
$func219 # 00970c26:0x1a030
$func167 # 00970c26:0xcac9
$func166 # 00970c26:0xb9dc
$func2810 # 00970c26:0xabb22
$func1615 # 00970c26:0x6f935
$func1613 # 00970c26:0x6f8a7
$func966 # 00970c26:0x502f8
$func219 # 00970c26:0x1a0b4
$func167 # 00970c26:0xcac9
$func166 # 00970c26:0xb9dc
$func2810 # 00970c26:0xabb22
$func1615 # 00970c26:0x6f935
$func1613 # 00970c26:0x6f8a7
$func966 # 00970c26:0x502f8
$func219 # 00970c26:0x1a0b4
$func167 # 00970c26:0xcac9
$func166 # 00970c26:0xb9dc
$func2810 # 00970c26:0xabb22
$func1615 # 00970c26:0x6f935
$func1619 # 00970c26:0x6ffa2
$mono_wasm_invoke_method # 00970c26:0x969b
Module._mono_wasm_invoke_method # dotnet.6.0.4.dckq00jdfr.js:1
managed__Microsoft_AspNetCore_Components_WebAssembly__Microsoft_AspNetCore_Components_WebAssembly_Services_DefaultWebAssemblyJSRuntime_BeginInvokeDotNet # managed__Microsoft_A…eginInvokeDotNet:19
beginInvokeDotNetFromJS # blazor.webassembly.js:1
b # blazor.webassembly.js:1
invokeMethodAsync # blazor.webassembly.js:1
(anonymous) # blazor.webassembly.js:1
invokeWhenHeapUnlocked # blazor.webassembly.js:1
S # blazor.webassembly.js:1
C # blazor.webassembly.js:1
dispatchGlobalEventToAllElements # blazor.webassembly.js:1
onGlobalEvent # blazor.webassembly.js:1

Turns out it was BlazorApplicationInsights that was giving me an issue. I may be doing it wrong, but we have an HttpService and I was trying to catch errors, which it does. But clearly Radzen has issues with it. I have no issues with the BAI, but I will have to circle back on figure out what the issue is.
private async Task<bool> HandleResponseFailure(HttpVerbs verb, HttpResponseMessage responseMessage)
{
if (!responseMessage.IsSuccessStatusCode)
{
await appInsights.TrackException(
new Error
{
Message = responseMessage.ReasonPhrase,
Name = $"{verb.ToString().ToUpper()} Request Exception: StatusCode: {responseMessage.StatusCode} - {responseMessage.RequestMessage.RequestUri}",
}
);
Utils.HideSpinner();
Utils.WriteError(jsRuntime, $"Error during {verb.ToString().ToUpper()}, Status Code: {responseMessage.StatusCode}, Uri: {responseMessage.RequestMessage.RequestUri}");
// TODO: Do we want this -> Utils.ShowErrorNotification($"{verb.ToString().ToUpper()} Exception", $"Status Code: {responseMessage.StatusCode}\n{responseMessage.RequestMessage.RequestUri}");
}
return responseMessage.IsSuccessStatusCode;
}

Related

ValueError: Graph disconnected: cannot obtain value for tensor KerasTensor(type_spec=TensorSpec(shape=(None, None, None, 3)

I am working on a MetaLearning approach to solving an image segmentation problem. I trained 7 different models on different classes related to the eye dataset provided under Oculus SBVPI (iris, pupil, sclera, canthus, periocular, vessels, eyelashes). I want to connect these several models together by having seven input heads corresponding to seven pre-trained models and then concatenating their outputs to get the final result.
I want to create a model architecture with 7 input heads every input head connects with its own encoder block and then at the end of the encoder block the output is concatenated and passed to a single decoder block to produce output.
I am not able to figure out the problem, any suggestions at all will be of great help.
I tried other similar approaches as given here and here
My code:
import tensorflow as tf
# Assume all libraries are imported
class PretrainedMetaUNet:
def __init__(self, config, save_model=True, show_summary=True, sigmoid=True, **kwargs):
super(PretrainedMetaUNet, self).__init__(**kwargs)
self.configuration = config
self.x_size = config["dataset"]["width"] # 128
self.y_size = config["dataset"]["height"] # 128
self.channels = config["dataset"]["img_channels"] # 3
self.save_model = save_model
self.add_sigmoid = sigmoid
self.meta_classes = config["dataset"]["meta_channels"] # 1
self.show_summary = show_summary
self.model_img = config["Network"]["modelpath"]
self.dropout_factor = config["Network"]['dropout']
self.maxpool = tf.keras.layers.MaxPooling2D()
def ConvolutionBN(self, input_tensor, filters):
x = tf.keras.layers.Conv2D(filters, 3, padding='same', kernel_initializer='he_normal')(input_tensor)
x = tf.keras.layers.BatchNormalization()(x)
x = tf.keras.layers.ReLU()(x)
if self.dropout_factor != 0.0:
x = tf.keras.layers.Dropout(self.dropout_factor)(x)
x = tf.keras.layers.Conv2D(filters, 3, padding='same', kernel_initializer='he_normal')(x)
x = tf.keras.layers.BatchNormalization()(x)
x = tf.keras.layers.ReLU()(x)
if self.dropout_factor != 0.0:
x = tf.keras.layers.Dropout(self.dropout_factor)(x)
return x
def return_pretrained_model_encoder_weights(self):
root_path = self.configuration['train']['Output']['weight']
path = glob.glob(os.path.join(root_path, '*_weights'), recursive=True)
# path variable has absolute address of all the seven models ['/path to sclera model', '/path to iris model', ...]
# Every model is trained on the input images of spatial dimension 128x128x3 predicting a segmentation mask of 128x128x1.
encoder_weights = []
for idx, model_path in enumerate(path):
model = tf.keras.models.load_model(filepath=model_path, compile=False)
class_name = model_path.split('/')[-1].split('_')[0] # takes class name like iris, sclera etc..
for layer in model.layers:
layer._name = layer.name + str('_' + class_name)
# I used segmentation_models library ==> sm.UNet('resnet34', encoder_weights='imagenet')
# Accessing different encoding stages of the model. Every model is Unet pretrained with resnet34 weights.
s1 = model.get_layer(name='data'+str('_' + class_name)).output
s2 = model.get_layer(name='relu0'+str('_' + class_name)).output
s3 = model.get_layer(name='stage2_unit1_relu1'+str('_' + class_name)).output
s4 = model.get_layer(name='stage3_unit1_relu1'+str('_' + class_name)).output
b1 = model.get_layer(name='stage4_unit1_relu1'+str('_' + class_name)).output
encoder_weights.append([b1, s1, s2, s3, s4])
del model
return encoder_weights
def DecoderBlock(self, input_tensor, skip_features, filters, name=None):
if name is None:
x = tf.keras.layers.Conv2DTranspose(filters, kernel_size=2, strides=2,
padding='SAME', kernel_initializer='he_normal')(input_tensor)
else:
x = tf.keras.layers.Conv2DTranspose(filters, kernel_size=2, strides=2, name=name,
padding='SAME', kernel_initializer='he_normal')(input_tensor)
x = tf.keras.layers.Concatenate()([x, skip_features])
x = self.ConvolutionBN(x, filters)
return x
def return_model(self):
input_1 = tf.keras.layers.Input(shape=(self.x_size, self.y_size, self.channels)) # (128,128,3)
input_2 = tf.keras.layers.Input(shape=(self.x_size, self.y_size, self.channels)) # (128,128,3)
input_3 = tf.keras.layers.Input(shape=(self.x_size, self.y_size, self.channels)) # (128,128,3)
input_4 = tf.keras.layers.Input(shape=(self.x_size, self.y_size, self.channels)) # (128,128,3)
input_5 = tf.keras.layers.Input(shape=(self.x_size, self.y_size, self.channels)) # (128,128,3)
input_6 = tf.keras.layers.Input(shape=(self.x_size, self.y_size, self.channels)) # (128,128,3)
input_7 = tf.keras.layers.Input(shape=(self.x_size, self.y_size, self.channels)) # (128,128,3)
inputs = [input_1, input_2, input_3, input_4, input_5, input_6, input_7]
encoder_weights = self.return_pretrained_model_encoder_weights()
# Concatenating all the relative weights together
full_b = [layer[0] for layer in encoder_weights]
full_s1 = [layer[1] for layer in encoder_weights]
full_s2 = [layer[2] for layer in encoder_weights]
full_s3 = [layer[3] for layer in encoder_weights]
full_s4 = [layer[4] for layer in encoder_weights]
concatenated_b = tf.keras.layers.Concatenate(axis=-1)(full_b)
concatenated_s1 = tf.keras.layers.Concatenate(axis=-1)(full_s1)
concatenated_s2 = tf.keras.layers.Concatenate(axis=-1)(full_s2)
concatenated_s3 = tf.keras.layers.Concatenate(axis=-1)(full_s3)
concatenated_s4 = tf.keras.layers.Concatenate(axis=-1)(full_s4)
# Creating final decoder block
d1 = self.DecoderBlock(concatenated_b, concatenated_s4, 512, name='decoder_start')
d2 = self.DecoderBlock(d1, concatenated_s3, 256, name='block2')
d3 = self.DecoderBlock(d2, concatenated_s2, 128, name='block3')
d4 = self.DecoderBlock(d3, concatenated_s1, 64, name='block4')
""" Output """
if self.add_sigmoid:
activation = 'sigmoid'
else:
activation = None
output = tf.keras.layers.Conv2D(self.meta_classes, 1, padding='same', activation=activation)(d4)
model = tf.keras.Model(inputs=inputs, outputs=output)
if self.show_summary:
print(model.summary())
if self.save_model:
tf.keras.utils.plot_model(model, show_dtype=True, show_layer_names=True, show_shapes=True,
to_file=self.model_img)
return model
if __name__ == '__main__':
# Loaded Configuration file...
pretrained_unet = PretrainedMetaUNet(config=configuration)
model = pretrained_unet.return_model()
Error:
ValueError: Graph disconnected: cannot obtain value for tensor KerasTensor(type_spec=TensorSpec(shape=(None, None, None, 3), dtype=tf.float32, name='data'), name='data', description="created by layer 'data_pupil'") at layer "bn_data_pupil". The following previous layers were accessed without issue: []

Python script that can auto-annotate the images

I am using the https://github.com/mdhmz1/Auto-Annotate repo. I have tried to custom train my own dataset which has it own COCO JSON format file.
When I try to run
python3 customTrain.py train --dataset=path/to/dir --weights=coco
I get the following error:
Traceback (most recent call last):
File "customTrain.py", line 279, in
train(model)
File "customTrain.py", line 179, in train
dataset_train.load_custom(args.dataset, "train")
File "customTrain.py", line 87, in load_custom
annotations = [a for a in annotations if a['regions']]
File "customTrain.py", line 87, in
annotations = [a for a in annotations if a['regions']]
TypeError: list indices must be integers or slices, not str
My customtrain.py looks like the following:
import os
import sys
import json
import datetime
import numpy as np
import skimage.draw
Root directory of the project
ROOT_DIR = "/home/hiwi/Auto-Annotate"
Import Mask RCNN
sys.path.append(ROOT_DIR) # To find local version of the library
from mrcnn.config import Config
from mrcnn import model as modellib, utils
Path to trained weights file
COCO_WEIGHTS_PATH = os.path.join(ROOT_DIR, "mask_rcnn_coco.h5")
Directory to save logs and model checkpoints, if not provided
through the command line argument --logs
DEFAULT_LOGS_DIR = os.path.join(ROOT_DIR, "logs")
############################################################
Configurations
############################################################
class CustomConfig(Config):
"""Configuration for training on the toy dataset.
Derives from the base Config class and overrides some values.
"""
# Give the configuration a recognizable name
NAME = "custom"
IMAGES_PER_GPU = 1
# Number of classes (including background)
NUM_CLASSES = 1 + 2 # Background + 2 classes
# Number of training steps per epoch
STEPS_PER_EPOCH = 100
# Skip detections with < 90% confidence
DETECTION_MIN_CONFIDENCE = 0.9
############################################################
Dataset
############################################################
class CustomDataset(utils.Dataset):
def load_custom(self, dataset_dir, subset):
"""Load a subset of the Custom dataset.
dataset_dir: Root directory of the dataset.
subset: Subset to load: train or val
"""
# Add classes. We have only one class to add.
self.add_class("custom", 0, "Primary_Track")
self.add_class("custom", 1, "Secondary_Track")
# Train or validation dataset?
assert subset in ["train", "val"]
dataset_dir = os.path.join(dataset_dir, subset)
# Load annotations
# VGG Image Annotator (up to version 1.6) saves each image in the form:
# { 'filename': '28503151_5b5b7ec140_b.jpg',
# 'regions': {
# '0': {
# 'region_attributes': {},
# 'shape_attributes': {
# 'all_points_x': [...],
# 'all_points_y': [...],
# 'name': 'polygon'}},
# ... more regions ...
# },
# 'size': 100202
# }
# We mostly care about the x and y coordinates of each region
# Note: In VIA 2.0, regions was changed from a dict to a list.
annotations1 = json.load(open(os.path.join(dataset_dir, "train.json")))
annotations = list(annotations1.values()) # don't need the dict keys
# The VIA tool saves images in the JSON even if they don't have any
# annotations. Skip unannotated images.
annotations = [a for a in annotations if a['regions']]
# Add images
for a in annotations:
# Get the x, y coordinaets of points of the polygons that make up
# the outline of each object instance. These are stores in the
# shape_attributes (see json format above)
# The if condition is needed to support VIA versions 1.x and 2.x.
if type(a['regions']) is dict:
polygons = [r['shape_attributes'] for r in a['regions'].values()]
else:
polygons = [r['shape_attributes'] for r in a['regions']]
#labelling each class in the given image to a number
custom = [s['region_attributes'] for s in a['regions']]
num_ids=[]
#Add the classes according to the requirement
for n in custom:
try:
if n['name']=="Primary_Track":
num_ids.append(0)
elif n['name']=='Secondary_Track':
num_ids.append(1)
except:
pass
# load_mask() needs the image size to convert polygons to masks.
# Unfortunately, VIA doesn't include it in JSON, so we must read
# the image. This is only managable since the dataset is tiny.
image_path = os.path.join(dataset_dir, a['filename'])
image = skimage.io.imread(image_path)
height, width = image.shape[:2]
self.add_image(
"custom",
image_id=a['filename'], # use file name as a unique image id
path=image_path,
width=width, height=height,
polygons=polygons,
num_ids=num_ids)
def load_mask(self, image_id):
"""Generate instance masks for an image.
Returns:
masks: A bool array of shape [height, width, instance count] with
one mask per instance.
class_ids: a 1D array of class IDs of the instance masks.
"""
# If not a custom dataset image, delegate to parent class.
image_info = self.image_info[image_id]
if image_info["source"] != "custom":
return super(self.__class__, self).load_mask(image_id)
num_ids = image_info['num_ids']
#print("Here is the numID",num_ids)
# Convert polygons to a bitmap mask of shape
# [height, width, instance_count]
info = self.image_info[image_id]
mask = np.zeros([info["height"], info["width"], len(info["polygons"])],
dtype=np.uint8)
for i, p in enumerate(info["polygons"]):
if p['name'] == 'polygon':
# Get indexes of pixels inside the polygon and set them to 1
rr, cc = skimage.draw.polygon(p['all_points_y'], p['all_points_x'])
else:
rr, cc = skimage.draw.rectangle((p['y'], p['x']), extent=(p['height'], p['width']))
rr[rr > mask.shape[0]-1] = mask.shape[0]-1
cc[cc > mask.shape[1]-1] = mask.shape[1]-1
mask[rr, cc, i] = 1
# Return mask, and array of class IDs of each instance. Since we have
# one class ID only, we return an array of 1s
num_ids = np.array(num_ids, dtype=np.int32)
return mask.astype(np.bool), num_ids.astype(np.bool), np.ones([mask.shape[-1]], dtype=np.int32)
#return mask.astype(np.bool), np.ones([mask.shape[-1]], dtype=np.int32)
def image_reference(self, image_id):
"""Return the path of the image."""
info = self.image_info[image_id]
if info["source"] == "Railtrack":
return info["path"]
else:
super(self.__class__, self).image_reference(image_id)
def train(model):
"""Train the model."""
# Training dataset.
dataset_train = CustomDataset()
dataset_train.load_custom(args.dataset, "train")
dataset_train.prepare()
# Validation dataset
dataset_val = CustomDataset()
dataset_val.load_custom(args.dataset, "val")
dataset_val.prepare()
# *** This training schedule is an example. Update to your needs ***
# Since we're using a very small dataset, and starting from
# COCO trained weights, we don't need to train too long. Also,
# no need to train all layers, just the heads should do it.
print("Training network heads")
model.train(dataset_train, dataset_val,
learning_rate=config.LEARNING_RATE,
epochs=30,
layers='heads')
############################################################
Training
############################################################
if name == 'main':
import argparse
# Parse command line arguments
parser = argparse.ArgumentParser(
description='Train Mask R-CNN to detect custom objects.')
parser.add_argument("command",
metavar="<command>",
help="'train' or 'splash'")
parser.add_argument('--dataset', required=False,
metavar="/path/to/custom/dataset/",
help='Directory of the Custom dataset')
parser.add_argument('--weights', required=True,
metavar="/path/to/weights.h5",
help="Path to weights .h5 file or 'coco'")
parser.add_argument('--logs', required=False,
default=DEFAULT_LOGS_DIR,
metavar="/path/to/logs/",
help='Logs and checkpoints directory (default=logs/)')
parser.add_argument('--image', required=False,
metavar="path or URL to image",
help='Image to apply the color splash effect on')
parser.add_argument('--video', required=False,
metavar="path or URL to video",
help='Video to apply the color splash effect on')
args = parser.parse_args()
# Validate arguments
if args.command == "train":
assert args.dataset, "Argument --dataset is required for training"
elif args.command == "splash":
assert args.image or args.video,\
"Provide --image or --video to apply color splash"
print("Weights: ", args.weights)
print("Dataset: ", args.dataset)
print("Logs: ", args.logs)
# Configurations
if args.command == "train":
config = CustomConfig()
# Create model
if args.command == "train":
model = modellib.MaskRCNN(mode="training", config=config,
model_dir=args.logs)
# Select weights file to load
if args.weights.lower() == "coco":
weights_path = COCO_WEIGHTS_PATH
# Download weights file
if not os.path.exists(weights_path):
utils.download_trained_weights(weights_path)
elif args.weights.lower() == "last":
# Find last trained weights
weights_path = model.find_last()
elif args.weights.lower() == "imagenet":
# Start from ImageNet trained weights
weights_path = model.get_imagenet_weights()
else:
weights_path = args.weights
# Load weights
print("Loading weights ", weights_path)
if args.weights.lower() == "coco":
# Exclude the last layers because they require a matching
# number of classes
model.load_weights(weights_path, by_name=True, exclude=[
"mrcnn_class_logits", "mrcnn_bbox_fc",
"mrcnn_bbox", "mrcnn_mask"])
else:
model.load_weights(weights_path, by_name=True)
# Train or evaluate
if args.command == "train":
train(model)
else:
print("'{}' is not recognized. "
"Use 'train' or 'splash'".format(args.command))

Extend automatically Panel with Tabs in Powershell

I have a frame which contains one panel with Tabs. When I extend the main frame, I vould like my panel was extended too. Can you tell me what can I do for, please ?
function Show-tabcontrol_psf {
#----------------------------------------------
#region Import the Assemblies
#----------------------------------------------
[void][reflection.assembly]::Load('System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089')
[void][reflection.assembly]::Load('System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089')
[void][reflection.assembly]::Load('System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a')
[void][reflection.assembly]::Load('System.DirectoryServices, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a')
[void][reflection.assembly]::Load('System.ServiceProcess, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a')
#endregion Import Assemblies
#----------------------------------------------
#region Generated Form Objects
#----------------------------------------------
[System.Windows.Forms.Application]::EnableVisualStyles()
$form1 = New-Object 'System.Windows.Forms.Form'
$tabcontrol1 = New-Object 'System.Windows.Forms.TabControl'
$tabpage1 = New-Object 'System.Windows.Forms.TabPage'
$tabpage2 = New-Object 'System.Windows.Forms.TabPage'
$InitialFormWindowState = New-Object 'System.Windows.Forms.FormWindowState'
#endregion Generated Form Objects
#----------------------------------------------
# User Generated Script
#----------------------------------------------
$form1_Load={
}
# --End User Generated Script--
#----------------------------------------------
#region Generated Events
#----------------------------------------------
$Form_StateCorrection_Load=
{
#Correct the initial state of the form to prevent the .Net maximized form issue
$form1.WindowState = $InitialFormWindowState
}
$Form_Cleanup_FormClosed=
{
#Remove all event handlers from the controls
try
{
$form1.remove_Load($form1_Load)
$form1.remove_Load($Form_StateCorrection_Load)
$form1.remove_FormClosed($Form_Cleanup_FormClosed)
}
catch { Out-Null }
}
#endregion Generated Events
#----------------------------------------------
#region Generated Form Code
#----------------------------------------------
$form1.SuspendLayout()
$tabcontrol1.SuspendLayout()
#
# form1
#
$form1.Controls.Add($tabcontrol1)
$form1.AutoScaleDimensions = '6, 13'
$form1.AutoScaleMode = 'Font'
$form1.ClientSize = '453, 517'
$form1.Name = 'form1'
$form1.Text = 'Form'
$form1.add_Load($form1_Load)
#
# tabcontrol1
#
$tabcontrol1.Controls.Add($tabpage1)
$tabcontrol1.Controls.Add($tabpage2)
$tabcontrol1.Alignment = 'top'
$tabcontrol1.Location = '12, 12'
$tabcontrol1.Multiline = $True
$tabcontrol1.Name = 'tabcontrol1'
$tabcontrol1.SelectedIndex = 0
$tabcontrol1.Size = '429, 478'
$tabcontrol1.TabIndex = 0
#
# tabpage1
#
$tabpage1.Location = '42, 4'
$tabpage1.Name = 'tabpage1'
$tabpage1.Padding = '3, 3, 3, 3'
$tabpage1.Size = '583, 442'
$tabpage1.TabIndex = 0
$tabpage1.Text = 'tabpage1'
$tabpage1.UseVisualStyleBackColor = $True
#
# tabpage2
#
$tabpage2.Location = '23, 4'
$tabpage2.Name = 'tabpage2'
$tabpage2.Padding = '3, 3, 3, 3'
$tabpage2.Size = '602, 442'
$tabpage2.TabIndex = 1
$tabpage2.Text = 'tabpage2'
$tabpage2.UseVisualStyleBackColor = $True
#
#----------------------------------------------
#Save the initial state of the form
$InitialFormWindowState = $form1.WindowState
#Init the OnLoad event to correct the initial state of the form
$form1.add_Load($Form_StateCorrection_Load)
#Clean up the control events
$form1.add_FormClosed($Form_Cleanup_FormClosed)
#Show the Form
return $form1.ShowDialog()
} #End Function
Call the form
Show-tabcontrol_psf | Out-Null
----------------------------------------------
function Show-tabcontrol_psf {
#----------------------------------------------
#region Import the Assemblies
#----------------------------------------------
[void][reflection.assembly]::Load('System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089')
[void][reflection.assembly]::Load('System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089')
[void][reflection.assembly]::Load('System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a')
[void][reflection.assembly]::Load('System.DirectoryServices, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a')
[void][reflection.assembly]::Load('System.ServiceProcess, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a')
#endregion Import Assemblies
#----------------------------------------------
#region Generated Form Objects
#----------------------------------------------
[System.Windows.Forms.Application]::EnableVisualStyles()
$form1 = New-Object 'System.Windows.Forms.Form'
$tabcontrol1 = New-Object 'System.Windows.Forms.TabControl'
$tabpage1 = New-Object 'System.Windows.Forms.TabPage'
$tabpage2 = New-Object 'System.Windows.Forms.TabPage'
$InitialFormWindowState = New-Object 'System.Windows.Forms.FormWindowState'
#endregion Generated Form Objects
#----------------------------------------------
# User Generated Script
#----------------------------------------------
$form1_Load={
}
# --End User Generated Script--
#----------------------------------------------
#region Generated Events
#----------------------------------------------
$Form_StateCorrection_Load=
{
#Correct the initial state of the form to prevent the .Net maximized form issue
$form1.WindowState = $InitialFormWindowState
}
$Form_Cleanup_FormClosed=
{
#Remove all event handlers from the controls
try
{
$form1.remove_Load($form1_Load)
$form1.remove_Load($Form_StateCorrection_Load)
$form1.remove_FormClosed($Form_Cleanup_FormClosed)
}
catch { Out-Null }
}
#endregion Generated Events
#----------------------------------------------
#region Generated Form Code
#----------------------------------------------
$form1.SuspendLayout()
$tabcontrol1.SuspendLayout()
#
# form1
#
$form1.Controls.Add($tabcontrol1)
$form1.AutoScaleDimensions = '6, 13'
$form1.AutoScaleMode = 'Font'
$form1.ClientSize = '453, 517'
$form1.Name = 'form1'
$form1.Text = 'Form'
$form1.add_Load($form1_Load)
#
# tabcontrol1
#
$tabcontrol1.Controls.Add($tabpage1)
$tabcontrol1.Controls.Add($tabpage2)
$tabcontrol1.Alignment = 'top'
$tabcontrol1.Location = '12, 12'
$tabcontrol1.Multiline = $True
$tabcontrol1.Name = 'tabcontrol1'
$tabcontrol1.SelectedIndex = 0
$tabcontrol1.Size = '429, 478'
$tabcontrol1.TabIndex = 0
#
# tabpage1
#
$tabpage1.Location = '42, 4'
$tabpage1.Name = 'tabpage1'
$tabpage1.Padding = '3, 3, 3, 3'
$tabpage1.Size = '583, 442'
$tabpage1.TabIndex = 0
$tabpage1.Text = 'tabpage1'
$tabpage1.UseVisualStyleBackColor = $True
#
# tabpage2
#
$tabpage2.Location = '23, 4'
$tabpage2.Name = 'tabpage2'
$tabpage2.Padding = '3, 3, 3, 3'
$tabpage2.Size = '602, 442'
$tabpage2.TabIndex = 1
$tabpage2.Text = 'tabpage2'
$tabpage2.UseVisualStyleBackColor = $True
#
#----------------------------------------------
#Save the initial state of the form
$InitialFormWindowState = $form1.WindowState
#Init the OnLoad event to correct the initial state of the form
$form1.add_Load($Form_StateCorrection_Load)
#Clean up the control events
$form1.add_FormClosed($Form_Cleanup_FormClosed)
#Show the Form
return $form1.ShowDialog()
} #End Function
Call the form
Show-tabcontrol_psf | Out-Null
I have an incomplete solution
$TabControl.Anchor = [System.Windows.Forms.AnchorStyles]::Top -bor [System.Windows.Forms.AnchorStyles]::Bottom
$TabControl.Anchor = [System.Windows.Forms.AnchorStyles]::Left -bor [System.Windows.Forms.AnchorStyles]::Right
I have to gather this two lines and the problem will be solved.
I had the solution :
$TabControl.Anchor = [System.Windows.Forms.AnchorStyles]::Top
-bor [System.Windows.Forms.AnchorStyles]::Bottom
-bor [System.Windows.Forms.AnchorStyles]::Left
-bor [System.Windows.Forms.AnchorStyles]::Right

ROS service failed to save files

I want to have a service 'save_readings' that automatically saves data from a rostopic into a file. But each time the service gets called, it doesn't save any file.
I've tried to run those saving-file code in python without using a rosservice and the code works fine.
I don't understand why this is happening.
#!/usr/bin/env python
# license removed for brevity
import rospy,numpy
from std_msgs.msg import String,Int32MultiArray,Float32MultiArray,Bool
from std_srvs.srv import Empty,EmptyResponse
import geometry_msgs.msg
from geometry_msgs.msg import WrenchStamped
import json
# import settings
pos_record = []
wrench_record = []
def ftmsg2listandflip(ftmsg):
return [ftmsg.wrench.force.x,ftmsg.wrench.force.y,ftmsg.wrench.force.z, ftmsg.wrench.torque.x,ftmsg.wrench.torque.y,ftmsg.wrench.torque.z]
def callback_pos(data):
global pos_record
pos_record.append(data.data)
def callback_wrench(data):
global wrench_record
ft = ftmsg2listandflip(data)
wrench_record.append([data.header.stamp.to_sec()] + ft)
def exp_listener():
stop_sign = False
rospy.Subscriber("stage_pos", Float32MultiArray, callback_pos)
rospy.Subscriber("netft_data", WrenchStamped, callback_wrench)
rospy.spin()
def start_read(req):
global pos_record
global wrench_record
pos_record = []
wrench_record = []
return EmptyResponse()
def save_readings(req):
global pos_record
global wrench_record
filename = rospy.get_param('save_file_name')
output_data = {'pos_list':pos_record, 'wrench_list': wrench_record }
rospy.loginfo("output_data %s",output_data)
with open(filename, 'w') as outfile: # write data to 'data.json'
print('dumping json file')
json.dump(output_data, outfile) #TODO: find out why failing to save the file.
outfile.close()
print("file saved")
rospy.sleep(2)
return EmptyResponse()
if __name__ == '__main__':
try:
rospy.init_node('lisener_node', log_level = rospy.INFO)
s_1 = rospy.Service('start_read', Empty, start_read)
s_1 = rospy.Service('save_readings', Empty, save_readings)
exp_listener()
print ('mylistener ready!')
except rospy.ROSInterruptException:
pass
Got it. I need to specify a path for the file to be saved.
save_path = '/home/user/catkin_ws/src/motionstage/'
filename = save_path + filename

Calling variable from another function

The function below gives me this error:
"UnboundLocalError: local variable 'housebank' referenced before assignment"
def placeBet(table, playerDictionary, bet, wager):
playerDictionary['You'][1].add(bet)
housebank -= (wager*table[bet][0])
table[bet][1]['You']=wager
The housebank variable is declared in my main function below:
def main():
housebank = 1000000
table = {'7' : [9/1,{}]}
playerDirectory = {'player1':[1,set(),True]}
placeBet(table,playerDirectory, 10, 100)
How can I use housebank in the placeBet function?
If I do a return it will exit the main function, which I do not want to do... Any ideas?
housebank is local to placeBet. There's three ways to do it that I can see:
Make a class.
class Foo:
def __init__():
self.housebank = 1000000
def run():
# ....
def placeBet(....):
# ....
self.housebank -= (wager*table[bet][0])
# ....
def main():
Foo().run()
Declare housebank in a wider scope:
housebank = 1000000
def placeBet(....):
# ....
def main():
# ....
Make placeBet a closure inside main:
def main():
housebank = 1000000
def placeBet(....):
# ....
# .... rest of main ....