Are all parameters required when creating a contract? - daml

When creating a contract from a template, are all the parameters required? What if some fields need to be entered later?
template Exp
with
member1 : Party
member2 : Party
comment : Text
where
signatory : member1
choice ABC : ()
with
anotherParty : Party
controller member1
do create this with member2 = anotherParty
pure()
If I want to leave member2 blank when creating the contract, how do I do that? Is it a good pattern or there is better way to work around the problem?

All fields are required. There is no equivalent of null in daml. If you want fields to be optional, use the Optional type. In your case declare member2 : Optional Party. The Optional type can take values None or Some p where p: Party. The first time you create an instance of Exp, you can set member2 to None and then in you choice do create this with member2 = Some anotherParty.

Related

Creating string debug Vec for state machine

When designing a state machine in Verilog I will normally use localparam to define state names. Most simulators will be able to deduce this and during debugging you can view the state signal by name and not by a number. For simulators that don't figure this out automatically (Icarus), I will generally do something like the following:
`ifdef SIMULATION
reg [8*40:1] state_name;
always #(*) begin
case(state)
WAIT_SDS : state_name = "WAIT_SDS";
IDLE : state_name = "IDLE";
HEADER_DI : state_name = "HEADER_DI";
HEADER_WC0 : state_name = "HEADER_WC0";
HEADER_WC1 : state_name = "HEADER_WC1";
HEADER_ECC : state_name = "HEADER_ECC";
LONG_DATA : state_name = "LONG_DATA";
CRC0 : state_name = "CRC0";
CRC1 : state_name = "CRC1";
IDL_SYM_ST : state_name = "IDL_SYM_ST";
endcase
end
`endif
Allowing me to plot this signal in ASCII.
I have been trying to find a decent way to perform this in Chisel but I'm having no real luck. I currently use ChiselEnum and while I know there was a issue on the Github for trying to make it print a localparam it's not implemented yet. So I would like to add this to what Chisel generates.
Is there a way to achieve this, or something similar with current Chisel APIs?
One issue is I would need to create something and also put a dontTouch around it. If I can't wrap in SYNTHESIS ifdefs then it would likely create some logic I don't want.
An alternative method would be to automatically generate translation files for the waveform viewer.
Here's a FIRRTL transform targeting gtkwave. It creates translation filter files for all ChiselEnums definitions and a "gtkw" savefile populated with all ports and submodules.
https://gist.github.com/kammoh/b3c85db9f2646a664f8dc84825f1bd1d
You can use it with chiseltest (chisel-testers2) like this:
class MySpec extends FlatSpec with ChiselScalatestTester{
val annos = Seq(
WriteVcdAnnotation,
GtkwaveColoredFiltersAnnotation,
)
test(new MyModule).withAnnotations(annos) { dut =>
// test logic
}
}
It's still a work in progress and if there's interest, I can suggest a PR for adding it to chiseltest.

In Ada, How do I recursively map and memory manage a type within itself

