xojo call a method with button - xojo

I have the code below in a View method to parse JSON files. The method ContentsOfDictionary accepts the parameters d as Xojo.Core.Dictionary and level as an integer, and returns text.If I use ContentsOfDictionary in an action button, I get this error:
error: Not Enough arguments: got 0, expected at least 1
Here is a link to the test file I am using.
How do I call the method ContentsOfDictionary?
dim dict as Xojo.Core.Dictionary = Xojo.Data.ParseJSON (kJsonData)
const kEOL = &u0A
dim indent as text
for i as integer = 1 to level
indent = indent + " "
next
dim t as text
for each entry as Xojo.Core.DictionaryEntry in dict
t = t + indent + entry.Key + " "
if Xojo.Introspection.GetType( entry.Value ) is nil then
t = t + "nil" + kEOL
else
select case Xojo.Introspection.GetType( entry.Value ).Name
case "Boolean"
t = t + if( entry.Value, "true", "false" ) + kEOL
case "Text"
t = t + entry.Value + kEOL
case "Int32", "Int64"
//
// You get the idea
//
case "Dictionary"
t = t + kEOL + ContentsOfDictionary( entry.Value, level + 1 )
end select
end if
next
return t

UPDATE: None of the below applies as #johnnyB's example was of the ContentsOfDictionary function and should not have been trying to access the JSON data but just working on the supplied Dictionary. There is a link to the fixed test project in the comments below.
It's failing because you're not satisfying the parameter types of any of ContentsOfDictionary's signatures.
entry.Value is of type Auto, so before calling ContentsOfDictionary you need to copy entry.Value into a Dictionary and pass that in to the function instead.
For example...
...
case "Dictionary"
dim d as new Xojo.Core.Dictionary = entry.Value
t = t + kEOL + ContentsOfDictionary( d, level + 1 )
end select

Related

Making a print function repeat on a new line everytime it prints

So I want this final print function to print its function on a new line every time it prints. I've tried various "\n" placements to make it work but to no avail. Any tips?
from datetime import date
currentYear = date.today().year
print('Hi. What is your name?')
name = input()
while True:
try:
print('How old are you, ' + name + '?')
age = int(input())
if age >= 0:
break
else:
print('That is not a valid number.')
except ValueError:
print('That is not a valid number')
ageinHundred = 100 - int(age)
y = currentYear + int(ageinHundred)
t = 'You will be 100 years old in the year ' + str(int((y)))
print(t)
print('Give me another number')
num = input()
f = (int(num) * t)
print(f)
I want the final print function (print(f)) to print f multiple times on a new line each time. Not one after the other like the above code does now.
Thanks!
Change the last couple of lines to:
# Put t inside a list so it does list multiplication instead
# of string multiplication
f = int(num) * [t]
# Then join the individual f-lists with newlines and print
print("\n".join(f))
For the f = line, inspect f to get a better idea of what's going on there.
For the join part, join takes a list of strings, inserts the given string (in this case "\n"; a newline), and "joins" it all together. Get used to using join. It is a very helpful function.
Try this:
from datetime import date
currentYear = date.today().year
print('Hi. What is your name?')
name = input()
while True:
try:
print('How old are you, ' + name + '?')
age = int(input())
if age >= 0:
break
else:
print('That is not a valid number.')
except ValueError:
print('That is not a valid number')
ageinHundred = 100 - int(age)
y = currentYear + int(ageinHundred)
t = 'You will be 100 years old in the year ' + str(int((y)))
print(t)
print('Give me another number')
num = input()
for i in range(0,int(num)):
print(t)

How do I append an int value into a string array in Swift?

I'm learning Swift now (with basic programming know-how), and I'm making a String array containing a deck of 52 cards via a for loop, but I'm not sure how to append a value with an int and string values.
I know using \(int) converts an int to a string, but it doesn't seem to work when appending to an array. My code, including the error messages are below:
var suits = ["Spades", "Hearts", "Clubs", "Diamonds"]
var deck:[String] = []
for s in suits
{
deck.append("Ace of " + s)
deck.append("King of " + s)
deck.append("Queen of " + s)
deck.append("Jack of " + s)
for (var i = 2; i < 11; ++i)
{
deck.append(\(i) + " of " + s)
//error message: "Expected ',' separator"
//error message: "Invalid character in source file"
}
}
You need to have your (i) in quotes in order for it to be converted to a String.
deck.append("\(i)" + " of " + s)
You could also do this:
var value = String(i)
deck.append(value + " of " + s)

How do I find what a TextBox's contents will be after pressing Ctrl + Z, before it occurs?

