Getting a Fail Trying to Parse a ZonedDateTime from a String Using ZonedDateTimePattern - nodatime

I've been learning how to use NodaTime, as I think it is a far superior "all things temporal" library that the handful of structs in the BCL. Reading the docs and experimenting.
This experiment has me flummoxed. I started out just trying to parse a ZonedDateTime.
The things I was trying were not successful, so I thought I'd try something which should be "bulletproof". The following code represents that attempt:
Instant thisNow = SystemClock.Instance.GetCurrentInstant();
var timezone = DateTimeZoneProviders.Tzdb["Australia/Brisbane"];
var zonedDateTime = thisNow.InZone(timezone);
var zonePattern = ZonedDateTimePattern.GeneralFormatOnlyIso;
var zoneFormatted = zonePattern.Format(zonedDateTime);
var zoneParseResult = zonePattern.Parse(zoneFormatted);
Console.WriteLine(zoneParseResult.Success ? "parse success" : "parse failure");
So, simply trying to parse back that which you just converted to a string.
The zoneFormatted has the following value 2021-09-04T16:59:08 Australia/Brisbane (+10)
Any ideas what I am doing wrong?
Cheers

Any ideas what I am doing wrong?
You're using ZonedDateTimePattern.GeneralFormatOnlyIso, which is (as the name suggests) only for formatting, not for parsing.
To get a pattern which is able to parse time zones, you need to specify an IDateTimeZoneProvider. The easiest way to do that is to start with a format-only pattern, and use WithZoneProvider:
using NodaTime;
using NodaTime.Text;
using System;
class Program
{
static void Main(string[] args)
{
var pattern = ZonedDateTimePattern.GeneralFormatOnlyIso
.WithZoneProvider(DateTimeZoneProviders.Tzdb);
var text = "2021-09-04T16:59:08 Australia/Brisbane (+10)";
var result = pattern.Parse(text);
Console.WriteLine(result.Success);
Console.WriteLine(result.Value);
}
}

Related

How does proto3 set the value of the map type

How to set the value of map type in static code?
I have a map structure like this.
message HelloRequest {
Maps maps = 1;
}
message Maps {
map<string, AudioChannelCountMapBitrateOptions> formatMapChannelCount = 1;
}
message AudioChannelCountMapBitrateOptions{
map<string, StringVec> bitrateMap = 1;
}
message StringVec{
repeated string strings = 1;
}
After I generate the pb file, how do I use it?
StringVec provides a set method and a get method,so the strings field can be get and set like this.
const strVec = new messages.StringVec();
strVec.setStringsList(['1', '2']);
console.log(strVec.getStringsList());
But Maps and AudioChannelCountMapBitrateOptions only provide the get method, like getFormatmapchannelcountMap,getBitratemapMap.
How do I set the value of this map structure so that I can get a complete map data structure.
the map data structure like this? right?
formatMapChannelCount : {
bitrateMap : ['1','2','3']
}
If you feel my description is not clear, please ask me questions.
https://developers.google.com/protocol-buffers/docs/reference/javascript-generated#map
The official document has instructions, but I actually only found it now.

Is there a way to suppress single quotes in YamlScalarNode output?

