All thinkscript Stock Fundamentals API returning NaN? - thinkscript

I'm working on a simple label overlay for thinkorswim's charting software using thinkscript.
I'm noticing that all of the "Fundamental" API calls I make return NaN. Those "stock fundamental" API calls are documented here: https://tlc.thinkorswim.com/center/reference/thinkScript/Functions/Stock-Fundamentals
Here's my usage for the API call 'OperatingProfitMargin':
def opm = if IsNaN(OperatingProfitMargin()) then 123 else OperatingProfitMargin();
AddLabel(yes, "Op PM: " + opm, Color.White);
My label is rendered with '123', which suggests to me that the API is returning something that is NaN.
I've been unsuccessful finding example usages of these functions on the official documentation, you tube, or on stack overflow.
I assume I'm misusing the API, in that it's returning some sort of object or tuple with which I should be post-processing/de-structuring in some way.
Has anyone had success using these "Stock Fundamentals" API calls?

Try it this way:
def opm = if IsNaN(OperatingProfitMargin()) then opm[1] else OperatingProfitMargin();
AddLabel(yes, "Op PM: " + opm, Color.WHITE);

Related

Bringing Google search results into Google Sheets using Regex instead of ImportXML

I am tracking keywords for Google search results in Google sheets.
When using importXML it looks like I am getting limited for the amount of XML I can import as I am getting #N/A in cells after a certain amount of use.
I found this custom code by #joshbradley that use of custom scripts to use regex instead of XPath which is meant to get around any limitation. Credit to Josh.
Essentially this goes in the script editor:
function importRegex(url, regexInput) {
var output = '';
var fetchedUrl = UrlFetchApp.fetch(url, {muteHttpExceptions: true});
if (fetchedUrl) {
var html = fetchedUrl.getContentText();
if (html.length && regexInput.length) {
output = html.match(new RegExp(regexInput, 'i'))[1];
}
}
// Grace period to avoid call limit
Utilities.sleep(1000);
return unescapeHTML(output);
}
Then you call the script like this
=importRegex("https://example.com", "<title>(.*)<\/title>")
From here, I am trying to adapt the following code taken from GDS (Credit to Tara) that brings in Google search results but use the custom importregex approach above instead of importxml.
=ARRAYFORMULA(REGEXEXTRACT(IMPORTXML("https://www.google.co.uk/search?q="& SUBSTITUTE(B$1, " ", "+") &"&pws=0&gl=UK&num=50", "//h3[#class='r']/a/#href[contains(.,'url')]"), "\/url\?q=(.+)&sa\b"))
Update
Here are two approaches I have tried (second has the array) but neither are working.
=importRegex("https://www.google.co.uk/search?q="& SUBSTITUTE(B$1, " ", "+") &"&pws=0&gl=UK&num=50", "//h3[#class='r']/a/#href[contains(.,'url')]"), "\/url\?q=(.+)&sa\b"))
=ARRAYFORMULA(REGEXEXTRACT(importRegex("https://www.google.co.uk/search?q="& SUBSTITUTE(B$1, " ", "+") &"&pws=0&gl=UK&num=50", "//h3[#class='r']/a/#href[contains(.,'url')]"), "\/url\?q=(.+)&sa\b"))
If it helps I have put a link to a Google sheet with the importregex script working here

PagedResultList Instance in Grails 3.1.7 Unit Test

Is it possible to create PagedResultList instance or Mock?
For Background: Currently I´m writing Controller Unit tests. If it is necessary I stubbing Service function calls. But some of this functions have PagedResultList as return type. So i have to inject a PagedResultList instance or null.
In some cases I need an instance because the controller do something like this:
testFunction(){
def result = sampleService.doSomething()
if (result.empty) {
variable = "it´s empty"
}
render variable
}
My Test looking like this:
void "sample Test"(){
given:
controller.sampleService = Mock(SampleService)
PagedResultList emptyPagedResultList = ?????
when:
controller.testFunction()
then:
1 * controller.sampleService.doSomething() >> emptyPagedResultList
response.text == "it´s empty"
}
Someone can help me to replace the ????? with a pice of code to fix this issue?
Thanks in advance.
Yes, there are a couple options here:
You could use a real PagedResultList as the emptyPagedResultList - See FooControllerSpec.groovy line 11 for an example
You could use another Spock Mock() as the emptyPagedResultList - See FooControllerSpec.groovy line 25 for an example