I am writing a small function that will calculate the contents of a TextBox after the KeyPress event, but during the KeyPress event. I know, it sounds strange. :)
The reason for this is because I have been given a project at work, where I am to fix any errors in a current program.
There is currently a TextBox, which triggers a search on a SQL Server, in the KeyPress event.
This searches for the current contents of the TextBox concatenated with Chr(KeyAscii)
This means that if your TextBox contains Hello and your cursor is at the end of the word it will work correctly, but if you have the o selected and press a it will search for Helloa instead of Hella.
So to correct, this I have come up with the following function
Private Function TextAfterKeyPress(Ctrl As Control, KeyAscii As Integer) As String
Dim strUnSelLeft As String
Dim strUnSelRight As String
Dim strSel As String
Dim strMid As String
With Ctrl
strUnSelLeft = ""
strUnSelRight = ""
strMid = .Text
Select Case KeyAscii
Case 1 ' Ctrl + A
' No change to text
Case 3 ' Ctrl + C
' No change to text
Case 8 ' BackSpace
If .SelStart = 0 Then
' No change to text
Else
If .SelLength = 0 Then
strUnSelLeft = Left(.Text, .SelStart - 1)
strUnSelRight = Right(.Text, Len(.Text) - (.SelStart + .SelLength))
strMid = ""
Else
strUnSelLeft = Left(.Text, .SelStart)
strUnSelRight = Right(.Text, Len(.Text) - (.SelStart + .SelLength))
strMid = ""
End If
End If
Case 9 ' Tab
' No change to text
Case 13 ' Return
' No change to text
Case 22 ' Ctrl + V
strUnSelLeft = Left(.Text, .SelStart)
strUnSelRight = Right(.Text, Len(.Text) - (.SelStart + .SelLength))
strMid = Clipboard.GetText
Case 24 ' Ctrl + X
If .SelLength = 0 Then
' No change to text
Else
strUnSelLeft = Left(.Text, .SelStart)
strUnSelRight = Right(.Text, Len(.Text) - (.SelStart + .SelLength))
strMid = ""
End If
Case 26 ' Ctrl + Z
Case 27 ' Esc
' No Change to text
Case 137, 153, 160, 169, 188, 189, 190, 215, 247 ' Disallowed Chars
' No Change to text
Case 128 To 255 ' Allowed non standard Chars
strUnSelLeft = Left(.Text, .SelStart)
strUnSelRight = Right(.Text, Len(.Text) - (.SelStart + .SelLength))
strMid = Chr(KeyAscii)
Case 32 To 127 ' Standard Printable Chars
strUnSelLeft = Left(.Text, .SelStart)
strUnSelRight = Right(.Text, Len(.Text) - (.SelStart + .SelLength))
strMid = Chr(KeyAscii)
Case Else
End Select
TextAfterKeyPress = strUnSelLeft & strMid & strUnSelRight
End With
End Function
Now for the section where it says "Case 26", it will perform an undo action, and then the search won't work correctly again.
Is there any way to find out what the contents of the TextBox will be when you press Ctrl + Z, but during the KeyPress in which it happens? The KeyPress event fires before the content of the TextBox changes so I would need to find out what is in the Undo buffer so that I can run a correct search.
Can anyone point me in the right direction?
I have worked with textbox APIs a bit ..And i don't think you can deal with its UNDO buffer due to its limitation.. but something you can do is to manually send an UNDO then read the textbox content.
Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
Private Const EM_UNDO = &HC7
,
Case 26
KeyAscii = 0
SendMessage .hwnd, EM_UNDO, ByVal 0, ByVal 0
strMid = .Text
If you only need to read the text and not to change it you can send an another UNDO msg to get the text to its previous content.

Does VBA have any built in URL decoding?

