Second dict refering to first dict doesn't register changes to first - dictionary

dictOne = {'a':1, 'b':2}
dictTwo = {'aa':dictOne['a'], 'bb':dictOne['b']}
print(dictTwo['aa']
# returns 1
If I make a change to dictOne like:
dictOne['a'] = 2
print(dictOne['a'])
# returns 2
but the second dict that refers to the first still returns the original value.
print(dictTwo['aa'])
# returns 1
What is happening here? I'm sure this is somehow an inappropriate usage of dict but I need to resolve this in the immediate. Thanks.

You're extracting the value from the key 'a' inside dictOne with the below piece of code
dictTwo = {'aa':dictOne['a']}
You may find some value in reading the python FAQ on pass by assignment
Without knowing more about the problem, it's difficult to say exactly how you can solve this. If you need to create a mapping between different sets of keys, there's the option to do something like:
dictTwo = {'aa' : 'a', 'bb' : 'b'}
dictOne[dictTwo['aa']]
Although maybe what you're looking for is a multi key dict

The line here:
dictTwo = {'aa':dictOne['a'], 'bb':dictOne['b']}
Is equivalent to:
dictTwo = {'aa':1, 'bb':2}
Since dictOne['a'] and dictOne['b'] both return immutable values (integers), they are passed by copy, and not by reference. See How do I pass a variable by reference?
Had you done dictTwo = dictOne, updating dictOne would also update dictTwo, however they would have the same key values.

Related

KEYWORD_SET in IDL

I am new to IDL and find the KEYWORD_SET difficult to grasp. I understand that it is a go no go switch. I think its the knocking on and off part that I am having difficulty with. I have written a small program to master this as such
Pro get_this_done, keyword1 = keyword1
WW=[3,6,8]
PRINT,'WW'
print,WW
y= WW*3
IF KEYWORD_Set(keyword1) Then BEGIN
print,'y'
print,y
ENDIF
Return
END
WW prints but print, y is restricted by the keyword. How do I knock off the keyword to allow y to print.
Silly little question, but if somebody can indulge me, it would be great.
After compiling the routine, type something like
get_this_done,KEYWORD1=1b
where the b after the one sets the numeric value to a BYTE type integer (also equivalent to TRUE). That should cause the y-variable to be printed to the screen.
The KEYWORD_SET function will return a TRUE for lots of different types of inputs that are basically either defined or not zero. The IF loop executes when the argument is TRUE.
Keywords are simply passed as arguments to the function:
get_this_done, KEYWORD1='whatever'
or also
get_this_done, /KEYWORD1
which will give KEYWORD1 the INT value of 1 inside the function. Inside the function KEYWORD_SET will return 1 (TRUE) when the keyword was passed any kind of value - no matter whether it makes sense or not.
Thus as a side note to the question: It often is advisable to NOT use KEYWORD_SET, but instead resort to a type query:
IF SIZE(variable, /TNAME) EQ 'UNDEFINED' THEN $
variable = 'default value'
It has the advantage that you can actually check for the correct type of the keyword and handle unexpected or even different variable types:
IF SIZE(variable, /TNAME) NE 'LONG' THEN BEGIN
IF SIZE(variable, /TNAME) EQ 'STRING' THEN $
PRINT, "We need a number here... sure that the cast to LONG works?"
variable = LONG(variable)
ENDIF

Strange Dict behavior with keys of a custom type

I have a recursive function which utilizes a global dict to store values already obtained when traversing the tree. However, at least some of the values stored in the dict seem to disappear! This simplified code shows the problem:
type id
level::Int32
x::Int32
end
Vdict = Dict{id,Float64}()
function getV(w::id)
if haskey(Vdict,w)
return Vdict[w]
end
if w.level == 12
return 1.0
end
w.x == -111 && println("dont have: ",w)
local vv = 0.0
for j = -15:15
local wj = id(w.level+1,w.x+j)
vv += getV(wj)
end
Vdict[w] = vv
w.x == -111 && println("just stored: ",w)
vv
end
getV(id(0,0))
The output has many lines like this:
just stored: id(11,-111)
dont have: id(11,-111)
just stored: id(11,-111)
dont have: id(11,-111)
just stored: id(11,-111)
dont have: id(11,-111)
...
Do I have a silly error, or is there a bug in Julia's dict?
By default, custom types come with implementations of equality and hashing by object identity. Since your id type is mutable, Julia is conservative and assumes that you care about distinguishing each instance from another (since they could potentially diverge):
julia> type Id # There's a strong convention to capitalize type names in Julia
level::Int32
x::Int32
end
julia> x = Id(11, -111)
y = Id(11, -111)
x == y
false
julia> x.level = 12; (x,y)
(Id(12,-111),Id(11,-111))
Julia doesn't know whether you care about the object's long-term behavior or its current value.
There are two ways to make this behave as you'd like:
Make your custom type immutable. It looks like you don't need to mutate the contents of Id. The simplest and most straightforward way to solve this is to define it as immutable Id. Now Id(11, -111) is completely indistinguishable from any other construction of Id(11, -111) since its values can never change. As a bonus, you may see better performance, too.
If you do need to mutate the values, you could alternatively define your own implementations of == and Base.hash so they only care about the current value:
==(a::Id, b::Id) = a.level == b.level && a.x == b.x
Base.hash(a::Id, h::Uint) = hash(a.level, hash(a.x, h))
As #StefanKarpinski just pointed out on the mailing list, this isn't the default for mutable values "since it makes it easy to stick something in a dict, then mutate it, and 'lose it'." That is, the object's hash value has changed but the dictionary stored it in a place based upon its old hash value, and now you can no longer access that key/value pair by key lookup. Even if you create a second object with the same original properties as the first it won't be able to find it since the dictionary checks equality after finding a hash match. The only way to lookup that key is to mutate it back to its original value or explicitly asking the dictionary to Base.rehash! its contents.
In this case, I highly recommend option 1.

does an object need to be initialized before for loop in R

am wondering if I an create an object within a for loop - i.e. don't have to initialize it. I have tried this how one might do it in matlab. Please see the following R code:
> for (i in 1:nrow(snp.ids)) {
+ snp.fasta[i]<-entrez_fetch(db="protein", id=snp.ids[i,], rettype="xml",retmode="text")
+ snp.seq[i]<-xpathSApply(xmlParse(snp.fasta[i]), "//Seq-data_iupacaa",xmlValue)
+ }
Error in snp.fasta[i] <- entrez_fetch(db = "protein", id = snp.ids[i, :
object 'snp.fasta' not found
where it obviously does not find snp.fasta - but you can see from the code I am trying to create snp.fasta. can anyone shed any light on why it would not create it within. the for loop, and what would be the proper way to initialize snp.fasta if I cannot create it within the for loop.
Thanks
Generally , yes. That would be an acceptable way to loop over a vector of ids. Just assign to a non-indexed object.
for (i in 1:nrow(snp.ids)) {
snp.fasta <- entrez_fetch(db="protein", id=snp.ids[i,], rettype="xml",retmode="text")
snp.seq <- xpathSApply(xmlParse(snp.fasta), "//Seq-data_iupacaa",xmlValue)
}
(You would then still need to assign any useful result to an index-able object or build a sequence of such within the loop or print some result. As it stands this example will over-write all the values of snp.seq and leave only the last one. )
It's a bit confusing to see id=snp.ids[i,]. That would imply that snp.ids has a dimension of 2. I would have expected a column name or number to be used: id=snp.ids[i,"id"]. You should provide dput(head(snp.ids)) so we can do some realistic testing rather than this half-assed guesswork.
In R, subsetting is also a function, so assigning value to an item in a vector:
a[1] = 123
is identical to
"["(a, 1) = 123
Here [ is a normal function. If a is not defined, there is an error.
Before the loop:
snp.fasta <- NULL

Variable Names in SWI Prolog

I have been using the chr library along with the jpl interface. I have a general inquiry though. I send the constraints from SWI Prolog to an instance of a java class from within my CHR program. The thing is if the input constraint is leq(A,B) for example, the names of the variables are gone, and the variable names that appear start with _G. This happens even if I try to print leq(A,B) without using the interface at all. It appears that whenever the variable is processed the name is replaced with a fresh one. My question is whether there is a way to do the mapping back. For example whether there is a way to know that _G123 corresponds to A and so on.
Thank you very much.
(This question has nothing to do with CHR nor is it specific to SWI).
The variable names you use when writing a Prolog program are discarded completely by the Prolog system. The reason is that this information cannot be used to print variables accurately. There might be several independent instances of that variable. So one would need to add some unique identifier to the variable name. Also, maintaining that information at runtime would incur significant overheads.
To see this, consider a predicate mylist/1.
?- [user].
|: mylist([]).
|: mylist([_E|Es]) :- mylist(Es).
|: % user://2 compiled 0.00 sec, 4 clauses
true.
Here, we have used the variable _E for each element of the list. The toplevel now prints all those elements with a unique identifier:
?- mylist(Fs).
Fs = [] ;
Fs = [_G295] ;
Fs = [_G295, _G298] .
Fs = [_G295, _G298, _G301] .
The second answer might be printed as Fs = [_E] instead. But what about the third? It cannot be printed as Fs = [_E,_E] since the elements are different variables. So something like Fs = [_E_295,_E_298] is the best we could get. However, this would imply a lot of extra book keeping.
But there is also another reason, why associating source code variable names with runtime variables would lead to extreme complexities: In different places, that variable might have a different name. Here is an artificial example to illustrate this:
p1([_A,_B]).
p2([_B,_A]).
And the query:
?- p1(L), p2(L).
L = [_G337, _G340].
What names, would you like, these two elements should have? The first element might have the name _A or _B or maybe even better: _A_or_B. Or, even _Ap1_and_Bp2. For whom will this be a benefit?
Note that the variable names mentioned in the query at the toplevel are retained:
?- Fs = [_,F|_], mylist(Fs).
Fs = [_G231, F] ;
Fs = [_G231, F, _G375] ;
Fs = [_G231, F, _G375, _G378]
So there is a way to get that information. On how to obtain the names of variables in SWI and YAP while reading a term, please refer to this question.

check if output parameter is null before binding

How can i check if an output parameter is null before i bind it to a asp literal, and if it is null i want to just make the literal
hname1.Text = cmd.Parameters("#hotel1").Value
hname1.DataBind()
hname2.Text = cmd.Parameters("#hotel2").Value
hname2.DataBind()
hname3.Text = cmd.Parameters("#hotel3").Value
hname3.DataBind()
hname4.Text = cmd.Parameters("#hotel4").Value
hname4.DataBind()
hname5.Text = cmd.Parameters("#hotel5").Value
hname5.DataBind()
If Not IsDBNull(cmd.Parameters("#hotel1").Value) Then
hname1.Text = cmd.Parameters("#hotel1").Value
hname1.DataBind();
Else
' Manual binding would go here
End If
I believe. Syntax may be a bit hairy as it's been a bit since I've done VB, but the premise should be the same.
This is also assuming cmd.Parameters("#hotel1") will always be a callable object with a Value property. If this could potentially be null, we need to add another comparison to avoid NullObjectReference exception(s).
Also, I hope I understand the question correctly, your mention of "output parameter" without having a Subroutine/Function to look at leads me to believe there's a bit of confusion on semantics.
Version Change
Using IsDBNull to check against empty value

Resources