Better CoffeeScript syntax for jQuery parameters - coffeescript

I have this code for making a post request, sending some data, and logging the return value
$.post '/saveletter', {start: {x: startX, y:startY}, letter: currentLetter, unitVectors: letter.unitVectorsJson(), timeVectors: letter.timeVectorsJson()}, (data) =>
console.log data
I want to split the long parameter object into several lines, for better readability, but can't figure out the syntax that will work.

To make your code more readable, you can use the following (fiddle and compiled result):
$.post '/saveletter',
    start:
        x: startX
        y: startY
    letter: currentLetter
    unitVectors: letter.unitVectorsJson()
    timeVectors: letter.timeVectorsJson()
, (data) =>
  console.log data​​
In Coffeescript, { and } may be omitted from the object literal. And commas may be exchanged for newlines (within an object literal, not between arguments).
The following is also valid, but might be less readable (ie not obvious at the first glance):
start: x: startX, y: startY

Related

Get expression value from drools

I want to get expression value from drools.The drl like this.
global java.util.Map $globalVar;
global java.lang.Object $result;
import java.util.Map;
function myFunc(Map map){
return "hello";
}
rule "onlyone"
when
$factMap: Map($tmpResult:(myFunc($globalVar)), eval(true))
then
$result = $tmpResult;
end
When the rule get exception,like this
Caused by: org.mvel2.PropertyAccessException: [unable to resolve method: java.util.Map.$globalVar() [argslength=0]]
The global variable $globarVar has no relation with the fact.
It is likely drools can't recognize the global variable.Is there any grammar error in my drl?
Your syntax is so wrong I can't even figure out what you're trying to do.
Functions are very simple, they're just like methods in Java. They even look like methods in Java -- yours is missing a return type.
function String myFunc(Map map) {
return "hello";
}
function String greeting(String name) {
return "Hello, " + name + ". How are you?"
}
You can invoke them in your rules as you would any other function, either on the left hand side ("when") or on the right hand side ("then").
rule "Apply Greeting and Send Memo"
when
$memo: Memo( $recipient: recipient, sent == false )
$greeting: String() from greeting($recipient)
then
MemoSender.send($greeting, $memo);
modify( $memo ) {
setSent(true)
};
end
rule "Apply Greeting and Send Memo - v2"
when
$memo: Memo( $recipient: recipient, sent == false )
then
String $greeting = greeting($recipient);
MemoSender.send( $greeting, $memo );
modify( $memo ) {
setSent(true)
}
end
The bits with the globals in your question are red herrings. Yes, they're not working and throwing errors, but the syntax is so wrong that I'm not sure how it was supposed to work in the first place.
One way you might interact with a global in a function would possibly be something like ...
global Float taxRate; // passed in as a global because it's an external constant value
global Float freeShippingThreshold;
function float calculateTotal(float subtotal) {
// some math here that references taxRate
return calculatedTotal
}
rule "Apply free shipping"
when
Cart( $subtotal: subtotal )
Float( this >= freeShippingThreshold) from calculateTotal($subtotal)
then
// you get free shipping
end

Is there a name for the phenomenon of lines with only parentheses and other tokens that don't contain meaningful information for the programmer?

