Is a ValueList() a string? - coldfusion

I am trying to convert the results of a query into an array
this.arLibrary = ValueList(qryLibrary.ID).ListToArray();
And I get the following error
Detail A script statement must end with ";".The CFML compiler was
processing:A script statement beginning with
this.arLibrary on line 43, column 9.A cfscript tag
beginning on line 21, column 2. KnownColumn -1 KnownLine -1
KnownText <unknown> Line 43 Message Invalid construct.
Snippet this.arLibrary =
ValueList(qryLibrary.ID).
StackTrace
This does work
temp = ValueList(qryLibrary.ID);
this.arMetricLibActive = temp.ListToArray();
It makes me wonder if ValueList() is a string

Yes, it's a string. The error is a parsing issue in the CFML engine. The same syntax works fine in Lucee. File a bug like Henry suggested.
Here's an example in the CommandBox REPL
CFSCRIPT-REPL: foo = queryNew('bar')
{
"COLUMNS":[
"BAR"
],
"DATA":[
]
}
CFSCRIPT-REPL: valueList( foo.bar ).listToArray()
[
]

James, it'd be useful if you read error messages when they are presented to you: they generally contain pertinent information. I don't mean this in a "stating the obvious" sort of way, but rather that it's actually a very important part of troubleshooting problems. You are faced with an error message from the compiler, which means the error occurred when the source code was being compiled. However you are asking a question about data types, which - in a loosely and dynamically typed language like CFML - is a runtime consideration. "Runtime" implies "when the code is being run" which is intrinsically after the code is compiled. If the code can't compile: it won't be run.
So the issue is not whether valueList() returns a string or anything like that.
The issue here is that there is a bug in ColdFusion's CFML parser, and it is not able to interpret this expression:
ValueList(qryLibrary.ID).ListToArray()
I don't know why there's a problem with this: there should be no problem with parsing the calling of a method on another function call's return value; and indeed it seems to be a peculiarity of using valueList() like this, as opposed to built-in functions in general.
File a bug.
As for what to do about it in your code in the meantime, I think Dan is right: generally one can use a query column as an array anyhow, provided one uses bracket notation to reference the column, eg: qryLibrary["ID"]. Brad draws attention to this not working on Lucee, but... this is neither here nor there, and just something that Lucee needs to deal with. There was a bug raised for this in Railo - https://issues.jboss.org/browse/RAILO-641 - but they declined to address it, with only semi-valid reasoning.

Epilog:
This works on ColdFusion 2016 and above
<cfscript>
qryLibrary = QueryNew("ID", "varchar");
qryLibrary.addrow({"id" : "cat"});
qryLibrary.addrow({"id" : "dog"});
qryLibrary.addrow({"id" : "fish"});
writedump(qryLibrary);
arLibrary = ValueList(qryLibrary.ID).ListToArray();
writedump(arLibrary);
</cfscript>
https://cffiddle.org/app/file?filepath=6588296c-5e4d-49a4-894b-4986513e9e30/0ecde857-6d28-4e43-88a7-7830c109ab11/84cd7e81-16f8-43d7-b4c9-5490b1b5d007.cfm

Related

DDMathParser implicit multiplication not working

I use DDMathParser to solver formula expressions using Swift. The following code works fine, however, implicit multiplication doesn't. Reading the docs it should work... So, what do I miss here?
my code:
...
substitutions.updateValue(3, forKey: "x")
let myString = "3$x"
do{
let expression = try Expression(string: myString, operatorSet: operatorSet, options: myTRO, locale: myLocale)
let result = try evaluator.evaluate(expression, substitutions: substitutions)
print("expression is: \(expression), the result is : \(result)")
} catch {
print("Error")
}
...
The code throws the "Error". Using the string "3*$x" the expression is calculated as expected.
DDMathParser author here.
So, the .invalidFormat error is thrown when the framework has a sequence of tokens and is looking for an operator in order to figure out what goes around it. If it can't find an operator but still has tokens to resolve but no operator, then it throws the .invalidFormat error.
This implies that you have a 3.0 number token and a $x variable token, but no × multiplication token.
I see also that you're passing in a custom set of TokenResolverOptions (the myTRO variable). I'd guess that you're passing in an option set that does not include the .allowImplicitMultiplication value. If I try to parse 3$x without the .allowImplicitMultiplication resolver option, then I get the .invalidFormat error thrown.
Ok, got it myself. As Dave DeLong mentioned .allowImplicitMultiplication is included by default in the options but will get ignored when creating custom options. Since I want to use localized expressions (decimal separator within expression string is local) I need to use the advanced definition of Expression:
let expression = try Expression(string: ..., operatorSet: ..., options: ..., locale: ...)
In order to use the localized string option I defined let myLocale = NSLocale.current but accidentally also created a new operatorSet new options and passed it to the expression definition. The right way is not to create custom operatorSet and options but to use the defaults within the Expression definition:
let expression = try Expression(string: expressionString, operatorSet: OperatorSet.default, options: TokenResolverOptions.default, locale: myLocale)
Dave DeLong did a really great job in creating the DDMatParser framework. For newbies it is very hard to get started with. The wiki section at DDMathParser is pretty basic and doesn't give some details or examples for all the other great functionality DDMatParser is providing.

