Python decorator to create dictionary - python-decorators

Decorator fun!
I would like to create a ‘function dispatch dictionary’
decorator ‘assign1’ creates a dictionary as expected:
decorator ‘assign2’ I try to make the dictionary value a tuple, things get a little weird
d1 = dict()
d2 = dict()
assign1 = lambda d, k: lambda f: d.setdefault(k, f)
assign2 = lambda d, k, s: lambda f: d.setdefault(k, (f,s))
#assign1 (d1, 'FW')
#assign1 (d1, 'PW')
def func1():
pass
#assign2 (d2, 'FW', 'XX')
#assign2 (d2, 'PW', 'XD')
#assign2 (d2, 'DF', 'XC')
def func2():
pass
print ('assign1')
for k in d1:
print ('{0} : {1}'.format( k, d1[k]))
print('assign2')
for k in d2:
print ('{0} : {1}'.format( k, d2[k]))
#Output
assign1
FW : <function func1 at 0x000000000311F400>
PW : <function func1 at 0x000000000311F400>
assign2
DF : (<function func2 at 0x000000000311F510>, 'XC')
FW : (((<function func2 at 0x000000000311F510>, 'XC'), 'XD'), 'XX')
PW : ((<function func2 at 0x000000000311F510>, 'XC'), 'XD')

It's tricky but here is how you could find out:
In [55]: func1()
In [56]: func2()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-57-dff3c14b0386> in <module>()
----> 1 func2()
TypeError: 'tuple' object is not callable
What ?! func2 is now a tuple ???
Yes it is. The setdefault method returns the value you have set. In the first case it worked because you set it to func1 but in the second case it became a tuple, and that tuple was applied to the next decorator and so on...

Related

Random number generation problem with meta table

