How do I add a constraint for a list to not be empty in smithy? - constraints

How do I add a constraint for a list to not be empty in smithy?
I have a smithy list as below -
list CarsList {
member: Car
}
struct Car {
#required
Name: CarName
}
#length(min: 1)
string CarName
I want to add a constraint/trait to the list CarList to not allow it to be empty.
I tried to add #required to CarName in struct Car and #length(min: 1) to string Carname as shown above but it did not do any work.

You can use the #min trait for such requirements.
list CarsList {
#min(1)
member: Car
}
struct Car {
#required
Name: CarName
}
#length(min: 1)
string CarName
If you create an instance of CarsList with no elements, it will be considered invalid. #min trait specifies a minimum amount of elements that the list must have, here we have at least 1 is required.

Related

How to transform a Custom Object List by excluding particular property in Kotlin?

How to transform a List into a new List by excluding a property in T.
For instance if User data class has 10 properties, I need to transform List into a new List without one particular property in User . New List like List
data class User(val name: String, val age: Int)
var userList = mutableListOf<User>()
var nameList= userList.map { it.name }
If a List to be created without property 'age'. Like
var withoutAgeList
In your first example:
var userList = mutableListOf<User>()
var nameList= userList.map { it.name }
The question "What's the type of nameList?" has a simple answer: List<String>. So let me ask you a similar question: What's the type of withoutAgeList? The answer to that question informs the answer to your question.
Perhaps a user without the age property is a separate AgelessUser class, meaning withoutAgeList is of type List<AgelessUser>. In that case, I suggest either a constructor or a factory function that builds AgelessUser from User, and you want one of these:
val withoutAgeList = userList.map { AgelessUser(it) } // constructor
val withoutAgeList = userList.map { agelessUserOf(it) } // factory
Alternatively, maybe the age property in User is nullable and immutable, and you want to represent users without an age as a regular User where age=null. In this case, you could copy the Users and override the age field
// TODO: pass all the other fields too
val withoutAgeList = userList.map { User(it.name, null) }
Assuming Users is a data class, we can avoid explicitly naming all fields by making use of copy():
val withoutAgeList = userList.map { it.copy(age = null) }
Maybe the age property is nullable and mutable — and you actually want to change the users in place instead of copying them. This is somewhat risky and I don't advocate doing it this way unless you really know what you're doing though.
userList.forEach { it.age = null }
// They're actually the same list!
val withoutAgeList = userList
In such a simple case you can map a list of Users into a list of strings:
val names: List<String> = userList.map(User::name)
Or you can declare a DTO and map into the latter:
class UserWithoutAge(val name: String)
val usersWithoutAge: List<UserWithoutAge> = userList.map { UserWithoutAge(it.name) }
P.S. you don't have to write an explicit type
You can use the Object Oriented approach:
data class User(val name: String, val age: Int)
data class UserNoAge(var name: String) {
constructor(user: User) : this(user.name)
}
var userList = listOf(User("John", 25), User("Jane", 30))
var userNoAge: List<UserNoAge> = mutableListOf<UserNoAge>()
userNoAge = userList.map{ UserNoAge(it) }
println(userNoAge) // [UserNoAge(name=John), UserNoAge(name=Jane)]

Sitecore Glass Mapper Infer Type Droptree Field with different template items

