Dart encodeUriComponent Map.keys() - dictionary

There is an example that I have seen in a number of places for encoding a Map as follows:
#import('dart:uri');
String encodeMap(Map data) {
return Strings.join(data.getKeys().map((k) {
return "${encodeUriComponent(k)}=${encodeUriComponent(data[k])}";
}), "&");
}
I'm running what appears to be the latest Dart editor (version 0.2.9_r 16323)
in the above example, for Dart M2, I believe that data.getKeys() has been changed to data.keys() which I have altered.
However, I get an error when running it in the Editor:
Exception: NoSuchMethodError : method not found: 'call'"
I have 2 questions:
I'm wondering if this above code should still work in M2 with the change indicated (Map.keys())?
I'm wondering if this above code does something different to: JSON.stringify(data);
Any other pointers are welcome.
TIA.

Two changes to do :
import syntax has changed.
getKeys() method became a getter called keys.
A working version :
import 'dart:uri';
String encodeMap(Map data) {
return Strings.join(data.keys.map((k) {
return "${encodeUriComponent(k)}=${encodeUriComponent(data[k])}";
}), "&");
}
The String generated by this encodeMap is quite different from the one generated by JSON.stringify as you can see in the bellow snippet :
main() {
final map = {"a":"b", "c":"d"};
assert(encodeMap(map) == "a=b&c=d");
assert(JSON.stringify(map) == '{"a":"b","c":"d"}');
}

Related

This block contains invalid or unexpected content on Custom HTML

I am editing a document in draft mode Wordpress 5.2.2 in the Gutenberg editor, and add this Custom HTML block:
<pre><code class="language-typescript">const simple = &ltT&gt(cl: T) => cl;
class Hero {
constructor(public position: [number, number]) {}
}
interface { hello: number }
const errorOne = &ltT&gt(cl: T) => new cl(); // Cannot use 'new' with an expression whose type lacks a call or construct signature.</code></pre>
and it happily works as expected in preview. I save as draft.
When I return the HTML is ghosted and I get the error in the title. I can convert to HTML and it works again, but then it errors again when I return to it later.
It seems this error is talked about everywhere but the explanations are nonsense and resolve nothing.
If my Custom HTML is valid (which it seems to be), why does it work and then give an error. How do I fix this?
I think the main issue is not converting < & > properly in your code. They are missing the semicolon at the end of the string.
This code is working fine:
<pre><code class="language-typescript">const simple = <T>(cl: T) => cl;
class Hero {
constructor(public position: [number, number]) {}
}
interface { hello: number }
const errorOne = <T>(cl: T) => new cl(); // Cannot use 'new' with an expression whose type lacks a call or construct signature.</code></pre>
When you insert the code with missing semicolon, WordPress saved as is. However, when trying the load the page again WordPress compares the saved content (with missing characters) to the one generated from the block (which is probably attempting to display correct HTML). This process led to an error as both texts were not identical.
If you want to check the error yourself you can check the console through developer tool in your browser (F12 in Chrome).

Gosu system table query failing in Gunits

