Writing specs for Atom editor - coffeescript

I'm trying to write a simple package for Atom.io editor. This is my first experience with Coffeescript.
So I'm probably missing something trivial.
Anyway, this is my index.coffee
module.exports =
activate: ->
atom.workspaceView.command "md-utils:unorderedList", => #unorderedList()
unorderedList: ->
out = ""
editor = atom.workspace.activePaneItem
selection = editor.getSelection()
lines = selection.getText().split "\n"
for line in lines
out += "- " + line + "\n"
console.log(lines)
selection.insertText(out)
And here it is my index-spec.coffee
{WorkspaceView} = require 'atom'
describe "Markdown Utilities", ->
[editor, editorView] = []
unorderedList = (callback) ->
editorView.trigger "md-utils:unorderedList"
runs(callback)
beforeEach ->
atom.workspaceView = new WorkspaceView
atom.workspaceView.openSync()
editorView = atom.workspaceView.getActiveView()
editor = editorView.getEditor()
describe "when text is selected", ->
it "formats it correctly", ->
console.log = jasmine.createSpy("log")
editor.setText """
a
b
c
d
"""
editor.selectAll()
unorderedList ->
expect(console.log).toHaveBeenCalled()
expect(editor.getText()).toBe """
- a
- b
- c
- d
"""
Now, when I run the spec looks like the method in the index.coffee is not even called.
Both expectations failed :
Expected spy log to have been called.
Expected 'a b c d' to be '-a -b -c -d"
The method in itself works , so I do not understand why test fails.
Any suggestion is much appreciated

Actually your specs lack of a package activation, which is generally done with something like this:
beforeEach ->
atom.workspaceView = new WorkspaceView
atom.workspaceView.openSync()
editorView = atom.workspaceView.getActiveView()
editor = editorView.getEditor()
# Package activation is done within a promise so this will wait for the end of it
# before actually running the tests.
waitsForPromise -> atom.packages.activatePackage('your-package-name')
As your package is never activated, the command you define in the activate method is never registered, so the event triggered in your unorderedList helper never reach it.

Related

Blank windows with documentation examples of Gtk(0.17) (julia 1.1)

I got an issue with Gtk.
My code is compiling with no error, but only the windows with its title is appearing.
So I wondered if I made something wrong and tried some examples of the documentation (see below).
And it didn't worked either.
I updated the packages, rm, and add again, no error.
No error in compiling, nothing.
When I ask if the widgets are visible it is saying yes.
I saw that it could be a configuration problem of gtk but with no more explanation.
Thank you for your help !
using Gtk
ls = GtkListStore(String, Int, Bool, Bool)
push!(ls,("Peter",20,false,true))
push!(ls,("Paul",30,false,true))
push!(ls,("Mary",25,true,true))
insert!(ls, 2, ("Susanne",35,true,true))
rTxt = GtkCellRendererText()
rTog = GtkCellRendererToggle()
c1 = GtkTreeViewColumn("Name", rTxt, Dict([("text",0)]), sort_column_id=0)
c2 = GtkTreeViewColumn("Age", rTxt, Dict([("text",1)]), sort_column_id=1)
c3 = GtkTreeViewColumn("Female", rTog, Dict([("active",2)]), sort_column_id=2)
tmFiltered = GtkTreeModelFilter(ls)
GAccessor.visible_column(tmFiltered,3)
tv = GtkTreeView(GtkTreeModel(tmFiltered))
push!(tv, c1, c2, c3)
selection = GAccessor.selection(tv)
signal_connect(selection, "changed") do widget
if hasselection(selection)
currentIt = selected(selection)
println("Name: ", GtkTreeModel(tmFiltered)[currentIt,1],
" Age: ", GtkTreeModel(tmFiltered)[currentIt,1])
end
end
ent = GtkEntry()
signal_connect(ent, "changed") do widget
searchText = get_gtk_property(ent, :text, String)
for l=1:length(ls)
showMe = true
if length(searchText) > 0
showMe = showMe && occursin(lowercase(searchText), lowercase(ls[l,1]))
end
ls[l,4] = showMe
end
end
vbox = GtkBox(:v)
push!(vbox,ent,tv)
win = GtkWindow(vbox, "List View with Filter")
showall(win)
I tried it, but run as a file, your app closes so fast you do not see it display at all. This is covered in the Gtk.jl docs under "Non REPL Usage" ie running as a file, outside the julia REPL command line. Just replace showall(win) with:
condition = Condition()
endit(w) = notify(condition)
signal_connect(endit, win, :destroy)
showall(win)
wait(condition)
The app will then pass control to the internal Gtk runtime event loop and wait for the app to close. I was able to run your app and see the check boxes fine with this. If you cannot, you might have a problem with your local files.

dbutils.notebook.run not working for mapping arguments

Suppose I have 2 notebooks of which the first is the main and the second is for testing.
In the main, I have the following
dbutils.notebook.run("testing", timeoutSeconds = 60, arguments = Map("var" -> "1234"))
In testing:
%scala
println(s"Donut price = $var")
And in Main run the notebook. There is error:
You can pass arguments to DataImportNotebook and run different notebooks (DataCleaningNotebook or ErrorHandlingNotebook) based on the result from DataImportNotebook.
val status = dbutils.notebook.run("DataImportNotebook", timeoutSeconds
= 60, argumenrs = Map ("x" -> "1234"))
println("Status: " + status)
In scala, the variables are declared as follows:
The following are examples of value definitions:
var $price = 1234
println("Donut price:" + $price)
For more details, refer "Scala - How to declare variables" and "Databricks - Notebook workflows".
Hope this helps.

