Search is not available for this dataset
content
stringlengths 0
376M
|
---|
'
L_Welcome_MsgBox_Message_Text = "This script demonstrates how to add/remove snapins from scriptable objects."
L_Welcome_MsgBox_Title_Text = "Windows Scripting Host Sample"
Call Welcome()
' ********************************************************************************
Dim mmc
Dim doc
Dim snapins
Dim frame
Dim views
Dim view
Dim scopenamespace
Dim rootnode
Dim Nodes
Dim scopenode
Dim SnapNode1
Dim Services
Dim Eventlog
Dim OtherData
'get the various objects we'll need
Set mmc = wscript.CreateObject("MMC20.Application")
Set frame = mmc.Frame
Set doc = mmc.Document
Set namespace = doc.ScopeNamespace
Set rootnode = namespace.GetRoot
Set views = doc.views
Set view = views(1)
Set snapins = doc.snapins
mmc.UserControl = true
Set Eventlog = snapins.Add("Event Viewer")
Set Services = snapins.Add("Services", EventLog)
OtherData = "Num Snapins: " & snapins.Count
intRet = MsgBox(OtherData, vbInformation, "Snapins count")
' Enumerate the snapins collection and print the about info for each snapin.
For Each snapin in snapins
SnapinName = snapin.Name
OtherData = "Vendor : " + snapin.Vendor
OtherData = OtherData + ", Version : " + snapin.Version
OtherData = OtherData + ", CLSID : " + snapin.SnapinCLSID
' intRet = MsgBox(OtherData, vbInformation, "About Information for " & SnapinName)
Next
For i = 1 To snapins.count
Set snapin = snapins.Item(i)
SnapinName = snapin.Name
OtherData = "Vendor : " + snapin.Vendor
OtherData = OtherData + ", Version : " + snapin.Version
OtherData = OtherData + ", CLSID : " + snapin.SnapinCLSID
intRet = MsgBox(OtherData, vbInformation, "About Information for " & SnapinName)
Next
snapins.Remove(EventLog)
Set mmc = Nothing
' ********************************************************************************
' *
' * Welcome
' *
Sub Welcome()
Dim intDoIt
intDoIt = MsgBox(L_Welcome_MsgBox_Message_Text, _
vbOKCancel + vbInformation, _
L_Welcome_MsgBox_Title_Text )
If intDoIt = vbCancel Then
WScript.Quit
End If
End Sub
|
VERSION 5.00
Object = "{EAB22AC0-30C1-11CF-A7EB-0000C05BAE0B}#1.1#0"; "shdocvw.dll"
Object = "{F9043C88-F6F2-101A-A3C9-08002B2F49FB}#1.2#0"; "COMDLG32.OCX"
Object = "{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}#2.0#0"; "MSCOMCTL.OCX"
Begin VB.Form Form1
BorderStyle = 1 'Fixed Single
Caption = "XPathTester"
ClientHeight = 9900
ClientLeft = 2055
ClientTop = 1305
ClientWidth = 14415
LinkTopic = "Form1"
MaxButton = 0 'False
MinButton = 0 'False
ScaleHeight = 9900
ScaleWidth = 14415
Begin SHDocVwCtl.WebBrowser WebBrowser1
Height = 8415
Left = 5400
TabIndex = 11
Top = 1200
Width = 8775
ExtentX = 15478
ExtentY = 14843
ViewMode = 0
Offline = 0
Silent = 0
RegisterAsBrowser= 0
RegisterAsDropTarget= 1
AutoArrange = 0 'False
NoClientEdge = 0 'False
AlignLeft = 0 'False
NoWebView = 0 'False
HideFileNames = 0 'False
SingleClick = 0 'False
SingleSelection = 0 'False
NoFolders = 0 'False
Transparent = 0 'False
ViewID = "{0057D0E0-3573-11CF-AE69-08002B2E1262}"
Location = "http:///"
End
Begin MSComctlLib.TreeView TreeView
Height = 9255
Left = 120
TabIndex = 6
Top = 480
Width = 3495
_ExtentX = 6165
_ExtentY = 16325
_Version = 393217
HideSelection = 0 'False
Indentation = 353
Style = 7
Appearance = 1
End
Begin VB.Frame Frame1
Caption = "Query tester"
Height = 9255
Left = 3720
TabIndex = 3
Top = 480
Width = 10575
Begin VB.ComboBox Combo1
Height = 315
Left = 120
TabIndex = 12
Top = 240
Width = 8895
End
Begin VB.Frame Frame2
Caption = "Syntax used"
Height = 855
Left = 120
TabIndex = 8
Top = 8280
Width = 1455
Begin VB.OptionButton optIE5
Caption = "IE5 syntax"
Height = 195
Left = 120
TabIndex = 10
Top = 600
Width = 1215
End
Begin VB.OptionButton optXPath
Caption = "XPath"
Height = 255
Left = 120
TabIndex = 9
Top = 240
Value = -1 'True
Width = 1215
End
End
Begin VB.CommandButton Command3
Caption = "Query!"
Default = -1 'True
Enabled = 0 'False
Height = 375
Left = 9120
TabIndex = 5
Top = 240
Width = 1335
End
Begin VB.ListBox List1
Height = 6885
ItemData = "Form1.frx":0000
Left = 120
List = "Form1.frx":0002
TabIndex = 4
Top = 720
Width = 1455
End
Begin VB.Label NumberLabel
Height = 255
Left = 120
TabIndex = 13
Top = 7680
Width = 1455
End
Begin VB.Label TimeLabel
BackStyle = 0 'Transparent
Height = 255
Left = 120
TabIndex = 7
Top = 7920
Width = 1455
End
End
Begin VB.CommandButton Command2
Caption = "Open"
Height = 325
Left = 13560
TabIndex = 2
Top = 120
Width = 735
End
Begin VB.CommandButton Command1
Caption = "..."
Height = 325
Left = 13080
TabIndex = 1
Top = 120
Width = 375
End
Begin VB.TextBox Text1
Height = 315
Left = 120
TabIndex = 0
Top = 120
Width = 12855
End
Begin MSComDlg.CommonDialog CommonDialog1
Left = 480
Top = 3720
_ExtentX = 847
_ExtentY = 847
_Version = 393216
End
End
Attribute VB_Name = "Form1"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Dim oDoc As MSXML2.DOMDocument
Dim oList As MSXML2.IXMLDOMNodeList
Private p_strTempFile As String
Private Sub Form_Load()
p_strTempFile = Environ$("TEMP") & "\XPathTester.xml"
p_DisplayInWebBrowser "<EMPTY/>"
End Sub
Private Sub Command1_Click()
CommonDialog1.ShowOpen
Text1.Text = CommonDialog1.FileName
End Sub
Private Sub Command2_Click()
Dim oNode As Node
Set oDoc = New MSXML2.DOMDocument
oDoc.async = True
oDoc.Load "file:///" & CommonDialog1.FileName
If Not oDoc.parseError.errorCode = 0 Then
MsgBox "Error loading XML: " & vbCrLf & _
oDoc.parseError.reason & vbCrLf & _
"In: " & oDoc.parseError.srcText
Else
Frame1.Enabled = True
Combo1.Enabled = True
Command3.Enabled = True
TreeView.Nodes.Clear
Set oNode = TreeView.Nodes.Add
oNode.Text = "/ (ROOT)"
Set oNode.Tag = oDoc
oNode.Expanded = True
oNode.Selected = True
AddNode oDoc.documentElement, oNode
End If
End Sub
Private Sub Command3_Click()
Dim i As Integer
Dim contextNode As IXMLDOMNode
Dim liStart As LARGE_INTEGER
Dim liEnd As LARGE_INTEGER
On Error Resume Next
Call QueryPerformanceCounter(liStart)
Set contextNode = TreeView.SelectedItem.Tag
' Set the correct querying syntax
If optIE5.Value = True Then
oDoc.setProperty "SelectionLanguage", "XSLPattern"
Else
oDoc.setProperty "SelectionLanguage", "XPath"
End If
Set oList = contextNode.selectNodes(Combo1.Text)
p_AddStringIfRequired Combo1.Text
List1.Clear
p_DisplayInWebBrowser "<EMPTY/>"
DoEvents
Call QueryPerformanceCounter(liEnd)
TimeLabel.Caption = "Time: " & Format(getSecondsDifference(liStart, liEnd), "##0.000000")
If Err.Number = 0 Then
NumberLabel.Caption = "Total: " & oList.length
DoEvents
If oList.length = 0 Then List1.AddItem "No matching elements"
If (oList.length > 10000) Then
List1.AddItem oList.length & " matching elements"
Else
For i = 1 To oList.length
List1.AddItem CStr(i)
Next
End If
Else
List1.AddItem "Error in query"
NumberLabel.Caption = "Total: 0"
End If
On Error GoTo 0
End Sub
Private Sub List1_Click()
If List1.ListIndex < oList.length Then
p_DisplayInWebBrowser oList.Item(List1.ListIndex).xml
End If
End Sub
Private Sub p_DisplayInWebBrowser(ByVal i_str As String)
FileWrite p_strTempFile, i_str, , True
WebBrowser1.Navigate p_strTempFile
End Sub
Private Function p_Wrap(ByVal i_str As String) As String
Dim intLength As Long
Dim intCurrentPosition As Long
Const intMax As Long = 80
Dim str As String
str = i_str
intLength = Len(i_str)
intCurrentPosition = Int(intLength / intMax) * intMax
Do While (intCurrentPosition > 0)
str = Mid(str, 1, intCurrentPosition) & vbCrLf & Mid(str, intCurrentPosition)
intCurrentPosition = intCurrentPosition - intMax
Loop
p_Wrap = str
End Function
Private Sub AddNode(ByRef oElem As IXMLDOMNode, Optional ByRef oTreeNode As Node)
Dim oNewNode As Node
Dim oNodeList As IXMLDOMNodeList
Dim i As Long
Dim bRoot As Boolean
Set oNewNode = TreeView.Nodes.Add(oTreeNode, tvwChild)
oNewNode.Expanded = False
If TypeOf oTreeNode.Tag Is DOMDocument Then
' This is the root node
oNewNode.Expanded = True
bRoot = True
End If
oNewNode.Text = oElem.nodeName
Set oNewNode.Tag = oElem
If bRoot Then
AddNodeList oElem.childNodes, oNewNode
Else
Set oNewNode = TreeView.Nodes.Add(oNewNode, tvwChild)
oNewNode.Expanded = False
oNewNode.Text = "parsing"
Set oNewNode.Tag = Nothing
End If
End Sub
Private Sub AddNodeList(ByRef oElems As IXMLDOMNodeList, ByRef oTreeNode As Node)
Dim i As Long
For i = 0 To oElems.length - 1
AddNode oElems.Item(i), oTreeNode
Next
End Sub
Private Sub TreeView_Expand(ByVal Node As MSComctlLib.Node)
If Node.children = 1 Then
' Check if the single child is indeed the dummy child
If Node.Child.Tag Is Nothing Then
' Remove the dummy
TreeView.Nodes.Remove (Node.Child.Index)
' Add the child nodes to the treeview
AddNodeList Node.Tag.childNodes, Node
End If
End If
End Sub
Private Sub p_AddStringIfRequired(i_str As String)
Dim intIndex As Long
Dim str As String
str = LCase$(i_str)
For intIndex = 0 To Combo1.ListCount - 1
If (str = LCase$(Combo1.List(intIndex))) Then
Exit Sub
End If
Next
Combo1.AddItem i_str, 0
End Sub
Private Sub TreeView_NodeClick(ByVal Node As MSComctlLib.Node)
Combo1.Text = Replace$(Mid$(Node.FullPath, 9), "\", "/")
p_AddStringIfRequired Combo1.Text
End Sub
|
NEW
10 REM THIS DOESNT WORK REGISTER LOCATIONS HAVE CHANGED
100 TIMADR%=-128
110 COUNTER%=TIMADR%
120 PERIOD%=TIMADR%+4*1
130 ENHANCE%=TIMADR+4*3
140 INC%=TIMADR%+4*2
150 APPLY%=TIMADR%+4*7
160 DIM ICP_START%(2),ICP_STOP%(2)
170 ICP_START%(1)=TIMADR%+4*12:ICP_START%(2)=TIMADR%+4*14
180 ICP_STOP%(1)=TIMADR%+4*13:ICP_STOP%(2)=TIMADR%+4*15
190 OCP_START%(1)=TIMADR%+4*8:OCP_START%(2)=TIMADR%+4*10
200 OCP_STOP%(1)=TIMADR%+4*9:OCP_STOP%(2)=TIMADR%+4*11
210 CONTROL%=TIMADR%+4*6
220 AND_OR%=CONTROL%+1
230 REM set output compare 1 and 2
240 POKE OCP_START%(1)+3,0:POKE OCP_START%(1)+2,0:POKE OCP_START%(1)+1,0:POKE OCP_START%(1),0
250 POKE OCP_STOP%(1)+3,0:POKE OCP_STOP%(1)+2,0:POKE OCP_STOP%(1)+1,10:POKE OCP_STOP%(1),0
260 POKE OCP_START%(2)+3,0:POKE OCP_START%(2)+2,0:POKE OCP_START%(2)+1,0:POKE OCP_START%(2),0
270 POKE OCP_STOP%(2)+3,20:POKE OCP_STOP%(2)+2,250:POKE OCP_STOP%(2)+1,20:POKE OCP_STOP%(2),0
280 POKE APPLY%+1,15: REM apply ocp values
290 REM set timer step (unused)
300 POKE INC%+3,0:POKE INC%+2,0:POKE INC%+1,0:POKE INC%+0,10
310 REM commit timer step (not implemented, not needed)
320 POKE APPLY%,4
330 REM set period
340 POKE PERIOD%+3,250:POKE PERIOD%+2,250:POKE PERIOD%+1,250:POKE PERIOD%+0,250
350 REM set period enhancement
360 POKE ENHANCE%+3,0:POKE ENHANCE%+2,0:POKE ENHANCE%+1,0:POKE ENHANCE%+0,0
370 REM commit timer period and enhancement
380 POKE APPLY%,2+8
390 REM set initial timer value (commited later)
400 POKE COUNTER%+3,1:POKE COUNTER%+2,10:POKE COUNTER%+1,0: POKE COUNTER%,0
410 FOR I%=1 TO 10
420 ?PEEK(COUNTER%+3),PEEK(COUNTER%+2),PEEK(COUNTER%+1),PEEK(COUNTER%)
430 IF I%=5 THEN ?"commit changes":POKE APPLY%,1
440 NEXT
450 REM set capture range 1 and 2
460 POKE ICP_START%(1)+3,0:POKE ICP_START%(1)+2,0:POKE ICP_START%(1)+1,0:POKE ICP_START%(1),0
470 POKE ICP_STOP%(1)+3,20:POKE ICP_STOP%(1)+2,250:POKE ICP_STOP%(1)+1,120:POKE ICP_STOP%(1),250
480 POKE ICP_START%(2)+3,0:POKE ICP_START%(2)+2,0:POKE ICP_START%(2)+1,0:POKE ICP_START%(2),0
490 POKE ICP_STOP%(2)+3,20:POKE ICP_STOP%(2)+2,250:POKE ICP_STOP%(2)+1,120:POKE ICP_STOP%(2),250
500 POKE APPLY%+1,16+32+64+128: REM apply ICP setting
510 REM input capture mixing: 16+32 AND, output compare mixing: 1+2 AND
520 POKE AND_OR%,16+32+1+2
530 POKE APPLY%,64: REM apply control register (and/or setting)
540 SLEEP(0.1)
550 REM blink led0 and led1 to activate input capture
560 POKE -240,0:POKE -240,1:POKE -240,3
570 ?
580 FOR I%=0 TO 15
590 ?PEEK(TIMADR%+3+4*I%),PEEK(TIMADR%+2+4*I%),PEEK(TIMADR%+1+4*I%),PEEK(TIMADR%+4*I%)
600 NEXT
610 POKE -240,0
RUN
|
<reponame>npocmaka/Windows-Server-2003<filename>admin/pchealth/authtools/prodtools/common/xml.bas
Attribute VB_Name = "XML"
Option Explicit
Public Function XMLFindFirstNode( _
ByVal i_DOMNode As MSXML2.IXMLDOMNode, _
ByVal i_strName As String _
) As MSXML2.IXMLDOMNode
Dim DOMNode As MSXML2.IXMLDOMNode
Set XMLFindFirstNode = Nothing
If (i_DOMNode.nodeName = i_strName) Then
Set XMLFindFirstNode = i_DOMNode
Exit Function
ElseIf (Not (i_DOMNode.firstChild Is Nothing)) Then
For Each DOMNode In i_DOMNode.childNodes
Set XMLFindFirstNode = XMLFindFirstNode(DOMNode, i_strName)
If (Not (XMLFindFirstNode Is Nothing)) Then
Exit Function
End If
Next
End If
End Function
Public Function XMLGetAttribute( _
ByVal i_DOMNode As MSXML2.IXMLDOMNode, _
ByVal i_strAttributeName As String _
) As String
On Error Resume Next
XMLGetAttribute = i_DOMNode.Attributes.getNamedItem(i_strAttributeName).nodeValue
End Function
Public Sub XMLSetAttribute( _
ByVal u_DOMNode As MSXML2.IXMLDOMNode, _
ByVal i_strAttributeName As String, _
ByVal i_strAttributeValue As String _
)
Dim Element As MSXML2.IXMLDOMElement
Set Element = u_DOMNode
Element.setAttribute i_strAttributeName, i_strAttributeValue
End Sub
Public Function XMLCreateChildElement( _
ByVal u_DOMNodeParent As MSXML2.IXMLDOMNode, _
ByVal i_strElementName As String, _
ByVal i_strText As String, _
ByVal i_blnNameValuePairsExist As Boolean, _
ByRef i_arrNameValuePairs() As String _
) As MSXML2.IXMLDOMNode
Dim DOMDoc As MSXML2.DOMDocument
Dim Element As MSXML2.IXMLDOMElement
Dim intIndex As Long
Set DOMDoc = u_DOMNodeParent.ownerDocument
Set Element = DOMDoc.createElement(i_strElementName)
If (i_strText <> "") Then
Element.Text = i_strText
End If
Set XMLCreateChildElement = u_DOMNodeParent.appendChild(Element)
If (i_blnNameValuePairsExist) Then
For intIndex = LBound(i_arrNameValuePairs) To UBound(i_arrNameValuePairs)
Element.setAttribute i_arrNameValuePairs(intIndex, 0), _
i_arrNameValuePairs(intIndex, 1)
Next
End If
End Function
Public Sub XMLCopyAttributes( _
ByRef i_DOMNodeSrc As MSXML2.IXMLDOMNode, _
ByRef u_DOMNodeDest As MSXML2.IXMLDOMNode _
)
Dim Attr As MSXML2.IXMLDOMAttribute
Dim Element As MSXML2.IXMLDOMElement
Set Element = u_DOMNodeDest
For Each Attr In i_DOMNodeSrc.Attributes
Element.setAttribute Attr.Name, Attr.Value
Next
End Sub
Public Function XMLCopyDOMTree( _
ByRef i_DOMNodeSrc As MSXML2.IXMLDOMNode, _
ByRef u_DOMNodeParent As MSXML2.IXMLDOMNode _
) As MSXML2.IXMLDOMNode
Dim DOMNode As MSXML2.IXMLDOMNode
Dim DOMElement As MSXML2.IXMLDOMElement
Dim DOMText As MSXML2.IXMLDOMText
Dim DOMAttr As MSXML2.IXMLDOMAttribute
Dim DOMNodeChild As MSXML2.IXMLDOMNode
If (i_DOMNodeSrc.ownerDocument Is u_DOMNodeParent.ownerDocument) Then
Set DOMNode = i_DOMNodeSrc.cloneNode(True)
u_DOMNodeParent.appendChild DOMNode
Else
' Different DOM Nodes, so we really have to copy and
' recreate the node from one DOM Tree to another.
Select Case i_DOMNodeSrc.nodeType
Case NODE_TEXT
Set DOMText = u_DOMNodeParent.ownerDocument.createTextNode(i_DOMNodeSrc.Text)
Set DOMNode = u_DOMNodeParent.appendChild(DOMText)
Case Else
Set DOMElement = u_DOMNodeParent.ownerDocument.createElement(i_DOMNodeSrc.nodeName)
Set DOMNode = u_DOMNodeParent.appendChild(DOMElement)
For Each DOMAttr In i_DOMNodeSrc.Attributes
DOMElement.setAttribute DOMAttr.nodeName, DOMAttr.nodeValue
Next
For Each DOMNodeChild In i_DOMNodeSrc.childNodes
XMLCopyDOMTree DOMNodeChild, DOMNode
Next
End Select
End If
Set XMLCopyDOMTree = DOMNode
End Function
Private Function p_XMLValidChar( _
ByRef i_char As String _
) As Boolean
Dim intAscW As Long
intAscW = AscW(i_char)
' Sometimes AscW returns a negative number. Eg 0x8021 -> 0xFFFF8021
intAscW = intAscW And &HFFFF&
Select Case intAscW
Case &H9&, &HA&, &HD&, &H20& To &HD7FF&, &HE000& To &HFFFD&
p_XMLValidChar = True
Case Else
p_XMLValidChar = False
End Select
End Function
Public Function XMLValidString( _
ByRef i_str As String _
) As Boolean
Dim intIndex As Long
Dim intLength As Long
intLength = Len(i_str)
For intIndex = 1 To intLength
If (Not p_XMLValidChar(Mid$(i_str, intIndex, 1))) Then
XMLValidString = False
Exit Function
End If
Next
XMLValidString = True
End Function
Public Function XMLMakeValidString( _
ByRef i_str As String _
) As String
Dim intIndex As Long
Dim intLength As Long
Dim str As String
XMLMakeValidString = i_str
intLength = Len(i_str)
For intIndex = 1 To intLength
If (Not p_XMLValidChar(Mid$(i_str, intIndex, 1))) Then
XMLMakeValidString = Mid$(XMLMakeValidString, 1, intIndex - 1) & " " & _
Mid$(XMLMakeValidString, intIndex + 1)
End If
Next
End Function
Public Function XMLEscape( _
ByVal i_str As String _
) As String
XMLEscape = XMLMakeValidString(i_str)
XMLEscape = Replace$(XMLEscape, "&", "&")
XMLEscape = Replace$(XMLEscape, "<", "<")
XMLEscape = Replace$(XMLEscape, ">", ">")
XMLEscape = Replace$(XMLEscape, "'", "'")
XMLEscape = Replace$(XMLEscape, """", """)
End Function
Public Function XMLUnEscape( _
ByVal i_str As String _
) As String
XMLUnEscape = i_str
XMLUnEscape = Replace$(XMLUnEscape, """, """")
XMLUnEscape = Replace$(XMLUnEscape, "'", "'")
XMLUnEscape = Replace$(XMLUnEscape, ">", ">")
XMLUnEscape = Replace$(XMLUnEscape, "<", "<")
XMLUnEscape = Replace$(XMLUnEscape, "&", "&")
End Function
Public Function XMLSpecialCharacter( _
ByVal i_chr As String _
) As Boolean
Select Case i_chr
Case """", "'", ">", "<", "&"
XMLSpecialCharacter = True
Case Else
XMLSpecialCharacter = False
End Select
End Function
|
<gh_stars>10-100
VERSION 5.00
Object = "{6B7E6392-850A-101B-AFC0-4210102A8DA7}#1.2#0"; "COMCTL32.OCX"
Object = "{BDC217C8-ED16-11CD-956C-0000C04E4C0A}#1.1#0"; "TABCTL32.OCX"
Begin VB.Form frmVoice
BorderStyle = 0 'None
Caption = "Voice Profile"
ClientHeight = 5730
ClientLeft = 0
ClientTop = 0
ClientWidth = 9480
LinkTopic = "Form1"
MaxButton = 0 'False
MDIChild = -1 'True
MinButton = 0 'False
NegotiateMenus = 0 'False
ScaleHeight = 5730
ScaleWidth = 9480
ShowInTaskbar = 0 'False
Visible = 0 'False
Begin VB.CommandButton cmdAddValue
Caption = "&Add Value"
Enabled = 0 'False
BeginProperty Font
Name = "Small Fonts"
Size = 6
Charset = 0
Weight = 400
Underline = 0 'False
Italic = 0 'False
Strikethrough = 0 'False
EndProperty
Height = 220
Left = 6465
Style = 1 'Graphical
TabIndex = 2
Top = 5520
Visible = 0 'False
Width = 930
End
Begin TabDlg.SSTab SSTab1
Height = 5055
Left = 0
TabIndex = 3
TabStop = 0 'False
Top = 360
Width = 9405
_ExtentX = 16589
_ExtentY = 8916
_Version = 327681
Tabs = 1
TabsPerRow = 8
TabHeight = 794
ShowFocusRect = 0 'False
BeginProperty Font {0BE35203-8F91-11CE-9DE3-00AA004BB851}
Name = "MS Sans Serif"
Size = 8.25
Charset = 0
Weight = 400
Underline = 0 'False
Italic = 0 'False
Strikethrough = 0 'False
EndProperty
TabCaption(0) = " Voice Profile"
TabPicture(0) = "frmVoice.frx":0000
Tab(0).ControlEnabled= -1 'True
Tab(0).Control(0)= "List"
Tab(0).Control(0).Enabled= 0 'False
Tab(0).ControlCount= 1
Begin VB.ListBox List
Columns = 2
Height = 4110
ItemData = "frmVoice.frx":001C
Left = 120
List = "frmVoice.frx":00C1
Style = 1 'Checkbox
TabIndex = 1
Top = 600
Width = 9135
End
End
Begin VB.TextBox Text1
Height = 285
Left = 0
TabIndex = 0
Top = 0
Width = 9375
End
Begin ComctlLib.StatusBar StatusBar1
Align = 2 'Align Bottom
Height = 300
Left = 0
TabIndex = 4
Top = 5430
Width = 9480
_ExtentX = 16722
_ExtentY = 529
SimpleText = ""
_Version = 327682
BeginProperty Panels {0713E89E-850A-101B-AFC0-4210102A8DA7}
NumPanels = 3
BeginProperty Panel1 {0713E89F-850A-101B-AFC0-4210102A8DA7}
AutoSize = 1
Object.Width = 13070
Key = ""
Object.Tag = ""
EndProperty
BeginProperty Panel2 {0713E89F-850A-101B-AFC0-4210102A8DA7}
Style = 6
AutoSize = 2
Object.Width = 1773
MinWidth = 1764
TextSave = "5/12/98"
Key = ""
Object.Tag = ""
EndProperty
BeginProperty Panel3 {0713E89F-850A-101B-AFC0-4210102A8DA7}
Style = 5
AutoSize = 2
Object.Width = 1773
MinWidth = 1764
TextSave = "4:40 PM"
Key = ""
Object.Tag = ""
EndProperty
EndProperty
BeginProperty Font {0BE35203-8F91-11CE-9DE3-00AA004BB851}
Name = "<NAME>"
Size = 8.25
Charset = 0
Weight = 700
Underline = 0 'False
Italic = 0 'False
Strikethrough = 0 'False
EndProperty
End
Begin VB.Label Label1
Caption = "Voice"
Height = 495
Left = 3840
TabIndex = 5
Top = 1920
Width = 1215
End
End
Attribute VB_Name = "frmVoice"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Dim One()
Dim Filename$
Dim Comment(31) As String
Dim First(7)
Const Delim As String = ","
Const HKR As String = "HKR,, VoiceProfile, 1, "
Const Q As String = """"
Const H As String = "&H"
Dim i As Integer
Dim Number As String
Dim Num As Integer
Dim Length As Integer
Dim FirstDword4, FirstDword3, FirstDword2, FirstDword1 As Variant
Dim Which As Integer
Public Sub ClearControl()
ReDim One(List.ListCount - 1)
Dim c As Integer
For c = 0 To List.ListCount - 1
List.Selected(c) = False
One(c) = "0"
Next c
Dim X As Integer
For X = 0 To 7
First(X) = "0"
Next X
Update
Dim strFirst As String
strFirst = Len(HKR)
Text1.SelStart = strFirst
Text1.SelLength = 11
If frmVoice.Visible = False Then
frmVoice.Visible = True
End If
Text1.SetFocus
End Sub
Private Sub cmdAddValue_Click()
frmAddValue.Show
End Sub
Private Sub Form_Load()
ClearControl
ClearControl
' Dim NewString As String
' Dim NewValue As String
' Dim Num As String
' Dim i As Integer
'
' Filename$ = App.Path
' If Right$(Filename$, 1) <> "\" Then Filename$ = Filename$ & "\"
' Filename$ = Filename$ & "Voice.avf"
' Open Filename$ For Input As #1
' Do While Not EOF(1)
' Input #1, NewString, NewValue
' Num = Right$(NewValue, 8)
' While Left$(Num, 1) = "0"
' Num = Mid(Num, 2)
' Wend
' i = Len(Num) - 1
' Num = Left$(Num, 1)
' Select Case Num
' Case "1"
' frmVoice.List.RemoveItem (i * 4)
' frmVoice.List.AddItem NewString, (i * 4)
' frmVoice.List.ItemData((i * 4)) = Right(NewValue, 8)
' Case "2"
' frmVoice.List.RemoveItem ((i * 4) + 1)
' frmVoice.List.AddItem NewString, ((i * 4) + 1)
' frmVoice.List.ItemData(((i * 4) + 1)) = Right(NewValue, 8)
' Case "4"
' frmVoice.List.RemoveItem ((i * 4) + 2)
' frmVoice.List.AddItem NewString, ((i * 4) + 2)
' frmVoice.List.ItemData(((i * 4) + 2)) = Right(NewValue, 8)
' Case "8"
' frmVoice.List.RemoveItem ((i * 4) + 3)
' frmVoice.List.AddItem NewString, ((i * 4) + 3)
' frmVoice.List.ItemData(((i * 4) + 3)) = Right(NewValue, 8)
' End Select
' Loop
' Close #1
Comment(0) = "Set for all voice modems."
Comment(1) = "Modem can play audio to handset and/or report handset hookswitch events."
Comment(2) = "Modem has a speakerphone."
Comment(3) = ""
Comment(4) = ""
Comment(5) = "Wave output uses serial driver."
Comment(6) = "Set if dial string must always end with DialSuffix in voice mode."
Comment(7) = "Modem does not support caller ID."
Comment(8) = "Modem speaker volume can be changed with a multimedia mixer."
Comment(9) = "Force blind dialing after dialtone detection."
Comment(10) = "Speakerphone state must be reset after recording from line."
Comment(11) = "Speakerphone state must be reset after playing to line."
Comment(12) = "Modem does not support distinctive ring."
Comment(13) = "Modem supports distinctive ringing with ring duration (DRON and DROF)."
Comment(14) = "If distinctive ringing is on. Unimodem will not report the first ring."
Comment(15) = "Modem does not report first ring when distinctive ringing is enabled."
Comment(16) = "Modem monitors silence."
Comment(17) = "Modem does not generate DTMF digits in voice mode."
Comment(18) = "Modem does not monitor DTMF digits in voice mode."
Comment(19) = "If set, the UART baud rate will be set before issuing StartPlay or StartRecord commands."
Comment(20) = "If set, the UART baudrate will be reset after StopPlay or StopRecord is issued."
Comment(21) = "Indicates that modem keeps handset disconnected from modem while in voice mode."
Comment(22) = "Indicates the speakerphone cannot be muted."
Comment(23) = "Sierra chipset Voice Modem."
Comment(24) = ""
Comment(25) = "NT5 Voice Bit."
Comment(26) = ""
Comment(27) = ""
Comment(28) = ""
Comment(29) = ""
Comment(30) = ""
Comment(31) = ""
StatusBar1.Panels.Item(1).Text = "Set for all voice modems."
End Sub
Private Sub Update()
Text1.Text = HKR & First(1) & First(0) & Delim & First(3) & First(2) _
& Delim & First(5) & First(4) & Delim & First(7) & First(6)
End Sub
Private Sub Form_Resize()
Text1.Width = frmVoice.Width
SSTab1.Width = frmVoice.Width - 75
SSTab1.Height = frmVoice.Height - 675
List.Height = SSTab1.Height - 645
List.Width = SSTab1.Width - 270
cmdAddValue.Top = frmVoice.Height - 245
cmdAddValue.Left = frmVoice.Width - 3015
End Sub
Private Sub List_Click()
List.Refresh
StatusBar1.Panels.Item(1).Text = Comment(List.ListIndex)
Dim strFirst As String
strFirst = Len(HKR)
Text1.SelStart = strFirst
Text1.SelLength = 11
Text1.SetFocus
End Sub
Private Sub List_ItemCheck(i As Integer)
Number = List.ItemData(i)
Num = Left(Number, 1)
Length = Len(Number) - 1
If List.Selected(i) = True Then
One(Length) = One(Length) + Num
Else
One(Length) = One(Length) - Num
End If
First(Length) = Hex(One(Length))
Update
End Sub
Private Function PasteCheck(i As Integer)
Dim Num As Integer
Dim Mult As Integer
Dim Incoming As String
Select Case i
Case "1"
Incoming = First(0)
Mult = 0
Case "2"
Incoming = First(1)
Mult = 4
Case "3"
Incoming = First(2)
Mult = 8
Case "4"
Incoming = First(3)
Mult = 12
Case "5"
Incoming = First(4)
Mult = 16
Case "6"
Incoming = First(5)
Mult = 20
Case "7"
Incoming = First(6)
Mult = 24
Case "8"
Incoming = First(7)
Mult = 28
End Select
Num = CDec(H & Incoming)
If Num >= 8 Then
Num = Num - 8
List.Selected(3 + Mult) = True
End If
If Num >= 4 Then
Num = Num - 4
List.Selected(2 + Mult) = True
End If
If Num >= 2 Then
Num = Num - 2
List.Selected(1 + Mult) = True
End If
If Num = 1 Then
List.Selected(Mult) = True
End If
End Function
Private Sub GetWord(strString As String)
Dim strSubString As String
Dim lStart As Long
Dim lStop As Long
lStart = 1
lStop = Len(strString)
While lStart < lStop And "1" <> Mid$(strString, lStart, 1) ' Loop until first 1 found
lStart = lStart + 1
Wend
lStop = lStart
While Delim <> Mid$(strString, lStop + 1, 1) And lStop <= Len(strString) ' Loop until next , found
lStop = lStop + 1
Wend
strSubString = Mid$(strString, lStop + 1)
lStart = 1
lStop = Len(strSubString)
While lStart < lStop And "," <> Mid$(strSubString, lStart, 1) ' Loop until first , found
lStart = lStart + 1
Wend
lStop = lStart
While "," <> Mid$(strSubString, lStop + 1, 1) And lStop <= Len(strSubString) ' Loop until last , found
lStop = lStop + 1
Wend
FirstDword1 = Mid$(strSubString, lStart + 1, lStop - 1) ' Grab word found between ,'s
strSubString = Mid$(strSubString, lStop + 1)
Clean (FirstDword1)
FirstDword1 = CleanNum
First(1) = Left(FirstDword1, 1)
First(0) = Right(FirstDword1, 1)
lStart = 1
lStop = Len(strSubString)
While lStart < lStop And "," <> Mid$(strSubString, lStart, 1) ' Loop until first , found
lStart = lStart + 1
Wend
lStop = lStart
While "," <> Mid$(strSubString, lStop + 1, 1) And lStop <= Len(strSubString) ' Loop until last , found
lStop = lStop + 1
Wend
FirstDword2 = Mid$(strSubString, lStart + 1, lStop - 1) ' Grab word found between ,'s
strSubString = Mid$(strSubString, lStop + 1)
Clean (FirstDword2)
FirstDword2 = CleanNum
First(3) = Left(FirstDword2, 1)
First(2) = Right(FirstDword2, 1)
lStart = 1
lStop = Len(strSubString)
While lStart < lStop And "," <> Mid$(strSubString, lStart, 1) ' Loop until first , found
lStart = lStart + 1
Wend
lStop = lStart
While "," <> Mid$(strSubString, lStop + 1, 1) And lStop <= Len(strSubString) ' Loop until last , found
lStop = lStop + 1
Wend
FirstDword3 = Mid$(strSubString, lStart + 1, lStop - 1) ' Grab word found between ,'s
strSubString = Mid$(strSubString, lStop + 1)
Clean (FirstDword3)
FirstDword3 = CleanNum
First(5) = Left(FirstDword3, 1)
First(4) = Right(FirstDword3, 1)
lStart = 1
lStop = Len(strSubString)
While lStart < lStop And "," <> Mid$(strSubString, lStart, 1) ' Loop until first , found
lStart = lStart + 1
Wend
lStop = lStart
While "," <> Mid$(strSubString, lStop + 1, 1) And lStop <= Len(strSubString) ' Loop until last , found
lStop = lStop + 1
Wend
FirstDword4 = Mid$(strSubString, lStart + 1, lStop - 1) ' Grab word found between ,'s
strSubString = Mid$(strSubString, lStop + 1)
Clean (FirstDword4)
FirstDword4 = CleanNum
First(7) = Left(FirstDword4, 1)
First(6) = Right(FirstDword4, 1)
End Sub
Public Sub Paste(Incoming As String)
Dim i As Integer
ClearControl
ClearControl
GetWord (Incoming)
If FirstDword4 = "" Then
Message = MsgBox(Q & Incoming & Q & " is not a valid input")
Else
Update
For i = 1 To 8
PasteCheck (i)
Next i
End If
End Sub
Public Sub EditCopy()
Text1.SelStart = 0
Text1.SelLength = Len(Text1.Text)
Text1.SetFocus
Clipboard.Clear
Clipboard.SetText Text1.Text
End Sub
Public Sub EditPaste()
Paste (Clipboard.GetText)
End Sub
Private Sub Text1_KeyPress(KeyAscii As Integer)
If KeyAscii = 13 Then
Paste (Text1.Text)
End If
End Sub
Private Sub Text1_Click()
Dim Start As Integer
Start = Text1.SelStart
If 21 < Start And Start < 35 Then
If Which = 1 Then Exit Sub
Text1.SelStart = 23
Text1.SelLength = 11
Text1.SetFocus
Which = 1
Else
Which = 0
End If
'MsgBox Start
End Sub
|
<gh_stars>10-100
VERSION 5.00
Begin VB.Form frmAddValue
BorderStyle = 1 'Fixed Single
Caption = "Add Value"
ClientHeight = 1350
ClientLeft = 45
ClientTop = 390
ClientWidth = 9240
Icon = "frmAddValue.frx":0000
LinkTopic = "Form2"
MaxButton = 0 'False
MinButton = 0 'False
ScaleHeight = 1350
ScaleWidth = 9240
ShowInTaskbar = 0 'False
StartUpPosition = 1 'CenterOwner
Begin VB.TextBox txtHex
Height = 285
Left = 3120
MaxLength = 10
TabIndex = 3
Text = "0X"
Top = 840
Width = 2775
End
Begin VB.TextBox txtValue
Height = 285
Left = 240
MaxLength = 21
TabIndex = 1
Top = 840
Width = 2775
End
Begin VB.CheckBox Check1
Caption = "&Reset Voice Profile to original values."
Height = 375
Left = 6120
TabIndex = 4
Top = 780
Width = 1695
End
Begin VB.CommandButton cmdAddValue
Caption = "&Add Value"
Default = -1 'True
Enabled = 0 'False
Height = 495
Left = 7920
TabIndex = 5
Top = 120
Width = 1215
End
Begin VB.CommandButton cmdCancel
Cancel = -1 'True
Caption = "&Cancel"
Height = 495
Left = 7920
TabIndex = 6
Top = 720
Width = 1215
End
Begin VB.Label Label3
AutoSize = -1 'True
Caption = $"frmAddValue.frx":0442
Height = 375
Left = 120
TabIndex = 7
Top = 0
Width = 7575
WordWrap = -1 'True
End
Begin VB.Label Label2
Caption = "&Hex Value (example: 0X02000000)"
Height = 255
Left = 3120
TabIndex = 2
Top = 600
Width = 2775
End
Begin VB.Label Label1
Caption = "&Value Name (example: NT5VoiceBit)"
Height = 255
Left = 240
TabIndex = 0
Top = 600
Width = 2775
End
End
Attribute VB_Name = "frmAddValue"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Dim i As Integer
Dim Filename$
Private Sub Check1_Click()
If Check1.Value = 1 Then
txtValue.Enabled = False
txtValue.Text = ""
txtValue.BackColor = &H8000000F
txtHex.Enabled = False
txtHex.Text = "0X"
txtHex.BackColor = &H8000000F
cmdAddValue.Enabled = True
cmdAddValue.Caption = "R&eset"
cmdAddValue.SetFocus
ElseIf Check1.Value = 0 Then
cmdAddValue.Enabled = False
cmdAddValue.Caption = "&Add Value"
txtValue.Enabled = True
txtValue.BackColor = &H80000005
txtHex.Enabled = True
txtHex.BackColor = &H80000005
End If
End Sub
Private Sub cmdAddValue_Click()
Dim NewString As String
Dim NewValue As String
Dim Num As String
Dim i As Integer
If cmdAddValue.Caption = "R&eset" Then
Response = MsgBox("Profile Calculator will restart to complete this action. Please save any work before continuing", 49, "Reset ProCalc")
If Response = 1 Then
Filename$ = App.Path
If Right$(Filename$, 1) <> "\" Then Filename$ = Filename$ & "\"
Filename$ = Filename$ & "Voice.avf"
Open Filename$ For Output As #1
Do While Not EOF(1)
Input #1, NewString, NewValue
Num = Right$(NewValue, 8)
While Left$(Num, 1) = "0"
Num = Mid(Num, 2)
Wend
i = Len(Num) - 1
Num = Left$(Num, 1)
Select Case Num
Case "1"
frmVoice.List.RemoveItem (i * 4)
frmVoice.List.AddItem "0", (i * 4)
frmVoice.List.ItemData((i * 4)) = "0"
'Comment((i * 4)) = ""
Case "2"
frmVoice.List.RemoveItem ((i * 4) + 1)
frmVoice.List.AddItem "0", ((i * 4) + 1)
frmVoice.List.ItemData(((i * 4) + 1)) = "0"
'Comment((i * 4) + 1) = ""
Case "4"
frmVoice.List.RemoveItem ((i * 4) + 2)
frmVoice.List.AddItem "0", ((i * 4) + 2)
frmVoice.List.ItemData(((i * 4) + 2)) = "0"
'Comment((i * 4) + 2) = ""
Case "8"
frmVoice.List.RemoveItem ((i * 4) + 3)
frmVoice.List.AddItem "0", ((i * 4) + 3)
frmVoice.List.ItemData(((i * 4) + 3)) = "0"
'Comment((i * 4) + 3) = ""
End Select
NewString = ""
NewValue = ""
Loop
Close #1
Unload frmAddValue
Unload fMainForm
Else
Unload frmAddValue
End If
Else
NewString = txtHex.Text & " " & txtValue.Text
NewValue = txtHex.Text
Num = Right$(NewValue, 8)
While Left$(Num, 1) = "0"
Num = Mid(Num, 2)
Wend
i = Len(Num) - 1
Num = Left$(Num, 1)
Select Case Num
Case "1"
If frmVoice.List.ItemData(i * 4) = 0 Then
frmVoice.List.RemoveItem (i * 4)
frmVoice.List.AddItem NewString, (i * 4)
frmVoice.List.ItemData((i * 4)) = Right(NewValue, 8)
Else
Response = MsgBox("Value already in use.", 48)
Unload frmAddValue
Exit Sub
End If
Case "2"
If frmVoice.List.ItemData((i * 4) + 1) = 0 Then
frmVoice.List.RemoveItem ((i * 4) + 1)
frmVoice.List.AddItem NewString, ((i * 4) + 1)
frmVoice.List.ItemData(((i * 4) + 1)) = Right(NewValue, 8)
Else
Response = MsgBox("Value already in use.", 48)
Unload frmAddValue
Exit Sub
End If
Case "4"
If frmVoice.List.ItemData((i * 4) + 2) = 0 Then
frmVoice.List.RemoveItem ((i * 4) + 2)
frmVoice.List.AddItem NewString, ((i * 4) + 2)
frmVoice.List.ItemData(((i * 4) + 2)) = Right(NewValue, 8)
Else
Response = MsgBox("Value already in use.", 48)
Unload frmAddValue
Exit Sub
End If
Case "8"
If frmVoice.List.ItemData((i * 4) + 3) = 0 Then
frmVoice.List.RemoveItem ((i * 4) + 3)
frmVoice.List.AddItem NewString, ((i * 4) + 3)
frmVoice.List.ItemData(((i * 4) + 3)) = Right(NewValue, 8)
Else
Response = MsgBox("Value already in use.", 48)
Unload frmAddValue
Exit Sub
End If
End Select
Open "Voice.avf" For Append As #1
Write #1, NewString, NewValue
Close #1
End If
txtValue.Text = ""
txtHex.Text = "0X"
Check1.Value = 0
Unload frmAddValue
frmVoice.ClearControl
frmVoice.ClearControl
End Sub
Private Sub cmdCancel_Click()
txtValue.Text = ""
txtHex.Text = "0X"
Check1.Value = 0
Me.Hide
Unload frmAddValue
End Sub
Private Sub Form_Load()
txtHex.Text = "0X"
End Sub
Private Sub txtHex_Change()
If Len(txtHex.Text) = 10 And Len(txtValue.Text) <> 0 Then
cmdAddValue.Enabled = True
Else
If Len(txtHex.Text) <> 10 Or Len(txtValue.Text) = 0 Then
cmdAddValue.Enabled = False
End If
End If
End Sub
Private Sub txtValue_Change()
If Len(txtHex.Text) = 10 And Len(txtValue.Text) <> 0 Then
cmdAddValue.Enabled = True
Else
If Len(txtHex.Text) <> 10 Or Len(txtValue.Text) = 0 Then
cmdAddValue.Enabled = False
End If
End If
End Sub
Private Sub txtHex_GotFocus()
txtHex.SelStart = 2
End Sub
Private Sub txtHex_KeyPress(KeyAscii As Integer)
Select Case KeyAscii
Case "8"
Exit Sub
Case "48"
Exit Sub
Case "49"
txtHex.Text = txtHex.Text & "1"
While Len(txtHex.Text) < 10
txtHex.Text = txtHex.Text & "0"
Wend
Exit Sub
Case "50"
txtHex.Text = txtHex.Text & "2"
While Len(txtHex.Text) < 10
txtHex.Text = txtHex.Text & "0"
Wend
Exit Sub
Case "52"
txtHex.Text = txtHex.Text & "4"
While Len(txtHex.Text) < 10
txtHex.Text = txtHex.Text & "0"
Wend
Exit Sub
Case "56"
txtHex.Text = txtHex.Text & "8"
While Len(txtHex.Text) < 10
txtHex.Text = txtHex.Text & "0"
Wend
Exit Sub
Case "120"
KeyAscii = 88
Exit Sub
Case "88"
Exit Sub
Case Else
Beep
KeyAscii = 0
End Select
End Sub
|
<reponame>LaudateCorpus1/RosettaCodeData
Function arithmetic_mean(arr)
sum = 0
For i = 0 To UBound(arr)
sum = sum + arr(i)
Next
arithmetic_mean = sum / (UBound(arr)+1)
End Function
Function geometric_mean(arr)
product = 1
For i = 0 To UBound(arr)
product = product * arr(i)
Next
geometric_mean = product ^ (1/(UBound(arr)+1))
End Function
Function harmonic_mean(arr)
sum = 0
For i = 0 To UBound(arr)
sum = sum + (1/arr(i))
Next
harmonic_mean = (UBound(arr)+1) / sum
End Function
WScript.StdOut.WriteLine arithmetic_mean(Array(1,2,3,4,5,6,7,8,9,10))
WScript.StdOut.WriteLine geometric_mean(Array(1,2,3,4,5,6,7,8,9,10))
WScript.StdOut.WriteLine harmonic_mean(Array(1,2,3,4,5,6,7,8,9,10))
|
<reponame>npocmaka/Windows-Server-2003<filename>admin/wmi/wbem/scripting/test/whistler/objpath/setasclass.vbs
Set obj = CreateObject("WbemScripting.SWbemObjectPath")
obj.Class = "foo"
obj.SetAsClass
WScript.Echo obj.Path
|
<reponame>LaudateCorpus1/RosettaCodeData<filename>Task/Conditional-structures/VBA/conditional-structures-4.vba
Sub C_S_IIF()
Dim myName
myName = 2
Debug.Print IIf(myName = 1, "Bryan", "Justin")
'return : Justin
End Sub
|
Set ofso = CreateObject("Scripting.FileSystemObject")
Set config = ofso.OpenTextFile(ofso.GetParentFolderName(WScript.ScriptFullName)&"\config.txt",1)
config_out = ""
Do Until config.AtEndOfStream
line = config.ReadLine
If Left(line,1) <> "#" And Len(line) <> 0 Then
config_out = config_out & parse_var(line) & vbCrLf
End If
Loop
WScript.Echo config_out
Function parse_var(s)
'boolean false
If InStr(s,";") Then
parse_var = Mid(s,InStr(1,s,";")+2,Len(s)-InStr(1,s,";")+2) & " = FALSE"
'boolean true
ElseIf UBound(Split(s," ")) = 0 Then
parse_var = s & " = TRUE"
'multiple parameters
ElseIf InStr(s,",") Then
var = Left(s,InStr(1,s," ")-1)
params = Split(Mid(s,InStr(1,s," ")+1,Len(s)-InStr(1,s," ")+1),",")
n = 1 : tmp = ""
For i = 0 To UBound(params)
parse_var = parse_var & var & "(" & n & ") = " & LTrim(params(i)) & vbCrLf
n = n + 1
Next
'single var and paramater
Else
parse_var = Left(s,InStr(1,s," ")-1) & " = " & Mid(s,InStr(1,s," ")+1,Len(s)-InStr(1,s," ")+1)
End If
End Function
config.Close
Set ofso = Nothing
|
Function matrix_multiplication(a As Variant, b As Variant) As Variant
matrix_multiplication = WorksheetFunction.MMult(a, b)
End Function
|
Option Explicit
Sub Main()
Dim Div
If CatchDivideByZero(152, 0, Div) Then Debug.Print Div Else Debug.Print "Error"
If CatchDivideByZero(152, 10, Div) Then Debug.Print Div Else Debug.Print "Error"
End Sub
Function CatchDivideByZero(Num, Den, Div) As Boolean
On Error Resume Next
Div = Num / Den
If Err = 0 Then CatchDivideByZero = True
On Error GoTo 0
End Function
|
'
' Enums for IMPCUploadJob.Mode
'
Const UL_MODE_BACKGROUND = &H0
Const UL_MODE_FOREGROUND = &H1
'stop
Set oArguments = wscript.Arguments
If oArguments.length > 0 then
Id = oArguments.Item(0)
End If
History = 0
Compressed = false
PersistToDisk = true
If oArguments.length > 1 then
History = CInt(oArguments.Item(1))
End If
If oArguments.length > 2 then
Compressed = CBool(oArguments.Item(2))
End If
If oArguments.length > 3 then
PersistToDisk = CBool(oArguments.Item(3))
End If
Set obj = CreateObject( "UploadManager.MPCUpload" )
Set job = obj.CreateJob()
job.Sig = "{2B12E858-F61B-11d2-938E-00C04F72DAF7}"
'job.Server = "http://localhost/pchealth/uploadserver.dll"
'job.Server = "http://pchts1/pchealth_esc/uploadserver.dll"
'job.Server = "http://beta.mspchealth.com/pchealth_esc/UpLoadServer.dll"
job.Server = "http://dmassare2/pchealth/uploadserver.dll"
'job.Server = "http://172.16.17.32/pchealth_esc/UpLoadServer.dll"
job.ProviderID = "Esc"
job.Mode = UL_MODE_BACKGROUND
job.Mode = UL_MODE_FOREGROUND
job.History = History
job.Compressed = Compressed
job.PersistToDisk = PersistToDisk
'job.UserName = "davide&"
'job.Password = "<PASSWORD> +"
If Id <> "" Then
job.JobID = ID
End If
wscript.echo job.JobID
|
Option Explicit
Sub Main()
Dim Lines(9) As String, i&
'Input
Lines(0) = "------------- Ice And Fire -------------"
Lines(1) = ""
Lines(2) = "fire, in end will world the say Some"
Lines(3) = "ice. in say Some"
Lines(4) = "desire of tasted I've what From"
Lines(5) = "fire. favor who those with hold I"
Lines(6) = ""
Lines(7) = "... elided paragraph last ..."
Lines(8) = ""
Lines(9) = "<NAME> -----------------------"
'Output
For i = 0 To 9
Debug.Print ReverseLine(Lines(i), " ")
Next
End Sub
Private Function ReverseLine(Line As String, Optional Separat As String) As String
Dim T, R, i&, j&, deb&, fin&
If Len(Line) = 0 Then
ReverseLine = vbNullString
Else
If Separat = "" Then Separat = " "
T = Split(Line, Separat)
ReDim R(UBound(T)): j = LBound(T)
deb = UBound(T): fin = deb / 2
For i = deb To fin Step -1
R(j) = T(i)
R(i) = T(j)
j = j + 1
Next i
ReverseLine = Join(R, Separat)
End If
End Function
|
<reponame>npocmaka/Windows-Server-2003
on error resume next
set s = GetObject("winmgmts:root\default")
set cimomid = s.Get("__cimomidentification=@")
if err <> 0 then
WScript.Echo ErrNumber, Err.Source, Err.Description
else
WScript.Echo cimomid.path_.displayname
WScript.Echo cimomid.versionusedtocreatedb
end if
|
<gh_stars>1-10
Public Sub test()
'LTrim trims leading spaces
'RTrim trims tailing spaces
'Trim trims both leading and tailing spaces
s = " trim "
Debug.Print """" & s & """"
Debug.Print """" & LTrim(s) & """"
Debug.Print """" & RTrim(s) & """"
Debug.Print """" & WorksheetFunction.trim(s) & """"
'these functions do not remove tabs or newlines
End Sub
|
<filename>Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/tests/syntax/visual_basic.vb<gh_stars>10-100
' Visual Basic Hello World
' Some more comments about this file
VERSION 4.00
Begin VB.Form Form1
Caption = "Hello"
ClientHeight = 6030
ClientLeft = 1095
ClientTop = 1515
ClientWidth = 6720
Height = 6435
Left = 1035
LinkTopic = "Form1"
ScaleHeight = 6030
ScaleWidth = 6720
Top = 1170
Width = 6840
Begin VB.CommandButton Command1
Caption = "Hello World"
Height = 975
Left = 2040
TabIndex = 0
Top = 2280
Width = 2535
End
End
Attribute VB_Name = "Form1"
Attribute VB_Creatable = False
Attribute VB_Exposed = False
Private Sub Command1_Click()
Cls
Print "Hello World"
End Sub
|
Private Function agm(a As Double, g As Double, Optional tolerance As Double = 0.000000000000001) As Double
Do While Abs(a - g) > tolerance
tmp = a
a = (a + g) / 2
g = Sqr(tmp * g)
Debug.Print a
Loop
agm = a
End Function
Public Sub main()
Debug.Print agm(1, 1 / Sqr(2))
End Sub
|
<filename>admin/pchealth/authtools/prodtools/applets/miscfixes/main.bas
Attribute VB_Name = "Main"
Option Explicit
Public Sub MainFunction( _
ByVal i_strCABIn As String, _
ByVal i_strCABOut As String, _
ByVal i_strSubSiteXML As String, _
ByVal i_strHHT As String, _
ByVal i_blnPopulateHelpImage As Boolean _
)
On Error GoTo LError
Dim strFolder As String
Dim intErrorNumber As Long
strFolder = Cab2Folder(i_strCABIn)
If (i_strSubSiteXML <> "") Then
MarkSubSites strFolder, i_strSubSiteXML
End If
If (i_strHHT <> "") Then
AddHHT strFolder, i_strHHT
End If
If (i_blnPopulateHelpImage) Then
PopulateHelpImage strFolder
End If
Folder2Cab strFolder, i_strCABOut
LEnd:
DeleteCabFolder strFolder
Exit Sub
LError:
frmMain.Output Err.Description, LOGGING_TYPE_ERROR_E
intErrorNumber = Err.Number
DeleteCabFolder strFolder
Err.Raise intErrorNumber
End Sub
|
dim a
set a = new accumulator
x = a( 1 )
a 5
dim b
set b = new accumulator
b 3
wscript.echo a(2.3)
|
<filename>admin/pchealth/authtools/prodtools/common/databaseandhht.bas
Attribute VB_Name = "DatabaseAndHHT"
Option Explicit
Public Const ROOT_TID_C As Long = 1
Public Const INVALID_ID_C As Long = -1
Public Const NODE_FOR_ORPHANS_C As String = "Orphaned Nodes and Topics"
Public Const ALL_SKUS_C As Long = &HFFFFFFFF
Public Const MAX_TITLE_LENGTH_C As Long = 120
Public Const MAX_KEYWORD_LENGTH_C As Long = 120
Public Const PREFERRED_ORDER_DELTA_C As Long = 20000
Public Const MAX_ORDER_C As Long = 2000000000
Public Const LOC_INCLUDE_ALL_C As String = "ALL"
Public Const LOC_INCLUDE_ENU_C As String = "ENU"
Public Const LOC_INCLUDE_LOC_C As String = "LOC"
Public Const NAVMODEL_DEFAULT_NUM_C As Long = 0
Public Const NAVMODEL_SERVER_NUM_C As Long = 1
Public Const NAVMODEL_DESKTOP_NUM_C As Long = 2
Public Const NAVMODEL_DEFAULT_STR_C As String = "Default"
Public Const NAVMODEL_SERVER_STR_C As String = "Server"
Public Const NAVMODEL_DESKTOP_STR_C As String = "Desktop"
Public Const AG_CORE_MAX_C As Long = 1000
Public Const AG_MICROSOFT_INTERNAL_MAX_C As Long = 10000
' Values in the DBParameters table
Public Const DB_VERSION_C As String = "DBVersion"
Public Const PRODUCT_ID_C As String = "ProductId"
Public Const PRODUCT_VERSION_C As String = "ProductVersion"
Public Const DISPLAY_NAME_C As String = "DisplayName"
Public Const BROKEN_LINK_WORKING_DIR_C As String = "BrokenLinkWorkingDir"
Public Const MINIMUM_KEYWORD_VALIDATION_C As String = "MinimumKeywordValidation"
Public Const AUTHORING_GROUP_C As String = "AuthoringGroup"
Public Const VENDOR_STRING_C As String = "VendorString"
Public Const DOM_FRAGMENT_PKG_C As String = "DomFragmentPackageDesc"
Public Const DOM_FRAGMENT_HHT_C As String = "DomFragmentHHT"
Public Const FILES_TO_INCLUDE_C As String = "FilesToInclude"
Public Const OPERATORS_AND_C As String = "OperatorsAnd"
Public Const OPERATORS_OR_C As String = "OperatorsOr"
Public Const OPERATORS_NOT_C As String = "OperatorsNot"
Public Const LOCK_KEYWORDS_C As String = "LockKeywords"
Public Const LOCK_STOP_SIGNS_C As String = "LockStopSigns"
Public Const LOCK_STOP_WORDS_C As String = "LockStopWords"
Public Const LOCK_SYNONYMS_C As String = "LockSynonyms"
Public Const LOCK_SYNONYM_SETS_C As String = "LockSynonymSets"
Public Const LOCK_TAXONOMY_C As String = "LockTaxonomy"
Public Const LOCK_TYPES_C As String = "LockTypes"
Public Const HHT_TAXONOMY_ENTRIES_C As String = "TAXONOMY_ENTRIES"
Public Const HHT_TAXONOMY_ENTRY_C As String = "TAXONOMY_ENTRY"
Public Const HHT_METADATA_C As String = "METADATA"
' All Caps => Used in real HHT recognized by HcUpdate
Public Const HHT_CATEGORY_C As String = "CATEGORY"
Public Const HHT_ENTRY_C As String = "ENTRY"
Public Const HHT_URI_C As String = "URI"
Public Const HHT_ICONURI_C As String = "ICONURI"
Public Const HHT_TITLE_C As String = "TITLE"
Public Const HHT_DESCRIPTION_C As String = "DESCRIPTION"
Public Const HHT_TYPE_C As String = "TYPE"
Public Const HHT_VISIBLE_C As String = "VISIBLE"
Public Const HHT_ACTION_C As String = "ACTION"
Public Const HHT_KEYWORD_C As String = "KEYWORD"
Public Const HHT_PRIORITY_C As String = "PRIORITY"
Public Const HHT_INSERTMODE_C As String = "INSERTMODE"
Public Const HHT_INSERTLOCATION_C As String = "INSERTLOCATION"
Public Const HHT_SUBSITE_C As String = "SUBSITE"
Public Const HHT_NAVIGATIONMODEL_C As String = "NAVIGATIONMODEL"
Public Const HHT_STOPWORD_C As String = "STOPWORD"
Public Const HHT_STOPSIGN_C As String = "STOPSIGN"
Public Const HHT_CONTEXT_C As String = "CONTEXT"
Public Const HHTVAL_ADD_C As String = "ADD"
Public Const HHTVAL_TOP_C As String = "TOP"
Public Const HHTVAL_AFTER_NODE_C As String = "AFTER_NODE"
Public Const HHTVAL_AFTER_TOPIC_C As String = "AFTER_TOPIC"
Public Const HHTVAL_ANYWHERE_C As String = "ANYWHERE"
Public Const HHTVAL_ENDOFWORD_C As String = "ENDOFWORD"
' Lower case => internal attributes, not recognized by HcUpdate
Public Const HHT_dbparameters_C As String = "dbparameters"
Public Const HHT_dbparameter_C As String = "dbparameter"
Public Const HHT_name_C As String = "name"
Public Const HHT_value_C As String = "value"
Public Const HHT_tid_C As String = "tid"
Public Const HHT_comments_C As String = "comments"
Public Const HHT_locinclude_C As String = "locinclude"
Public Const HHT_skus_C As String = "skus"
Public Const HHT_modifiedtime_C As String = "modifiedtime"
Public Const HHT_username_C As String = "username"
Public Const HHT_leaf_C As String = "leaf"
Public Const HHT_parenttid_C As String = "parenttid"
Public Const HHT_basefile_C As String = "basefile"
Public Const HHT_keywords_C As String = "keywords"
Public Const HHT_orderunderparent_C As String = "orderunderparent"
Public Const HHT_authoringgroup_C As String = "authoringgroup"
Public Const HHT_allowedskus_C As String = "allowedskus"
' For a Node, if CATEGORY is "A" and ENTRY is "B", then category2 is "A/B"
Public Const HHT_category2_C As String = "category2"
' Broken link attributes
Public Const HHT_brokenlinkwinme_C As String = "blwm"
Public Const HHT_brokenlinkstd_C As String = "blst"
Public Const HHT_brokenlinkpro_C As String = "blpr"
Public Const HHT_brokenlinkpro64_C As String = "blpr64"
Public Const HHT_brokenlinksrv_C As String = "blsr"
Public Const HHT_brokenlinkadv_C As String = "blad"
Public Const HHT_brokenlinkadv64_C As String = "blad64"
Public Const HHT_brokenlinkdat_C As String = "bldt"
Public Const HHT_brokenlinkdat64_C As String = "bldt64"
Public Enum SKU_E
SKU_STANDARD_E = &H1
SKU_PROFESSIONAL_E = &H2
SKU_SERVER_E = &H4
SKU_ADVANCED_SERVER_E = &H8
SKU_DATA_CENTER_SERVER_E = &H10
SKU_PROFESSIONAL_64_E = &H20
SKU_ADVANCED_SERVER_64_E = &H40
SKU_DATA_CENTER_SERVER_64_E = &H80
SKU_WINDOWS_MILLENNIUM_E = &H100
SKU_DESKTOP_ALL_E = SKU_STANDARD_E Or SKU_PROFESSIONAL_E Or SKU_PROFESSIONAL_64_E
SKU_SERVER_ALL_E = SKU_SERVER_E Or SKU_ADVANCED_SERVER_E Or SKU_DATA_CENTER_SERVER_E Or SKU_ADVANCED_SERVER_64_E Or SKU_DATA_CENTER_SERVER_64_E
SKU_ALL_E = SKU_DESKTOP_ALL_E Or SKU_SERVER_ALL_E
End Enum
Public Enum HELPDIR_E
HELPDIR_HELP_MSITS_E = 0
HELPDIR_HELP_HCP_E = 1
HELPDIR_SYSTEM_E = 2
HELPDIR_VENDOR_E = 3
End Enum
Public Enum CONTEXT_E
CONTEXT_ANYWHERE_E = 0
CONTEXT_AT_END_OF_WORD_E = 1
End Enum
Public Function XmlSKU( _
ByVal i_enumSKU As SKU_E _
) As String
Select Case i_enumSKU
Case SKU_STANDARD_E
XmlSKU = "Personal_32"
Case SKU_PROFESSIONAL_E
XmlSKU = "Professional_32"
Case SKU_SERVER_E
XmlSKU = "Server_32"
Case SKU_ADVANCED_SERVER_E
XmlSKU = "AdvancedServer_32"
Case SKU_DATA_CENTER_SERVER_E
XmlSKU = "DataCenter_32"
Case SKU_PROFESSIONAL_64_E
XmlSKU = "Professional_64"
Case SKU_ADVANCED_SERVER_64_E
XmlSKU = "AdvancedServer_64"
Case SKU_DATA_CENTER_SERVER_64_E
XmlSKU = "DataCenter_64"
Case SKU_SERVER_ALL_E
XmlSKU = "Server"
Case SKU_DESKTOP_ALL_E
XmlSKU = "Desktop"
Case SKU_ALL_E
XmlSKU = "All"
Case SKU_WINDOWS_MILLENNIUM_E
XmlSKU = "WinMe" ' Here for conveniece only.
End Select
End Function
Public Function DisplayNameForSKU( _
ByVal i_enumSKU As SKU_E _
) As String
Select Case i_enumSKU
Case SKU_STANDARD_E
DisplayNameForSKU = "32-bit Personal"
Case SKU_PROFESSIONAL_E
DisplayNameForSKU = "32-bit Professional"
Case SKU_SERVER_E
DisplayNameForSKU = "32-bit Server"
Case SKU_ADVANCED_SERVER_E
DisplayNameForSKU = "32-bit Advanced Server"
Case SKU_DATA_CENTER_SERVER_E
DisplayNameForSKU = "32-bit Datacenter Server"
Case SKU_PROFESSIONAL_64_E
DisplayNameForSKU = "64-bit Professional"
Case SKU_ADVANCED_SERVER_64_E
DisplayNameForSKU = "64-bit Advanced Server"
Case SKU_DATA_CENTER_SERVER_64_E
DisplayNameForSKU = "64-bit Datacenter Server"
Case SKU_WINDOWS_MILLENNIUM_E
DisplayNameForSKU = "Windows Me"
Case SKU_DESKTOP_ALL_E
DisplayNameForSKU = "All Desktop"
Case SKU_SERVER_ALL_E
DisplayNameForSKU = "All Server"
Case SKU_ALL_E
DisplayNameForSKU = "All"
End Select
End Function
Public Function AbbreviationToSKU( _
ByVal i_strSKU As String _
) As Long
Dim strSKU As String
strSKU = UCase$(i_strSKU)
AbbreviationToSKU = 0
Select Case strSKU
Case "STD"
AbbreviationToSKU = SKU_STANDARD_E
Case "PRO"
AbbreviationToSKU = SKU_PROFESSIONAL_E
Case "SRV"
AbbreviationToSKU = SKU_SERVER_E
Case "ADV"
AbbreviationToSKU = SKU_ADVANCED_SERVER_E
Case "DAT"
AbbreviationToSKU = SKU_DATA_CENTER_SERVER_E
Case "PRO64"
AbbreviationToSKU = SKU_PROFESSIONAL_64_E
Case "ADV64"
AbbreviationToSKU = SKU_ADVANCED_SERVER_64_E
Case "DAT64"
AbbreviationToSKU = SKU_DATA_CENTER_SERVER_64_E
Case "WINME"
AbbreviationToSKU = SKU_WINDOWS_MILLENNIUM_E
End Select
End Function
Public Function FormatKeywordsForTaxonomy( _
ByVal i_strKeywords As String _
) As String
' This function sorts the Keywords and removes duplicates.
On Error GoTo LErrorHandler
Dim arrStrKIDs() As String
Dim arrKIDs() As Long
Dim intIndex1 As Long
Dim intIndex2 As Long
Dim intKID As Long
Dim intLastKID As Long
If (Trim$(i_strKeywords) = "") Then
FormatKeywordsForTaxonomy = ""
Exit Function
End If
arrStrKIDs = Split(i_strKeywords, " ")
ReDim arrKIDs(UBound(arrStrKIDs))
For intIndex1 = LBound(arrStrKIDs) To UBound(arrStrKIDs)
If (arrStrKIDs(intIndex1) <> "") Then
arrKIDs(intIndex2) = arrStrKIDs(intIndex1)
intIndex2 = intIndex2 + 1
End If
Next
ReDim Preserve arrKIDs(intIndex2 - 1)
InsertionSort arrKIDs
FormatKeywordsForTaxonomy = " "
intLastKID = INVALID_ID_C
For intIndex1 = LBound(arrKIDs) To UBound(arrKIDs)
intKID = arrKIDs(intIndex1)
If (intKID <> intLastKID) Then
intLastKID = intKID
FormatKeywordsForTaxonomy = FormatKeywordsForTaxonomy & intKID & " "
End If
Next
Exit Function
LErrorHandler:
Err.Clear
Err.Raise errBadKeywordsFormat
End Function
Public Function NavModelNumber( _
ByVal i_strNavModel As String _
) As String
If (i_strNavModel = "") Then
NavModelNumber = NAVMODEL_DEFAULT_NUM_C
Exit Function
End If
Select Case i_strNavModel
Case NAVMODEL_DEFAULT_STR_C
NavModelNumber = NAVMODEL_DEFAULT_NUM_C
Case NAVMODEL_SERVER_STR_C
NavModelNumber = NAVMODEL_SERVER_NUM_C
Case NAVMODEL_DESKTOP_STR_C
NavModelNumber = NAVMODEL_DESKTOP_NUM_C
End Select
End Function
Public Function NavModelString( _
ByVal i_strNavModel As String _
) As String
Dim intNavModel As Long
If (i_strNavModel = "") Then
NavModelString = NAVMODEL_DEFAULT_STR_C
Exit Function
Else
intNavModel = i_strNavModel
End If
Select Case intNavModel
Case NAVMODEL_DEFAULT_NUM_C
NavModelString = NAVMODEL_DEFAULT_STR_C
Case NAVMODEL_SERVER_NUM_C
NavModelString = NAVMODEL_SERVER_STR_C
Case NAVMODEL_DESKTOP_NUM_C
NavModelString = NAVMODEL_DESKTOP_STR_C
End Select
End Function
Public Function HhtPreamble( _
ByVal u_DomDoc As MSXML2.DOMDocument, _
ByVal i_blnNestedTaxonomyEntries As Boolean _
) As MSXML2.IXMLDOMNode
Dim PI As MSXML2.IXMLDOMProcessingInstruction
Dim DOMComment As MSXML2.IXMLDOMComment
Dim Node As MSXML2.IXMLDOMNode
Dim Element As MSXML2.IXMLDOMElement
u_DomDoc.preserveWhiteSpace = True
Set PI = u_DomDoc.createProcessingInstruction("xml", "version='1.0' encoding='UTF-16'")
u_DomDoc.appendChild PI
Set DOMComment = u_DomDoc.createComment("Insert your comments here")
u_DomDoc.appendChild DOMComment
Set Element = u_DomDoc.createElement(HHT_METADATA_C)
Set Node = u_DomDoc.appendChild(Element)
If (i_blnNestedTaxonomyEntries) Then
Set Element = u_DomDoc.createElement(HHT_TAXONOMY_ENTRIES_C)
Set Node = Node.appendChild(Element)
End If
Set HhtPreamble = Node
End Function
Public Function TableExists( _
ByVal i_Catalog As ADOX.Catalog, _
ByVal i_strTableName As String _
) As Boolean
Dim tbl As ADOX.Table
Dim strTableName As String
TableExists = False
strTableName = UCase$(i_strTableName)
For Each tbl In i_Catalog.Tables
If (strTableName = UCase$(tbl.Name)) Then
TableExists = True
Exit For
End If
Next
End Function
Public Function ColumnExists( _
ByVal i_Catalog As ADOX.Catalog, _
ByVal i_strTableName As String, _
ByVal i_strColumnName As String _
) As Boolean
Dim col As Column
Dim strColumnName As String
ColumnExists = False
strColumnName = UCase$(i_strColumnName)
For Each col In i_Catalog.Tables(i_strTableName).Columns
If (UCase$(col.Name) = strColumnName) Then
ColumnExists = True
Exit For
End If
Next
End Function
Public Function DeleteTable( _
ByVal i_Catalog As ADOX.Catalog, _
ByVal i_strTableName As String _
) As Boolean
On Error GoTo LErrorHandler
If (TableExists(i_Catalog, i_strTableName)) Then
i_Catalog.Tables.Delete i_strTableName
End If
DeleteTable = True
Exit Function
LErrorHandler:
DeleteTable = False
End Function
|
<filename>Task/Day-of-the-week/VBA/day-of-the-week.vba
Option Explicit
Sub MainDayOfTheWeek()
Debug.Print "Xmas will be a Sunday in : " & XmasSunday(2008, 2121)
End Sub
Private Function XmasSunday(firstYear As Integer, lastYear As Integer) As String
Dim i As Integer, temp$
For i = firstYear To lastYear
If Weekday(CDate("25/12/" & i)) = vbSunday Then temp = temp & ", " & i
Next
XmasSunday = Mid(temp, 2)
End Function
|
Dim doorIsOpen(100), pass, currentDoor, text
For currentDoor = 0 To 99
doorIsOpen(currentDoor) = False
Next
For pass = 0 To 99
For currentDoor = pass To 99 Step pass + 1
doorIsOpen(currentDoor) = Not doorIsOpen(currentDoor)
Next
Next
For currentDoor = 0 To 99
text = "Door #" & currentDoor + 1 & " is "
If doorIsOpen(currentDoor) Then
text = text & "open."
Else
text = text & "closed."
End If
WScript.Echo(text)
Next
|
Option Explicit
Private Type Aliquot
Sequence() As Double
Classification As String
End Type
Sub Main()
Dim result As Aliquot, i As Long, j As Double, temp As String
'display the classification and sequences of the numbers one to ten inclusive
For j = 1 To 10
result = Aliq(j)
temp = vbNullString
For i = 0 To UBound(result.Sequence)
temp = temp & result.Sequence(i) & ", "
Next i
Debug.Print "Aliquot seq of " & j & " : " & result.Classification & " " & Left(temp, Len(temp) - 2)
Next j
'show the classification and sequences of the following integers, in order:
Dim a
'15 355 717 786 080 : impossible in VBA ==> out of memory
a = Array(11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488)
For j = LBound(a) To UBound(a)
result = Aliq(CDbl(a(j)))
temp = vbNullString
For i = 0 To UBound(result.Sequence)
temp = temp & result.Sequence(i) & ", "
Next i
Debug.Print "Aliquot seq of " & a(j) & " : " & result.Classification & " " & Left(temp, Len(temp) - 2)
Next
End Sub
Private Function Aliq(Nb As Double) As Aliquot
Dim s() As Double, i As Long, temp, j As Long, cpt As Long
temp = Array("non-terminating", "Terminate", "Perfect", "Amicable", "Sociable", "Aspiring", "Cyclic")
ReDim s(0)
s(0) = Nb
For i = 1 To 15
cpt = cpt + 1
ReDim Preserve s(cpt)
s(i) = SumPDiv(s(i - 1))
If s(i) > 140737488355328# Then Exit For
If s(i) = 0 Then j = 1
If s(1) = s(0) Then j = 2
If s(i) = s(0) And i > 1 And i <> 2 Then j = 4
If s(i) = s(i - 1) And i > 1 Then j = 5
If i >= 2 Then
If s(2) = s(0) Then j = 3
If s(i) = s(i - 2) And i <> 2 Then j = 6
End If
If j > 0 Then Exit For
Next
Aliq.Classification = temp(j)
Aliq.Sequence = s
End Function
Private Function SumPDiv(n As Double) As Double
'returns the sum of the Proper divisors of n
Dim j As Long, t As Long
If n > 1 Then
For j = 1 To n \ 2
If n Mod j = 0 Then t = t + j
Next
End If
SumPDiv = t
End Function
|
<filename>admin/wmi/wbem/scripting/test/vbscript/ntevent.vbs
on error resume next
set events = GetObject("winmgmts:").ExecNotificationQuery _
("select * from __instancecreationevent where targetinstance isa 'Win32_NTLogEvent'")
if err <> 0 then
WScript.Echo Err.Description, Err.Number, Err.Source
end if
do
set NTEvent = events.nextevent (1000)
if err <> 0 then
WScript.Echo Err.Number, Err.Description, Err.Source
else
WScript.Echo NTEvent.TargetInstance.Message
end if
exit do
loop
WScript.Echo "finished"
|
'http://rosettacode.org/wiki/Van_der_Corput_sequence
'Van der Corput Sequence fucntion call = VanVanDerCorput(number,base)
Base2 = "0" : Base3 = "0" : Base4 = "0" : Base5 = "0"
Base6 = "0" : Base7 = "0" : Base8 = "0" : Base9 = "0"
l = 1
h = 1
Do Until l = 9
'Set h to the value of l after each function call
'as it sets it to 0 - see lines 37 to 40.
Base2 = Base2 & ", " & VanDerCorput(h,2) : h = l
Base3 = Base3 & ", " & VanDerCorput(h,3) : h = l
Base4 = Base4 & ", " & VanDerCorput(h,4) : h = l
Base5 = Base5 & ", " & VanDerCorput(h,5) : h = l
Base6 = Base6 & ", " & VanDerCorput(h,6) : h = l
l = l + 1
Loop
WScript.Echo "Base 2: " & Base2
WScript.Echo "Base 3: " & Base3
WScript.Echo "Base 4: " & Base4
WScript.Echo "Base 5: " & Base5
WScript.Echo "Base 6: " & Base6
'Van der Corput Sequence
Function VanDerCorput(n,b)
k = RevString(Dec2BaseN(n,b))
For i = 1 To Len(k)
VanDerCorput = VanDerCorput + (CLng(Mid(k,i,1)) * b^-i)
Next
End Function
'Decimal to Base N Conversion
Function Dec2BaseN(q,c)
Dec2BaseN = ""
Do Until q = 0
Dec2BaseN = CStr(q Mod c) & Dec2BaseN
q = Int(q / c)
Loop
End Function
'Reverse String
Function RevString(s)
For j = Len(s) To 1 Step -1
RevString = RevString & Mid(s,j,1)
Next
End Function
|
Dim coll As New Collection
coll.Add "apple"
coll.Add "banana"
|
'Fhash is a file containing the line we
'want to replace form ?_hash.txt. NHash is
'the hash to replace it.
DIM FSO,HashTextFileName,HashTextFile,HashTextFileLine,MyVar,FirstArg
DIM HashTextFileOutName,HashTextFileOut,HashTextFileOutLine
DIM NHash,FHashFileName,NHashFileName,FHashFile,NHashFile,FHashText,NHashText,Ptr,SystemCommand
Set FSO=CreateObject("Scripting.FileSystemObject")
'Check for help
FirstArg=Wscript.Arguments(0)
If FirstArg="/?" then
Usage
End if
If FirstArg="-?" then
Usage
End if
If FirstArg="?" then
Usage
End if
FHashFileName=FirstArg
NHashFileName=Wscript.Arguments(1)
HashTextFileName=Wscript.Arguments(2)
If not FSO.FileExists (FHashFileName) then
Wscript.Stdout.Writeline("Cannot find" & FHashFileName)
WScript.Quit(1)
End If
If not FSO.FileExists (NHashFileName) then
Wscript.Stdout.Writeline("Cannot find" & NHashFileName)
WScript.Quit(1)
End If
If not FSO.FileExists (HashTextFileName) then
Wscript.Stdout.Writeline("Cannot find" & HashTextFileName)
WScript.Quit(1)
End If
Set FHashFile=FSO.GetFile(FHashFileName)
Set NHashFile=FSO.GetFile(NHashFileName)
Set FHashText=FHashFile.OpenAsTextStream()
Set NHashText=NHashFile.OpenAsTextStream()
'Get the filename
While not FHashText.AtEndOfStream '& not done
FHashLine=FHashText.Readline
' now we have the line from FHash.tmp
' we need to parse out the path\filename and the hash
Ptr = Instr(FHashLine,"=")
FilePath = Left(FHashLine,Ptr)
' if Ptr > 0 then
' done=true
' FilePath = Left(FHashLine,Ptr)
' end if
Wend
'Now get the new hash
While not NHashText.AtEndOfStream
NHashLine=NHashText.Readline
NHash=NHashLine
Wend
Set HashTextFile=FSO.GetFile(HashTextFileName)
Set HashTextFileText=HashTextFile.OpenAsTextStream()
Ptr=InStr(HashTextFileName,".")
HashTextFileOutName=Left(HashTextFileName,Ptr)
HashTextFileOutName=HashTextFileOutName&"tmp"
if FSO.FileExists (HashTextFileOutName) then
FSO.DeleteFile(HashTextFileOutName)
End If
Set HashTextFileOutText=FSO.CreateTextFile(HashTextFileOutName)
While not HashTextFileText.AtEndOfStream
HashTextFileLine=HashTextFileText.Readline
' now we need to check if the line begins with our name
' if it doesn't, just append to the tmp file
' if it does, replace the line with the new one.
Ptr=InStr(HashTextFileLine,"=")
if Left(HashTextFileLine,Ptr)=FilePath then
' do our replacement here
HashTextFileOutText.Writeline FilePath & NHash
else
' do our append here
HashTextFileOutText.Writeline HashTextFileLine
End If
Wend
' now rename the tmp file to the txt file.
' system call is easiest here.
Set ShellObj = CreateObject("WScript.Shell")
myVar="mv " & HashTextFileOutName & " " & HashTextFileName
Call ShellObj.Run(myVar)
Sub Usage()
Wscript.stdout.writeline("")
Wscript.stdout.writeline("Hashrep.vbs: Replaces the hash of file you are updating in ?_hash.txt")
Wscript.stdout.writeline(" with the file's new hash, to be used for future backprops.")
Wscript.stdout.writeline("")
Wscript.stdout.writeline("Syntax:")
Wscript.stdout.writeline("")
Wscript.stdout.writeline(" Hashrep.vbs %TMP%\Fhash.tmp %TMP%\Nhash.tmp %BINARIES%\dump\cathash\?_Hash.txt")
Wscript.stdout.writeline("")
Wscript.stdout.writeline(" Fhash.tmp: Conatins the file path and its old hash")
Wscript.stdout.writeline(" Nhash.tmp: Conatins the file's new hash")
Wscript.stdout.writeline(" ?_Hash.txt: Conatins all of ?.cat's hash's and there associated file names.")
Wscript.stdout.writeline("")
Wscript.stdout.writeline("This script is called by %BLDTOOLS%\updtcat.cmd")
Wscript.Quit(0)
End Sub
|
<filename>admin/pchealth/authtools/prodtools/ui/frmstopwords.frm
VERSION 5.00
Begin VB.Form frmStopWords
BorderStyle = 1 'Fixed Single
Caption = "Edit Stop Words"
ClientHeight = 5910
ClientLeft = 1260
ClientTop = 690
ClientWidth = 7710
LinkTopic = "Form1"
MaxButton = 0 'False
MinButton = 0 'False
ScaleHeight = 5910
ScaleWidth = 7710
Begin VB.Frame fraSeparator
Height = 135
Left = 120
TabIndex = 8
Top = 5160
Width = 7455
End
Begin VB.Frame fraCreate
Caption = "Create new Stop Word"
Height = 1815
Left = 3360
TabIndex = 2
Top = 240
Width = 4215
Begin VB.CommandButton cmdCreate
Caption = "Create"
Height = 375
Left = 2880
TabIndex = 5
Top = 1320
Width = 1215
End
Begin VB.TextBox txtStopWord
Height = 285
Left = 120
TabIndex = 4
Top = 600
Width = 3975
End
Begin VB.Label lblStopWord
Caption = "Stop Word:"
Height = 255
Left = 120
TabIndex = 3
Top = 360
Width = 855
End
End
Begin VB.CommandButton cmdDelete
Caption = "Delete"
Height = 375
Left = 2040
TabIndex = 6
Top = 4680
Width = 1215
End
Begin VB.CommandButton cmdClose
Caption = "Close"
Height = 375
Left = 6360
TabIndex = 7
Top = 5400
Width = 1215
End
Begin VB.ListBox lstAllStopWords
Height = 4155
Left = 120
TabIndex = 1
Top = 360
Width = 3135
End
Begin VB.Label lblAllStopWords
Caption = "All Stop Words:"
Height = 255
Left = 120
TabIndex = 0
Top = 120
Width = 3015
End
End
Attribute VB_Name = "frmStopWords"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Option Explicit
Private p_clsStopWords As AuthDatabase.StopWords
Private p_rsAllStopWords As ADODB.Recordset
Private Sub Form_Load()
On Error GoTo LErrorHandler
Set p_clsStopWords = g_AuthDatabase.StopWords
Set p_rsAllStopWords = New ADODB.Recordset
p_UpdateAllStopWords
cmdClose.Cancel = True
p_SetToolTips
LEnd:
Exit Sub
LErrorHandler:
p_DisplayErrorMessage "Form_Load"
GoTo LEnd
End Sub
Private Sub Form_Unload(Cancel As Integer)
Set p_clsStopWords = Nothing
Set p_rsAllStopWords = Nothing
End Sub
Private Sub lstAllStopWords_Click()
On Error GoTo LErrorHandler
p_rsAllStopWords.Move lstAllStopWords.ListIndex, adBookmarkFirst
LEnd:
Exit Sub
LErrorHandler:
p_DisplayErrorMessage "lstAllStopWords_Click"
GoTo LEnd
End Sub
Private Sub cmdDelete_Click()
On Error GoTo LErrorHandler
p_clsStopWords.Delete p_rsAllStopWords("SWID"), 0, ""
p_UpdateAllStopWords
LEnd:
Exit Sub
LErrorHandler:
p_DisplayErrorMessage "cmdDelete_Click"
GoTo LEnd
End Sub
Private Sub cmdCreate_Click()
On Error GoTo LErrorHandler
Dim strStopWord As String
strStopWord = LCase$(RemoveExtraSpaces(txtStopWord.Text))
If (strStopWord = "") Then
GoTo LEnd
End If
p_clsStopWords.Create strStopWord
p_UpdateAllStopWords
txtStopWord.Text = ""
txtStopWord.SetFocus
LEnd:
Exit Sub
LErrorHandler:
p_DisplayErrorMessage "cmdCreate_Click"
GoTo LEnd
End Sub
Private Sub cmdClose_Click()
Unload Me
End Sub
Private Sub p_UpdateAllStopWords()
p_clsStopWords.GetAllStopWordsRs p_rsAllStopWords
lstAllStopWords.Clear
Do While (Not p_rsAllStopWords.EOF)
lstAllStopWords.AddItem p_rsAllStopWords("StopWord") & ""
p_rsAllStopWords.MoveNext
Loop
If (lstAllStopWords.ListCount > 0) Then
' This simulates clicking the list box.
lstAllStopWords.ListIndex = 0
End If
End Sub
Private Sub p_DisplayErrorMessage( _
ByVal i_strFunction As String _
)
Select Case Err.Number
Case errContainsGarbageChar
MsgBox "The Stop Word " & txtStopWord & " contains garbage characters", _
vbExclamation + vbOKOnly
Case errMultiWord
MsgBox "The Stop Word " & txtStopWord & " contains multiple words", _
vbExclamation + vbOKOnly
Case errContainsStopSign
MsgBox "The Stop Word " & txtStopWord & " contains a Stop Sign", _
vbExclamation + vbOKOnly
Case errContainsOperatorShortcut
MsgBox "The Stop Word " & txtStopWord & " contains an operator shortcut", _
vbExclamation + vbOKOnly
Case errContainsVerbalOperator
MsgBox "The Stop Word " & txtStopWord & " is a verbal operator", _
vbExclamation + vbOKOnly
Case errAlreadyExists
MsgBox "The Stop Word " & txtStopWord & " already exists", _
vbExclamation + vbOKOnly
Case E_FAIL
DisplayDatabaseLockedError
Case errDatabaseVersionIncompatible
DisplayDatabaseVersionError
Case errNotPermittedForAuthoringGroup, errAuthoringGroupDiffers, _
errAuthoringGroupNotPresent
DisplayAuthoringGroupError
Case Else
g_ErrorInfo.SetInfoAndDump i_strFunction
End Select
End Sub
Private Sub p_SetToolTips()
lblAllStopWords.ToolTipText = "This is a list of all stop words that have been " & _
"created for this database."
lstAllStopWords.ToolTipText = lblAllStopWords.ToolTipText
txtStopWord.ToolTipText = "Type in a new stop word to add to the list."
End Sub
|
'
' test5.vbs
'
' device creation / manipulation
'
Dim WshSHell
Dim DevCon
Dim Devs
Dim Dev
Dim HwIds
Dim HwId
Dim Strings
set WshShell = WScript.CreateObject("WScript.Shell")
set DevCon = WScript.CreateObject("DevCon.DeviceConsole")
set Strings = WScript.CreateObject("DevCon.Strings")
Strings.Add "a"
Strings.Add "b"
Strings.Add "c"
set Devs = DevCon.CreateEmptyDeviceList()
set Dev = Devs.CreateRootDevice("jimbo")
Dev.FriendlyName = "MyName"
Wscript.Echo "FriendlyName: "+Dev.FriendlyName
Dev.HardwareIds = "doh"
set HwIds = Dev.HardwareIds
FOR EACH HwId IN HwIds
WScript.Echo "HWID: " + HwId
NEXT
Dev.CompatibleIds = Strings
set HwIds = Dev.CompatibleIds
FOR EACH HwId IN HwIds
WScript.Echo "Compat: " + HwId
NEXT
Dev.Delete
|
dim m
m = 1
for i = 0 to 13
m = looksay(m)
wscript.echo m
next
|
<reponame>npocmaka/Windows-Server-2003
VERSION 5.00
Begin VB.Form frmMain
Caption = "PrepareHHCsForLoc"
ClientHeight = 5430
ClientLeft = 270
ClientTop = 450
ClientWidth = 9390
LinkTopic = "Form1"
ScaleHeight = 5430
ScaleWidth = 9390
StartUpPosition = 3 'Windows Default
Begin VB.CheckBox chkRecurse
Caption = "&Recurse through sub folders"
Height = 255
Left = 120
TabIndex = 3
Top = 480
Width = 2415
End
Begin VB.TextBox txtOutput
Height = 4335
Left = 120
MultiLine = -1 'True
ScrollBars = 3 'Both
TabIndex = 6
Top = 960
Width = 9135
End
Begin VB.CommandButton cmdClose
Caption = "Close"
Height = 375
Left = 8400
TabIndex = 5
Top = 480
Width = 855
End
Begin VB.CommandButton cmdFolder
Caption = "..."
Height = 255
Left = 8880
TabIndex = 2
Top = 120
Width = 375
End
Begin VB.CommandButton cmdGo
Caption = "Go"
Height = 375
Left = 7440
TabIndex = 4
Top = 480
Width = 855
End
Begin VB.TextBox txtFolder
Height = 285
Left = 720
TabIndex = 1
Top = 120
Width = 8055
End
Begin VB.Label lbl
Caption = "&Folder"
Height = 255
Left = 120
TabIndex = 0
Top = 120
Width = 495
End
End
Attribute VB_Name = "frmMain"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Option Explicit
' Make sure that these letters correspond to the Alt key combinations.
Private Const OPT_FOLDER_C As String = "f"
Private Const OPT_RECURSE_C As String = "r"
Private Const OPT_LOG_FILE_C As String = "l"
Private Const OPT_CLOSE_ON_WARNING_C As String = "qw"
Private Const OPT_CLOSE_ALWAYS_C As String = "qa"
Private Const OPT_HELP_C As String = "h,?,help"
Private p_strSeparator As String
Private p_blnWarning As Boolean
Private p_blnError As Boolean
Private p_clsSizer As Sizer
Private WithEvents p_frmFolderChooser As frmFolderChooser
Attribute p_frmFolderChooser.VB_VarHelpID = -1
Private Sub p_DisplayHelp()
Dim str As String
str = "Usage: " & vbCrLf & vbCrLf & _
App.EXEName & " /f <Folder> /r /l <Log File> /qw /qa" & vbCrLf & vbCrLf & _
"The /r, /l, /qw, and /qa arguments are optional." & vbCrLf & _
"/r causes the application to recurse through sub folders." & vbCrLf & _
"/qw makes the window go away even if there are Warnings." & vbCrLf & _
"/qa makes the window go away even if there are Errors and/or Warnings." & vbCrLf & _
"""" & App.EXEName & " /?"" displays this message."
Output str, LOGGING_TYPE_NORMAL_E
Output p_strSeparator, LOGGING_TYPE_NORMAL_E
End Sub
Private Sub Form_Load()
Dim strLogFile As String
cmdGo.Default = True
cmdClose.Cancel = True
Set p_clsSizer = New Sizer
Set p_frmFolderChooser = New frmFolderChooser
strLogFile = GetOption(Command$, OPT_LOG_FILE_C, True)
SetLogFile strLogFile
Output "Version " & App.Major & "." & App.Minor & "." & App.Revision, LOGGING_TYPE_NORMAL_E
p_strSeparator = String(80, "-")
Output p_strSeparator, LOGGING_TYPE_NORMAL_E
p_ProcessCommandLine
End Sub
Private Sub p_ProcessCommandLine()
Dim strCommand As String
Dim blnCloseOnWarning As Boolean
Dim blnCloseAlways As Boolean
Dim blnClose As Boolean
strCommand = Trim$(Command$)
If (strCommand = "") Then
Exit Sub
End If
txtFolder = GetOption(strCommand, OPT_FOLDER_C, True)
If (OptionExists(strCommand, OPT_RECURSE_C, True)) Then
chkRecurse.Value = vbChecked
End If
blnCloseOnWarning = OptionExists(strCommand, OPT_CLOSE_ON_WARNING_C, True)
blnCloseAlways = OptionExists(strCommand, OPT_CLOSE_ALWAYS_C, True)
If (OptionExists(strCommand, OPT_HELP_C, True)) Then
p_DisplayHelp
ElseIf (Len(strCommand) <> 0) Then
cmdGo_Click
If (p_blnError) Then
' If an error occurred, then close the window only if OPT_CLOSE_ALWAYS_C is specified.
If (blnCloseAlways) Then
blnClose = True
End If
ElseIf (p_blnWarning) Then
' If a warning occurred, but there was no error, then close the window only if
' OPT_CLOSE_ON_WARNING_C or OPT_CLOSE_ALWAYS_C is specified.
If (blnCloseOnWarning Or blnCloseAlways) Then
blnClose = True
End If
Else
' If there was no warning or error, then close the window.
blnClose = True
End If
If (blnClose) Then
cmdClose_Click
End If
End If
End Sub
Private Sub cmdGo_Click()
On Error GoTo LError
Dim strFolder As String
Dim blnRecurse As Boolean
Output "Start: " & Date & " " & Time, LOGGING_TYPE_NORMAL_E
strFolder = Trim$(txtFolder.Text)
If (strFolder = "") Then
Output "Please specify the Folder", LOGGING_TYPE_ERROR_E
GoTo LError
End If
If (chkRecurse.Value = vbChecked) Then
blnRecurse = True
End If
Me.Enabled = False
MainFunction strFolder, blnRecurse
LEnd:
Output "End: " & Date & " " & Time, LOGGING_TYPE_NORMAL_E
Output "The log file is: " & GetLogFileName, LOGGING_TYPE_NORMAL_E
Output p_strSeparator, LOGGING_TYPE_NORMAL_E
Me.Enabled = True
Exit Sub
LError:
GoTo LEnd
End Sub
Private Sub cmdClose_Click()
Unload Me
End Sub
Private Sub cmdFolder_Click()
Load p_frmFolderChooser
p_frmFolderChooser.SetFolder 0, txtFolder.Text
p_frmFolderChooser.Show vbModal
End Sub
Private Sub p_frmFolderChooser_FolderChosen( _
ByVal i_intIndex As Long, _
ByVal strFolder As String _
)
txtFolder.Text = strFolder
End Sub
Private Sub Form_Activate()
On Error GoTo LError
p_SetSizingInfo
DoEvents
LError:
End Sub
Private Sub Form_Resize()
On Error GoTo LError
p_clsSizer.Resize
LError:
End Sub
Private Sub p_SetSizingInfo()
Dim intIndex As Long
p_clsSizer.AddControl txtFolder
Set p_clsSizer.ReferenceControl(DIM_RIGHT_E) = Me
p_clsSizer.ReferenceDimension(DIM_RIGHT_E) = DIM_WIDTH_E
p_clsSizer.AddControl cmdGo
Set p_clsSizer.ReferenceControl(DIM_LEFT_E) = Me
p_clsSizer.ReferenceDimension(DIM_LEFT_E) = DIM_WIDTH_E
p_clsSizer.AddControl cmdClose
Set p_clsSizer.ReferenceControl(DIM_LEFT_E) = Me
p_clsSizer.ReferenceDimension(DIM_LEFT_E) = DIM_WIDTH_E
p_clsSizer.AddControl txtOutput
Set p_clsSizer.ReferenceControl(DIM_RIGHT_E) = Me
p_clsSizer.ReferenceDimension(DIM_RIGHT_E) = DIM_WIDTH_E
Set p_clsSizer.ReferenceControl(DIM_BOTTOM_E) = Me
p_clsSizer.ReferenceDimension(DIM_BOTTOM_E) = DIM_HEIGHT_E
End Sub
Public Sub Output( _
ByVal i_str As String, _
ByVal i_enumLoggingType As LOGGING_TYPE_E _
)
OutputToTextBoxAndWriteLog txtOutput, i_str, i_enumLoggingType
If (i_enumLoggingType = LOGGING_TYPE_ERROR_E) Then
p_blnError = True
ElseIf (i_enumLoggingType = LOGGING_TYPE_WARNING_E) Then
p_blnWarning = True
End If
End Sub
|
'
' Script to update OPK MSI package
'
'
' Uses uuidgen.exe to generate a GUID, then formats it to be
' a MSI acceptable string guid
'
' This makes use of a temporary file %temp%\MakeTempGUID.txt
'
Function MakeGuid()
Dim WSHShell, FileSystem, File, ret, TempFileName, regEx
Set WSHShell = CreateObject("WScript.Shell")
Set FileSystem = CreateObject("Scripting.FileSystemObject")
TempFileName = WSHShell.ExpandEnvironmentStrings("%temp%\MakeTempGUID.txt")
If FileSystem.fileExists(TempFileName) Then
FileSystem.DeleteFile TempFileName
End If
ret = WSHShell.Run("uuidgen -o" & TempFileName, 2, True)
If FileSystem.fileExists(TempFileName) Then
Set File = FileSystem.OpenTextFile(TempFileName, 1)
MakeGuid = "{" & UCase(File.ReadLine) & "}"
File.Close
FileSystem.DeleteFile TempFileName
wscript.echo " Generated GUID: " & MakeGuid
Else
MakeGuid = "{00000000-0000-0000-0000-000000000000}"
Wscript.echo " ERROR: Failed to generate GUID"
End If
Exit Function
End Function
'
' Updates the OS install MSI package using the following paramaters
' szPackage - path to package to update. requires read/write access
'
Function UpdateOsPackage( szPackage )
Dim WSHShell, Installer, Database, SummaryInfo, View, SQL
Wscript.echo " Package name : " & szPackage
UpdateOsPackage = 0
On Error Resume Next
'
'Create the MSI API object
'
Set Installer = CreateObject("WindowsInstaller.Installer")
If Err <> 0 Then
Err = 0
Set Installer = CreateObject("WindowsInstaller.Application")
End If
If Err <> 0 Then
Err = 0
Set Installer = CreateObject("Msi.ApiAutomation")
End If
If Err <> 0 Then
Err = 0
Wscript.echo "ERROR: Error creating Installer object"
UpdateOsPackage = -1
Exit Function
End If
'
'Create the WSH shell object
'
Set WSHShell = CreateObject("WScript.Shell")
If Err <> 0 Then
Wscript.echo "ERROR: Error creating WSHShell object"
UpdateOsPackage = -1
Exit Function
End If
'
'Open the package
'
Set Database = Installer.OpenDatabase(szPackage, 1)
If Err <> 0 Then
Wscript.echo "ERROR: Error opening database"
UpdateOsPackage = -1
Exit Function
End If
Wscript.echo " Database opened for update"
'
'Generate and set a new package code
'
Set SummaryInfo = Database.SummaryInformation(3)
If Err <> 0 Then
Wscript.echo "ERROR: Creating Summary Info Object"
UpdateOsPackage = -1
Exit Function
End If
'
' Set the Package code
'
Err=0
SummaryInfo.Property(9) = MakeGuid()
If Err <> 0 Then
Wscript.echo "ERROR: Error setting package code"
UpdateOsPackage = -1
Exit Function
End If
Wscript.echo " Successfully updated package Code"
'-------------------------------------------------
'Generate and set a new product code
'-------------------------------------------------
SQL = "UPDATE Property SET Property.Value = '" & MakeGuid() & "' WHERE Property.Property= 'ProductCode'"
Set View = Database.OpenView(SQL)
If Err <> 0 Then
Wscript.echo "ERROR: Error opening view: " & SQL
UpdateOsPackage = -1
Exit Function
End If
View.Execute
If Err <> 0 Then
Wscript.echo "ERROR: Error executing view: " & SQL
UpdateOsPackage = -1
Exit Function
End If
Wscript.echo " Succesfully updated Product Code"
'-------------------------------------------------
'Persist the summary info
'-------------------------------------------------
SummaryInfo.Persist
If Err <> 0 Then
Wscript.echo "ERROR: Error persisting summary info"
UpdateOsPackage = -1
Exit Function
End If
Wscript.echo " Successfully persisted summary stream"
'Commit changes
Database.Commit
If Err <> 0 Then
Wscript.echo "ERROR: Error commiting changes: " & SQL
UpdateOsPackage = -1
Exit Function
End If
Wscript.echo " Successfully commited changes to opk.msi"
End Function
Set Args = Wscript.Arguments
Status = UpdateOsPackage ( Args ( 0 ) )
if Status = -1 Then
Wscript.echo "Failed to update opk.msi"
End if
Wscript.Quit Status
|
<reponame>AtomicRoland/AtomFpga
10 DIM LL10
11 FOR I=0 TO 1
15 P=#800
20[
30 LDA#FD;PHA
40 LDA@4;STA#BFFF
50 JSR LL1
60 PLA;STA#BFFF
70 LDA@12;JSR#FFF4
80 JSR#F7D1;]
90 $P="ACORN ATOM + ATOMMC2"
100 P=P+L.P+1;[
105 NOP
110 JSR#FFED;JMP#FFED
111:LL1
112 JMP (#AFFE)
115]
116 NEXT
120 END
|
Function Selection_Sort(s)
arr = Split(s,",")
For i = 0 To UBound(arr)
For j = i To UBound(arr)
temp = arr(i)
If arr(j) < arr(i) Then
arr(i) = arr(j)
arr(j) = temp
End If
Next
Next
Selection_Sort = (Join(arr,","))
End Function
WScript.StdOut.Write "Pre-Sort" & vbTab & "Sorted"
WScript.StdOut.WriteLine
WScript.StdOut.Write "3,2,5,4,1" & vbTab & Selection_Sort("3,2,5,4,1")
WScript.StdOut.WriteLine
WScript.StdOut.Write "c,e,b,a,d" & vbTab & Selection_Sort("c,e,b,a,d")
|
<filename>Task/Mouse-position/Visual-Basic/mouse-position-1.vb
Private Sub Form_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single)
'X and Y are in "twips" -- 15 twips per pixel
Me.Print "X:" & X
Me.Print "Y:" & Y
End Sub
|
Sub C_S_Switch()
Dim myName
myName = 2
Debug.Print Switch(myName = 1, "Bryan", myName = 2, "Justin", myName = 3, "John")
'return : Justin
End Sub
|
<gh_stars>1-10
Function digital_root(n)
ap = 0
Do Until Len(n) = 1
x = 0
For i = 1 To Len(n)
x = x + CInt(Mid(n,i,1))
Next
n = x
ap = ap + 1
Loop
digital_root = "Additive Persistence = " & ap & vbCrLf &_
"Digital Root = " & n & vbCrLf
End Function
WScript.StdOut.Write digital_root(WScript.Arguments(0))
|
<gh_stars>1-10
Public Sub zero()
x = 0
y = 0
z = 0 ^ 0
Debug.Print "z ="; z
End Sub
|
<gh_stars>1-10
On Error GoTo 0
i = 2147483647 + 1 'Run-time error '6' : Overflow
Debug.Print i
|
<reponame>npocmaka/Windows-Server-2003
VERSION 5.00
Begin VB.Form frmLiveImageTracker
Caption = "Live Image Tracking Utility"
ClientHeight = 5115
ClientLeft = 3375
ClientTop = 2910
ClientWidth = 6930
LinkTopic = "Form1"
ScaleHeight = 5115
ScaleWidth = 6930
Begin VB.TextBox txtReport
Height = 2655
Left = 0
MultiLine = -1 'True
TabIndex = 9
Top = 1920
Width = 6855
End
Begin VB.ComboBox cmbSku
Height = 315
Left = 1920
TabIndex = 8
Top = 480
Width = 4935
End
Begin VB.TextBox txtDbLocation
Height = 375
Left = 1920
TabIndex = 6
Top = 840
Width = 4935
End
Begin VB.CommandButton cmdCLose
Caption = "&Close"
Height = 375
Left = 6120
TabIndex = 2
Top = 4680
Width = 735
End
Begin VB.CommandButton cmdGo
Caption = "&Go"
Height = 375
Left = 5280
TabIndex = 1
Top = 4680
Width = 735
End
Begin VB.TextBox txtLiveImageDir
Height = 375
Left = 1920
TabIndex = 0
Top = 120
Width = 4935
End
Begin VB.Label lblDbLocation
Caption = "Database Location"
Height = 375
Left = 120
TabIndex = 7
Top = 840
Width = 1815
End
Begin VB.Label lblStatus
Height = 375
Left = 120
TabIndex = 5
Top = 1320
Width = 6735
End
Begin VB.Label lblSku
Caption = "Sku Specifier"
Height = 375
Left = 120
TabIndex = 4
Top = 480
Width = 1815
End
Begin VB.Label lblLiveImageDir
Caption = "Live Image Directory"
Height = 255
Left = 120
TabIndex = 3
Top = 120
Width = 1815
End
End
Attribute VB_Name = "frmLiveImageTracker"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
'===========================================================================================
' Compiland : frmLiveImageTracker.frm
' Author : <NAME>
' Version : 1.0
'
' Description : Implements Interactive UI and Command Line Wrappers for COM Object
' that tracks Live Help File Image for HSC Production Tools.
'
' Called by : Command Line with Arguments or Interactively from Explorer.
'
' Environment data:
' Files that it uses (Specify if they are inherited in open state): NONE
' Parameters (Command Line) and usage mode {I,I/O,O}:
' Look in Function ParseOpts() for the latest incarnation of these.
'
' Parameters (inherited from environment) : NONE
' Public Variables created: NONE
' Environment Variables (Public or Module Level) modified: NONE
' Environment Variables used in coupling with other routines: NONE
' Local variables : N/A
' Problems detected :
' DCR Suggestions:
' - Make File Copies Incremental, even in those cases where things should be
' completely destroyed.
'
' History:
' 2000-07-16 Initial Creation
'===========================================================================================
Option Explicit
' We declare the Live Help File Image Com Object with Events in order to be abel to get Status
' information from it and eventually cancel the run.
Private m_db As AuthDatabase.Main
Private WithEvents m_oLvi As AuthDatabase.LiveImageTracker
Attribute m_oLvi.VB_VarHelpID = -1
' ================== SKU Relatewd Stuff ================================
'' NOTE: This is the SKU ENUM as defined elsewhere in the System, however we do not NEED it here
' as long as this SKU IDs are respected, we do extrapolate the ID from the Index of either
' the array used or the ComboBox.
' Enum SKU_E
' SKU_STANDARD_E = &H1
' SKU_PROFESSIONAL_E = &H2
' SKU_SERVER_E = &H4
' SKU_ADVANCED_SERVER_E = &H8
' SKU_DATA_CENTER_SERVER_E = &H10
' SKU_PROFESSIONAL_64_E = &H20
' SKU_ADVANCED_SERVER_64_E = &H40
' SKU_DATA_CENTER_SERVER_64_E = &H80
' End Enum
Private m_idSku As Long
Private m_SkuMap(8) As String
Private Sub cmbSku_Click()
Debug.Print cmbSku.ListIndex
m_idSku = 2 ^ cmbSku.ListIndex
End Sub
Private Sub cmdCLose_Click()
Unload Me
End Sub
Private Sub cmdGo_Click()
Dim strErrMsg As String: strErrMsg = "": If (g_bOnErrorHandling) Then On Error GoTo Error_Handler
m_db.SetDatabase Me.txtDbLocation
' While we work, we disable all Data Entry except for the Cancel Button.
cmdGo.Enabled = False
cmdCLose.Caption = "&Cancel"
With Me
.txtLiveImageDir.Enabled = False
.cmbSku.Enabled = False
.txtDbLocation.Enabled = False
End With
m_oLvi.UpdateTrackingInfo m_idSku, Me.txtLiveImageDir, Emitreport:=True
p_CreateReport
' We are done, so let's get out.
cmdGo.Caption = "Done"
cmdCLose.Caption = "&Close"
Common_Exit:
Exit Sub
Error_Handler:
g_XErr.SetInfo "frmLiveImageTracker::cmdGo_Click", strErrMsg
g_XErr.Dump
End Sub
Private Sub Form_Load()
If (Not GlobalInit) Then
MsgBox "Could Not Initialize"
Unload Me
GoTo Common_Exit
End If
Dim strErrMsg As String: strErrMsg = "": If (g_bOnErrorHandling) Then On Error GoTo Error_Handler
Set m_db = New AuthDatabase.Main
Set m_oLvi = m_db.LiveImageTracker
Me.cmbSku.AddItem "Whistler Standard (STD)"
Me.cmbSku.AddItem "Whistler Pro (PRO)"
Me.cmbSku.AddItem "Whistler Server (SRV)"
Me.cmbSku.AddItem "Whistler Advanced Server (ADV)"
Me.cmbSku.AddItem "Whistler Datacenter (DAT)"
Me.cmbSku.AddItem "Whistler Pro 64 (PRO64)"
Me.cmbSku.AddItem "Whistler Advanced Server 64 (ADV64)"
Me.cmbSku.AddItem "Whistler Datacenter 64 (DAT64)"
Me.cmbSku.AddItem "Windows Me (WINME)"
Me.cmbSku.ListIndex = 0
If (Len(Command$) = 0) Then
' Temporary default FileNames. They should not be taken as indicative of
' anything.
' txtLiveImageDir = "\\taos\public\builds\win98\Latest"
txtLiveImageDir = "c:\temp\test"
Me.txtDbLocation = "c:\temp\winme.mdb"
Else
doWork Command$
Unload Me
End If
Common_Exit:
Exit Sub
Error_Handler:
' We will hit an Err.Number of vbObject + 9999 by Normal Exit Conditions,
' so we are not interested in dumping this information.
If (Err.Number = (vbObject + 9999)) Then
Unload Me
Else
g_XErr.Dump
End If
GoTo Common_Exit
End Sub
Private Sub m_oLvi_GoStatus(strWhere As String, bCancel As Boolean)
lblStatus.Caption = strWhere
End Sub
' ============= Command Line Interface ====================
' Function: Parseopts
' Objective : Supplies a Command Line arguments interface for creating the Live Help File Image.
'
' LviTracker /LVIDIR \\pietrino\d$\public\HlpImages\Server\winnt\help
' /SKU SkuString
' /DBLOCATION MDB-File
Function ParseOpts(ByVal strCmd As String) As Boolean
Dim strErrMsg As String: strErrMsg = "": If (g_bOnErrorHandling) Then On Error GoTo Error_Handler
Dim lProgOpt As Long
Dim iError As Long
Const OPT_LVIDIR As Long = 2 ^ 2
Const OPT_SKU As Long = 2 ^ 3
Const OPT_DBLOCATION As Long = 2 ^ 4
m_SkuMap(0) = "std": m_SkuMap(1) = "pro": m_SkuMap(2) = "srv":
m_SkuMap(3) = "adv": m_SkuMap(4) = "dat": m_SkuMap(5) = "pro64"
m_SkuMap(6) = "adv64": m_SkuMap(7) = "dat64": m_SkuMap(8) = "winme"
Dim strArg As String
Do While (Len(strCmd) > 0 And iError = 0)
strCmd = Trim$(strCmd)
If Left$(strCmd, 1) = Chr(34) Then
strCmd = Right$(strCmd, Len(strCmd) - 1)
strArg = vntGetTok(strCmd, sTokSepIN:=Chr(34))
Else
strArg = vntGetTok(strCmd, sTokSepIN:=" ")
End If
If (Left$(strArg, 1) = "/" Or Left$(strArg, 1) = "-") Then
strArg = Mid$(strArg, 2)
Select Case UCase$(strArg)
' All the Cases are in alphabetical order to make your life
' easier to go through them. There are a couple of exceptions.
' The first one is that every NOXXX option goes after the
' pairing OPTION.
Case "DBLOCATION"
strArg = LCase$(vntGetTok(strCmd, sTokSepIN:=" "))
If ("\\" = Left$(strArg, 2)) Then
lProgOpt = (lProgOpt Or OPT_DBLOCATION)
Me.txtDbLocation = strArg
Else
MsgBox ("Database location must be specified using UNC '\\' style notation")
iError = 1
End If
Case "LVIDIR"
strArg = LCase$(vntGetTok(strCmd, sTokSepIN:=" "))
If ("\\" = Left$(strArg, 2)) Then
lProgOpt = (lProgOpt Or OPT_LVIDIR)
Me.txtLiveImageDir = strArg
Else
MsgBox ("Live Image Directory must be specified using UNC '\\' style notation")
iError = 1
End If
Case "SKU"
strArg = LCase$(vntGetTok(strCmd, sTokSepIN:=" "))
m_idSku = Arg2SkuID(strArg)
If (m_idSku > 0) Then
lProgOpt = (lProgOpt Or OPT_SKU)
Else
iError = 1
End If
Case Else
MsgBox "Program Option: " & "/" & strArg & " is not supported", vbOKOnly, "Program Arguments Error"
lProgOpt = 0
iError = 1
End Select
End If
Loop
' Now we check for a complete and <coherent> list of options. As all options are
' mandatory then we check for ALL options being set.
If ((lProgOpt And (OPT_DBLOCATION Or OPT_LVIDIR Or OPT_SKU)) <> _
(OPT_DBLOCATION Or OPT_LVIDIR Or OPT_SKU)) Then
UseageMsg
iError = 1
End If
ParseOpts = (0 = iError)
Exit Function
Error_Handler:
g_XErr.SetInfo "frmLiveImageTracker::ParseOpts", strErrMsg
Err.Raise Err.Number
End Function
Sub doWork(ByVal strCmd As String)
Dim strErrMsg As String: strErrMsg = "": If (g_bOnErrorHandling) Then On Error GoTo Error_Handler
If Not ParseOpts(strCmd) Then
GoTo Common_Exit
End If
Me.Show vbModeless
cmdGo_Click
Common_Exit:
Exit Sub
Error_Handler:
g_XErr.SetInfo "frmLiveImageTracker::doWork", strErrMsg
Err.Raise Err.Number
End Sub
Private Function Arg2SkuID(ByVal strSku As String) As Long
Arg2SkuID = 0
strSku = Trim$(strSku)
If (Len(strSku) = 0) Then GoTo Common_Exit
Dim i As Integer
For i = 0 To UBound(m_SkuMap)
If (strSku = m_SkuMap(i)) Then
Arg2SkuID = 2 ^ i
Exit For
End If
Next i
Common_Exit:
Exit Function
End Function
Sub UseageMsg()
MsgBox "LviTracker [/LVIDIR \\pietrino\d$\public\HlpImages\Server\winnt\help]" + vbCrLf + _
" /SKU {STD|PRO|SRV|ADV|DAT|PRO64|ADV64|DAT64|WINME}" + vbCrLf + _
" /DBLOCATION \\pietrino\HSCDB\HSC.MDB" + vbCrLf + vbCrLf + _
"Where each option means:" + vbCrLf + vbCrLf + _
"/LVIDIR Destination Live Help File Image Directory" + vbCr + _
"/SKU String Identifier for SKU to be processed" + vbCr + _
"/DBLOCATION Database location where tracking information is to be written"
End Sub
Private Function p_ID2SkuName(ByVal IDSku As Long) As Long
p_ID2SkuName = Log(IDSku) / Log(2#)
End Function
Private Sub p_CreateReport()
Dim rs As ADODB.Recordset
Set rs = m_oLvi.DetailedReport
txtReport.Font = "Courier New"
txtReport.FontSize = 8
txtReport = txtReport & "Summary Data for Run of " & App.EXEName & _
" Version: " & App.Major & "." & App.Minor & "." & App.Revision & vbCrLf
txtReport = txtReport & "Date: " & Now & vbCrLf
txtReport = txtReport + "Live Image Directory: " + Me.txtLiveImageDir + vbCrLf
txtReport = txtReport + "Database Location: " + Me.txtDbLocation + vbCrLf
txtReport = txtReport + "SKU: " + Me.cmbSku.List(p_ID2SkuName(m_idSku)) + vbCrLf + vbCrLf
Do While (Not rs.EOF)
txtReport = txtReport & rs("Action") & " - " & rs("PathName") & " - " & rs("DateFileModified") & vbCrLf
rs.MoveNext
Loop
txtReport = txtReport + vbCrLf
txtReport = txtReport & "Summary of File Operations: Added (" & m_oLvi.AddedFiles & _
") Changed (" & m_oLvi.ChangedFiles & ") Deleted (" & m_oLvi.DeletedFiles & ")"
Dim iFh As Integer
iFh = FreeFile
Open App.EXEName + ".log" For Output As #iFh
Print #iFh, txtReport.Text
Close #iFh
Common_Exit:
Exit Sub
End Sub
|
Function ArrayConcat(arr1, arr2)
ReDim ret(UBound(arr1) + UBound(arr2) + 1)
For i = 0 To UBound(arr1)
ret(i) = arr1(i)
Next
offset = Ubound(arr1) + 1
For i = 0 To UBound(arr2)
ret(i + offset) = arr2(i)
Next
ArrayConcat = ret
End Function
arr1 = array(10,20,30)
arr2 = array(40,50,60)
WScript.Echo "arr1 = array(" & Join(arr1,", ") & ")"
WScript.Echo "arr2 = array(" & Join(arr2,", ") & ")"
arr3 = ArrayConcat(arr1, arr2)
WScript.Echo "arr1 + arr2 = array(" & Join(arr3,", ") & ")"
|
<gh_stars>10-100
'////////////////////////////////////////////////////////////////////////////
'
' Copyright (c) 1999-2000 Microsoft Corp. All Rights Reserved.
'
' File name:
'
' test.vbs
'
' Abstract:
'
' Windows Embedded Prototype Script for Printers
'
' Remarks:
'
' This file tests dependency mapping functionality
'
' Author:
'
' <NAME> (lzhu) 11-29-2000
'
'////////////////////////////////////////////////////////////////////////////
'Option Explicit
' fake cmi global variables so test.vbs can execute standalone
Public cmiInclude: cmiInclude = 0
Public cmiExactlyOne: cmiExactlyOne = 1
' this function tests one test case
Function DependencyMappingTestOne(files(), componentIDs)
initializeTables ' safe to call it more than once
Dim componentFlagArray()
ReDim componentFlagArray(g_nComponents - 1)
' initialize componentFlagArray
initComponentFlagArray componentFlagArray
If Not isValid(componentFlagArray) Then
DependencyMappingTestOne = False
Exit Function
End If
' now map all the files
Dim bIgnore: bIgnore = False
Dim i
For i = 0 To UBound(files)
bIgnore = MapIt(files(i), componentFlagArray)
WScript.Echo "Mapping " & files(i) & " ... mapped? " & bIgnore
Next
' check if the mapping is correct
For i = 0 To UBound(componentIDs)
If Not componentFlagArray(componentIDs(i)) Then
WScript.Echo "Wrong Component Mapped"
DependencyMappingTestOne = False
Exit Function
End If
componentFlagArray(componentIDs(i)) = False
Next
For i = 0 To UBound(componentFlagArray)
If componentFlagArray(i) Then
WScript.Echo "Extra Component Mapped"
DependencyMappingTestOne = False
Exit Function
End If
Next
DependencyMappingTestOne = True
End Function
' this sub tests all the test cases and prints a "Success" when it succeedes
Sub DependencyMappingTest()
Dim bSuccess: bSuccess = False
Dim files()
Dim componentIDs()
' test case one
WScript.Echo "'''''''''''''''''''' Test case one '''''''''''''''''''''''"
ReDim files(0)
files(0) = "pscript5.dll"
ReDim componentIDs(0)
componentIDs(0) = 0
bSuccess = DependencyMappingTestOne(files, componentIDs)
If Not bSuccess Then
WScript.Echo " Failed "
Exit Sub
End If
' test case two
WScript.Echo "'''''''''''''''''''' Test case two '''''''''''''''''''''''"
ReDim files(3)
files(0) = "pscript5.dll"
files(1) = "ps5ui.dll"
files(2) = "localspl.dll"
files(3) = "pscript5.ntf"
ReDim componentIDs(0)
componentIDs(0) = 0
bSuccess = DependencyMappingTestOne(files, componentIDs)
If Not bSuccess Then
WScript.Echo " Failed "
Exit Sub
End If
' test case three
WScript.Echo "'''''''''''''''''''' Test case three '''''''''''''''''''''''"
ReDim files(3)
files(0) = "pscript5.dll"
files(1) = "ps5ui.dll"
files(2) = "unidrv.dll"
files(3) = "pscript5.ntf"
ReDim componentIDs(1)
componentIDs(0) = 0
componentIDs(1) = 1
bSuccess = DependencyMappingTestOne(files, componentIDs)
If Not bSuccess Then
WScript.Echo " Failed "
Exit Sub
End If
' test case four
WScript.Echo "'''''''''''''''''''' Test case four '''''''''''''''''''''''"
ReDim files(3)
files(0) = "pscript5.dll"
files(1) = "ps5ui.dll"
files(2) = "unidrv.dll"
files(3) = "pscript5.ntf"
ReDim componentIDs(1)
componentIDs(0) = 0
componentIDs(1) = 1
bSuccess = DependencyMappingTestOne(files, componentIDs)
If Not bSuccess Then
WScript.Echo " Failed "
Exit Sub
End If
' test case five
WScript.Echo "'''''''''''''''''''' Test case five '''''''''''''''''''''''"
ReDim files(3)
files(0) = "pscript5.dll"
files(1) = "ps5ui.dll"
files(2) = "plotter.dll"
files(3) = "pscript5.ntf"
ReDim componentIDs(1)
componentIDs(0) = 0
componentIDs(1) = 2
bSuccess = DependencyMappingTestOne(files, componentIDs)
If Not bSuccess Then
WScript.Echo " Failed "
Exit Sub
End If
' test case six
WScript.Echo "'''''''''''''''''''' Test case six '''''''''''''''''''''''"
ReDim files(6)
files(0) = "pscript5.dll"
files(1) = "ps5ui.dll"
files(2) = "uniDrv.dll"
files(3) = "unidRVUi.dll"
files(4) = "plotui.dll"
files(5) = "csrspl.dll"
files(6) = "plotter.dll"
ReDim componentIDs(2)
componentIDs(0) = 0
componentIDs(1) = 1
componentIDs(2) = 2
bSuccess = DependencyMappingTestOne(files, componentIDs)
If Not bSuccess Then
WScript.Echo " Failed "
Exit Sub
End If
'''''''''''''''''''''''''''''''''''''''''''''''''''''
' fail cases
'''''''''''''''''''''''''''''''''''''''''''''''''''''
' test case 1
WScript.Echo "'''''''''''''''''''' failed case 1 '''''''''''''''''''''''"
ReDim files(3)
files(0) = "pscript5.dll"
files(1) = "ps5ui.dll"
files(2) = "ploTTER.dll"
files(3) = "pscript5.ntf"
ReDim componentIDs(1)
componentIDs(0) = 0
componentIDs(1) = 1 ' wrong component
bSuccess = DependencyMappingTestOne(files, componentIDs)
If bSuccess Then ' shall fail
Debug.Print " Failed "
Exit Sub
End If
' test case 2
WScript.Echo "'''''''''''''''''''' failed case 2 '''''''''''''''''''''''"
ReDim files(3)
files(0) = "pscript5.dll"
files(1) = "ps5ui.dll"
files(2) = "plotter.dll"
files(3) = "pscript5.ntf"
ReDim componentIDs(0)
componentIDs(0) = 0
bSuccess = DependencyMappingTestOne(files, componentIDs)
If bSuccess Then ' shall fail
WScript.Echo " Failed "
Exit Sub
End If
' test case 3
WScript.Echo "'''''''''''''''''''' failed case 3 '''''''''''''''''''''''"
ReDim files(3)
files(0) = "pscript5.dll"
files(1) = "ps5ui.dll"
files(2) = "plotter.dll"
files(3) = "pscript5.ntf"
ReDim componentIDs(0)
componentIDs(0) = 2
bSuccess = DependencyMappingTestOne(files, componentIDs)
If bSuccess Then ' shall fail
WScript.Echo " Failed "
Exit Sub
End If
' declare success
WScript.Echo "'''''''''''''''''''' The End '''''''''''''''''''''''"
WScript.Echo " Success "
End Sub
' run the test
DependencyMappingTest
|
<gh_stars>10-100
for each Process in GetObject("winmgmts:{impersonationLevel=impersonate}").InstancesOf ("win32_process")
WScript.Echo Process.ProcessId, Process.name
next
|
On Error Resume Next
while true
Set t_Service = GetObject("winmgmts:{impersonationLevel=impersonate}")
Set t_Enumerator = t_Service.ExecQuery ("select * from win32_systemusers")
for each inst in t_Enumerator
WScript.Echo inst.groupcomponent
Next
wend
|
<reponame>AtomicRoland/AtomFpga
10 DIM LL10
20 FOR I=0 TO 10
30 LLI=-1
40 NEXT
50 C=16000000
60 B=115200
70 D=C/B/4
80 P.$21
90 FOR I=0 TO 1
100 P=#2800
110[
120:LL0
130 LDA @D%256
140 STA #B502
150 LDA @D/256
160 STA #B503
170 LDA #80
180 STA #82
190 LDA #81
200 STA #83
210 LDY @#00
220:LL1
230 LDA #B501
240 AND @#02
250 BEQ LL1
260 BNE LL4
270:LL2
280 LDX @#00 \ 2
290:LL3
300 LDA #B501 \ 4
310 AND @#02 \ 2
320 BNE LL4 \ 3
330 DEX \ 2
340 BNE LL3 \ 3
350 DEY \ 2
360 BNE LL3 \ 3
370 BEQ LL5
380:LL4
390 LDA #B002 \ 4
400 EOR @#04 \ 2
410 STA #B002 \ 4
420 LDA #B500 \ 4
430 LDY @#00 \ 2
440 STA (#82),Y \ 6
450 INC #82 \ 5
460 BNE LL2 \ 3
470 INC #83 \ 5
480 BNE LL2 \ 3 == 56
490:LL5
500 JSR LL10
510 RTS
520:LL10
530 LDA #80
540 STA #84
550 LDA #81
560 STA #85
570 LDA @#00
580 STA #86
590 STA #87
600:LL11
610 LDY @#00
620 LDA (#84),Y
630 STA #88
640 LDX @#08
650:LL12
660 LSR #88
670 ROL #86
680 ROL #87
690 BCC LL13
700 LDA #86
710 EOR @#2D
720 STA #86
730:LL13
740 DEX
750 BNE LL12
760 INC #84
770 BNE LL14
780 INC #85
790:LL14
800 LDA #84
810 CMP #82
820 BNE LL11
830 LDA #85
840 CMP #83
850 BNE LL11
860 RTS
870]
880 NEXT
890 P.$6
900 DO
910 P."WAITING FOR START OF DATA"'
920 !#80=#4000
930 LINK LL0
940 P." START = ",&!#80 & #FFFF'
950 P." END = ",&!#82 & #FFFF'
960 P."LENGTH = ",&!#82 - !#80'
970 P." CRC = ",&!#86 & #FFFF''
980 UNTIL 0
990 END
|
<reponame>npocmaka/Windows-Server-2003
'Copyright (c)<2002>Microsoft Corporation. All rights reserved.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' DeleteServices
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function DeleteServices
On Error Resume Next
Dim WshShell, objEnv, strSADir
Set WshShell = CreateObject("WScript.Shell")
'Stopping Services
Call WshShell.Run("net stop appmgr", 0, True)
Call WshShell.Run("net stop elementmgr", 0, True)
Call WshShell.Run("net stop srvcsurg", 0, True)
'Deleting Services
Set objEnv = WshShell.Environment("Process")
strSADir = objEnv("SYSTEMROOT") + "\system32\serverappliance\"
Call WshShell.Run(strSADir & "appmgr.exe -unregserver", 0, True)
Call WshShell.Run(strSADir & "elementmgr.exe -unregserver", 0, True)
Call WshShell.Run(strSADir & "srvcsurg.exe -unregserver", 0, True)
End Function
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' DeleteLocalUIService
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function DeleteLocalUIService
On Error Resume Next
Dim WshShell, objEnv, strSADir
Set WshShell = CreateObject("WScript.Shell")
'Stopping Services
Call WshShell.Run("net stop saldm", 0, True)
'Deleting Services
Set objEnv = WshShell.Environment("Process")
strSADir = objEnv("SYSTEMROOT") + "\system32\serverappliance\"
Call WshShell.Run(strSADir & "saldm.exe -unregserver", 0, True)
End Function
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' StartServices
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function StartServices
On Error Resume Next
Dim objEnv
Dim tmp
Dim WshShell
'
' registering services here
Set WshShell = CreateObject("WScript.Shell")
set objEnv = WshShell.Environment("Process")
tmp = objEnv("SYSTEMROOT") + "\system32\serverappliance\appmgr.exe -service"
WshShell.Run tmp, 0, TRUE
tmp = objEnv("SYSTEMROOT") + "\system32\serverappliance\appmgr.exe -service"
WshShell.Run tmp, 0, TRUE
tmp = objEnv("SYSTEMROOT") + "\system32\serverappliance\elementmgr.exe"
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FileExists(tmp)) Then
tmp = tmp + " -service"
WshShell.Run tmp, 0, TRUE
WshShell.Run tmp, 0, TRUE
End If
tmp = objEnv("SYSTEMROOT") + "\system32\serverappliance\srvcsurg.exe -service"
WshShell.Run tmp, 0, TRUE
tmp = objEnv("SYSTEMROOT") + "\system32\serverappliance\srvcsurg.exe -service"
WshShell.Run tmp, 0, TRUE
tmp = objEnv("SYSTEMROOT") + "\system32\serverappliance\Elementmgr.dll"
WshShell.RegWrite "HKLM\System\CurrentControlSet\Services\Eventlog\Application\Elementmgr\EventMessageFile",tmp
tmp = objEnv("SYSTEMROOT") + "\system32\serverappliance\srvcsurg.dll"
WshShell.RegWrite "HKLM\System\CurrentControlSet\Services\Eventlog\Application\srvcsurg\EventMessageFile",tmp
WshShell.RegWrite "HKLM\System\CurrentControlSet\Services\elementmgr\start",2,"REG_DWORD"
WshShell.RegWrite "HKLM\System\CurrentControlSet\Services\Appmgr\start",2,"REG_DWORD"
WshShell.RegWrite "HKLM\System\CurrentControlSet\Services\Appmgr\TaskCoordinator\RestartableTasks\", ""
WshShell.RegWrite "HKLM\System\CurrentControlSet\Services\srvcsurg\start",2,"REG_DWORD"
'the services are auto start - so start them now
WshShell.Run "net start winmgmt", 0, TRUE
WshShell.Run "net start appmgr", 0, TRUE
WshShell.Run "net start elementmgr", 0, TRUE
WshShell.Run "net start srvcsurg", 0, TRUE
End Function
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' StartLocalUIService
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function StartLocalUIService
On Error Resume Next
Dim objEnv
Dim tmp
Dim WshShell
'
' registering services here
Set WshShell = CreateObject("WScript.Shell")
set objEnv = WshShell.Environment("Process")
tmp = objEnv("SYSTEMROOT") + "\system32\serverappliance\saldm.exe -service"
WshShell.Run tmp, 0, TRUE
tmp = objEnv("SYSTEMROOT") + "\system32\serverappliance\saldm.exe -service"
WshShell.Run tmp, 0, TRUE
WshShell.Run "net start saldm", 0, TRUE
End Function
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' StopElementMgr
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function StopElementMgr
On Error Resume Next
Dim WshShell
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run "net stop winmgmt /y", 0, TRUE
WshShell.Run "net stop appmgr", 0, TRUE
WshShell.Run "net stop srvcsurg", 0, TRUE
WshShell.Run "net stop elementmgr", 0, TRUE
End Function
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' InitTaskExecutables
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function InitTaskExecutables
Dim WshShell, dt, bf, te, ae, pa
On Error Resume Next
Set WshShell = CreateObject("WScript.Shell")
bf = WshShell.RegRead("HKLM\System\CurrentControlSet\Services\Appmgr\ObjectName")
'Remove all occurances of GenTask in case there are more
'Append GenTask at the end of the key
if bf="LocalSystem" then
'Check if SetDateTime COM object is installed
dt = WshShell.RegRead("HKLM\Software\Classes\CLSID\{F0229EA0-D1D8-11D2-84FC-0080C7227EA1}\ProgID\")
'Check if AlertEmail COM object is installed
ae = WshShell.RegRead("HKLM\Software\Classes\CLSID\{44FCEFBB-3477-4FB2-97B0-1651E697A511}\ProgID\")
'Check if AlertBootTask COM object is installed
pa = WshShell.RegRead("HKLM\SOFTWARE\Classes\CLSID\{90701F02-6539-41F2-973B-ECF2A7439C77}\ProgID\")
'Check if Self Sign Certificate COM object is installed
ss = WshShell.RegRead("HKLM\SOFTWARE\Classes\CLSID\{EA003ECF-3A51-48DA-86A1-0AFE8C3182AE}\ProgID\")
te = "ServerAppliance.SAGenTask.1 "
'Persistent alerts need to be the first task on the list, otherwise duplicate alerts get raised
if pa="ServerAppliance.SAAlertBootTask.1" then
te = te + " " + pa
else
te = Replace(te," ServerAppliance.SAAlertBootTask.1","",1,-1,1)
end if
if dt="SetDateTime.DateTime.1" then
te = te + " " + dt
else
te = Replace(te," SetDateTime.DateTime.1","",1,-1,1)
end if
if ae="SetAlertEmail.AlertEmail.1" then
te = te + " " + ae
else
te = Replace(te," SetAlertEmail.AlertEmail.1","",1,-1,1)
end if
if ss="SelfSignCert.SelfSignCert.1" then
te = te + " " + ss
else
te = Replace(te," SelfSignCert.SelfSignCert.1","",1,-1,1)
end if
WshShell.RegWrite "HKLM\Software\Microsoft\ServerAppliance\ApplianceManager\ObjectManagers\Microsoft_SA_Task\ApplianceInitializationTask\TaskExecutables",te
WshShell.RegWrite "HKLM\Software\Microsoft\ServerAppliance\ApplianceManager\ObjectManagers\Microsoft_SA_Task\ApplianceInitializationTask\CanDisable", 0, "REG_DWORD"
WshShell.RegWrite "HKLM\Software\Microsoft\ServerAppliance\ApplianceManager\ObjectManagers\Microsoft_SA_Task\ApplianceInitializationTask\IsEnabled", 1, "REG_DWORD"
WshShell.RegWrite "HKLM\Software\Microsoft\ServerAppliance\ApplianceManager\ObjectManagers\Microsoft_SA_Task\ApplianceInitializationTask\TaskName", "ApplianceInitializationTask"
end if
End Function
Function AddSupportedLanguagesToRegistry
On Error Resume Next
Dim WshShell
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run "regedit /s %SYSTEMROOT%\system32\serverappliance\setup\lang.reg", 0, TRUE
End Function
|
Function StringPrepend()
Dim s As String
s = "bar"
s = "foo" & s
Debug.Print s
End Function
|
on error resume next
set s = GetObject("winmgmts:root\default")
Set t_Class = s.Get
t_Class.Path_.Class = "EXECNQUERYTEST01"
Set Property = t_Class.Properties_.Add ("p", 19)
Property.Qualifiers_.Add "key", true
t_Class.Put_
set e = s.ExecNotificationQuery _
("select * from __instancecreationevent where targetinstance isa 'EXECNQUERYTEST01'")
if err <> 0 then
Wscript.Echo err.number, err.description, err.source
end if
c = e.Count
if err <> 0 then
Wscript.Echo err.number, err.description, err.source
end if
|
<gh_stars>1-10
Private Function ToReducedRowEchelonForm(M As Variant) As Variant
Dim lead As Integer: lead = 0
Dim rowCount As Integer: rowCount = UBound(M)
Dim columnCount As Integer: columnCount = UBound(M(0))
Dim i As Integer
For r = 0 To rowCount
If lead >= columnCount Then
Exit For
End If
i = r
Do While M(i)(lead) = 0
i = i + 1
If i = rowCount Then
i = r
lead = lead + 1
If lead = columnCount Then
Exit For
End If
End If
Loop
Dim tmp As Variant
tmp = M(r)
M(r) = M(i)
M(i) = tmp
If M(r)(lead) <> 0 Then
div = M(r)(lead)
For t = LBound(M(r)) To UBound(M(r))
M(r)(t) = M(r)(t) / div
Next t
End If
For j = 0 To rowCount
If j <> r Then
subt = M(j)(lead)
For t = LBound(M(j)) To UBound(M(j))
M(j)(t) = M(j)(t) - subt * M(r)(t)
Next t
End If
Next j
lead = lead + 1
Next r
ToReducedRowEchelonForm = M
End Function
Public Sub main()
r = ToReducedRowEchelonForm(Array( _
Array(1, 2, -1, -4), _
Array(2, 3, -1, -11), _
Array(-2, 0, -3, 22)))
For i = LBound(r) To UBound(r)
Debug.Print Join(r(i), vbTab)
Next i
End Sub
|
<filename>Task/Even-or-odd/VBA/even-or-odd.vba
Option Explicit
Sub Main_Even_Odd()
Dim i As Long
For i = -50 To 48 Step 7
Debug.Print i & " : IsEven ==> " & IIf(IsEven(i), "is even", "is odd") _
& " " & Chr(124) & " IsEven2 ==> " & IIf(IsEven2(i), "is even", "is odd") _
& " " & Chr(124) & " IsEven3 ==> " & IIf(IsEven3(i), "is even", "is odd") _
& " " & Chr(124) & " IsEven4 ==> " & IIf(IsEven4(i), "is even", "is odd")
Next
End Sub
Function IsEven(Number As Long) As Boolean
'Use the even and odd predicates
IsEven = (WorksheetFunction.Even(Number) = Number)
End Function
Function IsEven2(Number As Long) As Boolean
'Check the least significant digit.
'With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd.
Dim lngTemp As Long
lngTemp = CLng(Right(CStr(Number), 1))
If (lngTemp And 1) = 0 Then IsEven2 = True
End Function
Function IsEven3(Number As Long) As Boolean
'Divide i by 2.
'The remainder equals 0 if i is even.
Dim sngTemp As Single
sngTemp = Number / 2
IsEven3 = ((Int(sngTemp) - sngTemp) = 0)
End Function
Function IsEven4(Number As Long) As Boolean
'Use modular congruences
IsEven4 = (Number Mod 2 = 0)
End Function
|
' Windows Installer database table export for use with Windows Scripting Host
' Copyright (c) 1999-2000, Microsoft Corporation
' Demonstrates the use of the Database.Export method and MsiDatabaseExport API
'
Option Explicit
Const msiOpenDatabaseModeReadOnly = 0
Dim shortNames:shortNames = False
Dim argCount:argCount = Wscript.Arguments.Count
Dim iArg:iArg = 0
If (argCount < 3) Then
Wscript.Echo "Windows Installer database table export utility" &_
vbNewLine & " 1st argument is path to MSI database (installer package)" &_
vbNewLine & " 2nd argument is path to folder to contain the exported table(s)" &_
vbNewLine & " Subseqent arguments are table names to export (case-sensitive)" &_
vbNewLine & " Specify '*' to export all tables, including _SummaryInformation" &_
vbNewLine & " Specify /s or -s anywhere before table list to force short names" &_
vbNewLine &_
vbNewLine & " Copyright (C) Microsoft Corporation, 1999-2000. All rights reserved."
Wscript.Quit 1
End If
On Error Resume Next
Dim installer : Set installer = Nothing
Set installer = Wscript.CreateObject("WindowsInstaller.Installer") : CheckError
Dim database : Set database = installer.OpenDatabase(NextArgument, msiOpenDatabaseModeReadOnly) : CheckError
Dim folder : folder = NextArgument
Dim table, view, record
While iArg < argCount
table = NextArgument
If table = "*" Then
Set view = database.OpenView("SELECT `Name` FROM _Tables")
view.Execute : CheckError
Do
Set record = view.Fetch : CheckError
If record Is Nothing Then Exit Do
table = record.StringData(1)
Export table, folder : CheckError
Loop
Set view = Nothing
table = "_SummaryInformation" 'not an actual table
Export table, folder : Err.Clear ' ignore if no summary information
Else
Export table, folder : CheckError
End If
Wend
Wscript.Quit(0)
Sub Export(table, folder)
Dim file : If shortNames Then file = Left(table, 8) & ".idt" Else file = table & ".idt"
database.Export table, folder, file
End Sub
Function NextArgument
Dim arg, chFlag
Do
arg = Wscript.Arguments(iArg)
iArg = iArg + 1
chFlag = AscW(arg)
If (chFlag = AscW("/")) Or (chFlag = AscW("-")) Then
chFlag = UCase(Right(arg, Len(arg)-1))
If chFlag = "S" Then
shortNames = True
Else
Wscript.Echo "Invalid option flag:", arg : Wscript.Quit 1
End If
Else
Exit Do
End If
Loop
NextArgument = arg
End Function
Sub CheckError
Dim message, errRec
If Err = 0 Then Exit Sub
message = Err.Source & " " & Hex(Err) & ": " & Err.Description
If Not installer Is Nothing Then
Set errRec = installer.LastErrorRecord
If Not errRec Is Nothing Then message = message & vbNewLine & errRec.FormatText
End If
Wscript.Echo message
Wscript.Quit 2
End Sub
|
<gh_stars>1-10
'N-queens problem - non recursive & structured - vba - 26/02/2017
Sub n_queens()
Const l = 15 'number of queens
Const b = False 'print option
Dim a(l), s(l), u(4 * l - 2)
Dim n, m, i, j, p, q, r, k, t, z
For i = 1 To UBound(a): a(i) = i: Next i
For n = 1 To l
m = 0
i = 1
j = 0
r = 2 * n - 1
Do
i = i - 1
j = j + 1
p = 0
q = -r
Do
i = i + 1
u(p) = 1
u(q + r) = 1
z = a(j): a(j) = a(i): a(i) = z 'Swap a(i), a(j)
p = i - a(i) + n
q = i + a(i) - 1
s(i) = j
j = i + 1
Loop Until j > n Or u(p) Or u(q + r)
If u(p) = 0 Then
If u(q + r) = 0 Then
m = m + 1 'm: number of solutions
If b Then
Debug.Print "n="; n; "m="; m
For k = 1 To n
For t = 1 To n
Debug.Print IIf(a(n - k + 1) = t, "Q", ".");
Next t
Debug.Print
Next k
End If
End If
End If
j = s(i)
Do While j >= n And i <> 0
Do
z = a(j): a(j) = a(i): a(i) = z 'Swap a(i), a(j)
j = j - 1
Loop Until j < i
i = i - 1
p = i - a(i) + n
q = i + a(i) - 1
j = s(i)
u(p) = 0
u(q + r) = 0
Loop
Loop Until i = 0
Debug.Print n, m 'number of queens, number of solutions
Next n
End Sub 'n_queens
|
<filename>verif/block/mbist/SRAM_4096X8X4CM8/membistpv_P1_SMARCHCHKB_LVISION_MBISTPG_ASSEMBLY_ClockMon.vb<gh_stars>0
//-----------------------------------------------------------
// This file created by: membistpVerify
// Software version: 2017.1 Mon Feb 27 18:45:32 GMT 2017
// Created on: 02/01/19 13:44:14
//-----------------------------------------------------------
//=============================================================================
//
// File : membistpv_P1_SMARCHCHKB_LVISION_MBISTPG_ASSEMBLY_ClockMon.vb
// Description : Clock Monitor module for pattern membistpv_P1_SMARCHCHKB_LVISION_MBISTPG_ASSEMBLY
//
//=============================================================================
//
// By default the clock monitoring is enabled.
// To disable clock monitoring define one of the following macros:
// DISABLE_CLOCK_MONITOR
// membistpv_P1_SMARCHCHKB_LVISION_MBISTPG_ASSEMBLY_DISABLE_CLOCK_MONITOR
//
`timescale 100fs/10fs
module membistpv_P1_SMARCHCHKB_LVISION_MBISTPG_ASSEMBLY_ClockMon;
integer number_clock_cycles;
event start_monitor_clocks;
event stop_monitor_clocks;
`define ENABLE_CLOCK_MONITOR
`ifdef DISABLE_CLOCK_MONITOR
`undef ENABLE_CLOCK_MONITOR
`endif
`ifdef membistpv_P1_SMARCHCHKB_LVISION_MBISTPG_ASSEMBLY_DISABLE_CLOCK_MONITOR
`undef ENABLE_CLOCK_MONITOR
`endif
`ifdef ENABLE_CLOCK_MONITOR
// [start] : Signal declarations {{{
time CLOCK_0_start_time;
time CLOCK_0_measured_period;
time CLOCK_0_expected_period;
integer CLOCK_0_cycle_counter;
reg CLOCK_0_complete;
wire CLOCK_0_clkNet;
// [end] : Signal declarations }}}
// Assign the clock nets we are monitoring
assign CLOCK_0_clkNet = TB.CHIP.SMARCHCHKB_LVISION_MBISTPG_ASSEMBLY_UNDER_TEST_INST.SMARCHCHKB_MBIST_CTRL.BIST_CLK ;
`endif
// [start] : Initialize some signals {{{
initial begin
$timeformat(-9, 3, " ns", 10);
`ifdef ENABLE_CLOCK_MONITOR
number_clock_cycles = 10;
CLOCK_0_cycle_counter = 0;
CLOCK_0_complete <= 0;
CLOCK_0_expected_period = 50000.0; // 1ns -> 100fs scale
`endif
end
// [end] : Initialize some signals }}}
// Display Results when monitoring is over
//----------------------------------------
always @(stop_monitor_clocks) begin
`ifdef ENABLE_CLOCK_MONITOR
$display ($time, " Clock Monitoring results");
$display ($time, " ------------------------");
// [start] : SMARCHCHKB_LVISION_MBISTPG_ASSEMBLY_UNDER_TEST_INST.SMARCHCHKB_MBIST_CTRL.BIST_CLK {{{
if (CLOCK_0_complete) begin
if (( CLOCK_0_measured_period > CLOCK_0_expected_period * 1.01) | ( CLOCK_0_measured_period < CLOCK_0_expected_period * 0.99 )) begin
$display ($time,
" Compare fail: SMARCHCHKB_LVISION_MBISTPG_ASSEMBLY_UNDER_TEST_INST.SMARCHCHKB_MBIST_CTRL.BIST_CLK Period expect = %t actual = %t",
CLOCK_0_expected_period, CLOCK_0_measured_period);
increment_compareFailures;
end else begin
$display ($time,
" SMARCHCHKB_LVISION_MBISTPG_ASSEMBLY_UNDER_TEST_INST.SMARCHCHKB_MBIST_CTRL.BIST_CLK Period = %t as expected (within 1.0%% margin of %t) ", CLOCK_0_measured_period,CLOCK_0_expected_period);
increment_compareEvents;
end
end else begin
if (CLOCK_0_cycle_counter == 0 ) begin
$display ($time,
" Compare fail: SMARCHCHKB_LVISION_MBISTPG_ASSEMBLY_UNDER_TEST_INST.SMARCHCHKB_MBIST_CTRL.BIST_CLK Period expect = %t actual = n/a ( no transition detected )",
CLOCK_0_expected_period);
increment_compareFailures;
end else begin
$display ($time,
" Compare fail: SMARCHCHKB_LVISION_MBISTPG_ASSEMBLY_UNDER_TEST_INST.SMARCHCHKB_MBIST_CTRL.BIST_CLK Period expect = %t actual = %t ( did not receive the expected %0d cycles)",
CLOCK_0_expected_period,($time - CLOCK_0_start_time) / number_clock_cycles, number_clock_cycles);
increment_compareFailures;
end
end
// [end] : SMARCHCHKB_LVISION_MBISTPG_ASSEMBLY_UNDER_TEST_INST.SMARCHCHKB_MBIST_CTRL.BIST_CLK }}}
$display ($time, "");
`endif
end
`ifdef ENABLE_CLOCK_MONITOR
// [start] : SMARCHCHKB_LVISION_MBISTPG_ASSEMBLY_UNDER_TEST_INST.SMARCHCHKB_MBIST_CTRL.BIST_CLK {{{
always @(start_monitor_clocks) begin
forever begin
@(posedge CLOCK_0_clkNet) begin
if (~CLOCK_0_complete) begin
if ( CLOCK_0_cycle_counter == 0 ) begin
CLOCK_0_start_time = $time;
end
if ( CLOCK_0_cycle_counter >= number_clock_cycles ) begin
CLOCK_0_complete <= 1'b1;
CLOCK_0_measured_period = ($time - CLOCK_0_start_time) / number_clock_cycles;
end else begin
CLOCK_0_cycle_counter = CLOCK_0_cycle_counter + 1;
end
end
end
end
end
// [end] : SMARCHCHKB_LVISION_MBISTPG_ASSEMBLY_UNDER_TEST_INST.SMARCHCHKB_MBIST_CTRL.BIST_CLK }}}
`endif
task increment_compareEvents;
TB.checker_inst.number_compareEvents = TB.checker_inst.number_compareEvents + 1;
endtask
task increment_compareFailures;
begin
TB.checker_inst.number_compareEvents = TB.checker_inst.number_compareEvents + 1;
TB.checker_inst.number_compareFailures = TB.checker_inst.number_compareFailures + 1;
end
endtask
endmodule
|
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' SecureLaunch.vbs
' Launch the Web UI for Remote Administration in IE
'
' Copyright (c) Microsoft Corporation. All rights reserved.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
On Error Resume Next
webSrvName = GetWebSrvNum("Administration")
' Check if the Administration site exists
If Not (webSrvName = 0) Then
' Get the SSL port for the Admin site
Set oWebSrv = GetObject("IIS://localhost/w3svc/" & webSrvName)
sslPort = Split(oWebSrv.SecureBindings(0)(0), ":")
' Construct the URL
Set sysInfo = CreateObject("WinNTSystemInfo")
strURL = "https://" & sysInfo.ComputerName & ":" & sslPort(1) & "/"
' Open the URL with IE
Set WshShell = CreateObject("WScript.Shell")
strIExploreKey = "HKLM\Software\Microsoft\Windows\CurrentVersion\App Paths\IEXPLORE.EXE\"
strCommand = """" & WshShell.RegRead(strIExploreKey) & """ " & strURL
WshShell.Run strCommand, 3, FALSE
End If
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' GetWebSrvNum
' Get the number of the web site with the given name
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function GetWebSrvNum(strWebSiteName)
On Error Resume Next
GetWebSrvNum = 0
Const REGKEY_WEBFRAMEWORK = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\ServerAppliance\WebFramework\"
Set WshShell = CreateObject("WScript.Shell")
Dim nSiteID : nSiteID = WshShell.RegRead(REGKEY_WEBFRAMEWORK & strWebSiteName & "SiteID")
If (nSiteID <> 0) Then
Set oWebSite = GetObject("IIS://localhost/w3svc/" & nSiteID)
If Err.number = 0 Then
'The website exists
GetWebSrvNum = nSiteID
End If
Err.Clear
End If
End Function
|
Type point
x As Integer
y As Integer
End Type
|
For i = 0 To 20
WScript.StdOut.WriteLine Oct(i)
Next
|
<filename>Task/Look-and-say-sequence/VBA/look-and-say-sequence.vba<gh_stars>1-10
Public Sub LookAndSay(Optional Niter As Integer = 10)
'generate "Niter" members of the look-and-say sequence
'(argument is optional; default is 10)
Dim s As String 'look-and-say number
Dim news As String 'next number in sequence
Dim curdigit As String 'current digit in s
Dim newdigit As String 'next digit in s
Dim curlength As Integer 'length of current run
Dim p As Integer 'position in s
Dim L As Integer 'length of s
On Error GoTo Oops 'to catch overflow, i.e. number too long
'start with "1"
s = "1"
For i = 1 To Niter
'initialise
L = Len(s)
p = 1
curdigit = Left$(s, 1)
curlength = 1
news = ""
For p = 2 To L
'check next digit in s
newdigit = Mid$(s, p, 1)
If curdigit = newdigit Then 'extend current run
curlength = curlength + 1
Else ' "output" run and start new run
news = news & CStr(curlength) & curdigit
curdigit = newdigit
curlength = 1
End If
Next p
' "output" last run
news = news & CStr(curlength) & curdigit
Debug.Print news
s = news
Next i
Exit Sub
Oops:
Debug.Print
If Err.Number = 6 Then 'overflow
Debug.Print "Oops - number too long!"
Else
Debug.Print "Error: "; Err.Number, Err.Description
End If
End Sub
|
Debug.Print String(5, "x")
|
<reponame>LaudateCorpus1/RosettaCodeData<filename>Task/Date-format/VBA/date-format.vba
Function DateFormats()
Debug.Print Format(Date, "yyyy-mm-dd")
Debug.Print Format(Date, "dddd, mmmm dd yyyy")
End Function
|
<gh_stars>1-10
Function tpk(s)
arr = Split(s," ")
For i = UBound(arr) To 0 Step -1
n = fx(CDbl(arr(i)))
If n > 400 Then
WScript.StdOut.WriteLine arr(i) & " = OVERFLOW"
Else
WScript.StdOut.WriteLine arr(i) & " = " & n
End If
Next
End Function
Function fx(x)
fx = Sqr(Abs(x))+5*x^3
End Function
'testing the function
WScript.StdOut.Write "Please enter a series of numbers:"
list = WScript.StdIn.ReadLine
tpk(list)
|
'***************************************************************************
'This script tests associators methods on ISWbemServices and ISWbemObject
'***************************************************************************
On Error Resume Next
'Do it via a ISWbemServices
Set Service = GetObject("winmgmts:{impersonationLevel=impersonate}!root\cimv2")
Service.Security_.ImpersonationLevel = 3
if Err <> 0 Then
WScript.Echo Err.Description
Err.Clear
End if
Set Enumerator = Service.AssociatorsOf _
("Win32_DiskPartition.DeviceID=""Disk #0, Partition #1""", , "Win32_ComputerSystem",,,true)
for each Thingy in Enumerator
WScript.Echo Thingy.Path_.Relpath
next
'Do it via a ISWbemObject
Set Object = GetObject("winmgmts:Win32_DiskPartition")
for each Thingy in Object.Associators_ (,,,,,true)
WScript.Echo Thingy.Path_.Relpath
next
if Err <> 0 Then
WScript.Echo Err.Description
Err.Clear
End if
|
<reponame>LaudateCorpus1/RosettaCodeData<filename>Task/Stack/VBScript/stack-1.vb
class stack
dim tos
dim stack()
dim stacksize
private sub class_initialize
stacksize = 100
redim stack( stacksize )
tos = 0
end sub
public sub push( x )
stack(tos) = x
tos = tos + 1
end sub
public property get stackempty
stackempty = ( tos = 0 )
end property
public property get stackfull
stackfull = ( tos > stacksize )
end property
public property get stackroom
stackroom = stacksize - tos
end property
public function pop()
pop = stack( tos - 1 )
tos = tos - 1
end function
public sub resizestack( n )
redim preserve stack( n )
stacksize = n
if tos > stacksize then
tos = stacksize
end if
end sub
end class
dim s
set s = new stack
s.resizestack 10
wscript.echo s.stackempty
dim i
for i = 1 to 10
s.push rnd
wscript.echo s.stackroom
if s.stackroom = 0 then exit for
next
for i = 1 to 10
wscript.echo s.pop
if s.stackempty then exit for
next
|
'
' Updates an MSI package using the following paramaters
' szPackage - path to package to update. requires read/write access
' szBuildNumber - 4 digit build number of the current build, i.e 3610
'
' Syntax: cscript updatever.vbs package_path build_number
'
'
Sub Usage
Wscript.echo "SYNTAX:"
Wscript.echo "cscript updatever.vbs <package_path> <build_number>"
Wscript.echo " <package_path> - path to package to update. requires read/write access"
Wscript.echo " <build_number> - 4 digit build number of the current build, i.e 3456"
Wscript.Quit -1
End Sub
Function UpdateVer(szPackage, szBuildNumber )
Dim WSHShell, Installer, Database, SummaryInfo, Record, View, SQL
Wscript.echo "Updating MSI package: " & szPackage
Wscript.echo " Build: " & szBuildNumber
UpdateVer = 0
On Error Resume Next
'Create the MSI API object
Set Installer = CreateObject("WindowsInstaller.Installer")
If Err <> 0 Then
Set Installer = CreateObject("WindowsInstaller.Application")
End If
If Err <> 0 Then
Set Installer = CreateObject("Msi.ApiAutomation")
End if
If Err <> 0 Then
Wscript.echo "ERROR: Error creating Installer object"
UpdateVer = -1
End if
'Create the WSH shell object
Set WSHShell = CreateObject("WScript.Shell")
If Err <> 0 Then
Wscript.echo "ERROR: Error creating WSHShell object"
UpdateVer = -1
End if
'Open the package
Set Database = Installer.OpenDatabase(szPackage, 1)
If Err <> 0 Then
Wscript.echo "ERROR: Error opening database"
UpdateVer = -1
End if
Wscript.echo " Database opened for update"
'Set the product version property
SQL = "UPDATE Property SET Property.Value = '5.2." & szBuildNumber & "' WHERE Property.Property= 'ProductVersion'"
Set View = Database.OpenView( SQL )
If Err <> 0 Then
Wscript.echo Err.Number
Wscript.echo "ERROR: Error opening view: " & SQL
UpdateVer = -1
End if
View.Execute
If Err <> 0 Then
Wscript.echo "ERROR: Error executing view: " & SQL
UpdateVer = -1
End if
Wscript.echo " ProductVersion Property updated"
'Commit changes
Database.Commit
If Err <> 0 Then
Wscript.echo "ERROR: Error commiting changes: " & SQL
UpdateVer = -1
End if
Wscript.echo " Changes commited"
End Function
' main()
Set Args = Wscript.Arguments
Set FileSystem = CreateObject("Scripting.FileSystemObject")
If Args.Count <> 2 Then
Usage
End If
szPathToPackage = Args(0)
If not FileSystem.fileExists ( szPathToPackage ) Then
Wscript.echo "ERROR: Invalid path: " & szPathToPackage
Usage
End If
szBuild = Args(1)
iLen = Len(szBuild)
If (iLen <= 0) Or (iLen >4) Then
Wscript.echo "ERROR: Invalid build number: " & szBuild
Usage
End If
wscript.echo szPathToPackage, szBuild
status = UpdateVer( szPathToPackage, szBuild )
Wscript.Quit status
|
<filename>Task/Averages-Mode/VBA/averages-mode.vba
Public Sub main()
s = [{1,2,3,3,3,4,4,4,5,5,6}]
t = WorksheetFunction.Mode_Mult(s)
For Each x In t
Debug.Print x;
Next x
End Sub
|
<filename>net/rras/cps/pba/source/getdir.frm
'//+----------------------------------------------------------------------------
'//
'// File: getdir.frm
'//
'// Module: pbadmin.exe
'//
'// Synopsis: Directory location form
'//
'// Copyright (c) 1997-1999 Microsoft Corporation
'//
'// Author: quintinb Created Header 09/02/99
'//
'//+----------------------------------------------------------------------------
VERSION 5.00
Begin VB.Form frmGetDir
BorderStyle = 3 'Fixed Dialog
Caption = "Select a directory"
ClientHeight = 3720
ClientLeft = 4920
ClientTop = 1440
ClientWidth = 2850
Icon = "GetDir.frx":0000
KeyPreview = -1 'True
LinkTopic = "Form1"
MaxButton = 0 'False
MinButton = 0 'False
PaletteMode = 1 'UseZOrder
ScaleHeight = 3720
ScaleWidth = 2850
ShowInTaskbar = 0 'False
Begin VB.CommandButton OKButton
Caption = "ok"
Height = 375
Left = 195
TabIndex = 2
Top = 3225
Width = 1050
End
Begin VB.CommandButton CancelButton
Cancel = -1 'True
Caption = "cancel"
Height = 375
Left = 1560
TabIndex = 3
Top = 3225
Width = 1050
End
Begin VB.DriveListBox Drive1
Height = 360
HelpContextID = 11020
Left = 105
TabIndex = 0
Top = 120
WhatsThisHelpID = 11020
Width = 2625
End
Begin VB.DirListBox Dir1
Height = 2505
Left = 120
TabIndex = 1
Top = 540
WhatsThisHelpID = 11030
Width = 2595
End
End
Attribute VB_Name = "frmGetDir"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Option Explicit
Public SelDir As String
Private Sub CancelButton_Click()
SelDir = ""
Me.Hide
End Sub
Private Sub Drive1_Change()
On Error GoTo DriveErr
If Left(Dir1.path, 2) = Left(Drive1.Drive, 2) Then Exit Sub
Dir1.path = Drive1.Drive
Dir1.Refresh
On Error GoTo 0
Exit Sub
DriveErr:
MsgBox LoadResString(6023) & Chr(13) & Drive1.Drive, vbInformation
Drive1.Drive = Left(Dir1.path, 2)
Exit Sub
End Sub
Private Sub Form_Activate()
On Error GoTo ErrTrap
Dir1.path = SelDir
If Left(SelDir, 1) <> "\" Then
Drive1.Drive = Left(SelDir, 1)
Else
Drive1.ListIndex = -1
End If
On Error GoTo 0
Exit Sub
ErrTrap:
Exit Sub
End Sub
Private Sub Form_Deactivate()
Unload Me
End Sub
Private Sub Form_Load()
On Error GoTo LoadErr
CenterForm Me, Screen
Me.Caption = LoadResString(5205)
OKButton.Caption = LoadResString(1002)
CancelButton.Caption = LoadResString(1003)
SetFonts Me
On Error GoTo 0
Exit Sub
LoadErr:
Exit Sub
End Sub
Private Sub OKButton_Click()
On Error GoTo ErrTrap
If Len(Dir1.path) > 110 Then
MsgBox LoadResString(6059), 0
Dir1.SetFocus
Else
SelDir = Dir1.path
Me.Hide
End If
Exit Sub
ErrTrap:
Exit Sub
End Sub
|
<filename>Task/Probabilistic-choice/VBScript/probabilistic-choice.vb
item = Array("aleph","beth","gimel","daleth","he","waw","zayin","heth")
prob = Array(1/5.0, 1/6.0, 1/7.0, 1/8.0, 1/9.0, 1/10.0, 1/11.0, 1759/27720)
Dim cnt(7)
'Terminate script if sum of probabilities <> 1.
sum = 0
For i = 0 To UBound(prob)
sum = sum + prob(i)
Next
If sum <> 1 Then
WScript.Quit
End If
For trial = 1 To 1000000
r = Rnd(1)
p = 0
For i = 0 To UBound(prob)
p = p + prob(i)
If r < p Then
cnt(i) = cnt(i) + 1
Exit For
End If
Next
Next
WScript.StdOut.Write "item" & vbTab & "actual" & vbTab & vbTab & "theoretical"
WScript.StdOut.WriteLine
For i = 0 To UBound(item)
WScript.StdOut.Write item(i) & vbTab & FormatNumber(cnt(i)/1000000,6) & vbTab & FormatNumber(prob(i),6)
WScript.StdOut.WriteLine
Next
|
'...............................................................................
' Summary Copies the board outline as tracks and arcs onto specified layer.
' Layer and Width values to be specified by the user before proceeding.
'
' Version 1.0
'
' Copyright (c) 2004 by Altium Limited
'...............................................................................
Dim PCB_Board
'...............................................................................
'...............................................................................
Sub CopyBoardOutline(AWidth, ALayer)
Dim Track
Dim Arc
Dim I
Dim J
PCB_Board.BoardOutline.Invalidate
PCB_Board.BoardOutline.Rebuild
PCB_Board.BoardOutline.Validate
PCBServer.PreProcess
' Step through each of the vertices of the Board Outline in turn.
For I = 0 To PCB_Board.BoardOutline.PointCount - 1
' Set the value of J to point to the "next" vertex this is normally
' I + 1, but needs to be set to 0 instead for the very last vertex
' that is processed by this loop.
If I = PCB_Board.BoardOutline.PointCount - 1 Then
J = 0
Else
J = I + 1
End If
If PCB_Board.BoardOutline.Segments(I).Kind = ePolySegmentLine Then
' Current segment is a straight line create a Track object.
Track = PCBServer.PCBObjectFactory(eTrackObject, eNoDimension, eCreate_Default)
Track.X1 = PCB_Board.BoardOutline.Segments(I).vx
Track.Y1 = PCB_Board.BoardOutline.Segments(I).vy
Track.X2 = PCB_Board.BoardOutline.Segments(J).vx
Track.Y2 = PCB_Board.BoardOutline.Segments(J).vy
Track.Layer = ALayer
Track.Width = AWidth
PCB_Board.AddPCBObject(Track)
Else
' Current segment is an arc create an Arc object.
Arc = PCBServer.PCBObjectFactory(eArcObject, eNoDimension, eCreate_Default)
Arc.XCenter = PCB_Board.BoardOutline.Segments(I).cx
Arc.YCenter = PCB_Board.BoardOutline.Segments(I).cy
Arc.Layer = ALayer
Arc.LineWidth = AWidth
Arc.Radius = PCB_Board.BoardOutline.Segments(I).Radius
Arc.StartAngle = PCB_Board.BoardOutline.Segments(I).Angle1
Arc.EndAngle = PCB_Board.BoardOutline.Segments(I).Angle2
PCB_Board.AddPCBObject(Arc)
End If
Next
PCBServer.PostProcess
' Display (unconditionally) the layer selected by the user.
PCB_Board.LayerIsDisplayed(ALayer) = True
' Refresh PCB workspace.
ResetParameters
Call AddStringParameter("Action", "Redraw")
RunProcess("PCB:Zoom")
End Sub
'...............................................................................
'...............................................................................
Sub bCancelClick(Sender)
Close
End Sub
'...............................................................................
'...............................................................................
Sub bOKClick(Sender)
Dim Width
Dim Layer
If PCBServer Is Nothing Then Exit Sub
' Check PCB document exist and is not a library
Set PCB_Board = PCBServer.GetCurrentPCBBoard
If PCB_Board Is Nothing Then Exit Sub
' Note the Width is in Coord units.
Call StringToCoordUnit(eWidth.Text,Width,PCB_Board.DisplayUnit)
Layer = String2Layer(cbLayers.Items(cbLayers.ItemIndex))
Call CopyBoardOutline(Width,Layer)
Close
End Sub
'...............................................................................
'...............................................................................
|
<filename>drivers/storage/wmiprov/vds/test/scripts/defraganalysis.vbs
'//on error resume next
set objArgs = wscript.Arguments
if objArgs.count < 1 then
wscript.echo "Usage defragAnalysis volume"
wscript.quit(1)
end if
strVolume = Replace(objArgs(0), "\", "\\")
'// Get the volume
strQuery = "select * from Win32_Volume where Name = '" & strVolume & "'"
set VolumeSet = GetObject("winmgmts:").ExecQuery(strQuery)
for each obj in VolumeSet
set Volume = obj
exit for
next
wscript.echo "Volume: " & Volume.Name
Result = Volume.DefragAnalysis(fRecommended, objReport)
wscript.echo "result " & result
strMessage = MapErrorCode("Win32_Volume", "DefragAnalysis", Result)
wscript.echo "Volume.DefragAnalysis returned: " & Result & " : " & strMessage
if Result = 0 then
wscript.echo "Analysis Report"
wscript.echo ""
wscript.echo " Volume size = " & objReport.VolumeSize
wscript.echo " Cluster size = " & objReport.ClusterSize
wscript.echo " Used space = " & objReport.UsedSpace
wscript.echo " Free space = " & objReport.FreeSpace
wscript.echo " Percent free space = " & objReport.FreeSpacePercent
wscript.echo ""
wscript.echo "Volume fragmentation"
wscript.echo " Total fragmentation = " & objReport.TotalPercentFragmentation
wscript.echo " File fragmentation = " & objReport.FilePercentFragmentation
wscript.echo " Free space fragmentation = " & objReport.FreeSpacePercentFragmentation
wscript.echo ""
wscript.echo "File fragmentation"
wscript.echo " Total files = " & objReport.TotalFiles
wscript.echo " Average file size = " & objReport.AverageFileSize
wscript.echo " Total fragmented files = " & objReport.TotalFragmentedFiles
wscript.echo " Total excess fragments = " & objReport.TotalExcessFragments
wscript.echo " Average fragments per file = " & objReport.AverageFragmentsPerFile
wscript.echo ""
wscript.echo "Pagefile fragmentation"
wscript.echo " Pagefile size = " & objReport.PagefileSize
wscript.echo " Total fragments = " & objReport.TotalPagefileFragments
wscript.echo ""
wscript.echo "Folder fragmentation"
wscript.echo " Total folders = " & objReport.TotalFolders
wscript.echo " Fragmented folders = " & objReport.FragmentedFolders
wscript.echo " Excess folder fragments = " & objReport.ExcessFolderFragments
wscript.echo ""
wscript.echo "Master File Table (MFT) fragmentation"
wscript.echo " Total MFT size = " & objReport.TotalMFTSize
wscript.echo " MFT record count = " & objReport.MFTRecordCount
wscript.echo " Percent MFT in use = " & objReport.MFTPercentInUse
wscript.echo " Total MFT fragments = " & objReport.TotalMFTFragments
wscript.echo ""
if fRecommended = True then
wscript.echo "this volume should be defragged"
else
wscript.echo "this volume does not need to be defragged"
end if
end if
Function MapErrorCode(ByRef strClass, ByRef strMethod, ByRef intCode)
set objClass = GetObject("winmgmts:").Get(strClass, &h20000)
set objMethod = objClass.methods_(strMethod)
values = objMethod.qualifiers_("values")
if ubound(values) < intCode then
wscript.echo " FAILURE - no error message found for " & intCode & " : " & strClass & "." & strMethod
f.writeline ("FAILURE - no error message found for " & intCode & " : " & strClass & "." & strMethod)
MapErrorCode = ""
else
MapErrorCode = values(intCode)
end if
End Function
|
>cscript "C:\foo\assert.vbs"
C:\foo\assert.vbs(3, 3) (null): There's got to be more to life than this!
|
Dim WshShell
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.SendKeys "{Down}{F2}"
WScript.Sleep 1000 ' one-second delay
WshShell.SendKeys "{Left}{Left}{BkSp}{BkSp}Some text here.~" ' ~ -> Enter
|
<filename>Task/99-Bottles-of-Beer/VBScript/99-bottles-of-beer-3.vb
function pluralBottles( n )
select case n
case 1
pluralBottles = "one bottle"
case 0
pluralBottles = "no more bottles"
case else
pluralBottles = n & " bottles"
end select
end function
function eef( b, r1, r2 )
if b then
eef = r1
else
eef = r2
end if
end function
Function evalEmbedded(sInput, sP1)
dim oRe, oMatch, oMatches
dim sExpr, sResult
Set oRe = New RegExp
'Look for expressions as enclosed in braces
oRe.Pattern = "{(.+?)}"
sResult = sInput
do
Set oMatches = oRe.Execute(sResult)
if oMatches.count = 0 then exit do
for each oMatch in oMatches
'~ wscript.echo oMatch.Value
for j = 0 to omatch.submatches.count - 1
sExpr = omatch.submatches(j)
sResult = Replace( sResult, "{" & sExpr & "}", eval(sExpr) )
next
next
loop
evalEmbedded = sResult
End Function
sub sing( numBottles )
dim i
for i = numBottles to 0 step -1
if i = 0 then
wscript.echo evalEmbedded("no more bottles of beer on the wall" & vbNewline & _
"no more bottles of beer" & vbNewline & _
"go to the store and buy some more" & vbNewline & _
"{pluralBottles(sP1)} of beer on the wall" & vbNewline, numBottles)
else
wscript.echo evalEmbedded("{pluralBottles(sP1)} of beer on the wall" & vbNewline & _
"{pluralBottles(sP1)} of beer" & vbNewline & _
"take {eef(sP1=1,""it"",""one"")} down and pass it round" & vbNewline & _
"{pluralBottles(sP1-1)} of beer on the wall" & vbNewline, i)
end if
next
end sub
sing 3
|
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_
"\unixdict.txt",1)
Set objUnixDict = CreateObject("Scripting.Dictionary")
Set objSemordnilap = CreateObject("Scripting.Dictionary")
Do Until objInFile.AtEndOfStream
line = objInFile.ReadLine
If Len(line) > 1 Then
objUnixDict.Add line,""
End If
reverse_line = StrReverse(line)
If reverse_line <> line And objUnixDict.Exists(reverse_line) Then
objSemordnilap.Add line, reverse_line
End If
Loop
'Display the first 5 keys.
k = 0
For Each Key In objSemordnilap.Keys
WScript.StdOut.Write Key & " - " & objSemordnilap.Item(Key)
WScript.StdOut.WriteLine
k = k + 1
If k = 5 Then
Exit For
End If
Next
WScript.StdOut.Write "Total Count: " & objSemordnilap.Count
WScript.StdOut.WriteLine
objInFile.Close
Set objFSO = Nothing
Set objUnixDict = Nothing
Set objSemordnilap = Nothing
|
<filename>admin/pchealth/authtools/prodtools/applets/hhts2mdb/database.bas
Attribute VB_Name = "Database"
Option Explicit
Private p_cnn As ADODB.Connection
Private p_intSKU As Long
Private p_intAuthoringGroup As Long
Private p_strUserName As String
Private p_dictStopSigns As Scripting.Dictionary
Private p_dictStopWords As Scripting.Dictionary
Private p_dictKeywords As Scripting.Dictionary
Private p_dictSynonymSets As Scripting.Dictionary
Private p_dictSynonyms As Scripting.Dictionary
Private p_dictTaxonomyNodes As Scripting.Dictionary
Private Const EID_KID_SEPARATOR_C As String = "/"
Private Const KEY_PREFIX_C As String = "KEY"
Private Const ROOT_KEY_C As String = "KEY1"
Private Const SYNONYM_C As String = "SYNONYM"
Private Const SUPER_KEYWORD_C As String = "SuperKeyword"
Private Const SYNSET_ID_C As String = "ID"
Private Const HHT_OPERATOR_C As String = "OPERATOR"
Private Const HHT_OPERATION_C As String = "OPERATION"
Private Const OPERATOR_SEPARATOR_C As String = ";"
Public Sub OpenDatabaseAndSetSKU( _
ByVal i_strDatabase As String, _
ByVal i_intSKU As Long _
)
On Error GoTo LError
p_AllocateDBGlobals
p_cnn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & i_strDatabase & ";"
p_intSKU = i_intSKU
p_intAuthoringGroup = GetParameter(p_cnn, AUTHORING_GROUP_C)
p_strUserName = GetUserName1
p_ReadDatabase
LEnd:
Exit Sub
LError:
Err.Raise E_FAIL, , "Unable to open database " & i_strDatabase & ": " & Err.Description
End Sub
Public Sub ImportTaxonomyEntry( _
ByVal i_DOMNode As MSXML2.IXMLDOMNode _
)
On Error GoTo LError
Dim rs As ADODB.Recordset
Dim strQuery As String
Dim intParentTID As Long
Dim intOrderUnderParent As Long
Dim strCategory As String
Dim strEntry As String
Dim strNewCategory As String
Dim strVisible As String
Dim strSubSite As String
Dim blnLeaf As Boolean
Dim intTID As Long
strCategory = XMLGetAttribute(i_DOMNode, HHT_CATEGORY_C)
If (Not p_dictTaxonomyNodes.Exists(strCategory)) Then
Err.Raise E_FAIL, , "Category " & strCategory & " doesn't exist"
Exit Sub
End If
intParentTID = p_dictTaxonomyNodes(strCategory)(0)
intOrderUnderParent = p_dictTaxonomyNodes(strCategory)(1)
Set rs = New ADODB.Recordset
strQuery = "" & _
"SELECT * " & _
"FROM Taxonomy"
rs.Open strQuery, p_cnn, adOpenForwardOnly, adLockOptimistic
strEntry = XMLGetAttribute(i_DOMNode, HHT_ENTRY_C)
blnLeaf = IIf((strEntry = ""), True, False)
strVisible = XMLGetAttribute(i_DOMNode, HHT_VISIBLE_C)
strSubSite = XMLGetAttribute(i_DOMNode, HHT_SUBSITE_C)
rs.AddNew
rs("ModifiedTime") = Now
rs("Comments") = ""
rs("ENUTitle") = p_GetValue(i_DOMNode, HHT_TITLE_C)
rs("ENUDescription") = p_GetValue(i_DOMNode, HHT_DESCRIPTION_C)
rs("Type") = XMLGetAttribute(i_DOMNode, HHT_TYPE_C)
rs("ContentURI") = XMLGetAttribute(i_DOMNode, HHT_URI_C)
rs("SKUs") = p_intSKU
rs("ParentTID") = intParentTID
rs("Leaf") = blnLeaf
rs("BaseFile") = ""
rs("LocInclude") = LOC_INCLUDE_ALL_C
rs("Visible") = IIf((strVisible = ""), True, strVisible)
rs("Keywords") = GetKeywords(p_cnn, i_DOMNode, p_dictKeywords)
rs("OrderUnderParent") = intOrderUnderParent
rs("AuthoringGroup") = p_intAuthoringGroup
rs("IconURI") = XMLGetAttribute(i_DOMNode, HHT_ICONURI_C)
rs("SubSite") = IIf((strSubSite = ""), False, strSubSite)
rs("Username") = p_strUserName
rs("Entry") = strEntry
rs("NavigationModel") = p_GetNavigationModel(i_DOMNode)
rs.Update
intTID = rs("TID")
p_dictTaxonomyNodes(strCategory) = Array(intParentTID, intOrderUnderParent + 1)
If (Not blnLeaf) Then
strNewCategory = strCategory
If (strNewCategory <> "") Then
strNewCategory = strNewCategory & "/" & strEntry
Else
strNewCategory = strEntry
End If
p_dictTaxonomyNodes.Add strNewCategory, Array(intTID, MAX_ORDER_C)
End If
LEnd:
Exit Sub
LError:
Err.Raise E_FAIL, , "While importing " & i_DOMNode.XML & ": " & Err.Description
End Sub
Public Sub ImportOperators( _
ByVal i_DOMNodeList As MSXML2.IXMLDOMNodeList _
)
Dim strOperator As String
Dim strOperation As String
Dim strOperatorsAnd As String
Dim strOperatorsOr As String
Dim strOperatorsNot As String
Dim DOMNode As MSXML2.IXMLDOMNode
strOperatorsAnd = GetParameter(p_cnn, OPERATORS_AND_C) & ""
strOperatorsOr = GetParameter(p_cnn, OPERATORS_OR_C) & ""
strOperatorsNot = GetParameter(p_cnn, OPERATORS_NOT_C) & ""
For Each DOMNode In i_DOMNodeList
strOperator = XMLGetAttribute(DOMNode, HHT_OPERATOR_C)
strOperation = UCase$(XMLGetAttribute(DOMNode, HHT_OPERATION_C))
Select Case strOperation
Case "AND"
If (strOperatorsAnd = "") Then
strOperatorsAnd = strOperator
Else
strOperatorsAnd = strOperatorsAnd & OPERATOR_SEPARATOR_C & strOperator
End If
Case "OR"
If (strOperatorsOr = "") Then
strOperatorsOr = strOperator
Else
strOperatorsOr = strOperatorsOr & OPERATOR_SEPARATOR_C & strOperator
End If
Case "NOT"
If (strOperatorsNot = "") Then
strOperatorsNot = strOperator
Else
strOperatorsNot = strOperatorsNot & OPERATOR_SEPARATOR_C & strOperator
End If
End Select
Next
SetParameter p_cnn, OPERATORS_AND_C, strOperatorsAnd
SetParameter p_cnn, OPERATORS_OR_C, strOperatorsOr
SetParameter p_cnn, OPERATORS_NOT_C, strOperatorsNot
End Sub
Public Sub ImportStopSign( _
ByVal i_DOMNode As MSXML2.IXMLDOMNode _
)
Dim strStopSign As String
Dim strContext As String
Dim intContext As Long
Dim rs As ADODB.Recordset
Dim strQuery As String
strStopSign = XMLGetAttribute(i_DOMNode, HHT_STOPSIGN_C)
strContext = UCase$(XMLGetAttribute(i_DOMNode, HHT_CONTEXT_C))
Select Case strContext
Case HHTVAL_ANYWHERE_C
intContext = CONTEXT_ANYWHERE_E
Case Else
intContext = CONTEXT_AT_END_OF_WORD_E
End Select
If (p_dictStopSigns.Exists(strStopSign)) Then
If (p_dictStopSigns(strStopSign) <> intContext) Then
frmMain.Output "Existing StopSign """ & strStopSign & """ has opposite context", LOGGING_TYPE_WARNING_E
End If
Exit Sub
End If
Set rs = New ADODB.Recordset
strQuery = "" & _
"SELECT * " & _
"FROM StopSigns"
rs.Open strQuery, p_cnn, adOpenForwardOnly, adLockOptimistic
rs.AddNew
rs("StopSign") = strStopSign
rs("Context") = intContext
rs.Update
p_dictStopSigns.Add strStopSign, intContext
End Sub
Public Sub ImportStopWord( _
ByVal i_DOMNode As MSXML2.IXMLDOMNode _
)
Dim strStopWord As String
Dim rs As ADODB.Recordset
Dim strQuery As String
strStopWord = XMLGetAttribute(i_DOMNode, HHT_STOPWORD_C)
If (p_dictStopWords.Exists(strStopWord)) Then
Exit Sub
End If
Set rs = New ADODB.Recordset
strQuery = "" & _
"SELECT * " & _
"FROM StopWords"
rs.Open strQuery, p_cnn, adOpenForwardOnly, adLockOptimistic
rs.AddNew
rs("StopWord") = strStopWord
rs.Update
p_dictStopWords.Add strStopWord, True
End Sub
Public Sub ImportSynset( _
ByVal i_DOMNode As MSXML2.IXMLDOMNode _
)
' The error handling is a hack. It is required, because a synonym set may have
' 2 keywords: "800 X 600" and "800 x 600". However, they are the same keyword.
' So rs2.Update will fail. The solution is to remember that we have already
' created the synonym and not try to create it again.
On Error Resume Next
Dim rs1 As ADODB.Recordset
Dim rs2 As ADODB.Recordset
Dim strQuery As String
Dim intEID As Long
Dim intKID As Long
Dim DOMNode As MSXML2.IXMLDOMNode
Dim strKeyword As String
' Dim blnSynonymSetNamed As Boolean
intEID = XMLGetAttribute(i_DOMNode, SYNSET_ID_C)
Set rs1 = New ADODB.Recordset
strQuery = "" & _
"SELECT * " & _
"FROM SynonymSets"
rs1.Open strQuery, p_cnn, adOpenForwardOnly, adLockOptimistic
rs1.AddNew
rs1("Name") = "Not named yet"
rs1("EID") = intEID
rs1.Update
Set rs2 = New ADODB.Recordset
strQuery = "" & _
"SELECT * " & _
"FROM Synonyms"
rs2.Open strQuery, p_cnn, adOpenForwardOnly, adLockOptimistic
If (Not i_DOMNode.firstChild Is Nothing) Then
For Each DOMNode In i_DOMNode.childNodes
If (DOMNode.baseName = SYNONYM_C) Then
strKeyword = DOMNode.Text
If (strKeyword <> "") Then
intKID = GetKID(p_cnn, strKeyword, p_dictKeywords)
rs2.AddNew
rs2("EID") = intEID
rs2("KID") = intKID
rs2.Update
' If (Not blnSynonymSetNamed) Then
' rs1("Name") = strKeyword
' rs1.Update
' blnSynonymSetNamed = True
' End If
End If
ElseIf (DOMNode.baseName = SUPER_KEYWORD_C) Then
rs1("Name") = DOMNode.Text
rs1.Update
End If
Next
End If
End Sub
Public Sub SetDomFragment( _
ByVal i_strXML As String _
)
Dim strName As String
Dim strXML As String
strName = DOM_FRAGMENT_HHT_C & p_intSKU
strXML = GetParameter(p_cnn, strName) & vbCrLf & i_strXML
SetParameter p_cnn, strName, strXML
End Sub
Public Sub FinalizeDatabase( _
)
FixOrderingNumbers p_cnn
End Sub
Private Function p_GetValue( _
ByVal i_DOMNode As MSXML2.IXMLDOMNode, _
ByVal i_strName As String _
) As String
On Error Resume Next
Dim str As String
str = XMLGetAttribute(i_DOMNode, i_strName)
If (str = "") Then
str = i_DOMNode.selectSingleNode(i_strName).Text
End If
p_GetValue = str
End Function
Private Function p_GetNavigationModel( _
ByVal i_DOMNode As MSXML2.IXMLDOMNode _
) As Long
Dim str As String
str = LCase$(XMLGetAttribute(i_DOMNode, HHT_NAVIGATIONMODEL_C))
Select Case str
Case NAVMODEL_SERVER_STR_C
p_GetNavigationModel = NAVMODEL_SERVER_NUM_C
Case NAVMODEL_DESKTOP_STR_C
p_GetNavigationModel = NAVMODEL_DESKTOP_NUM_C
Case Else
p_GetNavigationModel = NAVMODEL_DEFAULT_NUM_C
End Select
End Function
Private Sub p_AllocateDBGlobals()
Set p_cnn = New ADODB.Connection
Set p_dictStopSigns = New Scripting.Dictionary
Set p_dictStopWords = New Scripting.Dictionary
p_dictStopWords.CompareMode = TextCompare
Set p_dictKeywords = New Scripting.Dictionary
p_dictKeywords.CompareMode = TextCompare
Set p_dictSynonymSets = New Scripting.Dictionary
Set p_dictSynonyms = New Scripting.Dictionary
Set p_dictTaxonomyNodes = New Scripting.Dictionary
p_dictTaxonomyNodes.CompareMode = TextCompare
End Sub
Private Sub p_ReadDatabase()
p_ReadStopSigns
p_ReadStopWords
p_ReadKeywords
p_ReadSynonymSets
p_ReadSynonyms
p_ReadTaxonomyNodes
End Sub
Private Sub p_ReadStopSigns()
Dim rs As ADODB.Recordset
Dim strQuery As String
frmMain.Output "Reading existing Stop Signs", LOGGING_TYPE_NORMAL_E
Set rs = New ADODB.Recordset
strQuery = "" & _
"SELECT * " & _
"FROM StopSigns"
rs.Open strQuery, p_cnn, adOpenForwardOnly, adLockReadOnly
Do While (Not rs.EOF)
p_dictStopSigns.Add rs("StopSign").Value, rs("Context").Value
DoEvents
rs.MoveNext
Loop
End Sub
Private Sub p_ReadStopWords()
Dim rs As ADODB.Recordset
Dim strQuery As String
frmMain.Output "Reading existing Stop Words", LOGGING_TYPE_NORMAL_E
Set rs = New ADODB.Recordset
strQuery = "" & _
"SELECT * " & _
"FROM StopWords"
rs.Open strQuery, p_cnn, adOpenForwardOnly, adLockReadOnly
Do While (Not rs.EOF)
p_dictStopWords.Add rs("StopWord").Value, True
DoEvents
rs.MoveNext
Loop
End Sub
Private Sub p_ReadKeywords()
Dim rs As ADODB.Recordset
Dim strQuery As String
frmMain.Output "Reading existing Keywords", LOGGING_TYPE_NORMAL_E
Set rs = New ADODB.Recordset
strQuery = "" & _
"SELECT * " & _
"FROM Keywords"
rs.Open strQuery, p_cnn, adOpenForwardOnly, adLockReadOnly
Do While (Not rs.EOF)
p_dictKeywords.Add rs("Keyword").Value, rs("KID").Value
DoEvents
rs.MoveNext
Loop
End Sub
Private Sub p_ReadSynonymSets()
Dim rs As ADODB.Recordset
Dim strQuery As String
frmMain.Output "Reading existing Synonym Sets", LOGGING_TYPE_NORMAL_E
Set rs = New ADODB.Recordset
strQuery = "" & _
"SELECT * " & _
"FROM SynonymSets"
rs.Open strQuery, p_cnn, adOpenForwardOnly, adLockReadOnly
Do While (Not rs.EOF)
p_dictSynonymSets.Add rs("Name").Value, rs("EID").Value
DoEvents
rs.MoveNext
Loop
End Sub
Private Sub p_ReadSynonyms()
Dim rs As ADODB.Recordset
Dim strQuery As String
frmMain.Output "Reading existing Synonyms", LOGGING_TYPE_NORMAL_E
Set rs = New ADODB.Recordset
strQuery = "" & _
"SELECT * " & _
"FROM Synonyms"
rs.Open strQuery, p_cnn, adOpenForwardOnly, adLockReadOnly
Do While (Not rs.EOF)
p_dictSynonyms.Add rs("EID").Value & EID_KID_SEPARATOR_C & rs("KID").Value, True
DoEvents
rs.MoveNext
Loop
End Sub
Private Sub p_ReadTaxonomyNodes()
Dim rs As ADODB.Recordset
Dim strQuery As String
Dim dict As Scripting.Dictionary
frmMain.Output "Reading existing Taxonomy Nodes", LOGGING_TYPE_NORMAL_E
Set rs = New ADODB.Recordset
Set dict = New Scripting.Dictionary
strQuery = "" & _
"SELECT * " & _
"FROM Taxonomy"
rs.Open strQuery, p_cnn, adOpenForwardOnly, adLockReadOnly
Do While (Not rs.EOF)
If (Not rs("Leaf").Value) Then
dict.Add KEY_PREFIX_C & rs("TID").Value, _
Array("", rs("Entry").Value, rs("ParentTID").Value)
End If
DoEvents
rs.MoveNext
Loop
p_PopulateDictTaxonomyNodes dict
End Sub
Private Sub p_PopulateDictTaxonomyNodes( _
ByVal i_dict As Scripting.Dictionary _
)
Dim vntKey As Variant
Dim intKey As Long
For Each vntKey In i_dict.Keys
p_SetCategory i_dict, vntKey
Next
For Each vntKey In i_dict.Keys
intKey = Mid$(vntKey, 4) ' Get rid of KEY_PREFIX_C
p_dictTaxonomyNodes.Add i_dict(vntKey)(0), Array(intKey, MAX_ORDER_C)
Next
End Sub
Private Sub p_SetCategory( _
ByVal i_dict As Scripting.Dictionary, _
ByVal i_strKey As String _
)
Dim strParentKey As String
Dim strParentCategory As String ' The Category represented by the Node, not the Category of the Node.
Dim strCategory As String
Dim vnt As Variant
If (i_strKey = ROOT_KEY_C) Then
Exit Sub
End If
vnt = i_dict(i_strKey)
strParentKey = KEY_PREFIX_C & vnt(2)
If (i_dict(strParentKey)(0) = "") Then
p_SetCategory i_dict, strParentKey
End If
strParentCategory = i_dict(strParentKey)(0)
If (strParentKey = ROOT_KEY_C) Then
strCategory = vnt(1)
Else
strCategory = strParentCategory & "/" & vnt(1)
End If
i_dict(i_strKey) = Array(strCategory, vnt(1), vnt(2))
End Sub
|
' Windows Installer utility to report or update file versions, sizes, languages
' For use with Windows Scripting Host, CScript.exe or WScript.exe
' Copyright (c) 1999-2000, Microsoft Corporation
' Demonstrates the access to install engine and actions
'
Option Explicit
' FileSystemObject.CreateTextFile and FileSystemObject.OpenTextFile
Const OpenAsASCII = 0
Const OpenAsUnicode = -1
' FileSystemObject.CreateTextFile
Const OverwriteIfExist = -1
Const FailIfExist = 0
' FileSystemObject.OpenTextFile
Const OpenAsDefault = -2
Const CreateIfNotExist = -1
Const FailIfNotExist = 0
Const ForReading = 1
Const ForWriting = 2
Const ForAppending = 8
Const msiOpenDatabaseModeReadOnly = 0
Const msiOpenDatabaseModeTransact = 1
Const msiViewModifyInsert = 1
Const msiViewModifyUpdate = 2
Const msiViewModifyAssign = 3
Const msiViewModifyReplace = 4
Const msiViewModifyDelete = 6
Const msiUILevelNone = 2
Const msiRunModeSourceShortNames = 9
Const msidbFileAttributesNoncompressed = &h00002000
Dim argCount:argCount = Wscript.Arguments.Count
Dim iArg:iArg = 0
If argCount > 0 Then If InStr(1, Wscript.Arguments(0), "?", vbTextCompare) > 0 Then argCount = 0
If (argCount < 1) Then
Wscript.Echo "Windows Installer utility to updata File table sizes and versions" &_
vbNewLine & " The 1st argument is the path to MSI database, at the source file root" &_
vbNewLine & " The 2nd argument can optionally specify separate source location from the MSI" &_
vbNewLine & " The following options may be specified at any point on the command line" &_
vbNewLine & " /U to update the MSI database with the file sizes, versions, and languages" &_
vbNewLine & " Notes:" &_
vbNewLine & " If source type set to compressed, all files will be opened at the root" &_
vbNewLine & " Using CSCRIPT.EXE without the /U option, the file info will be displayed" &_
vbNewLine &_
vbNewLine & "Copyright (C) Microsoft Corporation, 1999-2000. All rights reserved."
Wscript.Quit 1
End If
' Get argument values, processing any option flags
Dim updateMsi : updateMsi = False
Dim sequenceFile : sequenceFile = False
Dim databasePath : databasePath = NextArgument
Dim sourceFolder : sourceFolder = NextArgument
If Not IsEmpty(NextArgument) Then Fail "More than 2 arguments supplied" ' process any trailing options
If Not IsEmpty(sourceFolder) And Right(sourceFolder, 1) <> "\" Then sourceFolder = sourceFolder & "\"
Dim console : If UCase(Mid(Wscript.FullName, Len(Wscript.Path) + 2, 1)) = "C" Then console = True
' Connect to Windows Installer object
On Error Resume Next
Dim installer : Set installer = Nothing
Set installer = Wscript.CreateObject("WindowsInstaller.Installer") : CheckError
' Check if multiple language package, and force use of primary language
REM Set sumInfo = database.SummaryInformation(3) : CheckError
' Open database
Dim database, openMode, view, record, updateMode, sumInfo
If updateMsi Then openMode = msiOpenDatabaseModeTransact Else openMode = msiOpenDatabaseModeReadOnly
Set database = installer.OpenDatabase(databasePath, openMode) : CheckError
' Create an install session and execute actions in order to perform directory resolution
installer.UILevel = msiUILevelNone
Dim session : Set session = installer.OpenPackage(database,1) : If Err <> 0 Then Fail "Database: " & databasePath & ". Invalid installer package format"
Dim shortNames : shortNames = session.Mode(msiRunModeSourceShortNames) : CheckError
If Not IsEmpty(sourceFolder) Then session.Property("OriginalDatabase") = sourceFolder : CheckError
Dim stat : stat = session.DoAction("CostInitialize") : CheckError
If stat <> 1 Then Fail "CostInitialize failed, returned " & stat
' Join File table to Component table in order to find directories
Dim orderBy : If sequenceFile Then orderBy = "Directory_" Else orderBy = "Sequence"
Set view = database.OpenView("SELECT File,FileName,Directory_,FileSize,Version,Language FROM File,Component WHERE Component_=Component ORDER BY " & orderBy) : CheckError
view.Execute : CheckError
' Fetch each file and request the source path, then verify the source path, and get the file info if present
Dim fileKey, fileName, folder, sourcePath, fileSize, version, language, delim, message, info
Do
Set record = view.Fetch : CheckError
If record Is Nothing Then Exit Do
REM fileKey = record.StringData(1)
fileName = record.StringData(2)
folder = record.StringData(3)
REM fileSize = record.IntegerData(4)
REM version = record.StringData(5)
REM language = record.StringData(6)
delim = InStr(1, fileName, "|", vbTextCompare)
If delim <> 0 Then
If shortNames Then fileName = Left(fileName, delim-1) Else fileName = Right(fileName, Len(fileName) - delim)
End If
sourcePath = session.SourcePath(folder) & fileName
If installer.FileAttributes(sourcePath) = -1 Then
message = message & vbNewLine & sourcePath
Else
fileSize = installer.FileSize(sourcePath) : CheckError
version = Empty : version = installer.FileVersion(sourcePath, False) : Err.Clear ' early MSI implementation fails if no version
language = Empty : language = installer.FileVersion(sourcePath, True) : Err.Clear ' early MSI implementation doesn't support language
If language = version Then language = Empty ' Temp check for MSI.DLL version without language support
If Err <> 0 Then version = Empty : Err.Clear
If updateMsi Then
record.IntegerData(4) = fileSize
If Len(version) > 0 Then record.StringData(5) = version
If Len(language) > 0 Then record.StringData(6) = language
view.Modify msiViewModifyUpdate, record : CheckError
ElseIf console Then
info = fileName : If Len(info) < 12 Then info = info & Space(12 - Len(info))
info = info & " size=" & fileSize : If Len(info) < 26 Then info = info & Space(26 - Len(info))
If Len(version) > 0 Then info = info & " vers=" & version : If Len(info) < 45 Then info = info & Space(45 - Len(info))
If Len(language) > 0 Then info = info & " lang=" & language
Wscript.Echo info
End If
End If
Loop
REM Wscript.Echo "SourceDir = " & session.Property("SourceDir")
If Not IsEmpty(message) Then Fail "Error, the following files were not available:" & message
' Update SummaryInformation
If updateMsi Then
Set sumInfo = database.SummaryInformation(3) : CheckError
sumInfo.Property(11) = Now
sumInfo.Property(13) = Now
sumInfo.Persist
End If
' Commit database in case updates performed
database.Commit : CheckError
Wscript.Quit 0
' Extract argument value from command line, processing any option flags
Function NextArgument
Dim arg
Do ' loop to pull in option flags until an argument value is found
If iArg >= argCount Then Exit Function
arg = Wscript.Arguments(iArg)
iArg = iArg + 1
If (AscW(arg) <> AscW("/")) And (AscW(arg) <> AscW("-")) Then Exit Do
Select Case UCase(Right(arg, Len(arg)-1))
Case "U" : updateMsi = True
Case Else: Wscript.Echo "Invalid option flag:", arg : Wscript.Quit 1
End Select
Loop
NextArgument = arg
End Function
Sub CheckError
Dim message, errRec
If Err = 0 Then Exit Sub
message = Err.Source & " " & Hex(Err) & ": " & Err.Description
If Not installer Is Nothing Then
Set errRec = installer.LastErrorRecord
If Not errRec Is Nothing Then message = message & vbNewLine & errRec.FormatText
End If
Fail message
End Sub
Sub Fail(message)
Wscript.Echo message
Wscript.Quit 2
End Sub
|
<reponame>LaudateCorpus1/RosettaCodeData
s = "bar"
s = "foo" & s
WScript.Echo s
|
' starts the RRAS snapin's Routing and Remote Access Server Setup Wizard
option explicit
Dim mmc
Set mmc = CreateObject("MMC20.Application")
' msgbox(1)
' uncomment this to cause the MMC console to appear
' Dim frame
' Set frame = mmc.Frame
' frame.restore
' since the RRAS snapin does not automatically add the local computer
' to the scope pane, which is lame, we have to load their saved console
' file to do so.
mmc.load("rrasmgmt.msc")
' Dim snapins
' Set snapins = doc.snapins
'Dim snapin
'const RAS_SNAPIN_CLSID = "{1AA7F839-C7F5-11D0-A376-00C04FC9DA04}"
' if RAS is not installed, this will fail.
'set snapin = snapins.Add(RAS_SNAPIN_CLSID)
' msgbox("snapin added")
Dim doc
Set doc = mmc.Document
Dim views
Set views = doc.views
Dim view
Set view = views(1)
Dim namespace
Set namespace = doc.ScopeNamespace
Dim rootnode
Set rootnode = namespace.GetRoot
View.ActiveScopeNode = namespace.GetChild(rootnode)
View.ActiveScopeNode = namespace.GetChild(View.ActiveScopeNode)
View.ActiveScopeNode = namespace.GetNext(View.ActiveScopeNode)
' how do I get the snapin to add the local server to the scope node?
' msgbox("about to exec menu")
Dim menu
Set menu = view.ScopeNodeContextMenu
Dim menuItem
Set menuItem = menu.item(2)
menuItem.Execute
doc.Close(FALSE)
|
VERSION 5.00
Begin VB.Form ServerProperty
Caption = "Server Properties"
ClientHeight = 5475
ClientLeft = 5970
ClientTop = 4065
ClientWidth = 6405
LinkTopic = "Form1"
ScaleHeight = 5475
ScaleWidth = 6405
Begin VB.OptionButton UnpauseQueue
Caption = "Unpause Server Queue"
Height = 375
Left = 2400
TabIndex = 17
Top = 1800
Width = 2055
End
Begin VB.OptionButton PauseQueue
Caption = "Pause Server Queue"
Height = 375
Left = 360
TabIndex = 16
Top = 1800
Width = 2175
End
Begin VB.CommandButton Cancel
Caption = "Cancel"
BeginProperty Font
Name = "Palatino Linotype"
Size = 11.25
Charset = 0
Weight = 700
Underline = 0 'False
Italic = 0 'False
Strikethrough = 0 'False
EndProperty
Height = 495
Left = 2760
TabIndex = 15
Top = 4800
Width = 3375
End
Begin VB.CommandButton OK
Caption = "OK"
BeginProperty Font
Name = "Palatino Linotype"
Size = 11.25
Charset = 0
Weight = 700
Underline = 0 'False
Italic = 0 'False
Strikethrough = 0 'False
EndProperty
Height = 495
Left = 240
TabIndex = 14
Top = 4800
Width = 2295
End
Begin VB.CheckBox UseDeviceTsid
Caption = "Use Device Tsid"
Height = 495
Left = 3600
TabIndex = 12
Top = 1200
Width = 1695
End
Begin VB.TextBox SvcMapiProfile
Height = 495
Left = 2640
TabIndex = 10
Top = 3840
Width = 3015
End
Begin VB.TextBox ArchiveDir
Height = 495
Left = 1560
TabIndex = 6
Top = 2880
Width = 4095
End
Begin VB.CheckBox ArchiveFaxes
Caption = "Enable"
Height = 495
Left = 480
TabIndex = 5
Top = 2880
Width = 2175
End
Begin VB.CheckBox ServerCoverpg
Caption = "Allow Server Coverpages only"
Height = 495
Left = 3600
TabIndex = 4
Top = 720
Width = 2535
End
Begin VB.CheckBox Branding
Caption = "Page Branding"
Height = 495
Left = 3600
TabIndex = 3
Top = 240
Width = 1575
End
Begin VB.TextBox DirtyDays
Height = 375
Left = 1440
TabIndex = 2
Top = 1200
Width = 1815
End
Begin VB.TextBox RetryDelay
Height = 375
Left = 1440
TabIndex = 1
Top = 720
Width = 1815
End
Begin VB.TextBox Retries
Height = 375
Left = 1440
TabIndex = 0
Top = 240
Width = 1815
End
Begin VB.Frame Frame1
Caption = "Archive Outgoing Faxes"
Height = 1215
Left = 240
TabIndex = 13
Top = 2400
Width = 5655
End
Begin VB.Label Label5
Caption = "Server MAPI Profile:"
Height = 375
Left = 480
TabIndex = 11
Top = 3960
Width = 1935
End
Begin VB.Label Label4
Caption = "Dirty Days:"
Height = 255
Left = 240
TabIndex = 9
Top = 1320
Width = 1095
End
Begin VB.Label Label3
Caption = "Retry Delay:"
Height = 255
Left = 240
TabIndex = 8
Top = 840
Width = 1095
End
Begin VB.Label Label2
Caption = "Retries:"
Height = 255
Left = 360
TabIndex = 7
Top = 360
Width = 855
End
End
Attribute VB_Name = "ServerProperty"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Private Sub Cancel_Click()
Unload ServerProperty
End Sub
Private Sub Form_Load()
GetServerProperties
End Sub
Sub GetServerProperties()
ArchiveDir.Text = Fax.ArchiveDirectory
SvcMapiProfile.Text = Fax.ServerMapiProfile
Retries.Text = Fax.Retries
RetryDelay.Text = Fax.RetryDelay
DirtyDays.Text = Fax.DirtyDays
If (Fax.PauseServerQueue <> False) Then
PauseQueue.Value = True
UnpauseQueue.Value = False
Else
PauseQueue.Value = False
UnpauseQueue.Value = True
End If
If (Fax.ArchiveOutboundFaxes <> False) Then
ArchiveFaxes.Value = 1
Else
ArchiveFaxes.Value = 0
End If
If (Fax.UseDeviceTsid <> False) Then
UseDeviceTsid.Value = 1
Else
UseDeviceTsid.Value = 0
End If
If (Fax.Branding <> False) Then
Branding.Value = 1
Else
Branding.Value = 0
End If
If (Fax.ServerCoverpage <> False) Then
ServerCoverpg.Value = 1
Else
ServerCoverpg.Value = 0
End If
End Sub
Private Sub OK_Click()
Fax.ArchiveDirectory = ArchiveDir.Text
Fax.ServerMapiProfile = SvcMapiProfile.Text
Fax.Retries = Retries.Text
Fax.RetryDelay = RetryDelay.Text
Fax.DirtyDays = DirtyDays.Text
Fax.PauseServerQueue = PauseQueue.Value
Fax.ArchiveOutboundFaxes = ArchiveFaxes.Value
Fax.UseDeviceTsid = UseDeviceTsid.Value
Fax.Branding = Branding.Value
Fax.ServerCoverpage = ServerCoverpg.Value
Unload ServerProperty
End Sub
|
set obj = getobject("winmgmts:win32_logicaldisk='C:'")
set ser = obj.Parent_
set obj2 = ser.Get ("Win32_LogicalDisk='D:'")
WScript.Echo obj2.Path_.Path
|
<gh_stars>10-100
set o = Createobject ("FaxControl.FaxControl.1")
if o.IsFaxServiceInstalled then
Msgbox "Fax is installed"
else
Msgbox "Fax is NOT installed - attempting to install"
o.InstallFaxService
if o.IsFaxServiceInstalled then
Msgbox "Fax is installed now!!!"
end if
end if
if o.IsLocalFaxPrinterInstalled then
Msgbox "Local Fax printer is installed"
else
Msgbox "Local Fax printer is NOT installed - attempting to install"
o.InstallLocalFaxPrinter
if o.IsLocalFaxPrinterInstalled then
Msgbox "Local Fax printer is installed now!!!"
end if
end if
|
Function remove_duplicates(list)
arr = Split(list,",")
Set dict = CreateObject("Scripting.Dictionary")
For i = 0 To UBound(arr)
If dict.Exists(arr(i)) = False Then
dict.Add arr(i),""
End If
Next
For Each key In dict.Keys
tmp = tmp & key & ","
Next
remove_duplicates = Left(tmp,Len(tmp)-1)
End Function
WScript.Echo remove_duplicates("a,a,b,b,c,d,e,d,f,f,f,g,h")
|
100 REM TEST 8
101 REM From http://www.cpcwiki.eu/index.php/BASIC_Benchmark
102 REM Executes in about 65s on SBC9995MAX with 12MHz crystal (3MHz CPU)
103 REM Executed in about 840s on 1802 Membership Card with 3.8MHz crystal
104 REM Executed in about 195s on CDP180X FPGA implementation at 25MHz clock
105 ENINT 200
110 PRINT "START (Press INT button to see variable values)"
120 K=0
130 K=K+1
140 A=K^2
150 B=LOG(K)
160 C=SIN(K)
170 IF K<1000 THEN GOTO 130
180 PRINT "STOP"
190 END
200 PRINT K,A,B,C
205 RETURN
|
<reponame>djgoku/RosettaCodeData<gh_stars>0
dim items(2)
items(0)="Apple"
items(1)="Orange"
items(2)="Banana"
For Each x in items
WScript.Echo x
Next
|
<filename>Task/Minesweeper-game/VBA/minesweeper-game-1.vba
Option Explicit
Public vTime As Single
Public PlaysCount As Long
Sub Main_MineSweeper()
Dim Userf As New cMinesweeper
'Arguments :
'First arg is level : 0 = easy, 1 = middle, 2 = difficult
'Second arg is Cheat Mode : True if you want to cheat...
Userf.Show 0, True
End Sub
|
'***************************************************************************
'This script tests the manipulation of context values, in the case that the
'context value is an array type
'***************************************************************************
On Error Resume Next
Set Locator = CreateObject("WbemScripting.SWbemLocator")
Set Service = Locator.ConnectServer()
if Err <> 0 Then
WScript.Echo Err.Description
Err.Clear
End if
|
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Create two buttons to use as the accept and cancel buttons.
Dim button1 As New Button()
Dim button2 As New Button()
' Set the text of button1 to "OK".
button1.Text = "OK"
' Set the position of the button on the form.
button1.Location = New Point(10, 10)
' Set the text of button2 to "Cancel".
button2.Text = "Cancel"
' Set the position of the button based on the location of button1.
button2.Location = _
New Point(button1.Left, button1.Height + button1.Top + 10)
' Set the caption bar text of the form.
Me.Text = "tutorialspoint.com"
' Display a help button on the form.
Me.HelpButton = True
' Define the border style of the form to a dialog box.
Me.FormBorderStyle = FormBorderStyle.FixedDialog
' Set the MaximizeBox to false to remove the maximize box.
Me.MaximizeBox = False
' Set the MinimizeBox to false to remove the minimize box.
Me.MinimizeBox = False
' Set the accept button of the form to button1.
Me.AcceptButton = button1
' Set the cancel button of the form to button2.
Me.CancelButton = button2
' Set the start position of the form to the center of the screen.
Me.StartPosition = FormStartPosition.CenterScreen
' Set window width and height
Me.Height = 300
Me.Width = 560
' Add button1 to the form.
Me.Controls.Add(button1)
' Add button2 to the form.
Me.Controls.Add(button2)
End Sub
End Class
|
On Error Resume Next
Dim service
Dim context
set context = CreateObject("WbemScripting.SWbemNamedValueSet")
Set service = GetObject("winmgmts:")
Dim disk
context.Add "fred", 23
Set disk = service.Get("win32_logicaldisk",fred)
If Err <> 0 Then
WScript.Echo Err.Description, Err.Source, Err.Number
Err.clear
End If
WScript.Echo disk.Path_.DisplayName
If Err <> 0 Then
WScript.Echo Err.Description, Err.Source, Err.Number
End If
|
Attribute VB_Name = "Config"
DefInt A-Z
Option Explicit
'========Public Config Vars and Structs========
'Main Form
Public MainFormHeight As Long
Public MainFormWidth As Long
Public MainFormVDivider As Long
Public MainFormHDivider As Long
Public StatusBar As Boolean
Public DataListIdColWidth As Long
Public DataListNameColWidth As Long
Public DataListAttrColWidth As Long
Public DataListUTColWidth As Long
Public DataListDTColWidth As Long
Public DataListDataColWidth As Long
Public ErrorListKeyColWidth As Long
Public ErrorListPropColWidth As Long
Public ErrorListIdColWidth As Long
Public ErrorListSeverityColWidth As Long
Public ErrorListDescColWidth As Long
Public MaxKeySize As Long
Public MaxPropSize As Long
Public MaxNumErrors As Long
Const MainFormHeightDefault = 8000
Const MainFormWidthDefault = 12000
Const MainFormHDividerDefault = 2500
Const MainFormVDividerDefault = 2500
Const StatusBarDefault = True
Const DataListIdColWidthDefault = 800
Const DataListNameColWidthDefault = 1500
Const DataListAttrColWidthDefault = 1000
Const DataListUTColWidthDefault = 700
Const DataListDTColWidthDefault = 500
Const DataListDataColWidthDefault = 1500
Const ErrorListKeyColWidthDefault = 3000
Const ErrorListPropColWidthDefault = 800
Const ErrorListIdColWidthDefault = 800
Const ErrorListSeverityColWidthDefault = 800
Const ErrorListDescColWidthDefault = 3000
Const MaxKeySizeDefault = 102400
Const MaxPropSizeDefault = 1024
Const MaxNumErrorsDefault = 100
'========API Declarations========
'Load APIs for registry editing
Private Type FILETIME
dwLowDateTime As Long
dwHighDateTime As Long
End Type
Private Declare Function RegOpenKeyEx Lib "advapi32.dll" Alias "RegOpenKeyExA" (ByVal hKey As Long, ByVal lpSubKey As String, ByVal ulOptions As Long, ByVal samDesired As Long, phkResult As Long) As Long
Private Declare Function RegCloseKey Lib "advapi32.dll" (ByVal hKey As Long) As Long
Private Declare Function RegCreateKeyEx Lib "advapi32.dll" Alias "RegCreateKeyExA" (ByVal hKey As Long, ByVal lpSubKey As String, ByVal Reserved As Long, ByVal lpClass As String, ByVal dwOptions As Long, ByVal samDesired As Long, ByVal lpSecurityAttributes As Long, phkResult As Long, lpdwDisposition As Long) As Long
Private Declare Function RegDeleteKey Lib "advapi32.dll" Alias "RegDeleteKeyA" (ByVal hKey As Long, ByVal lpSubKey As String) As Long
Private Declare Function RegSetValueEx Lib "advapi32.dll" Alias "RegSetValueExA" (ByVal hKey As Long, ByVal lpValueName As String, ByVal Reserved As Long, ByVal dwType As Long, ByVal lpData As String, ByVal cbData As Long) As Long ' Note that if you declare the lpData parameter as String, you must pass it By Value.
Private Declare Function RegQueryValueEx Lib "advapi32.dll" Alias "RegQueryValueExA" (ByVal hKey As Long, ByVal lpValueName As String, ByVal lpReserved As Long, lpType As Long, ByVal lpData As String, lpcbData As Long) As Long ' Note that if you declare the lpData parameter as String, you must pass it By Value.
'Origial Declaration, the reserved parameter was set up wrong and I set up the class parameter to always be double NULL
'Private Declare Function RegEnumKeyEx Lib "advapi32.dll" Alias "RegEnumKeyExA" (ByVal hKey As Long, ByVal dwIndex As Long, ByVal lpName As String, lpcbName As Long, lpReserved As Long, ByVal lpClass As String, lpcbClass As Long, lpftLastWriteTime As FILETIME) As Long
Private Declare Function RegEnumKeyEx Lib "advapi32.dll" Alias "RegEnumKeyExA" (ByVal hKey As Long, ByVal dwIndex As Long, ByVal lpName As String, lpcbName As Long, ByVal lpReserved As Long, ByVal lpClass As Long, ByVal lpcbClass As Long, lpftLastWriteTime As FILETIME) As Long
Const ERROR_SUCCESS = 0&
Const HKEY_CURRENT_USER = &H80000001
Const HKEY_LOCAL_MACHINE = &H80000002
Const STANDARD_RIGHTS_ALL = &H1F0000
Const KEY_QUERY_VALUE = &H1
Const KEY_SET_VALUE = &H2
Const KEY_CREATE_SUB_KEY = &H4
Const KEY_ENUMERATE_SUB_KEYS = &H8
Const KEY_NOTIFY = &H10
Const KEY_CREATE_LINK = &H20
Const SYNCHRONIZE = &H100000
Const KEY_ALL_ACCESS = ((STANDARD_RIGHTS_ALL Or KEY_QUERY_VALUE _
Or KEY_SET_VALUE Or KEY_CREATE_SUB_KEY Or KEY_ENUMERATE_SUB_KEYS _
Or KEY_NOTIFY Or KEY_CREATE_LINK) And (Not SYNCHRONIZE))
Const REG_OPTION_NON_VOLATILE = 0 ' Key is preserved when system is rebooted
Const REG_CREATED_NEW_KEY = &H1 ' New Registry Key created
Const REG_OPENED_EXISTING_KEY = &H2 ' Existing Key opened
Const REG_SZ = 1
Sub LoadConfig()
LoadMainFormConfig
End Sub
Sub LoadMainFormConfig()
Dim Ret As Long
Dim Disposition As Long
Dim KeyHandle As Long
'Open/Create Key
Ret = RegCreateKeyEx(HKEY_CURRENT_USER, "Software\Microsoft\MetEdit", _
0, "", REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, 0, KeyHandle, Disposition)
If Ret <> ERROR_SUCCESS Then Debug.Print "Error creating or opening MetEdit key in LoadMainFormConfig"
'Get Settings
MainFormHeight = RegGetLong(KeyHandle, "Main Form Height", MainFormHeightDefault)
MainFormWidth = RegGetLong(KeyHandle, "Main Form Width", MainFormWidthDefault)
MainFormVDivider = RegGetLong(KeyHandle, "Main Form V Divider", MainFormVDividerDefault)
MainFormHDivider = RegGetLong(KeyHandle, "Main Form H Divider", MainFormHDividerDefault)
StatusBar = RegGetBoolean(KeyHandle, "Status Bar", StatusBarDefault)
DataListIdColWidth = RegGetLong(KeyHandle, "Data List Id Col Width", DataListIdColWidthDefault)
DataListNameColWidth = RegGetLong(KeyHandle, "Data List Name Col Width", DataListNameColWidthDefault)
DataListAttrColWidth = RegGetLong(KeyHandle, "Data List Attr Col Width", DataListAttrColWidthDefault)
DataListUTColWidth = RegGetLong(KeyHandle, "Data List UT Col Width", DataListUTColWidthDefault)
DataListDTColWidth = RegGetLong(KeyHandle, "Data List DT Col Width", DataListDTColWidthDefault)
DataListDataColWidth = RegGetLong(KeyHandle, "Data List Data Col Width", DataListDataColWidthDefault)
ErrorListKeyColWidth = RegGetLong(KeyHandle, "Error List Key Col Width", ErrorListKeyColWidthDefault)
ErrorListPropColWidth = RegGetLong(KeyHandle, "Error List Prop Col Width", ErrorListPropColWidthDefault)
ErrorListIdColWidth = RegGetLong(KeyHandle, "Error List Id Col Width", ErrorListIdColWidthDefault)
ErrorListSeverityColWidth = RegGetLong(KeyHandle, "Error List Severity Col Width", ErrorListSeverityColWidthDefault)
ErrorListDescColWidth = RegGetLong(KeyHandle, "Error List Desc Col Width", ErrorListDescColWidthDefault)
MaxKeySize = RegGetLong(KeyHandle, "Max Key Size", MaxKeySizeDefault)
MaxPropSize = RegGetLong(KeyHandle, "Max Property Size", MaxPropSizeDefault)
MaxNumErrors = RegGetLong(KeyHandle, "Max Number of Errors", MaxNumErrorsDefault)
'Close Key
Ret = RegCloseKey(KeyHandle)
End Sub
Sub SaveConfig()
SaveMainFormConfig
End Sub
Sub SaveMainFormConfig()
Dim KeyHandle As Long
Dim Ret As Long
Dim Disposition As Long
'Open Key
Ret = RegCreateKeyEx(HKEY_CURRENT_USER, "Software\Microsoft\MetEdit", _
0, "", REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, 0, KeyHandle, Disposition)
If Ret <> ERROR_SUCCESS Then Debug.Print "Error creating or opening MetEdit key in SaveMainFormConfig"
'Save Values
RegSetLong KeyHandle, "Main Form Height", MainFormHeight
RegSetLong KeyHandle, "Main Form Width", MainFormWidth
RegSetLong KeyHandle, "Main Form V Divider", MainFormVDivider
RegSetLong KeyHandle, "Main Form H Divider", MainFormHDivider
RegSetBoolean KeyHandle, "Status Bar", StatusBar
RegSetLong KeyHandle, "Data List Id Col Width", DataListIdColWidth
RegSetLong KeyHandle, "Data List Name Col Width", DataListNameColWidth
RegSetLong KeyHandle, "Data List Attr Col Width", DataListAttrColWidth
RegSetLong KeyHandle, "Data List UT Col Width", DataListUTColWidth
RegSetLong KeyHandle, "Data List DT Col Width", DataListDTColWidth
RegSetLong KeyHandle, "Data List Data Col Width", DataListDataColWidth
RegSetLong KeyHandle, "Error List Key Col Width", ErrorListKeyColWidth
RegSetLong KeyHandle, "Error List Prop Col Width", ErrorListPropColWidth
RegSetLong KeyHandle, "Error List Id Col Width", ErrorListIdColWidth
RegSetLong KeyHandle, "Error List Severity Col Width", ErrorListSeverityColWidth
RegSetLong KeyHandle, "Error List Desc Col Width", ErrorListDescColWidth
RegSetLong KeyHandle, "Max Key Size", MaxKeySize
RegSetLong KeyHandle, "Max Property Size", MaxPropSize
RegSetLong KeyHandle, "Max Number of Errors", MaxNumErrors
'Close Key
Ret = RegCloseKey(KeyHandle)
End Sub
Function ConvertCString(CString As String) As String
'Cleans up a C style string into a VB string
Dim i As Integer
Dim CharStr As String
Dim NullStr As String
Dim RetStr As String
'Find the first NULL
NullStr = String(1, 0)
i = 1
Do
CharStr = Mid(CString, i, 1)
i = i + 1
Loop While ((i <= Len(CString)) And (CharStr <> NullStr))
'If we found the null, keep the part before the null
If (CharStr = NullStr) Then
ConvertCString = Left(CString, i - 2)
Else
ConvertCString = CString
End If
End Function
Sub RegNukeKey(KeyHnd As Long, SubKeyStr As String)
'Nukes a key and all subkeys, should work with both ninety-blah and NT
Dim Ret As Long
Dim SubKeyHnd As Long
'Open the subkey so we can look for sub keys
Ret = RegOpenKeyEx(KeyHnd, SubKeyStr, 0, KEY_ALL_ACCESS, SubKeyHnd)
If Ret <> ERROR_SUCCESS Then Exit Sub
'Recursivly nuke all of the subsubkeys
Dim i As Long
Dim SubSubKeyStr As String
Dim LastWrite As FILETIME
i = 0
SubSubKeyStr = String(301, "X") 'Trick it into allocating memory
Ret = RegEnumKeyEx(SubKeyHnd, i, SubSubKeyStr, 300, 0, 0, 0, LastWrite)
Do While (Ret = ERROR_SUCCESS)
SubSubKeyStr = RTrim(ConvertCString(SubSubKeyStr))
RegNukeKey SubKeyHnd, SubSubKeyStr
'i = i + 1 Not needed since the next one becomes index 0
SubSubKeyStr = String(301, "X") 'Trick it into reallocating memory
Ret = RegEnumKeyEx(SubKeyHnd, i, SubSubKeyStr, 300, 0, 0, 0, LastWrite)
Loop
'Close the target key
Ret = RegCloseKey(SubKeyHnd)
'Delete the target key
Ret = RegDeleteKey(KeyHnd, SubKeyStr)
End Sub
Function RegGetString(KeyHandle As Long, Var As String, MaxLen As Long, DefaultStr As String) As String
Dim OutStr As String
Dim Ret As Long
OutStr = String(MaxLen + 1, "X") 'Trick it into allocating memory
Ret = RegQueryValueEx(KeyHandle, Var, 0, REG_SZ, OutStr, MaxLen + 1)
If Ret <> ERROR_SUCCESS Then
'If we didn't get it, set it to default
OutStr = DefaultStr
Ret = RegSetValueEx(KeyHandle, Var, 0, REG_SZ, OutStr, Len(OutStr) + 1)
If Ret <> ERROR_SUCCESS Then Error.Print "Error setting " & Var & " value"
Else
'If we got it, convert it to a VB String
OutStr = Left(Trim(ConvertCString(OutStr)), MaxLen)
End If
RegGetString = OutStr
End Function
Sub RegSetString(KeyHandle As Long, Var As String, Val As String)
Dim Ret As Long
Ret = RegSetValueEx(KeyHandle, Var, 0, REG_SZ, Val + String(1, 0), Len(Val) + 1)
If Ret <> ERROR_SUCCESS Then Error.Print "Error setting registry Var=" & Var & " Val=" & Val
End Sub
Function RegGetBoolean(KeyHandle As Long, Var As String, Default As Boolean) As Boolean
Dim BoolStr As String
If Default = True Then
BoolStr = RegGetString(KeyHandle, Var, 2, "1")
Else
BoolStr = RegGetString(KeyHandle, Var, 2, "0")
End If
If BoolStr = "1" Then
RegGetBoolean = True
Else
RegGetBoolean = False
End If
End Function
Sub RegSetBoolean(KeyHandle As Long, Var As String, Val As Boolean)
If Val Then
RegSetString KeyHandle, Var, "1"
Else
RegSetString KeyHandle, Var, "0"
End If
End Sub
Function RegGetLong(KeyHandle As Long, Var As String, Default As Long) As Long
Dim NumStr As String
NumStr = RegGetString(KeyHandle, Var, 20, Str(Default))
RegGetLong = CLng(NumStr)
End Function
Sub RegSetLong(KeyHandle As Long, Var As String, Val As Long)
RegSetString KeyHandle, Var, Str(Val)
End Sub
|
'////////////////////////////////////////////////////////////////////////////
' $Header:$
' Windows Embedded Default Prototype Script
' Version: 2.00
' Author: timhill
' Copyright (c) 1999-2000 Microsoft Corp. All Rights Reserved.
'////////////////////////////////////////////////////////////////////////////
Option Explicit
' Setup basic objects (reflect config objects)
Dim g_oConfigScript : Set g_oConfigScript = cmiThis.Configuration.Script
Dim g_oFSO : Set g_oFSO = g_oConfigScript.g_oFSO
Dim g_oShell : Set g_oShell = g_oConfigScript.g_oShell
Dim g_oEnv : Set g_oEnv = g_oConfigScript.g_oEnv
Dim g_oNet : Set g_oNet = g_oConfigScript.g_oNet
Dim g_oCMIUtil : Set g_oCMIUtil = g_oConfigScript.g_oCMIUtil
'////////////////////////////////////////////////////////////////////////////
' Configuration handlers
'////////////////////////////////////////////////////////////////////////////
'////////////////////////////////////////////////////////////////////////////
' cmiOnOpenConfig
' Called from Config::cmiOnOpenConfig
'
Sub cmiOnOpenConfig
TraceEnter "DefProto::cmiOnOpenConfig"
TraceLeave "DefProto::cmiOnOpenConfig"
End Sub
'////////////////////////////////////////////////////////////////////////////
' cmiOnSaveConfig
' Called from Config::cmiOnSaveConfig
'
Sub cmiOnSaveConfig
TraceEnter "DefProto::cmiOnSaveConfig"
TraceLeave "DefProto::cmiOnSaveConfig"
End Sub
'////////////////////////////////////////////////////////////////////////////
' cmiOnCloseConfig
' Called from Config::cmiOnCloseConfig
'
Sub cmiOnCloseConfig
TraceEnter "DefProto::cmiOnCloseConfig"
TraceLeave "DefProto::cmiOnCloseConfig"
End Sub
'////////////////////////////////////////////////////////////////////////////
' Instance handlers
'////////////////////////////////////////////////////////////////////////////
'////////////////////////////////////////////////////////////////////////////
' cmiOnAddInstance (virtual)
' Called from Config::cmiOnAddInstance
'
' We need to collapse the component chain properties, dependencies and
' resources, and also validate the instance. We always allow a resource etc
' in a more-derived component to over-ride one of the same name in a baser
' component. Note that script (DHTML and regular) is not collapsed.
'
' Returns False to disallow addition, True to allow addition
Function cmiOnAddInstance
TraceEnter "DefProto::cmiOnAddInstance"
TraceState "cmiThis.Comment", cmiThis.Comment
' Initial instance validity check
cmiOnAddInstance = cmiThis.Script.cmiCollapseFirstCheck
' Build instance by collapsing component chain data
If cmiOnAddInstance Then cmiOnAddInstance = cmiThis.Script.cmiCollapseProperties
If cmiOnAddInstance Then cmiOnAddInstance = cmiThis.Script.cmiCollapseResources
If cmiOnAddInstance Then cmiOnAddInstance = cmiThis.Script.cmiCollapseDependencies
' Final instance validity check before acceptance
If cmiOnAddInstance Then cmiOnAddInstance = cmithis.Script.cmiCollapseLastCheck
TraceLeave "DefProto::cmiOnAddInstance"
End Function
'////////////////////////////////////////////////////////////////////////////
' cmiCollapseFirstCheck and cmiCollapseLastCheck (virtual)
' Check valid instance first and last checks
'
' Returns False to disallow addition, True to allow addition
Function cmiCollapseFirstCheck
TraceEnter "DefProto::cmiCollapseFirstCheck"
cmiCollapseFirstCheck = True ' OK to add instance
TraceLeave "DefProto::cmiCollapseFirstCheck"
End Function
Function cmiCollapseLastCheck
TraceEnter "DefProto::cmiCollapseLastCheck"
cmiCollapseLastCheck = True ' OK to add instance
TraceLeave "DefProto::cmiCollapseLastCheck"
End Function
'////////////////////////////////////////////////////////////////////////////
' cmiCollapseProperties (virtual)
' Collapse all instance properties (standard and extended)
'
' Returns False to disallow addition, True to allow addition
Function cmiCollapseProperties
TraceEnter "DefProto::cmiCollapseProperties"
Dim oDict : Set oDict = CreateObject("Scripting.Dictionary")
oDict.CompareMode = vbTextCompare
Dim oTopComp : Set oTopComp = cmiThis.ComponentChain(1)
Dim oComp, oProp
' Set standard properties
cmiThis.Editable = False ' True if any component true
cmiThis.IsBaseComponent = (LCase(oTopComp.VIGUID) = LCase(cmiThis.Platform.BaseComponentVIGUID))
cmiThis.IsMacro = oTopComp.IsMacro ' Are we a macro instance?
cmiThis.MultiInstance = True ' False if any component false
cmiThis.Visibility = 0 ' Use max of all components
' Merge component chain properties
For Each oComp In cmiThis.ComponentChain ' For each component..
cmiThis.Editable = cmiThis.Editable Or oComp.Editable
cmiThis.MultiInstance = cmiThis.MultiInstance And oComp.MultiInstance
If oComp.Visibility > cmiThis.Visibility Then
cmiThis.Visibility = oComp.Visibility ' Choose most visible
End If
For Each oProp In oComp.Properties ' For each extended property..
If Not oDict.Exists(oProp.Name) Then ' If not yet added..
If cmiThis.Script.cmiCollapseProperty(oComp, oProp) Then
oDict.Add oProp.Name, "" ' Mark it's added
End If
End If
Next
Next
If cmiThis.Editable Then ' Force visibility if editable
If cmiThis.Visibility < 1000 Then cmiThis.Visibility = 1000 ' Force to default
End If
' Not ok if single instance component and instance > 0
cmiCollapseProperties = (cmiThis.MultiInstance Or cmiThis.InstanceID = 0)
TraceLeave "DefProto::cmiCollapseProperties"
End Function
'////////////////////////////////////////////////////////////////////////////
' cmiCollapseProperty (virtual)
' Collapse an individual property
'
' oComponent Source component for property
' oProperty Property to collapse (add) into instance
' Returns True if property added, else False (not added)
Function cmiCollapseProperty(oComponent, oProperty)
TraceEnter "DefProto::cmiCollapseProperty"
TraceState "oProperty.Name", oProperty.Name
cmiThis.Properties.Add oProperty.Name, oProperty.Format, oProperty.Value
cmiCollapseProperty = True ' Mark that we added it
TraceLeave "DefProto::cmiCollapseProperty"
End Function
'////////////////////////////////////////////////////////////////////////////
' cmiCollapseResources (virtual)
' Collapse resources (choose most derived where overlap occurs)
'
' Returns False to disallow addition, True to allow addition
Function cmiCollapseResources
TraceEnter "DefProto::cmiCollapseResources"
Dim oDict : Set oDict = CreateObject("Scripting.Dictionary")
oDict.CompareMode = vbTextCompare
Dim oComp, oRes
For Each oComp In cmiThis.ComponentChain ' For each component..
For Each oRes In oComp.GetResources ' For each resource..
If Not oDict.Exists(oRes.Name) Then ' If not yet added..
If cmiThis.Script.cmiCollapseResource(oComp, oRes) Then
oDict.Add oRes.Name, "" ' Mark it's added
End If
End If
Next
Next
cmiCollapseResources = True ' OK to add instance
TraceLeave "DefProto::cmiCollapseResources"
End Function
'////////////////////////////////////////////////////////////////////////////
' cmiCollapseResource (virtual)
' Collapse an individual resource
'
' oComponent Source component for resource
' oResource Resource to collapse (add) into instance
' Returns True if resource added, else False (not added)
Function cmiCollapseResource(oComponent, oResource)
TraceEnter "DefProto::cmiCollapseResource"
TraceState "oResource.Name", oResource.Name
Dim oNewRes, oProp, oNewProp
Set oNewRes = cmiThis.Resources.Add(oResource.Type, oResource.BuildTypeMask, oResource.Localize, oResource.Disabled, oResource.DisplayName, oResource.Description)
For Each oProp In oResource.Properties ' For each property
Set oNewProp = oNewRes.Properties(oProp.Name)
If oNewProp Is Nothing Then ' Property does not exist
oNewRes.Properties.Add oProp.Name, oProp.Format, oProp.Value
Else
If oNewProp.Format = oProp.Format Then ' If same format..
If oProp.Format = cmiObject Then
Set oNewProp.Value = oProp.Value
Else
oNewProp.Value = oProp.Value ' ..just copy value
End If
Else
oNewRes.Properties.Remove oProp.Name ' Delete default
oNewRes.Properties.Add oProp.Name, oProp.Format, oProp.Value
End If
End If
Next
Set oProp = oNewRes.Properties("ComponentVSGUID")
If Not oProp Is Nothing Then ' If present..
oProp.Value = oComponent.VSGUID ' ..record component VSGUID
End If
cmiCollapseResource = True ' Add the resource
TraceLeave "DefProto::cmiCollapseResource"
End Function
'////////////////////////////////////////////////////////////////////////////
' cmiCollapseDependencies (virtual)
' Collapse dependencies
'
' Returns False to disallow addition, True to allow addition
Function cmiCollapseDependencies
TraceEnter "DefProto::cmiCollapseDependencies"
Dim oComp, oDep
cmiCollapseDependencies = True ' Mark that we added it
For Each oComp In cmiThis.ComponentChain ' For each component..
For Each oDep In oComp.GetDependencies ' For each dependency..
If Not cmiThis.Script.cmiCollapseDependency(oComp, oDep) Then
cmiCollapseDependencies = False
End If
Next
Next
TraceLeave "DefProto::cmiCollapseDependencies"
End Function
'////////////////////////////////////////////////////////////////////////////
' cmiCollapseDependency (virtual)
' Collapse an individual dependency
'
' oComponent Source component for dependency
' oDependency Dependency to collapse (add) into instance
' Returns True if dependency added, else False (not added)
Function cmiCollapseDependency(oComponent, oDependency)
TraceEnter "DefProto::cmiCollapseDependency"
cmiThis.Dependencies.Add oDependency.Class, oDependency.Type, oDependency.TargetGUID, oDependency.MinRevision, oDependency.DisplayName, oDependency.Description
cmiCollapseDependency = True ' Mark that we added it
TraceLeave "DefProto::cmiCollapseDependency"
End Function
'////////////////////////////////////////////////////////////////////////////
' cmiOnLoadInstance
' Called from Config::cmiOnLoadInstance
'
' Returns False to disallow load, True to allow load
Function cmiOnLoadInstance
TraceEnter "DefProto::cmiOnLoadInstance"
TraceState "cmiThis.Comment", cmiThis.Comment
cmiOnLoadInstance = True
TraceLeave "DefProto::cmiOnLoadInstance"
End Function
'////////////////////////////////////////////////////////////////////////////
' cmiOnConfigureInstance
' Called from Config::cmiOnConfigureInstance
Sub cmiOnConfigureInstance
TraceEnter "DefProto::cmiOnConfigureInstance"
TraceState "cmiThis.Comment", cmiThis.Comment
TraceLeave "DefProto::cmiOnConfigureInstance"
End Sub
'////////////////////////////////////////////////////////////////////////////
' cmiOnUpgradeInstance
' Called from Config::cmiOnUpgradeInstance
'
' oOldInstance Old instance (source of upgrade state)
Sub cmiOnUpgradeInstance(oOldInstance)
TraceEnter "DefProto::cmiOnUpgradeInstance"
TraceState "cmiThis.Comment", cmiThis.Comment
TraceState "oOldInstance.Comment", oOldInstance.Comment
TraceLeave "DefProto::cmiOnUpgradeInstance"
End Sub
'////////////////////////////////////////////////////////////////////////////
' cmiOnDeleteInstance
' Called from Config::cmiOnDeleteInstance
'
' Returns False to disallow deletion, True to allow
Function cmiOnDeleteInstance
TraceEnter "DefProto::cmiOnDeleteInstance"
TraceState "cmiThis.Comment", cmiThis.Comment
cmiOnDeleteInstance = Not cmiThis.IsBaseComponent ' Cannot delete base
TraceLeave "DefProto::cmiOnDeleteInstance"
End Function
'////////////////////////////////////////////////////////////////////////////
' Resource handlers
'////////////////////////////////////////////////////////////////////////////
'////////////////////////////////////////////////////////////////////////////
' cmiOnAddResource (virtual)
' Called from Config::cmiOnAddResource
'
' oNewResource Resource being added to instance
' Returns True if resource added, else False (not added)
Function cmiOnAddResource(oNewResource)
TraceEnter "DefProto::cmiOnAddResource"
TraceState "oNewResource.Name", oNewResource.Name
cmiOnAddResource = oNewResource.Type.Script.cmiOnAddResource(cmiThis.Configuration, cmiThis, oNewResource)
TraceLeave "DefProto::cmiOnAddResource"
End Function
'////////////////////////////////////////////////////////////////////////////
' cmiOnDeleteResource (virtual)
' Called from Config::cmiOnDeleteResource
'
' oResource Resource being deleted from instance
' Returns True if resource deleted, else False
Function cmiOnDeleteResource(oResource)
TraceEnter "DefProto::cmiOnDeleteResource"
TraceState "oResource.Name", oResource.Name
cmiOnDeleteResource = oResource.Type.Script.cmiOnDeleteResource(cmiThis.Configuration, cmiThis, oResource)
TraceLeave "DefProto::cmiOnDeleteResource"
End Function
'////////////////////////////////////////////////////////////////////////////
' cmiOnLoadResource (virtual)
' Called from Config::cmiOnLoadResource
'
' oNewResource Resource being added to instance
' Returns True if resource added, else False (not added)
Function cmiOnLoadResource(oNewResource)
TraceEnter "DefProto::cmiOnLoadResource"
TraceState "oNewResource.Name", oNewResource.Name
cmiOnLoadResource = oNewResource.Type.Script.cmiOnLoadResource(cmiThis.Configuration, cmiThis, oNewResource)
TraceLeave "DefProto::cmiOnLoadResource"
End Function
'////////////////////////////////////////////////////////////////////////////
' Build handlers
'////////////////////////////////////////////////////////////////////////////
'////////////////////////////////////////////////////////////////////////////
' cmiOnPreBuild and cmiOnPostBuild (virtual)
' Called from Config::cmiOnBuild
'
' These routines are called before and after the build for each instance
' to allow special setup/teardown. The base instance is first in and
' last out but other instances are NOT ORDERED.
Sub cmiOnPreBuild
TraceEnter "DefProto::cmiOnPreBuild"
TraceState "cmiThis.Comment", cmiThis.Comment
TraceLeave "DefProto::cmiOnPreBuild"
End Sub
Sub cmiOnPostBuild
TraceEnter "DefProto::cmiOnPostBuild"
TraceState "cmiThis.Comment", cmiThis.Comment
TraceLeave "DefProto::cmiOnPostBuild"
End Sub
'////////////////////////////////////////////////////////////////////////////
' cmiOnBuild (virtual)
' Called from Config::OnBuild
'
' Each instance should build itself at this time. Individual cmiOnBuild
' calls are made against each instance in correct build order.
Sub cmiOnBuild
TraceEnter "DefProto::cmiOnBuild"
TraceState "cmiThis.Comment", cmiThis.Comment
Dim oRes, oProp, sOldHKR
Set oProp = cmiThis.Properties("cmiHKRRoot") ' Get HKR root..
If Not oProp Is Nothing Then
sOldHKR = g_oCMIUtil.RelativeKey
g_oCMIUtil.RelativeKey = oProp.Value
End If
cmiThis.Script.cmiOnBeginBuild ' Start instance build
For Each oRes In cmiThis.Resources ' For each resource..
cmiThis.Script.cmiOnBuildResource oRes ' ..build it
Next
cmiThis.Script.cmiOnEndBuild ' End instance build
If Not oProp Is Nothing Then g_oCMIUtil.RelativeKey = sOldHKR
TraceLeave "DefProto::cmiOnBuild"
End Sub
'////////////////////////////////////////////////////////////////////////////
' cmiOnBeginBuild and cmiOnEndBuild (virtual)
' Called from DefProto::cmiOnBuild
Sub cmiOnBeginBuild
TraceEnter "DefProto::cmiOnBeginBuild"
TraceLeave "DefProto::cmiOnBeginBuild"
End Sub
Sub cmiOnEndBuild
TraceEnter "DefProto::cmiOnEndBuild"
TraceLeave "DefProto::cmiOnEndBuild"
End Sub
'////////////////////////////////////////////////////////////////////////////
' cmiOnBuildResource (virtual)
' Called from DefProto::cmiOnBuild
'
' oResource Resource to build
Sub cmiOnBuildResource(oResource)
TraceEnter "DefProto::cmiOnBuildResource"
TraceState "oResource.Name", oResource.Name
If Not oResource.Disabled And (cmiThis.Configuration.BuildType And oResource.BuildTypeMask) Then
cmiThis.Script.cmiOnBuildFilteredResource oResource
End If
TraceLeave "DefProto::cmiOnBuildResource"
End Sub
'////////////////////////////////////////////////////////////////////////////
' cmiOnBuildFilteredResource (virtual)
' Called from DefProt::cmiOnBuildResource
'
' oResource Resource to build
Sub cmiOnBuildFilteredResource(oResource)
TraceEnter "DefProto::cmiOnBuildFilteredResource"
TraceState "oResource.Name", oResource.Name
g_oConfigScript.BuildResource cmiThis, oResource
TraceLeave "DefProto::cmiOnBuildFilteredResource"
End Sub
'////////////////////////////////////////////////////////////////////////////
' Dependency checking handlers
'////////////////////////////////////////////////////////////////////////////
'////////////////////////////////////////////////////////////////////////////
' cmiAutoResolveDependencies
' Resolve all non-ambiguous dependencies for instance
'
' Returns Edit array on commands to add/remove components
Function cmiAutoResolveDependencies
TraceEnter "DefProto::cmiAutoResolveDependencies"
cmiAutoResolveDependencies = Array()
TraceLeave "DefProto::cmiAutoResolveDependencies"
End Function
'////////////////////////////////////////////////////////////////////////////
' cmiOnCheckDependencies
' Check all include depencencies against current instances
'
' oGUIDMember GUID membership dictionary
Sub cmiOnCheckDependencies(oGUIDMember)
TraceEnter "DefProto::cmiOnCheckDependencies"
TraceState "cmiThis.Comment", cmiThis.Comment
Dim oDep, nRet2
' Process each dependency (include class only)
For Each oDep In cmiThis.Dependencies
If oDep.Class = cmiInclude Then ' Only check include class
nRet2 = ReportInfoStatus(Array(104, cmiThis.Index, oDep.Index), "... Dependency: " & oDep.Index & ", name: " & oDep.DisplayName)
cmiThis.Script.cmiCheckDependency oDep, oGUIDMember
End If
Next
TraceLeave "DefProto::cmiOnCheckDependencies"
End Sub
'////////////////////////////////////////////////////////////////////////////
' cmiCheckDependency
' Check individual include dependency for validity
'
' To check a dependency, we need to discover how many instances are
' referenced by the target of the dependency. As with build, this involves
' converting one or more component GUIDs into instance indexes, which is
' done via the GUID member dictionary already built. This ensures that we
' correctly "see" the entire prototype chain of GUIDs as belonging to an
' instance. When resolving groups it's important to OR each vector first
' before counting instances to stop individual instances being counted twice.
' Once we have the match count, checking the dependency rule is trivial.
'
' oDep Dependency to check
' oGUIDMember GUID membership dictionary
Sub cmiCheckDependency(oDep, oGUIDMember)
TraceEnter "DefProto::cmiCheckDependency"
Dim oTarget, bGroupTarget, aVector, nMembers, oComp, aTemp, ix, iy
Dim nMatchCount, nType, nReport, sTemp, nRet2
' Get the target object and check if it's a group or component
Set oTarget = oDep.TargetObject ' Get target object
If oTarget Is Nothing Then ' Target not in database
nRet2 = ReportInfoStatus(Array(113, cmiThis.Index, oDep.Index), "Missing dependency target, instance: " & cmiThis.Comment & ", dependency: " & oDep.DisplayName)
Exit Sub ' Nothing to check
End If
bGroupTarget = LCase(TypeName(oTarget)) = "group" ' Check for group
nType = oDep.Type ' Get dependency type
If nType = cmiFromGroup Then nType = oTarget.DefaultDependencyType
' For groups, we OR together each members vector, else just get the vector
If bGroupTarget Then ' Count matching instances
aVector = oGUIDMember.GetEmptyVector ' Clear vector
nMembers = oTarget.GetMembers.Count ' Get membership count
For Each oComp In oTarget.GetMembers ' For each component..
aTemp = oGUIDMember.GetVector(oComp.VIGUID)
If Not IsEmpty(aTemp) Then
For ix = 1 To UBound(aTemp) ' Accumulate results
aVector(ix) = aVector(ix) Or aTemp(ix)
Next
End If
Next
Else
aVector = oGUIDMember.GetVector(oTarget.VIGUID)
If IsEmpty(aVector) Then aVector = oGUIDMember.GetEmptyVector
nMembers = 1 ' Single component target
End If
' Now count the number of instances that match this dependency
nMatchCount = 0 ' Clear match counter
For ix = 1 To UBound(aVector)
If aVector(ix) Then nMatchCount = nMatchCount + 1 ' Count matches
Next
' Now check this result against the dependency requirements
nReport = 0 ' Assume good result
Select Case nType ' Check dependency type
Case cmiExactlyOne ' Exactly one match
If nMatchCount = 0 Then nReport = 112 ' Missing instance
If nMatchCount > 1 Then nReport = 111 ' Too many instances
Case cmiAtLeastOne ' At least one match
If nMatchCount = 0 Then nReport = 112 ' Missing instance
Case cmiZeroOrOne ' Zero or one match
If nMatchCount > 1 Then nReport = 111 ' Too many instances
Case cmiAll ' All match
If nMatchCount < nMembers Then nReport = 112 ' Missing instance
Case cmiNone ' No match (conflict)
If nMatchCount > 0 Then nReport = 110 ' Conflicting instances
End Select
' Finally, report discrepances
If nReport <> 0 Then ' If discrepancy in dependency..
Select Case nReport ' Process reports
Case 110, 111 ' Conflicting or too many
aTemp = Array() : ReDim aTemp(nMatchCount + 2)
aTemp(0) = nReport ' Status code
aTemp(1) = cmiThis.Index ' Instance index
aTemp(2) = oDep.Index ' Dependency index
iy = 3 ' List of conflicting instances
For ix = 1 To UBound(aVector)
If aVector(ix) Then aTemp(iy) = ix : iy = iy + 1
Next
If nReport = 110 Then
nRet2 = ReportInfoStatus(aTemp, "Conflicting instance(s), instance: " & cmiThis.Comment & ", dependency: " & oDep.DisplayName)
Else
nRet2 = ReportInfoStatus(aTemp, "Too many instance(s), instance: " & cmiThis.Comment & ", dependency: " & oDep.DisplayName)
End If
Case 112 ' Missing instance(s)
nRet2 = ReportInfoStatus(Array(112, cmiThis.Index, oDep.Index), "Required instance(s) missing, instance: " & cmiThis.Comment & ", dependency: " & oDep.DisplayName)
End Select
End If
TraceLeave "DefProto::cmiCheckDependency"
End Sub
'////////////////////////////////////////////////////////////////////////////
' Platform script reflectors
'////////////////////////////////////////////////////////////////////////////
'////////////////////////////////////////////////////////////////////////////
' GetPropValue and GetPropValue2 reflectors
Function GetPropValue(oProp, vCurrValue)
GetPropValue = g_oConfigScript.GetPropValue(oProp, vCurrValue)
End Function
Function GetPropValue2(vRawValue, nFormat, vCurrValue)
GetPropValue2 = g_oConfigScript.GetPropValue2(vRawValue, nFormat, vCurrValue)
End Function
'////////////////////////////////////////////////////////////////////////////
' ReportInfoStatus and ReportErrorStatus reflectors
Function ReportInfoStatus(nCode, sText)
ReportInfoStatus = g_oConfigScript.ReportInfoStatus(nCode, sText)
End Function
Function ReportErrorStatus(nError, sText)
ReportErrorStatus = g_oConfigScript.ReportErrorStatus(nError, sText)
End Function
'////////////////////////////////////////////////////////////////////////////
' TraceExcept reflector
Sub TraceExcept(nError, sText)
g_oConfigScript.TraceExcept nError, sText
End Sub
'////////////////////////////////////////////////////////////////////////////
' TraceEnter and TraceLeave reflectors
Sub TraceEnter(sProc)
g_oConfigScript.TraceEnter sProc
End Sub
Sub TraceLeave(sProc)
g_oConfigScript.TraceLeave sProc
End Sub
'////////////////////////////////////////////////////////////////////////////
' TraceState reflector
Sub TraceState(sName, vValue)
g_oConfigScript.TraceState sName, vValue
End Sub
'////////////////////////////////////////////////////////////////////////////
' TraceInfo reflector
Sub TraceInfo(sText)
g_oConfigScript.TraceInfo sText
End Sub
'////////////////////////////////////////////////////////////////////////////
|
<filename>Task/Matrix-transposition/VBScript/matrix-transposition.vb
'create and display the initial matrix
WScript.StdOut.WriteLine "Initial Matrix:"
x = 4 : y = 6 : n = 1
Dim matrix()
ReDim matrix(x,y)
For i = 0 To y
For j = 0 To x
matrix(j,i) = n
If j < x Then
WScript.StdOut.Write n & vbTab
Else
WScript.StdOut.Write n
End If
n = n + 1
Next
WScript.StdOut.WriteLine
Next
'display the trasposed matrix
WScript.StdOut.WriteBlankLines(1)
WScript.StdOut.WriteLine "Transposed Matrix:"
For i = 0 To x
For j = 0 To y
If j < y Then
WScript.StdOut.Write matrix(i,j) & vbTab
Else
WScript.StdOut.Write matrix(i,j)
End If
Next
WScript.StdOut.WriteLine
Next
|
Private Function vdc(ByVal n As Integer, BASE As Variant) As Variant
Dim res As String
Dim digit As Integer, g As Integer, denom As Integer
denom = 1
Do While n
denom = denom * BASE
digit = n Mod BASE
n = n \ BASE
res = res & CStr(digit) '+ "0"
Loop
vdc = IIf(Len(res) = 0, "0", "0." & res)
End Function
Public Sub show_vdc()
Dim v As Variant, j As Integer
For i = 2 To 5
Debug.Print "Base "; i; ": ";
For j = 0 To 9
v = vdc(j, i)
Debug.Print v; " ";
Next j
Debug.Print
Next i
End Sub
|
start = Now
Set nlookup = CreateObject("Scripting.Dictionary")
Set uniquepair = CreateObject("Scripting.Dictionary")
For i = 1 To 20000
sum = 0
For n = 1 To 20000
If n < i Then
If i Mod n = 0 Then
sum = sum + n
End If
End If
Next
nlookup.Add i,sum
Next
For j = 1 To 20000
sum = 0
For m = 1 To 20000
If m < j Then
If j Mod m = 0 Then
sum = sum + m
End If
End If
Next
If nlookup.Exists(sum) And nlookup.Item(sum) = j And j <> sum _
And uniquepair.Exists(sum) = False Then
uniquepair.Add j,sum
End If
Next
For Each key In uniquepair.Keys
WScript.Echo key & ":" & uniquepair.Item(key)
Next
WScript.Echo "Execution Time: " & DateDiff("s",Start,Now) & " seconds"
|
<gh_stars>1-10
Public Function RepeatStr(aString As String, aNumber As Integer) As String
Dim bString As String, i As Integer
bString = ""
For i = 1 To aNumber
bString = bString & aString
Next i
RepeatStr = bString
End Function
Debug.Print RepeatStr("ha", 5)
|
<reponame>LaudateCorpus1/RosettaCodeData
Option Explicit
Private small As Variant, tens As Variant, big As Variant
Sub Main()
small = Array("one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", _
"eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", _
"eighteen", "nineteen")
tens = Array("twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety")
big = Array("thousand", "million", "billion")
Dim tmpInt As Long
tmpInt = Val(InputBox("Gimme a number!", "NOW!", Trim$(Year(Now)) & IIf(Month(Now) < 10, "0", "") & _
Trim$(Month(Now)) & IIf(Day(Now) < 10, "0", "") & Trim$(Day(Now))))
MsgBox int2Text$(tmpInt)
End Sub
Function int2Text$(number As Long)
Dim num As Long, outP As String, unit As Integer
Dim tmpLng1 As Long
If 0 = number Then
int2Text$ = "zero"
Exit Function
End If
num = Abs(number)
Do
tmpLng1 = num Mod 100
Select Case tmpLng1
Case 1 To 19
outP = small(tmpLng1 - 1) + " " + outP
Case 20 To 99
Select Case tmpLng1 Mod 10
Case 0
outP = tens((tmpLng1 \ 10) - 2) + " " + outP
Case Else
outP = tens((tmpLng1 \ 10) - 2) + "-" + small(tmpLng1 Mod 10) + " " + outP
End Select
End Select
tmpLng1 = (num Mod 1000) \ 100
If tmpLng1 Then
outP = small(tmpLng1 - 1) + " hundred " + outP
End If
num = num \ 1000
If num < 1 Then Exit Do
tmpLng1 = num Mod 1000
If tmpLng1 Then outP = big(unit) + " " + outP
unit = unit + 1
Loop
If number < 0 Then outP = "negative " & outP
int2Text$ = Trim$(outP)
End Function
|
<reponame>LaudateCorpus1/RosettaCodeData
Function transpose(m As Variant) As Variant
transpose = WorksheetFunction.transpose(m)
End Function
|
<reponame>LaudateCorpus1/RosettaCodeData
Sub matrix()
'create an array,
Dim a(3) As Integer
Dim i As Integer
'assign a value to it,
For i = 1 To 3
a(i) = i * i
Next i
'and retrieve an element
For i = 1 To 3
Debug.Print a(i)
Next i
'dynamic
Dim d() As Integer
ReDim d(3)
For i = 1 To 3
d(i) = i * i
Next i
'and retrieve an element
For i = 1 To 3
Debug.Print d(i)
Next i
'push a value to it - expand the array and preserve existing values
ReDim Preserve d(4)
d(4) = 16:
For i = 1 To 4
Debug.Print d(i)
Next i
End Sub
|
<filename>Task/Remove-lines-from-a-file/VBA/remove-lines-from-a-file-1.vba
Option Explicit
Sub Main()
'See Output #1
RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 11, 5
'See Output #2
RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 8, 5
'See Output #3
RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 3, 5
End Sub
Private Sub RemoveLines(StrFile As String, StartLine As Long, NumberOfLines As Long)
Dim Nb As Integer, s As String, count As Long, out As String
Nb = FreeFile
Open StrFile For Input As #Nb
While Not EOF(Nb)
count = count + 1
Line Input #Nb, s
If count < StartLine Or count >= StartLine + NumberOfLines Then
out = out & s & vbCrLf
End If
Wend
Close #Nb
If StartLine >= count Then
MsgBox "The file contains only " & count & " lines"
ElseIf StartLine + NumberOfLines > count Then
MsgBox "You only can remove " & count - StartLine & " lines"
Else
Nb = FreeFile
Open StrFile For Output As #Nb
Print #Nb, out
Close #Nb
End If
End Sub
|
<gh_stars>0
Function getCode(c)
Select Case c
Case "B", "F", "P", "V"
getCode = "1"
Case "C", "G", "J", "K", "Q", "S", "X", "Z"
getCode = "2"
Case "D", "T"
getCode = "3"
Case "L"
getCode = "4"
Case "M", "N"
getCode = "5"
Case "R"
getCode = "6"
End Select
End Function
Function soundex(s)
Dim code, previous
code = UCase(Mid(s, 1, 1))
previous = 7
For i = 2 to (Len(s) + 1)
current = getCode(UCase(Mid(s, i, 1)))
If Len(current) > 0 And current <> previous Then
code = code & current
End If
previous = current
Next
soundex = Mid(code, 1, 4)
If Len(code) < 4 Then
soundex = soundex & String(4 - Len(code), "0")
End If
End Function
|
<filename>base/pnp/tools/devcon2/scripts/hardware.vbs
'
' hardware.vbs
'
' collect information about all files currently being used by drivers
'
SET WshShell = WScript.CreateObject("WScript.Shell")
SET DevCon = WScript.CreateObject("DevCon.DeviceConsole")
SET Devs = DevCon.DevicesByInterfaceClasses("{86e0d1e0-8089-11d0-9ce4-08003e301f73}")
Count = Devs.Count
Wscript.Echo "Serial: Count="+CStr(Count)
'on error resume next
FOR EACH Dev IN Devs
PortName = Dev.RegRead("HW\PortName")
WScript.Echo PortName + " : " + Dev.Description
IF Dev.HasInterface("{4d36e978-e325-11ce-bfc1-08002be10318}") THEN
WScript.Echo " " + "Has serial enumerator"
END IF
IF Dev.HasInterface("{86e0d1e0-8089-11d0-9ce4-08003e301f73}") THEN
WScript.Echo " " + "Has serial port"
END IF
NEXT
|
Sub C_S_If()
Dim A$, B$
A = "Hello"
B = "World"
'test
If A = B Then Debug.Print A & " = " & B
'other syntax
If A = B Then
Debug.Print A & " = " & B
Else
Debug.Print A & " and " & B & " are differents."
End If
'other syntax
If A = B Then
Debug.Print A & " = " & B
Else: Debug.Print A & " and " & B & " are differents."
End If
'other syntax
If A = B Then Debug.Print A & " = " & B _
Else Debug.Print A & " and " & B & " are differents."
'other syntax
If A = B Then Debug.Print A & " = " & B Else Debug.Print A & " and " & B & " are differents."
If A = B Then Debug.Print A & " = " & B Else: Debug.Print A & " and " & B & " are differents."
End Sub
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.