I have a template BrochuresComponent that has a field named Location which is a droptree. Now using source on the field in sitecore template, a user is only going to be able to add a country item or a continent item to this dropdown option. I want glass to map the country item in option to a ICountry glass Item and the continent Item to a Icontinent glass item.
But when user selects a option in dropdown,one of the glassItem value is filled while other has evaluation errors on it resulting in error on the model. Below is my code snippet.
My glass Interface looks as follows:
using Collette.Library.GlassItems.Objects.Taxonomy.Locations;
using Collette.Library.GlassItemsConstants.Objects.Page_Components.Destination_Page_Components;
using Glass.Mapper.Sc.Configuration;
using Glass.Mapper.Sc.Configuration.Attributes;
namespace Collette.Library.GlassItems.Objects.Page_Components.Destination_Page_Components
{
[SitecoreType(TemplateId = BrochureComponentsConstants.TemplateIdString, AutoMap = true)]
public interface IBrochuresComponent: IGlassItemEx
{
//Brochures Data Section
[SitecoreField(FieldType = SitecoreFieldType.DropTree, FieldId = BrochureComponentsConstants.LocationItemFieldId, Setting = SitecoreFieldSettings.InferType)]
ICountry Country { get; set; }
[SitecoreField(FieldType = SitecoreFieldType.DropTree, FieldId = BrochureComponentsConstants.LocationItemFieldId, Setting = SitecoreFieldSettings.InferType)]
IContinent Continent { get; set; }
}
}
My Model Looks as follows:
var sitecoreContext = new SitecoreContext();
BrochuresComponentItem = sitecoreContext.Cast<IBrochuresComponent>(DisplayItem);
//IF we specified a continent in dropdown it works fine since that is the first condition so it does not go to else,
//but if we specify a country in the dropdown it breaks at the if condition below stating that templateid is empty string since nothing was evaluated.
Empty strings are not allowed.
Parameter name: fieldName
if (BrochuresComponentItem.Continent != null && BrochuresComponentItem.Continent.TemplateId.Equals(ContinentConstants.TemplateId))
{
SetBrochures(BrochuresComponentItem.Continent);
}
else if (BrochuresComponentItem.Country != null && BrochuresComponentItem.Country.TemplateId.Equals(CountryConstants.TemplateId))
{
SetBrochures(BrochuresComponentItem.Country);
}
Your implementation/understanding of how infertype works is wrong, have a read of the Glass tutorial for Inferred Types.
In order for this to work correctly, your Country and Continent templates need to have a common base, and then you can use the infertype to map to the specific type:
[SitecoreType(TemplateId = BrochureComponentsConstants.TemplateIdString, AutoMap = true)]
public interface IBrochuresComponent: IGlassItemEx
{
//Brochures Data Section
[SitecoreField(FieldType = SitecoreFieldType.DropTree, FieldId = BrochureComponentsConstants.LocationItemFieldId, Setting = SitecoreFieldSettings.InferType)]
ILocationBase Location { get; set; }
}
Then on your code you can check the type it has been mapped to:
if (BrochuresComponentItem.Location != null)
{
if (BrochuresComponentItem.Location is ICountry)
{
//do country specific thing
}
else if (BrochuresComponentItem.Location is IContinent)
{
// do continent specific thing
}
}
Make sure the models for both ICountry and IContinent inherit from the common base interface to match the base data template, ILocationBase

JavaFX Sqlite get ID from selected ListView Element

