id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
175,062
import os import stat import sys import pythoncom import win32gui import winerror from win32com.server.exception import COMException from win32com.shell import shell, shellcon class EmptyVolumeCache: _reg_progid_ = "Python.ShellExtension.EmptyVolumeCache" _reg_desc_ = "Python Sample Shell Extension (disk cleanup)" _reg_clsid_ = "{EADD0777-2968-4c72-A999-2BF5F756259C}" _reg_icon_ = ico _com_interfaces_ = [shell.IID_IEmptyVolumeCache, shell.IID_IEmptyVolumeCache2] _public_methods_ = IEmptyVolumeCache_Methods + IEmptyVolumeCache2_Methods def Initialize(self, hkey, volume, flags): # This should never be called, except on win98. print("Unless we are on 98, Initialize call is unexpected!") raise COMException(hresult=winerror.E_NOTIMPL) def InitializeEx(self, hkey, volume, key_name, flags): # Must return a tuple of: # (display_name, description, button_name, flags) print("InitializeEx called with", hkey, volume, key_name, flags) self.volume = volume if flags & shellcon.EVCF_SETTINGSMODE: print("We are being run on a schedule") # In this case, "because there is no opportunity for user # feedback, only those files that are extremely safe to clean up # should be touched. You should ignore the initialization # method's pcwszVolume parameter and clean unneeded files # regardless of what drive they are on." self.volume = None # flag as 'any disk will do' elif flags & shellcon.EVCF_OUTOFDISKSPACE: # In this case, "the handler should be aggressive about deleting # files, even if it results in a performance loss. However, the # handler obviously should not delete files that would cause an # application to fail or the user to lose data." print("We are being run as we are out of disk-space") else: # This case is not documented - we are guessing :) print("We are being run because the user asked") # For the sake of demo etc, we tell the shell to only show us when # there are > 0 bytes available. Our GetSpaceUsed will check the # volume, so will return 0 when we are on a different disk flags = shellcon.EVCF_DONTSHOWIFZERO | shellcon.EVCF_ENABLEBYDEFAULT return ( "pywin32 compiled files", "Removes all .pyc and .pyo files in the pywin32 directories", "click me!", flags, ) def _GetDirectories(self): root_dir = os.path.abspath(os.path.dirname(os.path.dirname(win32gui.__file__))) if self.volume is not None and not root_dir.lower().startswith( self.volume.lower() ): return [] return [ os.path.join(root_dir, p) for p in ("win32", "win32com", "win32comext", "isapi") ] def _WalkCallback(self, arg, directory, files): # callback function for os.path.walk - no need to be member, but its # close to the callers :) callback, total_list = arg for file in files: fqn = os.path.join(directory, file).lower() if file.endswith(".pyc") or file.endswith(".pyo"): # See below - total_list == None means delete files, # otherwise it is a list where the result is stored. Its a # list simply due to the way os.walk works - only [0] is # referenced if total_list is None: print("Deleting file", fqn) # Should do callback.PurgeProcess - left as an exercise :) os.remove(fqn) else: total_list[0] += os.stat(fqn)[stat.ST_SIZE] # and callback to the tool if callback: # for the sake of seeing the progress bar do its thing, # we take longer than we need to... # ACK - for some bizarre reason this screws up the XP # cleanup manager - clues welcome!! :) ## print "Looking in", directory, ", but waiting a while..." ## time.sleep(3) # now do it used = total_list[0] callback.ScanProgress(used, 0, "Looking at " + fqn) def GetSpaceUsed(self, callback): total = [0] # See _WalkCallback above try: for d in self._GetDirectories(): os.path.walk(d, self._WalkCallback, (callback, total)) print("After looking in", d, "we have", total[0], "bytes") except pythoncom.error as exc: # This will be raised by the callback when the user selects 'cancel'. if exc.hresult != winerror.E_ABORT: raise # that's the documented error code! print("User cancelled the operation") return total[0] def Purge(self, amt_to_free, callback): print("Purging", amt_to_free, "bytes...") # we ignore amt_to_free - it is generally what we returned for # GetSpaceUsed try: for d in self._GetDirectories(): os.path.walk(d, self._WalkCallback, (callback, None)) except pythoncom.error as exc: # This will be raised by the callback when the user selects 'cancel'. if exc.hresult != winerror.E_ABORT: raise # that's the documented error code! print("User cancelled the operation") def ShowProperties(self, hwnd): raise COMException(hresult=winerror.E_NOTIMPL) def Deactivate(self): print("Deactivate called") return 0 def DllUnregisterServer(): import winreg kn = r"Software\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\%s" % ( EmptyVolumeCache._reg_desc_, ) try: key = winreg.DeleteKey(winreg.HKEY_LOCAL_MACHINE, kn) except WindowsError as details: import errno if details.errno != errno.ENOENT: raise print(EmptyVolumeCache._reg_desc_, "unregistration complete.")
null
175,063
import os import pickle import random import sys import commctrl import pythoncom import win32api import win32con import winerror import winxpgui as win32gui from win32com.axcontrol import axcontrol from win32com.propsys import propsys from win32com.server.exception import COMException from win32com.server.util import NewEnum as _NewEnum, wrap as _wrap from win32com.shell import shell, shellcon from win32com.util import IIDToInterfaceName debug = 0 def wrap(ob, iid=None): return _wrap(ob, iid, useDispatcher=(debug > 0))
null
175,064
import os import pickle import random import sys import commctrl import pythoncom import win32api import win32con import winerror import winxpgui as win32gui from win32com.axcontrol import axcontrol from win32com.propsys import propsys from win32com.server.exception import COMException from win32com.server.util import NewEnum as _NewEnum, wrap as _wrap from win32com.shell import shell, shellcon from win32com.util import IIDToInterfaceName _sids = {} _last_ids = 0 def _make_ids(s): global _last_ids _last_ids += 1 _sids[_last_ids] = s return _last_ids
null
175,065
import os import pickle import random import sys import commctrl import pythoncom import win32api import win32con import winerror import winxpgui as win32gui from win32com.axcontrol import axcontrol from win32com.propsys import propsys from win32com.server.exception import COMException from win32com.server.util import NewEnum as _NewEnum, wrap as _wrap from win32com.shell import shell, shellcon from win32com.util import IIDToInterfaceName def pidl_to_item(pidl): # Note that only the *last* elt in the PIDL is certainly ours, # but it contains everything we need encoded as a dict. return pickle.loads(pidl[-1])
null
175,066
import os import pickle import random import sys import commctrl import pythoncom import win32api import win32con import winerror import winxpgui as win32gui from win32com.axcontrol import axcontrol from win32com.propsys import propsys from win32com.server.exception import COMException from win32com.server.util import NewEnum as _NewEnum, wrap as _wrap from win32com.shell import shell, shellcon from win32com.util import IIDToInterfaceName def NewEnum(seq, iid): return _NewEnum(seq, iid=iid, useDispatcher=(debug > 0)) def NewEnum( seq, cls=ListEnumerator, iid=pythoncom.IID_IEnumVARIANT, usePolicy=None, useDispatcher=None, ): """Creates a new enumerator COM server. This function creates a new COM Server that implements the IID_IEnumVARIANT interface. A COM server that can enumerate the passed in sequence will be created, then wrapped up for return through the COM framework. Optionally, a custom COM server for enumeration can be passed (the default is @ListEnumerator@), and the specific IEnum interface can be specified. """ ob = cls(seq, iid=iid) return wrap(ob, iid, usePolicy=usePolicy, useDispatcher=useDispatcher) def make_item_enum(level, flags): pidls = [] nums = """zero one two three four five size seven eight nine ten""".split() for i, name in enumerate(nums): size = random.randint(0, 255) sides = 1 while sides in [1, 2]: sides = random.randint(0, 5) is_folder = (i % 2) != 0 # check the flags say to include it. # (This seems strange; if you ask the same folder for, but appear skip = False if not (flags & shellcon.SHCONTF_STORAGE): if is_folder: skip = not (flags & shellcon.SHCONTF_FOLDERS) else: skip = not (flags & shellcon.SHCONTF_NONFOLDERS) if not skip: data = dict( name=name, size=size, sides=sides, level=level, is_folder=is_folder ) pidls.append([pickle.dumps(data)]) return NewEnum(pidls, shell.IID_IEnumIDList)
null
175,067
import os import pickle import random import sys import commctrl import pythoncom import win32api import win32con import winerror import winxpgui as win32gui from win32com.axcontrol import axcontrol from win32com.propsys import propsys from win32com.server.exception import COMException from win32com.server.util import NewEnum as _NewEnum, wrap as _wrap from win32com.shell import shell, shellcon from win32com.util import IIDToInterfaceName def DisplayItem(shell_item_array, hwnd_parent=0): def onDisplay(items, bindctx): DisplayItem(items)
null
175,068
import os import pickle import random import sys import commctrl import pythoncom import win32api import win32con import winerror import winxpgui as win32gui from win32com.axcontrol import axcontrol from win32com.propsys import propsys from win32com.server.exception import COMException from win32com.server.util import NewEnum as _NewEnum, wrap as _wrap from win32com.shell import shell, shellcon from win32com.util import IIDToInterfaceName def LoadString(sid): return _sids[sid] IDS_SETTING1 = _make_ids("Setting 1") def onSetting1(items, bindctx): win32gui.MessageBox(0, LoadString(IDS_SETTING1), "Hello", win32con.MB_OK)
null
175,069
import os import pickle import random import sys import commctrl import pythoncom import win32api import win32con import winerror import winxpgui as win32gui from win32com.axcontrol import axcontrol from win32com.propsys import propsys from win32com.server.exception import COMException from win32com.server.util import NewEnum as _NewEnum, wrap as _wrap from win32com.shell import shell, shellcon from win32com.util import IIDToInterfaceName def LoadString(sid): return _sids[sid] IDS_SETTING2 = _make_ids("Setting 2") def onSetting2(items, bindctx): win32gui.MessageBox(0, LoadString(IDS_SETTING2), "Hello", win32con.MB_OK)
null
175,070
import os import pickle import random import sys import commctrl import pythoncom import win32api import win32con import winerror import winxpgui as win32gui from win32com.axcontrol import axcontrol from win32com.propsys import propsys from win32com.server.exception import COMException from win32com.server.util import NewEnum as _NewEnum, wrap as _wrap from win32com.shell import shell, shellcon from win32com.util import IIDToInterfaceName def LoadString(sid): return _sids[sid] IDS_SETTING3 = _make_ids("Setting 3") def onSetting3(items, bindctx): win32gui.MessageBox(0, LoadString(IDS_SETTING3), "Hello", win32con.MB_OK)
null
175,071
import os import pickle import random import sys import commctrl import pythoncom import win32api import win32con import winerror import winxpgui as win32gui from win32com.axcontrol import axcontrol from win32com.propsys import propsys from win32com.server.exception import COMException from win32com.server.util import NewEnum as _NewEnum, wrap as _wrap from win32com.shell import shell, shellcon from win32com.util import IIDToInterfaceName class ContextMenu: def __init__(self): def Initialize(self, folder, dataobj, hkey): def QueryContextMenu(self, hMenu, indexMenu, idCmdFirst, idCmdLast, uFlags): def InvokeCommand(self, ci): def GetCommandString(self, cmd, typ): def SetSite(self, site): def GetSite(self, iid): class ShellFolder: def __init__(self, level=0): def ParseDisplayName(self, hwnd, reserved, displayName, attr): def EnumObjects(self, hwndOwner, flags): def BindToObject(self, pidl, bc, iid): def BindToStorage(self, pidl, bc, iid): def CompareIDs(self, param, id1, id2): def CreateViewObject(self, hwnd, iid): def GetAttributesOf(self, pidls, attrFlags): def GetUIObjectOf(self, hwndOwner, pidls, iid, inout): def GetDisplayNameOf(self, pidl, flags): def SetNameOf(self, hwndOwner, pidl, new_name, flags): def GetClassID(self): def Initialize(self, pidl): def EnumSearches(self): def GetDefaultColumn(self, dwres): def GetDefaultColumnState(self, iCol): def GetDefaultSearchGUID(self): def _GetColumnDisplayName(self, pidl, pkey): def GetDetailsEx(self, pidl, pkey): def GetDetailsOf(self, pidl, iCol): def MapColumnToSCID(self, iCol): def GetCurFolder(self): def get_schema_fname(): def DllRegisterServer(): import winreg if sys.getwindowsversion()[0] < 6: print("This sample only works on Vista") sys.exit(1) key = winreg.CreateKey( winreg.HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\" "Explorer\\Desktop\\Namespace\\" + ShellFolder._reg_clsid_, ) winreg.SetValueEx(key, None, 0, winreg.REG_SZ, ShellFolder._reg_desc_) # And special shell keys under our CLSID key = winreg.CreateKey( winreg.HKEY_CLASSES_ROOT, "CLSID\\" + ShellFolder._reg_clsid_ + "\\ShellFolder" ) # 'Attributes' is an int stored as a binary! use struct attr = ( shellcon.SFGAO_FOLDER | shellcon.SFGAO_HASSUBFOLDER | shellcon.SFGAO_BROWSABLE ) import struct s = struct.pack("i", attr) winreg.SetValueEx(key, "Attributes", 0, winreg.REG_BINARY, s) # register the context menu handler under the FolderViewSampleType type. keypath = "%s\\shellex\\ContextMenuHandlers\\%s" % ( ContextMenu._context_menu_type_, ContextMenu._reg_desc_, ) key = winreg.CreateKey(winreg.HKEY_CLASSES_ROOT, keypath) winreg.SetValueEx(key, None, 0, winreg.REG_SZ, ContextMenu._reg_clsid_) propsys.PSRegisterPropertySchema(get_schema_fname()) print(ShellFolder._reg_desc_, "registration complete.")
null
175,072
import os import pickle import random import sys import commctrl import pythoncom import win32api import win32con import winerror import winxpgui as win32gui from win32com.axcontrol import axcontrol from win32com.propsys import propsys from win32com.server.exception import COMException from win32com.server.util import NewEnum as _NewEnum, wrap as _wrap from win32com.shell import shell, shellcon from win32com.util import IIDToInterfaceName class ContextMenu: _reg_progid_ = "Python.ShellFolderSample.ContextMenu" _reg_desc_ = "Python FolderView Context Menu" _reg_clsid_ = "{fed40039-021f-4011-87c5-6188b9979764}" _com_interfaces_ = [ shell.IID_IShellExtInit, shell.IID_IContextMenu, axcontrol.IID_IObjectWithSite, ] _public_methods_ = ( shellcon.IContextMenu_Methods + shellcon.IShellExtInit_Methods + ["GetSite", "SetSite"] ) _context_menu_type_ = "PythonFolderViewSampleType" def __init__(self): self.site = None self.dataobj = None def Initialize(self, folder, dataobj, hkey): self.dataobj = dataobj def QueryContextMenu(self, hMenu, indexMenu, idCmdFirst, idCmdLast, uFlags): s = LoadString(IDS_DISPLAY) win32gui.InsertMenu( hMenu, indexMenu, win32con.MF_BYPOSITION, idCmdFirst + MENUVERB_DISPLAY, s ) indexMenu += 1 # other verbs could go here... # indicate that we added one verb. return 1 def InvokeCommand(self, ci): mask, hwnd, verb, params, dir, nShow, hotkey, hicon = ci # this seems very convuluted, but its what the sample does :) for verb_name, verb_id, flag in folderViewImplContextMenuIDs: if isinstance(verb, int): matches = verb == verb_id else: matches = verb == verb_name if matches: break else: assert False, ci # failed to find our ID if verb_id == MENUVERB_DISPLAY: sia = shell.SHCreateShellItemArrayFromDataObject(self.dataobj) DisplayItem(hwnd, sia) else: assert False, ci # Got some verb we weren't expecting? def GetCommandString(self, cmd, typ): raise COMException(hresult=winerror.E_NOTIMPL) def SetSite(self, site): self.site = site def GetSite(self, iid): return self.site class ShellFolder: _com_interfaces_ = [ shell.IID_IBrowserFrameOptions, pythoncom.IID_IPersist, shell.IID_IPersistFolder, shell.IID_IPersistFolder2, shell.IID_IShellFolder, shell.IID_IShellFolder2, ] _public_methods_ = ( shellcon.IBrowserFrame_Methods + shellcon.IPersistFolder2_Methods + shellcon.IShellFolder2_Methods ) _reg_progid_ = "Python.ShellFolderSample.Folder2" _reg_desc_ = "Python FolderView sample" _reg_clsid_ = "{bb8c24ad-6aaa-4cec-ac5e-c429d5f57627}" max_levels = 5 def __init__(self, level=0): self.current_level = level self.pidl = None # set when Initialize is called def ParseDisplayName(self, hwnd, reserved, displayName, attr): # print "ParseDisplayName", displayName raise COMException(hresult=winerror.E_NOTIMPL) def EnumObjects(self, hwndOwner, flags): if self.current_level >= self.max_levels: return None return make_item_enum(self.current_level + 1, flags) def BindToObject(self, pidl, bc, iid): tail = pidl_to_item(pidl) # assert tail['is_folder'], "BindToObject should only be called on folders?" # *sob* # No point creating object just to have QI fail. if iid not in ShellFolder._com_interfaces_: raise COMException(hresult=winerror.E_NOTIMPL) child = ShellFolder(self.current_level + 1) # hrmph - not sure what multiple PIDLs here mean? # assert len(pidl)==1, pidl # expecting just relative child PIDL child.Initialize(self.pidl + pidl) return wrap(child, iid) def BindToStorage(self, pidl, bc, iid): return self.BindToObject(pidl, bc, iid) def CompareIDs(self, param, id1, id2): return 0 # XXX - todo - implement this! def CreateViewObject(self, hwnd, iid): if iid == shell.IID_IShellView: com_folder = wrap(self) return shell.SHCreateShellFolderView(com_folder) elif iid == shell.IID_ICategoryProvider: return wrap(ViewCategoryProvider(self)) elif iid == shell.IID_IContextMenu: ws = wrap(self) dcm = (hwnd, None, self.pidl, ws, None) return shell.SHCreateDefaultContextMenu(dcm, iid) elif iid == shell.IID_IExplorerCommandProvider: return wrap(ExplorerCommandProvider()) else: raise COMException(hresult=winerror.E_NOINTERFACE) def GetAttributesOf(self, pidls, attrFlags): assert len(pidls) == 1, "sample only expects 1 too!" assert len(pidls[0]) == 1, "expect relative pidls!" item = pidl_to_item(pidls[0]) flags = 0 if item["is_folder"]: flags |= shellcon.SFGAO_FOLDER if item["level"] < self.max_levels: flags |= shellcon.SFGAO_HASSUBFOLDER return flags # Retrieves an OLE interface that can be used to carry out # actions on the specified file objects or folders. def GetUIObjectOf(self, hwndOwner, pidls, iid, inout): assert len(pidls) == 1, "oops - arent expecting more than one!" assert len(pidls[0]) == 1, "assuming relative pidls!" item = pidl_to_item(pidls[0]) if iid == shell.IID_IContextMenu: ws = wrap(self) dcm = (hwndOwner, None, self.pidl, ws, pidls) return shell.SHCreateDefaultContextMenu(dcm, iid) elif iid == shell.IID_IExtractIconW: dxi = shell.SHCreateDefaultExtractIcon() # dxi is IDefaultExtractIconInit if item["is_folder"]: dxi.SetNormalIcon("shell32.dll", 4) else: dxi.SetNormalIcon("shell32.dll", 1) # just return the dxi - let Python QI for IID_IExtractIconW return dxi elif iid == pythoncom.IID_IDataObject: return shell.SHCreateDataObject(self.pidl, pidls, None, iid) elif iid == shell.IID_IQueryAssociations: elts = [] if item["is_folder"]: elts.append((shellcon.ASSOCCLASS_FOLDER, None, None)) elts.append( (shellcon.ASSOCCLASS_PROGID_STR, None, ContextMenu._context_menu_type_) ) return shell.AssocCreateForClasses(elts, iid) raise COMException(hresult=winerror.E_NOINTERFACE) # Retrieves the display name for the specified file object or subfolder. def GetDisplayNameOf(self, pidl, flags): item = pidl_to_item(pidl) if flags & shellcon.SHGDN_FORPARSING: if flags & shellcon.SHGDN_INFOLDER: return item["name"] else: if flags & shellcon.SHGDN_FORADDRESSBAR: sigdn = shellcon.SIGDN_DESKTOPABSOLUTEEDITING else: sigdn = shellcon.SIGDN_DESKTOPABSOLUTEPARSING parent = shell.SHGetNameFromIDList(self.pidl, sigdn) return parent + "\\" + item["name"] else: return item["name"] def SetNameOf(self, hwndOwner, pidl, new_name, flags): raise COMException(hresult=winerror.E_NOTIMPL) def GetClassID(self): return self._reg_clsid_ # IPersistFolder method def Initialize(self, pidl): self.pidl = pidl # IShellFolder2 methods def EnumSearches(self): raise COMException(hresult=winerror.E_NOINTERFACE) # Retrieves the default sorting and display columns. def GetDefaultColumn(self, dwres): # result is (sort, display) return 0, 0 # Retrieves the default state for a specified column. def GetDefaultColumnState(self, iCol): if iCol < 3: return shellcon.SHCOLSTATE_ONBYDEFAULT | shellcon.SHCOLSTATE_TYPE_STR raise COMException(hresult=winerror.E_INVALIDARG) # Requests the GUID of the default search object for the folder. def GetDefaultSearchGUID(self): raise COMException(hresult=winerror.E_NOTIMPL) # Helper function for getting the display name for a column. def _GetColumnDisplayName(self, pidl, pkey): item = pidl_to_item(pidl) is_folder = item["is_folder"] if pkey == PKEY_ItemNameDisplay: val = item["name"] elif pkey == PKEY_Sample_AreaSize and not is_folder: val = "%d Sq. Ft." % item["size"] elif pkey == PKEY_Sample_NumberOfSides and not is_folder: val = str(item["sides"]) # not sure why str() elif pkey == PKEY_Sample_DirectoryLevel: val = str(item["level"]) else: val = "" return val # Retrieves detailed information, identified by a # property set ID (FMTID) and property ID (PID), # on an item in a Shell folder. def GetDetailsEx(self, pidl, pkey): item = pidl_to_item(pidl) is_folder = item["is_folder"] if not is_folder and pkey == PKEY_PropList_PreviewDetails: return "prop:Sample.AreaSize;Sample.NumberOfSides;Sample.DirectoryLevel" return self._GetColumnDisplayName(pidl, pkey) # Retrieves detailed information, identified by a # column index, on an item in a Shell folder. def GetDetailsOf(self, pidl, iCol): key = self.MapColumnToSCID(iCol) if pidl is None: data = [ (commctrl.LVCFMT_LEFT, "Name"), (commctrl.LVCFMT_CENTER, "Size"), (commctrl.LVCFMT_CENTER, "Sides"), (commctrl.LVCFMT_CENTER, "Level"), ] if iCol >= len(data): raise COMException(hresult=winerror.E_FAIL) fmt, val = data[iCol] else: fmt = 0 # ? val = self._GetColumnDisplayName(pidl, key) cxChar = 24 return fmt, cxChar, val # Converts a column name to the appropriate # property set ID (FMTID) and property ID (PID). def MapColumnToSCID(self, iCol): data = [ PKEY_ItemNameDisplay, PKEY_Sample_AreaSize, PKEY_Sample_NumberOfSides, PKEY_Sample_DirectoryLevel, ] if iCol >= len(data): raise COMException(hresult=winerror.E_FAIL) return data[iCol] # IPersistFolder2 methods # Retrieves the PIDLIST_ABSOLUTE for the folder object. def GetCurFolder(self): # The docs say this is OK, but I suspect its a problem in this case :) # assert self.pidl, "haven't been initialized?" return self.pidl def get_schema_fname(): me = win32api.GetFullPathName(__file__) sc = os.path.splitext(me)[0] + ".propdesc" assert os.path.isfile(sc), sc return sc def DllUnregisterServer(): import winreg paths = [ "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Desktop\\Namespace\\" + ShellFolder._reg_clsid_, "%s\\shellex\\ContextMenuHandlers\\%s" % (ContextMenu._context_menu_type_, ContextMenu._reg_desc_), ] for path in paths: try: winreg.DeleteKey(winreg.HKEY_LOCAL_MACHINE, path) except WindowsError as details: import errno if details.errno != errno.ENOENT: print("FAILED to remove %s: %s" % (path, details)) propsys.PSUnregisterPropertySchema(get_schema_fname()) print(ShellFolder._reg_desc_, "unregistration complete.")
null
175,073
import glob import os import random import sys import pythoncom import win32gui import winerror from win32com.shell import shell, shellcon class ShellExtension: _reg_progid_ = "Python.ShellExtension.IconHandler" _reg_desc_ = "Python Sample Shell Extension (icon handler)" _reg_clsid_ = "{a97e32d7-3b78-448c-b341-418120ea9227}" _com_interfaces_ = [shell.IID_IExtractIcon, pythoncom.IID_IPersistFile] _public_methods_ = IExtractIcon_Methods + IPersistFile_Methods def Load(self, filename, mode): self.filename = filename self.mode = mode def GetIconLocation(self, flags): # note - returning a single int will set the HRESULT (eg, S_FALSE, # E_PENDING - see MS docs for details. return random.choice(ico_files), 0, 0 def Extract(self, fname, index, size): return winerror.S_FALSE def DllRegisterServer(): import winreg key = winreg.CreateKey(winreg.HKEY_CLASSES_ROOT, "Python.File\\shellex") subkey = winreg.CreateKey(key, "IconHandler") winreg.SetValueEx(subkey, None, 0, winreg.REG_SZ, ShellExtension._reg_clsid_) print(ShellExtension._reg_desc_, "registration complete.")
null
175,074
import glob import os import random import sys import pythoncom import win32gui import winerror from win32com.shell import shell, shellcon class ShellExtension: _reg_progid_ = "Python.ShellExtension.IconHandler" _reg_desc_ = "Python Sample Shell Extension (icon handler)" _reg_clsid_ = "{a97e32d7-3b78-448c-b341-418120ea9227}" _com_interfaces_ = [shell.IID_IExtractIcon, pythoncom.IID_IPersistFile] _public_methods_ = IExtractIcon_Methods + IPersistFile_Methods def Load(self, filename, mode): self.filename = filename self.mode = mode def GetIconLocation(self, flags): # note - returning a single int will set the HRESULT (eg, S_FALSE, # E_PENDING - see MS docs for details. return random.choice(ico_files), 0, 0 def Extract(self, fname, index, size): return winerror.S_FALSE def DllUnregisterServer(): import winreg try: key = winreg.DeleteKey( winreg.HKEY_CLASSES_ROOT, "Python.File\\shellex\\IconHandler" ) except WindowsError as details: import errno if details.errno != errno.ENOENT: raise print(ShellExtension._reg_desc_, "unregistration complete.")
null
175,075
import os import stat import commctrl import pythoncom from pywintypes import IID from win32com.server.util import wrap from win32com.shell import shell, shellcon class ColumnProvider: def GetClassID(self): def Initialize(self, colInit): def GetColumnInfo(self, index): def GetItemData(self, colid, colData): def DllRegisterServer(): import winreg # Special ColumnProvider key key = winreg.CreateKey( winreg.HKEY_CLASSES_ROOT, "Folder\\ShellEx\\ColumnHandlers\\" + str(ColumnProvider._reg_clsid_), ) winreg.SetValueEx(key, None, 0, winreg.REG_SZ, ColumnProvider._reg_desc_) print(ColumnProvider._reg_desc_, "registration complete.")
null
175,076
import os import stat import commctrl import pythoncom from pywintypes import IID from win32com.server.util import wrap from win32com.shell import shell, shellcon class ColumnProvider: _reg_progid_ = "Python.ShellExtension.ColumnProvider" _reg_desc_ = "Python Sample Shell Extension (Column Provider)" _reg_clsid_ = IID("{0F14101A-E05E-4070-BD54-83DFA58C3D68}") _com_interfaces_ = [ pythoncom.IID_IPersist, shell.IID_IColumnProvider, ] _public_methods_ = IColumnProvider_Methods # IPersist def GetClassID(self): return self._reg_clsid_ # IColumnProvider def Initialize(self, colInit): flags, reserved, name = colInit print("ColumnProvider initializing for file", name) def GetColumnInfo(self, index): # We support exactly 2 columns - 'pyc size' and 'pyo size' if index in [0, 1]: # As per the MSDN sample, use our CLSID as the fmtid if index == 0: ext = ".pyc" else: ext = ".pyo" title = ext + " size" description = "Size of compiled %s file" % ext col_id = (self._reg_clsid_, index) # fmtid # pid col_info = ( col_id, # scid pythoncom.VT_I4, # vt commctrl.LVCFMT_RIGHT, # fmt 20, # cChars shellcon.SHCOLSTATE_TYPE_INT | shellcon.SHCOLSTATE_SECONDARYUI, # csFlags title, description, ) return col_info return None # Indicate no more columns. def GetItemData(self, colid, colData): fmt_id, pid = colid fmt_id == self._reg_clsid_ flags, attr, reserved, ext, name = colData if ext.lower() not in [".py", ".pyw"]: return None if pid == 0: ext = ".pyc" else: ext = ".pyo" check_file = os.path.splitext(name)[0] + ext try: st = os.stat(check_file) return st[stat.ST_SIZE] except OSError: # No file return None def DllUnregisterServer(): import winreg try: key = winreg.DeleteKey( winreg.HKEY_CLASSES_ROOT, "Folder\\ShellEx\\ColumnHandlers\\" + str(ColumnProvider._reg_clsid_), ) except WindowsError as details: import errno if details.errno != errno.ENOENT: raise print(ColumnProvider._reg_desc_, "unregistration complete.")
null
175,077
import pythoncom from win32com.server.policy import DesignatedWrapPolicy from win32com.shell import shell, shellcon tsf_flags = list( (k, v) for k, v in list(shellcon.__dict__.items()) if k.startswith("TSF_") ) def decode_flags(flags): if flags == 0: return "TSF_NORMAL" flag_txt = "" for k, v in tsf_flags: if flags & v: if flag_txt: flag_txt = flag_txt + "|" + k else: flag_txt = k return flag_txt
null
175,078
import pythoncom from win32com.server.policy import DesignatedWrapPolicy from win32com.shell import shell, shellcon class FileOperationProgressSink(DesignatedWrapPolicy): _com_interfaces_ = [shell.IID_IFileOperationProgressSink] _public_methods_ = [ "StartOperations", "FinishOperations", "PreRenameItem", "PostRenameItem", "PreMoveItem", "PostMoveItem", "PreCopyItem", "PostCopyItem", "PreDeleteItem", "PostDeleteItem", "PreNewItem", "PostNewItem", "UpdateProgress", "ResetTimer", "PauseTimer", "ResumeTimer", ] def __init__(self): self._wrap_(self) def StartOperations(self): print("StartOperations") def FinishOperations(self, Result): print("FinishOperations: HRESULT ", Result) def PreRenameItem(self, Flags, Item, NewName): print( "PreRenameItem: Renaming " + Item.GetDisplayName(shellcon.SHGDN_FORPARSING) + " to " + NewName ) def PostRenameItem(self, Flags, Item, NewName, hrRename, NewlyCreated): if NewlyCreated is not None: newfile = NewlyCreated.GetDisplayName(shellcon.SHGDN_FORPARSING) else: newfile = "not renamed, HRESULT " + str(hrRename) print( "PostRenameItem: renamed " + Item.GetDisplayName(shellcon.SHGDN_FORPARSING) + " to " + newfile ) def PreMoveItem(self, Flags, Item, DestinationFolder, NewName): print( "PreMoveItem: Moving " + Item.GetDisplayName(shellcon.SHGDN_FORPARSING) + " to " + DestinationFolder.GetDisplayName(shellcon.SHGDN_FORPARSING) + "\\" + str(NewName) ) def PostMoveItem( self, Flags, Item, DestinationFolder, NewName, hrMove, NewlyCreated ): if NewlyCreated is not None: newfile = NewlyCreated.GetDisplayName(shellcon.SHGDN_FORPARSING) else: newfile = "not copied, HRESULT " + str(hrMove) print( "PostMoveItem: Moved " + Item.GetDisplayName(shellcon.SHGDN_FORPARSING) + " to " + newfile ) def PreCopyItem(self, Flags, Item, DestinationFolder, NewName): if not NewName: NewName = "" print( "PreCopyItem: Copying " + Item.GetDisplayName(shellcon.SHGDN_FORPARSING) + " to " + DestinationFolder.GetDisplayName(shellcon.SHGDN_FORPARSING) + "\\" + NewName ) print("Flags: ", decode_flags(Flags)) def PostCopyItem( self, Flags, Item, DestinationFolder, NewName, hrCopy, NewlyCreated ): if NewlyCreated is not None: newfile = NewlyCreated.GetDisplayName(shellcon.SHGDN_FORPARSING) else: newfile = "not copied, HRESULT " + str(hrCopy) print( "PostCopyItem: Copied " + Item.GetDisplayName(shellcon.SHGDN_FORPARSING) + " to " + newfile ) print("Flags: ", decode_flags(Flags)) def PreDeleteItem(self, Flags, Item): print( "PreDeleteItem: Deleting " + Item.GetDisplayName(shellcon.SHGDN_FORPARSING) ) def PostDeleteItem(self, Flags, Item, hrDelete, NewlyCreated): print( "PostDeleteItem: Deleted " + Item.GetDisplayName(shellcon.SHGDN_FORPARSING) ) if NewlyCreated: print( " Moved to recycle bin - " + NewlyCreated.GetDisplayName(shellcon.SHGDN_FORPARSING) ) def PreNewItem(self, Flags, DestinationFolder, NewName): print( "PreNewItem: Creating " + DestinationFolder.GetDisplayName(shellcon.SHGDN_FORPARSING) + "\\" + NewName ) def PostNewItem( self, Flags, DestinationFolder, NewName, TemplateName, FileAttributes, hrNew, NewItem, ): print( "PostNewItem: Created " + NewItem.GetDisplayName(shellcon.SHGDN_FORPARSING) ) def UpdateProgress(self, WorkTotal, WorkSoFar): print("UpdateProgress: ", WorkSoFar, WorkTotal) def ResetTimer(self): print("ResetTimer") def PauseTimer(self): print("PauseTimer") def ResumeTimer(self): print("ResumeTimer") def CreateSink(): return pythoncom.WrapObject( FileOperationProgressSink(), shell.IID_IFileOperationProgressSink )
null
175,079
import pythoncom from win32com.server.policy import DesignatedWrapPolicy from win32com.shell import shell, shellcon class TransferAdviseSink(DesignatedWrapPolicy): _com_interfaces_ = [shell.IID_ITransferAdviseSink] _public_methods_ = [ "UpdateProgress", "UpdateTransferState", "ConfirmOverwrite", "ConfirmEncryptionLoss", "FileFailure", "SubStreamFailure", "PropertyFailure", ] def __init__(self): self._wrap_(self) def UpdateProgress( self, SizeCurrent, SizeTotal, FilesCurrent, FilesTotal, FoldersCurrent, FoldersTotal, ): print("UpdateProgress - processed so far:") print("\t %s out of %s bytes" % (SizeCurrent, SizeTotal)) print("\t %s out of %s files" % (FilesCurrent, FilesTotal)) print("\t %s out of %s folders" % (FoldersCurrent, FoldersTotal)) def UpdateTransferState(self, State): print( "Current state: ", TRANSFER_ADVISE_STATES.get(State, "??? Unknown state %s ???" % State), ) def ConfirmOverwrite(self, Source, DestParent, Name): print( "ConfirmOverwrite: ", Source.GetDisplayName(shellcon.SHGDN_FORPARSING), DestParent.GetDisplayName(shellcon.SHGDN_FORPARSING), Name, ) def ConfirmEncryptionLoss(self, Source): print( "ConfirmEncryptionLoss:", Source.GetDisplayName(shellcon.SHGDN_FORPARSING) ) def FileFailure(self, Item, ItemName, Error): print("FileFailure:", Item.GetDisplayName(shellcon.SHGDN_FORPARSING), ItemName) def SubStreamFailure(self, Item, StreamName, Error): print("SubStreamFailure:\n") def PropertyFailure(self, Item, key, Error): print("PropertyFailure:\n") def CreateSink(): return pythoncom.WrapObject( TransferAdviseSink(), shell.IID_ITransferAdviseSink, shell.IID_ITransferAdviseSink, )
null
175,080
import os import win32gui from win32com.shell import shell, shellcon def BrowseCallbackProc(hwnd, msg, lp, data): if msg == shellcon.BFFM_INITIALIZED: win32gui.SendMessage(hwnd, shellcon.BFFM_SETSELECTION, 1, data) elif msg == shellcon.BFFM_SELCHANGED: # Set the status text of the # For this message, 'lp' is the address of the PIDL. pidl = shell.AddressAsPIDL(lp) try: path = shell.SHGetPathFromIDList(pidl) win32gui.SendMessage(hwnd, shellcon.BFFM_SETSTATUSTEXT, 0, path) except shell.error: # No path for this PIDL pass
null
175,081
import glob import os import sys import pythoncom from win32com.shell import shell, shellcon from win32com.storagecon import * def FavDumper(nothing, path, names): # called by os.path.walk for name in names: print(name, end=" ") try: DumpLink(name) except pythoncom.com_error: print(" - not a link") def DumpFavorites(): favfold = str(shell.SHGetSpecialFolderPath(0, shellcon.CSIDL_FAVORITES)) print("Your favourites are at", favfold) os.path.walk(favfold, FavDumper, None)
null
175,082
from win32com.shell import shell, shellcon def walk(folder, depth=2, indent=""): try: pidls = folder.EnumObjects(0, shellcon.SHCONTF_FOLDERS) except shell.error: # no items return for pidl in pidls: dn = folder.GetDisplayNameOf(pidl, shellcon.SHGDN_NORMAL) print(indent, dn) if depth: try: child = folder.BindToObject(pidl, None, shell.IID_IShellFolder) except shell.error: pass else: walk(child, depth - 1, indent + " ")
null
175,083
import os import sys import pythoncom from win32com.shell import shell, shellcon print("Template folder:", template_folder) template_pb = shell.SHGetViewStatePropertyBag( template_pidl, "Shell", shellcon.SHGVSPB_FOLDERNODEFAULTS, pythoncom.IID_IPropertyBag, ) template_stream = template_iunk.QueryInterface(pythoncom.IID_IStream) template_colinfo = template_stream.Read(streamsize) os.path.walk(template_folder, update_colinfo, None) def update_colinfo(not_used, dir_name, fnames): for fname in fnames: full_fname = os.path.join(dir_name, fname) if os.path.isdir(full_fname): print(full_fname) pidl = shell.SHILCreateFromPath(full_fname, 0)[0] pb = shell.SHGetViewStatePropertyBag( pidl, "Shell", shellcon.SHGVSPB_FOLDERNODEFAULTS, pythoncom.IID_IPropertyBag, ) ## not all folders already have column info, and we're replacing it anyway pb.Write("ColInfo", template_stream) iunk = pb.Read("ColInfo", pythoncom.VT_UNKNOWN) s = iunk.QueryInterface(pythoncom.IID_IStream) s.Write(template_colinfo) s = None ## attribute names read from registry, can't find any way to enumerate IPropertyBag for attr in ( "Address", "Buttons", "Col", "Vid", "WFlags", "FFlags", "Sort", "SortDir", "ShowCmd", "FolderType", "Mode", "Rev", ): pb.Write(attr, template_pb.Read(attr)) pb = None
null
175,084
import win32con from win32com.shell import shell, shellcon def ExplorePIDL(): pidl = shell.SHGetSpecialFolderLocation(0, shellcon.CSIDL_DESKTOP) print("The desktop is at", shell.SHGetPathFromIDList(pidl)) shell.ShellExecuteEx( fMask=shellcon.SEE_MASK_NOCLOSEPROCESS, nShow=win32con.SW_NORMAL, lpClass="folder", lpVerb="explore", lpIDList=pidl, ) print("Done!")
null
175,085
import pythoncom from pywintypes import TimeType from . import mapi, mapitags mapiErrorTable = {} def GetScodeString(hr): if not mapiErrorTable: for name, value in mapi.__dict__.items(): if name[:7] in ["MAPI_E_", "MAPI_W_"]: mapiErrorTable[value] = name return mapiErrorTable.get(hr, pythoncom.GetScodeString(hr))
null
175,086
import pythoncom from pywintypes import TimeType from . import mapi, mapitags ptTable = {} The provided code snippet includes necessary dependencies for implementing the `GetMapiTypeName` function. Write a Python function `def GetMapiTypeName(propType, rawType=True)` to solve the following problem: Given a mapi type flag, return a string description of the type Here is the function: def GetMapiTypeName(propType, rawType=True): """Given a mapi type flag, return a string description of the type""" if not ptTable: for name, value in mapitags.__dict__.items(): if name[:3] == "PT_": # PT_TSTRING is a conditional assignment # for either PT_UNICODE or PT_STRING8 and # should not be returned during a lookup. if name in ["PT_TSTRING", "PT_MV_TSTRING"]: continue ptTable[value] = name if rawType: propType = propType & ~mapitags.MV_FLAG return ptTable.get(propType, str(hex(propType)))
Given a mapi type flag, return a string description of the type
175,087
TupleType = tuple ListType = list IntType = int import pythoncom from pywintypes import TimeType from . import mapi, mapitags The provided code snippet includes necessary dependencies for implementing the `GetProperties` function. Write a Python function `def GetProperties(obj, propList)` to solve the following problem: Given a MAPI object and a list of properties, return a list of property values. Allows a single property to be passed, and the result is a single object. Each request property can be an integer or a string. Of a string, it is automatically converted to an integer via the GetIdsFromNames function. If the property fetch fails, the result is None. Here is the function: def GetProperties(obj, propList): """Given a MAPI object and a list of properties, return a list of property values. Allows a single property to be passed, and the result is a single object. Each request property can be an integer or a string. Of a string, it is automatically converted to an integer via the GetIdsFromNames function. If the property fetch fails, the result is None. """ bRetList = 1 if type(propList) not in [TupleType, ListType]: bRetList = 0 propList = (propList,) realPropList = [] rc = [] for prop in propList: if type(prop) != IntType: # Integer props = ((mapi.PS_PUBLIC_STRINGS, prop),) propIds = obj.GetIDsFromNames(props, 0) prop = mapitags.PROP_TAG( mapitags.PT_UNSPECIFIED, mapitags.PROP_ID(propIds[0]) ) realPropList.append(prop) hr, data = obj.GetProps(realPropList, 0) if hr != 0: data = None return None if bRetList: return [v[1] for v in data] else: return data[0][1]
Given a MAPI object and a list of properties, return a list of property values. Allows a single property to be passed, and the result is a single object. Each request property can be an integer or a string. Of a string, it is automatically converted to an integer via the GetIdsFromNames function. If the property fetch fails, the result is None.
175,088
import pythoncom from pywintypes import TimeType from . import mapi, mapitags def GetPropTagName(pt): if not prTable: for name, value in mapitags.__dict__.items(): if name[:3] == "PR_": # Store both the full ID (including type) and just the ID. # This is so PR_FOO_A and PR_FOO_W are still differentiated, # but should we get a PT_FOO with PT_ERROR set, we fallback # to the ID. # String types should have 3 definitions in mapitags.py # PR_BODY = PROP_TAG( PT_TSTRING, 4096) # PR_BODY_W = PROP_TAG( PT_UNICODE, 4096) # PR_BODY_A = PROP_TAG( PT_STRING8, 4096) # The following change ensures a lookup using only the the # property id returns the conditional default. # PT_TSTRING is a conditional assignment for either PT_UNICODE or # PT_STRING8 and should not be returned during a lookup. if ( mapitags.PROP_TYPE(value) == mapitags.PT_UNICODE or mapitags.PROP_TYPE(value) == mapitags.PT_STRING8 ): if name[-2:] == "_A" or name[-2:] == "_W": prTable[value] = name else: prTable[mapitags.PROP_ID(value)] = name else: prTable[value] = name prTable[mapitags.PROP_ID(value)] = name try: try: return prTable[pt] except KeyError: # Can't find it exactly - see if the raw ID exists. return prTable[mapitags.PROP_ID(pt)] except KeyError: # god-damn bullshit hex() warnings: I don't see a way to get the # old behaviour without a warning!! ret = hex(int(pt)) # -0x8000000L -> 0x80000000 if ret[0] == "-": ret = ret[1:] if ret[-1] == "L": ret = ret[:-1] return ret def GetAllProperties(obj, make_tag_names=True): tags = obj.GetPropList(0) hr, data = obj.GetProps(tags) ret = [] for tag, val in data: if make_tag_names: hr, tags, array = obj.GetNamesFromIDs((tag,)) if type(array[0][1]) == type(""): name = array[0][1] else: name = GetPropTagName(tag) else: name = tag ret.append((name, val)) return ret
null
175,089
IntType = int import pythoncom from pywintypes import TimeType from . import mapi, mapitags _MapiTypeMap = { type(0.0): mapitags.PT_DOUBLE, type(0): mapitags.PT_I4, type("".encode("ascii")): mapitags.PT_STRING8, # bytes type(""): mapitags.PT_UNICODE, # str type(None): mapitags.PT_UNSPECIFIED, # In Python 2.2.2, bool isn't a distinct type (type(1==1) is type(0)). # (markh thinks the above is trying to say that in 2020, we probably *do* # want bool in this map? :) } def SetPropertyValue(obj, prop, val): if type(prop) != IntType: props = ((mapi.PS_PUBLIC_STRINGS, prop),) propIds = obj.GetIDsFromNames(props, mapi.MAPI_CREATE) if val == (1 == 1) or val == (1 == 0): type_tag = mapitags.PT_BOOLEAN else: type_tag = _MapiTypeMap.get(type(val)) if type_tag is None: raise ValueError( "Don't know what to do with '%r' ('%s')" % (val, type(val)) ) prop = mapitags.PROP_TAG(type_tag, mapitags.PROP_ID(propIds[0])) if val is None: # Delete the property obj.DeleteProps((prop,)) else: obj.SetProps(((prop, val),))
null
175,090
IntType = int import pythoncom from pywintypes import TimeType from . import mapi, mapitags The provided code snippet includes necessary dependencies for implementing the `SetProperties` function. Write a Python function `def SetProperties(msg, propDict)` to solve the following problem: Given a Python dictionary, set the objects properties. If the dictionary key is a string, then a property ID is queried otherwise the ID is assumed native. Coded for maximum efficiency wrt server calls - ie, maximum of 2 calls made to the object, regardless of the dictionary contents (only 1 if dictionary full of int keys) Here is the function: def SetProperties(msg, propDict): """Given a Python dictionary, set the objects properties. If the dictionary key is a string, then a property ID is queried otherwise the ID is assumed native. Coded for maximum efficiency wrt server calls - ie, maximum of 2 calls made to the object, regardless of the dictionary contents (only 1 if dictionary full of int keys) """ newProps = [] # First pass over the properties we should get IDs for. for key, val in propDict.items(): if type(key) == str: newProps.append((mapi.PS_PUBLIC_STRINGS, key)) # Query for the new IDs if newProps: newIds = msg.GetIDsFromNames(newProps, mapi.MAPI_CREATE) newIdNo = 0 newProps = [] for key, val in propDict.items(): if type(key) == str: type_val = type(val) if type_val == str: tagType = mapitags.PT_UNICODE elif type_val == IntType: tagType = mapitags.PT_I4 elif type_val == TimeType: tagType = mapitags.PT_SYSTIME else: raise ValueError( "The type of object %s(%s) can not be written" % (repr(val), type_val) ) key = mapitags.PROP_TAG(tagType, mapitags.PROP_ID(newIds[newIdNo])) newIdNo = newIdNo + 1 newProps.append((key, val)) msg.SetProps(newProps)
Given a Python dictionary, set the objects properties. If the dictionary key is a string, then a property ID is queried otherwise the ID is assumed native. Coded for maximum efficiency wrt server calls - ie, maximum of 2 calls made to the object, regardless of the dictionary contents (only 1 if dictionary full of int keys)
175,091
from win32com.mapi import mapi, mapitags The provided code snippet includes necessary dependencies for implementing the `SendEMAPIMail` function. Write a Python function `def SendEMAPIMail( Subject="", Message="", SendTo=None, SendCC=None, SendBCC=None, MAPIProfile=None )` to solve the following problem: Sends an email to the recipient using the extended MAPI interface Subject and Message are strings Send{To,CC,BCC} are comma-separated address lists MAPIProfile is the name of the MAPI profile Here is the function: def SendEMAPIMail( Subject="", Message="", SendTo=None, SendCC=None, SendBCC=None, MAPIProfile=None ): """Sends an email to the recipient using the extended MAPI interface Subject and Message are strings Send{To,CC,BCC} are comma-separated address lists MAPIProfile is the name of the MAPI profile""" # initialize and log on mapi.MAPIInitialize(None) session = mapi.MAPILogonEx( 0, MAPIProfile, None, mapi.MAPI_EXTENDED | mapi.MAPI_USE_DEFAULT ) messagestorestable = session.GetMsgStoresTable(0) messagestorestable.SetColumns( (mapitags.PR_ENTRYID, mapitags.PR_DISPLAY_NAME_A, mapitags.PR_DEFAULT_STORE), 0 ) while True: rows = messagestorestable.QueryRows(1, 0) # if this is the last row then stop if len(rows) != 1: break row = rows[0] # if this is the default store then stop if (mapitags.PR_DEFAULT_STORE, True) in row: break # unpack the row and open the message store (eid_tag, eid), (name_tag, name), (def_store_tag, def_store) = row msgstore = session.OpenMsgStore( 0, eid, None, mapi.MDB_NO_DIALOG | mapi.MAPI_BEST_ACCESS ) # get the outbox hr, props = msgstore.GetProps((mapitags.PR_IPM_OUTBOX_ENTRYID), 0) (tag, eid) = props[0] # check for errors if mapitags.PROP_TYPE(tag) == mapitags.PT_ERROR: raise TypeError("got PT_ERROR instead of PT_BINARY: %s" % eid) outboxfolder = msgstore.OpenEntry(eid, None, mapi.MAPI_BEST_ACCESS) # create the message and the addrlist message = outboxfolder.CreateMessage(None, 0) # note: you can use the resolveaddress functions for this. but you may get headaches pal = [] def makeentry(recipient, recipienttype): return ( (mapitags.PR_RECIPIENT_TYPE, recipienttype), (mapitags.PR_SEND_RICH_INFO, False), (mapitags.PR_DISPLAY_TYPE, 0), (mapitags.PR_OBJECT_TYPE, 6), (mapitags.PR_EMAIL_ADDRESS_A, recipient), (mapitags.PR_ADDRTYPE_A, "SMTP"), (mapitags.PR_DISPLAY_NAME_A, recipient), ) if SendTo: pal.extend( [makeentry(recipient, mapi.MAPI_TO) for recipient in SendTo.split(",")] ) if SendCC: pal.extend( [makeentry(recipient, mapi.MAPI_CC) for recipient in SendCC.split(",")] ) if SendBCC: pal.extend( [makeentry(recipient, mapi.MAPI_BCC) for recipient in SendBCC.split(",")] ) # add the resolved recipients to the message message.ModifyRecipients(mapi.MODRECIP_ADD, pal) message.SetProps([(mapitags.PR_BODY_A, Message), (mapitags.PR_SUBJECT_A, Subject)]) # save changes and submit outboxfolder.SaveChanges(0) message.SubmitMessage(0)
Sends an email to the recipient using the extended MAPI interface Subject and Message are strings Send{To,CC,BCC} are comma-separated address lists MAPIProfile is the name of the MAPI profile
175,092
import pythoncom import pywintypes from win32com import storagecon from win32com.ifilter import ifilter from win32com.ifilter.ifiltercon import * def _usage(): import os print("Usage: %s filename [verbose [dumpbody]]" % (os.path.basename(sys.argv[0]),)) print() print("Where:-") print("filename = name of the file to extract text & properties from") print("verbose = 1=debug output, 0=no debug output (default=0)") print("dumpbody = 1=print text content, 0=don't print content (default=1)") print() print("e.g. to dump a word file called spam.doc go:- filterDemo.py spam.doc") print() print("by default .htm, .txt, .doc, .dot, .xls, .xlt, .ppt are supported") print("you can filter .pdf's by downloading adobes ifilter component. ") print( "(currently found at http://download.adobe.com/pub/adobe/acrobat/win/all/ifilter50.exe)." ) print("ifilters for other filetypes are also available.") print() print( "This extension is only supported on win2000 & winXP - because thats the only" ) print("place the ifilter stuff is supported. For more info on the API check out ") print("MSDN under ifilters")
null
175,093
def iif(cond, t, f): if cond: return t else: return f
null
175,094
import re import sys import pythoncom import win32api import win32com.client.connect import win32com.server.util import winerror from win32com.axscript import axscript from win32com.server.exception import Exception, IsCOMServerException from . import error def RemoveCR(text): # No longer just "RemoveCR" - should be renamed to # FixNewlines, or something. Idea is to fix arbitary newlines into # something Python can compile... return re.sub("(\r\n)|\r|(\n\r)", "\n", text)
null
175,095
import re import sys import pythoncom import win32api import win32com.client.connect import win32com.server.util import winerror from win32com.axscript import axscript from win32com.server.exception import Exception, IsCOMServerException from . import error def profile(fn, *args): import profile prof = profile.Profile() try: # roll on 1.6 :-) # return prof.runcall(fn, *args) return prof.runcall(*(fn,) + args) finally: import pstats # Damn - really want to send this to Excel! # width, list = pstats.Stats(prof).strip_dirs().get_print_list([]) pstats.Stats(prof).strip_dirs().sort_stats("time").print_stats()
null
175,096
import re import sys import pythoncom import win32api import win32com.client.connect import win32com.server.util import winerror from win32com.axscript import axscript from win32com.server.exception import Exception, IsCOMServerException from . import error class SafeOutput: def __init__(self, redir=None): def write(self, message): def flush(self): def close(self): def MakeValidSysOuts(): if not isinstance(sys.stdout, SafeOutput): sys.stdout = sys.stderr = SafeOutput() # and for the sake of working around something I can't understand... # prevent keyboard interrupts from killing IIS import signal def noOp(a, b): # it would be nice to get to the bottom of this, so a warning to # the debug console can't hurt. print("WARNING: Ignoring keyboard interrupt from ActiveScripting engine") # If someone else has already redirected, then assume they know what they are doing! if signal.getsignal(signal.SIGINT) == signal.default_int_handler: try: signal.signal(signal.SIGINT, noOp) except ValueError: # Not the main thread - can't do much. pass
null
175,097
import re import sys import pythoncom import win32api import win32com.client.connect import win32com.server.util import winerror from win32com.axscript import axscript from win32com.server.exception import Exception, IsCOMServerException from . import error The provided code snippet includes necessary dependencies for implementing the `trace` function. Write a Python function `def trace(*args)` to solve the following problem: A function used instead of "print" for debugging output. Here is the function: def trace(*args): """A function used instead of "print" for debugging output.""" for arg in args: print(arg, end=" ") print()
A function used instead of "print" for debugging output.
175,098
import re import sys import pythoncom import win32api import win32com.client.connect import win32com.server.util import winerror from win32com.axscript import axscript from win32com.server.exception import Exception, IsCOMServerException from . import error Exception = COMException The provided code snippet includes necessary dependencies for implementing the `RaiseAssert` function. Write a Python function `def RaiseAssert(scode, desc)` to solve the following problem: A debugging function that raises an exception considered an "Assertion". Here is the function: def RaiseAssert(scode, desc): """A debugging function that raises an exception considered an "Assertion".""" print("**************** ASSERTION FAILED *******************") print(desc) raise Exception(desc, scode)
A debugging function that raises an exception considered an "Assertion".
175,099
import re import sys import pythoncom import win32api import win32com.client.connect import win32com.server.util import winerror from win32com.axscript import axscript from win32com.server.exception import Exception, IsCOMServerException from . import error def dumptypeinfo(typeinfo): return attr = typeinfo.GetTypeAttr() # Loop over all methods print("Methods") for j in range(attr[6]): fdesc = list(typeinfo.GetFuncDesc(j)) id = fdesc[0] try: names = typeinfo.GetNames(id) except pythoncom.ole_error: names = None doc = typeinfo.GetDocumentation(id) print(" ", names, "has attr", fdesc) # Loop over all variables (ie, properties) print("Variables") for j in range(attr[7]): fdesc = list(typeinfo.GetVarDesc(j)) names = typeinfo.GetNames(id) print(" ", names, "has attr", fdesc)
null
175,100
from win32com.axscript import axscript from . import pyscript from .pyscript import SCRIPTTEXT_FORCEEXECUTION, Exception, RaiseAssert, trace PyDump_CLSID = "{ac527e60-c693-11d0-9c25-00aa00125a98}" def RegisterServer( clsid, pythonInstString=None, desc=None, progID=None, verProgID=None, defIcon=None, threadingModel="both", policy=None, catids=[], other={}, addPyComCat=None, dispatcher=None, clsctx=None, addnPath=None, ): def Register(): import sys if "-d" in sys.argv: dispatcher = "DispatcherWin32trace" debug_desc = " (" + dispatcher + ")" debug_option = "Yes" else: dispatcher = None debug_desc = "" debug_option = "" categories = [axscript.CATID_ActiveScript, axscript.CATID_ActiveScriptParse] clsid = PyDump_CLSID lcid = 0x0409 # // english policy = None # "win32com.axscript.client.axspolicy.AXScriptPolicy" print("Registering COM server%s..." % debug_desc) from win32com.server.register import RegisterServer languageName = "PyDump" verProgId = "Python.Dumper.1" RegisterServer( clsid=clsid, pythonInstString="win32com.axscript.client.pyscript.PyDumper", className="Python Debugging/Dumping ActiveX Scripting Engine", progID=languageName, verProgID=verProgId, catids=categories, policy=policy, dispatcher=dispatcher, ) CreateRegKey(languageName + "\\OLEScript") # Basic Registration for wsh. win32com.server.register._set_string(".pysDump", "pysDumpFile") win32com.server.register._set_string("pysDumpFile\\ScriptEngine", languageName) print("Dumping Server registered.")
null
175,101
import types import pythoncom import win32com.server.policy import win32com.server.util import winerror from win32com.axscript import axscript from win32com.client import Dispatch from win32com.server.exception import COMException def _is_callable(obj): return type(obj) in [types.FunctionType, types.MethodType] # ignore hasattr(obj, "__call__") as this means all COM objects!
null
175,102
import types import pythoncom import win32com.server.policy import win32com.server.util import winerror from win32com.axscript import axscript from win32com.client import Dispatch from win32com.server.exception import COMException class StrictDynamicPolicy(win32com.server.policy.DynamicPolicy): def _wrap_(self, object): win32com.server.policy.DynamicPolicy._wrap_(self, object) if hasattr(self._obj_, "scriptNamespace"): for name in dir(self._obj_.scriptNamespace): self._dyn_dispid_to_name_[self._getdispid_(name, 0)] = name def _getmembername_(self, dispid): try: return str(self._dyn_dispid_to_name_[dispid]) except KeyError: raise COMException(scode=winerror.DISP_E_UNKNOWNNAME, desc="Name not found") def _getdispid_(self, name, fdex): try: func = getattr(self._obj_.scriptNamespace, str(name)) except AttributeError: raise COMException(scode=winerror.DISP_E_MEMBERNOTFOUND) # if not _is_callable(func): return win32com.server.policy.DynamicPolicy._getdispid_(self, name, fdex) def _wrap_debug(obj): return win32com.server.util.wrap( obj, usePolicy=StrictDynamicPolicy, useDispatcher=win32com.server.policy.DispatcherWin32trace, )
null
175,103
import types import pythoncom import win32com.server.policy import win32com.server.util import winerror from win32com.axscript import axscript from win32com.client import Dispatch from win32com.server.exception import COMException class StrictDynamicPolicy(win32com.server.policy.DynamicPolicy): def _wrap_(self, object): win32com.server.policy.DynamicPolicy._wrap_(self, object) if hasattr(self._obj_, "scriptNamespace"): for name in dir(self._obj_.scriptNamespace): self._dyn_dispid_to_name_[self._getdispid_(name, 0)] = name def _getmembername_(self, dispid): try: return str(self._dyn_dispid_to_name_[dispid]) except KeyError: raise COMException(scode=winerror.DISP_E_UNKNOWNNAME, desc="Name not found") def _getdispid_(self, name, fdex): try: func = getattr(self._obj_.scriptNamespace, str(name)) except AttributeError: raise COMException(scode=winerror.DISP_E_MEMBERNOTFOUND) # if not _is_callable(func): return win32com.server.policy.DynamicPolicy._getdispid_(self, name, fdex) def _wrap_nodebug(obj): return win32com.server.util.wrap(obj, usePolicy=StrictDynamicPolicy)
null
175,104
import types import pythoncom import win32com.server.policy import win32com.server.util import winerror from win32com.axscript import axscript from win32com.client import Dispatch from win32com.server.exception import COMException class ScriptDispatch: _public_methods_ = [] def __init__(self, engine, scriptNamespace): self.engine = engine self.scriptNamespace = scriptNamespace def _dynamic_(self, name, lcid, wFlags, args): # Ensure any newly added items are available. self.engine.RegisterNewNamedItems() self.engine.ProcessNewNamedItemsConnections() if wFlags & pythoncom.INVOKE_FUNC: # attempt to call a function try: func = getattr(self.scriptNamespace, name) if not _is_callable(func): raise AttributeError(name) # Not a function. realArgs = [] for arg in args: if type(arg) == PyIDispatchType: realArgs.append(Dispatch(arg)) else: realArgs.append(arg) # xxx - todo - work out what code block to pass??? return self.engine.ApplyInScriptedSection(None, func, tuple(realArgs)) except AttributeError: if not wFlags & pythoncom.DISPATCH_PROPERTYGET: raise COMException(scode=winerror.DISP_E_MEMBERNOTFOUND) if wFlags & pythoncom.DISPATCH_PROPERTYGET: # attempt to get a property try: ret = getattr(self.scriptNamespace, name) if _is_callable(ret): raise AttributeError(name) # Not a property. except AttributeError: raise COMException(scode=winerror.DISP_E_MEMBERNOTFOUND) except COMException as instance: raise except: ret = self.engine.HandleException() return ret raise COMException(scode=winerror.DISP_E_MEMBERNOTFOUND) def MakeScriptDispatch(engine, namespace): return _wrap(ScriptDispatch(engine, namespace))
null
175,105
import os import sys import pythoncom import win32api import win32com.client.connect import win32com.server.util import winerror from win32com.axdebug import adb, axdebug, contexts, documents, gateways, stackframe from win32com.axdebug.codecontainer import SourceCodeContainer from win32com.axdebug.util import _wrap, _wrap_remove from win32com.client.util import Enumerator from win32com.server.exception import COMException from win32com.util import IIDToInterfaceName from .framework import trace The provided code snippet includes necessary dependencies for implementing the `trace` function. Write a Python function `def trace(*args)` to solve the following problem: A function used instead of "print" for debugging output. Here is the function: def trace(*args): """A function used instead of "print" for debugging output.""" if not debuggingTrace: return print(win32api.GetCurrentThreadId(), end=" ") for arg in args: print(arg, end=" ") print()
A function used instead of "print" for debugging output.
175,106
import re import pythoncom import win32api import win32com import win32com.client.dynamic import win32com.server.register import winerror from win32com.axscript import axscript from win32com.axscript.client import framework, scriptdispatch from win32com.axscript.client.framework import ( SCRIPTTEXT_FORCEEXECUTION, SCRIPTTEXT_ISEXPRESSION, SCRIPTTEXT_ISPERSISTENT, Exception, RaiseAssert, trace, ) debugging_attr = 0 def debug_attr_print(*args): if debugging_attr: trace(*args)
null
175,107
import re import pythoncom import win32api import win32com import win32com.client.dynamic import win32com.server.register import winerror from win32com.axscript import axscript from win32com.axscript.client import framework, scriptdispatch from win32com.axscript.client.framework import ( SCRIPTTEXT_FORCEEXECUTION, SCRIPTTEXT_ISEXPRESSION, SCRIPTTEXT_ISPERSISTENT, Exception, RaiseAssert, trace, ) def ExpandTabs(text): return re.sub("\t", " ", text)
null
175,108
import re import pythoncom import win32api import win32com import win32com.client.dynamic import win32com.server.register import winerror from win32com.axscript import axscript from win32com.axscript.client import framework, scriptdispatch from win32com.axscript.client.framework import ( SCRIPTTEXT_FORCEEXECUTION, SCRIPTTEXT_ISEXPRESSION, SCRIPTTEXT_ISPERSISTENT, Exception, RaiseAssert, trace, ) def AddCR(text): return re.sub("\n", "\r\n", text)
null
175,109
import re import pythoncom import win32api import win32com import win32com.client.dynamic import win32com.server.register import winerror from win32com.axscript import axscript from win32com.axscript.client import framework, scriptdispatch from win32com.axscript.client.framework import ( SCRIPTTEXT_FORCEEXECUTION, SCRIPTTEXT_ISEXPRESSION, SCRIPTTEXT_ISPERSISTENT, Exception, RaiseAssert, trace, ) class PyScript(framework.COMScript): # Setup the auto-registration stuff... _reg_verprogid_ = "Python.AXScript.2" _reg_progid_ = "Python" # _reg_policy_spec_ = default _reg_catids_ = [axscript.CATID_ActiveScript, axscript.CATID_ActiveScriptParse] _reg_desc_ = "Python ActiveX Scripting Engine" _reg_clsid_ = PyScript_CLSID _reg_class_spec_ = "win32com.axscript.client.pyscript.PyScript" _reg_remove_keys_ = [(".pys",), ("pysFile",)] _reg_threading_ = "both" def __init__(self): framework.COMScript.__init__(self) self.globalNameSpaceModule = None self.codeBlocks = [] self.scriptDispatch = None def InitNew(self): framework.COMScript.InitNew(self) import imp self.scriptDispatch = None self.globalNameSpaceModule = imp.new_module("__ax_main__") self.globalNameSpaceModule.__dict__["ax"] = AXScriptAttribute(self) self.codeBlocks = [] self.persistedCodeBlocks = [] self.mapKnownCOMTypes = {} # Map of known CLSID to typereprs self.codeBlockCounter = 0 def Stop(self): # Flag every pending script as already done for b in self.codeBlocks: b.beenExecuted = 1 return framework.COMScript.Stop(self) def Reset(self): # Reset all code-blocks that are persistent, and discard the rest oldCodeBlocks = self.codeBlocks[:] self.codeBlocks = [] for b in oldCodeBlocks: if b.flags & SCRIPTTEXT_ISPERSISTENT: b.beenExecuted = 0 self.codeBlocks.append(b) return framework.COMScript.Reset(self) def _GetNextCodeBlockNumber(self): self.codeBlockCounter = self.codeBlockCounter + 1 return self.codeBlockCounter def RegisterNamedItem(self, item): wasReg = item.isRegistered framework.COMScript.RegisterNamedItem(self, item) if not wasReg: # Insert into our namespace. # Add every item by name if item.IsVisible(): self.globalNameSpaceModule.__dict__[item.name] = item.attributeObject if item.IsGlobal(): # Global items means sub-items are also added... for subitem in item.subItems.values(): self.globalNameSpaceModule.__dict__[ subitem.name ] = subitem.attributeObject # Also add all methods for name, entry in item.dispatchContainer._olerepr_.mapFuncs.items(): if not entry.hidden: self.globalNameSpaceModule.__dict__[name] = getattr( item.dispatchContainer, name ) def DoExecutePendingScripts(self): try: globs = self.globalNameSpaceModule.__dict__ for codeBlock in self.codeBlocks: if not codeBlock.beenExecuted: if self.CompileInScriptedSection(codeBlock, "exec"): self.ExecInScriptedSection(codeBlock, globs) finally: pass def DoRun(self): pass def Close(self): self.ResetNamespace() self.globalNameSpaceModule = None self.codeBlocks = [] self.scriptDispatch = None framework.COMScript.Close(self) def GetScriptDispatch(self, name): # trace("GetScriptDispatch with", name) # if name is not None: return None if self.scriptDispatch is None: self.scriptDispatch = scriptdispatch.MakeScriptDispatch( self, self.globalNameSpaceModule ) return self.scriptDispatch def MakeEventMethodName(self, subItemName, eventName): return ( subItemName[0].upper() + subItemName[1:] + "_" + eventName[0].upper() + eventName[1:] ) def DoAddScriptlet( self, defaultName, code, itemName, subItemName, eventName, delimiter, sourceContextCookie, startLineNumber, ): # Just store the code away - compile when called. (JIT :-) item = self.GetNamedItem(itemName) if ( itemName == subItemName ): # Explicit handlers - eg <SCRIPT LANGUAGE="Python" for="TestForm" Event="onSubmit"> subItem = item else: subItem = item.GetCreateSubItem(item, subItemName, None, None) funcName = self.MakeEventMethodName(subItemName, eventName) codeBlock = AXScriptCodeBlock( "Script Event %s" % funcName, code, sourceContextCookie, startLineNumber, 0 ) self._AddScriptCodeBlock(codeBlock) subItem.scriptlets[funcName] = codeBlock def DoProcessScriptItemEvent(self, item, event, lcid, wFlags, args): # trace("ScriptItemEvent", self, item, event, event.name, lcid, wFlags, args) funcName = self.MakeEventMethodName(item.name, event.name) codeBlock = function = None try: function = item.scriptlets[funcName] if type(function) == type(self): # ie, is a CodeBlock instance codeBlock = function function = None except KeyError: pass if codeBlock is not None: realCode = "def %s():\n" % funcName for line in framework.RemoveCR(codeBlock.codeText).split("\n"): realCode = realCode + "\t" + line + "\n" realCode = realCode + "\n" if not self.CompileInScriptedSection(codeBlock, "exec", realCode): return dict = {} self.ExecInScriptedSection( codeBlock, self.globalNameSpaceModule.__dict__, dict ) function = dict[funcName] # cache back in scriptlets as a function. item.scriptlets[funcName] = function if function is None: # still no function - see if in the global namespace. try: function = self.globalNameSpaceModule.__dict__[funcName] except KeyError: # Not there _exactly_ - do case ins search. funcNameLook = funcName.lower() for attr in self.globalNameSpaceModule.__dict__.keys(): if funcNameLook == attr.lower(): function = self.globalNameSpaceModule.__dict__[attr] # cache back in scriptlets, to avoid this overhead next time item.scriptlets[funcName] = function if function is None: raise Exception(scode=winerror.DISP_E_MEMBERNOTFOUND) return self.ApplyInScriptedSection(codeBlock, function, args) def DoParseScriptText( self, code, sourceContextCookie, startLineNumber, bWantResult, flags ): code = framework.RemoveCR(code) + "\n" if flags & SCRIPTTEXT_ISEXPRESSION: name = "Script Expression" exec_type = "eval" else: name = "Script Block" exec_type = "exec" num = self._GetNextCodeBlockNumber() if num == 1: num = "" name = "%s %s" % (name, num) codeBlock = AXScriptCodeBlock( name, code, sourceContextCookie, startLineNumber, flags ) self._AddScriptCodeBlock(codeBlock) globs = self.globalNameSpaceModule.__dict__ if bWantResult: # always immediate. if self.CompileInScriptedSection(codeBlock, exec_type): if flags & SCRIPTTEXT_ISEXPRESSION: return self.EvalInScriptedSection(codeBlock, globs) else: return self.ExecInScriptedSection(codeBlock, globs) # else compile failed, but user chose to keep running... else: if flags & SCRIPTTEXT_FORCEEXECUTION: if self.CompileInScriptedSection(codeBlock, exec_type): self.ExecInScriptedSection(codeBlock, globs) else: self.codeBlocks.append(codeBlock) def GetNamedItemClass(self): return ScriptItem def ResetNamespace(self): if self.globalNameSpaceModule is not None: try: self.globalNameSpaceModule.ax._Reset_() except AttributeError: pass # ??? globalNameSpaceModule = None def DllRegisterServer(): klass = PyScript win32com.server.register._set_subkeys( klass._reg_progid_ + "\\OLEScript", {} ) # Just a CreateKey # Basic Registration for wsh. win32com.server.register._set_string(".pys", "pysFile") win32com.server.register._set_string("pysFile\\ScriptEngine", klass._reg_progid_) guid_wsh_shellex = "{60254CA5-953B-11CF-8C96-00AA00B8708C}" win32com.server.register._set_string( "pysFile\\ShellEx\\DropHandler", guid_wsh_shellex ) win32com.server.register._set_string( "pysFile\\ShellEx\\PropertySheetHandlers\\WSHProps", guid_wsh_shellex ) def Register(klass=PyScript): ret = win32com.server.register.UseCommandLine( klass, finalize_register=DllRegisterServer ) return ret
null
175,110
import re import sys import traceback import pythoncom import win32com.server.exception import win32com.server.util import winerror from win32com.axscript import axscript def ExpandTabs(text): return re.sub("\t", " ", text) def AddCR(text): return re.sub("\n", "\r\n", text) The provided code snippet includes necessary dependencies for implementing the `FormatForAX` function. Write a Python function `def FormatForAX(text)` to solve the following problem: Format a string suitable for an AX Host Here is the function: def FormatForAX(text): """Format a string suitable for an AX Host""" # Replace all " with ', so it works OK in HTML (ie, ASP) return ExpandTabs(AddCR(text))
Format a string suitable for an AX Host
175,111
import re import sys import traceback import pythoncom import win32com.server.exception import win32com.server.util import winerror from win32com.axscript import axscript class IActiveScriptError: """An implementation of IActiveScriptError The ActiveX Scripting host calls this client whenever we report an exception to it. This interface provides the exception details for the host to report to the user. """ _com_interfaces_ = [axscript.IID_IActiveScriptError] _public_methods_ = ["GetSourceLineText", "GetSourcePosition", "GetExceptionInfo"] def _query_interface_(self, iid): print("IActiveScriptError QI - unknown IID", iid) return 0 def _SetExceptionInfo(self, exc): self.exception = exc def GetSourceLineText(self): return self.exception.linetext def GetSourcePosition(self): ctx = self.exception.sourceContext # Zero based in the debugger (but our columns are too!) return ( ctx, self.exception.lineno + self.exception.startLineNo - 1, self.exception.colno, ) def GetExceptionInfo(self): return self.exception The provided code snippet includes necessary dependencies for implementing the `ProcessAXScriptException` function. Write a Python function `def ProcessAXScriptException(scriptingSite, debugManager, exceptionInstance)` to solve the following problem: General function to handle any exception in AX code This function creates an instance of our IActiveScriptError interface, and gives it to the host, along with out exception class. The host will likely call back on the IActiveScriptError interface to get the source text and other information not normally in COM exceptions. Here is the function: def ProcessAXScriptException(scriptingSite, debugManager, exceptionInstance): """General function to handle any exception in AX code This function creates an instance of our IActiveScriptError interface, and gives it to the host, along with out exception class. The host will likely call back on the IActiveScriptError interface to get the source text and other information not normally in COM exceptions. """ # traceback.print_exc() instance = IActiveScriptError() instance._SetExceptionInfo(exceptionInstance) gateway = win32com.server.util.wrap(instance, axscript.IID_IActiveScriptError) if debugManager: fCallOnError = debugManager.HandleRuntimeError() if not fCallOnError: return None try: result = scriptingSite.OnScriptError(gateway) except pythoncom.com_error as details: print("**OnScriptError failed:", details) print("Exception description:'%s'" % (repr(exceptionInstance.description))) print("Exception text:'%s'" % (repr(exceptionInstance.linetext))) result = winerror.S_FALSE if result == winerror.S_OK: # If the above returns NOERROR, it is assumed the error has been # correctly registered and the value SCRIPT_E_REPORTED is returned. ret = win32com.server.exception.COMException(scode=axscript.SCRIPT_E_REPORTED) return ret else: # The error is taken to be unreported and is propagated up the call stack # via the IDispatch::Invoke's EXCEPINFO parameter (hr returned is DISP_E_EXCEPTION. return exceptionInstance
General function to handle any exception in AX code This function creates an instance of our IActiveScriptError interface, and gives it to the host, along with out exception class. The host will likely call back on the IActiveScriptError interface to get the source text and other information not normally in COM exceptions.
175,112
import os import sys import win32api import win32com.server.util import winerror from win32com.server.exception import Exception if debugging: _wrap = _wrap_debug else: _wrap = _wrap_nodebug import win32com.server.policy def trace(*args): if not debugging: return print(str(win32api.GetCurrentThreadId()) + ":", end=" ") for arg in args: print(arg, end=" ") print()
null
175,113
import os import sys import win32api import win32com.server.util import winerror from win32com.server.exception import Exception import win32com.server.policy def _wrap_nodebug(object, iid): return win32com.server.util.wrap(object, iid)
null
175,114
import os import sys import win32api import win32com.server.util import winerror from win32com.server.exception import Exception import win32com.server.policy def _wrap_debug(object, iid): import win32com.server.policy dispatcher = win32com.server.policy.DispatcherWin32trace return win32com.server.util.wrap(object, iid, useDispatcher=dispatcher)
null
175,115
import os import sys import win32api import win32com.server.util import winerror from win32com.server.exception import Exception import win32com.server.policy def _wrap_remove(object, iid=None): # Old - no longer used or necessary! return
null
175,116
import os import sys import win32api import win32com.server.util import winerror from win32com.server.exception import Exception all_wrapped = {} import win32com.server.policy def unwrap(ob): """Unwraps an interface. Given an interface which wraps up a Gateway, return the object behind the gateway. """ ob = pythoncom.UnwrapObject(ob) # see if the object is a dispatcher if hasattr(ob, "policy"): ob = ob.policy return ob._obj_ def _dump_wrapped(): from win32com.server.util import unwrap print("Wrapped items:") for key, items in all_wrapped.items(): print(key, end=" ") try: ob = unwrap(key) print(ob, sys.getrefcount(ob)) except: print("<error>")
null
175,117
import os import sys import win32api import win32com.server.util import winerror from win32com.server.exception import Exception import win32com.server.policy Exception = COMException def RaiseNotImpl(who=None): if who is not None: print("********* Function %s Raising E_NOTIMPL ************" % (who)) # Print a sort-of "traceback", dumping all the frames leading to here. try: 1 / 0 except: frame = sys.exc_info()[2].tb_frame while frame: print("File: %s, Line: %d" % (frame.f_code.co_filename, frame.f_lineno)) frame = frame.f_back # and raise the exception for COM raise Exception(scode=winerror.E_NOTIMPL)
null
175,118
import os import string import sys import pythoncom import win32api from win32com.axdebug import ( adb, axdebug, codecontainer, contexts, documents, expressions, gateways, ) from win32com.axdebug.util import _wrap, _wrap_remove, trace from win32com.axscript import axscript def BuildModule(module, built_nodes, rootNode, create_node_fn, create_node_args): def RefreshAllModules(builtItems, rootNode, create_node, create_node_args): for module in list(sys.modules.values()): BuildModule(module, builtItems, rootNode, create_node, create_node_args)
null
175,119
import os import string import sys import pythoncom import win32api from win32com.axdebug import ( adb, axdebug, codecontainer, contexts, documents, expressions, gateways, ) from win32com.axdebug.util import _wrap, _wrap_remove, trace from win32com.axscript import axscript def _GetCurrentDebugger(): global currentDebugger if currentDebugger is None: currentDebugger = AXDebugger() return currentDebugger def Break(): _GetCurrentDebugger().Break()
null
175,120
import os import string import sys import pythoncom import win32api from win32com.axdebug import ( adb, axdebug, codecontainer, contexts, documents, expressions, gateways, ) from win32com.axdebug.util import _wrap, _wrap_remove, trace from win32com.axscript import axscript def dosomethingelse(): a = 2 b = "Hi there" def dosomething(): a = 1 b = 2 dosomethingelse()
null
175,121
import pythoncom import win32api from win32com.server.exception import Exception from win32com.server.util import unwrap from . import axdebug, codecontainer, contexts, gateways from .util import RaiseNotImpl, _wrap, _wrap_remove, trace def GetGoodFileName(fname): if fname[0] != "<": return win32api.GetFullPathName(fname) return fname
null
175,122
import _thread import bdb import os import sys import traceback import pythoncom import win32api import win32com.client.connect from win32com.axdebug.util import _wrap, _wrap_remove, trace from win32com.server.util import unwrap from . import axdebug, gateways, stackframe def fnull(*args): pass
null
175,123
import _thread import bdb import os import sys import traceback import pythoncom import win32api import win32com.client.connect from win32com.axdebug.util import _wrap, _wrap_remove, trace from win32com.server.util import unwrap from . import axdebug, gateways, stackframe def _dumpf(frame): if frame is None: return "<None>" else: addn = "(with trace!)" if frame.f_trace is None: addn = " **No Trace Set **" return "Frame at %d, file %s, line: %d%s" % ( id(frame), frame.f_code.co_filename, frame.f_lineno, addn, )
null
175,124
import _thread import bdb import os import sys import traceback import pythoncom import win32api import win32com.client.connect from win32com.axdebug.util import _wrap, _wrap_remove, trace from win32com.server.util import unwrap from . import axdebug, gateways, stackframe g_adb = None def OnSetBreakPoint(codeContext, breakPointState, lineNo): try: fileName = codeContext.codeContainer.GetFileName() # inject the code into linecache. import linecache linecache.cache[fileName] = 0, 0, codeContext.codeContainer.GetText(), fileName g_adb._OnSetBreakPoint(fileName, codeContext, breakPointState, lineNo + 1) except: traceback.print_exc()
null
175,125
import _thread import bdb import os import sys import traceback import pythoncom import win32api import win32com.client.connect from win32com.axdebug.util import _wrap, _wrap_remove, trace from win32com.server.util import unwrap from . import axdebug, gateways, stackframe g_adb = None class Adb(bdb.Bdb, gateways.RemoteDebugApplicationEvents): def __init__(self): def canonic(self, fname): def reset(self): def __xxxxx__set_break(self, filename, lineno, cond=None): def stop_here(self, frame): def break_here(self, frame): def break_anywhere(self, frame): def dispatch_return(self, frame, arg): def dispatch_line(self, frame): def dispatch_call(self, frame, arg): def trace_dispatch(self, frame, event, arg): def user_line(self, frame): def user_return(self, frame, return_value): def user_exception(self, frame, exc_info): def _HandleBreakPoint(self, frame, tb, reason): def set_trace(self): def CloseApp(self): def AttachApp(self, debugApplication, codeContainerProvider): def ResetAXDebugging(self): def SetupAXDebugging(self, baseFrame=None, userFrame=None): def OnConnectDebugger(self, appDebugger): def OnDisconnectDebugger(self): def OnSetName(self, name): def OnDebugOutput(self, string): def OnClose(self): def OnEnterBreakPoint(self, rdat): def OnLeaveBreakPoint(self, rdat): def OnCreateThread(self, rdat): def OnDestroyThread(self, rdat): def OnBreakFlagChange(self, abf, rdat): def _BreakFlagsChanged(self): def _OnSetBreakPoint(self, key, codeContext, bps, lineNo): def Debugger(): global g_adb if g_adb is None: g_adb = Adb() return g_adb
null
175,126
import io import string import sys import traceback from pprint import pprint import winerror from win32com.server.exception import COMException from . import axdebug, gateways from .util import RaiseNotImpl, _wrap, _wrap_remove def GetPropertyInfo( obname, obvalue, dwFieldSpec, nRadix, hresult=0, dictionary=None, stackFrame=None ): # returns a tuple name = typ = value = fullname = attrib = dbgprop = None if dwFieldSpec & axdebug.DBGPROP_INFO_VALUE: value = MakeNiceString(obvalue) if dwFieldSpec & axdebug.DBGPROP_INFO_NAME: name = obname if dwFieldSpec & axdebug.DBGPROP_INFO_TYPE: if hresult: typ = "Error" else: try: typ = type(obvalue).__name__ except AttributeError: typ = str(type(obvalue)) if dwFieldSpec & axdebug.DBGPROP_INFO_FULLNAME: fullname = obname if dwFieldSpec & axdebug.DBGPROP_INFO_ATTRIBUTES: if hasattr(obvalue, "has_key") or hasattr( obvalue, "__dict__" ): # If it is a dict or object attrib = axdebug.DBGPROP_ATTRIB_VALUE_IS_EXPANDABLE else: attrib = 0 if dwFieldSpec & axdebug.DBGPROP_INFO_DEBUGPROP: dbgprop = _wrap( DebugProperty(name, obvalue, None, hresult, dictionary, stackFrame), axdebug.IID_IDebugProperty, ) return name, typ, value, fullname, attrib, dbgprop from win32com.server.util import ListEnumeratorGateway class EnumDebugPropertyInfo(ListEnumeratorGateway): """A class to expose a Python sequence as an EnumDebugCodeContexts Create an instance of this class passing a sequence (list, tuple, or any sequence protocol supporting object) and it will automatically support the EnumDebugCodeContexts interface for the object. """ _public_methods_ = ListEnumeratorGateway._public_methods_ + ["GetCount"] _com_interfaces_ = [axdebug.IID_IEnumDebugPropertyInfo] def GetCount(self): return len(self._list_) def _wrap(self, ob): return ob def MakeEnumDebugProperty(object, dwFieldSpec, nRadix, iid, stackFrame=None): name_vals = [] if hasattr(object, "items") and hasattr(object, "keys"): # If it is a dict. name_vals = iter(object.items()) dictionary = object elif hasattr(object, "__dict__"): # object with dictionary, module name_vals = iter(object.__dict__.items()) dictionary = object.__dict__ infos = [] for name, val in name_vals: infos.append( GetPropertyInfo(name, val, dwFieldSpec, nRadix, 0, dictionary, stackFrame) ) return _wrap(EnumDebugPropertyInfo(infos), axdebug.IID_IEnumDebugPropertyInfo)
null
175,127
import traceback import pythoncom from win32com.axdebug import axdebug from win32com.client.util import Enumerator def DumpDebugApplicationNode(node, level=0): # Recursive dump of a DebugApplicationNode spacer = " " * level for desc, attr in [ ("Node Name", axdebug.DOCUMENTNAMETYPE_APPNODE), ("Title", axdebug.DOCUMENTNAMETYPE_TITLE), ("Filename", axdebug.DOCUMENTNAMETYPE_FILE_TAIL), ("URL", axdebug.DOCUMENTNAMETYPE_URL), ]: try: info = node.GetName(attr) except pythoncom.com_error: info = "<N/A>" print("%s%s: %s" % (spacer, desc, info)) try: doc = node.GetDocument() except pythoncom.com_error: doc = None if doc: doctext = doc.QueryInterface(axdebug.IID_IDebugDocumentText) numLines, numChars = doctext.GetSize() # text, attr = doctext.GetText(0, 20, 1) text, attr = doctext.GetText(0, numChars, 1) print( "%sText is %s, %d bytes long" % (spacer, repr(text[:40] + "..."), len(text)) ) else: print("%s%s" % (spacer, "<No document available>")) for child in Enumerator(node.EnumChildren()): DumpDebugApplicationNode(child, level + 1) class Enumerator: """A class that provides indexed access into an Enumerator By wrapping a PyIEnum* object in this class, you can perform natural looping and indexing into the Enumerator. Looping is very efficient, but it should be noted that although random access is supported, the underlying object is still an enumerator, so this will force many reset-and-seek operations to find the requested index. """ def __init__(self, enum): self._oleobj_ = enum # a PyIEnumVARIANT self.index = -1 def __getitem__(self, index): return self.__GetIndex(index) def __call__(self, index): return self.__GetIndex(index) def __GetIndex(self, index): if type(index) != type(0): raise TypeError("Only integer indexes are supported for enumerators") # NOTE # In this context, self.index is users purely as a flag to say # "am I still in sequence". The user may call Next() or Reset() if they # so choose, in which case self.index will not be correct (although we # still want to stay in sequence) if index != self.index + 1: # Index requested out of sequence. self._oleobj_.Reset() if index: self._oleobj_.Skip( index ) # if asked for item 1, must skip 1, Python always zero based. self.index = index result = self._oleobj_.Next(1) if len(result): return self._make_retval_(result[0]) raise IndexError("list index out of range") def Next(self, count=1): ret = self._oleobj_.Next(count) realRets = [] for r in ret: realRets.append(self._make_retval_(r)) return tuple(realRets) # Convert back to tuple. def Reset(self): return self._oleobj_.Reset() def Clone(self): return self.__class__(self._oleobj_.Clone(), self.resultCLSID) def _make_retval_(self, result): return result def dumpall(): dm = pythoncom.CoCreateInstance( axdebug.CLSID_MachineDebugManager, None, pythoncom.CLSCTX_ALL, axdebug.IID_IMachineDebugManager, ) e = Enumerator(dm.EnumApplications()) for app in e: print("Application: %s" % app.GetName()) node = ( app.GetRootNode() ) # of type PyIDebugApplicationNode->PyIDebugDocumentProvider->PyIDebugDocumentInfo DumpDebugApplicationNode(node)
null
175,128
def _HRESULT_TYPEDEF_(_sc): return _sc
null
175,129
import pythoncom import pywintypes import win32security from win32com.adsi import adsi, adsicon from win32com.adsi.adsicon import * def _guid_from_buffer(b): return pywintypes.IID(b, True)
null
175,130
import pythoncom import pywintypes import win32security from win32com.adsi import adsi, adsicon from win32com.adsi.adsicon import * def _sid_from_buffer(b): return str(pywintypes.SID(b))
null
175,131
import pythoncom import pywintypes import win32security from win32com.adsi import adsi, adsicon from win32com.adsi.adsicon import * options = None def log(level, msg, *args): if options.verbose >= level: print("log:", msg % args) def getGC(): cont = adsi.ADsOpenObject( "GC:", options.user, options.password, 0, adsi.IID_IADsContainer ) enum = adsi.ADsBuildEnumerator(cont) # Only 1 child of the global catalog. for e in enum: gc = e.QueryInterface(adsi.IID_IDirectorySearch) return gc return None def print_attribute(col_data): prop_name, prop_type, values = col_data if values is not None: log(2, "property '%s' has type '%s'", prop_name, getADsTypeName(prop_type)) value = [converters.get(prop_name, _null_converter)(v[0]) for v in values] if len(value) == 1: value = value[0] print(" %s=%r" % (prop_name, value)) else: print(" %s is None" % (prop_name,)) def search(): gc = getGC() if gc is None: log(0, "Can't find the global catalog") return prefs = [(ADS_SEARCHPREF_SEARCH_SCOPE, (ADS_SCOPE_SUBTREE,))] hr, statuses = gc.SetSearchPreference(prefs) log(3, "SetSearchPreference returned %d/%r", hr, statuses) if options.attributes: attributes = options.attributes.split(",") else: attributes = None h = gc.ExecuteSearch(options.filter, attributes) hr = gc.GetNextRow(h) while hr != S_ADS_NOMORE_ROWS: print("-- new row --") if attributes is None: # Loop over all columns returned while 1: col_name = gc.GetNextColumnName(h) if col_name is None: break data = gc.GetColumn(h, col_name) print_attribute(data) else: # loop over attributes specified. for a in attributes: try: data = gc.GetColumn(h, a) print_attribute(data) except adsi.error as details: if details[0] != E_ADS_COLUMN_NOT_SET: raise print_attribute((a, None, None)) hr = gc.GetNextRow(h) gc.CloseSearchHandle(h)
null
175,132
import optparse import textwrap import traceback import ntsecuritycon as dscon import win32api import win32con import win32security import winerror from win32com.adsi import adsi from win32com.adsi.adsicon import * from win32com.client import Dispatch g_createdSCP = None import logging def ScpCreate( service_binding_info, service_class_name, # Service class string to store in SCP. account_name=None, # Logon account that needs access to SCP. container_name=None, keywords=None, object_class="serviceConnectionPoint", dns_name_type="A", dn=None, dns_name=None, ): container_name = container_name or service_class_name if not dns_name: # Get the DNS name of the local computer dns_name = win32api.GetComputerNameEx(win32con.ComputerNameDnsFullyQualified) # Get the distinguished name of the computer object for the local computer if dn is None: dn = win32api.GetComputerObjectName(win32con.NameFullyQualifiedDN) # Compose the ADSpath and bind to the computer object for the local computer comp = adsi.ADsGetObject("LDAP://" + dn, adsi.IID_IDirectoryObject) # Publish the SCP as a child of the computer object keywords = keywords or [] # Fill in the attribute values to be stored in the SCP. attrs = [ ("cn", ADS_ATTR_UPDATE, ADSTYPE_CASE_IGNORE_STRING, (container_name,)), ("objectClass", ADS_ATTR_UPDATE, ADSTYPE_CASE_IGNORE_STRING, (object_class,)), ("keywords", ADS_ATTR_UPDATE, ADSTYPE_CASE_IGNORE_STRING, keywords), ("serviceDnsName", ADS_ATTR_UPDATE, ADSTYPE_CASE_IGNORE_STRING, (dns_name,)), ( "serviceDnsNameType", ADS_ATTR_UPDATE, ADSTYPE_CASE_IGNORE_STRING, (dns_name_type,), ), ( "serviceClassName", ADS_ATTR_UPDATE, ADSTYPE_CASE_IGNORE_STRING, (service_class_name,), ), ( "serviceBindingInformation", ADS_ATTR_UPDATE, ADSTYPE_CASE_IGNORE_STRING, (service_binding_info,), ), ] new = comp.CreateDSObject("cn=" + container_name, attrs) logger.info("New connection point is at %s", container_name) # Wrap in a usable IDispatch object. new = Dispatch(new) # And allow access to the SCP for the specified account name AllowAccessToScpProperties(account_name, new) return new def _get_option(po, opt_name, default=_NoDefault): parser, options = po ret = getattr(options, opt_name, default) if not ret and default is _NoDefault: parser.error("The '%s' option must be specified for this operation" % opt_name) if not ret: ret = default return ret The provided code snippet includes necessary dependencies for implementing the `do_ScpCreate` function. Write a Python function `def do_ScpCreate(po)` to solve the following problem: Create a Service Connection Point Here is the function: def do_ScpCreate(po): """Create a Service Connection Point""" global g_createdSCP scp = ScpCreate( _get_option(po, "binding_string"), _get_option(po, "service_class"), _get_option(po, "account_name_sam", None), keywords=_get_option(po, "keywords", None), ) g_createdSCP = scp return scp.distinguishedName
Create a Service Connection Point
175,133
import optparse import textwrap import traceback import ntsecuritycon as dscon import win32api import win32con import win32security import winerror from win32com.adsi import adsi from win32com.adsi.adsicon import * from win32com.client import Dispatch import logging def ScpDelete(container_name, dn=None): if dn is None: dn = win32api.GetComputerObjectName(win32con.NameFullyQualifiedDN) logger.debug("Removing connection point '%s' from %s", container_name, dn) # Compose the ADSpath and bind to the computer object for the local computer comp = adsi.ADsGetObject("LDAP://" + dn, adsi.IID_IDirectoryObject) comp.DeleteDSObject("cn=" + container_name) logger.info("Deleted service connection point '%s'", container_name) def log(level, msg, *args): if verbose >= level: print(msg % args) def _get_option(po, opt_name, default=_NoDefault): parser, options = po ret = getattr(options, opt_name, default) if not ret and default is _NoDefault: parser.error("The '%s' option must be specified for this operation" % opt_name) if not ret: ret = default return ret The provided code snippet includes necessary dependencies for implementing the `do_ScpDelete` function. Write a Python function `def do_ScpDelete(po)` to solve the following problem: Delete a Service Connection Point Here is the function: def do_ScpDelete(po): """Delete a Service Connection Point""" sc = _get_option(po, "service_class") try: ScpDelete(sc) except adsi.error as details: if details[0] != winerror.ERROR_DS_OBJ_NOT_FOUND: raise log(2, "ScpDelete ignoring ERROR_DS_OBJ_NOT_FOUND for service-class '%s'", sc) return sc
Delete a Service Connection Point
175,134
import optparse import textwrap import traceback import ntsecuritycon as dscon import win32api import win32con import win32security import winerror from win32com.adsi import adsi from win32com.adsi.adsicon import * from win32com.client import Dispatch g_createdSCP = None g_createdSPNs = [] g_createdSPNLast = None import logging def log(level, msg, *args): if verbose >= level: print(msg % args) def _get_option(po, opt_name, default=_NoDefault): parser, options = po ret = getattr(options, opt_name, default) if not ret and default is _NoDefault: parser.error("The '%s' option must be specified for this operation" % opt_name) if not ret: ret = default return ret def _option_error(po, why): parser = po[0] parser.error(why) The provided code snippet includes necessary dependencies for implementing the `do_SpnCreate` function. Write a Python function `def do_SpnCreate(po)` to solve the following problem: Create a Service Principal Name Here is the function: def do_SpnCreate(po): """Create a Service Principal Name""" # The 'service name' is the dn of our scp. if g_createdSCP is None: # Could accept an arg to avoid this? _option_error(po, "ScpCreate must have been specified before SpnCreate") # Create a Service Principal Name" spns = win32security.DsGetSpn( dscon.DS_SPN_SERVICE, _get_option(po, "service_class"), g_createdSCP.distinguishedName, _get_option(po, "port", 0), None, None, ) spn = spns[0] log(2, "Created SPN: %s", spn) global g_createdSPNLast g_createdSPNLast = spn g_createdSPNs.append(spn) return spn
Create a Service Principal Name
175,135
import optparse import textwrap import traceback import ntsecuritycon as dscon import win32api import win32con import win32security import winerror from win32com.adsi import adsi from win32com.adsi.adsicon import * from win32com.client import Dispatch g_createdSPNLast = None import logging def SpnRegister( serviceAcctDN, # DN of the service's logon account spns, # List of SPNs to register operation, # Add, replace, or delete SPNs ): assert type(spns) not in [str, str] and hasattr(spns, "__iter__"), ( "spns must be a sequence of strings (got %r)" % spns ) # Bind to a domain controller. # Get the domain for the current user. samName = win32api.GetUserNameEx(win32api.NameSamCompatible) samName = samName.split("\\", 1)[0] if not serviceAcctDN: # Get the SAM account name of the computer object for the server. serviceAcctDN = win32api.GetComputerObjectName(win32con.NameFullyQualifiedDN) logger.debug("SpnRegister using DN '%s'", serviceAcctDN) # Get the name of a domain controller in that domain. info = win32security.DsGetDcName( domainName=samName, flags=dscon.DS_IS_FLAT_NAME | dscon.DS_RETURN_DNS_NAME | dscon.DS_DIRECTORY_SERVICE_REQUIRED, ) # Bind to the domain controller. handle = win32security.DsBind(info["DomainControllerName"]) # Write the SPNs to the service account or computer account. logger.debug("DsWriteAccountSpn with spns %s") win32security.DsWriteAccountSpn( handle, # handle to the directory operation, # Add or remove SPN from account's existing SPNs serviceAcctDN, # DN of service account or computer account spns, ) # names # Unbind the DS in any case (but Python would do it anyway) handle.Close() def _get_option(po, opt_name, default=_NoDefault): parser, options = po ret = getattr(options, opt_name, default) if not ret and default is _NoDefault: parser.error("The '%s' option must be specified for this operation" % opt_name) if not ret: ret = default return ret def _option_error(po, why): parser = po[0] parser.error(why) The provided code snippet includes necessary dependencies for implementing the `do_SpnRegister` function. Write a Python function `def do_SpnRegister(po)` to solve the following problem: Register a previously created Service Principal Name Here is the function: def do_SpnRegister(po): """Register a previously created Service Principal Name""" if not g_createdSPNLast: _option_error(po, "SpnCreate must appear before SpnRegister") SpnRegister( _get_option(po, "account_name_dn", None), (g_createdSPNLast,), dscon.DS_SPN_ADD_SPN_OP, ) return g_createdSPNLast
Register a previously created Service Principal Name
175,136
import optparse import textwrap import traceback import ntsecuritycon as dscon import win32api import win32con import win32security import winerror from win32com.adsi import adsi from win32com.adsi.adsicon import * from win32com.client import Dispatch g_createdSPNLast = None import logging def SpnRegister( serviceAcctDN, # DN of the service's logon account spns, # List of SPNs to register operation, # Add, replace, or delete SPNs ): assert type(spns) not in [str, str] and hasattr(spns, "__iter__"), ( "spns must be a sequence of strings (got %r)" % spns ) # Bind to a domain controller. # Get the domain for the current user. samName = win32api.GetUserNameEx(win32api.NameSamCompatible) samName = samName.split("\\", 1)[0] if not serviceAcctDN: # Get the SAM account name of the computer object for the server. serviceAcctDN = win32api.GetComputerObjectName(win32con.NameFullyQualifiedDN) logger.debug("SpnRegister using DN '%s'", serviceAcctDN) # Get the name of a domain controller in that domain. info = win32security.DsGetDcName( domainName=samName, flags=dscon.DS_IS_FLAT_NAME | dscon.DS_RETURN_DNS_NAME | dscon.DS_DIRECTORY_SERVICE_REQUIRED, ) # Bind to the domain controller. handle = win32security.DsBind(info["DomainControllerName"]) # Write the SPNs to the service account or computer account. logger.debug("DsWriteAccountSpn with spns %s") win32security.DsWriteAccountSpn( handle, # handle to the directory operation, # Add or remove SPN from account's existing SPNs serviceAcctDN, # DN of service account or computer account spns, ) # names # Unbind the DS in any case (but Python would do it anyway) handle.Close() def _get_option(po, opt_name, default=_NoDefault): parser, options = po ret = getattr(options, opt_name, default) if not ret and default is _NoDefault: parser.error("The '%s' option must be specified for this operation" % opt_name) if not ret: ret = default return ret def _option_error(po, why): parser = po[0] parser.error(why) The provided code snippet includes necessary dependencies for implementing the `do_SpnUnregister` function. Write a Python function `def do_SpnUnregister(po)` to solve the following problem: Unregister a previously created Service Principal Name Here is the function: def do_SpnUnregister(po): """Unregister a previously created Service Principal Name""" if not g_createdSPNLast: _option_error(po, "SpnCreate must appear before SpnUnregister") SpnRegister( _get_option(po, "account_name_dn", None), (g_createdSPNLast,), dscon.DS_SPN_DELETE_SPN_OP, ) return g_createdSPNLast
Unregister a previously created Service Principal Name
175,137
import optparse import textwrap import traceback import ntsecuritycon as dscon import win32api import win32con import win32security import winerror from win32com.adsi import adsi from win32com.adsi.adsicon import * from win32com.client import Dispatch import logging def UserChangePassword(username_dn, new_password): # set the password on the account. # Use the distinguished name to bind to the account object. accountPath = "LDAP://" + username_dn user = adsi.ADsGetObject(accountPath, adsi.IID_IADsUser) # Set the password on the account. user.SetPassword(new_password) def _get_option(po, opt_name, default=_NoDefault): parser, options = po ret = getattr(options, opt_name, default) if not ret and default is _NoDefault: parser.error("The '%s' option must be specified for this operation" % opt_name) if not ret: ret = default return ret The provided code snippet includes necessary dependencies for implementing the `do_UserChangePassword` function. Write a Python function `def do_UserChangePassword(po)` to solve the following problem: Change the password for a specified user Here is the function: def do_UserChangePassword(po): """Change the password for a specified user""" UserChangePassword(_get_option(po, "account_name_dn"), _get_option(po, "password")) return "Password changed OK"
Change the password for a specified user
175,138
import ast import collections import io import sys import token import tokenize from abc import ABCMeta from ast import Module, expr, AST from typing import Callable, Dict, Iterable, Iterator, List, Optional, Tuple, Union, cast, Any, TYPE_CHECKING from six import iteritems def token_repr(tok_type, string): # type: (int, Optional[str]) -> str """Returns a human-friendly representation of a token with the given type and string.""" # repr() prefixes unicode with 'u' on Python2 but not Python3; strip it out for consistency. return '%s:%s' % (token.tok_name[tok_type], repr(string).lstrip('u')) def match_token(token, tok_type, tok_str=None): # type: (Token, int, Optional[str]) -> bool """Returns true if token is of the given type and, if a string is given, has that string.""" return token.type == tok_type and (tok_str is None or token.string == tok_str) The provided code snippet includes necessary dependencies for implementing the `expect_token` function. Write a Python function `def expect_token(token, tok_type, tok_str=None)` to solve the following problem: Verifies that the given token is of the expected type. If tok_str is given, the token string is verified too. If the token doesn't match, raises an informative ValueError. Here is the function: def expect_token(token, tok_type, tok_str=None): # type: (Token, int, Optional[str]) -> None """ Verifies that the given token is of the expected type. If tok_str is given, the token string is verified too. If the token doesn't match, raises an informative ValueError. """ if not match_token(token, tok_type, tok_str): raise ValueError("Expected token %s, got %s on line %s col %s" % ( token_repr(tok_type, tok_str), str(token), token.start[0], token.start[1] + 1))
Verifies that the given token is of the expected type. If tok_str is given, the token string is verified too. If the token doesn't match, raises an informative ValueError.
175,139
import ast import collections import io import sys import token import tokenize from abc import ABCMeta from ast import Module, expr, AST from typing import Callable, Dict, Iterable, Iterator, List, Optional, Tuple, Union, cast, Any, TYPE_CHECKING from six import iteritems The provided code snippet includes necessary dependencies for implementing the `is_non_coding_token` function. Write a Python function `def is_non_coding_token(token_type)` to solve the following problem: These are considered non-coding tokens, as they don't affect the syntax tree. Here is the function: def is_non_coding_token(token_type): # type: (int) -> bool """ These are considered non-coding tokens, as they don't affect the syntax tree. """ return token_type in (token.NL, token.COMMENT, token.ENCODING)
These are considered non-coding tokens, as they don't affect the syntax tree.
175,140
import ast import collections import io import sys import token import tokenize from abc import ABCMeta from ast import Module, expr, AST from typing import Callable, Dict, Iterable, Iterator, List, Optional, Tuple, Union, cast, Any, TYPE_CHECKING from six import iteritems The provided code snippet includes necessary dependencies for implementing the `is_non_coding_token` function. Write a Python function `def is_non_coding_token(token_type)` to solve the following problem: These are considered non-coding tokens, as they don't affect the syntax tree. Here is the function: def is_non_coding_token(token_type): # type: (int) -> bool """ These are considered non-coding tokens, as they don't affect the syntax tree. """ return token_type >= token.N_TOKENS
These are considered non-coding tokens, as they don't affect the syntax tree.
175,141
import ast import collections import io import sys import token import tokenize from abc import ABCMeta from ast import Module, expr, AST from typing import Callable, Dict, Iterable, Iterator, List, Optional, Tuple, Union, cast, Any, TYPE_CHECKING from six import iteritems class Callable(BaseTypingInstance): def py__call__(self, arguments): """ def x() -> Callable[[Callable[..., _T]], _T]: ... """ # The 0th index are the arguments. try: param_values = self._generics_manager[0] result_values = self._generics_manager[1] except IndexError: debug.warning('Callable[...] defined without two arguments') return NO_VALUES else: from jedi.inference.gradual.annotation import infer_return_for_callable return infer_return_for_callable(arguments, param_values, result_values) def py__get__(self, instance, class_value): return ValueSet([self]) def cast(typ: Type[_T], val: Any) -> _T: ... def cast(typ: str, val: Any) -> Any: ... def cast(typ: object, val: Any) -> Any: ... The provided code snippet includes necessary dependencies for implementing the `generate_tokens` function. Write a Python function `def generate_tokens(text)` to solve the following problem: Generates standard library tokens for the given code. Here is the function: def generate_tokens(text): # type: (str) -> Iterator[TokenInfo] """ Generates standard library tokens for the given code. """ # tokenize.generate_tokens is technically an undocumented API for Python3, but allows us to use the same API as for # Python2. See http://stackoverflow.com/a/4952291/328565. # FIXME: Remove cast once https://github.com/python/typeshed/issues/7003 gets fixed return tokenize.generate_tokens(cast(Callable[[], str], io.StringIO(text).readline))
Generates standard library tokens for the given code.
175,142
import ast import collections import io import sys import token import tokenize from abc import ABCMeta from ast import Module, expr, AST from typing import Callable, Dict, Iterable, Iterator, List, Optional, Tuple, Union, cast, Any, TYPE_CHECKING from six import iteritems expr_class_names = ({n for n, c in iteritems(ast.__dict__) if isinstance(c, type) and issubclass(c, ast.expr)} | {'AssignName', 'DelName', 'Const', 'AssignAttr', 'DelAttr'}) The provided code snippet includes necessary dependencies for implementing the `is_expr` function. Write a Python function `def is_expr(node)` to solve the following problem: Returns whether node is an expression node. Here is the function: def is_expr(node): # type: (AstNode) -> bool """Returns whether node is an expression node.""" return node.__class__.__name__ in expr_class_names
Returns whether node is an expression node.
175,143
import ast import collections import io import sys import token import tokenize from abc import ABCMeta from ast import Module, expr, AST from typing import Callable, Dict, Iterable, Iterator, List, Optional, Tuple, Union, cast, Any, TYPE_CHECKING from six import iteritems stmt_class_names = {n for n, c in iteritems(ast.__dict__) if isinstance(c, type) and issubclass(c, ast.stmt)} The provided code snippet includes necessary dependencies for implementing the `is_stmt` function. Write a Python function `def is_stmt(node)` to solve the following problem: Returns whether node is a statement node. Here is the function: def is_stmt(node): # type: (AstNode) -> bool """Returns whether node is a statement node.""" return node.__class__.__name__ in stmt_class_names
Returns whether node is a statement node.
175,144
import ast import collections import io import sys import token import tokenize from abc import ABCMeta from ast import Module, expr, AST from typing import Callable, Dict, Iterable, Iterator, List, Optional, Tuple, Union, cast, Any, TYPE_CHECKING from six import iteritems The provided code snippet includes necessary dependencies for implementing the `is_module` function. Write a Python function `def is_module(node)` to solve the following problem: Returns whether node is a module node. Here is the function: def is_module(node): # type: (AstNode) -> bool """Returns whether node is a module node.""" return node.__class__.__name__ == 'Module'
Returns whether node is a module node.
175,145
import ast import collections import io import sys import token import tokenize from abc import ABCMeta from ast import Module, expr, AST from typing import Callable, Dict, Iterable, Iterator, List, Optional, Tuple, Union, cast, Any, TYPE_CHECKING from six import iteritems The provided code snippet includes necessary dependencies for implementing the `is_starred` function. Write a Python function `def is_starred(node)` to solve the following problem: Returns whether node is a starred expression node. Here is the function: def is_starred(node): # type: (AstNode) -> bool """Returns whether node is a starred expression node.""" return node.__class__.__name__ == 'Starred'
Returns whether node is a starred expression node.
175,146
import ast import collections import io import sys import token import tokenize from abc import ABCMeta from ast import Module, expr, AST from typing import Callable, Dict, Iterable, Iterator, List, Optional, Tuple, Union, cast, Any, TYPE_CHECKING from six import iteritems class Tuple(BaseTypingInstance): def _is_homogenous(self): # To specify a variable-length tuple of homogeneous type, Tuple[T, ...] # is used. return self._generics_manager.is_homogenous_tuple() def py__simple_getitem__(self, index): if self._is_homogenous(): return self._generics_manager.get_index_and_execute(0) else: if isinstance(index, int): return self._generics_manager.get_index_and_execute(index) debug.dbg('The getitem type on Tuple was %s' % index) return NO_VALUES def py__iter__(self, contextualized_node=None): if self._is_homogenous(): yield LazyKnownValues(self._generics_manager.get_index_and_execute(0)) else: for v in self._generics_manager.to_tuple(): yield LazyKnownValues(v.execute_annotation()) def py__getitem__(self, index_value_set, contextualized_node): if self._is_homogenous(): return self._generics_manager.get_index_and_execute(0) return ValueSet.from_sets( self._generics_manager.to_tuple() ).execute_annotation() def _get_wrapped_value(self): tuple_, = self.inference_state.builtins_module \ .py__getattribute__('tuple').execute_annotation() return tuple_ def name(self): return self._wrapped_value.name def infer_type_vars(self, value_set): # Circular from jedi.inference.gradual.annotation import merge_pairwise_generics, merge_type_var_dicts value_set = value_set.filter( lambda x: x.py__name__().lower() == 'tuple', ) if self._is_homogenous(): # The parameter annotation is of the form `Tuple[T, ...]`, # so we treat the incoming tuple like a iterable sequence # rather than a positional container of elements. return self._class_value.get_generics()[0].infer_type_vars( value_set.merge_types_of_iterate(), ) else: # The parameter annotation has only explicit type parameters # (e.g: `Tuple[T]`, `Tuple[T, U]`, `Tuple[T, U, V]`, etc.) so we # treat the incoming values as needing to match the annotation # exactly, just as we would for non-tuple annotations. type_var_dict = {} for element in value_set: try: method = element.get_annotated_class_object except AttributeError: # This might still happen, because the tuple name matching # above is not 100% correct, so just catch the remaining # cases here. continue py_class = method() merge_type_var_dicts( type_var_dict, merge_pairwise_generics(self._class_value, py_class), ) return type_var_dict def cast(typ: Type[_T], val: Any) -> _T: ... def cast(typ: str, val: Any) -> Any: ... def cast(typ: object, val: Any) -> Any: ... The provided code snippet includes necessary dependencies for implementing the `is_slice` function. Write a Python function `def is_slice(node)` to solve the following problem: Returns whether node represents a slice, e.g. `1:2` in `x[1:2]` Here is the function: def is_slice(node): # type: (AstNode) -> bool """Returns whether node represents a slice, e.g. `1:2` in `x[1:2]`""" # Before 3.9, a tuple containing a slice is an ExtSlice, # but this was removed in https://bugs.python.org/issue34822 return ( node.__class__.__name__ in ('Slice', 'ExtSlice') or ( node.__class__.__name__ == 'Tuple' and any(map(is_slice, cast(ast.Tuple, node).elts)) ) )
Returns whether node represents a slice, e.g. `1:2` in `x[1:2]`
175,147
import ast import collections import io import sys import token import tokenize from abc import ABCMeta from ast import Module, expr, AST from typing import Callable, Dict, Iterable, Iterator, List, Optional, Tuple, Union, cast, Any, TYPE_CHECKING from six import iteritems def is_empty_astroid_slice(node): # type: (AstNode) -> bool return ( node.__class__.__name__ == "Slice" and not isinstance(node, ast.AST) and node.lower is node.upper is node.step is None )
null
175,148
import ast import collections import io import sys import token import tokenize from abc import ABCMeta from ast import Module, expr, AST from typing import Callable, Dict, Iterable, Iterator, List, Optional, Tuple, Union, cast, Any, TYPE_CHECKING from six import iteritems class Token(collections.namedtuple('Token', 'type string start end line index startpos endpos')): """ TokenInfo is an 8-tuple containing the same 5 fields as the tokens produced by the tokenize module, and 3 additional ones useful for this module: - [0] .type Token type (see token.py) - [1] .string Token (a string) - [2] .start Starting (row, column) indices of the token (a 2-tuple of ints) - [3] .end Ending (row, column) indices of the token (a 2-tuple of ints) - [4] .line Original line (string) - [5] .index Index of the token in the list of tokens that it belongs to. - [6] .startpos Starting character offset into the input text. - [7] .endpos Ending character offset into the input text. """ def __str__(self): # type: () -> str return token_repr(self.type, self.string) def iter_children_func(node): # type: (AST) -> Callable """ Returns a function which yields all direct children of a AST node, skipping children that are singleton nodes. The function depends on whether ``node`` is from ``ast`` or from the ``astroid`` module. """ return iter_children_astroid if hasattr(node, 'get_children') else iter_children_ast _PREVISIT = object() Optional: _SpecialForm = ... def cast(typ: Type[_T], val: Any) -> _T: ... def cast(typ: str, val: Any) -> Any: ... def cast(typ: object, val: Any) -> Any: ... The provided code snippet includes necessary dependencies for implementing the `visit_tree` function. Write a Python function `def visit_tree(node, previsit, postvisit)` to solve the following problem: Scans the tree under the node depth-first using an explicit stack. It avoids implicit recursion via the function call stack to avoid hitting 'maximum recursion depth exceeded' error. It calls ``previsit()`` and ``postvisit()`` as follows: * ``previsit(node, par_value)`` - should return ``(par_value, value)`` ``par_value`` is as returned from ``previsit()`` of the parent. * ``postvisit(node, par_value, value)`` - should return ``value`` ``par_value`` is as returned from ``previsit()`` of the parent, and ``value`` is as returned from ``previsit()`` of this node itself. The return ``value`` is ignored except the one for the root node, which is returned from the overall ``visit_tree()`` call. For the initial node, ``par_value`` is None. ``postvisit`` may be None. Here is the function: def visit_tree(node, previsit, postvisit): # type: (Module, Callable[[AstNode, Optional[Token]], Tuple[Optional[Token], Optional[Token]]], Optional[Callable[[AstNode, Optional[Token], Optional[Token]], None]]) -> None """ Scans the tree under the node depth-first using an explicit stack. It avoids implicit recursion via the function call stack to avoid hitting 'maximum recursion depth exceeded' error. It calls ``previsit()`` and ``postvisit()`` as follows: * ``previsit(node, par_value)`` - should return ``(par_value, value)`` ``par_value`` is as returned from ``previsit()`` of the parent. * ``postvisit(node, par_value, value)`` - should return ``value`` ``par_value`` is as returned from ``previsit()`` of the parent, and ``value`` is as returned from ``previsit()`` of this node itself. The return ``value`` is ignored except the one for the root node, which is returned from the overall ``visit_tree()`` call. For the initial node, ``par_value`` is None. ``postvisit`` may be None. """ if not postvisit: postvisit = lambda node, pvalue, value: None iter_children = iter_children_func(node) done = set() ret = None stack = [(node, None, _PREVISIT)] # type: List[Tuple[AstNode, Optional[Token], Union[Optional[Token], object]]] while stack: current, par_value, value = stack.pop() if value is _PREVISIT: assert current not in done # protect againt infinite loop in case of a bad tree. done.add(current) pvalue, post_value = previsit(current, par_value) stack.append((current, par_value, post_value)) # Insert all children in reverse order (so that first child ends up on top of the stack). ins = len(stack) for n in iter_children(current): stack.insert(ins, (n, pvalue, _PREVISIT)) else: ret = postvisit(current, par_value, cast(Optional[Token], value)) return ret
Scans the tree under the node depth-first using an explicit stack. It avoids implicit recursion via the function call stack to avoid hitting 'maximum recursion depth exceeded' error. It calls ``previsit()`` and ``postvisit()`` as follows: * ``previsit(node, par_value)`` - should return ``(par_value, value)`` ``par_value`` is as returned from ``previsit()`` of the parent. * ``postvisit(node, par_value, value)`` - should return ``value`` ``par_value`` is as returned from ``previsit()`` of the parent, and ``value`` is as returned from ``previsit()`` of this node itself. The return ``value`` is ignored except the one for the root node, which is returned from the overall ``visit_tree()`` call. For the initial node, ``par_value`` is None. ``postvisit`` may be None.
175,149
import ast import collections import io import sys import token import tokenize from abc import ABCMeta from ast import Module, expr, AST from typing import Callable, Dict, Iterable, Iterator, List, Optional, Tuple, Union, cast, Any, TYPE_CHECKING from six import iteritems The provided code snippet includes necessary dependencies for implementing the `replace` function. Write a Python function `def replace(text, replacements)` to solve the following problem: Replaces multiple slices of text with new values. This is a convenience method for making code modifications of ranges e.g. as identified by ``ASTTokens.get_text_range(node)``. Replacements is an iterable of ``(start, end, new_text)`` tuples. For example, ``replace("this is a test", [(0, 4, "X"), (8, 9, "THE")])`` produces ``"X is THE test"``. Here is the function: def replace(text, replacements): # type: (str, List[Tuple[int, int, str]]) -> str """ Replaces multiple slices of text with new values. This is a convenience method for making code modifications of ranges e.g. as identified by ``ASTTokens.get_text_range(node)``. Replacements is an iterable of ``(start, end, new_text)`` tuples. For example, ``replace("this is a test", [(0, 4, "X"), (8, 9, "THE")])`` produces ``"X is THE test"``. """ p = 0 parts = [] for (start, end, new_text) in sorted(replacements): parts.append(text[p:start]) parts.append(new_text) p = end parts.append(text[p:]) return ''.join(parts)
Replaces multiple slices of text with new values. This is a convenience method for making code modifications of ranges e.g. as identified by ``ASTTokens.get_text_range(node)``. Replacements is an iterable of ``(start, end, new_text)`` tuples. For example, ``replace("this is a test", [(0, 4, "X"), (8, 9, "THE")])`` produces ``"X is THE test"``.
175,150
import ast import collections import io import sys import token import tokenize from abc import ABCMeta from ast import Module, expr, AST from typing import Callable, Dict, Iterable, Iterator, List, Optional, Tuple, Union, cast, Any, TYPE_CHECKING from six import iteritems def patched_generate_tokens(original_tokens): # type: (Iterable[TokenInfo]) -> Iterator[TokenInfo] return iter(original_tokens)
null
175,151
import ast import collections import io import sys import token import tokenize from abc import ABCMeta from ast import Module, expr, AST from typing import Callable, Dict, Iterable, Iterator, List, Optional, Tuple, Union, cast, Any, TYPE_CHECKING from six import iteritems if sys.version_info[0] == 2: # Python 2 doesn't support non-ASCII identifiers, and making the real patched_generate_tokens support Python 2 # means working with raw tuples instead of tokenize.TokenInfo namedtuples. else: def combine_tokens(group): # type: (List[tokenize.TokenInfo]) -> List[tokenize.TokenInfo] if not any(tok.type == tokenize.ERRORTOKEN for tok in group) or len({tok.line for tok in group}) != 1: return group return [ tokenize.TokenInfo( type=tokenize.NAME, string="".join(t.string for t in group), start=group[0].start, end=group[-1].end, line=group[0].line, ) ] The provided code snippet includes necessary dependencies for implementing the `patched_generate_tokens` function. Write a Python function `def patched_generate_tokens(original_tokens)` to solve the following problem: Fixes tokens yielded by `tokenize.generate_tokens` to handle more non-ASCII characters in identifiers. Workaround for https://github.com/python/cpython/issues/68382. Should only be used when tokenizing a string that is known to be valid syntax, because it assumes that error tokens are not actually errors. Combines groups of consecutive NAME, NUMBER, and/or ERRORTOKEN tokens into a single NAME token. Here is the function: def patched_generate_tokens(original_tokens): # type: (Iterable[TokenInfo]) -> Iterator[TokenInfo] """ Fixes tokens yielded by `tokenize.generate_tokens` to handle more non-ASCII characters in identifiers. Workaround for https://github.com/python/cpython/issues/68382. Should only be used when tokenizing a string that is known to be valid syntax, because it assumes that error tokens are not actually errors. Combines groups of consecutive NAME, NUMBER, and/or ERRORTOKEN tokens into a single NAME token. """ group = [] # type: List[tokenize.TokenInfo] for tok in original_tokens: if ( tok.type in (tokenize.NAME, tokenize.ERRORTOKEN, tokenize.NUMBER) # Only combine tokens if they have no whitespace in between and (not group or group[-1].end == tok.start) ): group.append(tok) else: for combined_token in combine_tokens(group): yield combined_token group = [] yield tok for combined_token in combine_tokens(group): yield combined_token
Fixes tokens yielded by `tokenize.generate_tokens` to handle more non-ASCII characters in identifiers. Workaround for https://github.com/python/cpython/issues/68382. Should only be used when tokenizing a string that is known to be valid syntax, because it assumes that error tokens are not actually errors. Combines groups of consecutive NAME, NUMBER, and/or ERRORTOKEN tokens into a single NAME token.
175,152
import ast import collections import io import sys import token import tokenize from abc import ABCMeta from ast import Module, expr, AST from typing import Callable, Dict, Iterable, Iterator, List, Optional, Tuple, Union, cast, Any, TYPE_CHECKING from six import iteritems The provided code snippet includes necessary dependencies for implementing the `last_stmt` function. Write a Python function `def last_stmt(node)` to solve the following problem: If the given AST node contains multiple statements, return the last one. Otherwise, just return the node. Here is the function: def last_stmt(node): # type: (ast.AST) -> ast.AST """ If the given AST node contains multiple statements, return the last one. Otherwise, just return the node. """ child_stmts = [ child for child in ast.iter_child_nodes(node) if isinstance(child, (ast.stmt, ast.excepthandler, getattr(ast, "match_case", ()))) ] if child_stmts: return last_stmt(child_stmts[-1]) return node
If the given AST node contains multiple statements, return the last one. Otherwise, just return the node.
175,153
import ast import collections import io import sys import token import tokenize from abc import ABCMeta from ast import Module, expr, AST from typing import Callable, Dict, Iterable, Iterator, List, Optional, Tuple, Union, cast, Any, TYPE_CHECKING from six import iteritems def walk(node): # type: (AST) -> Iterator[Union[Module, AstNode]] """ Recursively yield all descendant nodes in the tree starting at ``node`` (including ``node`` itself), using depth-first pre-order traversal (yieling parents before their children). This is similar to ``ast.walk()``, but with a different order, and it works for both ``ast`` and ``astroid`` trees. Also, as ``iter_children()``, it skips singleton nodes generated by ``ast``. """ iter_children = iter_children_func(node) done = set() stack = [node] while stack: current = stack.pop() assert current not in done # protect againt infinite loop in case of a bad tree. done.add(current) yield current # Insert all children in reverse order (so that first child ends up on top of the stack). # This is faster than building a list and reversing it. ins = len(stack) for c in iter_children(current): stack.insert(ins, c) if sys.version_info[:2] >= (3, 8): from functools import lru_cache def fstring_positions_work(): # type: () -> bool """ The positions attached to nodes inside f-string FormattedValues have some bugs that were fixed in Python 3.9.7 in https://github.com/python/cpython/pull/27729. This checks for those bugs more concretely without relying on the Python version. Specifically this checks: - Values with a format spec or conversion - Repeated (i.e. identical-looking) expressions - Multiline f-strings implicitly concatenated. """ source = """( f"a {b}{b} c {d!r} e {f:g} h {i:{j}} k {l:{m:n}}" f"a {b}{b} c {d!r} e {f:g} h {i:{j}} k {l:{m:n}}" f"{x + y + z} {x} {y} {z} {z} {z!a} {z:z}" )""" tree = ast.parse(source) name_nodes = [node for node in ast.walk(tree) if isinstance(node, ast.Name)] name_positions = [(node.lineno, node.col_offset) for node in name_nodes] positions_are_unique = len(set(name_positions)) == len(name_positions) correct_source_segments = all( ast.get_source_segment(source, node) == node.id for node in name_nodes ) return positions_are_unique and correct_source_segments else: def fstring_positions_work(): # type: () -> bool return False The provided code snippet includes necessary dependencies for implementing the `annotate_fstring_nodes` function. Write a Python function `def annotate_fstring_nodes(tree)` to solve the following problem: Add a special attribute `_broken_positions` to nodes inside f-strings if the lineno/col_offset cannot be trusted. Here is the function: def annotate_fstring_nodes(tree): # type: (ast.AST) -> None """ Add a special attribute `_broken_positions` to nodes inside f-strings if the lineno/col_offset cannot be trusted. """ for joinedstr in walk(tree): if not isinstance(joinedstr, ast.JoinedStr): continue for part in joinedstr.values: # The ast positions of the FormattedValues/Constant nodes span the full f-string, which is weird. setattr(part, '_broken_positions', True) # use setattr for mypy if isinstance(part, ast.FormattedValue): if not fstring_positions_work(): for child in walk(part.value): setattr(child, '_broken_positions', True) if part.format_spec: # this is another JoinedStr # Again, the standard positions span the full f-string. setattr(part.format_spec, '_broken_positions', True) # Recursively handle this inner JoinedStr in the same way. # While this is usually automatic for other nodes, # the children of f-strings are explicitly excluded in iter_children_ast. annotate_fstring_nodes(part.format_spec)
Add a special attribute `_broken_positions` to nodes inside f-strings if the lineno/col_offset cannot be trusted.
175,154
import ast import collections import io import sys import token import tokenize from abc import ABCMeta from ast import Module, expr, AST from typing import Callable, Dict, Iterable, Iterator, List, Optional, Tuple, Union, cast, Any, TYPE_CHECKING from six import iteritems def annotate_fstring_nodes(_tree): # type: (ast.AST) -> None pass
null
175,155
import abc import ast import bisect import sys import token from ast import Module from typing import Iterable, Iterator, List, Optional, Tuple, Any, cast, TYPE_CHECKING, Type import six from six.moves import xrange from .line_numbers import LineNumbers from .util import Token, match_token, is_non_coding_token, patched_generate_tokens, last_stmt, annotate_fstring_nodes, generate_tokens _unsupported_tokenless_types = () if sys.version_info[:2] >= (3, 8): _unsupported_tokenless_types += ( # no lineno ast.arguments, ast.withitem, ) if sys.version_info[:2] == (3, 8): _unsupported_tokenless_types += ( # _get_text_positions_tokenless works incorrectly for these types due to bugs in Python 3.8. ast.arg, ast.Starred, # no lineno in 3.8 ast.Slice, ast.ExtSlice, ast.Index, ast.keyword, ) The provided code snippet includes necessary dependencies for implementing the `supports_tokenless` function. Write a Python function `def supports_tokenless(node=None)` to solve the following problem: Returns True if the Python version and the node (if given) are supported by the ``get_text*`` methods of ``ASTText`` without falling back to ``ASTTokens``. See ``ASTText`` for why this matters. The following cases are not supported: - Python 3.7 and earlier - PyPy - Astroid nodes (``get_text*`` methods of ``ASTText`` will raise an error) - ``ast.arguments`` and ``ast.withitem`` - The following nodes in Python 3.8 only: - ``ast.arg`` - ``ast.Starred`` - ``ast.Slice`` - ``ast.ExtSlice`` - ``ast.Index`` - ``ast.keyword`` Here is the function: def supports_tokenless(node=None): # type: (Any) -> bool """ Returns True if the Python version and the node (if given) are supported by the ``get_text*`` methods of ``ASTText`` without falling back to ``ASTTokens``. See ``ASTText`` for why this matters. The following cases are not supported: - Python 3.7 and earlier - PyPy - Astroid nodes (``get_text*`` methods of ``ASTText`` will raise an error) - ``ast.arguments`` and ``ast.withitem`` - The following nodes in Python 3.8 only: - ``ast.arg`` - ``ast.Starred`` - ``ast.Slice`` - ``ast.ExtSlice`` - ``ast.Index`` - ``ast.keyword`` """ return ( isinstance(node, (ast.AST, type(None))) and not isinstance(node, _unsupported_tokenless_types) and sys.version_info[:2] >= (3, 8) and 'pypy' not in sys.version.lower() )
Returns True if the Python version and the node (if given) are supported by the ``get_text*`` methods of ``ASTText`` without falling back to ``ASTTokens``. See ``ASTText`` for why this matters. The following cases are not supported: - Python 3.7 and earlier - PyPy - Astroid nodes (``get_text*`` methods of ``ASTText`` will raise an error) - ``ast.arguments`` and ``ast.withitem`` - The following nodes in Python 3.8 only: - ``ast.arg`` - ``ast.Starred`` - ``ast.Slice`` - ``ast.ExtSlice`` - ``ast.Index`` - ``ast.keyword``
175,156
from .block_parser import BlockParser, expand_leading_tab, cleanup_lines from .inline_parser import InlineParser def cleanup_lines(s): s = _NEW_LINES.sub('\n', s) s = _BLANK_LINES.sub('', s) return s def expand_leading_tab(text): return _EXPAND_TAB.sub(_expand_tab_repl, text) def preprocess(s, state): state.update({ 'def_links': {}, 'def_footnotes': {}, 'footnotes': [], }) if s is None: s = '\n' else: s = s.replace('\u2424', '\n') s = cleanup_lines(s) s = expand_leading_tab(s) if not s.endswith('\n'): s += '\n' return s, state
null
175,157
from .base import Directive def render_html_admonition(text, name, title=""): html = '<section class="admonition ' + name + '">\n' if not title: title = name.capitalize() if title: html += '<p class="admonition-title">' + title + '</p>\n' if text: html += text return html + '</section>\n'
null
175,158
from .base import Directive def render_ast_admonition(children, name, title=""): return { 'type': 'admonition', 'children': children, 'name': name, 'title': title, }
null
175,159
from .base import Directive def record_toc_heading(text, level, state): # we will use this method to replace tokenize_heading tid = 'toc_' + str(len(state['toc_headings']) + 1) state['toc_headings'].append((tid, text, level)) return {'type': 'theading', 'text': text, 'params': (level, tid)}
null
175,160
from .base import Directive def _cleanup_headings_text(inline, items, state): for item in items: text = item[1] tokens = inline._scan(text, state, inline.rules) text = ''.join(_inline_token_text(tok) for tok in tokens) yield item[0], text, item[2] def md_toc_hook(md, tokens, state): headings = state.get('toc_headings') if not headings: return tokens # add TOC items into the given location default_depth = state.get('toc_depth', 3) headings = list(_cleanup_headings_text(md.inline, headings, state)) for tok in tokens: if tok['type'] == 'toc': params = tok['params'] depth = params[1] or default_depth items = [d for d in headings if d[2] <= depth] tok['raw'] = items return tokens
null
175,161
from .base import Directive def render_ast_toc(items, title, depth): return { 'type': 'toc', 'items': [list(d) for d in items], 'title': title, 'depth': depth, }
null