CoffeeScript not passing variable - coffeescript

Folks,
Trying to figure out the difference between these 2 statements, and why one works, and the other throws an error:
works:
jsonFileContents = fs.readFileSync('sample.json', 'utf8')
res.send(jsonFileContents)
does not:
jsonFileContents = fs.readFileSync('sample.json', 'utf8')
returnResult(jsonFileContents)
returnResult = (data) ->
res.send data
error thrown:
`TypeError: undefined is not a function`

It's because returnResult is not defined upon usage.
The following should work:
returnResult = (data) ->
res.send data
jsonFileContents = fs.readFileSync('sample.json', 'utf8')
returnResult(jsonFileContents)

Related

Can not call procedure by JPA - could not determine data type of parameter

When trying to call procedure with timestamp parameters by the code:
SimpleJdbcCall simpleJdbcCall = new SimpleJdbcCall(dataSource)
.withSchemaName("time_series")
.withProcedureName("refresh_continuous_aggregate")
.declareParameters(new SqlParameter("continuous_aggregate", Types.VARCHAR),
new SqlParameter("window_start", Types.TIMESTAMP),
new SqlParameter("window_end", Types.TIMESTAMP));
MapSqlParameterSource inParams = new MapSqlParameterSource()
.addValue("continuous_aggregate", "time_series.current_data_hourly", Types.VARCHAR)
.addValue("window_start", "2020-11-12 01:02:03.123456789", Types.TIMESTAMP)
.addValue("window_end", "2021-02-12 01:02:03.123456789", Types.TIMESTAMP);
Map<String, Object> execute = simpleJdbcCall.execute(inParams);
I'm getting error:
ERROR o.s.i.handler.LoggingHandler ->
org.springframework.jdbc.BadSqlGrammarException:
CallableStatementCallback; bad SQL grammar [{call
time_series.refresh_continuous_aggregate(?, ?, ?)}]; nested exception
is org.postgresql.util.PSQLException: ERROR: could not determine data
type of parameter $2
The similar error I'm getting when I try to use native query with dynamic parameters:
String queryStr = "CALL time_series.refresh_continuous_aggregate(?1, ?2, ?3)";
Query query = entityManager.createNativeQuery(queryStr)
.setParameter(1, continuousAggregate)
.setParameter(2, windowStart, TemporalType.TIMESTAMP)
.setParameter(3, windowEnd, TemporalType.TIMESTAMP);
Object singleResult = query.getSingleResult();
ERROR o.h.e.jdbc.spi.SqlExceptionHelper -> ERROR: syntax error at or
near "$2"
And by using StoredProcedureQuery:
StoredProcedureQuery query = entityManager.createStoredProcedureQuery("time_series.refresh_continuous_aggregate")
.registerStoredProcedureParameter("continuous_aggregate", String.class, ParameterMode.IN)
.registerStoredProcedureParameter("window_start", Date.class, ParameterMode.IN)
.registerStoredProcedureParameter("window_end", Date.class, ParameterMode.IN)
.setParameter("continuous_aggregate", "time_series.current_data_hourly")
.setParameter("window_start", new Date(), TemporalType.TIMESTAMP)
.setParameter("window_end", new Date(), TemporalType.TIMESTAMP);
query.execute();
WARN o.h.e.jdbc.spi.SqlExceptionHelper -> SQL Error: 0, SQLState:
42P18 ERROR o.h.e.jdbc.spi.SqlExceptionHelper -> ERROR: could not
determine data type of parameter $2
It looks like JDBC drivers issue.

The SOAP function called with localhost, works, when I call with external IP and port, returns Forbidden error

Function called:
public function getAcces($plngVersiune, $pstrNumeFirma, $pstrUtilizator, $pstrParolaSecurizata, $wsdl)
{
$this->plngVersiune = $plngVersiune;
$this->pstrNumeFirma = $pstrNumeFirma;
$this->pstrUtilizator = $pstrUtilizator;
$this->pstrParolaSecurizata = $pstrParolaSecurizata;
$this->wsdl = $wsdl;
$xml_array = array();
$xml_array['plngVersiune'] = $this->plngVersiune;
$xml_array['pstrNumeFirma'] = $this->pstrNumeFirma;
$xml_array['pstrUtilizator'] = $this->pstrUtilizator;
$xml_array['pstrParolaSecurizata'] = $this->pstrParolaSecurizata;
$client = new SoapClient($wsdl); // , array('trace' => $trace, 'exceptions' => $exceptions)
var_dump($client);
$clientToken = $client->LogIn($xml_array)->LogInResult;
var_dump($clientToken);
//unset($xml_array);
return $clientToken;
}
Line called:
$acces = $gru->getAcces(1,"ALM","Administrator","d41d8cd98f00b204e9800998ecf8427e", "http://82.108.151.XXX:8080/InterfacesWS/IInterfacesBO3.asmx?WSDL");
Returns Errors:
Fatal error: Uncaught SoapFault exception: [HTTP] Forbidden in C:\Program Files (x86)\Ampps\www\soap\class_01.php
SoapFault: Forbidden in C:\Program Files (x86)\Ampps\www\soap\class_01.php
Instead, if I call the same function with "http: //localhost/InterfacesWS/IInterfacesBO3.asmx? WSDL" I have no error. It works correctly.
How do I eliminate the SoapFault: Forbidden error?

