js-yaml -> Parse ruby types - javascript

I am making a Ruby console in JavaScript and thus need to accurately send Ruby object information to the renderer process. I decided to use YAML given that it is super easy to use YAML on the Ruby side and contains all information required. But I keep getting errors.
Take the following ruby:
[Test,Test.new].to_yaml
This converts to the following YAML:
---
- !ruby/class 'Test'
- !ruby/object:Test {}
When I try to parse this with JS-YAML we get the following error:
unknown tag !<!ruby/class> at line 2, column 21:
- !ruby/class 'Test'
^
So I expect this is happenning because YAML in JavaScript doesn't have Ruby types! I've seen that one solution is to create new YAML types to handle this data:
var RubyClassType = new jsyaml.Type('!ruby/class', {
kind: 'class'
});
However, in an ideal world I wouldn't have to define each individual type. In an ideal world either, all unknown types will be treated the same (e.g. as yaml sequences) or ruby wouldn't generate the odd ruby types in the first place. Can I get around this issue without having to define every Ruby type in JavaScript?

Looks like this can be handled in JS-YAML as follows: handle_unknown_types.js
Won't accept this as an answer though as a ruby-first solution would be better.

Related

JS module "YAML" does not stringify with quotes in the documented format

I have a client that needs YAML output in a specific way for a legacy app. The format they need in the file is
key: "string"
key: 123
According to the docs for the YAML module (recommended on https://yaml.org/):
YAML.scalarOptions.str.defaultType = 'QUOTE_SINGLE'
YAML.stringify({ this: null, that: 'value' })
Which reads as if using the defaultType option 'QUOTE_SINGLE' will format the element as that: 'value'.
It does not. What it does is format the entry like 'that': 'value', and the option 'QUOTE_DOUBLE' sets it to "that": "value".
[edit] I even tried adding YAML.scalarOptions.str.defaultKeyType = 'PLAIN' which had no visible effect on the output.
I'm not sure if I've missed a config setting somewhere, or if it's a bug.
What options for the YAML module do I need to use in order to set string-values in double quotes, but leave string-keys without quotes?
Answering my own question.
I wasn't the one that installed the module. I believe the person did a simple yarn add yaml.
By default it installed version 1.2.
The website for the module, by default, shows documentation for version 2.0.

Can I use `TextEncoder` in Bigquery JS UDF?

I am trying to use some Rust wasm code in Bigquery as UDF, and in order to pass on Java String to Rust code the TextEncoder and TextDecoder would be needed to conveniently doing that. As it mentioned here Passing a JavaScript string to a Rust function compiled to WebAssembly
But when I try out some of my code on BigQuery, I encountered an error saying TextEncoder is not defined.
You can try it out as well with a query like this:
https://github.com/liufuyang/rb62-wasm/blob/master/try-3-old.sql
While a working version without using TextEncoder is at https://github.com/liufuyang/rb62-wasm/blob/master/try-3.sql
That means the object is not defined.
As an option, bring your own TextEncoder.
For example, take your try-3-old.sql, and then add this line at the end of the JS UDF definition:
return main();
'''
OPTIONS (library="gs://fh-bigquery/js/inexorabletash.encoding.js");
And now it works:
(wondering, what's the goal with rb62?)

Angular server side rendering template (.cshtml) parse error with escape symbols

I have C# razor *.cshtml template file and would like to use it for Angular (5) server side rendering.
C# .cshtml snippet:
#helper RenderLookupComponent()
{
<list-lookup
[data]="getLookupData('#Model.LookupSourceType')"
[lookupType]="'#Model.LookupSourceType'">
</list-lookup>
}
Everything works fine until '#Model.LookupSourceType' value is not contains escape symbol ('\'), for e.g. when #Model.LookupSourceType = 'SomeType\'
Angular template parser Error:
[error]: Template parse errors:
Parser Error: Missing expected ) at column # in [getLookupData('SomeType\')]
At first glance, it looks like ordinary issue, actually it can be solve by replacing all '\' to '\'. (#Model.LookupSourceType.Replace(#"\", #"\\")).
Q: But i believe there should be more elegant, universal approaches to solve such kind of problems.
The approach that can handles all possible scenario for different kind of escape symbols
Please share your experience
Problem was solved with using HttpUtility.JavaScriptStringEncode(Model.LookupSourceType)

How to make python dictionary from big Javascript object

I have one string. which represents JavaScript object.
https://docs.google.com/document/d/1CFONQntMFMdtD-04rk9uut4UpLyB_OSsDH0bwDZ0tuM/edit?usp=sharing
When i'm using json.loads() python raises Exception: JSONDecodeError: Extra data.
What i'm doing wrong?
P.S.: It's dynamic object, I can't change him
As #DSupreme says, there are extra characters in your data.
This can be caused from various reasons, one being stringifying JSON files and parsing in different programs and languages. If you need to verify if a JSON string is in a correct format, you can use verifying tools such as http://jsonlint.com/ .
For your specific problem, there is an extra ' at the beginning of your string, / for escaping characters and you're also missing the double quote in the end of your string.
Is this what you are looking for
Things i changed:
Removed ' in the beginning
Remove extra / used for escaping double quotes
Added double quotes in the end
{"log_timeout":1000,"featureFlags":{"serverRenderingForBotsOnly":false,"experienceLevelOnFixedPriceJobs":true,"JSUIPaymentVerified":true,"JSUI736SaveSearchRedesign":true,"JSUI341ProposalsFilter":true},"csrfTokenCookieName":"XSRF-TOKEN","csrfTokenHeaderName":"X-Odesk-Csrf-Token","runtime_id":"32a28ec0399c4e8a-DME","clientStatsDMetrics":true,"smfAjax":false,"pageSpeedMetrics":false,"ccstCookieName":"oauth2_global_js_token","pageId":"User","isSearchWithEmptyParams":false,"queryParsedParams":{"q":"python"},"jobs":[{"title":"Python
app engine, Linux,
infrastructure","createdOn":"2017-01-31T16:57:42+00:00","type":2,"ciphertext":"~01440d6a85cc997768","description":"If
you know python and have at least some knowledge of app engine
development. Willing to learn and positive. A big plus if you have
worked with the linux environment and knows how to set up servers on
google-cloud or AWS. \n\nWe can offer a job for a longer period of
time if you are the right fit.\n\nAt least 5 years experience as a
developer required.","category2":"Web, Mobile & Software
Dev","subcategory2":"Other - Software
Development","skills":[{"name":"google-app-engine","prettyName":"Google
App Engine"},{"name":"python","prettyName":"Python"}],"duration":"1 to
3 months","engagement":"30+
hrs\/week","amount":{"currencyCode":"USD","amount":0},"recno":209422776,"client":{"paymentVerificationStatus":null,"location":{"country":null},"totalSpent":0,"totalReviews":0,"totalFeedback":0,"companyRid":0,"companyName":null,"edcUserId":0,"lastContractPlatform":null,"lastContractRid":0,"lastContractTitle":null,"feedbackText":"No
feedback
yet"},"freelancersToHire":0,"relevanceEncoded":"{}","maxAmount":{"currencyCode":"USD","amount":0},"enterpriseJob":false,"tierText":"Intermediate
($$)","isSaved":false,"feedback":null,"proposalsTier":"5 to
10","isApplied":false,"sticky":true,"stickyLabel":"Interesting
Job","jobTs":"1485881862000"},{"title":"Python</span>
Developer","createdOn":"2017-02-01T04:00:20+00:00","type":2,"ciphertext":"~019767ae6381e97a90","description":"Python</span> Developer who can read and
understand the legacy script and apply that understanding to an
existing Python business \nservice. ... Python Developer who can read
and understand the legacy script and apply that understanding to an
existing Python</span> business
\nservice.",
"category2":"Web,
Mobile & Software Dev",
"subcategory2":"Other - Software Development",
"skills":[],
"duration":"Less than 1 week",
"engagement":"Less than 10"
}
Problem was in { } at the end and begin of the string

rdflib.js with RDFa not returning any results

What I use:
Ubuntu 14.04
Node.js 0.10.36
rdflib.js 0.2.0
What I want to achieve:
Parse a html file with RDFa information
Print the found RDF triples
What I have in my Node.js script:
var rdflib = require('rdflib');
var kb = new rdflib.Formula();
rdflib.parse("http://ceur-ws.org/Vol-1085/", kb, "http://www.example.com/", "application/rdfa");
console.log(kb.statements);
The code of rdflib.js calls the third parameter of the 'parse' method 'base', however, I don't know what they mean by that, so I just added dummy URI.
What I get as a result:
[]
Hence, the there are no statements in the store. I would expect to see here the different triples that are present in the html file. Can anybody see what the problem is?
P.S. Because there is no (recent) documentation on how to use rdflib.js, I might be using the above methods in the wrong way.
The first argument of rdflib.parse takes a string that contains the resource at that URI, it doesn't read the URI. You need to use something like request to read the entity body first. Also the URI http://ceur-ws.org/Vol-1085/ does not seem to return application/rdf+xml.

Categories