Coffeescript running a second function before the first has finished executing - coffeescript

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

Related

Is there an Operation to block onComplete?

I am trying to learn reactive programming, so forgive me if I ask a silly question. I'm also open to advice on changing my design.
I am working in scala-swing to display the results of a simulator. With one setting, a chart is displayed as a histogram; with the other setting the chart is displayed as the cumulative sum. (I'm probably using the wrong word; in the first setting you might have bin1=2, bin2=5, bin3=3; in the second setting the first height is 2, the second is 2 + 5, the third is 2 + 5 + 3, etc.). The simulator can be slow, so I originally used a Future to compute it, and the set the data into the chart. I decided to try a reactive approach, so my requirements are: 1. I don't want to recreate the data when I change the display mode, and 2. I want to set the Observable once for the chart and have the chart listen to the same Observable permanently.
I got this to work when I started the chain with a PublishSubject and the Future set the data into the start of the chain. When the display mode changed, I created a new PublishSubject().map(newRenderingLogic).subscribe(theChartsObservable). I am now trying to do what looks like the "right way," but it's not working correctly. I've tried to simplify what I have done:
val textObservable: Subject[String] = PublishSubject()
textObservable.subscribe(text => {
println(s"Text: ${text}")
})
var textSubscription: Option[Subscription] = None
val start = Observable.from(Future {
"Base text"
}).cache
var i = 0
val button = new Button() {
text = "Click"
reactions += {
case event => {
i += 1
if (textSubscription.isDefined) {
textSubscription.get.unsubscribe()
}
textSubscription = Some(start.map(((j: Int) => { (base: String) => s"${base} ${j}" })(i)).subscribe(textObservable))
}
}
}
On start, an Observable is created and logic to print some text is added to it. Then, an Observable with the generated data is created and a cache is added so that the result is replayed if the next subscription comes in after its results are generated. Then, a button is created. Then on button clicks a middle observable is chained with unique logic (it's a function that creates a function to append the value of i into the string, run with the current value of i; I tried to make something that couldn't just be reused) that is supposed to change with each click. Then the first Observable is subscribed to it so that the results of the whole chain end up being printed.
In theory, the cache operation takes care of not regenerating the data, and this works once, but onComplete is called on textObservable and then it can't be used again. It works if I subscribe it like this:
textSubscription = Some(start.map(((j: Int) => { (base: String) => s"${base} ${j}" })(i)).subscribe(text => textObservable.onNext(text)))
because the call to onComplete is intercepted, but this looks wrong and I wanted to know if there was a more typical way to do this, or architect it. It makes me think that I don't understand how this is supposed to be done if there isn't an out-of-the-box operation to do this.
Thank you.
I'm not 100% sure if I got the essence of your question right, but: if you have an Observable that may complete and you want to turn it into an Observable that never completes, you can just concatenate it with Observable.never.
For example:
// will complete after emitting those three elements:
val completes = Observable.from(List(1, 2, 3))
// will emit those three elements, but will never complete:
val wontComplete = completes ++ Observable.never

My google sheets function does the job when run from editor but gives different outcome when trigered by Form submit

I have a google form and a sheet that collects the responses which of course always appear at the bottom. I have been using the following script to copy the last response (which is always on the last row) from the Response sheet (Form Responses 2) to row two of another sheet (All Responses). When run by a trigger on Form Submit the script inserts a blank row into All Responses, then the copied values into another row above the blank row. Please can you help and tell me why and how I might change the script so the blank row is not added:
function CopyLastrowformresponse () {
var ss = SpreadsheetApp.getActive();
var AR = ss.getSheetByName("All Responses");
var FR = ss.getSheetByName("Form responses 2");
var FRlastrow = FR.getLastRow();
AR.insertRowBefore(2);
FR.getRange(FRlastrow, 1, FRlastrow, 22).copyTo(AR.getRange("A2"), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
}
A few things could be going on here.
You're getting a number of rows equal to FRlastrow, when I think you only want to be getting 1 row.
Apps Script has buggy behavior with onFormSubmit() triggers, so you may to check duplicate triggers (see this answer).
The script isn't fully exploiting the event object provided by onFormSubmit(). Specifically, rather than getting the last row from one sheet, you could use e.values, which is the same data.
I would change the script to be something like this:
function CopyLastrowformresponse (e) {
if (e.values && e.values[1] != "") { // assuming e.values[1] (the first question) is required
SpreadsheetApp.getActive()
.getSheetByName("All Responses")
.insertRowBefore(2)
.getRange(2, 1, 1, e.values.length)
.setValues([e.values]);
}
}
But, ultimately, if all you want to do is simply reverse the order of the results, then I'd ditch Apps Script altogether and just use the =SORT() function.
=SORT('Form responses 2'!A:V, 'Form responses 2'!A:A, FALSE)

Can't get CoffeeScript to recognize a function in a js file

I am writing a simple app in Coffeescript to control a Philips Hue light. I have included this module into my project. The below code seems to work fine up until I try to set the color of the lights using setLightState. The compiler says the function isn't a function. I don't quite understand why it doesn't recognize the function.
# Connect with Philips Hue bridge
jsHue = require 'jshue'
hue = jsHue()
# Get the IP address of any bridges on the network
hueBridgeIPAddress = hue.discover().then((bridges) =>
if bridges.length is 0
console.log 'No bridges found. :('
else
(b.internalipaddress for b in bridges)
).catch((e) => console.log 'Error finding bridges', e)
if hueBridgeIPAddress.length isnt 0 # if there is at least 1 bridge
bridge = hue.bridge(hueBridgeIPAddress[0]) #get the first bridge in the list
# Create a user on that bridge (may need to press the reset button on the bridge before starting the tech buck)
user = bridge.createUser('myApp#testdevice').then((data) =>
username = data[0].success.username
console.log 'New username:', username
bridge.user(username)
)
if user?
#assuming a user was sucessfully created set the lighting to white
user.setLightState(1, {on:true, sat:0, bri:100, hue:65280}).then((data) =>
# process response data, do other things
)
As you can see on the github page of the jshue lib, bridge.createUser does not directly return a user object.
Instead the example code sets the user variable inside the then function of the returned promise:
bridge.createUser('myApp#testdevice').then(data => {
// extract bridge-generated username from returned data
var username = data[0].success.username;
// instantiate user object with username
var user = bridge.user(username);
user.setLightState( .... )
});
It can be expected that - using this approach - the user variable will be set correctly and user.setLightState will be defined.
A self-contained example:
Take this Codepen for example:
url = "https://api.ipify.org?format=json"
outside = axios.get(url).then (response) =>
inside = response.data.ip
console.log "inside: #{inside}"
inside
console.log "outside: #{outside}"
The console output is
outside: [object Promise]
inside: 178.19.212.102
You can see that:
the outside log is first and is a Promise object
the inside log comes last and contains the actual object from the Ajax call (in this case your IP)
the then function implicitly returning inside does not change anything

Protractor- ElementFinder returning unexpected values

I am writing a protractor test case to compare the name(s) of the displayed data is same as the searched name.
Even though my test case works fine, I am not able to understand what is happening. Because when i expect the name to compare, it compares as expected, but when i print the elementFinder's(rowData)(i have attached the output screen shot here) value in console.log, it show a huge list of some values which i am not able to understand?
PS: I am a newbie to protractor`
This is the testCase:
it('should show proper data for given last name', function () {
var searchValue='manning';
searchBox.sendKeys(searchValue);
search.click();
element.all(by.binding('row.loanNumber')).count().then(function(value) {
var loanCount = value;
for (var i = 0; i < loanCount; i++) {
var rowData = element.all(by.binding('row.borrowerName')).get(i).getText();
expect(rowData).toMatch(searchValue.toUpperCase());
console.log(rowData,'*****',searchValue.toUpperCase());
}
});
});`
And give me valuable suggestions about my style of code
rowData is a promise (not a value), so when you console.log it, you get the promise object
Protractor patches Jasmine to automatically resolve promises within the expect(), so that's how it knows to resolve the value and compare to the expected result.
If you want to console.log the value, you need to resolve the promise with .then() to get the value.
rowData.then(function(rowDataText) {
console.log(rowDataText);
)}
This is pretty much everyone's first question when they start using protractor. You will want to learn how promises work if you want a good understanding of how to manipulate them.

How to display content of an ArrayController inside a CollectionView

I am trying to understand how Ember.CollectionView works and I am having a basic issue with displaying the content of my ArrayController in the DOM. Here is my little jsfiddle experiment so you can see for yourself. Here is the coffeescript:
window.App = Ember.Application.create()
window.App.initialize()
App.Item = Em.View.create
tagName:'li'
willInsertElement: () ->
console.log "I **WILL** indert the element", this.$()
didInsertElement: () ->
console.log "I **DID** insert the element", this.$()
template: Ember.Handlebars.compile("~~ {{view.content.title}} ~~")
App.items = Em.ArrayController.create()
App.items.set('content',[
Em.Object.create({title:"AN"}),
Em.Object.create({title:"Epic"}),
Em.Object.create({title:"View"})
])
App.epicView = Ember.CollectionView.create
classNames: ['epic-view']
contentBinding: 'App.items'
itemViewClass: 'App.Item'
App.epicView.appendTo('body')
As you can see in the output of that fiddle, I have not been able to figure out how to access and display the title of objects in the list. When I append the view to body using the call to App.epicView.appendTo('body') it seems to iterate over the three objects but does not print anything.
Any ideas what am I missing here?
ps: I am using Ember 1.0pre
I would simply do something like this: http://jsfiddle.net/Sly7/nevW2/67/
Declare your views (with extend) instead of instantiate them (with create)