I have a ListView which is filled with artwork names (from SQLite database), these are strings and the names are not primary keys (not unique). Of course each artwork has its own ID (primary key).
What I do, I select one artwork from this list and pass it as a string argument to a button, which creates additional informations (that is not neccessary for this question).
But I select the name, now I need to get the ID from this selected artwork as foreign key.
Of course I can create a select query like this:
"select * from Artwork where Name = ?";
and then get the ID from the artwork with this name, but as I said before, there can be multiple artworks with the same name, so this is not good.
The Plan B which I have is to display in the ListView also the IDs of the the artworks, then If you select one artwork, you could slice the String at " " and take work with the list argument which contains the ID.
But that does not feel right.
Thanks! I hope you understood what I need, if not I could provide code, but there is really a lot.
You are confusing what is displayed in the list view (the data) with how it is displayed (the view). You want the data to consist of objects containing both the id and the name. You want the view to simply display the name of those objects.
Create a class representing the Artwork that contains both the id and the name:
public class Artwork {
private final int id ;
private final String name ;
public Artwork(int id, String name) {
this.id = id ;
this.name = name ;
}
public String getName() {
return name ;
}
public int getId() {
return id ;
}
}
Have your database code return a list of Artwork objects, and define your list view:
ListView<Artwork> listView = new ListView<>();
listView.getItems().addAll(getArtworkFromDatabase());
Finally, to configure how the list view is displayed, set the cell factory:
listView.setCellFactory(lv -> new ListCell<Artwork>() {
#Override
public void updateItem(Artwork artwork, boolean empty) {
super.updateItem(artwork, empty) ;
setText(empty ? null : artwork.getName());
}
}
Now you can get whatever data you need from the selected item:
Artwork selected = listView.getSelectionModel().getSelectedItem();
int selectedId = selected.getId();
String selectedName = selected.getName();

Bind repeater list with enum

I have a requirement where when a user clicks on image a list should be shown with checkboxes and all the categories that is present in DB and user should be able to select the checkboxes. How can this be achieved using asp:repeater control? the caegory is a enum type and can have n number of values. In repeater i have added a checkbox and a label; the label should display the category text.
To start with, you should add the [Description] attribute to each value in your Enum. This allows you to set proper descriptive text for each value. This attribute is in System.ComponentModel, here's an example: -
public enum CalendarShowAsEnum
{
[Description("None")]
None = 10,
[Description("Busy")]
Busy = 20,
[Description("Out Of Office")]
OutOfOffice = 30,
[Description("On Holiday")]
OnHoliday = 40
}
You then need 2 functions: -
One function that takes an Enum type and a ListBox/DropDown as parameters, and adds an entry for each Enum into the list
A helper function that converts the enum into the descriptive title you gave them (example above)
The List function might look as follows (all this is taken from a project I worked on): -
public static void BindNamedEnumList(ListControl list,
Type enumerationType)
{
list.Items.Clear();
Array array = Enum.GetValues(enumerationType);
ListItem item;
string name;
var enumerator = array.GetEnumerator();
if (enumerator != null)
{
while (enumerator.MoveNext())
{
Enum value = enumerator.Current as Enum;
name = EnumHelper.GetEnumName(value);
item = new ListItem(name);
item.Value = Convert.ToInt32(value).ToString();
list.Items.Add(item);
}
}
}
This function takes a Type and a ListControl (which ListBox and DropDownList both inherit from). The Type is the .GetType() of the enum you want to add to the list. Note that it doesn't select any values and that it does depend on each enum value having a defined integer value. The latter part will help you with selecting individual items.
Note the loop calls EnumHelper.GetEnumName(value) - this is the helper function that uses the Description attribute I mentioned at the start. This function looks like: -
public static string GetEnumName(object value)
{
string retVal = string.Empty;
try
{
FieldInfo fieldInfo = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
retVal = ((attributes.Length != 0) ? attributes[0].Description : value.ToString());
}
catch (System.NullReferenceException)
{
}
finally
{
if (string.IsNullOrEmpty(retVal))
{
retVal = "Unknown";
}
}
return retVal;
}
It uses reflection, so you'll need to add an Imports for System.Reflection
To use the list function to bind a set of Enum values to the list, simply call
{HelperClass}.BindNamedEnumList(myListBox, typeof({MyEnumType})

If I just want to determine a value is present, which Swift data structure should I use?

I'm looking at a bunch of names, and I want to record all the names. My plan was to iterate over the array of names, and use a dictionary to keep track of each name, so I could just look up the name in the dictionary in O(1) time to see if it existed.
What would be the best data structure for this available in Swift? (I'd love to learn the name of the generic data structure that would be best for this, even if it's not in Swift.)
A Dictionary object would do fine, but it requires a value for the key, when I really only need the key.
You're looking for a Set (a collection of unordered unique objects - some implementations are ordered, though).
Swift and ObjectiveC have NSSet, wouldn't this work for you?
Swift does not provide a set type. You can refer to this blog post for how to define a Set.
Code reproduced here for quick reference:
struct Set<T: Hashable> {
typealias Element = T
private var contents: [Element: Bool]
init() {
self.contents = [Element: Bool]()
}
/// The number of elements in the Set.
var count: Int { return contents.count }
/// Returns `true` if the Set is empty.
var isEmpty: Bool { return contents.isEmpty }
/// The elements of the Set as an array.
var elements: [Element] { return Array(self.contents.keys) }
/// Returns `true` if the Set contains `element`.
func contains(element: Element) -> Bool {
return contents[element] ?? false
}
/// Add `newElements` to the Set.
mutating func add(newElements: Element...) {
newElements.map { self.contents[$0] = true }
}
/// Remove `element` from the Set.
mutating func remove(element: Element) -> Element? {
return contents.removeValueForKey(element) != nil ? element : nil
}
}
Otherwise, you can just use Dictionary and use the name as both key and value.

Resources