What is the definition of a 'helper' in CodeMirror registerHelper method - codemirror

I am looking at CodeMirror help and registerHelper is described as
CodeMirror.registerHelper(type: string, name: string, value: helper)
Registers a helper value with the given name in the given namespace
(type). This is used to define functionality that may be looked up by
mode. ...
http://codemirror.net/doc/manual.html#registerHelper
This does not explain what the value is, when is it called (it seems to be a function), or why getHelpers accepts a position.
Is helper similar to a mode, but providing non-visual annotations (for code lookups)?

It's just a value -- any value. How it will be used depends on the type of helper. For "hint", it'll be a function providing completions at a given point in a document, for "hintWords", it'll be an array of strings that form possible completions, for "wordChars", it is a regular expression describing the characters that count as word characters for a mode, and so on.

Related

Question mark Typescript variable

I've seen code snippets like these:
export interface IUser {
email?: string;
firstName?: string;
lastName?: string;
}
But why are the variable names suffixed by a question mark? This snippet is part of an example of using mongodb with Typescript.
The answer is probably somewhere out there but I seem to be using the wrong keywords since I can't find it.
In TypeScript, <name>?: <typename> a shorthand for <name>: <typename> | undefined.
This indicates to the type system that a symbol may contain a value of the indicated type or it may contain the value undefined (which is like null).
This is important when the (new in TypeScript 2) --strictNullChecks option is enabled. The documentation on Null- and undefined-aware types option is probably where you should start to understand why this is useful.
It means they can be there but dont have to be. It allows for optional field names. It can be quite common to use.
An example use is allowing users on a website to have an optional display name.
If I am not mistaked, its to indicate that its optional, that means that it can be null.

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.

Using module annotations as method attributes

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.

Use Freemarker macro call within string parameter of another macro

I have a macro A that formats some text
<#macro A text>...${text}...</#macro>
and another macro that has a parameter accepting text
<#macro B x>Another ${x} text</#macro>
I'd like to call B with the x paramter to be some text formatted by A, s.th. like
<#B x="<#A text='abc'/>" /> returns Another <#A text='abc'/>
Is this possible somehow?
I tried the ?interpret as suggested here by ddekany -
<#B x="<#A text='abc'/>"?interpret /> but this fails with the error:
Expecting a string, date or number here, Expression .... is
instead a freemarker.core.Interpret$TemplateProcessorModel
It seems that a macro call in FreeMarker is something different than a function call in other languages.
Macro calls aren't expressions, and hence can't be used inside expression (like a parameter value). Macros are called for their side effects, which is typically printing to the output, and have no return value. Functions (see #function) are called for their return values, and so function calls are expressions. So maybe you need functions, not a macros in this case.
But if you absolutely have to use the output of a macro call in an expression (or of any arbitrary template fragment), then you have to capture the output via <#assign someVar>...</#assign> or <#local someVar>...</#local>. (Beware with #escape. If you re-print the captured output with ${...}, it will be escaped again, so you will need #noescape.)
I found a workaround using assign:
<#assign a><#A text="abc"/></#assign>
<#B text=a/>
Anyway, it would be interesting to know if this is possible somehow.

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).