so, maybe the most well-known thing in programming where what I'm talking about occurs frequently is callback hell in javascript.
Here's an example:
fs.readdir(source, function (err, files) {
if (err) {
console.log('Error finding files: ' + err)
} else {
files.forEach(function (filename, fileIndex) {
console.log(filename)
gm(source + filename).size(function (err, values) {
if (err) {
console.log('Error identifying file size: ' + err)
} else {
console.log(filename + ' : ' + values)
aspect = (values.width / values.height)
widths.forEach(function (width, widthIndex) {
height = Math.round(width / aspect)
console.log('resizing ' + filename + 'to ' + height + 'x' + height)
this.resize(width, height).write(dest + 'w' + width + '_' + filename, function(err) {
if (err) console.log('Error writing file: ' + err)
})
}.bind(this))
}
})
})
}
})
This is taken from callbackhell.com ...
What I'm talking about occurs in the last five lines: there are only braces and parens there and personally when I read the code those lines are essentially wasted space- they don't help me understand what's going on in this code since the extent of different code blocks is already shown via the indentation.
This kind of thing is at the moment really bugging me when programming in flutter, since there I naturally have deeply nested code when constructing widget trees.
The reason I'm asking is- I was wondering if there are techniques to avoid this kind of thing, both in terms of code styling, in general and/or for specific languages/frameworks, and in terms of tools. In my case the dart formatter by default formats the code to put parens on their own lines like this and I'm not sure I really want to look into configuring it to do something that strongly differs from common practices in that ecosystem, but I thought maybe there could be editor plugins for example that hide those lines by default. If there were a name for this searching for that kind of stuff would be a lot easier I'd wager.

Python - Integration of multiprocessing with classes

I have a problem in Python with the module multiprocessing.
Basically, I'm making a game (with tkinter as graphics)  in which I have a class Game and several classes (entites) that all have an update(self) method.
So it's a bit like:
class Game:
  __init__(self, etc...):
    self.entities = []
  gameloop(self):
     for entity in self.entities:
       entity.update
class EntityExample:
  __init__(self, game, etc...):
    self.game = game
  update(self):
    #stuff
   
And then I do:
game = Game()
game.entities.append(EntityExample())
game.gameloop()
So I tried, to optimize the code, to do a thing like that:
import multiprocessing
class Game:
  __init__(self, etc...):
    self.entities = []
    self.threads = []
    self.lock = multiprocessing.Lock()
  gameloop(self):
     for entity in self.entities:
       entity.update
class EntityExample:
  __init__(self, game, etc...):
    self.game = game
  update(self):
    self.game.lock.acquire()
    #stuff
    self.game.lock.release()
And in gameloop:
for entity in entities:
  t = multiprocessing.Process(target=entity.update)
  t.start()
  t.join
  self.threads.append(t)
The goal was to do the calculations on different cores at the same time to improve performance, but it doesn't work sadly.
I also asks to kill the program in IDLE: "The program is still running. Do you want to kill it?".
Thanks in advance,
Talesseed
P.S. : the classes are not picklable
P.P.S. : I've read that create a new Process copies the code inside the file to a new thread, and that could be a problem because my code is ~1600 lines long.
I found something interesting. Apparently, running it through the console make it work. But I've done some testing and the multithreaded version is in fact slower that the single threaded version. I've no clue :/
EDIT: Nevermind, it works now, my bad.

NSXMLElement walk through

I have an element of a NSXMLDocument (a FCPX exported .fcpxml) which I'd like to walk-through, as opposed to getting the children and then the nested children, etc:
 
    <spine>  
     <clip name="Referee" offset="0s" duration="5s" format="r2" tcFormat="NDF">  
      <video offset="0s" ref="r3" duration="418132800/90000s">  
       <audio lane="-2" offset="0s" ref="r3" srcID="2" duration="3345062400/720000s" role="dialogue" srcCh="1, 2"/>  
       <audio lane="-1" offset="0s" ref="r3" duration="3345062400/720000s" role="dialogue" srcCh="1, 2"/>  
      </video>  
      <spine lane="1" offset="119/25s" format="r1">  
       <clip name="Referee" offset="0s" duration="403200/90000s" start="1300/2500s" format="r2" tcFormat="NDF">  
        <adjust-volume amount="-96dB"/>  
        <video offset="0s" ref="r3" duration="418132800/90000s">  
         <audio lane="-2" offset="0s" ref="r3" srcID="2" duration="3345062400/720000s" role="dialogue" srcCh="1, 2"/>  
         <audio lane="-1" offset="0s" ref="r3" duration="3345062400/720000s" role="dialogue" srcCh="1, 2"/>  
        </video>  
       </clip>  
       <transition name="Cross Dissolve" offset="313200/90000s" duration="1s">  
        <filter-video ref="r4" name="Cross Dissolve">  
         <param name="Look" key="1" value="11 (Video)"/>  
         <param name="Amount" key="2" value="50"/>  
         <param name="Ease" key="50" value="2 (In & Out)"/>  
         <param name="Ease Amount" key="51" value="0"/>  
        </filter-video>  
        <filter-audio ref="r5" name="Audio Crossfade"/>  
       </transition>  
      </spine>  
     </clip>  
     <transition name="Cross Dissolve" offset="4s" duration="1s">  
      <filter-video ref="r4" name="Cross Dissolve">  
       <param name="Look" key="1" value="11 (Video)"/>  
       <param name="Amount" key="2" value="50"/>  
       <param name="Ease" key="50" value="2 (In & Out)"/>  
       <param name="Ease Amount" key="51" value="0"/>  
      </filter-video>  
      <filter-audio ref="r5" name="Audio Crossfade"/>  
     </transition>  
    </spine>  
 
