How to pass params to static callback function? - actionscript-3

I have code
MergeTool.as:
private static function askFromUser(cardId:uint, field:String, mainValue:*, addValue:*):void {
WindowManager.instance.showQuestionPopup({
message: "Client " + cardId + " has duplicate values. Do you want to replace" + mainValue + " to " + addValue,
id:cardId,
field:field,
value:addValue
}, okCallback);
}
private static function okCallback(p:*):void {
trace("ok", p.message);
}
QuestionPopup.as :
private function onClick(event:MouseEvent):void {
if(_ok) _ok.call(params);
}
When I press "Yes" it trows an error :
Error #1063: Argument count mismatch on core::MergeTool$/okCallback(). Expected 1, got 0.
But, if I use anonymous callback with 0 arguments - it works properly :
WindowManager.instance.showQuestionPopup({
message: "Client " + cardId + " has duplicate values. Do you want to replace" + mainValue + " to " + addValue,
id:cardId,
field:field,
value:addValue
}, function (){
trace("ok", this.message);
});
It returns params object, that I pass to WindowManager.instance.showQuestionPopup(params, callback) and I can access it with "this" inside anonymous fucntion.
I think 1 variant doesn`t wokr because of static. How to fix 1 variant, because 2 is non intuitive?

The function.call() method doesn't pass parameters, the argument is to tell what object this should refer to.
Instead, you should use the function.apply(context, parameter array) method. It takes the same first parameter as the call method, but then the second parameter takes an Arrayand applies each element of the array as an argument to the function you want to call. So for you, it should look like this:
private function onClick(event:MouseEvent):void {
if(_ok != null) _ok.apply(this, [params]);
}
To illustrate, let's say you have the following function that requires 3 parameters:
function test(p1:Number, p2Number, p3:Number){
}
The following two lines are exactly the same:
test(1,2,3);
test.apply(this, [1,2,3]);

Related

no implicit conversion between string and int in razor view javascript area

<script type="text/javascript">
var destinationId = #(Model.DestinationId == 0?"":Model.DestinationId);
</script>
I want to output "" if Model.DestinationId is 0 else display Model.DestinationId
Because your C# code is trying to return a string when the if condition yields true and returns an int(value of DestinationId) when the condition expression returns false. The compiler is telling you that it is not valid! You need to return the same type from both the cases.
To fix the issue, return the same type from both the cases. You can use ToString() method on the int type property so that your ternary expression will always return the same type (string)
var destinationId = #(Model.DestinationId == 0 ? "" : Model.DestinationId.ToString());
Although the above will fix your compiler error, it might not be giving what you are after. The above code will render something like this when your DestinationId property value is 0.
var destinationId = ;
Which is going to give you a script error
Uncaught SyntaxError: Unexpected token ;
and when DestinationId property has a non zero value, for example, 10.
var destinationId = 10;
There are multiple ways to solve the issue. One simple approach is to replace the empty string with something JavaScript understands. Here in the below sample, I am rendering null as the value
var destinationId = #(Model.DestinationId == 0 ? "null" : Model.DestinationId.ToString());
if (destinationId===null) {
console.log('value does not exist');
}
else {
console.log('value is '+ destinationId);
}
Another option is to simply read the DestinationId property value and check for 0 in your JavaScript code as needed.
Another option is to wrap your entire C# expression in single or double quotes. But then again you number value will be represented as a string :(, which is not good.
I suggest you to use the correct type(even in JavaScript)

Custom ARQ function not working with fuseki endpoint

I successfully implemented sparql queries using custom ARQ functions using the following (custom function code):
public class LevenshteinFilter extends FunctionBase2 {
public LevenshteinFilter() { super() ; }
public NodeValue exec(NodeValue value1, NodeValue value2){
LevenshteinDistance LD=new LevenshteinDistance();
int i = LD.apply(value1.asString(), value2.asString());
return NodeValue.makeInteger(i);
}
}
it works fine when I query against a Model loaded from a turtle file, like this:
InputStream input = QueryProcessor.class.getClassLoader().getResourceAsStream("full.ttl");
model = ModelFactory.createMemModelMaker().createModel("default");
model.read(input,null,"TURTLE"); // null base URI, since model URIs are absolute
input.close();
with the query being sent like this :
String functionUri = "http://www.example1.org/LevenshteinFunction";
FunctionRegistry.get().put(functionUri , LevenshteinFilter.class);
String s = "whatever you want";
String sparql = prefixes+" SELECT DISTINCT ?l WHERE { ?x rdfs:label ?l . " + "FILTER(fct:LevenshteinFunction(?l, \"" + s + "\") < 4) }";
Query query = QueryFactory.create(sparql);
QueryExecution qexec = QueryExecutionFactory.create(query, model);
ResultSet rs = qexec.execSelect();
However, if i use a working fuseki endpoint for the same dataset (full.ttl) like this :
fusekiUrl="http://localhost:3030/ds/query";
sending the query like this (using QueryExecutionFactory.sparqlService(fusekiUrl,query) instead of QueryExecutionFactory.create(query,model) ):
String functionUri = "http://www.example1.org/LevenshteinFunction";
FunctionRegistry.get().put(functionUri , LevenshteinFilter.class);
String s = "whatever you want";
String sparql = prefixes+" SELECT DISTINCT ?l WHERE { ?x rdfs:label ?l . " + "FILTER(fct:LevenshteinFunction(?l, \"" + s + "\") < 4) }";
Query query = QueryFactory.create(sparql);
QueryExecution qexec = QueryExecutionFactory.sparqlService(fusekiUrl,query);
ResultSet rs = qexec.execSelect();
Then I don't get any results back. In both cases I printed out the FunctionRegistry and they contain exactly the same entries, especially :
key=http://www.example1.org/LevenshteinFunction
value: org.apache.jena.sparql.function.FunctionFactoryAuto#5a45133e
Any clue ?
Thanks
Back on that question that I finally solved. There was several issues, one which is the fact that (obviously !!) Remote endpoint and client are running on different jvms.
To get the thing working, do the following (for a stupid MyFilter custom function - i.e strlen) :
1) Deploy the custom functions classes jar on fuseki server
2) Modify the fuseki config :
add [] ja:loadClass "my.functions.package.MyFilter"
where MyFilter implementation is :
import org.apache.jena.sparql.expr.NodeValue;
import org.apache.jena.sparql.function.FunctionBase1;
public class MyFilter extends FunctionBase1 {
public MyFilter() { super() ; }
public NodeValue exec(NodeValue value1){
int d = value1.asString().length();
return NodeValue.makeInteger(new Integer(d));
}
}
3) add the following prefix to the context:
PREFIX f: <java:my.functions.package.>
Note that "my.functions.package." is the package of MyFilter
class, not the class itself --> this means that you never call a class
method in sparql queries but only a class that implements
org.apache.jena.sparql.function.FunctionBaseX where X is the number of
argument of your filter function
4) Write (for instance) the query like this:
SELECT DISTINCT ?l
WHERE { ?x skos:prefLabel ?l .
FILTER (f:MyFilter(?l) < 20)
}
EDIT: step 2) is not necessary

Input string was not in a correct format in WQL query

I get the following error :
[WMI Event Watcher Task] Error: An error occurred with the following
error message: "Input string was not in a correct format.".
When I Execute WQL Query :
SELECT * FROM __InstanceCreationEvent WITHIN 10
WHERE TargetInstance ISA 'CIM_DataFile' AND TargetInstance.Name ='C:\\Users\Mohammed\\Desktop\\Test\\ETL\\ssis-basic-control-flow-tasks\\file_to_watch.txt'
I try to watch a file like this :
//Removes local network printer based
//on full unc path returns true if successful
//otherwise false
public static bool RemoveUnc(string printUncPath)
{
ManagementScope oManagementScope = new ManagementScope(ManagementPath.DefaultPath);
oManagementScope.Connect();
SelectQuery oSelectQuery = new SelectQuery();
oSelectQuery.QueryString = #"SELECT * FROM Win32_Printer WHERE Name = '" +
printUncPath.Replace("\\", "\\\\") + "'";
ManagementObjectSearcher oObjectSearcher =
new ManagementObjectSearcher(oManagementScope, oSelectQuery);
ManagementObjectCollection oObjectCollection = oObjectSearcher.Get();
if (oObjectCollection.Count != 0)
{
foreach (ManagementObject oItem in oObjectCollection)
{
oItem.Delete();
return true;
}
}
return false;
}
I am assuming it is string that includes slashes causing that error. Below is an example I use for removing a printer from a local workstation. Printer share names include a format like "\\printserver\printerShare". Pay attention to the printUncPath.Replace("\\","\\\\"). Think this will solve your problem. Pretty sure you have to escape twice.

PowerShell: Cannot find an overload for IndexOf and the argument count: 2

I am attempting to use a portion of a script I wrote to return a list of Local Groups a specified user may be part of on a remote server so they can be quickly removed from said Local Group. Everything seems to work fine until the groups a person may be part of goes below two. When there is only one group I get the following error:
Cannot find an overload for "IndexOf" and the argument count: "2".
At line:177 char:30
+ [string]([array]::IndexOf <<<< ($localGroups, $_)+1) + ". " + $_
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodCountCouldNotFindBest
Here are the Functions I wrote for this particular script...
This function will return a list of groups the given user is part of:
function Get-LocalGroupAccess
{
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true)]
[string]$fqdn,
[Parameter(Mandatory=$true)]
[string]$userName
)
Process
{
$serverPath = [ADSI]"WinNT://$fqdn,computer"
$serverPath.PSBase.Children | where {$_.PSBase.SchemaClassName -eq 'group'} | foreach {
$lGroup = [ADSI]$_.PSBase.Path
$lGroup.PSBase.Invoke("Members") | foreach {
$lMember = $_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null).Replace("WinNT://","")
if ($lMember -like "$userName")
{
$localAccess += #($lGroup.Name)
}
}
}
return($localAccess)
}
}
This function sets the User Object (I am not sure this is the technical term):
function Set-UserObj($userDomain, $userName)
{
$userObj = [ADSI]"WinNT://$userDomain/$userName"
return ($userObj)
}
This function set the FQDN (checks to see if it is pingable):
function Set-FQDN($fqdn)
{
do{
$fqdn = Read-Host "Enter the FQDN"
} while (-not(Test-Connection $fqdn -quiet))
return($fqdn)
}
This function will take the selection for the group you want to remove the given user from, change it to the proper place in the array, and return the group:
function Set-LocalGroup($localGroups, $selectGroup)
{
$selectGroup = Read-Host "What group would you like to add $userDomain/$userName to?"
$selectGroup = [int]$selectGroup -= 1
$setGroup = $localGroups[$selectGroup]
return($setGroup)
}
This function sets the Group object (not sure if this is the technical term):
function Set-GroupObj($fqdn, $group)
{
$groupObj = [ADSI]"WinNT://$fqdn/$group"
return($groupObj)
}
This function removes the given user from the group selected:
function Remove-UserAccess ($gObj, $uObj)
{
$gObj.PSBase.Invoke("Remove",$uObj.PSBase.Path)
}
In the script the user name, domain and FQDN are requested. After these are provided the script will return a list of groups the given user is part of. Everything works fine until the user is part of one group. Once that takes place, it throws the error I pasted above.
Please note, this is my first time posting and I am not sure what information is needed here. I hope I provided the proper and correct information. if not, please let me know if there is something else that you require.
Thanks!
I went back and was looking at the difference, if there were any, in the variable $localGroups that I was creating (I used Get-Member -InputObject $localGroups). I noticed that when $localGroups had only one item it was a System.String type but when it had more than one item in it, it was a System.Object[] type. I decided to do the following and it addressed the issue I was having:
$localGroups = #(Get-LocalGroupAccess $fqdn $userName)
previous code:
$localGroups = Get-LocalGroupAccess $fqdn $userName
Everything is working as it should because I forced the variable to a static type instead of allowing it to create whatever type it wanted.

Why does iterating over a generic object in ActionScript give me values instead of keys?

I may be doing something really stupid, but I don't get why the below code doesn't work...
Here, I create a generic Object called spellbook:
// A list of all the player's spells
public var spellBook:Object = {};
Here, I add a key-value pair to the spellbook:
spellBook["bubble"] = new BubbleSpell(spellBook);
And here I try to output the contents of the spellbook:
trace("Spells initialised. Available spells are:");
for each (var _spell:String in spellBook)
{
trace(" ", _spell, " : ", spellBook[_spell]);
}
But this is the output I get:
Spells initialised. Available spells are:
[object BubbleSpell] : undefined
What I don't get is why it's not outputting:
Spells initialised. Available spells are:
bubble : [object BubbleSpell]
??
It's as if I'm iterating over the values in spellbook, rather than the keys... is that what's happening? All the docs I've seen so far seem to indicate that this is the correct way to iterate over a dictionary (which a generic object kind of is...) Do I need to call a method to get keys instead of values for generic objects?
So confused!
for each is used to iterate over values, you want to use a for loop which iterates over keys, eg:
var mySpells = {
speedy: new SpeedySpell(),
sleepy: new SleepySpell()
};
for (var key : String in mySpells) {
trace("key: " + key + " value: " + mySpells[key]);
}
Note that when iterating over the keys in a Dictionary you should leave the key value untyped (*) as a Dictionary's keys can be of any type (whereas an Object's keys can only be of type String).
A common trick would be to create a utility function which extracts an Object's keys to an Array for easier iteration:
function getKeys(source : Object) : Array {
const result : Array = [];
for (var key : * in source) {
result.push(key);
}
return result;
}
You can then make use of this helper function:
trace(getKeys(mySpells));
Because you're using a for each loop. Use a for loop instead:
for (var key:* in spellBook) {
trace(key + ': ' + spellBook[key]);
}