creating custom components and running with NoFlo

I am creating a custom component which interfaces with MongoDB. I wrote a CoffeeScript file which just connects to MongoDB, and stored it at noflo/components folder.
MongoBase.coffee
noflo = require "noflo"
mongodb = require "mongodb"
url = require "url"
class exports.MongoBase extends noflo.Component
constructor: ->
super
#inPorts =
url: new noflo.Port()
#inPorts.url.on "data", (data) =>
try
#parseConnectionString(data)
#MongoClient = mongodb.MongoClient;
#MongoClient.connect #serverUrl, (err, db) ->
if err
console.log("Error in connecting to MongoDB")
else
console.log("Connected to MongoDB")
catch error
console.log(error)
parseConnectionString: (connectionString) =>
databaseUrl = try
url.parse(connectionString)
catch error
console.log(error)
[..., #serverUrl, #databaseName] = databaseUrl.split('/')
#serverUrl = "mongo://" + #serverUrl
I added the following entry to component.json
"MongoBase": "components/MongoBase.coffee"
In addition to this, I created a mongo.fbp file to check the flow of the component. The FBP file has the following code:
'mongodb://localhost:27017/test' -> url DocReader(MongoBase)
On running noflo mongo.fbp, I get the following error:
/home/saurabh/workspace/noflo/node_modules/fbp/lib/fbp.js:1628
edges.forEach(function (o, i) {
^
TypeError: Object #<Object> has no method 'forEach'
at Object.parser.registerEdges (/home/saurabh/workspace/noflo/node_modules/fbp/lib/fbp.js:1628:15)
at peg$c25 (/home/saurabh/workspace/noflo/node_modules/fbp/lib/fbp.js:60:50)
at peg$parseline (/home/saurabh/workspace/noflo/node_modules/fbp/lib/fbp.js:749:30)
at peg$parsestart (/home/saurabh/workspace/noflo/node_modules/fbp/lib/fbp.js:282:12)
at Object.parse (/home/saurabh/workspace/noflo/node_modules/fbp/lib/fbp.js:1650:18)
at Object.exports.loadFBP (/home/saurabh/workspace/noflo/lib/Graph.js:1065:33)
at /home/saurabh/workspace/noflo/lib/Graph.js:1116:24
at fs.js:268:14
at Object.oncomplete (fs.js:107:15)
Is there something wrong with my code, or the steps I am using to run the code?
You may have figured this out already, as it's been several month's since you asked, but I believe you need to add the getComponent() method to your class before you export it.
noflo = require "noflo"
mongodb = require "mongodb"
url = require "url"
class MongoBase extends noflo.Component
constructor: ->
super
#inPorts =
url: new noflo.Port()
#inPorts.url.on "data", (data) =>
try
#parseConnectionString(data)
#MongoClient = mongodb.MongoClient;
#MongoClient.connect #serverUrl, (err, db) ->
if err
console.log("Error in connecting to MongoDB")
else
console.log("Connected to MongoDB")
catch error
console.log(error)
parseConnectionString: (connectionString) =>
databaseUrl = try
url.parse(connectionString)
catch error
console.log(error)
[..., #serverUrl, #databaseName] = databaseUrl.split('/')
#serverUrl = "mongo://" + #serverUrl
MongoBase.getComponent = -> new MongoBase
exports.MongoBase = MongoBase
Additionally, in your graph for the component loader to work you need to specify the package your component lives in. If your package.json/component.json have a name entry like "name": "mongo-base" then you'd have to specify this in the FBP graph, like so:
'mongodb://localhost:27017/test' -> url DocReader(mongo-base/MongoBase)
N.B.: The loader clobbers any instances of 'noflo-' in the package name, so this needs to be taken into account. E.g. the name 'noflo-mongo' would get turned into just 'mongo', so when invoking the package's components you'd write in the fbp DocReader(mongo/MongoBase) and not DocReader(noflo-mongo/MongoBase).

BusterJs test in CoffeeScript

I've the follwoing test. For some reason the #$e I've set in the before function is undefined in the test:
assert = buster.assert
buster.testCase 'BaseChart',
before: ->
#el = sinon.spy()
#$el = [#el]
console.log(#$el)
##[LOG] [function spy() {}]
'updates when the model changed': ->
console.log(#$el)
##[LOG] undefined
This is a wild guess but change:
before: -> to before: =>
And see if that helps.

How to test a Controller which relies on an ngResource Service

I have a controller which relies on a service built through ngResource. I am having trouble testing this(although both appear to work like a charm in the actual application). The following is the (sanitized) Controller
MyApp.Controller.MyCarsController = (scope, http, typeService) ->
if scope.context==undefined
scope.ferrari_or_porshe =""
scope.id = ""
else if scope.context=="ferrari"
scope.country_or_pi ="Ferrari"
else if scope.context=="porshe"
scope.country_or_pi ="Porshe"
typeService.index
ferrari_or_porshe: scope.ferrari_or_porshe
id: scope.id
, (response) ->
scope.type = response
scope.loading = false
MyApp.Controller.MyCarsController.$inject = ['$scope', '$http', 'Type']
And this is the Service:
MyApp.MyModule.factory 'Type', ['$resource', ($resource) ->
TypeResource = $resource("/api/types/:ferrari_or_porshe/:id", {},
index:
method: "GET"
isArray: true
)
return TypeResource
]
Finally, some test code:
describe 'MyApp.Controller.MyCarsController', ->
beforeEach module('MyModule')
beforeEach inject ($rootScope, $http, $controller, Type) ->
#scope = $rootScope.$new()
#typeService = Type
#scope.context = undefined
$controller 'MyApp.Controller.MyCarsController', $scope: #scope
describe '#home-page', ->
it 'contains a list of types', ->
expect(#scope.types.length).toBeGreaterThan 0
it "sets instance variables correctly", ->
expect(#scope.ferrari_or_porshe).toBe ""
expect(#scope.id).toBe ""
Which fails with:
No more request expected in helpers/angular-mocks.js on line 889
TypeError: 'undefined' is not an object (evaluating 'this.scope.types.length') in controllers/my_cars_controller_spec.js
By judicious application of console.logs, I have discovered that the issue is that the final callback on response is never reached. TypeResource comes back as [Function].
My questions is:
How do I drive the Jasmine Tests to correctly enter the Service and fetch a response? And is there any way to create direct Unit Tests for Services?
Any and all help is appreciated
The Solution is as follows: for the Service, use $httpBackend which is bundled as part of ngMock:
http://code.google.com/p/google-drive-sdk-samples/source/browse/ruby/app/lib/angular-1.0.0/angular-mocks-1.0.0.js?r=c43c943e32be395b7abca8150deb301d3cbc0dbe
Use this to mock the Rest responses. Since in my case I only cared about verifying that a GET request goes out:
describe 'Type', ->
describe '#index', ->
beforeEach module('MyModule')
beforeEach inject(($httpBackend) ->
$httpBackend.whenGET('/api/types/ferrari/1').respond([])
)
it 'for a ferrari scope', inject((Type) ->
ferrari_or_porsche = 'ferrari'
id = '1'
expect( Type.index('ferrari_or_porsche': ferrari_or_porsche, 'id': id) ).toEqual([ ])
)
And then for the controller, mock the service using jasmine spies and use jasmine.any(Function) to warn of the callback.
describe 'MyApp.Controller.MyCarsController', ->
beforeEach module('myModule')
beforeEach inject ($rootScope, $http, $controller, Type) ->
#scope = $rootScope.$new()
#typeService = Type
#scope.context = undefined
spyOn(#typeService, 'index')
describe '#home-page', ->
beforeEach inject ($controller) ->
$controller 'MyApp.Controller.MyCarsController', $scope: #scope
it 'contains a list of types', ->
expect(#typeService.index).toHaveBeenCalledWith({ ferrari_or_porsche : '', id : '' }, jasmine.any(Function))
it "sets instance variables correctly", ->
expect(#scope.ferrari_or_porsche).toBe ""
expect(#scope.id).toBe ""
Note: I make no claims as to the "canonicalness" of this solution. But it works.
Note: The API endpoints are of course tested extensively elsewhere.