I'm thinking that using NSXMLParser would be the best bet, so I've one up like this:
 
NSXMLParser *new_parser = [[NSXMLParser alloc] initWithData:[NSData dataWithBytes:[[theXMLElement stringValue] UTF8String] length:[theXMLElement stringValue].length]];  
[new_parser setDelegate:self];  
BOOL parse_success = [new_parser parse];
  
 
But it fails as the -stringValue of the element returns a zero-length string (checked with a NSLog output). So how should I setup to parse just the above element (or similar) of a larger NSXMLDocument?
I should have used -XMLString to get a valid string for the parser. I'd seen -stringValue somewhere and it had become stuck in my head.

How do I free() after malloc() when the result of malloc() is returned by the function?

I have the following instance method (adapted from Listing 3-6 of the Event Handling section in the iPhone Application Programming Guide):
- (CGPoint)originOfTouch:(UITouch *)touch
{
CGPoint *touchOriginPoint = (CGPoint *)CFDictionaryGetValue(touchOriginPoints, touch);
if (touchOriginPoint == NULL)
{
touchOriginPoint = (CGPoint *)malloc(sizeof(CGPoint)); // leaks
CFDictionarySetValue(touchOriginPoints, touch, touchOriginPoint);
*touchOriginPoint = [touch locationInView:touch.view];
}
return *touchOriginPoint;
}
Every once in a while my app leaks 16 Bytes as a result of the call to malloc(). I'm not sure how to return touchOriginPoint while free()ing it as well.
If you do not care a minor performance loss, use an NSMutableDictionary and store the point as an NSValue:
NSValue* touchOriginPointValue = [touchOriginPoints objectForKey:touch];
if (touchOriginPointValue == nil) {
touchOriginPointValue = [NSValue valueWithCGPoint:[touch locationInView:touch.view]];
[touchOriginPoints setObject:touchOriginPointValue forKey:touch];
}
return [touchOriginPointValue CGPointValue];
If you must use the CFDictionary approach, you have to find a place to free those malloc-ed memory when the values are not needed. Therefore, you have to pass the values callbacks when creating the dictionary
static void free_malloced_memory (CFAllocatorRef allocator, const void *value) {
free((void*)value);
}
static const CFDictionaryValueCallBacks values_callbacks = {0, NULL, free_malloced_memory, NULL, NULL};
...
touchOriginPoints = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, & values_callbacks);
...
If you must return the malloc'd value from the function, then you have passed the responsibility for freeing the memory to the calling function, or one of its callers.
Since we can't see the calling functions, we can't diagnose any more.
If you are going to be returning an object that is allocated, then either you need to have the caller free() it, or else you need to be using some kind of garbage collection (so it gets freed automatically).
you don't actually return a pointer, the value is copied to a temp value when it is returned, so you aren't really returning the allocation at all, the problem is that you just aren't freeing it either, you add the allocation to the dictionary and just leave it there?
is there like an EndOfTouch function? where you remove the touch from the dictionary? if there is, call free on your allocation there and you should be fine