Using module annotations as method attributes - macros

So here's an interesting question, what I look at the documentation for module attributes in elixir i.e. http://elixir-lang.org/getting-started/module-attributes.html at the bottom it mentions that they can be used as method annotations as in ExUnit.
Unfortunately there is basically no information on how to achieve this and looking through ExUnit code has just got me lost. It seems like I would need to determine the closest method to the attribute to say that they are associated in some way (could be wrong though).
Any idea where I might look to learn about this?

It works like this. Look at source code of ExUnit.Case.
At first, look into __using__ macro, since it will be invoked first when you use it in a test case. Particularly, note here
Enum.each [:ex_unit_tests, :tag, :describetag, :moduletag, :ex_unit_registered],
&Module.register_attribute(__MODULE__, &1, accumulate: true)
This registers #tag and a bunch of more attributes as accumulated. Read the docs of Module.register_attribute/3, and you will see it means anytime attribute is invoked, the value gets appended to a list of previous attributes.
Then note test/3 macro, particularly here
quote bind_quoted: [var: var, contents: contents, message: message] do
name = ExUnit.Case.register_test(__ENV__, :test, message, [])
def unquote(name)(unquote(var)), do: unquote(contents)
end
Note the call to ExUnit.Case.register_test/4. Looking at it, specially here
tag = Module.delete_attribute(mod, :tag)
It fetches the tags until here, and deletes them. And by having the tags, and the name of test, it invokes (here)
test = %ExUnit.Test{name: name, case: mod, tags: tags}
Module.put_attribute(mod, :ex_unit_tests, test)
which saves the test along with tags inside another attributes.
And at last, note here
#doc false
defmacro __before_compile__(_) do
quote do
def __ex_unit__(:case) do
%ExUnit.TestCase{name: __MODULE__, tests: #ex_unit_tests}
end
end
end
The function __ex_unit__/1 is called in ExUnit.Runner.run_case/3 to get information of tests inside each case.
You see the point? Use an accumulated attribute, inside your macro call a function that always gets current value of the attribute and clears it, then do anything you want with the value, because you know it is always for when the macro is called.
I hope it was clear enough, drop a comment if you need more explanation.
PS. I just read the source code to find this out. It was exciting to know how it works.

Related

Tell IPython to use an object's `__str__` instead of `__repr__` for output

By default, when IPython displays an object, it seems to use __repr__.
__repr__ is supposed to produce a unique string which could be used to reconstruct an object, given the right environment.
This is distinct from __str__, which supposed to produce human-readable output.
Now suppose we've written a particular class and we'd like IPython to produce human readable output by default (i.e. without explicitly calling print or __str__).
We don't want to fudge it by making our class's __repr__ do __str__'s job.
That would be breaking the rules.
Is there a way to tell IPython to invoke __str__ by default for a particular class?
This is certainly possible; you just need implement the instance method _repr_pretty_(self). This is described in the documentation for IPython.lib.pretty. Its implementation could look something like this:
class MyObject:
def _repr_pretty_(self, p, cycle):
p.text(str(self) if not cycle else '...')
The p parameter is an instance of IPython.lib.pretty.PrettyPrinter, whose methods you should use to output the text representation of the object you're formatting. Usually you will use p.text(text) which just adds the given text verbatim to the formatted representation, but you can do things like starting and ending groups if your class represents a collection.
The cycle parameter is a boolean that indicates whether a reference cycle is detected - that is, whether you're trying to format the object twice in the same call stack (which leads to an infinite loop). It may or may not be necessary to consider it depending on what kind of object you're using, but it doesn't hurt.
As a bonus, if you want to do this for a class whose code you don't have access to (or, more accurately, don't want to) modify, or if you just want to make a temporary change for testing, you can use the IPython display formatter's for_type method, as shown in this example of customizing int display. In your case, you would use
get_ipython().display_formatter.formatters['text/plain'].for_type(
MyObject,
lambda obj, p, cycle: p.text(str(obj) if not cycle else '...')
)
with MyObject of course representing the type you want to customize the printing of. Note that the lambda function carries the same signature as _repr_pretty_, and works the same way.