How to print the values of variables in a JMeter bean shell assertion

Using Jmeter, I'm passing values to a webservice through a REST API. On Success the API updates the values to a mongo DB.
While Asserting using JMeter BeanShell Assertion..I want to display the values sent in the Request and values Stored in the DB.
Im Using the below Script..
String req_data="${Request_Configuration}";
String res_data="${mongo_db_Configuration}";
if(res_data.equalsIgnoreCase(req_data)){
Failure=false;
FailureMessage = "Data stored in DB is correct";
System.out.println("ReqData="+req_data);
System.out.println("ResData="+res_data);
}
else{
Failure = true;
FailureMessage = "Data Stored in DB is NOT correct";
System.out.println("ReqData="+req_data);
System.out.println("ResData="+res_data);
}
Im Just not able to Print ReqData and ResData. Please help out.
You have a problem in your script. In Beanshell you cannot access variables like ${Request_Configuration}, you need to use vars.get("Request_Configuration") instead.
vars is a shorthand for JMeterVariables class instance for current context.
So your Beanshell Assertion code should look as follows:
String req_data=vars.get("Request_Configuration");
String res_data=vars.get("mongo_db_Configuration");
if(res_data.equalsIgnoreCase(req_data)){
Failure=false;
FailureMessage = "Data stored in DB is correct";
System.out.println("ReqData="+req_data);
System.out.println("ResData="+res_data);
}
else{
Failure = true;
FailureMessage = "Data Stored in DB is NOT correct";
System.out.println("ReqData="+req_data);
System.out.println("ResData="+res_data);
}
I would also suggest using log.info() instead of System.out.println() as in that case results will go to jmeter.log file and won't be "eaten" by exceeding screen buffer size.
See How to use BeanShell: JMeter's favorite built-in component guide for more information on Beanshell scripting and various JMeter API objects exposed to Beanshell explanation.
Use log.info()
Example
log.info("myVariable: " + vars.get("myVariable"));
My use case:
I did use the following code snipped in a BeanShell Assertion within my HTTP Request-sampler to print out my three variables id, type and value:
log.info(Thread.currentThread().getName()+": " + SampleLabel + ": id: " + vars.get("id"));
log.info(Thread.currentThread().getName()+": " + SampleLabel + ": +-type: " + vars.get("type"));
log.info(Thread.currentThread().getName()+": " + SampleLabel + ": +-value: " + vars.get("value"));
Printing also the built-in SampleLabel variable gives you the hint from which sampler you logged this information.

Call multiple webservices from play 2