Please look at the next code, Lua.
randomNumber = {
new = function(self,o)
o = o or {}
setmetatable(o, self)
self.__index = self
return o
end,
math.randomseed(os.time()),
getNum = math.random()
}
for i = 1, 10 do
x = randomNumber:new()
print(x.getNum)
end
The output results are as follows.
0.13782639400248
0.13782639400248
0.13782639400248
0.13782639400248
0.13782639400248
0.13782639400248
0.13782639400248
0.13782639400248
0.13782639400248
0.13782639400248
I want to get 10 different numbers. Can someone help me? Thank you in advance.
Let's take a look at your table constructor
randomNumber = {
new = function(self,o) -- this assigns a function to randomNumber["new"]
o = o or {} -- that will return a new instance of your class
setmetatable(o, self)
self.__index = self
return o
end,
math.randomseed(os.time()), -- this assigns the first of two random seed components
-- returned by math.randomseed to randomNumber[1]
getNum = math.random() -- this assings a random number [0,1) to randomNumber["getNum"]
}
In the loop
for i = 1, 10 do
x = randomNumber:new()
print(x.getNum)
end
You create a new instance named x of randomNumber 10 times.
You then print x.getNum.
x.getNum is a nil value so Lua will check wether x has a metatable with a __index field. __index refers to randomNumber so Lua will print randomNumber.getNum which is the random number [0,1) which has not changed since we constructed randomNumber.
You need to call math.random every time you want a new random number.
If you want each instance of randomNumber to be constructed with a random number you need to assign o.rn = math.random() in your new function and either access it via x.rn later or add a function getNum to randomNumber.
getNum = function (self) return self.rn end`
so you can print(x:getNum())
I'm not sure if this is more than a exercise with metatables. But having a dedicated class that just holds a single number doesn't make too much sense to me. Just use a number value.
The main problem with your code is simply...
In a very fast Lua loop os.time() is not fast enough to set a good random seed.
You have to use something that is faster, like...
-- Lua 5.3 - 5.4
for i = 1, 10 do
math.randomseed(math.random(math.mininteger, math.maxinteger)) -- Set seed before print()
print('Seed: ' .. math.randomseed(math.random(math.mininteger, math.maxinteger)), '\nRandom: ' .. math.random(math.maxinteger)) -- Set seed in print()
math.randomseed(math.random(math.mininteger, math.maxinteger)) -- Set seed after print()
end
That puts out something like...
Seed: -634325252416746990
Random: 5554602367968798340
Seed: 574322306421972413
Random: 3317370212892010822
Seed: -5465512503977683870
Random: 6616070635043877067
Seed: -2566820481734265082
Random: 2581377472505137533
Seed: -8408106760854456996
Random: 708876515734960246
Seed: 5641371185711405705
Random: 4259990225803106481
Seed: -3172432877848732304
Random: 5472223279668970440
Seed: 5842301042132325387
Random: 6912957407189525897
Seed: 2126448976574029213
Random: 6156943198274398962
Seed: 4832369017575479065
Random: 6054703131408226582
Lua 5.1
-- Lua 5.1
math.randomseed(math.random(os.time()))
for i = 1, 10 do
math.randomseed(math.random(-99999999, 999999999)) -- Set seed before print()
print('Random: ' .. tostring(math.random(-999999999, 999999999)))
math.randomseed(math.random(-999999999, 999999999)) -- Set seed after print()
end

What am I supposed to pass to the following method in Crystal?

Background
I'm trying to use some Cairo bindings for Crystal, but I'm having some trouble with the syntax and how to call the method below.
It is implemented as such:
# Inside Module Cairo, class Surface
# ...
def write_to_png_stream(write_func : LibCairo::WriteFuncT, closure : Void*) : Status
Status.new(LibCairo.surface_write_to_png_stream(#surface, write_func, closure).value)
end
# Inside Module LibCairo
# ...
enum StatusT
SUCCESS = 0
NO_MEMORY
INVALID_RESTORE
# ...
end
# ...
alias WriteFuncT = Void*, UInt8*, UInt32 -> StatusT
# ...
fun surface_write_to_png_stream = cairo_surface_write_to_png_stream(
surface : PSurfaceT,
write_func : WriteFuncT,
closure : Void*
) : StatusT
Question
Specifically, I'm asking how to call the Cairo::Surface#write_to_png_stream method. What do I pass as the write_func:LibCairo::WriteFuncT? What do I pass as the closure: Void*?
I tried with the following but I haven't managed to get it to work...
def my_write_func(a : Void*, b : UInt8*, c : UInt32) : Cairo::C::LibCairo::StatusT
puts a
puts b
puts c
Cairo::C::LibCairo::StatusT::SUCCESS
end
surface = Cairo::Surface.new Cairo::Format::ARGB32, 400, 300
ctx = Cairo::Context.new surface
ctx.set_source_rgba 1.0, 0.0, 1.0, 1.0
ctx.rectangle 0.0, 0.0, 400.0, 300.0
ctx.fill
# here, how do I call surface.write_to_png_stream passing my 'my_write_func'?
# a Proc doesn't seem to work.. ( ->my_write_func(Void*, UInt8*, UInt32) )
surface.finish
Finally I got it working.. Or well, I managed to call it at least.
surface.write_to_png_stream ->my_write_func(Void*, UInt8*, UInt32), Pointer(Void).null
It turns out it was a Proc afterall as I suspected and that I just needed a null Pointer too.
For future reference, I have an issue at the repo talking about the specific usage of this method, but I suppose the syntax/semantics question is answered here on SO.

How to get value by reference from WIN32OLE::ARGV?

Below code returns 0
v = 0
obj.foo('',0)
printf("v : %d \n", WIN32OLE::ARGV[1])
when really it must return another value by reference.
For example in python it works like here:
v = obj.foo('')
print('v : %d' % v)
I don't get yet how to make same on Ruby.

browser() debug statement R

I have an R script where I have inserted the following code:
options(Debug=TRUE)
#SOME MORE CODE
browser(expr = isTRUE(getOption("Debug")))
#SOME MORE CODE
After the debugger starts, I would like it to proceed to the next line so I type n. However, this does not proceed to the next line but rather seems to continue.
How do I step through the remainder of my code after a browser() statement?
Thanks
To set a point within a function at which to begin debugging, you'll likely want to use trace().
Let's say you have a function myFun and want to begin debugging it right before its call to plot():
myFun <- function() {
x <-
8:1
y <-
1:8
plot(y~x)
lines(y~x)
text(x,y, letters[1:8], pos=3)
}
To construct the call to trace, you will need to know at which step in myFun the call to plot() occurs. To determine that, use the construct as.list(body(myFun)):
as.list(body(myFun))
# [[1]]
# `{`
#
# [[2]]
# x <- 8:1
#
# [[3]]
# y <- 1:8
#
# [[4]]
# plot(y ~ x)
#
# ... More ...
After noting that the call to plot occurs in step 4, you can use trace() to tell R that you'd like to enter a browser right before step 4 every time myFun is called:
trace(myFun, browser, 4)
# TRY IT OUT
# (Once in the browser, type "n" and press Enter to step through the code.)
myFun()
Finally, when you're done debugging the function, turn the trace off with a call to untrace(myFun).
EDIT: The strategy for setting breakpoints for sourced-in scripts is similar. Again, you don't actually insert code into the script. Instead use findLineNum() and setBreakPoint().
Let's say that the function myFun() described above is defined in the text file "myScript.R", which has five blank lines before the function definitions. To insert the breakpoint right before the call to plot:
source("myScript.R") # Must source() once before using findLineNum
# or setBreakPoint
findLineNum("myScript.R#10") # I see that I missed the step by one line
setBreakpoint("myScript.R#11") # Insert the breakpoint at the line that calls
# plot()
myFun() # Test that breakpoint was properly inserted
# (Again, use "n" and Enter to step through code)
browser() is generally for use when running in interactive mode and used in a sub function because if you have it inline in a script and source the whole thing in it will simply execute the next line against the browser prompt when it is called.
E.g. assuming the script:
options(Debug=TRUE)
browser(expr = isTRUE(getOption("Debug")))
b <- 1
b <- 2
b <- 3
It would execute like this:
R> options(Debug=TRUE)
R> browser(expr = isTRUE(getOption("Debug")))
Called from: top level
Browse[1]> b <- 1
Browse[1]> b <- 2
Browse[1]> b <- 3
If you were to run the script step by step and then call a function as so then it's use makes more sense:
R> options(Debug=TRUE)
R> a <- function() {
browser(expr = isTRUE(getOption("Debug")))
b <- 1
b <- 2
b <- 3
return(b)
}
R> e <- a()
Called from: a()
Browse[1]> n
debug at #5: b <- 1
Browse[2]> # ENTER
debug at #6: b <- 2
Browse[2]> b
[1] 1
Browse[2]> # ENTER
debug at #7: b <- 3
Browse[2]> b
[1] 2
Browse[2]> # ENTER
debug at #8: return(b)
Browse[2]> b
[1] 3
Browse[2]> # ENTER
[1] 3
R>

Slow Scala assert

We've been profiling our code recently and we've come across a few annoying hotspots. They're in the form
assert(a == b, a + " is not equal to " + b)
Because some of these asserts can be in code called a huge amount of times the string concat starts to add up. assert is defined as:
def assert(assumption : Boolean, message : Any) = ....
why isn't it defined as:
def assert(assumption : Boolean, message : => Any) = ....
That way it would evaluate lazily. Given that it's not defined that way is there an inline way of calling assert with a message param that is evaluated lazily?
Thanks
Lazy evaluation has also some overhead for the function object created. If your message object is already fully constructed (a static message) this overhead is unnecessary.
The appropriate method for your use case would be sprintf-style:
assert(a == b, "%s is not equal to %s", a, b)
As long as there is a speciaized function
assert(Boolean, String, Any, Any)
this implementation has no overhead or the cost of the var args array
assert(Boolean, String, Any*)
for the general case.
Implementing toString would be evaluated lazily, but is not readable:
assert(a == b, new { override def toString = a + " is not equal to " + b })
It is by-name, I changed it over a year ago.
http://www.scala-lang.org/node/825
Current Predef:
#elidable(ASSERTION)
def assert(assertion: Boolean, message: => Any) {
if (!assertion)
throw new java.lang.AssertionError("assertion failed: "+ message)
}
Thomas' answer is great, but just in case you like the idea of the last answer but dislike the unreadability, you can get around it:
object LazyS {
def apply(f: => String): AnyRef = new {
override def toString = f
}
}
Example:
object KnightSpeak {
override def toString = { println("Turned into a string") ; "Ni" }
}
scala> assert(true != false , LazyS("I say " + KnightSpeak))
scala> println( LazyS("I say " + KnightSpeak) )
Turned into a string
I say Ni
Try: assert( a==b, "%s is not equals to %s".format(a,b))
The format should only be called when the assert needs the string. Format is added to RichString via implicit.

Resources