Eval() for setting Form controls property

I work on an Access VBA 2013 application, and this part of the project focuses on form controls and buttons.
I want to lock/unlock control modification thanks to buttons set aside.
For more genericity, I wanted the subs called by the events call homemade functions:
Sub LockAssociateControl(fctName As String, val As Boolean)
Dim code As String
code = "Forms!" & getModuleName & ".Controls!" & fctName & ".Locked = " & CStr(val)
Debug.Print (code) 'just to test
Eval code
End Sub
(getModuleName is also a homemade function that returns the right name of the module calling the function)
For example, this one is called like below:
Private Sub FirstName_Exit(Cancel As Integer)
Call LockAssociateControl("FirstName", True)
End Sub
and in "code" variable, it sets "Forms!Module1.Controls!Name.Locked = True" (with Module1 generated by getModuleName, and Name as the parameter (I haven't found better yet)).
Now I want this code evaluated in order to avoid me from hard coding every event sub.
My problem is that an error occurs at the Eval() line and says:
Error Code: 2770. The object to which you reffered in the Visual Basic procedure as an OLE object is not an OLE object
I've looked around StockOverflow and others forums to find out what's wrong with Eval(), and I found that this function's behavior is not made for what I want. So I tried to find another way to do that, as Evaluate function doesn't exist in Access, etc, but I found nothing really helpful.
I tried to use DoCmd or Call or various transformations on the parameter string of Eval(), but nothing has worked so far...
So here's my question: Do any of you have a solution for that problem? And if not, do you know an alternative not to have to write in every event function full statements like: Forms!Module1.Controls!Name.Locked = False?
You can do what you want easier without using Eval() ...
Sub LockAssociateControl(fctName As String, pVal As Boolean)
Forms(getModuleName).Controls(fctName).Locked = pVal
End Sub
Note I changed the argument name from val to pVal to avoid confusing it with the Val() function.

How can I 'unparse' a parse tree in q/kdb+?

I am trying to create an automatic 'debugger' for tracing function flow. Because I'm not a god, I do make mistakes, and when I do, I normally end up throwing a bunch of "show" in my functions. What I'm looking to do is create a function that will insert shows prior to each line for each variable used in an expression on that line and any variable assigned to in the previous.
Imagine I have a function f that is throwing an unhelpful error. I would insert
f: debugwrap[f];
after the function definition to insert the appropriate debugging within the lines of function string, parse, and return the augmented function.
I have had success handling the params and simple functions, but where I have trouble is where semicolons do not indicate eol, such as in function calls. Using parse on the function body, I can easily break out all the lines and find the required variables, but once I do that, I need to 'unparse' each line in the function. That unparsing is giving me trouble, especially where functions are translated to what I believe is k - such as "*:".
Simple example with only initial logging:
q)f: {[a;b] a: a xexp b; c: a-first `int$-1#string first table[`symbols]; :c }
q)df: dp[f;";"]
q)df
"{[a;b] show "a is ",string[a]; show "b is ",string[b]; a : a xexp b;c : a - *:`int$-1#$:*:table`symbols;: c;}"
q)parse df
ERROR: *:
What I'm doing now is recursively walking through the parse tree and reconstructing the call. That is painful and not yet yielding results. What I think is the best way is to get the information I need out of each parse subtree, then unparse that subtree and append it to my function string.
Appreciate any help you all can offer.
The best place to see how debugging might be done, is with this code: http://code.kx.com/q/ref/debug/

Python: outside function applying changes to a class object's unique namespace