I am a play2.0-Scala-beginner and have to call several Webservices to generate a HTML page.
After reading the The Play WS API page and a very interesting article from Sadek Drobi I am still unsure what's the best way to accomplish this.
The article shows some code snippets which I don't fully understand as a Play beginner.
Figure 2 on page 4:
val response: Either[Response,Response] =
WS.url("http://someservice.com/post/123/comments").focusOnOk
val responseOrUndesired: Either[Result,Response] = response.left.map {
case Status(4,0,4) => NotFound
case Status(4,0,3) => NotAuthorized
case _ => InternalServerError
}
val comments: Either[Result,List[Comment]] =
responseOrUndesired.right.map(r => r.json.as[List[Comment]])
// in the controller
comment.fold(identity, cs => Ok(html.showComments(cs)))
What does the last line with the fold do? Should comment be comments? Haven't I group the last statement in an Async block?
Figure 4 shows how to combine several IO calls with a single for-expression:
for {
profile <- profilePromise
events <- attachedEventsPromise
articles <- topArticlesPromise
} yield Json.obj(
"profile" -> profile,
"events" -> events,
"articles" -> articles )
}
// in the controller
def showInfo(...) = Action { rq =>
Async {
actorInfo(...).map(info => Ok(info))
}
}
How can I use this snippet? (I am a bit confused by the extra-} after the for-expression.)
Should I write something like this?
var actorInfo = for { // Model
profile <- profilePromise
events <- attachedEventsPromise
articles <- topArticlesPromise
} yield Json.obj(
"profile" -> profile,
"events" -> events,
"articles" -> articles )
def showInfo = Action { rq => // Controller
Async {
actorInfo.map(info => Ok(info))
}
}
What's the best way to combine the snippets from figure 2 and 4 (error handling + composition of IO non-blocking calls)? (f.ex. I want to produce a Error 404 status code if any of the called webservice produce an Error 404).
Maybe someone knows a complete example of calling webservices in the play framework (cannot find an example in the play Sample applications or anywhere else).
I have to say that the article is wrong in the example you show in Figure 2. The method focusOnOk does not exist in Play 2.0. I assume the author of the article used a pre-release version of Play 2 then.
Regarding comment, yes it should be comments. The fold in the statement is operating on an Either. It takes 2 functions as parameters. The first is a function to apply if it is a left value. The second is a function to apply if it is a right value. A more detailed explanation can be found here: http://daily-scala.blogspot.com/2009/11/either.html
So what the line does is. If I have a left value (which meant I got an undesired response), apply the built-in identity function which just gives you back the value. If it has a right value (which means I got an OK response), make a new result that shows the comments somehow.
Regarding Async, it's not actually asynchronous. focusOnOk is a blocking function (a remnant from the old Java days of Play 1.x). But remember, that's not valid Play 2 code.
As for Figure 4, the trailing } is actually because it's a partial alternative of what's in Figure 3. Instead of the numerous promise flatMaps. You can do a for comprehension instead. Also, I think it should be userInfo(...).map instead of actorInfo(...).map.
The Play documentation you linked to actually already shows you a full example.
def feedTitle(feedUrl: String) = Action {
Async {
WS.url(feedUrl).get().map { response =>
Ok("Feed title: " + (response.json \ "title").as[String])
}
}
}
will get whatever is at feedUrl, and you map it to do something with the response which has a status field you can check to see if it was a 404 or something else.
To that end, the Figure 3 and 4 of your linked article should give you a starting point. So you'd have something like,
def getInfo(...) : Promise[String] = {
val profilePromise = WS.url(...).get()
val attachedEventsPromise = WS.url(...).get()
val topArticlesPromise = WS.url(...).get()
for {
profile <- profilePromise
events <- attachedEventsPromise
articles <- topArticlesPromise
} yield {
// or return whatever you want
// remember to change String to something else in the return type
profile.name
}
}
def showInfo(...) = Action { rq =>
Async {
getInfo(...).map { info =>
// convert your info to a Result
Ok(info)
}
}
}

apache and cgicc - differentiate between post and get variables

In PHP it is very simple to check, if a variable has been transmitted via GET or POST. With the cgicc library they all look the same. Is there another possibility to read only GET or only POST variables?
My Code:
cgicc:Cgicc cgiobj;
std::cout << "Both, post or get: " << cgiobj("variablename") << std::endl;
I had the same question so I looked for a solution in the cgicc documentation.
Class CgiEnvironment provides getRequestMethod() which returns "GET" or "POST" accordingly to your request.
eg.
cgicc::Cgicc cgi;
cgicc::CgiEnvironment env = cgi.getEnvironment();
std::string requestMethod = env.getRequestMethod();
I have not tested it, though.