Consider this simple program:
using System;
using YamlDotNet.RepresentationModel;
namespace TestYamlNode
{
class Program
{
static void Main(string[] args)
{
var scalarNode = new YamlScalarNode("!yada");
scalarNode.Style = YamlDotNet.Core.ScalarStyle.Plain;
var serializer = new YamlDotNet.Serialization.Serializer();
serializer.Serialize(Console.Out, scalarNode);
scalarNode = new YamlScalarNode("yada");
scalarNode.Style = YamlDotNet.Core.ScalarStyle.Plain;
serializer.Serialize(Console.Out, scalarNode);
}
}
}
The oputput of the program is:
'!yada'
yada
Is there a way to tell YamlDotNet to not include single quotes in the output when it has characters like !, { etc. included in it?
For some context, I'm processing a AWS SAM template that has a property that looks like this:
uri: !Sub arn:${AWS::Partition}:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${PetStorePetFunc.Arn}/invocations
OK - so after playing with this a bit, I realized that I asked what might be a dumb question.
In my use case I'm trying to generate an output with the form:
uri: !Sub arn:${AWS::Partition}:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${PetStorePetFunc.Arn}/invocations
It looks like the correct way to do this is to use the Tag property on the YamlScalarNode:
example:
var node = new YamlScalarNode("arn:${AWS::Partition}:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${PetStorePetFunc.Arn}/invocations");
node.Tag = "!Sub";

Calling function with callback defined as string

var method = 'serviceName.MethodName'
I Just want to call it like
serviceName.methodName(function(output callback){
});
Is there any approach to call it.thanks
There are two methods that I can think of now.
JS eval
You can use the javascript eval function to convert any string into code snippet like below. Although eval is a quick solution but should not be used unless you dont have any other option by your side.
var method = 'UserService.getData';
eval(method)();
Factory pattern
Use a below pattern to get the service
You would need to define the services in such a manner that you can access them using a pattern.
var Services = {
// UserService and AccountsService are again objects having some callable functions.
UserService : {getData: function(){}, getAge: function(){}},
AccountsService : {getData: function(){}, getAge: function(){}},
// getService is the heart of the code which will get you the required service depending on the string paramter you pass.
getService : function(serviceName){
var service = '';
switch(serviceName){
case 'User':
service = this.UserService;
break;
case 'Accounts':
service = this.AccountsService;
break;
}
return service;
}
}
You can use get the required service with below code
Services.getService('User')
I'm not aware of any way you can resolve the serviceName part of that string to an object, without using eval. So obviously you need to be extremely careful.
Perhaps:
if (method.match(/^[a-zA-Z0-9_]+\.[a-zA-Z0-9_]+$/) {
var servicePart = eval(method.split('.')[0]);
var methodPart = method.split('.')[1];
servicePart[methodPart](...)
}
There are two separate problems in your question:
How to access object property by property name (string)?
How to access object by it's name (string)?
Regarding the first problem - it is easy to access object property by string using the following notation:
const myObject = {
myProp: 1,
};
console.log(myObject['myProp']);
And regarding the second problem - it depends on what serviceName is:
if it is a property of some other object, then use someObject['serviceName']['MethodName']
if it is a local variable, consider using a Map (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) to associate strings with objects;

explicit POS tagged input provided and getting sentiment stanfordnlp

I am trying the code mentioned in question 11 from the URL.
I want to first give POS tagged input and second get sentiment analysis. First one I able to successfully get done. I able to print the tree and it looks fine. However second one returns me -1 (it should return me 4=very positive).
Please provide inputs/suggestions.
public static String test(){
try{
String grammer="/Users/lenin/jar/stanfordparser-master/stanford-parser/models/englishPCFG.ser.gz";
// set up grammar and options as appropriate
LexicalizedParser lp = LexicalizedParser.loadModel(grammer);
String[] sent3 = { "movie", "was","very", "good","." };
// Parser gets tag of second "can" wrong without help
String[] tag3 = { "PRP", "VBD", "RB", "JJ","." };
List sentence3 = new ArrayList();
for (int i = 0; i < sent3.length; i++) {
sentence3.add(new TaggedWord(sent3[i], tag3[i]));
}
Tree parse = lp.parse(sentence3);
parse.pennPrint();
int sentiment_score = RNNCoreAnnotations.getPredictedClass(parse);
System.out.println("score: "+sentiment_score);
}
catch(Exception e){
e.printStackTrace();
}
return "";
}
You're getting a value of -1 because you haven't run any sentiment analysis. You've only parsed the sentence for grammatical structure.
You can, of course, run the sentiment analyzer via code, but, unfortunately, at the moment there isn't an easy lower-level interface to do so. That would be a good thing to add sometime! You essentially need to duplicate the processing that happens in the class edu.stanford.nlp.pipeline.SentimentAnnotator:
Get a binarized tree from the parser (directly or by binarizing the tree returned)
Collapse unaries
Run the SentimentCostAndGradient class's forwardPropagateTree

Parse XML from String using XPath in Bada?

I have read the tutorial on XML parsing in Bada. But I don't want to use a file. I need to parse my XML from a Osp::Base::String. Any ideas which methods should I use? So far I have replaced
xpathCtx = xmlXPathNewContext(doc);
if(xpathCtx == NULL) {
AppLog("Error: unable to create new XPath context");
xmlFreeDoc(doc);
return(E_IO);
}
with
xpathCtx = (xmlXPathContextPtr) xmlXPathNewCString("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><title lang=\"en\">XQuery Kick Start</title><title lang=\"en\">Learning XML</title>");
But the emulator simply closes.
Thank you.
Your code is wrong because you cannot cast from xmlXPathObjectPtr to xmlXPathContextPtr: they are different structs.
The code given in the tutorial is right, just use
xmlDocPtr xmlReadDoc (const xmlChar * cur,
const char * URL,
const char * encoding,
int options)
instead of
xmlReadFile(..)
To understand how to use this function have a look at the docs and at the examples on libXML2 website.

Resources