I have a Guidewire Gunit for a transformer in gosu which queries the system table to get a description for a result code which is working fine when run on the server but Gunit fails for the same.
I have tried the annotation #ServerTest for Gunit but that is failing as well.
The same code works fine in Gosu scratchpad.
PFA the code snippet as follows:
var resultCodes = Query.make(SystemTable).select().where(\elt -> elt.ResultCode == "AS01")
var description = ""
if(resultCodes != null && !resultCodes.isEmpty())
{
description = resultCodes.get(0).getFullDescription()
}
I'm getting the exception as follows :
java.lang.IllegalStateException: TableMetadataFactory cannot be used before it is started
Thanks,
Deepti
(Suggestion : )If your requirement is just to query based on some values.
Better dont use that .where() condition.
This is like SELECT * FROM <TABLE> and after getting all the data you are picking out your required result.
The best and the actual way is to use like
Query.make(TABLE_NAME).compare(TABLE_NAME#FIELD_NAME,Relop.Equals,"value_to_compare").select();
Query will be like
SELECT * FROM <TABLE_NAME> WHERE FIELD_NAME = FIELD_VALUE_TO_COMPARE;
While running Gunits, GW uses Shadow tables which will be basically empty.
Here if you are using OOTB entities, You can use Builder classes
or if you need to use some custom entities, use bundles to insert data first.
After inserting data into SystemTable (either using builder classes or bundles) run the below code.
var resultCodes = Query.make(SystemTable).compare(SystemTable#ResultCode ,Relop.Equals,"AS01").select()
foreach(result in resultCodes){
description = result.FullDescription
print("Output : "+description);
}
This happens when your RunLevel is set too low. Run levels below "NO_DAEMONS" will not load system tables. The default should be "NO_DAEMONS" so if you have an annotation on your test like this:
#RunLevel(gw.api.system.server.Runlevel.NONE)
either remove it or increase the level.
You can refactor your code like this:
uses gw.testharness.RunLevel
uses gw.api.database.Query
uses org.mockito.Mockito
uses gw.api.database.IQueryBeanResult
#RunLevel(NONE)
class StackOverflowTest {
function testDoQuery() {
var rs = Mockito.mock(IQueryBeanResult<SystemTable>)
var query = Mockito.mock(Query<SystemTable>)
Mockito.when(query.select()).thenReturn(rs)
var stackOverflow = Mockito.spy(new StackOverflow())
Mockito.doReturn(query).when(stackOverflow).getSystemTableQuery()
stackOverflow.doQuery()
Mockito.verify(stackOverflow, Mockito.times(1)).getSystemTableQuery()
Mockito.verify(query, Mockito.times(1)).select()
Mockito.verify(rs, Mockito.times(1)).iterator()
}
class StackOverflow {
function doQuery() {
var resultCodes = getSystemTableQuery().select().where(\elt -> elt.ResultCode == "AS01")
}
protected function getSystemTableQuery(): Query<SystemTable> {
return Query.make(SystemTable)
}
}
}

RDotNet function to add two user defined inputs giving errors

I wrote the following controller function in an ASP.NET MVC5 application to return the sum of 2 user defined inputs using the R function sum(). This compiles successfully but does not give any output.
It is giving 500 (Internal Server Error) since the ajax function is failing.
Can anyone please tell me where I am making mistake?
public JsonResult Sum(int? Text1,int? Text2)
{
REngine.SetEnvironmentVariables(); //
REngine engine = REngine.GetInstance();
return Json(engine.Evaluate("function(Text1,Text2)
{sum(Text1,Text2)}").AsFunction(), JsonRequestBehavior.AllowGet);
}
I have solved the problem myself. The correct code snippet for the controller function is as follows:
var mySum = engine.Evaluate("function(x,y){return (x+y)}").AsFunction();
var v = engine.CreateInteger(Text1);
var u = engine.CreateInteger(Text2);
var sum1 = mySum.Invoke(new SymbolicExpression[] { u, v }).AsInteger();
return Json(sum1, JsonRequestBehavior.AllowGet); }
Since many of you messaged me asking for a sample code for the rdotnet application, I have published an example code with explanation on my blog:
wordpress.com/post/pheonix116s.wordpress.com/169
I hope you all may find it useful.

Cannot implicitly convert type 'System.Linq.IQueryable to System.Data.Entity.DbSet<>

I receive the following error when I try to run my code. I haven't managed to solve it yet, please Help:
edit: Marked with * where it fails.
>
public IQueryable<Video> GetVideos([QueryString("id")] int? categorieId)
{
var _db = new TeleviziuneAcademicaAspSilverlight.Models.VideoContext();
IQueryable<Video> query = *_db.Videos;*
if (categorieId.HasValue && categorieId > 0)
{
query = query.Where(v => v.CategorieID == categorieId);
}
return query;
Change
IQueryable<Video> query =
to
IQueryable<Appname.Models.Video> query =
The reason for your error is that you have the type Video defined twice and because of using a short type name you accidentally reference not the one Video you should.
Also change it in the method's return value
public IQueryable<Appname.Models.Video> GetVideos( ... )
You seem to have two classes called Video. If you need both, you'll need to project from one to the other before your return statement:
return query.Select(dbVideo => new Appname.Video()
{
Prop1 = dbVideo.Prop1,
Prop2 = dbVideo.Prop2,
// etc.
});
Though you'll probably need to change the return type to an IEnumerable<> if you do that.
If you can just work with Appname.Models.Video, change IQueryable<Video> to IQueryable<Appname.Models.Video> in the method signature and the method body.

Is it possible to find the function and/or line number that caused an error in ActionScript 3.0 without using debug mode?

I'm currently trying to implement an automated bug reporter for a Flex application, and would like to return error messages to a server along with the function/line number that caused the error. Essentially, I'm trying to get the getStackTrace() information without going into debug mode, because most users of the app aren't likely to have the debug version of flash player.
My current method is using the UncaughtErrorEvent handler to catch errors that occur within the app, but the error message only returns the type of error that has occurred, and not the location (which means it's useless). I have tried implementing getStackTrace() myself using a function name-grabber such as
private function getFunctionName (callee:Function, parent:Object):String {
for each ( var m:XML in describeType(parent)..method) {
if ( this[m.#name] == callee) return m.#name;
}
return "private function!";
}
but that will only work because of arguments.callee, and so won't go through multiple levels of function calls (it would never get above my error event listener).
So! Anyone have any ideas on how to get informative error messages through the global
error event handler?
EDIT: There seems to be some misunderstanding. I'm explicitly avoiding getStackTrace() because it returns 'null' when not in debug mode. Any solution that uses this function is what I'm specifically trying to avoid.
Just noticed the part about "I don't want to use debug." Well, that's not an option, as the non-debug version of Flash does not have any concept of a stack trace at all. Sucks, don't it?
Not relevant but still cool.
The rest is just for with the debug player.
This is part of my personal debug class (strangely enough, it is added to every single project I work on). It returns a String which represents the index in the stack passed -- class and method name. Once you have those, line number is trivial.
/**
* Returns the function name of whatever called this function (and whatever called that)...
*/
public static function getCaller( index:int = 0 ):String
{
try
{
throw new Error('pass');
}
catch (e:Error)
{
var arr:Array = String(e.getStackTrace()).split("\t");
var value:String = arr[3 + index];
// This pattern matches a standard function.
var re:RegExp = /^at (.*?)\/(.*?)\(\)/ ;
var owner:Array = re.exec(value);
try
{
var cref:Array = owner[1].split('::');
return cref[ 1 ] + "." + owner[2];
}
catch( e:Error )
{
try
{
re = /^at (.*?)\(\)/; // constructor.
owner = re.exec(value);
var tmp:Array = owner[1].split('::');
var cName:String = tmp.join('.');
return cName;
}
catch( error:Error )
{
}
}
}
return "No caller could be found.";
}
As a side note: this is not set up properly to handle an event model -- sometimes events present themselves as either not having callers or as some very weird alternate syntax.
You don't have to throw an error to get the stack trace.
var myError:Error = new Error();
var theStack:String = myError.getStackTrace();
good reference on the Error class
[EDIT]
Nope after reading my own reference getStackTrace() is only available in debug versions of the flash player.
So it looks like you are stuck with what you are doing now.

Resources