I'm new to VBScript and I am running into some trouble. The script is making an API call and pulling account information, placing the data into a CSV file. I'm pulling the data into an array, looping through each account and, if certain properties qualify, assigning them to a variable to be written to the CSV. The problem I am having is if one account qualifies for a property, it sets the variable and if the next account doesn't qualify, the variable is still retaining the value, giving false results in the CSV.
Set SFTPServer = WScript.CreateObject("SFTPCOMInterface.CIServer")
accounts = SFTPServer.AdminAccounts
For each admin in accounts
adminName = admin.Login
Dim count : count = admin.GetPermissionsCount()
For i = 0 To CInt(count )- 1
Set permission = admin.GetPermission(i)
' AdminPermissionsPolicy:
' ServerManagement = 0,
' SiteManagement = 1,
' STManagement = 2,
' UserCreation = 3,
' ChangePassword = 4,
' COMManagement = 5,
' ReportManagement = 6,
Select case permission.Permission
case 0:
serverAdmin = "Server Admin"
case 1:
site = permission.SiteName
case 2:
stMan = "2"
case 3:
userCreate = "3"
case 4:
chPassword = "4"
case 5:
comMan = "5"
case 6:
report = "6"
End Select
Next
WriteStuff.WriteLine""+adminName+"|"+site+"|"+stMan+"|"+userCreate+"|"+chPassword+"|"+comMan+"|"+report+"")
Next
Unfortunately variables in VBScript are either at global, or function scope.
So you'll need to reset each of the variables on each iteration of the for loop.
One way would be to write Dim dummy at the top of your script, and just before the Select Case, write serverAdmin = dummy, site = dummy etc.
It's good practice to Dim explicitly all your variables, and to use Option Explicit at the top of the module to enforce that.
Here's an alternate way to do what you need without having to empty each variable on each iteration. You've already documented what each value means in your code. Instead of using comments for that purpose, define them as constants at the top of your scope block:
' AdminPermissionsPolicy:
Const ServerManagement = 0
Const SiteManagement = 1
Const STManagement = 2
Const UserCreation = 3
Const ChangePassword = 4
Const COMManagement = 5
Const ReportManagement = 6
Then you can declare an array to hold the values:
Dim a(6)
And then in your loop you can empty the array on each iteration using the Erase function. You can use the constant names instead of 0/1/2/etc and, when it comes time to write the values, you can use Join() to combine your array values into a string instead of having to concatenate 7 variables.
For each admin in accounts
adminName = admin.Login
Erase a ' Empty the Permissions array for each new account
Dim count : count = admin.GetPermissionsCount()
For i = 0 To CInt(count )- 1
Set permission = admin.GetPermission(i)
Select case permission.Permission
case ServerManagement: ' Now you can use the constant instead of "0"
a(ServerManagement) = "Server Admin"
case SiteManagement:
a(SiteManagement) = permission.SiteName
...
End Select
Next
WriteStuff.WriteLine Join(a, "|") ' Use Join() to combine array values
Next
Let's start with the output. You want to print a list of items (some of them possibly Empty) separated by "|". That should be done like this:
WriteStuff.WriteLine Join(aOut, "|")
Advantages:
You don't need to know that VBScript's concatenation operator is &, not +, because you can't even use the wrong one with Join.
You don't need to repeat the separator.
No useless pre/ap-pending of the empty string "".
Works with any number of items.
aOut needs to be initalized in the loop. That is easy with ReDim - without Preserve.
Advantages:
You don't need to know that Empty is the literal for empty/uninitialzed in VBScript.
You don't need to repeat an assignment for each variable.
Works with any number of items.
Demo code:
Option Explicit
Const cnUB = 3
Dim nTest
For nTest = 0 To cnUB
ReDim aOut(cnUB)
Select Case nTest
Case 0
aOut(0) = "A"
Case 1
aOut(1) = "B"
Case 2
aOut(2) = "C"
Case 3
aOut(3) = "D"
End Select
WScript.Echo Join(aOut, "|")
Next
output:
cscript 31565794.vbs
A|||
|B||
||C|
|||D
Disadvantage:
Putting the data into the array anonymously (just known by number/index) may be more errorprone than using distinct variable( name)s. If you need the elements for further computations it may be a good idea to define constants
wtf
Const ciReport = 1
...
aOut(ciReport) = "B"
Related
I`m having the following code from which I extract randomPW for my db.
I need this string of random characters in order to use it a primary key in my Db. The problem is that I`m getting quite a lot of duplicates when I execute this code more than once or if I get a Loop in order to extract (for example) 100 keys at once.
If I try to reload the page in order to insert one by one key the same problem occurs... every 50-80 reloads there is a duplicate. What's wrong with my code?
<%
Function RandomPW(myLength)
Const minLength = 6
Const maxLength = 20
Dim X, Y, strPW
If myLength = 0 Then
Randomize
myLength = Int((maxLength * Rnd) + minLength)
End If
For X = 1 To myLength
Y = Int((3 * Rnd) + 1) '(1) Numeric, (2) Uppercase, (3) Lowercase
Select Case Y
Case 1
'Numeric character
Randomize
strPW = strPW & CHR(Int((9 * Rnd) + 48))
Case 2
'Uppercase character
Randomize
strPW = strPW & CHR(Int((25 * Rnd) + 65))
Case 3
'Lowercase character
Randomize
strPW = strPW & CHR(Int((25 * Rnd) + 97))
End Select
Next
RandomPW = strPW
End Function
%>
I expect my code to extract a string that will not duplicate every now and then.
I need this string of random characters in order to use it a primary key in my Db.
In this case I would recommend to use Scriptlet.TypeLib :
Function RandomPW(myLength)
Set TypeLib = CreateObject("Scriptlet.TypeLib")
If myLength < Len(TypeLib.Guid)
RandomPW = Left(TypeLib.Guid, myLength)
Else
RandomPW = TypeLib.Guid
End If
End Function
Randomize is not supposed to be used more than once, unless you want to make sure you are creating fake, repeatable randomness. Per docs, helpfully linked by Lankymart (emphasis mine):
Randomize uses number to initialize the Rnd function's random-number generator, giving it a new seed value. If you omit number, the value returned by the system timer is used as the new seed value.
The system timer referred to above is in seconds; which means, successive calls to Randomize in short succession will make sure the following Rnd is yielding the same value.
It would likely help you immensely to remove all calls to Randomize.
I need to iterate over all of the selected rows in an SSDBGrid. Then, I need to get the value in the current row and populate the relevant place in the array with this value.
I've been attempting to do this with the code below:
Dim i As Integer
i = 0
Dim nomCode(Grd_Nominal.SelBookmarks.Count) As String ' This is my array.
Do While Grd_Nominal.SelBookmarks <> 0
nomCode(i) = Grd_Nominal.SelBookmarks(0)
If Grd_Nominal.SelBookmarks.Count > 0 Then
Grd_Nominal.SelBoomarks(0).Remove
End If
i = i + 1
Loop
However, nomCode(i) is always being filled as nomCode(i) = "??"
Why is it inserting "??", and how can I fix this to insert the value of the current row?
You need to first of all re-think how you're declaring your array.
Dim nomCode() As String
ReDim nomCode(Grd_Nominal.SelBookmarks.Count - 1) As String
This is because when declaring an array you need to pass in a constant as the length. ReDim doesn't, so this will go partly towards solving the issue.
Dim x As Integer
Dim bk As Variant
For x = 0 to Grd_Nominal.Rows.Count - 1
bm = Grd_Nominal.SelBookmarks(x)
nomCode(x) = Grd_Nominal.Columns("Your_Column").CellValue(bm)
Next
This should sort the rest of the issue, I think.
I would like to sort the field values (strings) by their frequency in lotusscript.
Has anyone an idea to solve this?
Thanks a lot.
Personally I would avoid LotusScript if you can help it. You are going to run into limitations that cannot be worked around.
Regardless of which route you do take, from a performance point of view it is better to have the View indexes do the work.
So you would create a view. The first column would be as follows.
Column Value: The field you want to check.
Sort: Ascending
Type: Categorized
After this you can access the data using the NotesViewNavigator. The related method call is getNextCategory. This will give you a view entry object which you can call ChildCount on to get totals.
For example (Disclaimer: Code written from memory, not guaranteed to run):
Dim sess As New NotesSession
Dim db As NotesDatabase
Dim vw As NotesView
Dim nav as NotesViewNavigator
Dim entryA As NotesViewEntry
Dim entryB As NotesViewEntry
Set db = sess.CurrentDatabase
Set vw = db.GetView("testView")
vw.AutoUpdate = False
Set nav = vw.CreateViewNav
Set entryA = nav.GetFirst
while entryA not Nothing
Set entryB = nav.GetNextCategory(entryA)
if entryB not nothing then
' Do your processing.
' entryB.childCount will give total.
end if
set EntryA = EntryB
Wend
view.AutoUpdate = True
This way the heavy lifting (string sorting, counting) is handled by the View index. So you only need to process the final results.
To answer the op's (old) question directly, the way to do this in LotusScript is both simple and easy:
dim para as string
dim words as variant
dim fq list as long
'get the text to freq-count
para = doc.text '(or $ from somewhere)
'tidy up para by removing/replacing characters you don't want
para = replace(para, split(". , : ; - [ ] ()"), "")
words = split(para) 'or split(words, "delim") - default is space
forall w in words
if iselement(words(w)) then
fq(w) = fq(w) + 1
Else
fq(w) = 1
End forall
'you now have a count of each individual word in the FQ list
'to get the words out and the word frequencies (not sorted):
forall x in fq
print listtag(x) = x
End forall
Thats it. No issue with LotusScript - quick and easy (and lists can be massive). To get a sorted list, you would have to move to an array and do a sort on it or move to a field and let #sort do the job somehow.
I need to sort a column in my Access2010 Query correctly. It is a Textcolumn containing Strings with numbers like "CRMPPC1". The text length may vary within the column.
When I sort this it looks like
CRMPPC1
**CRMPPC10**
CRMPPC2
CRMPPC3
CRMPPC4
....
But what I need is
CRMPPC1
CRMPPC2
CRMPPC3
CRMPPC4
....
**CRMPPC10**
Can anybody help me out (preferably with SQL)? I tried various approaches like VAL, CAST etc. but nothing works so far.
If the number of characters in the text prefix is variable then I don't think there is a pure Access SQL solution, but the VBA function
Public Function ExtractNumber(textString As Variant) As Long
Dim s As String, i As Long
s = Nz(textString, "")
For i = 1 To Len(s)
Select Case Mid(s, i, 1)
Case "0" To "9"
Exit For
End Select
Next
If i > Len(s) Then
ExtractNumber = 0
Else
ExtractNumber = Val(Mid(s, i))
End If
End Function
would allow you to use a query like this
SELECT textTest.*
FROM textTest
ORDER BY ExtractNumber([textColumn]);
Try out using this 'hack' for natural order sorting. It only works for two characters, but you can modify it for more of course.
'''' ONLY WORKS WITH LAST TWO CHARACTER NUMBERS AT THE END. IF YOU HAVE THREE NUMBERS IT WILL BREAK'''''''
Function PadNumberForNatSort(strToMod) As String
If IsNumeric(Right(strToMod, 1)) = True Then
If IsNumeric(Mid(strToMod, Len(strToMod), 1)) = True And IsNumeric(Mid(strToMod, Len(strToMod) - 1, 1)) = True Then
PadNumberForNatSort = strToMod
Else
PadNumberForNatSort = Mid(strToMod, 1, Len(strToMod) - 1) & "0" & Mid(strToMod, Len(strToMod), 1)
End If
Else
PadNumberForNatSort = strToMod
End If
End Function
In your SQL: ORDER BY PadNumberForNatSort([column_name])
I got this comma separated file with a bunch of numbers
The only thing that I need to be able to do is to find what number that appears the most time
Ex:
817;9;516;11;817;408;9;817
then the result will be 817
I hope you understand what I am trying to do.
I would suggest using the FileSystemObjects, specifically the OpenTextFile method to read the file, then use split function to separate based on columns. Then iterate the array returned, and count the number of times each number occurs.
The following code will count your array for you. It uses the useful Dictionary object.
Set counts = CreateObject("Scripting.Dictionary")
For i = Lbound(arr) to Ubound(arr)
If Not counts.Exists(arr(i)) Then
counts.add arr(i), 1
Else
currCount = counts.Item(arr(i))
counts.Item(arr(i)) = currCount + 1
End If
Next
nums = counts.Keys()
currMax = 0
currNum = 0
For i = Lbound(nums) to Ubound(nums)
If counts.Item(nums(i)) > currMax Then
currMax = counts.Item(nums(i))
currNum = nums(i)
End If
Next
num = currNum ' Most often found number
max = currMax ' Number of times it was found
i would go through the text and count the number of your nubmers.
after that i would redim an dynamic array.
- go throught the text from beginning to end, and store them in the array.
after that i would pick the first number, go through the array and count (for example in tmpcounter) the number of dublicates. [you could store the counted number from the textfile in tmphit]
the you pick the second number, count the number of dublicates ( tmpcounter2 /tmphit2)
compare the two counters,you "keep" the higher one and use the lowe one for the next number
...go on until the last field is validated.
at the end you know which number appearse most and how often.
i hope this help you.
this is how i would programm it, maybe there is a better way or an API.
at the end you know
Try this
Set objFile = CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\Test.txt",1)
Set dictNumbers = CreateObject("Scripting.Dictionary")
Dim MostKey
intHighest = -1
do while NOT objFile.AtEndOfStream
LineArray = Split(objFile.ReadLine,";")
for i = 0 to UBound(LineArray)
if dictNumbers.Exists(LineArray(i)) Then
dictNumbers.Item(LineArray(i)) = dictNumbers.Item(LineArray(i)) + 1
else
dictNumbers.Add LineArray(i), 1
end if
if dictNumbers.Item(LineArray(i)) > intHighest Then
intHeighest = dictNumbers.Item(LineArray(i))
MostKey = LineArray(i)
end if
next
Loop
MsgBox MostKey