My question is how to program in Python (2.6) a function that uses a namespace of an object, while the function is defined outside the object/class. In addition, that function should only change the variables in the object's namespace; it should not take over the namespace (because with multiple objects they will all use the same namespace).
My reason for pursuing this, is because I wish to write a very small class, where during construction all necessary functions for future use are already given and subsequent function calls (self.__call__) on the object itself can be directly applied.
I realize that this idea is not very pythonic (as they say), and I have thought of various other solutions (such as putting the functions in another class and connecting them), but I can't help but feel that each of these solutions is a lot more work than I would think makes sense.
One simple way that accomplishes what I want is the following:
class A:
def __init__(self, some_dict, func_a):
self.memory = some_dict
self.__call__ = func_a
def test_func(obj, some_input):
if some_input in obj.memory :
return obj.memory[some_input]
else :
obj.memory[some_input] = 0. # some default value
return 0.
first_object = A({}, test_func)
print first_object(first_object, '3')
This will work fine, but what aches me is that when I make function calls to the object, I will also have to give the object itself (see the last line). I hope to be able make calls as such:
print first_object('3')
So far, my ideas were unsuccesful to avoid this (e.g. copying the function method and link its namespace by self.__call__.memory = self.memory). I wish to find something to change the def __init__ part to 'adopt' a function and link their namespaces.
I have rigorously searched for an answer on the internet, but a definite solution has not yet been found. The following http://www.velocityreviews.com/forums/t738476-inserting-class-namespace-into-method-scope.html seeks the same, but is also not succesfull.
Anyone have a solution to tackle this?

In Scala is there any way to get a parameter's method name and class?

At my work we use a typical heavy enterprise stack of Hibernate, Spring, and JSF to handle our application, but after learning Scala I've wanted to try to replicate much of our functionality within a more minimal Scala stack (Squeryl, Scalatra, Scalate) to see if I can decrease code and improve performance (an Achilles heal for us right now).
Often my way of doing things is influenced by our previous stack, so I'm open to advice on a way of doing things that are closer to Scala paradigms. However, I've chosen some of what I do based on previous paradigms we have in the Java code base so that other team members will hopefully be more receptive to the work I'm doing. But here is my question:
We have a domain class like so:
class Person(var firstName: String, var lastName: String)
Within a jade template I make a call like:
.section
- view(fields)
The backing class has a list of fields like so:
class PersonBean(val person: Person) {
val fields: Fields = Fields(person,
List(
Text(person.firstName),
Text(person.lastName)
))
}
Fields has a base object (person) and a list of Field objects. Its template prints all its fields templates. Text extends Field and its Jade template is supposed to print:
<label for="person:firstName">#{label}</label>: <input type="text" id="person:firstName" value="#{value}" />
Now the #{value} is simply a call to person.firstName. However, to find out the label I reference a ResourceBundle and need to produce a string key. I was thinking of using a naming convention like:
person.firstName.field=First Name
So the problem then becomes, how can I within the Text class (or parent Field class) discover what the parameter being passed in is? Is there a way I can pass in person.firstName and find that it is calling firstName on class Person? And finally, am I going about this completely wrong?
If you want to take a walk on the wild side, there's a (hidden) API in Scala that allows you to grab the syntax tree for a thunk of code - at runtime.
This incantation goes something like:
scala.reflect.Code.lift(f).tree
This should contain all the information you need, and then some, but you'll have your work cut out interpreting the output.
You can also read a bit more on the subject here: Can I get AST from live scala code?
Be warned though... It's rightly classified as experimental, do this at your own risk!
You can never do this anywhere from within Java, so I'm not wholly clear as to how you are just following the idiom you are used to. The obvious reason that this is not possible is that Java is pass-by-value. So in:
public void foo(String s) { ... }
There is no sense that the parameter s is anything other than what it is. It is not person.firstName just because you called foo like:
foo(person.firstName);
Because person.firstName and s are completely separate references!
What you could do is replacing the fields (e.g. firstname) with actual objects, which have a name attribute.
I did something similiar in a recent blog post:http://blog.schauderhaft.de/2011/05/01/binding-scala-objects-to-swing-components/
The property doesn't have a name property (yet), but it is a full object but is still just as easy to use as a field.
I would not be very surprised if the following is complete nonsense:
Make the parameter type of type A that gets passed in not A but Context[A]
create an implicit that turns any A into a Context[A] and while doing so captures the value of the parameter in a call-by-name parameter
then use reflection to inspect the call-by-name parameter that gets passed in
For this to work, you'd need very specific knowledge of how stuff gets turned into call-by-name functions; and how to extract the information you want (if it's present at all).