Go validator.v2 gives error "unknown tag" for regexp

I have been trying to understand why some regular expressions give me an error "Unknown tag" while using the validator.v2 package in golang. It works for some regular expressions but does not work with some which have "{}" inside them, and when I use the validator.Validate() it gives me an error at runtime "unknown tag".
Here's the code:
type Company struct {
Name string `validate:"regexp=^[a-zA-Z .]{1,100}$"`
}
which gives me the following error at runtime:
Name: unknown tag
however this regex works perfectly fine
type Company struct {
Name string `validate:"regexp=^[a-zA-Z .]*$"`
}
I am using the braces because of length restrictions that I want to put on the string. There could be other ways to do it, but I feel the regex is the way to go and is easier to have it along with other rules right there in the expression.
The problem appears to be the , char in your first regex. You can see in the validator source code that the tag is split on ,. By UTSLing, I see no support for escaped commas in the tags; this is probably an oversight on the part of the project author. I suggest filing a bug/feature request.
The problem pointed out by #Flimzy is correct, but it's not a bug.
Probably it was fixed since then, so at the moment validator supports escape sequence \\ for such case, and you can do it like this:
type Company struct {
Name string `validate:"regexp=^[a-zA-Z .]{1\\,100}$"`
}

Parsing Javascript with Python