I just need to decode a URL, for example, replace %2E with .
I can hack out a method if one isn't build in, but my assumption is that there must be a URL decoding tool already existing.
Here's a snippet I wrote years ago
-markus
Public Function URLDecode(sEncodedURL As String) As String
On Error GoTo Catch
Dim iLoop As Integer
Dim sRtn As String
Dim sTmp As String
If Len(sEncodedURL) > 0 Then
' Loop through each char
For iLoop = 1 To Len(sEncodedURL)
sTmp = Mid(sEncodedURL, iLoop, 1)
sTmp = Replace(sTmp, "+", " ")
' If char is % then get next two chars
' and convert from HEX to decimal
If sTmp = "%" and LEN(sEncodedURL) + 1 > iLoop + 2 Then
sTmp = Mid(sEncodedURL, iLoop + 1, 2)
sTmp = Chr(CDec("&H" & sTmp))
' Increment loop by 2
iLoop = iLoop + 2
End If
sRtn = sRtn & sTmp
Next
URLDecode = sRtn
End If
Finally:
Exit Function
Catch:
URLDecode = ""
Resume Finally
End Function
No.
But here's one: URL Encoder and Decoder for VB
Or something along the lines of (possibly not complete):
Public Function URLDecode(ByVal strEncodedURL As String) As String
Dim str As String
str = strEncodedURL
If Len(str) > 0 Then
str = Replace(str, "&amp", " & ")
str = Replace(str, "&#03", Chr(39))
str = Replace(str, "&quo", Chr(34))
str = Replace(str, "+", " ")
str = Replace(str, "%2A", "*")
str = Replace(str, "%40", "#")
str = Replace(str, "%2D", "-")
str = Replace(str, "%5F", "_")
str = Replace(str, "%2B", "+")
str = Replace(str, "%2E", ".")
str = Replace(str, "%2F", "/")
URLDecode = str
End If
End Function
Also, take a look at How can I URL encode a string in Excel VBA?
EncodeURL and DecodeURL function using htmlfile object(Late binding)
I got this source from this site: http://cocosoft.kr/442
Function ENCODEURL(varText As Variant, Optional blnEncode = True)
Static objHtmlfile As Object
If objHtmlfile Is Nothing Then
Set objHtmlfile = CreateObject("htmlfile")
With objHtmlfile.parentWindow
.execScript "function encode(s) {return encodeURIComponent(s)}", "jscript"
End With
End If
If blnEncode Then
ENCODEURL = objHtmlfile.parentWindow.encode(varText)
End If
End Function
Function DECODEURL(varText As Variant, Optional blnEncode = True)
Static objHtmlfile As Object
If objHtmlfile Is Nothing Then
Set objHtmlfile = CreateObject("htmlfile")
With objHtmlfile.parentWindow
.execScript "function decode(s) {return decodeURIComponent(s)}", "jscript"
End With
End If
If blnEncode Then
DECODEURL = objHtmlfile.parentWindow.decode(varText)
End If
End Function
For example,
str = ENCODEURL("/?&=") 'returns "%2F%3F%26%3D"
str = DECODEURL("%2F%3F%26%3D") 'returns "/?&="
Here is the code from the URL posted in another answer in case it goes down as it works great.
http://www.freevbcode.com/ShowCode.asp?ID=1512
Public Function URLEncode(StringToEncode As String, Optional _
UsePlusRatherThanHexForSpace As Boolean = False) As String
Dim TempAns As String
Dim CurChr As Integer
CurChr = 1
Do Until CurChr - 1 = Len(StringToEncode)
Select Case Asc(Mid(StringToEncode, CurChr, 1))
Case 48 To 57, 65 To 90, 97 To 122
TempAns = TempAns & Mid(StringToEncode, CurChr, 1)
Case 32
If UsePlusRatherThanHexForSpace = True Then
TempAns = TempAns & "+"
Else
TempAns = TempAns & "%" & Hex(32)
End If
Case Else
TempAns = TempAns & "%" & _
Format(Hex(Asc(Mid(StringToEncode, _
CurChr, 1))), "00")
End Select
CurChr = CurChr + 1
Loop
URLEncode = TempAns
End Function
Public Function URLDecode(StringToDecode As String) As String
Dim TempAns As String
Dim CurChr As Integer
CurChr = 1
Do Until CurChr - 1 = Len(StringToDecode)
Select Case Mid(StringToDecode, CurChr, 1)
Case "+"
TempAns = TempAns & " "
Case "%"
TempAns = TempAns & Chr(Val("&h" & _
Mid(StringToDecode, CurChr + 1, 2)))
CurChr = CurChr + 2
Case Else
TempAns = TempAns & Mid(StringToDecode, CurChr, 1)
End Select
CurChr = CurChr + 1
Loop
URLDecode = TempAns
End Function
' URLDecode function in Perl for reference
' both VB and Perl versions must return same
'
' sub urldecode{
' local($val)=#_;
' $val=~s/\+/ /g;
' $val=~s/%([0-9A-H]{2})/pack('C',hex($1))/ge;
' return $val;
' }

help with linq to sql

Help me with this algorithm please.
var companies = companyrepository.GetAll().OrderBy(sidx + " " + sord).Skip(pageIndex * pageSize).Take(pageSize);
string where = "";
if (op == "eq")
where = field + "=" + data;
else if (op == "cn")
where = field + " LIKE '%"+data+"%'"; ///here lies my problem
companies = companies.Where(where);
its for adding dynamic where clauses to a linq query... op, field, and data are all strings that come with ajax from a jquery grid.
The problem is that it gives me an error when it tries to do the Like operator... it works just fine with the equals operator.
Based on this page, the following should work for you:
if (op == "eq")
where = field + "=" + data;
else if (op == "cn")
where = field + ".Contains(\"" + data + "\")";
I ran some tests on my own data, and it appears to work fine.

Resources