error: unexpected if for unknown reasons

I don't have a clue why this happens, but here is code of the file:
express = require "express"
fs = require "fs"
router = express.Router()
module.exports = (config) ->
fileRe = /^([a-zA-Z0-9-_]+)(\.(png|jpg|jpeg))?$/i
router.get '/:file', (req, res) ->
file = req.params.file
if !file or !fileRe.test file
return res.error(404).send "404 Not Found"
fileInfo = fileRe.exec file
if !fileInfo[3]
# .png is default if extension is ommited
# abc => abc.png, but abc.jpg will stay
file += ".png"
if fs.access config.destination + file, fs.F_OK, (err) ->
if err
res.status(500).send "An error occured"
else
if !fileInfo[3] or fileInfo[3] == "png"
ct = "image/png"
else if fileInfo[3] == "jpg"
ct = "image/jpg"
opts =
lastModified: false
headers:
"Content-Disposition": "inline; filename=\"#{file}\""
"Content-Type": ""
return router
I get the following error
/home/kindlyfire/Webroot/uplimg-server/src/web/view.coffee:24:9: error: unexpected if
if fs.access config.destination + file, fs.F_OK, (err) ->
^^
I looked at the spaces, no problem there. Has anybody an idea about what it might be ?
What you wrote is not valid coffeescript. Specifically, it is the commas on the line the error is pointing you to. I'd offer info on how to fix it, but I can't even tell what you were trying to accomplish here. You have to provide a way for the compiler (not to mention readers) to be able to tell, unambiguously, what divisions you want in your code:
# fine
if foo then (a, b) -> c
# also fine
if foo
(a, b) ->
c
# ??
if foo (a, b) -> c
# ????
if foo a, b -> c
Repro of the bug. Note that this is a good example of how to make a minimum reproduction of the problem. I highly, highly recommend you read a coffeescript style guide and discipline yourself to follow it. Which one is not terribly important, its the consistency that matters. Do not just randomly copy-paste stuff from the internets into your code, re-write it to follow the same style as the rest of your code. Doing so will often have the added benefit of realizing how the snippet you copied is working.

How to enable Tracing in F# interactive

I'd like to view the output of a library that I use.
It prints intermediate info with a simple Trace, and for my experiments I use F# Interactive.
What I've tried:
Console.Out.WriteLine("Hello") // prints "Hello" :)
type MyListener() =
inherit TraceListener()
override u.Write (msg : string) = printf "Trace: %s" msg
override u.WriteLine (msg : string) = printfn "Trace: %s" msg
Trace.Listeners.Add(new TextWriterTraceListener(Console.Out)) // prints "val it : int = 1"
Trace.Listeners.Add(new MyListener()) // prints "val it : int = 2"
Trace.AutoFlush <- true // prints "val it : unit = ()"
Trace.TraceInformation("test") // prints "val it : unit = ()".
Nothing 'test'-related is produced with the last line.
Apparently, I need to enable a debugging flag or set a property.
How do I Trace?
I found out about this when trying to debug a library I was planning to use in Azure, where tracing is among the more useful logging options.
In VS2013 you can set the flags that get passed to the FSI in Tools -> Options -> F# Tools -> F# interactive. This allows me to read the trace output in the fsi window.
I have set mine to read:
--optimize- --readline+ --debug+ -d:TRACE

Coffeescript running a second function before the first has finished executing

My code is as follows. I would expect the code inside configureMission() to finish running before running mapSurface. This does not appear to be happening.
missionCommands = "" # you don't have a mission yet
$('#startExploration').click -> # Set #missionControl as input for game configuration
configureMission()
mapSurface()
configureMission =->
$('#MissionControl').on "submit", ->
# cool helper function shamelessly pinched from http://jsfiddle.net/sxGtM/3/
$.fn.serializeObject = function() # not shown
missionCommands = JSON.stringify($('form').serializeObject())
return false #stops click event from firing
mapSurface =->
console.log('map')
console.log(missionCommands)
I have noticed that if I submit the form a second time, the missionCommands variable has been updated with the json data, so it appears that the form data has been processed, but that this is happening after the second function has run.
map login.js:60
login.js:61
map login.js:60
{"xMaximum":"","yMaximum":"","xCoord":["iuoiuyi",""],"yCoord":["",""],"orientaiton":["",""]} login.js:61
I can make it work by moving the mapSurface function inside the configureMission function, but this seems like bad form. I wonder, is there a more correct pattern I could use to achieve my desired result of processing the form data into json, setting this into a variable and passing the variable to a second function.
You're treating asynchronous commands as synchronous commands. JavaScript (and thereby CoffeeScript) works asynchronously, meaning that functions will be run in parallel.
You can solve this problem by specifying mapSurface() as the callback for configureMission() as follows:
missionCommands = ""
$('#startExploration').click ->
configureMission(mapSurface)
configureMission = (cb) ->
console.log "now running configureMission()"
$('#MissionControl').on "submit", ->
$.fn.serializeObject = function() # not shown
missionCommands = JSON.stringify($('form').serializeObject())
console.log "completed configureMission()"
return cb()
mapSurface = ->
console.log "now running mapSurface()"
console.log missionCommands
console.log "completed mapSurface()"
Learn about JavaScript callbacks here: http://recurial.com/programming/understanding-callback-functions-in-javascript/.