In one of my script I use urllib2and BeautifulSoup to parse a HTML page and read a <script> tag.
This is what I get :
<script>
var x_data = {
logged: logged,
lengthcarrousel: 2,
products : [
{
"serial" : "106541823"
...
</script>
My goal is to read the JSON in the x_data variable and I do not know how to do it properly.
I though of :
Convert to string and remove the first chars to the { and same for last }
Use Regular Expression with something like '{.*}' and take the first group
Something else ?
I don't know if these are efficient and if there is some other ways to do it in a nice way.
Do you think a method is preferable to the other ? any method I may not be aware of ?
Thank you in advance for any advice.
EDIT :
Following advice I get the Regexp solution but I can't search in multiple lines despite using re.MULTILINE :
string1 = '<script>
var x_data = {
logged: logged,
lengthcarrousel: 2,
products : [
{
"serial" : "106541823"}
]
};
</script>'
p = re.compile(r'\{.*\};',re.MULTILINE);
m = p.search(string1)
if m:
print m.group(0)
else:
print "Error !"
I always got an "Error !".
EDIT2 :
Works well with re.DOTALL.
I think these methods are essentially the same in terms of elegance and performance (using {.*} may be slightly better because .* is greedy, i.e. there will be almost no backtracking, and because it seems to me more "forgiving" for different JS code formatting nuances). What you may be more interested in is this: https://docs.python.org/3.6/library/json.html.
If it always looks exactly like this, then you can hack a solution like the one you proposed, based on it looking exactly like this.
Because programmers do everything in code, I suspect in practice it will not alway look exactly this, and then any hacky solution will be fragile and will fail at unexpected (read "impossibly inconvenient") moments. (Regex is known to be hacky when it comes to parsing code).
If you want to do this right, you will need to get a real JavaScript parser, apply it to the code fragment defined by the script tag content, to produce an AST, then search the AST for JavaScript nested structures that happen to look like JSON, and take the content of that tree, prettyprinted.
Even this will be fragile in the face of a programmer who assembles the JSON fragment using JavaScript assignment statements. You can handle this by computing data flow, and discovering sets of code that happen to assemble JSON code. This is rather a lot of work.
So you get to decide what the limits on your solution will be, and then accept the consequences when somebody you don't control does something random.

Trouble with C++ Regex POSIX character class

I'm trying to create a regex that is capable of analysing something like this:
002561-1415179671591i.jpg
The second part is a unix timestamp (before the i), and I need to extract that. I came up with the following syntax, but std::regex keeps throwing a regex_error before I even check for a match and I'm not too sure what's wrong.
Here's what I've got so far:([:d:])*-[[:d:]]*([:alpha:])\.jpg
The C++ code line that throws the error is the constructor to regex
std::regex reg(regex_expr);
where regex_expr is a string that has been read in from a file.
Really appreciate any help you can give.
Edit: I wrote a try catch section, and it seems I'm getting the following error code
std::regex_constants::error_brack
Edit 2: Ok... seems I'm still getting the error even with a cut-down test:
([:alpha:])*
Edit 3:
Seems I can't get any expression to work. Here's a bit more info. I'm using clang++ 3.5.0 on Kubuntu 14.04.
Not sure that [:d:] can stand for [:digit:]. [EDIT] (It seems it's possible)
When you use a POSIX character class, it must be enclosed in a character class like that:
[[:digit:]]
(This syntax allows to compose other classes [[:digit:]ab])
so:
std::string regex_expr = "([[:digit:]]*)-([[:digit:]]*)([[:alpha:]])\\.jpg";
or if you use the basic mode:
std::string regex_expr = "\\([[:digit:]]*\\)-\\([[:digit:]]*\\)\\([[:alpha:]]\\)\\.jpg";
I would rather use the perl-compatible syntax instead of character classes:
\d+-(\d+)[a-z]*\.jpg
After many tests, for whatever reason, I couldn't get this to work. As I had boost anyway, I tried out the boost::regex and it worked straight away, so I presume that something to do with either clang, or the version of the standard on this pc just wasn't working.
So simply put, tried boost and it worked straight away. Not much of an answer, but I guess that's how things go sometimes.

Highlighting Javascript Inline Block Comments in Vim

Background
I use JScript (Microsoft's ECMAScript implementation) for a lot of Windows system administration needs. This means I use a lot of ActiveX (Automated COM) objects. The methods of these objects often expect Number or Boolean arguments. For example:
var fso = new ActiveXObject("Scripting.FileSystemObject");
var a = fso.CreateTextFile("c:\\testfile.txt", true);
a.WriteLine("This is a test.");
a.Close();
(CreateTextFile Method on MSDN)
On the second line you see that the second argument is one that I'm talking about. A Boolean of "true" doesn't really describe how the method's behavior will change. This isn't a problem for me, but my automation-shy coworkers are easily spooked. Not knowing what an argument does spooks them. Unfortunately a long list of constants (not real constants, of course, since current JScript versions don't support them) will also spook them. So I've taken to documenting some of these basic function calls with inline block comments. The second line in the above example would be written as such:
var a = fso.CreateTextFile("c:\\testfile.txt", /*overwrite*/ true, /*unicode*/ false);
That ends up with a small syntax highlighting dilemma for me, though. I like my comments highlighted vibrantly; both block and line comments. These tiny inline block comments mean little to me, personally, however. I'd like to highlight those particular comments in a more muted fashion (light gray on white, for example). Which brings me to my dilemma.
Dilemma
I'd like to override the default syntax highlighting for block comments when both the beginning and end marks are on the same line. Ideally this is done solely in my vimrc file, and not in a superseding personal copy of the javascript.vim syntax. My initial attempt is pathetic:
hi inlineComment guifg=#bbbbbb
match inlineComment "\/\*.*\*\/"
Straight away you can see the first problem with this regular expression pattern is that it's a greedy search. It's going to match from the first "/*" to the last "*/" on the line, meaning everything between two inline block comments will get this highlight style as well. I can fix that, but I'm really not sure how to deal with my second concern.
Comments can't be defined inside of String literals in ECMAScript. So this syntax highlighting will override String highlighting as well. I've never had a problem with this in system administration scripts, but it does often bite me when I'm examining the source of many javascript libraries intended for browsers (less.js for example).
What regex pattern, syntax definition, or other solution would the amazing StackOverflow community recommend to restore my vimrc zen?
I'm not sure, but from your description it sounds like you don't need a new syntax definition. Vim syntax files usually let you override a particular syntax item with your own choice of highlighting. In this case, the item you want is called javaScriptComment, so a command like this will set its highlighting:-
hi javaScriptComment guifg=#bbbbbb
but you have to do this in your .vimrc file (or somewhere that's sourced from there), so it's evaluated before the syntax file. The syntax file uses the highlight default command, so the syntax file's choice of highlighting only affects syntax items with no highlighting set. See :help :hi-default for more details on that. BTW, it only works on Vim 5.8 and later.
The above command will change all inline /* */ comments, and leave // line comments with their default setting, because line comments are a different syntax item (javaScriptLineComment). You can find the names of all these groups by looking at the javascript.vim file. (The easiest way to do this is :e $VIMRUNTIME/syntax/javascript.vim .)
If you only want to change some inline comments, it's a little more complicated, but still easy to see what to do by looking at javascript.vim . If you do that, you can see that block comments are defined like this:-
syn region javaScriptComment start="/\*" end="\*/" contains=#Spell,javaScriptCommentTodo
See that you can use separate regexes for begin and end markers: you don't need to worry about matching the stuff in between with non-greedy quantifiers, or anything like that. To have a syntax item that works similarly but only on one line, try adding the oneline option (:h :syn-oneline for more details):-
syn region myOnelineComment start="/\*" end="\*/" oneline
I've removed the two contains groups because (1) if you're only using it for parameter names, you probably don't want spell-checking turned on inside these comments, and (2) contained sections that aren't oneline override the oneline in the container region, so you would still match all TODO comments with this region.
You can define this new kind of comment region in your .vimrc, and set the highlighting how you like: it looks like you already know how to do that, so I won't go into more details on that. I haven't tried out this particular example, so you may still need a bit of fiddling to make it work. Give it a try and let me know how it goes.
Why don't you simply add a comment line above the call?
I think that
// fso.CreateTextFile(filename:String, overwrite:Boolean, unicode:Boolean)
var a = fso.CreateTextFile("c:\\testfile.txt", true, false);
is a lot more readable and informative than
var a = fso.CreateTextFile("c:\\testfile.txt", /*overwrite*/ true, /*unicode*/ false);