I've been struggling with this little issue for a while. I am trying to create my own implementation of an internal JSON structure. The challenge is that with Ada I have to use an access type to make it recursive and access types have the risk of leaking if I don't have it tightly controlled. In order to make it controlled, I kept all the real activity private I provided Get (Source:...) and Set (Target:...; Value:...) functions/procedures for the Node type that will attempt to verify and handle any existing Vector (json-array) or Map (json-object) elements. In order to further ensure that I was using stable features of Ada 2012 and catching contents as they go out of scope, I tried to use a Protected_Controlled type and "managing" Ada libraries, but found that the container libraries couldn't handle protected types, so I used simply Controlled. The Finalize (...) procedure is for any Vector or Map types and recursively frees the Node_Value.Reference.
My question is if I am applying Ada 2012 correctly, or else how do I create a memory managed recursion of a type that could be either a vector/map or a string/number?
private
...
type Node_Access is access Node;
type Node_Value is new Ada.Finalization.Controlled with record
Reference : Node_Access;
end record;
overriding procedure Initialize (Item : in out Node_Value);
overriding procedure Adjust (Item : in out Node_Value);
overriding procedure Finalize (Item : in out Node_Value);
...
package Of_Array is new Ada.Containers.Indefinite_Vectors (Natural, Node_Value);
package Of_Object is new Ada.Containers.Indefinite_Ordered_Maps (Wide_String, Node_Value);
type Node is record
...
Vector : aliased Of_Array.Vector;
Object : aliased Of_Object.Map;
end record
with Size => 96;
procedure Free is new Ada.Unchecked_Deallocation (Node, Node_Access);
The way to do it (in my opinion) is to use OOP and have an abstract element as the root node of a family of types representing the different kinds of data which can be stored.
An array of elements can then be implemented as a vector of the class rooted at the abstract element type. An "object" can be implemented as a hash-table with a string key and the class rooted at the abstract element type as the values.
Self-referential types without access types are a valid use for type extension in combination with an indefinite container. A simple example is S-expressions, or Sexes. A Sex is either an atom or a list of zero or more Sexes. The right way to be able to do this would be
with Ada.Containers.Indefinite_Vectors;
package Sexes is
type Sex is private;
-- Operations on Sex
private -- Sexes
package Sex_List is new Ada.Containers.Indefinite_Vectors
(Index_Type => Positive, Element_Type => Sex); -- Illegal
type Sex (Is_Atom : Boolean := False) is record
case Is_Atom is
when False =>
Value : Atom;
when True =>
List : Sex_List.Vector;
end case;
end record;
end Sexes;
but Ada doesn't allow this. We can use type extension to get around this:
private -- Sexes
type Root is tagged null record;
package Sex_List is new Ada.Containers.Indefinite_Vectors
(Index_Type => Positive, Element_Type => Root'Class);
type Sex (Is_Atom : Boolean := False) is new Root with record
case Is_Atom is
when False =>
Value : Atom;
when True =>
List : Sex_List.Vector;
end case;
end record;
end Sexes;
which is legal. The only catch is that you have to convert anything taken from List to Sex (or Node in your case).
HTH; sorry about the late response.

How to have an argument possible values dependent on another argument with IPython Widgets?

Assume I have this simple function in Python:
def f(gender, name):
if gender == 'male':
return ranking_male(name)
else:
return ranking_female(name)
where gender belongs to ['male', 'female'] whereas name belongs to ['Adam', 'John', 'Max', 'Frodo'] (if gender is male) or ['Mary', 'Sarah', 'Arwen'] (otherwise).
I wish to apply interact from ipywidgets to this function f. Normally one would do
from ipywidgets import interact
interact(f, gender = ('male', 'female'), name = ('Adam', 'John', 'Max', 'Frodo'))
The problem is that the admissible values for name now depend on the value chosen for gender.
I tried to find it in the docs but couldn't find it. The only thing I think may be important is
This is used to setup dynamic notifications of trait changes.
Parameters
----------
handler : callable
A callable that is called when a trait changes. Its
signature should be ``handler(change)``, where ``change```is a
dictionary. The change dictionary at least holds a 'type' key.
* ``type``: the type of notification.
Other keys may be passed depending on the value of 'type'. In the
case where type is 'change', we also have the following keys:
* ``owner`` : the HasTraits instance
* ``old`` : the old value of the modified trait attribute
* ``new`` : the new value of the modified trait attribute
* ``name`` : the name of the modified trait attribute.
names : list, str, All
If names is All, the handler will apply to all traits. If a list
of str, handler will apply to all names in the list. If a
str, the handler will apply just to that name.
type : str, All (default: 'change')
The type of notification to filter by. If equal to All, then all
notifications are passed to the observe handler.
But I have no idea how to do it nor to interpret what the doc string is talking about. Any help is much appreciated!
For example you have brand and model of car and model depends on brand.
d = {'Volkswagen' : ['Tiguan', 'Passat', 'Polo', 'Touareg', 'Jetta'], 'Chevrolet' : ['TAHOE', 'CAMARO'] }
brand_widget = Dropdown( options=list(d.keys()),
value='Volkswagen',
description='Brand:',
style=style
)
model_widget = Dropdown( options=d['Volkswagen'],
value=None,
description='Model:',
style=style
)
def on_update_brand_widget(*args):
model_widget.options = d[brand_widget.value]
brand_widget.observe(on_update_brand_widget, 'value')
I've used nested widgets to solve this problem. It'll work, but it's ugly, partially because it doesn't seem to be a common use case in ipywidgets (see discussion).
Given your function f(gender, name) you can define an intermediate wrapper:
def f_intermediate_wrapper(gender):
if gender=="male":
possible_names = ['Adam', 'John', 'Max', 'Frodo']
else:
possible_names = ['Mary', 'Sarah', 'Arwen']
try:
f_intermediate_wrapper.name_widget.widget.close()
except AttributeError:
pass
f_intermediate_wrapper.name_widget = interact(f,
gender=widgets.fixed(gender),
name = possible_names)
The first part sets the possible name options given the gender, as desired.
The second part closes the name_widget from your previous evaluation, if it exists. Otherwise, every time you change the gender, it'll leave up the old list of names, which are the wrong gender (see example).
The third part creates a name widget of the possible names for that gender, and stores it somewhere sufficiently static. (Otherwise, when you change the gender the old name widget will be out of scope, and you won't be able to close it.)
Now you can create your gender and name widget:
gender_and_name_widget = interact(f_intermediate_wrapper,
gender = ["male", "female"])
And you can access the result of your f(gender, name) using
gender_and_name_widget.name_widget.widget.result

Python 2.7.5, using a loop within a function and calling the function

I can't seem to get user input for a number of times to display. For example, if the input is
Jeff 6
The output should be
Jeff
Jeff
Jeff
Jeff
Jeff
Jeff
I'm new to functions in Python, but here is my code thus far:
def getName():
name = raw_input("please enter name")
return name
def getRepval():
irepnum = float(raw_input("please enter number to show name entered"))
return irepnum
def inamed(name, irepnum):
count = 1 #the loop to show the name entered by the user
while irepnum != count:
print name
count += 1 #do I need to use return??
def main(): #having the main func like this gives me an infinite loop
irepnum = 0
iname = getName() #I think my problem is somewhere here.
irepnum = getRepval()
inamed(irepnum,name)
main()
You need to call inamed(iname, irepnum), not inamed(irepnum, name), as you are doing now.
Other than the obvious mistake of name not being defined (the actual variable is called iname), the wrong order causes irepnum in the function to be set to a string the user entered as name. Since count, no matter how large, never compares equal to the passed string, the code loops infinitely.
Several tips:
Learn to use the for loop and xrange. The idiom you want is for count in xrange(irepnum):. (Using it would have prevented this bug.)
Give more distinctive names to your identifiers. Currently you have an inamed function and an iname variable. Confusing.
Don't use floats where an int would suffice. Misusing floats is asking for trouble.

How can I clone (or copy) a object to another one, but don't copy PK attribute?

I'm trying to copy all object attibutes to another object, fox example:
Person p1 = new Person();
p1.name = "John";
p1.sex = 'M';
Person p2 = new Person();
p2 = Util.Clone(p1);
The problem is that Person entity has an identity PK 'codPerson' and I don't want to copy this PK. Is there a way to clone/copy an object, but don't copy its PK attribute??
Thanks!!!
Perhaps you might consider the following:
Ensure Util.Clone(Person p) doesn't
copy the codPerson attribute
Clear the attribute after the Clone method
is called
Create a new Person object while specifically initializing specific properties.
At the most basic level you can't - given an arbitrary object o (and the question implies you're looking for generic solutions) you have no way to determine which field is a primary key.
So you step up a level - by adding some constraints i.e. that you will inform your tools what the primary key field is (or fields are) and hence enable use of a generic method.
So, you could explicitly specify the PK field (name) to the code that does the clone (I assume that you're using reflection to avoid explicitly copying all the fields). You could identify the PK by using annotation of some sort on the classes being cloned and have the clone code exclude properties with the relevant annotation (the annotation implies that the field won't be cloned). There may be other methods
You mention Linq - are you using a specific bit of Linq ?
Beyond that there's not a lot one can suggest without more details - ah but the question is tagged with Linq to SQL (which I missed) ok...
There's nothing obvious in a Linq to SQL class that will help - nor with the "table" but a quick look at the generated code in .designer.cs shows that a key field has annotations similar to the following (taken from a set of classes I have to hand):
[Column(Storage="_ID", AutoSync=AutoSync.OnInsert, DbType="Int NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)]
Therefore when you're do your reflection on the class to enumerate the properties to copy you'll want to look for the column and the "IsPrimaryKey" property within the column - unfortunately the details of how to do that are some distance outside my comfort zone!
You could manually set the properties on the new object to be equal to the old one.
For example:
Person p2 = new Person {
Name = p1.Name,
Gender = p1.Gender,
//...
};
you can use .net Reflection.
//using System.Reflection;
var yourEntity = new Person {Name = "Green", Surname= "White"};
var cloneEntity = new Person();
var allPi = typeof(Person).GetProperties();
foreach (var pi in allPi)
{
if (pi.Name != "codPerson" && pi != null && pi.CanWrite)
pi.SetValue(cloneEntity , pi.GetValue(yourEntity , null));
}