id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
172,778 | import sys
import types
import pythoncom
import pywintypes
import win32api
import win32con
import winerror
from pythoncom import (
DISPATCH_METHOD,
DISPATCH_PROPERTYGET,
DISPATCH_PROPERTYPUT,
DISPATCH_PROPERTYPUTREF,
DISPID_COLLECT,
DISPID_CONSTRUCTOR,
DISPID_DESTRUCTOR,
DISPID_EVALUATE,
DISPID_NEWENUM,
DISPID_PROPERTYPUT,
DISPID_STARTENUM,
DISPID_UNKNOWN,
DISPID_VALUE,
)
from .exception import COMException
error = __name__ + " error"
regPolicy = "CLSID\\%s\\PythonCOMPolicy"
regDispatcher = "CLSID\\%s\\PythonCOMDispatcher"
regAddnPath = "CLSID\\%s\\PythonCOMPath"
DefaultPolicy = DesignatedWrapPolicy
def resolve_func(spec):
"""Resolve a function by name
Given a function specified by 'module.function', return a callable object
(ie, the function itself)
"""
try:
idx = spec.rindex(".")
mname = spec[:idx]
fname = spec[idx + 1 :]
# Dont attempt to optimize by looking in sys.modules,
# as another thread may also be performing the import - this
# way we take advantage of the built-in import lock.
module = _import_module(mname)
return getattr(module, fname)
except ValueError: # No "." in name - assume in this module
return globals()[spec]
try:
from .dispatcher import DispatcherTrace, DispatcherWin32trace
except ImportError: # Quite likely a frozen executable that doesnt need dispatchers
pass
import sys
if sys.version_info >= (3, 7):
from builtins import _PathLike
if sys.version_info >= (3, 7):
class ThreadingHTTPServer(socketserver.ThreadingMixIn, HTTPServer):
daemon_threads: bool # undocumented
The provided code snippet includes necessary dependencies for implementing the `CreateInstance` function. Write a Python function `def CreateInstance(clsid, reqIID)` to solve the following problem:
Create a new instance of the specified IID The COM framework **always** calls this function to create a new instance for the specified CLSID. This function looks up the registry for the name of a policy, creates the policy, and asks the policy to create the specified object by calling the _CreateInstance_ method. Exactly how the policy creates the instance is up to the policy. See the specific policy documentation for more details.
Here is the function:
def CreateInstance(clsid, reqIID):
"""Create a new instance of the specified IID
The COM framework **always** calls this function to create a new
instance for the specified CLSID. This function looks up the
registry for the name of a policy, creates the policy, and asks the
policy to create the specified object by calling the _CreateInstance_ method.
Exactly how the policy creates the instance is up to the policy. See the
specific policy documentation for more details.
"""
# First see is sys.path should have something on it.
try:
addnPaths = win32api.RegQueryValue(
win32con.HKEY_CLASSES_ROOT, regAddnPath % clsid
).split(";")
for newPath in addnPaths:
if newPath not in sys.path:
sys.path.insert(0, newPath)
except win32api.error:
pass
try:
policy = win32api.RegQueryValue(win32con.HKEY_CLASSES_ROOT, regPolicy % clsid)
policy = resolve_func(policy)
except win32api.error:
policy = DefaultPolicy
try:
dispatcher = win32api.RegQueryValue(
win32con.HKEY_CLASSES_ROOT, regDispatcher % clsid
)
if dispatcher:
dispatcher = resolve_func(dispatcher)
except win32api.error:
dispatcher = None
if dispatcher:
retObj = dispatcher(policy, None)
else:
retObj = policy(None)
return retObj._CreateInstance_(clsid, reqIID) | Create a new instance of the specified IID The COM framework **always** calls this function to create a new instance for the specified CLSID. This function looks up the registry for the name of a policy, creates the policy, and asks the policy to create the specified object by calling the _CreateInstance_ method. Exactly how the policy creates the instance is up to the policy. See the specific policy documentation for more details. |
172,779 | import sys
import types
import pythoncom
import pywintypes
import win32api
import win32con
import winerror
from pythoncom import (
DISPATCH_METHOD,
DISPATCH_PROPERTYGET,
DISPATCH_PROPERTYPUT,
DISPATCH_PROPERTYPUTREF,
DISPID_COLLECT,
DISPID_CONSTRUCTOR,
DISPID_DESTRUCTOR,
DISPID_EVALUATE,
DISPID_NEWENUM,
DISPID_PROPERTYPUT,
DISPID_STARTENUM,
DISPID_UNKNOWN,
DISPID_VALUE,
)
from .exception import COMException
def resolve_func(spec):
"""Resolve a function by name
Given a function specified by 'module.function', return a callable object
(ie, the function itself)
"""
try:
idx = spec.rindex(".")
mname = spec[:idx]
fname = spec[idx + 1 :]
# Dont attempt to optimize by looking in sys.modules,
# as another thread may also be performing the import - this
# way we take advantage of the built-in import lock.
module = _import_module(mname)
return getattr(module, fname)
except ValueError: # No "." in name - assume in this module
return globals()[spec]
The provided code snippet includes necessary dependencies for implementing the `call_func` function. Write a Python function `def call_func(spec, *args)` to solve the following problem:
Call a function specified by name. Call a function specified by 'module.function' and return the result.
Here is the function:
def call_func(spec, *args):
"""Call a function specified by name.
Call a function specified by 'module.function' and return the result.
"""
return resolve_func(spec)(*args) | Call a function specified by name. Call a function specified by 'module.function' and return the result. |
172,780 | import os
import sys
import pythoncom
import win32api
import win32con
import winerror
def _get_string(path, base=win32con.HKEY_CLASSES_ROOT):
"Get a string value from the registry."
try:
return win32api.RegQueryValue(base, path)
except win32api.error:
return None
The provided code snippet includes necessary dependencies for implementing the `GetRegisteredServerOption` function. Write a Python function `def GetRegisteredServerOption(clsid, optionName)` to solve the following problem:
Given a CLSID for a server and option name, return the option value
Here is the function:
def GetRegisteredServerOption(clsid, optionName):
"""Given a CLSID for a server and option name, return the option value"""
keyNameRoot = "CLSID\\%s\\%s" % (str(clsid), str(optionName))
return _get_string(keyNameRoot) | Given a CLSID for a server and option name, return the option value |
172,781 | import os
import sys
import pythoncom
import win32api
import win32con
import winerror
CATID_PythonCOMServer = "{B3EF80D0-68E2-11D0-A689-00C04FD658FF}"
def _cat_registrar():
return pythoncom.CoCreateInstance(
pythoncom.CLSID_StdComponentCategoriesMgr,
None,
pythoncom.CLSCTX_INPROC_SERVER,
pythoncom.IID_ICatRegister,
)
The provided code snippet includes necessary dependencies for implementing the `RegisterPyComCategory` function. Write a Python function `def RegisterPyComCategory()` to solve the following problem:
Register the Python COM Server component category.
Here is the function:
def RegisterPyComCategory():
"""Register the Python COM Server component category."""
regCat = _cat_registrar()
regCat.RegisterCategories([(CATID_PythonCOMServer, 0x0409, "Python COM Server")]) | Register the Python COM Server component category. |
172,782 | import traceback
import types
import pythoncom
import win32com.client
import winerror
from pywintypes import IIDType
from . import build
debugging = 0
def debug_print(*args):
if debugging:
for arg in args:
print(arg, end=" ")
print() | null |
172,783 | import traceback
import types
import pythoncom
import win32com.client
import winerror
from pywintypes import IIDType
from . import build
debugging_attr = 0
def debug_attr_print(*args):
if debugging_attr:
for arg in args:
print(arg, end=" ")
print() | null |
172,784 | import traceback
import types
import pythoncom
import win32com.client
import winerror
from pywintypes import IIDType
from . import build
def MakeMethod(func, inst, cls):
return types.MethodType(func, inst) | null |
172,785 | import traceback
import types
import pythoncom
import win32com.client
import winerror
from pywintypes import IIDType
from . import build
def _GetDescInvokeType(entry, invoke_type):
# determine the wFlags argument passed as input to IDispatch::Invoke
# Only ever called by __getattr__ and __setattr__ from dynamic objects!
# * `entry` is a MapEntry with whatever typeinfo we have about the property we are getting/setting.
# * `invoke_type` is either INVOKE_PROPERTYGET | INVOKE_PROPERTYSET and really just
# means "called by __getattr__" or "called by __setattr__"
if not entry or not entry.desc:
return invoke_type
if entry.desc.desckind == pythoncom.DESCKIND_VARDESC:
return invoke_type
# So it's a FUNCDESC - just use what it specifies.
return entry.desc.invkind | null |
172,786 | import traceback
import types
import pythoncom
import win32com.client
import winerror
from pywintypes import IIDType
from . import build
def _GetGoodDispatchAndUserName(IDispatch, userName, clsctx):
# Get a dispatch object, and a 'user name' (ie, the name as
# displayed to the user in repr() etc.
if userName is None:
if isinstance(IDispatch, str):
userName = IDispatch
## ??? else userName remains None ???
else:
userName = str(userName)
return (_GetGoodDispatch(IDispatch, clsctx), userName)
def MakeOleRepr(IDispatch, typeinfo, typecomp):
olerepr = None
if typeinfo is not None:
try:
attr = typeinfo.GetTypeAttr()
# If the type info is a special DUAL interface, magically turn it into
# a DISPATCH typeinfo.
if (
attr[5] == pythoncom.TKIND_INTERFACE
and attr[11] & pythoncom.TYPEFLAG_FDUAL
):
# Get corresponding Disp interface;
# -1 is a special value which does this for us.
href = typeinfo.GetRefTypeOfImplType(-1)
typeinfo = typeinfo.GetRefTypeInfo(href)
attr = typeinfo.GetTypeAttr()
if typecomp is None:
olerepr = build.DispatchItem(typeinfo, attr, None, 0)
else:
olerepr = build.LazyDispatchItem(attr, None)
except pythoncom.ole_error:
pass
if olerepr is None:
olerepr = build.DispatchItem()
return olerepr
class CDispatch:
def __init__(
self, IDispatch, olerepr, userName=None, UnicodeToString=None, lazydata=None
):
assert UnicodeToString is None, "this is deprecated and will go away"
if userName is None:
userName = "<unknown>"
self.__dict__["_oleobj_"] = IDispatch
self.__dict__["_username_"] = userName
self.__dict__["_olerepr_"] = olerepr
self.__dict__["_mapCachedItems_"] = {}
self.__dict__["_builtMethods_"] = {}
self.__dict__["_enum_"] = None
self.__dict__["_unicode_to_string_"] = None
self.__dict__["_lazydata_"] = lazydata
def __call__(self, *args):
"Provide 'default dispatch' COM functionality - allow instance to be called"
if self._olerepr_.defaultDispatchName:
invkind, dispid = self._find_dispatch_type_(
self._olerepr_.defaultDispatchName
)
else:
invkind, dispid = (
pythoncom.DISPATCH_METHOD | pythoncom.DISPATCH_PROPERTYGET,
pythoncom.DISPID_VALUE,
)
if invkind is not None:
allArgs = (dispid, LCID, invkind, 1) + args
return self._get_good_object_(
self._oleobj_.Invoke(*allArgs), self._olerepr_.defaultDispatchName, None
)
raise TypeError("This dispatch object does not define a default method")
def __bool__(self):
return True # ie "if object:" should always be "true" - without this, __len__ is tried.
# _Possibly_ want to defer to __len__ if available, but Im not sure this is
# desirable???
def __repr__(self):
return "<COMObject %s>" % (self._username_)
def __str__(self):
# __str__ is used when the user does "print object", so we gracefully
# fall back to the __repr__ if the object has no default method.
try:
return str(self.__call__())
except pythoncom.com_error as details:
if details.hresult not in ERRORS_BAD_CONTEXT:
raise
return self.__repr__()
def __dir__(self):
lst = list(self.__dict__.keys()) + dir(self.__class__) + self._dir_ole_()
try:
lst += [p.Name for p in self.Properties_]
except AttributeError:
pass
return list(set(lst))
def _dir_ole_(self):
items_dict = {}
for iTI in range(0, self._oleobj_.GetTypeInfoCount()):
typeInfo = self._oleobj_.GetTypeInfo(iTI)
self._UpdateWithITypeInfo_(items_dict, typeInfo)
return list(items_dict.keys())
def _UpdateWithITypeInfo_(self, items_dict, typeInfo):
typeInfos = [typeInfo]
# suppress IDispatch and IUnknown methods
inspectedIIDs = {pythoncom.IID_IDispatch: None}
while len(typeInfos) > 0:
typeInfo = typeInfos.pop()
typeAttr = typeInfo.GetTypeAttr()
if typeAttr.iid not in inspectedIIDs:
inspectedIIDs[typeAttr.iid] = None
for iFun in range(0, typeAttr.cFuncs):
funDesc = typeInfo.GetFuncDesc(iFun)
funName = typeInfo.GetNames(funDesc.memid)[0]
if funName not in items_dict:
items_dict[funName] = None
# Inspect the type info of all implemented types
# E.g. IShellDispatch5 implements IShellDispatch4 which implements IShellDispatch3 ...
for iImplType in range(0, typeAttr.cImplTypes):
iRefType = typeInfo.GetRefTypeOfImplType(iImplType)
refTypeInfo = typeInfo.GetRefTypeInfo(iRefType)
typeInfos.append(refTypeInfo)
# Delegate comparison to the oleobjs, as they know how to do identity.
def __eq__(self, other):
other = getattr(other, "_oleobj_", other)
return self._oleobj_ == other
def __ne__(self, other):
other = getattr(other, "_oleobj_", other)
return self._oleobj_ != other
def __int__(self):
return int(self.__call__())
def __len__(self):
invkind, dispid = self._find_dispatch_type_("Count")
if invkind:
return self._oleobj_.Invoke(dispid, LCID, invkind, 1)
raise TypeError("This dispatch object does not define a Count method")
def _NewEnum(self):
try:
invkind = pythoncom.DISPATCH_METHOD | pythoncom.DISPATCH_PROPERTYGET
enum = self._oleobj_.InvokeTypes(
pythoncom.DISPID_NEWENUM, LCID, invkind, (13, 10), ()
)
except pythoncom.com_error:
return None # no enumerator for this object.
from . import util
return util.WrapEnum(enum, None)
def __getitem__(self, index): # syver modified
# Improved __getitem__ courtesy Syver Enstad
# Must check _NewEnum before Item, to ensure b/w compat.
if isinstance(index, int):
if self.__dict__["_enum_"] is None:
self.__dict__["_enum_"] = self._NewEnum()
if self.__dict__["_enum_"] is not None:
return self._get_good_object_(self._enum_.__getitem__(index))
# See if we have an "Item" method/property we can use (goes hand in hand with Count() above!)
invkind, dispid = self._find_dispatch_type_("Item")
if invkind is not None:
return self._get_good_object_(
self._oleobj_.Invoke(dispid, LCID, invkind, 1, index)
)
raise TypeError("This object does not support enumeration")
def __setitem__(self, index, *args):
# XXX - todo - We should support calling Item() here too!
# print "__setitem__ with", index, args
if self._olerepr_.defaultDispatchName:
invkind, dispid = self._find_dispatch_type_(
self._olerepr_.defaultDispatchName
)
else:
invkind, dispid = (
pythoncom.DISPATCH_PROPERTYPUT | pythoncom.DISPATCH_PROPERTYPUTREF,
pythoncom.DISPID_VALUE,
)
if invkind is not None:
allArgs = (dispid, LCID, invkind, 0, index) + args
return self._get_good_object_(
self._oleobj_.Invoke(*allArgs), self._olerepr_.defaultDispatchName, None
)
raise TypeError("This dispatch object does not define a default method")
def _find_dispatch_type_(self, methodName):
if methodName in self._olerepr_.mapFuncs:
item = self._olerepr_.mapFuncs[methodName]
return item.desc[4], item.dispid
if methodName in self._olerepr_.propMapGet:
item = self._olerepr_.propMapGet[methodName]
return item.desc[4], item.dispid
try:
dispid = self._oleobj_.GetIDsOfNames(0, methodName)
except: ### what error?
return None, None
return pythoncom.DISPATCH_METHOD | pythoncom.DISPATCH_PROPERTYGET, dispid
def _ApplyTypes_(self, dispid, wFlags, retType, argTypes, user, resultCLSID, *args):
result = self._oleobj_.InvokeTypes(
*(dispid, LCID, wFlags, retType, argTypes) + args
)
return self._get_good_object_(result, user, resultCLSID)
def _wrap_dispatch_(
self, ob, userName=None, returnCLSID=None, UnicodeToString=None
):
# Given a dispatch object, wrap it in a class
assert UnicodeToString is None, "this is deprecated and will go away"
return Dispatch(ob, userName)
def _get_good_single_object_(self, ob, userName=None, ReturnCLSID=None):
if isinstance(ob, PyIDispatchType):
# make a new instance of (probably this) class.
return self._wrap_dispatch_(ob, userName, ReturnCLSID)
if isinstance(ob, PyIUnknownType):
try:
ob = ob.QueryInterface(pythoncom.IID_IDispatch)
except pythoncom.com_error:
# It is an IUnknown, but not an IDispatch, so just let it through.
return ob
return self._wrap_dispatch_(ob, userName, ReturnCLSID)
return ob
def _get_good_object_(self, ob, userName=None, ReturnCLSID=None):
"""Given an object (usually the retval from a method), make it a good object to return.
Basically checks if it is a COM object, and wraps it up.
Also handles the fact that a retval may be a tuple of retvals"""
if ob is None: # Quick exit!
return None
elif isinstance(ob, tuple):
return tuple(
map(
lambda o, s=self, oun=userName, rc=ReturnCLSID: s._get_good_single_object_(
o, oun, rc
),
ob,
)
)
else:
return self._get_good_single_object_(ob)
def _make_method_(self, name):
"Make a method object - Assumes in olerepr funcmap"
methodName = build.MakePublicAttributeName(name) # translate keywords etc.
methodCodeList = self._olerepr_.MakeFuncMethod(
self._olerepr_.mapFuncs[name], methodName, 0
)
methodCode = "\n".join(methodCodeList)
try:
# print "Method code for %s is:\n" % self._username_, methodCode
# self._print_details_()
codeObject = compile(methodCode, "<COMObject %s>" % self._username_, "exec")
# Exec the code object
tempNameSpace = {}
# "Dispatch" in the exec'd code is win32com.client.Dispatch, not ours.
globNameSpace = globals().copy()
globNameSpace["Dispatch"] = win32com.client.Dispatch
exec(
codeObject, globNameSpace, tempNameSpace
) # self.__dict__, self.__dict__
name = methodName
# Save the function in map.
fn = self._builtMethods_[name] = tempNameSpace[name]
newMeth = MakeMethod(fn, self, self.__class__)
return newMeth
except:
debug_print("Error building OLE definition for code ", methodCode)
traceback.print_exc()
return None
def _Release_(self):
"""Cleanup object - like a close - to force cleanup when you dont
want to rely on Python's reference counting."""
for childCont in self._mapCachedItems_.values():
childCont._Release_()
self._mapCachedItems_ = {}
if self._oleobj_:
self._oleobj_.Release()
self.__dict__["_oleobj_"] = None
if self._olerepr_:
self.__dict__["_olerepr_"] = None
self._enum_ = None
def _proc_(self, name, *args):
"""Call the named method as a procedure, rather than function.
Mainly used by Word.Basic, which whinges about such things."""
try:
item = self._olerepr_.mapFuncs[name]
dispId = item.dispid
return self._get_good_object_(
self._oleobj_.Invoke(*(dispId, LCID, item.desc[4], 0) + (args))
)
except KeyError:
raise AttributeError(name)
def _print_details_(self):
"Debug routine - dumps what it knows about an object."
print("AxDispatch container", self._username_)
try:
print("Methods:")
for method in self._olerepr_.mapFuncs.keys():
print("\t", method)
print("Props:")
for prop, entry in self._olerepr_.propMap.items():
print("\t%s = 0x%x - %s" % (prop, entry.dispid, repr(entry)))
print("Get Props:")
for prop, entry in self._olerepr_.propMapGet.items():
print("\t%s = 0x%x - %s" % (prop, entry.dispid, repr(entry)))
print("Put Props:")
for prop, entry in self._olerepr_.propMapPut.items():
print("\t%s = 0x%x - %s" % (prop, entry.dispid, repr(entry)))
except:
traceback.print_exc()
def __LazyMap__(self, attr):
try:
if self._LazyAddAttr_(attr):
debug_attr_print(
"%s.__LazyMap__(%s) added something" % (self._username_, attr)
)
return 1
except AttributeError:
return 0
# Using the typecomp, lazily create a new attribute definition.
def _LazyAddAttr_(self, attr):
if self._lazydata_ is None:
return 0
res = 0
typeinfo, typecomp = self._lazydata_
olerepr = self._olerepr_
# We need to explicitly check each invoke type individually - simply
# specifying '0' will bind to "any member", which may not be the one
# we are actually after (ie, we may be after prop_get, but returned
# the info for the prop_put.)
for i in ALL_INVOKE_TYPES:
try:
x, t = typecomp.Bind(attr, i)
# Support 'Get' and 'Set' properties - see
# bug 1587023
if x == 0 and attr[:3] in ("Set", "Get"):
x, t = typecomp.Bind(attr[3:], i)
if x == pythoncom.DESCKIND_FUNCDESC: # it's a FUNCDESC
r = olerepr._AddFunc_(typeinfo, t, 0)
elif x == pythoncom.DESCKIND_VARDESC: # it's a VARDESC
r = olerepr._AddVar_(typeinfo, t, 0)
else: # not found or TYPEDESC/IMPLICITAPP
r = None
if not r is None:
key, map = r[0], r[1]
item = map[key]
if map == olerepr.propMapPut:
olerepr._propMapPutCheck_(key, item)
elif map == olerepr.propMapGet:
olerepr._propMapGetCheck_(key, item)
res = 1
except:
pass
return res
def _FlagAsMethod(self, *methodNames):
"""Flag these attribute names as being methods.
Some objects do not correctly differentiate methods and
properties, leading to problems when calling these methods.
Specifically, trying to say: ob.SomeFunc()
may yield an exception "None object is not callable"
In this case, an attempt to fetch the *property* has worked
and returned None, rather than indicating it is really a method.
Calling: ob._FlagAsMethod("SomeFunc")
should then allow this to work.
"""
for name in methodNames:
details = build.MapEntry(self.__AttrToID__(name), (name,))
self._olerepr_.mapFuncs[name] = details
def __AttrToID__(self, attr):
debug_attr_print(
"Calling GetIDsOfNames for property %s in Dispatch container %s"
% (attr, self._username_)
)
return self._oleobj_.GetIDsOfNames(0, attr)
def __getattr__(self, attr):
if attr == "__iter__":
# We can't handle this as a normal method, as if the attribute
# exists, then it must return an iterable object.
try:
invkind = pythoncom.DISPATCH_METHOD | pythoncom.DISPATCH_PROPERTYGET
enum = self._oleobj_.InvokeTypes(
pythoncom.DISPID_NEWENUM, LCID, invkind, (13, 10), ()
)
except pythoncom.com_error:
raise AttributeError("This object can not function as an iterator")
# We must return a callable object.
class Factory:
def __init__(self, ob):
self.ob = ob
def __call__(self):
import win32com.client.util
return win32com.client.util.Iterator(self.ob)
return Factory(enum)
if attr.startswith("_") and attr.endswith("_"): # Fast-track.
raise AttributeError(attr)
# If a known method, create new instance and return.
try:
return MakeMethod(self._builtMethods_[attr], self, self.__class__)
except KeyError:
pass
# XXX - Note that we current are case sensitive in the method.
# debug_attr_print("GetAttr called for %s on DispatchContainer %s" % (attr,self._username_))
# First check if it is in the method map. Note that an actual method
# must not yet exist, (otherwise we would not be here). This
# means we create the actual method object - which also means
# this code will never be asked for that method name again.
if attr in self._olerepr_.mapFuncs:
return self._make_method_(attr)
# Delegate to property maps/cached items
retEntry = None
if self._olerepr_ and self._oleobj_:
# first check general property map, then specific "put" map.
retEntry = self._olerepr_.propMap.get(attr)
if retEntry is None:
retEntry = self._olerepr_.propMapGet.get(attr)
# Not found so far - See what COM says.
if retEntry is None:
try:
if self.__LazyMap__(attr):
if attr in self._olerepr_.mapFuncs:
return self._make_method_(attr)
retEntry = self._olerepr_.propMap.get(attr)
if retEntry is None:
retEntry = self._olerepr_.propMapGet.get(attr)
if retEntry is None:
retEntry = build.MapEntry(self.__AttrToID__(attr), (attr,))
except pythoncom.ole_error:
pass # No prop by that name - retEntry remains None.
if retEntry is not None: # see if in my cache
try:
ret = self._mapCachedItems_[retEntry.dispid]
debug_attr_print("Cached items has attribute!", ret)
return ret
except (KeyError, AttributeError):
debug_attr_print("Attribute %s not in cache" % attr)
# If we are still here, and have a retEntry, get the OLE item
if retEntry is not None:
invoke_type = _GetDescInvokeType(retEntry, pythoncom.INVOKE_PROPERTYGET)
debug_attr_print(
"Getting property Id 0x%x from OLE object" % retEntry.dispid
)
try:
ret = self._oleobj_.Invoke(retEntry.dispid, 0, invoke_type, 1)
except pythoncom.com_error as details:
if details.hresult in ERRORS_BAD_CONTEXT:
# May be a method.
self._olerepr_.mapFuncs[attr] = retEntry
return self._make_method_(attr)
raise
debug_attr_print("OLE returned ", ret)
return self._get_good_object_(ret)
# no where else to look.
raise AttributeError("%s.%s" % (self._username_, attr))
def __setattr__(self, attr, value):
if (
attr in self.__dict__
): # Fast-track - if already in our dict, just make the assignment.
# XXX - should maybe check method map - if someone assigns to a method,
# it could mean something special (not sure what, tho!)
self.__dict__[attr] = value
return
# Allow property assignment.
debug_attr_print(
"SetAttr called for %s.%s=%s on DispatchContainer"
% (self._username_, attr, repr(value))
)
if self._olerepr_:
# Check the "general" property map.
if attr in self._olerepr_.propMap:
entry = self._olerepr_.propMap[attr]
invoke_type = _GetDescInvokeType(entry, pythoncom.INVOKE_PROPERTYPUT)
self._oleobj_.Invoke(entry.dispid, 0, invoke_type, 0, value)
return
# Check the specific "put" map.
if attr in self._olerepr_.propMapPut:
entry = self._olerepr_.propMapPut[attr]
invoke_type = _GetDescInvokeType(entry, pythoncom.INVOKE_PROPERTYPUT)
self._oleobj_.Invoke(entry.dispid, 0, invoke_type, 0, value)
return
# Try the OLE Object
if self._oleobj_:
if self.__LazyMap__(attr):
# Check the "general" property map.
if attr in self._olerepr_.propMap:
entry = self._olerepr_.propMap[attr]
invoke_type = _GetDescInvokeType(
entry, pythoncom.INVOKE_PROPERTYPUT
)
self._oleobj_.Invoke(entry.dispid, 0, invoke_type, 0, value)
return
# Check the specific "put" map.
if attr in self._olerepr_.propMapPut:
entry = self._olerepr_.propMapPut[attr]
invoke_type = _GetDescInvokeType(
entry, pythoncom.INVOKE_PROPERTYPUT
)
self._oleobj_.Invoke(entry.dispid, 0, invoke_type, 0, value)
return
try:
entry = build.MapEntry(self.__AttrToID__(attr), (attr,))
except pythoncom.com_error:
# No attribute of that name
entry = None
if entry is not None:
try:
invoke_type = _GetDescInvokeType(
entry, pythoncom.INVOKE_PROPERTYPUT
)
self._oleobj_.Invoke(entry.dispid, 0, invoke_type, 0, value)
self._olerepr_.propMap[attr] = entry
debug_attr_print(
"__setattr__ property %s (id=0x%x) in Dispatch container %s"
% (attr, entry.dispid, self._username_)
)
return
except pythoncom.com_error:
pass
raise AttributeError(
"Property '%s.%s' can not be set." % (self._username_, attr)
)
def Dispatch(
IDispatch,
userName=None,
createClass=None,
typeinfo=None,
UnicodeToString=None,
clsctx=pythoncom.CLSCTX_SERVER,
):
assert UnicodeToString is None, "this is deprecated and will go away"
IDispatch, userName = _GetGoodDispatchAndUserName(IDispatch, userName, clsctx)
if createClass is None:
createClass = CDispatch
lazydata = None
try:
if typeinfo is None:
typeinfo = IDispatch.GetTypeInfo()
if typeinfo is not None:
try:
# try for a typecomp
typecomp = typeinfo.GetTypeComp()
lazydata = typeinfo, typecomp
except pythoncom.com_error:
pass
except pythoncom.com_error:
typeinfo = None
olerepr = MakeOleRepr(IDispatch, typeinfo, lazydata)
return createClass(IDispatch, olerepr, userName, lazydata=lazydata) | null |
172,787 | import traceback
import types
import pythoncom
import win32com.client
import winerror
from pywintypes import IIDType
from . import build
def _GetGoodDispatchAndUserName(IDispatch, userName, clsctx):
# Get a dispatch object, and a 'user name' (ie, the name as
# displayed to the user in repr() etc.
if userName is None:
if isinstance(IDispatch, str):
userName = IDispatch
## ??? else userName remains None ???
else:
userName = str(userName)
return (_GetGoodDispatch(IDispatch, clsctx), userName)
class CDispatch:
def __init__(
self, IDispatch, olerepr, userName=None, UnicodeToString=None, lazydata=None
):
assert UnicodeToString is None, "this is deprecated and will go away"
if userName is None:
userName = "<unknown>"
self.__dict__["_oleobj_"] = IDispatch
self.__dict__["_username_"] = userName
self.__dict__["_olerepr_"] = olerepr
self.__dict__["_mapCachedItems_"] = {}
self.__dict__["_builtMethods_"] = {}
self.__dict__["_enum_"] = None
self.__dict__["_unicode_to_string_"] = None
self.__dict__["_lazydata_"] = lazydata
def __call__(self, *args):
"Provide 'default dispatch' COM functionality - allow instance to be called"
if self._olerepr_.defaultDispatchName:
invkind, dispid = self._find_dispatch_type_(
self._olerepr_.defaultDispatchName
)
else:
invkind, dispid = (
pythoncom.DISPATCH_METHOD | pythoncom.DISPATCH_PROPERTYGET,
pythoncom.DISPID_VALUE,
)
if invkind is not None:
allArgs = (dispid, LCID, invkind, 1) + args
return self._get_good_object_(
self._oleobj_.Invoke(*allArgs), self._olerepr_.defaultDispatchName, None
)
raise TypeError("This dispatch object does not define a default method")
def __bool__(self):
return True # ie "if object:" should always be "true" - without this, __len__ is tried.
# _Possibly_ want to defer to __len__ if available, but Im not sure this is
# desirable???
def __repr__(self):
return "<COMObject %s>" % (self._username_)
def __str__(self):
# __str__ is used when the user does "print object", so we gracefully
# fall back to the __repr__ if the object has no default method.
try:
return str(self.__call__())
except pythoncom.com_error as details:
if details.hresult not in ERRORS_BAD_CONTEXT:
raise
return self.__repr__()
def __dir__(self):
lst = list(self.__dict__.keys()) + dir(self.__class__) + self._dir_ole_()
try:
lst += [p.Name for p in self.Properties_]
except AttributeError:
pass
return list(set(lst))
def _dir_ole_(self):
items_dict = {}
for iTI in range(0, self._oleobj_.GetTypeInfoCount()):
typeInfo = self._oleobj_.GetTypeInfo(iTI)
self._UpdateWithITypeInfo_(items_dict, typeInfo)
return list(items_dict.keys())
def _UpdateWithITypeInfo_(self, items_dict, typeInfo):
typeInfos = [typeInfo]
# suppress IDispatch and IUnknown methods
inspectedIIDs = {pythoncom.IID_IDispatch: None}
while len(typeInfos) > 0:
typeInfo = typeInfos.pop()
typeAttr = typeInfo.GetTypeAttr()
if typeAttr.iid not in inspectedIIDs:
inspectedIIDs[typeAttr.iid] = None
for iFun in range(0, typeAttr.cFuncs):
funDesc = typeInfo.GetFuncDesc(iFun)
funName = typeInfo.GetNames(funDesc.memid)[0]
if funName not in items_dict:
items_dict[funName] = None
# Inspect the type info of all implemented types
# E.g. IShellDispatch5 implements IShellDispatch4 which implements IShellDispatch3 ...
for iImplType in range(0, typeAttr.cImplTypes):
iRefType = typeInfo.GetRefTypeOfImplType(iImplType)
refTypeInfo = typeInfo.GetRefTypeInfo(iRefType)
typeInfos.append(refTypeInfo)
# Delegate comparison to the oleobjs, as they know how to do identity.
def __eq__(self, other):
other = getattr(other, "_oleobj_", other)
return self._oleobj_ == other
def __ne__(self, other):
other = getattr(other, "_oleobj_", other)
return self._oleobj_ != other
def __int__(self):
return int(self.__call__())
def __len__(self):
invkind, dispid = self._find_dispatch_type_("Count")
if invkind:
return self._oleobj_.Invoke(dispid, LCID, invkind, 1)
raise TypeError("This dispatch object does not define a Count method")
def _NewEnum(self):
try:
invkind = pythoncom.DISPATCH_METHOD | pythoncom.DISPATCH_PROPERTYGET
enum = self._oleobj_.InvokeTypes(
pythoncom.DISPID_NEWENUM, LCID, invkind, (13, 10), ()
)
except pythoncom.com_error:
return None # no enumerator for this object.
from . import util
return util.WrapEnum(enum, None)
def __getitem__(self, index): # syver modified
# Improved __getitem__ courtesy Syver Enstad
# Must check _NewEnum before Item, to ensure b/w compat.
if isinstance(index, int):
if self.__dict__["_enum_"] is None:
self.__dict__["_enum_"] = self._NewEnum()
if self.__dict__["_enum_"] is not None:
return self._get_good_object_(self._enum_.__getitem__(index))
# See if we have an "Item" method/property we can use (goes hand in hand with Count() above!)
invkind, dispid = self._find_dispatch_type_("Item")
if invkind is not None:
return self._get_good_object_(
self._oleobj_.Invoke(dispid, LCID, invkind, 1, index)
)
raise TypeError("This object does not support enumeration")
def __setitem__(self, index, *args):
# XXX - todo - We should support calling Item() here too!
# print "__setitem__ with", index, args
if self._olerepr_.defaultDispatchName:
invkind, dispid = self._find_dispatch_type_(
self._olerepr_.defaultDispatchName
)
else:
invkind, dispid = (
pythoncom.DISPATCH_PROPERTYPUT | pythoncom.DISPATCH_PROPERTYPUTREF,
pythoncom.DISPID_VALUE,
)
if invkind is not None:
allArgs = (dispid, LCID, invkind, 0, index) + args
return self._get_good_object_(
self._oleobj_.Invoke(*allArgs), self._olerepr_.defaultDispatchName, None
)
raise TypeError("This dispatch object does not define a default method")
def _find_dispatch_type_(self, methodName):
if methodName in self._olerepr_.mapFuncs:
item = self._olerepr_.mapFuncs[methodName]
return item.desc[4], item.dispid
if methodName in self._olerepr_.propMapGet:
item = self._olerepr_.propMapGet[methodName]
return item.desc[4], item.dispid
try:
dispid = self._oleobj_.GetIDsOfNames(0, methodName)
except: ### what error?
return None, None
return pythoncom.DISPATCH_METHOD | pythoncom.DISPATCH_PROPERTYGET, dispid
def _ApplyTypes_(self, dispid, wFlags, retType, argTypes, user, resultCLSID, *args):
result = self._oleobj_.InvokeTypes(
*(dispid, LCID, wFlags, retType, argTypes) + args
)
return self._get_good_object_(result, user, resultCLSID)
def _wrap_dispatch_(
self, ob, userName=None, returnCLSID=None, UnicodeToString=None
):
# Given a dispatch object, wrap it in a class
assert UnicodeToString is None, "this is deprecated and will go away"
return Dispatch(ob, userName)
def _get_good_single_object_(self, ob, userName=None, ReturnCLSID=None):
if isinstance(ob, PyIDispatchType):
# make a new instance of (probably this) class.
return self._wrap_dispatch_(ob, userName, ReturnCLSID)
if isinstance(ob, PyIUnknownType):
try:
ob = ob.QueryInterface(pythoncom.IID_IDispatch)
except pythoncom.com_error:
# It is an IUnknown, but not an IDispatch, so just let it through.
return ob
return self._wrap_dispatch_(ob, userName, ReturnCLSID)
return ob
def _get_good_object_(self, ob, userName=None, ReturnCLSID=None):
"""Given an object (usually the retval from a method), make it a good object to return.
Basically checks if it is a COM object, and wraps it up.
Also handles the fact that a retval may be a tuple of retvals"""
if ob is None: # Quick exit!
return None
elif isinstance(ob, tuple):
return tuple(
map(
lambda o, s=self, oun=userName, rc=ReturnCLSID: s._get_good_single_object_(
o, oun, rc
),
ob,
)
)
else:
return self._get_good_single_object_(ob)
def _make_method_(self, name):
"Make a method object - Assumes in olerepr funcmap"
methodName = build.MakePublicAttributeName(name) # translate keywords etc.
methodCodeList = self._olerepr_.MakeFuncMethod(
self._olerepr_.mapFuncs[name], methodName, 0
)
methodCode = "\n".join(methodCodeList)
try:
# print "Method code for %s is:\n" % self._username_, methodCode
# self._print_details_()
codeObject = compile(methodCode, "<COMObject %s>" % self._username_, "exec")
# Exec the code object
tempNameSpace = {}
# "Dispatch" in the exec'd code is win32com.client.Dispatch, not ours.
globNameSpace = globals().copy()
globNameSpace["Dispatch"] = win32com.client.Dispatch
exec(
codeObject, globNameSpace, tempNameSpace
) # self.__dict__, self.__dict__
name = methodName
# Save the function in map.
fn = self._builtMethods_[name] = tempNameSpace[name]
newMeth = MakeMethod(fn, self, self.__class__)
return newMeth
except:
debug_print("Error building OLE definition for code ", methodCode)
traceback.print_exc()
return None
def _Release_(self):
"""Cleanup object - like a close - to force cleanup when you dont
want to rely on Python's reference counting."""
for childCont in self._mapCachedItems_.values():
childCont._Release_()
self._mapCachedItems_ = {}
if self._oleobj_:
self._oleobj_.Release()
self.__dict__["_oleobj_"] = None
if self._olerepr_:
self.__dict__["_olerepr_"] = None
self._enum_ = None
def _proc_(self, name, *args):
"""Call the named method as a procedure, rather than function.
Mainly used by Word.Basic, which whinges about such things."""
try:
item = self._olerepr_.mapFuncs[name]
dispId = item.dispid
return self._get_good_object_(
self._oleobj_.Invoke(*(dispId, LCID, item.desc[4], 0) + (args))
)
except KeyError:
raise AttributeError(name)
def _print_details_(self):
"Debug routine - dumps what it knows about an object."
print("AxDispatch container", self._username_)
try:
print("Methods:")
for method in self._olerepr_.mapFuncs.keys():
print("\t", method)
print("Props:")
for prop, entry in self._olerepr_.propMap.items():
print("\t%s = 0x%x - %s" % (prop, entry.dispid, repr(entry)))
print("Get Props:")
for prop, entry in self._olerepr_.propMapGet.items():
print("\t%s = 0x%x - %s" % (prop, entry.dispid, repr(entry)))
print("Put Props:")
for prop, entry in self._olerepr_.propMapPut.items():
print("\t%s = 0x%x - %s" % (prop, entry.dispid, repr(entry)))
except:
traceback.print_exc()
def __LazyMap__(self, attr):
try:
if self._LazyAddAttr_(attr):
debug_attr_print(
"%s.__LazyMap__(%s) added something" % (self._username_, attr)
)
return 1
except AttributeError:
return 0
# Using the typecomp, lazily create a new attribute definition.
def _LazyAddAttr_(self, attr):
if self._lazydata_ is None:
return 0
res = 0
typeinfo, typecomp = self._lazydata_
olerepr = self._olerepr_
# We need to explicitly check each invoke type individually - simply
# specifying '0' will bind to "any member", which may not be the one
# we are actually after (ie, we may be after prop_get, but returned
# the info for the prop_put.)
for i in ALL_INVOKE_TYPES:
try:
x, t = typecomp.Bind(attr, i)
# Support 'Get' and 'Set' properties - see
# bug 1587023
if x == 0 and attr[:3] in ("Set", "Get"):
x, t = typecomp.Bind(attr[3:], i)
if x == pythoncom.DESCKIND_FUNCDESC: # it's a FUNCDESC
r = olerepr._AddFunc_(typeinfo, t, 0)
elif x == pythoncom.DESCKIND_VARDESC: # it's a VARDESC
r = olerepr._AddVar_(typeinfo, t, 0)
else: # not found or TYPEDESC/IMPLICITAPP
r = None
if not r is None:
key, map = r[0], r[1]
item = map[key]
if map == olerepr.propMapPut:
olerepr._propMapPutCheck_(key, item)
elif map == olerepr.propMapGet:
olerepr._propMapGetCheck_(key, item)
res = 1
except:
pass
return res
def _FlagAsMethod(self, *methodNames):
"""Flag these attribute names as being methods.
Some objects do not correctly differentiate methods and
properties, leading to problems when calling these methods.
Specifically, trying to say: ob.SomeFunc()
may yield an exception "None object is not callable"
In this case, an attempt to fetch the *property* has worked
and returned None, rather than indicating it is really a method.
Calling: ob._FlagAsMethod("SomeFunc")
should then allow this to work.
"""
for name in methodNames:
details = build.MapEntry(self.__AttrToID__(name), (name,))
self._olerepr_.mapFuncs[name] = details
def __AttrToID__(self, attr):
debug_attr_print(
"Calling GetIDsOfNames for property %s in Dispatch container %s"
% (attr, self._username_)
)
return self._oleobj_.GetIDsOfNames(0, attr)
def __getattr__(self, attr):
if attr == "__iter__":
# We can't handle this as a normal method, as if the attribute
# exists, then it must return an iterable object.
try:
invkind = pythoncom.DISPATCH_METHOD | pythoncom.DISPATCH_PROPERTYGET
enum = self._oleobj_.InvokeTypes(
pythoncom.DISPID_NEWENUM, LCID, invkind, (13, 10), ()
)
except pythoncom.com_error:
raise AttributeError("This object can not function as an iterator")
# We must return a callable object.
class Factory:
def __init__(self, ob):
self.ob = ob
def __call__(self):
import win32com.client.util
return win32com.client.util.Iterator(self.ob)
return Factory(enum)
if attr.startswith("_") and attr.endswith("_"): # Fast-track.
raise AttributeError(attr)
# If a known method, create new instance and return.
try:
return MakeMethod(self._builtMethods_[attr], self, self.__class__)
except KeyError:
pass
# XXX - Note that we current are case sensitive in the method.
# debug_attr_print("GetAttr called for %s on DispatchContainer %s" % (attr,self._username_))
# First check if it is in the method map. Note that an actual method
# must not yet exist, (otherwise we would not be here). This
# means we create the actual method object - which also means
# this code will never be asked for that method name again.
if attr in self._olerepr_.mapFuncs:
return self._make_method_(attr)
# Delegate to property maps/cached items
retEntry = None
if self._olerepr_ and self._oleobj_:
# first check general property map, then specific "put" map.
retEntry = self._olerepr_.propMap.get(attr)
if retEntry is None:
retEntry = self._olerepr_.propMapGet.get(attr)
# Not found so far - See what COM says.
if retEntry is None:
try:
if self.__LazyMap__(attr):
if attr in self._olerepr_.mapFuncs:
return self._make_method_(attr)
retEntry = self._olerepr_.propMap.get(attr)
if retEntry is None:
retEntry = self._olerepr_.propMapGet.get(attr)
if retEntry is None:
retEntry = build.MapEntry(self.__AttrToID__(attr), (attr,))
except pythoncom.ole_error:
pass # No prop by that name - retEntry remains None.
if retEntry is not None: # see if in my cache
try:
ret = self._mapCachedItems_[retEntry.dispid]
debug_attr_print("Cached items has attribute!", ret)
return ret
except (KeyError, AttributeError):
debug_attr_print("Attribute %s not in cache" % attr)
# If we are still here, and have a retEntry, get the OLE item
if retEntry is not None:
invoke_type = _GetDescInvokeType(retEntry, pythoncom.INVOKE_PROPERTYGET)
debug_attr_print(
"Getting property Id 0x%x from OLE object" % retEntry.dispid
)
try:
ret = self._oleobj_.Invoke(retEntry.dispid, 0, invoke_type, 1)
except pythoncom.com_error as details:
if details.hresult in ERRORS_BAD_CONTEXT:
# May be a method.
self._olerepr_.mapFuncs[attr] = retEntry
return self._make_method_(attr)
raise
debug_attr_print("OLE returned ", ret)
return self._get_good_object_(ret)
# no where else to look.
raise AttributeError("%s.%s" % (self._username_, attr))
def __setattr__(self, attr, value):
if (
attr in self.__dict__
): # Fast-track - if already in our dict, just make the assignment.
# XXX - should maybe check method map - if someone assigns to a method,
# it could mean something special (not sure what, tho!)
self.__dict__[attr] = value
return
# Allow property assignment.
debug_attr_print(
"SetAttr called for %s.%s=%s on DispatchContainer"
% (self._username_, attr, repr(value))
)
if self._olerepr_:
# Check the "general" property map.
if attr in self._olerepr_.propMap:
entry = self._olerepr_.propMap[attr]
invoke_type = _GetDescInvokeType(entry, pythoncom.INVOKE_PROPERTYPUT)
self._oleobj_.Invoke(entry.dispid, 0, invoke_type, 0, value)
return
# Check the specific "put" map.
if attr in self._olerepr_.propMapPut:
entry = self._olerepr_.propMapPut[attr]
invoke_type = _GetDescInvokeType(entry, pythoncom.INVOKE_PROPERTYPUT)
self._oleobj_.Invoke(entry.dispid, 0, invoke_type, 0, value)
return
# Try the OLE Object
if self._oleobj_:
if self.__LazyMap__(attr):
# Check the "general" property map.
if attr in self._olerepr_.propMap:
entry = self._olerepr_.propMap[attr]
invoke_type = _GetDescInvokeType(
entry, pythoncom.INVOKE_PROPERTYPUT
)
self._oleobj_.Invoke(entry.dispid, 0, invoke_type, 0, value)
return
# Check the specific "put" map.
if attr in self._olerepr_.propMapPut:
entry = self._olerepr_.propMapPut[attr]
invoke_type = _GetDescInvokeType(
entry, pythoncom.INVOKE_PROPERTYPUT
)
self._oleobj_.Invoke(entry.dispid, 0, invoke_type, 0, value)
return
try:
entry = build.MapEntry(self.__AttrToID__(attr), (attr,))
except pythoncom.com_error:
# No attribute of that name
entry = None
if entry is not None:
try:
invoke_type = _GetDescInvokeType(
entry, pythoncom.INVOKE_PROPERTYPUT
)
self._oleobj_.Invoke(entry.dispid, 0, invoke_type, 0, value)
self._olerepr_.propMap[attr] = entry
debug_attr_print(
"__setattr__ property %s (id=0x%x) in Dispatch container %s"
% (attr, entry.dispid, self._username_)
)
return
except pythoncom.com_error:
pass
raise AttributeError(
"Property '%s.%s' can not be set." % (self._username_, attr)
)
The provided code snippet includes necessary dependencies for implementing the `DumbDispatch` function. Write a Python function `def DumbDispatch( IDispatch, userName=None, createClass=None, UnicodeToString=None, clsctx=pythoncom.CLSCTX_SERVER, )` to solve the following problem:
Dispatch with no type info
Here is the function:
def DumbDispatch(
IDispatch,
userName=None,
createClass=None,
UnicodeToString=None,
clsctx=pythoncom.CLSCTX_SERVER,
):
"Dispatch with no type info"
assert UnicodeToString is None, "this is deprecated and will go away"
IDispatch, userName = _GetGoodDispatchAndUserName(IDispatch, userName, clsctx)
if createClass is None:
createClass = CDispatch
return createClass(IDispatch, build.DispatchItem(), userName) | Dispatch with no type info |
172,788 | import pythoncom
from win32com.client import Dispatch, _get_good_object_
class EnumVARIANT(Enumerator):
def __init__(self, enum, resultCLSID=None):
self.resultCLSID = resultCLSID
Enumerator.__init__(self, enum)
def _make_retval_(self, result):
return _get_good_object_(result, resultCLSID=self.resultCLSID)
The provided code snippet includes necessary dependencies for implementing the `WrapEnum` function. Write a Python function `def WrapEnum(ob, resultCLSID=None)` to solve the following problem:
Wrap an object in a VARIANT enumerator. All VT_DISPATCHs returned by the enumerator are converted to wrapper objects (which may be either a class instance, or a dynamic.Dispatch type object).
Here is the function:
def WrapEnum(ob, resultCLSID=None):
"""Wrap an object in a VARIANT enumerator.
All VT_DISPATCHs returned by the enumerator are converted to wrapper objects
(which may be either a class instance, or a dynamic.Dispatch type object).
"""
if type(ob) != pythoncom.TypeIIDs[pythoncom.IID_IEnumVARIANT]:
ob = ob.QueryInterface(pythoncom.IID_IEnumVARIANT)
return EnumVARIANT(ob, resultCLSID) | Wrap an object in a VARIANT enumerator. All VT_DISPATCHs returned by the enumerator are converted to wrapper objects (which may be either a class instance, or a dynamic.Dispatch type object). |
172,789 | mapCLSIDToClass = {}
The provided code snippet includes necessary dependencies for implementing the `RegisterCLSID` function. Write a Python function `def RegisterCLSID(clsid, pythonClass)` to solve the following problem:
Register a class that wraps a CLSID This function allows a CLSID to be globally associated with a class. Certain module will automatically convert an IDispatch object to an instance of the associated class.
Here is the function:
def RegisterCLSID(clsid, pythonClass):
"""Register a class that wraps a CLSID
This function allows a CLSID to be globally associated with a class.
Certain module will automatically convert an IDispatch object to an
instance of the associated class.
"""
mapCLSIDToClass[str(clsid)] = pythonClass | Register a class that wraps a CLSID This function allows a CLSID to be globally associated with a class. Certain module will automatically convert an IDispatch object to an instance of the associated class. |
172,790 | mapCLSIDToClass = {}
The provided code snippet includes necessary dependencies for implementing the `RegisterCLSIDsFromDict` function. Write a Python function `def RegisterCLSIDsFromDict(dict)` to solve the following problem:
Register a dictionary of CLSID's and classes. This module performs the same function as @RegisterCLSID@, but for an entire dictionary of associations. Typically called by makepy generated modules at import time.
Here is the function:
def RegisterCLSIDsFromDict(dict):
"""Register a dictionary of CLSID's and classes.
This module performs the same function as @RegisterCLSID@, but for
an entire dictionary of associations.
Typically called by makepy generated modules at import time.
"""
mapCLSIDToClass.update(dict) | Register a dictionary of CLSID's and classes. This module performs the same function as @RegisterCLSID@, but for an entire dictionary of associations. Typically called by makepy generated modules at import time. |
172,791 | import os
import sys
import time
import pythoncom
import win32com
from . import build
def MakeDefaultArgsForPropertyPut(argsDesc):
ret = []
for desc in argsDesc[1:]:
default = build.MakeDefaultArgRepr(desc)
if default is None:
break
ret.append(default)
return tuple(ret) | null |
172,792 | import os
import sys
import time
import pythoncom
import win32com
from . import build
def MakeMapLineEntry(dispid, wFlags, retType, argTypes, user, resultCLSID):
# Strip the default value
argTypes = tuple([what[:2] for what in argTypes])
return '(%s, %d, %s, %s, "%s", %s)' % (
dispid,
wFlags,
retType[:2],
argTypes,
user,
resultCLSID,
) | null |
172,793 | import os
import sys
import time
import pythoncom
import win32com
from . import build
def MakeEventMethodName(eventName):
if eventName[:2] == "On":
return eventName
else:
return "On" + eventName
def WriteSinkEventMap(obj, stream):
print("\t_dispid_to_func_ = {", file=stream)
for name, entry in (
list(obj.propMapGet.items())
+ list(obj.propMapPut.items())
+ list(obj.mapFuncs.items())
):
fdesc = entry.desc
print(
'\t\t%9d : "%s",' % (fdesc.memid, MakeEventMethodName(entry.names[0])),
file=stream,
)
print("\t\t}", file=stream) | null |
172,794 | import os
import sys
import time
import pythoncom
import win32com
from . import build
def WriteAliasesForItem(item, aliasItems, stream):
for alias in aliasItems.values():
if item.doc and alias.aliasDoc and (alias.aliasDoc[0] == item.doc[0]):
alias.WriteAliasItem(aliasItems, stream) | null |
172,795 | usageHelp = """ \
Usage:
makepy.py [-i] [-v|q] [-h] [-u] [-o output_file] [-d] [typelib, ...]
-i -- Show information for the specified typelib.
-v -- Verbose output.
-q -- Quiet output.
-h -- Do not generate hidden methods.
-u -- Python 1.5 and earlier: Do NOT convert all Unicode objects to
strings.
Python 1.6 and later: Convert all Unicode objects to strings.
-o -- Create output in a specified output file. If the path leading
to the file does not exist, any missing directories will be
created.
NOTE: -o cannot be used with -d. This will generate an error.
-d -- Generate the base code now and the class code on demand.
Recommended for large type libraries.
typelib -- A TLB, DLL, OCX or anything containing COM type information.
If a typelib is not specified, a window containing a textbox
will open from which you can select a registered type
library.
Examples:
makepy.py -d
Presents a list of registered type libraries from which you can make
a selection.
makepy.py -d "Microsoft Excel 8.0 Object Library"
Generate support for the type library with the specified description
(in this case, the MS Excel object model).
"""
import importlib
import os
import sys
import pythoncom
from win32com.client import Dispatch, gencache, genpy, selecttlb
def usage():
sys.stderr.write(usageHelp)
sys.exit(2) | null |
172,796 | import importlib
import os
import sys
import pythoncom
from win32com.client import Dispatch, gencache, genpy, selecttlb
def GetTypeLibsForSpec(arg):
"""Given an argument on the command line (either a file name, library
description, or ProgID of an object) return a list of actual typelibs
to use."""
typelibs = []
try:
try:
tlb = pythoncom.LoadTypeLib(arg)
spec = selecttlb.TypelibSpec(None, 0, 0, 0)
spec.FromTypelib(tlb, arg)
typelibs.append((tlb, spec))
except pythoncom.com_error:
# See if it is a description
tlbs = selecttlb.FindTlbsWithDescription(arg)
if len(tlbs) == 0:
# Maybe it is the name of a COM object?
try:
ob = Dispatch(arg)
# and if so, it must support typelib info
tlb, index = ob._oleobj_.GetTypeInfo().GetContainingTypeLib()
spec = selecttlb.TypelibSpec(None, 0, 0, 0)
spec.FromTypelib(tlb)
tlbs.append(spec)
except pythoncom.com_error:
pass
if len(tlbs) == 0:
print("Could not locate a type library matching '%s'" % (arg))
for spec in tlbs:
# Version numbers not always reliable if enumerated from registry.
# (as some libs use hex, other's dont. Both examples from MS, of course.)
if spec.dll is None:
tlb = pythoncom.LoadRegTypeLib(
spec.clsid, spec.major, spec.minor, spec.lcid
)
else:
tlb = pythoncom.LoadTypeLib(spec.dll)
# We have a typelib, but it may not be exactly what we specified
# (due to automatic version matching of COM). So we query what we really have!
attr = tlb.GetLibAttr()
spec.major = attr[3]
spec.minor = attr[4]
spec.lcid = attr[1]
typelibs.append((tlb, spec))
return typelibs
except pythoncom.com_error:
t, v, tb = sys.exc_info()
sys.stderr.write("Unable to load type library from '%s' - %s\n" % (arg, v))
tb = None # Storing tb in a local is a cycle!
sys.exit(1)
def ShowInfo(spec):
if not spec:
tlbSpec = selecttlb.SelectTlb(excludeFlags=selecttlb.FLAG_HIDDEN)
if tlbSpec is None:
return
try:
tlb = pythoncom.LoadRegTypeLib(
tlbSpec.clsid, tlbSpec.major, tlbSpec.minor, tlbSpec.lcid
)
except pythoncom.com_error: # May be badly registered.
sys.stderr.write(
"Warning - could not load registered typelib '%s'\n" % (tlbSpec.clsid)
)
tlb = None
infos = [(tlb, tlbSpec)]
else:
infos = GetTypeLibsForSpec(spec)
for tlb, tlbSpec in infos:
desc = tlbSpec.desc
if desc is None:
if tlb is None:
desc = "<Could not load typelib %s>" % (tlbSpec.dll)
else:
desc = tlb.GetDocumentation(-1)[0]
print(desc)
print(
" %s, lcid=%s, major=%s, minor=%s"
% (tlbSpec.clsid, tlbSpec.lcid, tlbSpec.major, tlbSpec.minor)
)
print(" >>> # Use these commands in Python code to auto generate .py support")
print(" >>> from win32com.client import gencache")
print(
" >>> gencache.EnsureModule('%s', %s, %s, %s)"
% (tlbSpec.clsid, tlbSpec.lcid, tlbSpec.major, tlbSpec.minor)
) | null |
172,797 | import glob
import os
import sys
from importlib import reload
import pythoncom
import pywintypes
import win32com
import win32com.client
from . import CLSIDToClass
import pickle as pickle
def _LoadDicts():
# Load the dictionary from a .zip file if that is where we live.
if is_zip:
import io as io
loader = win32com.__loader__
arc_path = loader.archive
dicts_path = os.path.join(win32com.__gen_path__, "dicts.dat")
if dicts_path.startswith(arc_path):
dicts_path = dicts_path[len(arc_path) + 1 :]
else:
# Hm. See below.
return
try:
data = loader.get_data(dicts_path)
except AttributeError:
# The __loader__ has no get_data method. See below.
return
except IOError:
# Our gencache is in a .zip file (and almost certainly readonly)
# but no dicts file. That actually needn't be fatal for a frozen
# application. Assuming they call "EnsureModule" with the same
# typelib IDs they have been frozen with, that EnsureModule will
# correctly re-build the dicts on the fly. However, objects that
# rely on the gencache but have not done an EnsureModule will
# fail (but their apps are likely to fail running from source
# with a clean gencache anyway, as then they would be getting
# Dynamic objects until the cache is built - so the best answer
# for these apps is to call EnsureModule, rather than freezing
# the dict)
return
f = io.BytesIO(data)
else:
# NOTE: IOError on file open must be caught by caller.
f = open(os.path.join(win32com.__gen_path__, "dicts.dat"), "rb")
try:
p = pickle.Unpickler(f)
version = p.load()
global clsidToTypelib
clsidToTypelib = p.load()
versionRedirectMap.clear()
finally:
f.close()
def Rebuild(verbose=1):
"""Rebuild the cache indexes from the file system."""
clsidToTypelib.clear()
infos = GetGeneratedInfos()
if verbose and len(infos): # Dont bother reporting this when directory is empty!
print("Rebuilding cache of generated files for COM support...")
for info in infos:
iid, lcid, major, minor = info
if verbose:
print("Checking", GetGeneratedFileName(*info))
try:
AddModuleToCache(iid, lcid, major, minor, verbose, 0)
except:
print(
"Could not add module %s - %s: %s"
% (info, sys.exc_info()[0], sys.exc_info()[1])
)
if verbose and len(infos): # Dont bother reporting this when directory is empty!
print("Done.")
_SaveDicts()
def __init__():
# Initialize the module. Called once explicitly at module import below.
try:
_LoadDicts()
except IOError:
Rebuild() | null |
172,798 | import glob
import os
import sys
from importlib import reload
import pythoncom
import pywintypes
import win32com
import win32com.client
from . import CLSIDToClass
import pickle as pickle
The provided code snippet includes necessary dependencies for implementing the `SplitGeneratedFileName` function. Write a Python function `def SplitGeneratedFileName(fname)` to solve the following problem:
Reverse of GetGeneratedFileName()
Here is the function:
def SplitGeneratedFileName(fname):
"""Reverse of GetGeneratedFileName()"""
return tuple(fname.split("x", 4)) | Reverse of GetGeneratedFileName() |
172,799 | import glob
import os
import sys
from importlib import reload
import pythoncom
import pywintypes
import win32com
import win32com.client
from . import CLSIDToClass
import pickle as pickle
def GetClassForCLSID(clsid):
"""Get a Python class for a CLSID
Given a CLSID, return a Python class which wraps the COM object
Returns the Python class, or None if no module is available.
Params
clsid -- A COM CLSID (or string repr of one)
"""
# first, take a short-cut - we may already have generated support ready-to-roll.
clsid = str(clsid)
if CLSIDToClass.HasClass(clsid):
return CLSIDToClass.GetClass(clsid)
mod = GetModuleForCLSID(clsid)
if mod is None:
return None
try:
return CLSIDToClass.GetClass(clsid)
except KeyError:
return None
The provided code snippet includes necessary dependencies for implementing the `GetClassForProgID` function. Write a Python function `def GetClassForProgID(progid)` to solve the following problem:
Get a Python class for a Program ID Given a Program ID, return a Python class which wraps the COM object Returns the Python class, or None if no module is available. Params progid -- A COM ProgramID or IID (eg, "Word.Application")
Here is the function:
def GetClassForProgID(progid):
"""Get a Python class for a Program ID
Given a Program ID, return a Python class which wraps the COM object
Returns the Python class, or None if no module is available.
Params
progid -- A COM ProgramID or IID (eg, "Word.Application")
"""
clsid = pywintypes.IID(progid) # This auto-converts named to IDs.
return GetClassForCLSID(clsid) | Get a Python class for a Program ID Given a Program ID, return a Python class which wraps the COM object Returns the Python class, or None if no module is available. Params progid -- A COM ProgramID or IID (eg, "Word.Application") |
172,800 | import glob
import os
import sys
from importlib import reload
import pythoncom
import pywintypes
import win32com
import win32com.client
from . import CLSIDToClass
import pickle as pickle
def GetModuleForCLSID(clsid):
"""Get a Python module for a CLSID
Given a CLSID, return a Python module which contains the
class which wraps the COM object.
Returns the Python module, or None if no module is available.
Params
progid -- A COM CLSID (ie, not the description)
"""
clsid_str = str(clsid)
try:
typelibCLSID, lcid, major, minor = clsidToTypelib[clsid_str]
except KeyError:
return None
try:
mod = GetModuleForTypelib(typelibCLSID, lcid, major, minor)
except ImportError:
mod = None
if mod is not None:
sub_mod = mod.CLSIDToPackageMap.get(clsid_str)
if sub_mod is None:
sub_mod = mod.VTablesToPackageMap.get(clsid_str)
if sub_mod is not None:
sub_mod_name = mod.__name__ + "." + sub_mod
try:
__import__(sub_mod_name)
except ImportError:
info = typelibCLSID, lcid, major, minor
# Force the generation. If this typelibrary has explicitly been added,
# use it (it may not be registered, causing a lookup by clsid to fail)
if info in demandGeneratedTypeLibraries:
info = demandGeneratedTypeLibraries[info]
from . import makepy
makepy.GenerateChildFromTypeLibSpec(sub_mod, info)
# Generate does an import...
mod = sys.modules[sub_mod_name]
return mod
The provided code snippet includes necessary dependencies for implementing the `GetModuleForProgID` function. Write a Python function `def GetModuleForProgID(progid)` to solve the following problem:
Get a Python module for a Program ID Given a Program ID, return a Python module which contains the class which wraps the COM object. Returns the Python module, or None if no module is available. Params progid -- A COM ProgramID or IID (eg, "Word.Application")
Here is the function:
def GetModuleForProgID(progid):
"""Get a Python module for a Program ID
Given a Program ID, return a Python module which contains the
class which wraps the COM object.
Returns the Python module, or None if no module is available.
Params
progid -- A COM ProgramID or IID (eg, "Word.Application")
"""
try:
iid = pywintypes.IID(progid)
except pywintypes.com_error:
return None
return GetModuleForCLSID(iid) | Get a Python module for a Program ID Given a Program ID, return a Python module which contains the class which wraps the COM object. Returns the Python module, or None if no module is available. Params progid -- A COM ProgramID or IID (eg, "Word.Application") |
172,801 | import glob
import os
import sys
from importlib import reload
import pythoncom
import pywintypes
import win32com
import win32com.client
from . import CLSIDToClass
bForDemandDefault = 0
demandGeneratedTypeLibraries = {}
import pickle as pickle
def GetModuleForTypelib(typelibCLSID, lcid, major, minor):
"""Get a Python module for a type library ID
Given the CLSID of a typelibrary, return an imported Python module,
else None
Params
typelibCLSID -- IID of the type library.
major -- Integer major version.
minor -- Integer minor version
lcid -- Integer LCID for the library.
"""
modName = GetGeneratedFileName(typelibCLSID, lcid, major, minor)
mod = _GetModule(modName)
# If the import worked, it doesn't mean we have actually added this
# module to our cache though - check that here.
if "_in_gencache_" not in mod.__dict__:
AddModuleToCache(typelibCLSID, lcid, major, minor)
assert "_in_gencache_" in mod.__dict__
return mod
def MakeModuleForTypelibInterface(
typelib_ob, progressInstance=None, bForDemand=bForDemandDefault, bBuildHidden=1
):
"""Generate support for a type library.
Given a PyITypeLib interface generate and import the necessary support files. This is useful
for getting makepy support for a typelibrary that is not registered - the caller can locate
and load the type library itself, rather than relying on COM to find it.
Returns the Python module.
Params
typelib_ob -- The type library itself
progressInstance -- Instance to use as progress indicator, or None to
use the GUI progress bar.
"""
from . import makepy
try:
makepy.GenerateFromTypeLibSpec(
typelib_ob,
progressInstance=progressInstance,
bForDemand=bForDemandDefault,
bBuildHidden=bBuildHidden,
)
except pywintypes.com_error:
return None
tla = typelib_ob.GetLibAttr()
guid = tla[0]
lcid = tla[1]
major = tla[3]
minor = tla[4]
return GetModuleForTypelib(guid, lcid, major, minor)
The provided code snippet includes necessary dependencies for implementing the `EnsureModuleForTypelibInterface` function. Write a Python function `def EnsureModuleForTypelibInterface( typelib_ob, progressInstance=None, bForDemand=bForDemandDefault, bBuildHidden=1 )` to solve the following problem:
Check we have support for a type library, generating if not. Given a PyITypeLib interface generate and import the necessary support files if necessary. This is useful for getting makepy support for a typelibrary that is not registered - the caller can locate and load the type library itself, rather than relying on COM to find it. Returns the Python module. Params typelib_ob -- The type library itself progressInstance -- Instance to use as progress indicator, or None to use the GUI progress bar.
Here is the function:
def EnsureModuleForTypelibInterface(
typelib_ob, progressInstance=None, bForDemand=bForDemandDefault, bBuildHidden=1
):
"""Check we have support for a type library, generating if not.
Given a PyITypeLib interface generate and import the necessary
support files if necessary. This is useful for getting makepy support
for a typelibrary that is not registered - the caller can locate and
load the type library itself, rather than relying on COM to find it.
Returns the Python module.
Params
typelib_ob -- The type library itself
progressInstance -- Instance to use as progress indicator, or None to
use the GUI progress bar.
"""
tla = typelib_ob.GetLibAttr()
guid = tla[0]
lcid = tla[1]
major = tla[3]
minor = tla[4]
# If demand generated, save the typelib interface away for later use
if bForDemand:
demandGeneratedTypeLibraries[(str(guid), lcid, major, minor)] = typelib_ob
try:
return GetModuleForTypelib(guid, lcid, major, minor)
except ImportError:
pass
# Generate it.
return MakeModuleForTypelibInterface(
typelib_ob, progressInstance, bForDemand, bBuildHidden
) | Check we have support for a type library, generating if not. Given a PyITypeLib interface generate and import the necessary support files if necessary. This is useful for getting makepy support for a typelibrary that is not registered - the caller can locate and load the type library itself, rather than relying on COM to find it. Returns the Python module. Params typelib_ob -- The type library itself progressInstance -- Instance to use as progress indicator, or None to use the GUI progress bar. |
172,802 | import glob
import os
import sys
from importlib import reload
import pythoncom
import pywintypes
import win32com
import win32com.client
from . import CLSIDToClass
versionRedirectMap = {}
demandGeneratedTypeLibraries = {}
import pickle as pickle
The provided code snippet includes necessary dependencies for implementing the `ForgetAboutTypelibInterface` function. Write a Python function `def ForgetAboutTypelibInterface(typelib_ob)` to solve the following problem:
Drop any references to a typelib previously added with EnsureModuleForTypelibInterface and forDemand
Here is the function:
def ForgetAboutTypelibInterface(typelib_ob):
"""Drop any references to a typelib previously added with EnsureModuleForTypelibInterface and forDemand"""
tla = typelib_ob.GetLibAttr()
guid = tla[0]
lcid = tla[1]
major = tla[3]
minor = tla[4]
info = str(guid), lcid, major, minor
try:
del demandGeneratedTypeLibraries[info]
except KeyError:
# Not worth raising an exception - maybe they dont know we only remember for demand generated, etc.
print(
"ForgetAboutTypelibInterface:: Warning - type library with info %s is not being remembered!"
% (info,)
)
# and drop any version redirects to it
for key, val in list(versionRedirectMap.items()):
if val == info:
del versionRedirectMap[key] | Drop any references to a typelib previously added with EnsureModuleForTypelibInterface and forDemand |
172,803 | import glob
import os
import sys
from importlib import reload
import pythoncom
import pywintypes
import win32com
import win32com.client
from . import CLSIDToClass
import pickle as pickle
def GetModuleForCLSID(clsid):
"""Get a Python module for a CLSID
Given a CLSID, return a Python module which contains the
class which wraps the COM object.
Returns the Python module, or None if no module is available.
Params
progid -- A COM CLSID (ie, not the description)
"""
clsid_str = str(clsid)
try:
typelibCLSID, lcid, major, minor = clsidToTypelib[clsid_str]
except KeyError:
return None
try:
mod = GetModuleForTypelib(typelibCLSID, lcid, major, minor)
except ImportError:
mod = None
if mod is not None:
sub_mod = mod.CLSIDToPackageMap.get(clsid_str)
if sub_mod is None:
sub_mod = mod.VTablesToPackageMap.get(clsid_str)
if sub_mod is not None:
sub_mod_name = mod.__name__ + "." + sub_mod
try:
__import__(sub_mod_name)
except ImportError:
info = typelibCLSID, lcid, major, minor
# Force the generation. If this typelibrary has explicitly been added,
# use it (it may not be registered, causing a lookup by clsid to fail)
if info in demandGeneratedTypeLibraries:
info = demandGeneratedTypeLibraries[info]
from . import makepy
makepy.GenerateChildFromTypeLibSpec(sub_mod, info)
# Generate does an import...
mod = sys.modules[sub_mod_name]
return mod
def EnsureModule(
typelibCLSID,
lcid,
major,
minor,
progressInstance=None,
bValidateFile=not is_readonly,
bForDemand=bForDemandDefault,
bBuildHidden=1,
):
"""Ensure Python support is loaded for a type library, generating if necessary.
Given the IID, LCID and version information for a type library, check and if
necessary (re)generate, then import the necessary support files. If we regenerate the file, there
is no way to totally snuff out all instances of the old module in Python, and thus we will regenerate the file more than necessary,
unless makepy/genpy is modified accordingly.
Returns the Python module. No exceptions are caught during the generate process.
Params
typelibCLSID -- IID of the type library.
major -- Integer major version.
minor -- Integer minor version
lcid -- Integer LCID for the library.
progressInstance -- Instance to use as progress indicator, or None to
use the GUI progress bar.
bValidateFile -- Whether or not to perform cache validation or not
bForDemand -- Should a complete generation happen now, or on demand?
bBuildHidden -- Should hidden members/attributes etc be generated?
"""
bReloadNeeded = 0
try:
try:
module = GetModuleForTypelib(typelibCLSID, lcid, major, minor)
except ImportError:
# If we get an ImportError
# We may still find a valid cache file under a different MinorVersion #
# (which windows will search out for us)
# print "Loading reg typelib", typelibCLSID, major, minor, lcid
module = None
try:
tlbAttr = pythoncom.LoadRegTypeLib(
typelibCLSID, major, minor, lcid
).GetLibAttr()
# if the above line doesn't throw a pythoncom.com_error, check if
# it is actually a different lib than we requested, and if so, suck it in
if tlbAttr[1] != lcid or tlbAttr[4] != minor:
# print "Trying 2nd minor #", tlbAttr[1], tlbAttr[3], tlbAttr[4]
try:
module = GetModuleForTypelib(
typelibCLSID, tlbAttr[1], tlbAttr[3], tlbAttr[4]
)
except ImportError:
# We don't have a module, but we do have a better minor
# version - remember that.
minor = tlbAttr[4]
# else module remains None
except pythoncom.com_error:
# couldn't load any typelib - mod remains None
pass
if module is not None and bValidateFile:
assert not is_readonly, "Can't validate in a read-only gencache"
try:
typLibPath = pythoncom.QueryPathOfRegTypeLib(
typelibCLSID, major, minor, lcid
)
# windows seems to add an extra \0 (via the underlying BSTR)
# The mainwin toolkit does not add this erroneous \0
if typLibPath[-1] == "\0":
typLibPath = typLibPath[:-1]
suf = getattr(os.path, "supports_unicode_filenames", 0)
if not suf:
# can't pass unicode filenames directly - convert
try:
typLibPath = typLibPath.encode(sys.getfilesystemencoding())
except AttributeError: # no sys.getfilesystemencoding
typLibPath = str(typLibPath)
tlbAttributes = pythoncom.LoadRegTypeLib(
typelibCLSID, major, minor, lcid
).GetLibAttr()
except pythoncom.com_error:
# We have a module, but no type lib - we should still
# run with what we have though - the typelib may not be
# deployed here.
bValidateFile = 0
if module is not None and bValidateFile:
assert not is_readonly, "Can't validate in a read-only gencache"
filePathPrefix = "%s\\%s" % (
GetGeneratePath(),
GetGeneratedFileName(typelibCLSID, lcid, major, minor),
)
filePath = filePathPrefix + ".py"
filePathPyc = filePathPrefix + ".py"
if __debug__:
filePathPyc = filePathPyc + "c"
else:
filePathPyc = filePathPyc + "o"
# Verify that type library is up to date.
# If we have a differing MinorVersion or genpy has bumped versions, update the file
from . import genpy
if (
module.MinorVersion != tlbAttributes[4]
or genpy.makepy_version != module.makepy_version
):
# print "Version skew: %d, %d" % (module.MinorVersion, tlbAttributes[4])
# try to erase the bad file from the cache
try:
os.unlink(filePath)
except os.error:
pass
try:
os.unlink(filePathPyc)
except os.error:
pass
if os.path.isdir(filePathPrefix):
import shutil
shutil.rmtree(filePathPrefix)
minor = tlbAttributes[4]
module = None
bReloadNeeded = 1
else:
minor = module.MinorVersion
filePathPrefix = "%s\\%s" % (
GetGeneratePath(),
GetGeneratedFileName(typelibCLSID, lcid, major, minor),
)
filePath = filePathPrefix + ".py"
filePathPyc = filePathPrefix + ".pyc"
# print "Trying py stat: ", filePath
fModTimeSet = 0
try:
pyModTime = os.stat(filePath)[8]
fModTimeSet = 1
except os.error as e:
# If .py file fails, try .pyc file
# print "Trying pyc stat", filePathPyc
try:
pyModTime = os.stat(filePathPyc)[8]
fModTimeSet = 1
except os.error as e:
pass
# print "Trying stat typelib", pyModTime
# print str(typLibPath)
typLibModTime = os.stat(typLibPath)[8]
if fModTimeSet and (typLibModTime > pyModTime):
bReloadNeeded = 1
module = None
except (ImportError, os.error):
module = None
if module is None:
# We need to build an item. If we are in a read-only cache, we
# can't/don't want to do this - so before giving up, check for
# a different minor version in our cache - according to COM, this is OK
if is_readonly:
key = str(typelibCLSID), lcid, major, minor
# If we have been asked before, get last result.
try:
return versionRedirectMap[key]
except KeyError:
pass
# Find other candidates.
items = []
for desc in GetGeneratedInfos():
if key[0] == desc[0] and key[1] == desc[1] and key[2] == desc[2]:
items.append(desc)
if items:
# Items are all identical, except for last tuple element
# We want the latest minor version we have - so just sort and grab last
items.sort()
new_minor = items[-1][3]
ret = GetModuleForTypelib(typelibCLSID, lcid, major, new_minor)
else:
ret = None
# remember and return
versionRedirectMap[key] = ret
return ret
# print "Rebuilding: ", major, minor
module = MakeModuleForTypelib(
typelibCLSID,
lcid,
major,
minor,
progressInstance,
bForDemand=bForDemand,
bBuildHidden=bBuildHidden,
)
# If we replaced something, reload it
if bReloadNeeded:
module = reload(module)
AddModuleToCache(typelibCLSID, lcid, major, minor)
return module
The provided code snippet includes necessary dependencies for implementing the `EnsureDispatch` function. Write a Python function `def EnsureDispatch( prog_id, bForDemand=1 )` to solve the following problem:
Given a COM prog_id, return an object that is using makepy support, building if necessary
Here is the function:
def EnsureDispatch(
prog_id, bForDemand=1
): # New fn, so we default the new demand feature to on!
"""Given a COM prog_id, return an object that is using makepy support, building if necessary"""
disp = win32com.client.Dispatch(prog_id)
if not disp.__dict__.get("CLSID"): # Eeek - no makepy support - try and build it.
try:
ti = disp._oleobj_.GetTypeInfo()
disp_clsid = ti.GetTypeAttr()[0]
tlb, index = ti.GetContainingTypeLib()
tla = tlb.GetLibAttr()
mod = EnsureModule(tla[0], tla[1], tla[3], tla[4], bForDemand=bForDemand)
GetModuleForCLSID(disp_clsid)
# Get the class from the module.
from . import CLSIDToClass
disp_class = CLSIDToClass.GetClass(str(disp_clsid))
disp = disp_class(disp._oleobj_)
except pythoncom.com_error:
raise TypeError(
"This COM object can not automate the makepy process - please run makepy manually for this object"
)
return disp | Given a COM prog_id, return an object that is using makepy support, building if necessary |
172,804 | import glob
import os
import sys
from importlib import reload
import pythoncom
import pywintypes
import win32com
import win32com.client
from . import CLSIDToClass
clsidToTypelib = {}
import pickle as pickle
def GetModuleForTypelib(typelibCLSID, lcid, major, minor):
"""Get a Python module for a type library ID
Given the CLSID of a typelibrary, return an imported Python module,
else None
Params
typelibCLSID -- IID of the type library.
major -- Integer major version.
minor -- Integer minor version
lcid -- Integer LCID for the library.
"""
modName = GetGeneratedFileName(typelibCLSID, lcid, major, minor)
mod = _GetModule(modName)
# If the import worked, it doesn't mean we have actually added this
# module to our cache though - check that here.
if "_in_gencache_" not in mod.__dict__:
AddModuleToCache(typelibCLSID, lcid, major, minor)
assert "_in_gencache_" in mod.__dict__
return mod
def _Dump():
print("Cache is in directory", win32com.__gen_path__)
# Build a unique dir
d = {}
for clsid, (typelibCLSID, lcid, major, minor) in clsidToTypelib.items():
d[typelibCLSID, lcid, major, minor] = None
for typelibCLSID, lcid, major, minor in d.keys():
mod = GetModuleForTypelib(typelibCLSID, lcid, major, minor)
print("%s - %s" % (mod.__doc__, typelibCLSID)) | null |
172,805 | import datetime
import string
import sys
from keyword import iskeyword
import pythoncom
import winerror
from pywintypes import TimeType
def _makeDocString(s):
if sys.version_info < (3,):
s = s.encode("mbcs")
return repr(s) | null |
172,806 | import datetime
import string
import sys
from keyword import iskeyword
import pythoncom
import winerror
from pywintypes import TimeType
class NotSupportedException(Exception):
pass # Raised when we cant support a param type.
typeSubstMap = {
pythoncom.VT_INT: pythoncom.VT_I4,
pythoncom.VT_UINT: pythoncom.VT_UI4,
pythoncom.VT_HRESULT: pythoncom.VT_I4,
}
def _ResolveType(typerepr, itypeinfo):
# Resolve VT_USERDEFINED (often aliases or typed IDispatches)
if type(typerepr) == tuple:
indir_vt, subrepr = typerepr
if indir_vt == pythoncom.VT_PTR:
# If it is a VT_PTR to a VT_USERDEFINED that is an IDispatch/IUnknown,
# then it resolves to simply the object.
# Otherwise, it becomes a ByRef of the resolved type
# We need to drop an indirection level on pointer to user defined interfaces.
# eg, (VT_PTR, (VT_USERDEFINED, somehandle)) needs to become VT_DISPATCH
# only when "somehandle" is an object.
# but (VT_PTR, (VT_USERDEFINED, otherhandle)) doesnt get the indirection dropped.
was_user = type(subrepr) == tuple and subrepr[0] == pythoncom.VT_USERDEFINED
subrepr, sub_clsid, sub_doc = _ResolveType(subrepr, itypeinfo)
if was_user and subrepr in [
pythoncom.VT_DISPATCH,
pythoncom.VT_UNKNOWN,
pythoncom.VT_RECORD,
]:
# Drop the VT_PTR indirection
return subrepr, sub_clsid, sub_doc
# Change PTR indirection to byref
return subrepr | pythoncom.VT_BYREF, sub_clsid, sub_doc
if indir_vt == pythoncom.VT_SAFEARRAY:
# resolve the array element, and convert to VT_ARRAY
subrepr, sub_clsid, sub_doc = _ResolveType(subrepr, itypeinfo)
return pythoncom.VT_ARRAY | subrepr, sub_clsid, sub_doc
if indir_vt == pythoncom.VT_CARRAY: # runtime has no support for this yet.
# resolve the array element, and convert to VT_CARRAY
# sheesh - return _something_
return pythoncom.VT_CARRAY, None, None
if indir_vt == pythoncom.VT_USERDEFINED:
try:
resultTypeInfo = itypeinfo.GetRefTypeInfo(subrepr)
except pythoncom.com_error as details:
if details.hresult in [
winerror.TYPE_E_CANTLOADLIBRARY,
winerror.TYPE_E_LIBNOTREGISTERED,
]:
# an unregistered interface
return pythoncom.VT_UNKNOWN, None, None
raise
resultAttr = resultTypeInfo.GetTypeAttr()
typeKind = resultAttr.typekind
if typeKind == pythoncom.TKIND_ALIAS:
tdesc = resultAttr.tdescAlias
return _ResolveType(tdesc, resultTypeInfo)
elif typeKind in [pythoncom.TKIND_ENUM, pythoncom.TKIND_MODULE]:
# For now, assume Long
return pythoncom.VT_I4, None, None
elif typeKind == pythoncom.TKIND_DISPATCH:
clsid = resultTypeInfo.GetTypeAttr()[0]
retdoc = resultTypeInfo.GetDocumentation(-1)
return pythoncom.VT_DISPATCH, clsid, retdoc
elif typeKind in [pythoncom.TKIND_INTERFACE, pythoncom.TKIND_COCLASS]:
# XXX - should probably get default interface for CO_CLASS???
clsid = resultTypeInfo.GetTypeAttr()[0]
retdoc = resultTypeInfo.GetDocumentation(-1)
return pythoncom.VT_UNKNOWN, clsid, retdoc
elif typeKind == pythoncom.TKIND_RECORD:
return pythoncom.VT_RECORD, None, None
raise NotSupportedException("Can not resolve alias or user-defined type")
return typeSubstMap.get(typerepr, typerepr), None, None | null |
172,807 | import datetime
import string
import sys
from keyword import iskeyword
import pythoncom
import winerror
from pywintypes import TimeType
def MakePublicAttributeName(className, is_global=False):
# Given a class attribute that needs to be public, convert it to a
# reasonable name.
# Also need to be careful that the munging doesnt
# create duplicates - eg, just removing a leading "_" is likely to cause
# a clash.
# if is_global is True, then the name is a global variable that may
# overwrite a builtin - eg, "None"
if className[:2] == "__":
return demunge_leading_underscores(className)
elif className == "None":
# assign to None is evil (and SyntaxError in 2.4, even though
# iskeyword says False there) - note that if it was a global
# it would get picked up below
className = "NONE"
elif iskeyword(className):
# most keywords are lower case (except True, False etc in py3k)
ret = className.capitalize()
# but those which aren't get forced upper.
if ret == className:
ret = ret.upper()
return ret
elif is_global and hasattr(__builtins__, className):
# builtins may be mixed case. If capitalizing it doesn't change it,
# force to all uppercase (eg, "None", "True" become "NONE", "TRUE"
ret = className.capitalize()
if ret == className: # didn't change - force all uppercase.
ret = ret.upper()
return ret
# Strip non printable chars
return "".join([char for char in className if char in valid_identifier_chars])
The provided code snippet includes necessary dependencies for implementing the `_BuildArgList` function. Write a Python function `def _BuildArgList(fdesc, names)` to solve the following problem:
Builds list of args to the underlying Invoke method.
Here is the function:
def _BuildArgList(fdesc, names):
"Builds list of args to the underlying Invoke method."
# Word has TypeInfo for Insert() method, but says "no args"
numArgs = max(fdesc[6], len(fdesc[2]))
names = list(names)
while None in names:
i = names.index(None)
names[i] = "arg%d" % (i,)
# We've seen 'source safe' libraries offer the name of 'ret' params in
# 'names' - although we can't reproduce this, it would be insane to offer
# more args than we have arg infos for - hence the upper limit on names...
names = list(map(MakePublicAttributeName, names[1 : (numArgs + 1)]))
name_num = 0
while len(names) < numArgs:
names.append("arg%d" % (len(names),))
# As per BuildCallList(), avoid huge lines.
# Hack a "\n" at the end of every 5th name - "strides" would be handy
# here but don't exist in 2.2
for i in range(0, len(names), 5):
names[i] = names[i] + "\n\t\t\t"
return "," + ", ".join(names) | Builds list of args to the underlying Invoke method. |
172,808 | import datetime
import string
import sys
from keyword import iskeyword
import pythoncom
import winerror
from pywintypes import TimeType
def MakePublicAttributeName(className, is_global=False):
# Given a class attribute that needs to be public, convert it to a
# reasonable name.
# Also need to be careful that the munging doesnt
# create duplicates - eg, just removing a leading "_" is likely to cause
# a clash.
# if is_global is True, then the name is a global variable that may
# overwrite a builtin - eg, "None"
if className[:2] == "__":
return demunge_leading_underscores(className)
elif className == "None":
# assign to None is evil (and SyntaxError in 2.4, even though
# iskeyword says False there) - note that if it was a global
# it would get picked up below
className = "NONE"
elif iskeyword(className):
# most keywords are lower case (except True, False etc in py3k)
ret = className.capitalize()
# but those which aren't get forced upper.
if ret == className:
ret = ret.upper()
return ret
elif is_global and hasattr(__builtins__, className):
# builtins may be mixed case. If capitalizing it doesn't change it,
# force to all uppercase (eg, "None", "True" become "NONE", "TRUE"
ret = className.capitalize()
if ret == className: # didn't change - force all uppercase.
ret = ret.upper()
return ret
# Strip non printable chars
return "".join([char for char in className if char in valid_identifier_chars])
def MakeDefaultArgRepr(defArgVal):
try:
inOut = defArgVal[1]
except IndexError:
# something strange - assume is in param.
inOut = pythoncom.PARAMFLAG_FIN
if inOut & pythoncom.PARAMFLAG_FHASDEFAULT:
# times need special handling...
val = defArgVal[2]
if isinstance(val, datetime.datetime):
# VARIANT <-> SYSTEMTIME conversions always lose any sub-second
# resolution, so just use a 'timetuple' here.
return repr(tuple(val.utctimetuple()))
if type(val) is TimeType:
# must be the 'old' pywintypes time object...
year = val.year
month = val.month
day = val.day
hour = val.hour
minute = val.minute
second = val.second
msec = val.msec
return (
"pywintypes.Time((%(year)d, %(month)d, %(day)d, %(hour)d, %(minute)d, %(second)d,0,0,0,%(msec)d))"
% locals()
)
return repr(val)
return None
The provided code snippet includes necessary dependencies for implementing the `BuildCallList` function. Write a Python function `def BuildCallList( fdesc, names, defNamedOptArg, defNamedNotOptArg, defUnnamedArg, defOutArg, is_comment=False, )` to solve the following problem:
Builds a Python declaration for a method.
Here is the function:
def BuildCallList(
fdesc,
names,
defNamedOptArg,
defNamedNotOptArg,
defUnnamedArg,
defOutArg,
is_comment=False,
):
"Builds a Python declaration for a method."
# Names[0] is the func name - param names are from 1.
numArgs = len(fdesc[2])
numOptArgs = fdesc[6]
strval = ""
if numOptArgs == -1: # Special value that says "var args after here"
firstOptArg = numArgs
numArgs = numArgs - 1
else:
firstOptArg = numArgs - numOptArgs
for arg in range(numArgs):
try:
argName = names[arg + 1]
namedArg = argName is not None
except IndexError:
namedArg = 0
if not namedArg:
argName = "arg%d" % (arg)
thisdesc = fdesc[2][arg]
# See if the IDL specified a default value
defArgVal = MakeDefaultArgRepr(thisdesc)
if defArgVal is None:
# Out params always get their special default
if (
thisdesc[1] & (pythoncom.PARAMFLAG_FOUT | pythoncom.PARAMFLAG_FIN)
== pythoncom.PARAMFLAG_FOUT
):
defArgVal = defOutArg
else:
# Unnamed arg - always allow default values.
if namedArg:
# Is a named argument
if arg >= firstOptArg:
defArgVal = defNamedOptArg
else:
defArgVal = defNamedNotOptArg
else:
defArgVal = defUnnamedArg
argName = MakePublicAttributeName(argName)
# insanely long lines with an 'encoding' flag crashes python 2.4.0
# keep 5 args per line
# This may still fail if the arg names are insane, but that seems
# unlikely. See also _BuildArgList()
if (arg + 1) % 5 == 0:
strval = strval + "\n"
if is_comment:
strval = strval + "#"
strval = strval + "\t\t\t"
strval = strval + ", " + argName
if defArgVal:
strval = strval + "=" + defArgVal
if numOptArgs == -1:
strval = strval + ", *" + names[-1]
return strval | Builds a Python declaration for a method. |
172,809 | import logging
import json
import re
from datetime import date, datetime, time, timezone
import traceback
import importlib
from typing import Any, Dict, Optional, Union, List, Tuple
from inspect import istraceback
from collections import OrderedDict
Union: _SpecialForm = ...
Optional: _SpecialForm = ...
List = _Alias()
Dict = _Alias()
The provided code snippet includes necessary dependencies for implementing the `merge_record_extra` function. Write a Python function `def merge_record_extra( record: logging.LogRecord, target: Dict, reserved: Union[Dict, List], rename_fields: Optional[Dict[str,str]] = None, ) -> Dict` to solve the following problem:
Merges extra attributes from LogRecord object into target dictionary :param record: logging.LogRecord :param target: dict to update :param reserved: dict or list with reserved keys to skip :param rename_fields: an optional dict, used to rename field names in the output. Rename levelname to log.level: {'levelname': 'log.level'}
Here is the function:
def merge_record_extra(
record: logging.LogRecord,
target: Dict,
reserved: Union[Dict, List],
rename_fields: Optional[Dict[str,str]] = None,
) -> Dict:
"""
Merges extra attributes from LogRecord object into target dictionary
:param record: logging.LogRecord
:param target: dict to update
:param reserved: dict or list with reserved keys to skip
:param rename_fields: an optional dict, used to rename field names in the output.
Rename levelname to log.level: {'levelname': 'log.level'}
"""
if rename_fields is None:
rename_fields = {}
for key, value in record.__dict__.items():
# this allows to have numeric keys
if (key not in reserved
and not (hasattr(key, "startswith")
and key.startswith('_'))):
target[rename_fields.get(key,key)] = value
return target | Merges extra attributes from LogRecord object into target dictionary :param record: logging.LogRecord :param target: dict to update :param reserved: dict or list with reserved keys to skip :param rename_fields: an optional dict, used to rename field names in the output. Rename levelname to log.level: {'levelname': 'log.level'} |
172,810 | import codecs
import os
import shlex
import signal
import socket
import subprocess
import threading
import time
from shutil import which
from .winpty import PTY
The provided code snippet includes necessary dependencies for implementing the `_read_in_thread` function. Write a Python function `def _read_in_thread(address, pty, blocking)` to solve the following problem:
Read data from the pty in a thread.
Here is the function:
def _read_in_thread(address, pty, blocking):
"""Read data from the pty in a thread.
"""
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(address)
call = 0
while 1:
try:
data = pty.read(4096, blocking=blocking) or b'0011Ignore'
try:
client.send(bytes(data, 'utf-8'))
except socket.error:
break
# Handle end of file.
if pty.iseof():
try:
client.send(b'')
except socket.error:
pass
finally:
break
call += 1
except Exception as e:
break
time.sleep(1e-3)
client.close() | Read data from the pty in a thread. |
172,811 | import re
from typing import Match, Tuple, Union, cast
from zmq.backend import zmq_version_info
__version__: str = "25.0.2"
__revision__: str = ''
The provided code snippet includes necessary dependencies for implementing the `pyzmq_version` function. Write a Python function `def pyzmq_version() -> str` to solve the following problem:
return the version of pyzmq as a string
Here is the function:
def pyzmq_version() -> str:
"""return the version of pyzmq as a string"""
if __revision__:
return '+'.join([__version__, __revision__[:6]])
else:
return __version__ | return the version of pyzmq as a string |
172,812 | import re
from typing import Match, Tuple, Union, cast
from zmq.backend import zmq_version_info
version_info: Union[Tuple[int, int, int], Tuple[int, int, int, float]] = (
VERSION_MAJOR,
VERSION_MINOR,
VERSION_PATCH,
)
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
Union: _SpecialForm = ...
The provided code snippet includes necessary dependencies for implementing the `pyzmq_version_info` function. Write a Python function `def pyzmq_version_info() -> Union[Tuple[int, int, int], Tuple[int, int, int, float]]` to solve the following problem:
return the pyzmq version as a tuple of at least three numbers If pyzmq is a development version, `inf` will be appended after the third integer.
Here is the function:
def pyzmq_version_info() -> Union[Tuple[int, int, int], Tuple[int, int, int, float]]:
"""return the pyzmq version as a tuple of at least three numbers
If pyzmq is a development version, `inf` will be appended after the third integer.
"""
return version_info | return the pyzmq version as a tuple of at least three numbers If pyzmq is a development version, `inf` will be appended after the third integer. |
172,813 | import re
from typing import Match, Tuple, Union, cast
from zmq.backend import zmq_version_info
The provided code snippet includes necessary dependencies for implementing the `zmq_version` function. Write a Python function `def zmq_version() -> str` to solve the following problem:
return the version of libzmq as a string
Here is the function:
def zmq_version() -> str:
"""return the version of libzmq as a string"""
return "%i.%i.%i" % zmq_version_info() | return the version of libzmq as a string |
172,814 | import zmq
from zmq.backend import Frame as FrameBase
from .attrsettr import AttributeSetter
def _draft(v, feature):
zmq.error._check_version(v, feature)
if not zmq.DRAFT_API:
raise RuntimeError(
"libzmq and pyzmq must be built with draft support for %s" % feature
) | null |
172,815 | from typing import Any, Dict, List, Optional, Tuple
from zmq.backend import zmq_poll
from zmq.constants import POLLERR, POLLIN, POLLOUT
Optional: _SpecialForm = ...
List = _Alias()
POLLIN: int = PollEvent.POLLIN
POLLOUT: int = PollEvent.POLLOUT
POLLERR: int = PollEvent.POLLERR
The provided code snippet includes necessary dependencies for implementing the `select` function. Write a Python function `def select(rlist: List, wlist: List, xlist: List, timeout: Optional[float] = None)` to solve the following problem:
select(rlist, wlist, xlist, timeout=None) -> (rlist, wlist, xlist) Return the result of poll as a lists of sockets ready for r/w/exception. This has the same interface as Python's built-in ``select.select()`` function. Parameters ---------- timeout : float, int, optional The timeout in seconds. If None, no timeout (infinite). This is in seconds to be compatible with ``select.select()``. rlist : list of sockets/FDs sockets/FDs to be polled for read events wlist : list of sockets/FDs sockets/FDs to be polled for write events xlist : list of sockets/FDs sockets/FDs to be polled for error events Returns ------- (rlist, wlist, xlist) : tuple of lists of sockets (length 3) Lists correspond to sockets available for read/write/error events respectively.
Here is the function:
def select(rlist: List, wlist: List, xlist: List, timeout: Optional[float] = None):
"""select(rlist, wlist, xlist, timeout=None) -> (rlist, wlist, xlist)
Return the result of poll as a lists of sockets ready for r/w/exception.
This has the same interface as Python's built-in ``select.select()`` function.
Parameters
----------
timeout : float, int, optional
The timeout in seconds. If None, no timeout (infinite). This is in seconds to be
compatible with ``select.select()``.
rlist : list of sockets/FDs
sockets/FDs to be polled for read events
wlist : list of sockets/FDs
sockets/FDs to be polled for write events
xlist : list of sockets/FDs
sockets/FDs to be polled for error events
Returns
-------
(rlist, wlist, xlist) : tuple of lists of sockets (length 3)
Lists correspond to sockets available for read/write/error events respectively.
"""
if timeout is None:
timeout = -1
# Convert from sec -> ms for zmq_poll.
# zmq_poll accepts 3.x style timeout in ms
timeout = int(timeout * 1000.0)
if timeout < 0:
timeout = -1
sockets = []
for s in set(rlist + wlist + xlist):
flags = 0
if s in rlist:
flags |= POLLIN
if s in wlist:
flags |= POLLOUT
if s in xlist:
flags |= POLLERR
sockets.append((s, flags))
return_sockets = zmq_poll(sockets, timeout)
rlist, wlist, xlist = [], [], []
for s, flags in return_sockets:
if flags & POLLIN:
rlist.append(s)
if flags & POLLOUT:
wlist.append(s)
if flags & POLLERR:
xlist.append(s)
return rlist, wlist, xlist | select(rlist, wlist, xlist, timeout=None) -> (rlist, wlist, xlist) Return the result of poll as a lists of sockets ready for r/w/exception. This has the same interface as Python's built-in ``select.select()`` function. Parameters ---------- timeout : float, int, optional The timeout in seconds. If None, no timeout (infinite). This is in seconds to be compatible with ``select.select()``. rlist : list of sockets/FDs sockets/FDs to be polled for read events wlist : list of sockets/FDs sockets/FDs to be polled for write events xlist : list of sockets/FDs sockets/FDs to be polled for error events Returns ------- (rlist, wlist, xlist) : tuple of lists of sockets (length 3) Lists correspond to sockets available for read/write/error events respectively. |
172,816 | import atexit
import os
from threading import Lock
from typing import (
Any,
Callable,
Dict,
Generic,
List,
Optional,
Type,
TypeVar,
Union,
overload,
)
from warnings import warn
from weakref import WeakSet
from zmq.backend import Context as ContextBase
from zmq.constants import ContextOption, Errno, SocketOption
from zmq.error import ZMQError
from zmq.utils.interop import cast_int_addr
from .attrsettr import AttributeSetter, OptValT
from .socket import Socket
_exiting = False
def _notice_atexit() -> None:
global _exiting
_exiting = True | null |
172,817 | import atexit
import os
import re
import signal
import socket
import sys
import warnings
from getpass import getpass, getuser
from multiprocessing import Process
def _try_passwordless_openssh(server, keyfile):
"""Try passwordless login with shell ssh command."""
if pexpect is None:
raise ImportError("pexpect unavailable, use paramiko")
cmd = 'ssh -f ' + server
if keyfile:
cmd += ' -i ' + keyfile
cmd += ' exit'
# pop SSH_ASKPASS from env
env = os.environ.copy()
env.pop('SSH_ASKPASS', None)
ssh_newkey = 'Are you sure you want to continue connecting'
p = pexpect.spawn(cmd, env=env)
while True:
try:
i = p.expect([ssh_newkey, _password_pat], timeout=0.1)
if i == 0:
raise SSHException(
'The authenticity of the host can\'t be established.'
)
except pexpect.TIMEOUT:
continue
except pexpect.EOF:
return True
else:
return False
def _try_passwordless_paramiko(server, keyfile):
"""Try passwordless login with paramiko."""
if paramiko is None:
msg = "Paramiko unavailable, "
if sys.platform == 'win32':
msg += "Paramiko is required for ssh tunneled connections on Windows."
else:
msg += "use OpenSSH."
raise ImportError(msg)
username, server, port = _split_server(server)
client = paramiko.SSHClient()
known_hosts = os.path.expanduser("~/.ssh/known_hosts")
try:
client.load_host_keys(known_hosts)
except FileNotFoundError:
pass
policy_name = os.environ.get("PYZMQ_PARAMIKO_HOST_KEY_POLICY", None)
if policy_name:
policy = getattr(paramiko, f"{policy_name}Policy")
client.set_missing_host_key_policy(policy())
try:
client.connect(
server, port, username=username, key_filename=keyfile, look_for_keys=True
)
except paramiko.AuthenticationException:
return False
else:
client.close()
return True
if sys.platform == 'win32':
ssh_tunnel = paramiko_tunnel
else:
ssh_tunnel = openssh_tunnel
The provided code snippet includes necessary dependencies for implementing the `try_passwordless_ssh` function. Write a Python function `def try_passwordless_ssh(server, keyfile, paramiko=None)` to solve the following problem:
Attempt to make an ssh connection without a password. This is mainly used for requiring password input only once when many tunnels may be connected to the same server. If paramiko is None, the default for the platform is chosen.
Here is the function:
def try_passwordless_ssh(server, keyfile, paramiko=None):
"""Attempt to make an ssh connection without a password.
This is mainly used for requiring password input only once
when many tunnels may be connected to the same server.
If paramiko is None, the default for the platform is chosen.
"""
if paramiko is None:
paramiko = sys.platform == 'win32'
if not paramiko:
f = _try_passwordless_openssh
else:
f = _try_passwordless_paramiko
return f(server, keyfile) | Attempt to make an ssh connection without a password. This is mainly used for requiring password input only once when many tunnels may be connected to the same server. If paramiko is None, the default for the platform is chosen. |
172,818 | import atexit
import os
import re
import signal
import socket
import sys
import warnings
from getpass import getpass, getuser
from multiprocessing import Process
def open_tunnel(addr, server, keyfile=None, password=None, paramiko=None, timeout=60):
"""Open a tunneled connection from a 0MQ url.
For use inside tunnel_connection.
Returns
-------
(url, tunnel) : (str, object)
The 0MQ url that has been forwarded, and the tunnel object
"""
lport = select_random_ports(1)[0]
transport, addr = addr.split('://')
ip, rport = addr.split(':')
rport = int(rport)
if paramiko is None:
paramiko = sys.platform == 'win32'
if paramiko:
tunnelf = paramiko_tunnel
else:
tunnelf = openssh_tunnel
tunnel = tunnelf(
lport,
rport,
server,
remoteip=ip,
keyfile=keyfile,
password=password,
timeout=timeout,
)
return 'tcp://127.0.0.1:%i' % lport, tunnel
The provided code snippet includes necessary dependencies for implementing the `tunnel_connection` function. Write a Python function `def tunnel_connection( socket, addr, server, keyfile=None, password=None, paramiko=None, timeout=60 )` to solve the following problem:
Connect a socket to an address via an ssh tunnel. This is a wrapper for socket.connect(addr), when addr is not accessible from the local machine. It simply creates an ssh tunnel using the remaining args, and calls socket.connect('tcp://localhost:lport') where lport is the randomly selected local port of the tunnel.
Here is the function:
def tunnel_connection(
socket, addr, server, keyfile=None, password=None, paramiko=None, timeout=60
):
"""Connect a socket to an address via an ssh tunnel.
This is a wrapper for socket.connect(addr), when addr is not accessible
from the local machine. It simply creates an ssh tunnel using the remaining args,
and calls socket.connect('tcp://localhost:lport') where lport is the randomly
selected local port of the tunnel.
"""
new_url, tunnel = open_tunnel(
addr,
server,
keyfile=keyfile,
password=password,
paramiko=paramiko,
timeout=timeout,
)
socket.connect(new_url)
return tunnel | Connect a socket to an address via an ssh tunnel. This is a wrapper for socket.connect(addr), when addr is not accessible from the local machine. It simply creates an ssh tunnel using the remaining args, and calls socket.connect('tcp://localhost:lport') where lport is the randomly selected local port of the tunnel. |
172,819 | import asyncio
import selectors
import sys
import warnings
from asyncio import Future, SelectorEventLoop
from weakref import WeakKeyDictionary
import zmq as _zmq
from zmq import _future
_selectors: WeakKeyDictionary = WeakKeyDictionary()
import asyncio
from asyncio import Future, SelectorEventLoop
class AddThreadSelectorEventLoop(asyncio.AbstractEventLoop):
"""Wrap an event loop to add implementations of the ``add_reader`` method family.
Instances of this class start a second thread to run a selector.
This thread is completely hidden from the user; all callbacks are
run on the wrapped event loop's thread.
This class is used automatically by Tornado; applications should not need
to refer to it directly.
It is safe to wrap any event loop with this class, although it only makes sense
for event loops that do not implement the ``add_reader`` family of methods
themselves (i.e. ``WindowsProactorEventLoop``)
Closing the ``AddThreadSelectorEventLoop`` also closes the wrapped event loop.
"""
# This class is a __getattribute__-based proxy. All attributes other than those
# in this set are proxied through to the underlying loop.
MY_ATTRIBUTES = {
"_consume_waker",
"_select_cond",
"_select_args",
"_closing_selector",
"_thread",
"_handle_event",
"_readers",
"_real_loop",
"_start_select",
"_run_select",
"_handle_select",
"_wake_selector",
"_waker_r",
"_waker_w",
"_writers",
"add_reader",
"add_writer",
"close",
"remove_reader",
"remove_writer",
}
def __getattribute__(self, name: str) -> Any:
if name in AddThreadSelectorEventLoop.MY_ATTRIBUTES:
return super().__getattribute__(name)
return getattr(self._real_loop, name)
def __init__(self, real_loop: asyncio.AbstractEventLoop) -> None:
self._real_loop = real_loop
# Create a thread to run the select system call. We manage this thread
# manually so we can trigger a clean shutdown from an atexit hook. Note
# that due to the order of operations at shutdown, only daemon threads
# can be shut down in this way (non-daemon threads would require the
# introduction of a new hook: https://bugs.python.org/issue41962)
self._select_cond = threading.Condition()
self._select_args = (
None
) # type: Optional[Tuple[List[_FileDescriptorLike], List[_FileDescriptorLike]]]
self._closing_selector = False
self._thread = threading.Thread(
name="Tornado selector",
daemon=True,
target=self._run_select,
)
self._thread.start()
# Start the select loop once the loop is started.
self._real_loop.call_soon(self._start_select)
self._readers = {} # type: Dict[_FileDescriptorLike, Callable]
self._writers = {} # type: Dict[_FileDescriptorLike, Callable]
# Writing to _waker_w will wake up the selector thread, which
# watches for _waker_r to be readable.
self._waker_r, self._waker_w = socket.socketpair()
self._waker_r.setblocking(False)
self._waker_w.setblocking(False)
_selector_loops.add(self)
self.add_reader(self._waker_r, self._consume_waker)
def __del__(self) -> None:
# If the top-level application code uses asyncio interfaces to
# start and stop the event loop, no objects created in Tornado
# can get a clean shutdown notification. If we're just left to
# be GC'd, we must explicitly close our sockets to avoid
# logging warnings.
_selector_loops.discard(self)
self._waker_r.close()
self._waker_w.close()
def close(self) -> None:
with self._select_cond:
self._closing_selector = True
self._select_cond.notify()
self._wake_selector()
self._thread.join()
_selector_loops.discard(self)
self._waker_r.close()
self._waker_w.close()
self._real_loop.close()
def _wake_selector(self) -> None:
try:
self._waker_w.send(b"a")
except BlockingIOError:
pass
def _consume_waker(self) -> None:
try:
self._waker_r.recv(1024)
except BlockingIOError:
pass
def _start_select(self) -> None:
# Capture reader and writer sets here in the event loop
# thread to avoid any problems with concurrent
# modification while the select loop uses them.
with self._select_cond:
assert self._select_args is None
self._select_args = (list(self._readers.keys()), list(self._writers.keys()))
self._select_cond.notify()
def _run_select(self) -> None:
while True:
with self._select_cond:
while self._select_args is None and not self._closing_selector:
self._select_cond.wait()
if self._closing_selector:
return
assert self._select_args is not None
to_read, to_write = self._select_args
self._select_args = None
# We use the simpler interface of the select module instead of
# the more stateful interface in the selectors module because
# this class is only intended for use on windows, where
# select.select is the only option. The selector interface
# does not have well-documented thread-safety semantics that
# we can rely on so ensuring proper synchronization would be
# tricky.
try:
# On windows, selecting on a socket for write will not
# return the socket when there is an error (but selecting
# for reads works). Also select for errors when selecting
# for writes, and merge the results.
#
# This pattern is also used in
# https://github.com/python/cpython/blob/v3.8.0/Lib/selectors.py#L312-L317
rs, ws, xs = select.select(to_read, to_write, to_write)
ws = ws + xs
except OSError as e:
# After remove_reader or remove_writer is called, the file
# descriptor may subsequently be closed on the event loop
# thread. It's possible that this select thread hasn't
# gotten into the select system call by the time that
# happens in which case (at least on macOS), select may
# raise a "bad file descriptor" error. If we get that
# error, check and see if we're also being woken up by
# polling the waker alone. If we are, just return to the
# event loop and we'll get the updated set of file
# descriptors on the next iteration. Otherwise, raise the
# original error.
if e.errno == getattr(errno, "WSAENOTSOCK", errno.EBADF):
rs, _, _ = select.select([self._waker_r.fileno()], [], [], 0)
if rs:
ws = []
else:
raise
else:
raise
try:
self._real_loop.call_soon_threadsafe(self._handle_select, rs, ws)
except RuntimeError:
# "Event loop is closed". Swallow the exception for
# consistency with PollIOLoop (and logical consistency
# with the fact that we can't guarantee that an
# add_callback that completes without error will
# eventually execute).
pass
except AttributeError:
# ProactorEventLoop may raise this instead of RuntimeError
# if call_soon_threadsafe races with a call to close().
# Swallow it too for consistency.
pass
def _handle_select(
self, rs: List["_FileDescriptorLike"], ws: List["_FileDescriptorLike"]
) -> None:
for r in rs:
self._handle_event(r, self._readers)
for w in ws:
self._handle_event(w, self._writers)
self._start_select()
def _handle_event(
self,
fd: "_FileDescriptorLike",
cb_map: Dict["_FileDescriptorLike", Callable],
) -> None:
try:
callback = cb_map[fd]
except KeyError:
return
callback()
def add_reader(
self, fd: "_FileDescriptorLike", callback: Callable[..., None], *args: Any
) -> None:
self._readers[fd] = functools.partial(callback, *args)
self._wake_selector()
def add_writer(
self, fd: "_FileDescriptorLike", callback: Callable[..., None], *args: Any
) -> None:
self._writers[fd] = functools.partial(callback, *args)
self._wake_selector()
def remove_reader(self, fd: "_FileDescriptorLike") -> None:
del self._readers[fd]
self._wake_selector()
def remove_writer(self, fd: "_FileDescriptorLike") -> None:
del self._writers[fd]
self._wake_selector()
The provided code snippet includes necessary dependencies for implementing the `_get_selector_windows` function. Write a Python function `def _get_selector_windows( asyncio_loop, ) -> asyncio.AbstractEventLoop` to solve the following problem:
Get selector-compatible loop Returns an object with ``add_reader`` family of methods, either the loop itself or a SelectorThread instance. Workaround Windows proactor removal of *reader methods, which we need for zmq sockets.
Here is the function:
def _get_selector_windows(
asyncio_loop,
) -> asyncio.AbstractEventLoop:
"""Get selector-compatible loop
Returns an object with ``add_reader`` family of methods,
either the loop itself or a SelectorThread instance.
Workaround Windows proactor removal of
*reader methods, which we need for zmq sockets.
"""
if asyncio_loop in _selectors:
return _selectors[asyncio_loop]
# detect add_reader instead of checking for proactor?
if hasattr(asyncio, "ProactorEventLoop") and isinstance(
asyncio_loop, asyncio.ProactorEventLoop # type: ignore
):
try:
from tornado.platform.asyncio import AddThreadSelectorEventLoop
except ImportError:
raise RuntimeError(
"Proactor event loop does not implement add_reader family of methods required for zmq."
" zmq will work with proactor if tornado >= 6.1 can be found."
" Use `asyncio.set_event_loop_policy(WindowsSelectorEventLoopPolicy())`"
" or install 'tornado>=6.1' to avoid this error."
)
warnings.warn(
"Proactor event loop does not implement add_reader family of methods required for zmq."
" Registering an additional selector thread for add_reader support via tornado."
" Use `asyncio.set_event_loop_policy(WindowsSelectorEventLoopPolicy())`"
" to avoid this warning.",
RuntimeWarning,
# stacklevel 5 matches most likely zmq.asyncio.Context().socket()
stacklevel=5,
)
selector_loop = _selectors[asyncio_loop] = AddThreadSelectorEventLoop(asyncio_loop) # type: ignore
# patch loop.close to also close the selector thread
loop_close = asyncio_loop.close
def _close_selector_and_loop():
# restore original before calling selector.close,
# which in turn calls eventloop.close!
asyncio_loop.close = loop_close
_selectors.pop(asyncio_loop, None)
selector_loop.close()
asyncio_loop.close = _close_selector_and_loop # type: ignore # mypy bug - assign a function to method
return selector_loop
else:
return asyncio_loop | Get selector-compatible loop Returns an object with ``add_reader`` family of methods, either the loop itself or a SelectorThread instance. Workaround Windows proactor removal of *reader methods, which we need for zmq sockets. |
172,820 | import asyncio
import selectors
import sys
import warnings
from asyncio import Future, SelectorEventLoop
from weakref import WeakKeyDictionary
import zmq as _zmq
from zmq import _future
import asyncio
from asyncio import Future, SelectorEventLoop
The provided code snippet includes necessary dependencies for implementing the `_get_selector_noop` function. Write a Python function `def _get_selector_noop(loop) -> asyncio.AbstractEventLoop` to solve the following problem:
no-op on non-Windows
Here is the function:
def _get_selector_noop(loop) -> asyncio.AbstractEventLoop:
"""no-op on non-Windows"""
return loop | no-op on non-Windows |
172,821 | import asyncio
import selectors
import sys
import warnings
from asyncio import Future, SelectorEventLoop
from weakref import WeakKeyDictionary
import zmq as _zmq
from zmq import _future
def _deprecated():
if _deprecated.called: # type: ignore
return
_deprecated.called = True # type: ignore
warnings.warn(
"ZMQEventLoop and zmq.asyncio.install are deprecated in pyzmq 17. Special eventloop integration is no longer needed.",
DeprecationWarning,
stacklevel=3,
)
_deprecated.called = False
The provided code snippet includes necessary dependencies for implementing the `install` function. Write a Python function `def install()` to solve the following problem:
DEPRECATED: No longer needed in pyzmq 17
Here is the function:
def install():
"""DEPRECATED: No longer needed in pyzmq 17"""
_deprecated() | DEPRECATED: No longer needed in pyzmq 17 |
172,822 | from functools import wraps
import zmq
class _ContextDecorator(_Decorator):
"""Decorator subclass for Contexts"""
def __init__(self):
super().__init__(zmq.Context)
The provided code snippet includes necessary dependencies for implementing the `context` function. Write a Python function `def context(*args, **kwargs)` to solve the following problem:
Decorator for adding a Context to a function. Usage:: @context() def foo(ctx): ... .. versionadded:: 15.3 :param str name: the keyword argument passed to decorated function
Here is the function:
def context(*args, **kwargs):
"""Decorator for adding a Context to a function.
Usage::
@context()
def foo(ctx):
...
.. versionadded:: 15.3
:param str name: the keyword argument passed to decorated function
"""
return _ContextDecorator()(*args, **kwargs) | Decorator for adding a Context to a function. Usage:: @context() def foo(ctx): ... .. versionadded:: 15.3 :param str name: the keyword argument passed to decorated function |
172,823 | from functools import wraps
import zmq
class _SocketDecorator(_Decorator):
"""Decorator subclass for sockets
Gets the context from other args.
"""
def process_decorator_args(self, *args, **kwargs):
"""Also grab context_name out of kwargs"""
kw_name, args, kwargs = super().process_decorator_args(*args, **kwargs)
self.context_name = kwargs.pop('context_name', 'context')
return kw_name, args, kwargs
def get_target(self, *args, **kwargs):
"""Get context, based on call-time args"""
context = self._get_context(*args, **kwargs)
return context.socket
def _get_context(self, *args, **kwargs):
"""
Find the ``zmq.Context`` from ``args`` and ``kwargs`` at call time.
First, if there is an keyword argument named ``context`` and it is a
``zmq.Context`` instance , we will take it.
Second, we check all the ``args``, take the first ``zmq.Context``
instance.
Finally, we will provide default Context -- ``zmq.Context.instance``
:return: a ``zmq.Context`` instance
"""
if self.context_name in kwargs:
ctx = kwargs[self.context_name]
if isinstance(ctx, zmq.Context):
return ctx
for arg in args:
if isinstance(arg, zmq.Context):
return arg
# not specified by any decorator
return zmq.Context.instance()
The provided code snippet includes necessary dependencies for implementing the `socket` function. Write a Python function `def socket(*args, **kwargs)` to solve the following problem:
Decorator for adding a socket to a function. Usage:: @socket(zmq.PUSH) def foo(push): ... .. versionadded:: 15.3 :param str name: the keyword argument passed to decorated function :param str context_name: the keyword only argument to identify context object
Here is the function:
def socket(*args, **kwargs):
"""Decorator for adding a socket to a function.
Usage::
@socket(zmq.PUSH)
def foo(push):
...
.. versionadded:: 15.3
:param str name: the keyword argument passed to decorated function
:param str context_name: the keyword only argument to identify context
object
"""
return _SocketDecorator()(*args, **kwargs) | Decorator for adding a socket to a function. Usage:: @socket(zmq.PUSH) def foo(push): ... .. versionadded:: 15.3 :param str name: the keyword argument passed to decorated function :param str context_name: the keyword only argument to identify context object |
172,824 | import datetime
import glob
import os
from typing import Dict, Optional, Tuple, Union
import zmq
_cert_secret_banner = """# **** Generated on {0} by pyzmq ****
# ZeroMQ CURVE **Secret** Certificate
# DO NOT PROVIDE THIS FILE TO OTHER USERS nor change its permissions.
"""
_cert_public_banner = """# **** Generated on {0} by pyzmq ****
# ZeroMQ CURVE Public Certificate
# Exchange securely, or use a secure mechanism to verify the contents
# of this file after exchange. Store public certificates in your home
# directory, in the .curve subdirectory.
"""
def _write_key_file(
key_filename: Union[str, os.PathLike],
banner: str,
public_key: Union[str, bytes],
secret_key: Optional[Union[str, bytes]] = None,
metadata: Optional[Dict[str, str]] = None,
encoding: str = 'utf-8',
) -> None:
"""Create a certificate file"""
if isinstance(public_key, bytes):
public_key = public_key.decode(encoding)
if isinstance(secret_key, bytes):
secret_key = secret_key.decode(encoding)
with open(key_filename, 'w', encoding='utf8') as f:
f.write(banner.format(datetime.datetime.now()))
f.write('metadata\n')
if metadata:
for k, v in metadata.items():
if isinstance(k, bytes):
k = k.decode(encoding)
if isinstance(v, bytes):
v = v.decode(encoding)
f.write(f" {k} = {v}\n")
f.write('curve\n')
f.write(f" public-key = \"{public_key}\"\n")
if secret_key:
f.write(f" secret-key = \"{secret_key}\"\n")
Union: _SpecialForm = ...
Optional: _SpecialForm = ...
Dict = _Alias()
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
The provided code snippet includes necessary dependencies for implementing the `create_certificates` function. Write a Python function `def create_certificates( key_dir: Union[str, os.PathLike], name: str, metadata: Optional[Dict[str, str]] = None, ) -> Tuple[str, str]` to solve the following problem:
Create zmq certificates. Returns the file paths to the public and secret certificate files.
Here is the function:
def create_certificates(
key_dir: Union[str, os.PathLike],
name: str,
metadata: Optional[Dict[str, str]] = None,
) -> Tuple[str, str]:
"""Create zmq certificates.
Returns the file paths to the public and secret certificate files.
"""
public_key, secret_key = zmq.curve_keypair()
base_filename = os.path.join(key_dir, name)
secret_key_file = f"{base_filename}.key_secret"
public_key_file = f"{base_filename}.key"
now = datetime.datetime.now()
_write_key_file(public_key_file, _cert_public_banner.format(now), public_key)
_write_key_file(
secret_key_file,
_cert_secret_banner.format(now),
public_key,
secret_key=secret_key,
metadata=metadata,
)
return public_key_file, secret_key_file | Create zmq certificates. Returns the file paths to the public and secret certificate files. |
172,825 | import datetime
import glob
import os
from typing import Dict, Optional, Tuple, Union
import zmq
def load_certificate(
filename: Union[str, os.PathLike]
) -> Tuple[bytes, Optional[bytes]]:
"""Load public and secret key from a zmq certificate.
Returns (public_key, secret_key)
If the certificate file only contains the public key,
secret_key will be None.
If there is no public key found in the file, ValueError will be raised.
"""
public_key = None
secret_key = None
if not os.path.exists(filename):
raise OSError(f"Invalid certificate file: {filename}")
with open(filename, 'rb') as f:
for line in f:
line = line.strip()
if line.startswith(b'#'):
continue
if line.startswith(b'public-key'):
public_key = line.split(b"=", 1)[1].strip(b' \t\'"')
if line.startswith(b'secret-key'):
secret_key = line.split(b"=", 1)[1].strip(b' \t\'"')
if public_key and secret_key:
break
if public_key is None:
raise ValueError("No public key found in %s" % filename)
return public_key, secret_key
Union: _SpecialForm = ...
Dict = _Alias()
The provided code snippet includes necessary dependencies for implementing the `load_certificates` function. Write a Python function `def load_certificates(directory: Union[str, os.PathLike] = '.') -> Dict[bytes, bool]` to solve the following problem:
Load public keys from all certificates in a directory
Here is the function:
def load_certificates(directory: Union[str, os.PathLike] = '.') -> Dict[bytes, bool]:
"""Load public keys from all certificates in a directory"""
certs = {}
if not os.path.isdir(directory):
raise OSError(f"Invalid certificate directory: {directory}")
# Follow czmq pattern of public keys stored in *.key files.
glob_string = os.path.join(directory, "*.key")
cert_files = glob.glob(glob_string)
for cert_file in cert_files:
public_key, _ = load_certificate(cert_file)
if public_key:
certs[public_key] = True
return certs | Load public keys from all certificates in a directory |
172,826 | import warnings
def _deprecated():
warnings.warn(
"zmq.eventloop.ioloop is deprecated in pyzmq 17."
" pyzmq now works with default tornado and asyncio eventloops.",
DeprecationWarning,
stacklevel=3,
)
_deprecated()
from tornado.ioloop import *
from tornado.ioloop import IOLoop
The provided code snippet includes necessary dependencies for implementing the `install` function. Write a Python function `def install()` to solve the following problem:
DEPRECATED pyzmq 17 no longer needs any special integration for tornado.
Here is the function:
def install():
"""DEPRECATED
pyzmq 17 no longer needs any special integration for tornado.
"""
_deprecated() | DEPRECATED pyzmq 17 no longer needs any special integration for tornado. |
172,827 | import time
import warnings
from typing import Tuple
from zmq import ETERM, POLLERR, POLLIN, POLLOUT, Poller, ZMQError
tornado_version: Tuple = ()
try:
import tornado
tornado_version = tornado.version_info
except (ImportError, AttributeError):
pass
from .minitornado.ioloop import PeriodicCallback, PollIOLoop
from .minitornado.log import gen_log
class ZMQIOLoop(PollIOLoop):
"""ZMQ subclass of tornado's IOLoop
Minor modifications, so that .current/.instance return self
"""
_zmq_impl = ZMQPoller
def initialize(self, impl=None, **kwargs):
impl = self._zmq_impl() if impl is None else impl
super().initialize(impl=impl, **kwargs)
def instance(cls, *args, **kwargs):
"""Returns a global `IOLoop` instance.
Most applications have a single, global `IOLoop` running on the
main thread. Use this method to get this instance from
another thread. To get the current thread's `IOLoop`, use `current()`.
"""
# install ZMQIOLoop as the active IOLoop implementation
# when using tornado 3
if tornado_version >= (3,):
PollIOLoop.configure(cls)
loop = PollIOLoop.instance(*args, **kwargs)
if not isinstance(loop, cls):
warnings.warn(
f"IOLoop.current expected instance of {cls!r}, got {loop!r}",
RuntimeWarning,
stacklevel=2,
)
return loop
def current(cls, *args, **kwargs):
"""Returns the current thread’s IOLoop."""
# install ZMQIOLoop as the active IOLoop implementation
# when using tornado 3
if tornado_version >= (3,):
PollIOLoop.configure(cls)
loop = PollIOLoop.current(*args, **kwargs)
if not isinstance(loop, cls):
warnings.warn(
f"IOLoop.current expected instance of {cls!r}, got {loop!r}",
RuntimeWarning,
stacklevel=2,
)
return loop
def start(self):
try:
super().start()
except ZMQError as e:
if e.errno == ETERM:
# quietly return on ETERM
pass
else:
raise
IOLoop = ZMQIOLoop
The provided code snippet includes necessary dependencies for implementing the `install` function. Write a Python function `def install()` to solve the following problem:
set the tornado IOLoop instance with the pyzmq IOLoop. After calling this function, tornado's IOLoop.instance() and pyzmq's IOLoop.instance() will return the same object. An assertion error will be raised if tornado's IOLoop has been initialized prior to calling this function.
Here is the function:
def install():
"""set the tornado IOLoop instance with the pyzmq IOLoop.
After calling this function, tornado's IOLoop.instance() and pyzmq's
IOLoop.instance() will return the same object.
An assertion error will be raised if tornado's IOLoop has been initialized
prior to calling this function.
"""
from tornado import ioloop
# check if tornado's IOLoop is already initialized to something other
# than the pyzmq IOLoop instance:
assert (
not ioloop.IOLoop.initialized()
) or ioloop.IOLoop.instance() is IOLoop.instance(), (
"tornado IOLoop already initialized"
)
if tornado_version >= (3,):
# tornado 3 has an official API for registering new defaults, yay!
ioloop.IOLoop.configure(ZMQIOLoop)
else:
# we have to set the global instance explicitly
ioloop.IOLoop._instance = IOLoop.instance() | set the tornado IOLoop instance with the pyzmq IOLoop. After calling this function, tornado's IOLoop.instance() and pyzmq's IOLoop.instance() will return the same object. An assertion error will be raised if tornado's IOLoop has been initialized prior to calling this function. |
172,828 | import sys
import time
import warnings
from typing import Tuple
import gevent
from gevent.event import AsyncResult
from gevent.hub import get_hub
import zmq
from zmq import Context as _original_Context
from zmq import Socket as _original_Socket
from .poll import _Poller
The provided code snippet includes necessary dependencies for implementing the `_stop` function. Write a Python function `def _stop(evt)` to solve the following problem:
simple wrapper for stopping an Event, allowing for method rename in gevent 1.0
Here is the function:
def _stop(evt):
"""simple wrapper for stopping an Event, allowing for method rename in gevent 1.0"""
try:
evt.stop()
except AttributeError:
# gevent<1.0 compat
evt.cancel() | simple wrapper for stopping an Event, allowing for method rename in gevent 1.0 |
172,829 | import zmq
from zmq.green import Poller
Poller = _Poller
The provided code snippet includes necessary dependencies for implementing the `device` function. Write a Python function `def device(device_type, isocket, osocket)` to solve the following problem:
Start a zeromq device (gevent-compatible). Unlike the true zmq.device, this does not release the GIL. Parameters ---------- device_type : (QUEUE, FORWARDER, STREAMER) The type of device to start (ignored). isocket : Socket The Socket instance for the incoming traffic. osocket : Socket The Socket instance for the outbound traffic.
Here is the function:
def device(device_type, isocket, osocket):
"""Start a zeromq device (gevent-compatible).
Unlike the true zmq.device, this does not release the GIL.
Parameters
----------
device_type : (QUEUE, FORWARDER, STREAMER)
The type of device to start (ignored).
isocket : Socket
The Socket instance for the incoming traffic.
osocket : Socket
The Socket instance for the outbound traffic.
"""
p = Poller()
if osocket == -1:
osocket = isocket
p.register(isocket, zmq.POLLIN)
p.register(osocket, zmq.POLLIN)
while True:
events = dict(p.poll())
if isocket in events:
osocket.send_multipart(isocket.recv_multipart())
if osocket in events:
isocket.send_multipart(osocket.recv_multipart()) | Start a zeromq device (gevent-compatible). Unlike the true zmq.device, this does not release the GIL. Parameters ---------- device_type : (QUEUE, FORWARDER, STREAMER) The type of device to start (ignored). isocket : Socket The Socket instance for the incoming traffic. osocket : Socket The Socket instance for the outbound traffic. |
172,830 | import zmq
def _relay(ins, outs, sides, prefix, swap_ids):
msg = ins.recv_multipart()
if swap_ids:
msg[:2] = msg[:2][::-1]
outs.send_multipart(msg)
sides.send_multipart([prefix] + msg)
def monitored_queue(
in_socket, out_socket, mon_socket, in_prefix=b'in', out_prefix=b'out'
):
swap_ids = in_socket.type == zmq.ROUTER and out_socket.type == zmq.ROUTER
poller = zmq.Poller()
poller.register(in_socket, zmq.POLLIN)
poller.register(out_socket, zmq.POLLIN)
while True:
events = dict(poller.poll())
if in_socket in events:
_relay(in_socket, out_socket, mon_socket, in_prefix, swap_ids)
if out_socket in events:
_relay(out_socket, in_socket, mon_socket, out_prefix, swap_ids) | null |
172,831 | from zmq.error import InterruptedSystemCall, _check_rc, _check_version
from ._cffi import ffi
from ._cffi import lib as C
def _check_version(
min_version_info: Union[Tuple[int], Tuple[int, int], Tuple[int, int, int]],
msg: str = "Feature",
):
"""Check for libzmq
raises ZMQVersionError if current zmq version is not at least min_version
min_version_info is a tuple of integers, and will be compared against zmq.zmq_version_info().
"""
global _zmq_version_info
if _zmq_version_info is None:
from zmq import zmq_version_info
_zmq_version_info = zmq_version_info()
if _zmq_version_info < min_version_info:
min_version = ".".join(str(v) for v in min_version_info)
raise ZMQVersionError(min_version, msg)
The provided code snippet includes necessary dependencies for implementing the `has` function. Write a Python function `def has(capability)` to solve the following problem:
Check for zmq capability by name (e.g. 'ipc', 'curve') .. versionadded:: libzmq-4.1 .. versionadded:: 14.1
Here is the function:
def has(capability):
"""Check for zmq capability by name (e.g. 'ipc', 'curve')
.. versionadded:: libzmq-4.1
.. versionadded:: 14.1
"""
_check_version((4, 1), 'zmq.has')
if isinstance(capability, str):
capability = capability.encode('utf8')
return bool(C.zmq_has(capability)) | Check for zmq capability by name (e.g. 'ipc', 'curve') .. versionadded:: libzmq-4.1 .. versionadded:: 14.1 |
172,832 | from zmq.error import InterruptedSystemCall, _check_rc, _check_version
from ._cffi import ffi
from ._cffi import lib as C
def _check_rc(rc, errno=None, error_without_errno=True):
"""internal utility for checking zmq return condition
and raising the appropriate Exception class
"""
if rc == -1:
if errno is None:
from zmq.backend import zmq_errno
errno = zmq_errno()
if errno == 0 and not error_without_errno:
return
from zmq import EAGAIN, ETERM
if errno == EINTR:
raise InterruptedSystemCall(errno)
elif errno == EAGAIN:
raise Again(errno)
elif errno == ETERM:
raise ContextTerminated(errno)
else:
raise ZMQError(errno)
def _check_version(
min_version_info: Union[Tuple[int], Tuple[int, int], Tuple[int, int, int]],
msg: str = "Feature",
):
"""Check for libzmq
raises ZMQVersionError if current zmq version is not at least min_version
min_version_info is a tuple of integers, and will be compared against zmq.zmq_version_info().
"""
global _zmq_version_info
if _zmq_version_info is None:
from zmq import zmq_version_info
_zmq_version_info = zmq_version_info()
if _zmq_version_info < min_version_info:
min_version = ".".join(str(v) for v in min_version_info)
raise ZMQVersionError(min_version, msg)
The provided code snippet includes necessary dependencies for implementing the `curve_keypair` function. Write a Python function `def curve_keypair()` to solve the following problem:
generate a Z85 key pair for use with zmq.CURVE security Requires libzmq (≥ 4.0) to have been built with CURVE support. Returns ------- (public, secret) : two bytestrings The public and private key pair as 40 byte z85-encoded bytestrings.
Here is the function:
def curve_keypair():
"""generate a Z85 key pair for use with zmq.CURVE security
Requires libzmq (≥ 4.0) to have been built with CURVE support.
Returns
-------
(public, secret) : two bytestrings
The public and private key pair as 40 byte z85-encoded bytestrings.
"""
_check_version((3, 2), "curve_keypair")
public = ffi.new('char[64]')
private = ffi.new('char[64]')
rc = C.zmq_curve_keypair(public, private)
_check_rc(rc)
return ffi.buffer(public)[:40], ffi.buffer(private)[:40] | generate a Z85 key pair for use with zmq.CURVE security Requires libzmq (≥ 4.0) to have been built with CURVE support. Returns ------- (public, secret) : two bytestrings The public and private key pair as 40 byte z85-encoded bytestrings. |
172,833 | from zmq.error import InterruptedSystemCall, _check_rc, _check_version
from ._cffi import ffi
from ._cffi import lib as C
def _check_rc(rc, errno=None, error_without_errno=True):
"""internal utility for checking zmq return condition
and raising the appropriate Exception class
"""
if rc == -1:
if errno is None:
from zmq.backend import zmq_errno
errno = zmq_errno()
if errno == 0 and not error_without_errno:
return
from zmq import EAGAIN, ETERM
if errno == EINTR:
raise InterruptedSystemCall(errno)
elif errno == EAGAIN:
raise Again(errno)
elif errno == ETERM:
raise ContextTerminated(errno)
else:
raise ZMQError(errno)
def _check_version(
min_version_info: Union[Tuple[int], Tuple[int, int], Tuple[int, int, int]],
msg: str = "Feature",
):
"""Check for libzmq
raises ZMQVersionError if current zmq version is not at least min_version
min_version_info is a tuple of integers, and will be compared against zmq.zmq_version_info().
"""
global _zmq_version_info
if _zmq_version_info is None:
from zmq import zmq_version_info
_zmq_version_info = zmq_version_info()
if _zmq_version_info < min_version_info:
min_version = ".".join(str(v) for v in min_version_info)
raise ZMQVersionError(min_version, msg)
The provided code snippet includes necessary dependencies for implementing the `curve_public` function. Write a Python function `def curve_public(private)` to solve the following problem:
Compute the public key corresponding to a private key for use with zmq.CURVE security Requires libzmq (≥ 4.2) to have been built with CURVE support. Parameters ---------- private The private key as a 40 byte z85-encoded bytestring Returns ------- bytestring The public key as a 40 byte z85-encoded bytestring.
Here is the function:
def curve_public(private):
"""Compute the public key corresponding to a private key for use
with zmq.CURVE security
Requires libzmq (≥ 4.2) to have been built with CURVE support.
Parameters
----------
private
The private key as a 40 byte z85-encoded bytestring
Returns
-------
bytestring
The public key as a 40 byte z85-encoded bytestring.
"""
if isinstance(private, str):
private = private.encode('utf8')
_check_version((4, 2), "curve_public")
public = ffi.new('char[64]')
rc = C.zmq_curve_public(public, private)
_check_rc(rc)
return ffi.buffer(public)[:40] | Compute the public key corresponding to a private key for use with zmq.CURVE security Requires libzmq (≥ 4.2) to have been built with CURVE support. Parameters ---------- private The private key as a 40 byte z85-encoded bytestring Returns ------- bytestring The public key as a 40 byte z85-encoded bytestring. |
172,834 | from ._cffi import ffi
from ._cffi import lib as C
from .socket import Socket
from .utils import _retry_sys_call
def proxy(frontend, backend, capture=None):
if isinstance(capture, Socket):
capture = capture._zmq_socket
else:
capture = ffi.NULL
_retry_sys_call(C.zmq_proxy, frontend._zmq_socket, backend._zmq_socket, capture)
def device(device_type, frontend, backend):
return proxy(frontend, backend) | null |
172,835 | from ._cffi import ffi
from ._cffi import lib as C
from .socket import Socket
from .utils import _retry_sys_call
class Socket:
context = None
socket_type = None
_zmq_socket = None
_closed = None
_ref = None
_shadow = False
copy_threshold = 0
def __init__(self, context=None, socket_type=None, shadow=0, copy_threshold=None):
if copy_threshold is None:
copy_threshold = zmq.COPY_THRESHOLD
self.copy_threshold = copy_threshold
self.context = context
if shadow:
self._zmq_socket = ffi.cast("void *", shadow)
self._shadow = True
else:
self._shadow = False
self._zmq_socket = C.zmq_socket(context._zmq_ctx, socket_type)
if self._zmq_socket == ffi.NULL:
raise ZMQError()
self._closed = False
def underlying(self):
"""The address of the underlying libzmq socket"""
return int(ffi.cast('size_t', self._zmq_socket))
def _check_closed_deep(self):
"""thorough check of whether the socket has been closed,
even if by another entity (e.g. ctx.destroy).
Only used by the `closed` property.
returns True if closed, False otherwise
"""
if self._closed:
return True
try:
self.get(zmq.TYPE)
except ZMQError as e:
if e.errno == zmq.ENOTSOCK:
self._closed = True
return True
elif e.errno == zmq.ETERM:
pass
else:
raise
return False
def closed(self):
return self._check_closed_deep()
def close(self, linger=None):
rc = 0
if not self._closed and hasattr(self, '_zmq_socket'):
if self._zmq_socket is not None:
if linger is not None:
self.set(zmq.LINGER, linger)
rc = C.zmq_close(self._zmq_socket)
self._closed = True
if rc < 0:
_check_rc(rc)
def bind(self, address):
if isinstance(address, str):
address_b = address.encode('utf8')
else:
address_b = address
if isinstance(address, bytes):
address = address_b.decode('utf8')
rc = C.zmq_bind(self._zmq_socket, address_b)
if rc < 0:
if IPC_PATH_MAX_LEN and C.zmq_errno() == errno_mod.ENAMETOOLONG:
path = address.split('://', 1)[-1]
msg = (
'ipc path "{}" is longer than {} '
'characters (sizeof(sockaddr_un.sun_path)).'.format(
path, IPC_PATH_MAX_LEN
)
)
raise ZMQError(C.zmq_errno(), msg=msg)
elif C.zmq_errno() == errno_mod.ENOENT:
path = address.split('://', 1)[-1]
msg = f'No such file or directory for ipc path "{path}".'
raise ZMQError(C.zmq_errno(), msg=msg)
else:
_check_rc(rc)
def unbind(self, address):
_check_version((3, 2), "unbind")
if isinstance(address, str):
address = address.encode('utf8')
rc = C.zmq_unbind(self._zmq_socket, address)
_check_rc(rc)
def connect(self, address):
if isinstance(address, str):
address = address.encode('utf8')
rc = C.zmq_connect(self._zmq_socket, address)
_check_rc(rc)
def disconnect(self, address):
_check_version((3, 2), "disconnect")
if isinstance(address, str):
address = address.encode('utf8')
rc = C.zmq_disconnect(self._zmq_socket, address)
_check_rc(rc)
def set(self, option, value):
length = None
if isinstance(value, str):
raise TypeError("unicode not allowed, use bytes")
try:
option = SocketOption(option)
except ValueError:
# unrecognized option,
# assume from the future,
# let EINVAL raise
opt_type = _OptType.int
else:
opt_type = option._opt_type
if isinstance(value, bytes):
if opt_type != _OptType.bytes:
raise TypeError("not a bytes sockopt: %s" % option)
length = len(value)
c_value_pointer, c_sizet = initialize_opt_pointer(option, value, length)
_retry_sys_call(
C.zmq_setsockopt,
self._zmq_socket,
option,
ffi.cast('void*', c_value_pointer),
c_sizet,
)
def get(self, option):
try:
option = SocketOption(option)
except ValueError:
# unrecognized option,
# assume from the future,
# let EINVAL raise
opt_type = _OptType.int
else:
opt_type = option._opt_type
c_value_pointer, c_sizet_pointer = new_pointer_from_opt(option, length=255)
_retry_sys_call(
C.zmq_getsockopt, self._zmq_socket, option, c_value_pointer, c_sizet_pointer
)
sz = c_sizet_pointer[0]
v = value_from_opt_pointer(option, c_value_pointer, sz)
if (
option != zmq.SocketOption.ROUTING_ID
and opt_type == _OptType.bytes
and v.endswith(b'\0')
):
v = v[:-1]
return v
def _send_copy(self, buf, flags):
"""Send a copy of a bufferable"""
zmq_msg = ffi.new('zmq_msg_t*')
if not isinstance(buf, bytes):
# cast any bufferable data to bytes via memoryview
buf = memoryview(buf).tobytes()
c_message = ffi.new('char[]', buf)
rc = C.zmq_msg_init_size(zmq_msg, len(buf))
_check_rc(rc)
C.memcpy(C.zmq_msg_data(zmq_msg), c_message, len(buf))
_retry_sys_call(C.zmq_msg_send, zmq_msg, self._zmq_socket, flags)
rc2 = C.zmq_msg_close(zmq_msg)
_check_rc(rc2)
def _send_frame(self, frame, flags):
"""Send a Frame on this socket in a non-copy manner."""
# Always copy the Frame so the original message isn't garbage collected.
# This doesn't do a real copy, just a reference.
frame_copy = frame.fast_copy()
zmq_msg = frame_copy.zmq_msg
_retry_sys_call(C.zmq_msg_send, zmq_msg, self._zmq_socket, flags)
tracker = frame_copy.tracker
frame_copy.close()
return tracker
def send(self, data, flags=0, copy=False, track=False):
if isinstance(data, str):
raise TypeError("Message must be in bytes, not a unicode object")
if copy and not isinstance(data, Frame):
return self._send_copy(data, flags)
else:
close_frame = False
if isinstance(data, Frame):
if track and not data.tracker:
raise ValueError('Not a tracked message')
frame = data
else:
if self.copy_threshold:
buf = memoryview(data)
# always copy messages smaller than copy_threshold
if buf.nbytes < self.copy_threshold:
self._send_copy(buf, flags)
return zmq._FINISHED_TRACKER
frame = Frame(data, track=track, copy_threshold=self.copy_threshold)
close_frame = True
tracker = self._send_frame(frame, flags)
if close_frame:
frame.close()
return tracker
def recv(self, flags=0, copy=True, track=False):
if copy:
zmq_msg = ffi.new('zmq_msg_t*')
C.zmq_msg_init(zmq_msg)
else:
frame = zmq.Frame(track=track)
zmq_msg = frame.zmq_msg
try:
_retry_sys_call(C.zmq_msg_recv, zmq_msg, self._zmq_socket, flags)
except Exception:
if copy:
C.zmq_msg_close(zmq_msg)
raise
if not copy:
return frame
_buffer = ffi.buffer(C.zmq_msg_data(zmq_msg), C.zmq_msg_size(zmq_msg))
_bytes = _buffer[:]
rc = C.zmq_msg_close(zmq_msg)
_check_rc(rc)
return _bytes
def monitor(self, addr, events=-1):
"""s.monitor(addr, flags)
Start publishing socket events on inproc.
See libzmq docs for zmq_monitor for details.
Note: requires libzmq >= 3.2
Parameters
----------
addr : str
The inproc url used for monitoring. Passing None as
the addr will cause an existing socket monitor to be
deregistered.
events : int [default: zmq.EVENT_ALL]
The zmq event bitmask for which events will be sent to the monitor.
"""
_check_version((3, 2), "monitor")
if events < 0:
events = zmq.EVENT_ALL
if addr is None:
addr = ffi.NULL
if isinstance(addr, str):
addr = addr.encode('utf8')
C.zmq_socket_monitor(self._zmq_socket, addr, events)
def _retry_sys_call(f, *args, **kwargs):
"""make a call, retrying if interrupted with EINTR"""
while True:
rc = f(*args)
try:
_check_rc(rc)
except InterruptedSystemCall:
continue
else:
break
The provided code snippet includes necessary dependencies for implementing the `proxy_steerable` function. Write a Python function `def proxy_steerable(frontend, backend, capture=None, control=None)` to solve the following problem:
proxy_steerable(frontend, backend, capture, control) Start a zeromq proxy with control flow. .. versionadded:: libzmq-4.1 .. versionadded:: 18.0 Parameters ---------- frontend : Socket The Socket instance for the incoming traffic. backend : Socket The Socket instance for the outbound traffic. capture : Socket (optional) The Socket instance for capturing traffic. control : Socket (optional) The Socket instance for control flow.
Here is the function:
def proxy_steerable(frontend, backend, capture=None, control=None):
"""proxy_steerable(frontend, backend, capture, control)
Start a zeromq proxy with control flow.
.. versionadded:: libzmq-4.1
.. versionadded:: 18.0
Parameters
----------
frontend : Socket
The Socket instance for the incoming traffic.
backend : Socket
The Socket instance for the outbound traffic.
capture : Socket (optional)
The Socket instance for capturing traffic.
control : Socket (optional)
The Socket instance for control flow.
"""
if isinstance(capture, Socket):
capture = capture._zmq_socket
else:
capture = ffi.NULL
if isinstance(control, Socket):
control = control._zmq_socket
else:
control = ffi.NULL
_retry_sys_call(
C.zmq_proxy_steerable,
frontend._zmq_socket,
backend._zmq_socket,
capture,
control,
) | proxy_steerable(frontend, backend, capture, control) Start a zeromq proxy with control flow. .. versionadded:: libzmq-4.1 .. versionadded:: 18.0 Parameters ---------- frontend : Socket The Socket instance for the incoming traffic. backend : Socket The Socket instance for the outbound traffic. capture : Socket (optional) The Socket instance for capturing traffic. control : Socket (optional) The Socket instance for control flow. |
172,836 | import warnings
from zmq.error import InterruptedSystemCall, _check_rc
from ._cffi import ffi
from ._cffi import lib as C
def _make_zmq_pollitem(socket, flags):
def _make_zmq_pollitem_fromfd(socket_fd, flags):
class InterruptedSystemCall(ZMQError, InterruptedError):
def __init__(self, errno="ignored", msg="ignored"):
def __str__(self):
def _check_rc(rc, errno=None, error_without_errno=True):
def zmq_poll(sockets, timeout):
cffi_pollitem_list = []
low_level_to_socket_obj = {}
from zmq import Socket
for item in sockets:
if isinstance(item[0], Socket):
low_level_to_socket_obj[item[0]._zmq_socket] = item
cffi_pollitem_list.append(_make_zmq_pollitem(item[0], item[1]))
else:
if not isinstance(item[0], int):
# not an FD, get it from fileno()
item = (item[0].fileno(), item[1])
low_level_to_socket_obj[item[0]] = item
cffi_pollitem_list.append(_make_zmq_pollitem_fromfd(item[0], item[1]))
items = ffi.new('zmq_pollitem_t[]', cffi_pollitem_list)
list_length = ffi.cast('int', len(cffi_pollitem_list))
while True:
c_timeout = ffi.cast('long', timeout)
start = monotonic()
rc = C.zmq_poll(items, list_length, c_timeout)
try:
_check_rc(rc)
except InterruptedSystemCall:
if timeout > 0:
ms_passed = int(1000 * (monotonic() - start))
if ms_passed < 0:
# don't allow negative ms_passed,
# which can happen on old Python versions without time.monotonic.
warnings.warn(
"Negative elapsed time for interrupted poll: %s."
" Did the clock change?" % ms_passed,
RuntimeWarning,
)
ms_passed = 0
timeout = max(0, timeout - ms_passed)
continue
else:
break
result = []
for item in items:
if item.revents > 0:
if item.socket != ffi.NULL:
result.append(
(
low_level_to_socket_obj[item.socket][0],
item.revents,
)
)
else:
result.append((item.fd, item.revents))
return result | null |
172,837 | import errno as errno_mod
from ._cffi import ffi
from ._cffi import lib as C
new_int64_pointer = lambda: (ffi.new('int64_t*'), nsp(ffi.sizeof('int64_t')))
new_int_pointer = lambda: (ffi.new('int*'), nsp(ffi.sizeof('int')))
new_binary_data = lambda length: (
ffi.new('char[%d]' % (length)),
nsp(ffi.sizeof('char') * length),
)
ZMQ_FD_64BIT = ffi.sizeof('ZMQ_FD_T') == 8
import zmq
from zmq.constants import SocketOption, _OptType
from zmq.error import ZMQError, _check_rc, _check_version
from .message import Frame
from .utils import _retry_sys_call
class _OptType(Enum):
int = 'int'
int64 = 'int64'
bytes = 'bytes'
fd = 'fd'
def new_pointer_from_opt(option, length=0):
opt_type = getattr(option, "_opt_type", _OptType.int)
if opt_type == _OptType.int64 or (ZMQ_FD_64BIT and opt_type == _OptType.fd):
return new_int64_pointer()
elif opt_type == _OptType.bytes:
return new_binary_data(length)
else:
# default
return new_int_pointer() | null |
172,838 | import errno as errno_mod
from ._cffi import ffi
from ._cffi import lib as C
import zmq
from zmq.constants import SocketOption, _OptType
from zmq.error import ZMQError, _check_rc, _check_version
from .message import Frame
from .utils import _retry_sys_call
class _OptType(Enum):
int = 'int'
int64 = 'int64'
bytes = 'bytes'
fd = 'fd'
class SocketOption(IntEnum):
"""Options for Socket.get/set
.. versionadded:: 23
"""
_opt_type: _OptType
def __new__(cls, value: int, opt_type: _OptType = _OptType.int):
"""Attach option type as `._opt_type`"""
obj = int.__new__(cls, value)
obj._value_ = value
obj._opt_type = opt_type
return obj
HWM = 1
AFFINITY = 4, _OptType.int64
ROUTING_ID = 5, _OptType.bytes
SUBSCRIBE = 6, _OptType.bytes
UNSUBSCRIBE = 7, _OptType.bytes
RATE = 8
RECOVERY_IVL = 9
SNDBUF = 11
RCVBUF = 12
RCVMORE = 13
FD = 14, _OptType.fd
EVENTS = 15
TYPE = 16
LINGER = 17
RECONNECT_IVL = 18
BACKLOG = 19
RECONNECT_IVL_MAX = 21
MAXMSGSIZE = 22, _OptType.int64
SNDHWM = 23
RCVHWM = 24
MULTICAST_HOPS = 25
RCVTIMEO = 27
SNDTIMEO = 28
LAST_ENDPOINT = 32, _OptType.bytes
ROUTER_MANDATORY = 33
TCP_KEEPALIVE = 34
TCP_KEEPALIVE_CNT = 35
TCP_KEEPALIVE_IDLE = 36
TCP_KEEPALIVE_INTVL = 37
IMMEDIATE = 39
XPUB_VERBOSE = 40
ROUTER_RAW = 41
IPV6 = 42
MECHANISM = 43
PLAIN_SERVER = 44
PLAIN_USERNAME = 45, _OptType.bytes
PLAIN_PASSWORD = 46, _OptType.bytes
CURVE_SERVER = 47
CURVE_PUBLICKEY = 48, _OptType.bytes
CURVE_SECRETKEY = 49, _OptType.bytes
CURVE_SERVERKEY = 50, _OptType.bytes
PROBE_ROUTER = 51
REQ_CORRELATE = 52
REQ_RELAXED = 53
CONFLATE = 54
ZAP_DOMAIN = 55, _OptType.bytes
ROUTER_HANDOVER = 56
TOS = 57
CONNECT_ROUTING_ID = 61, _OptType.bytes
GSSAPI_SERVER = 62
GSSAPI_PRINCIPAL = 63, _OptType.bytes
GSSAPI_SERVICE_PRINCIPAL = 64, _OptType.bytes
GSSAPI_PLAINTEXT = 65
HANDSHAKE_IVL = 66
SOCKS_PROXY = 68, _OptType.bytes
XPUB_NODROP = 69
BLOCKY = 70
XPUB_MANUAL = 71
XPUB_WELCOME_MSG = 72, _OptType.bytes
STREAM_NOTIFY = 73
INVERT_MATCHING = 74
HEARTBEAT_IVL = 75
HEARTBEAT_TTL = 76
HEARTBEAT_TIMEOUT = 77
XPUB_VERBOSER = 78
CONNECT_TIMEOUT = 79
TCP_MAXRT = 80
THREAD_SAFE = 81
MULTICAST_MAXTPDU = 84
VMCI_BUFFER_SIZE = 85, _OptType.int64
VMCI_BUFFER_MIN_SIZE = 86, _OptType.int64
VMCI_BUFFER_MAX_SIZE = 87, _OptType.int64
VMCI_CONNECT_TIMEOUT = 88
USE_FD = 89
GSSAPI_PRINCIPAL_NAMETYPE = 90
GSSAPI_SERVICE_PRINCIPAL_NAMETYPE = 91
BINDTODEVICE = 92, _OptType.bytes
# Deprecated options and aliases
# must not use name-assignment, must have the same value
IDENTITY = ROUTING_ID
CONNECT_RID = CONNECT_ROUTING_ID
TCP_ACCEPT_FILTER = 38, _OptType.bytes
IPC_FILTER_PID = 58
IPC_FILTER_UID = 59
IPC_FILTER_GID = 60
IPV4ONLY = 31
DELAY_ATTACH_ON_CONNECT = IMMEDIATE
FAIL_UNROUTABLE = ROUTER_MANDATORY
ROUTER_BEHAVIOR = ROUTER_MANDATORY
# Draft socket options
ZAP_ENFORCE_DOMAIN = 93
LOOPBACK_FASTPATH = 94
METADATA = 95, _OptType.bytes
MULTICAST_LOOP = 96
ROUTER_NOTIFY = 97
XPUB_MANUAL_LAST_VALUE = 98
SOCKS_USERNAME = 99, _OptType.bytes
SOCKS_PASSWORD = 100, _OptType.bytes
IN_BATCH_SIZE = 101
OUT_BATCH_SIZE = 102
WSS_KEY_PEM = 103, _OptType.bytes
WSS_CERT_PEM = 104, _OptType.bytes
WSS_TRUST_PEM = 105, _OptType.bytes
WSS_HOSTNAME = 106, _OptType.bytes
WSS_TRUST_SYSTEM = 107
ONLY_FIRST_SUBSCRIBE = 108
RECONNECT_STOP = 109
HELLO_MSG = 110, _OptType.bytes
DISCONNECT_MSG = 111, _OptType.bytes
PRIORITY = 112
def value_from_opt_pointer(option, opt_pointer, length=0):
try:
option = SocketOption(option)
except ValueError:
# unrecognized option,
# assume from the future,
# let EINVAL raise
opt_type = _OptType.int
else:
opt_type = option._opt_type
if opt_type == _OptType.bytes:
return ffi.buffer(opt_pointer, length)[:]
else:
return int(opt_pointer[0]) | null |
172,839 | import errno as errno_mod
from ._cffi import ffi
from ._cffi import lib as C
value_int64_pointer = lambda val: (ffi.new('int64_t*', val), ffi.sizeof('int64_t'))
value_int_pointer = lambda val: (ffi.new('int*', val), ffi.sizeof('int'))
value_binary_data = lambda val, length: (
ffi.new('char[%d]' % (length + 1), val),
ffi.sizeof('char') * length,
)
ZMQ_FD_64BIT = ffi.sizeof('ZMQ_FD_T') == 8
import zmq
from zmq.constants import SocketOption, _OptType
from zmq.error import ZMQError, _check_rc, _check_version
from .message import Frame
from .utils import _retry_sys_call
class _OptType(Enum):
def initialize_opt_pointer(option, value, length=0):
opt_type = getattr(option, "_opt_type", _OptType.int)
if opt_type == _OptType.int64 or (ZMQ_FD_64BIT and opt_type == _OptType.fd):
return value_int64_pointer(value)
elif opt_type == _OptType.bytes:
return value_binary_data(value, length)
else:
return value_int_pointer(value) | null |
172,840 | from ._cffi import ffi
from ._cffi import lib as C
def strerror(errno):
s = ffi.string(C.zmq_strerror(errno))
if not isinstance(s, str):
# py3
s = s.decode()
return s | null |
172,841 | import errno
from threading import Event
import zmq
import zmq.error
from zmq.constants import ETERM
from ._cffi import ffi
from ._cffi import lib as C
The provided code snippet includes necessary dependencies for implementing the `_content` function. Write a Python function `def _content(obj)` to solve the following problem:
Return content of obj as bytes
Here is the function:
def _content(obj):
"""Return content of obj as bytes"""
if type(obj) is bytes:
return obj
if not isinstance(obj, memoryview):
obj = memoryview(obj)
return obj.tobytes() | Return content of obj as bytes |
172,842 | import errno
from threading import Event
import zmq
import zmq.error
from zmq.constants import ETERM
from ._cffi import ffi
from ._cffi import lib as C
ETERM: int = Errno.ETERM
def _check_rc(rc):
err = C.zmq_errno()
if rc == -1:
if err == errno.EINTR:
raise zmq.error.InterrruptedSystemCall(err)
elif err == errno.EAGAIN:
raise zmq.error.Again(errno)
elif err == ETERM:
raise zmq.error.ContextTerminated(err)
else:
raise zmq.error.ZMQError(err)
return 0 | null |
172,843 | from importlib import import_module
from typing import Dict
public_api = [
'Context',
'Socket',
'Frame',
'Message',
'device',
'proxy',
'proxy_steerable',
'zmq_poll',
'strerror',
'zmq_errno',
'has',
'curve_keypair',
'curve_public',
'zmq_version_info',
'IPC_PATH_MAX_LEN',
]
def import_module(name: Text, package: Optional[Text] = ...) -> types.ModuleType: ...
Dict = _Alias()
The provided code snippet includes necessary dependencies for implementing the `select_backend` function. Write a Python function `def select_backend(name: str) -> Dict` to solve the following problem:
Select the pyzmq backend
Here is the function:
def select_backend(name: str) -> Dict:
"""Select the pyzmq backend"""
try:
mod = import_module(name)
except ImportError:
raise
except Exception as e:
raise ImportError(f"Importing {name} failed with {e}") from e
return {key: getattr(mod, key) for key in public_api} | Select the pyzmq backend |
172,844 | import struct
Z85MAP = {c: idx for idx, c in enumerate(Z85CHARS)}
_85s = [85**i for i in range(5)][::-1]
def encode(rawbytes):
"""encode raw bytes into Z85"""
# Accepts only byte arrays bounded to 4 bytes
if len(rawbytes) % 4:
raise ValueError("length must be multiple of 4, not %i" % len(rawbytes))
nvalues = len(rawbytes) / 4
values = struct.unpack('>%dI' % nvalues, rawbytes)
encoded = []
for v in values:
for offset in _85s:
encoded.append(Z85CHARS[(v // offset) % 85])
return bytes(encoded)
The provided code snippet includes necessary dependencies for implementing the `decode` function. Write a Python function `def decode(z85bytes)` to solve the following problem:
decode Z85 bytes to raw bytes, accepts ASCII string
Here is the function:
def decode(z85bytes):
"""decode Z85 bytes to raw bytes, accepts ASCII string"""
if isinstance(z85bytes, str):
try:
z85bytes = z85bytes.encode('ascii')
except UnicodeEncodeError:
raise ValueError('string argument should contain only ASCII characters')
if len(z85bytes) % 5:
raise ValueError("Z85 length must be multiple of 5, not %i" % len(z85bytes))
nvalues = len(z85bytes) / 5
values = []
for i in range(0, len(z85bytes), 5):
value = 0
for j, offset in enumerate(_85s):
value += Z85MAP[z85bytes[i + j]] * offset
values.append(value)
return struct.pack('>%dI' % nvalues, *values) | decode Z85 bytes to raw bytes, accepts ASCII string |
172,845 | import struct
from typing import Awaitable, List, Union, overload
import zmq
import zmq.asyncio
from zmq._typing import TypedDict
from zmq.error import _check_version
class _MonitorMessage(TypedDict):
event: int
value: int
endpoint: bytes
class Awaitable(Protocol[_T_co]):
def __await__(self) -> Generator[Any, None, _T_co]: ...
def recv_monitor_message(
socket: "zmq.asyncio.Socket",
flags: int = 0,
) -> Awaitable[_MonitorMessage]:
... | null |
172,846 | import struct
from typing import Awaitable, List, Union, overload
import zmq
import zmq.asyncio
from zmq._typing import TypedDict
from zmq.error import _check_version
class _MonitorMessage(TypedDict):
event: int
value: int
endpoint: bytes
def recv_monitor_message(
socket: zmq.Socket[bytes],
flags: int = 0,
) -> _MonitorMessage:
... | null |
172,847 | import struct
from typing import Awaitable, List, Union, overload
import zmq
import zmq.asyncio
from zmq._typing import TypedDict
from zmq.error import _check_version
class _MonitorMessage(TypedDict):
event: int
value: int
endpoint: bytes
def parse_monitor_message(msg: List[bytes]) -> _MonitorMessage:
"""decode zmq_monitor event messages.
Parameters
----------
msg : list(bytes)
zmq multipart message that has arrived on a monitor PAIR socket.
First frame is::
16 bit event id
32 bit event value
no padding
Second frame is the endpoint as a bytestring
Returns
-------
event : dict
event description as dict with the keys `event`, `value`, and `endpoint`.
"""
if len(msg) != 2 or len(msg[0]) != 6:
raise RuntimeError("Invalid event message format: %s" % msg)
event_id, value = struct.unpack("=hi", msg[0])
event: _MonitorMessage = {
'event': zmq.Event(event_id),
'value': zmq.Event(value),
'endpoint': msg[1],
}
return event
async def _parse_monitor_msg_async(
awaitable_msg: Awaitable[List[bytes]],
) -> _MonitorMessage:
"""Like parse_monitor_msg, but awaitable
Given awaitable message, return awaitable for the parsed monitor message.
"""
msg = await awaitable_msg
# 4.0-style event API
return parse_monitor_message(msg)
Union: _SpecialForm = ...
class Awaitable(Protocol[_T_co]):
def __await__(self) -> Generator[Any, None, _T_co]: ...
def _check_version(
min_version_info: Union[Tuple[int], Tuple[int, int], Tuple[int, int, int]],
msg: str = "Feature",
):
"""Check for libzmq
raises ZMQVersionError if current zmq version is not at least min_version
min_version_info is a tuple of integers, and will be compared against zmq.zmq_version_info().
"""
global _zmq_version_info
if _zmq_version_info is None:
from zmq import zmq_version_info
_zmq_version_info = zmq_version_info()
if _zmq_version_info < min_version_info:
min_version = ".".join(str(v) for v in min_version_info)
raise ZMQVersionError(min_version, msg)
The provided code snippet includes necessary dependencies for implementing the `recv_monitor_message` function. Write a Python function `def recv_monitor_message( socket: zmq.Socket, flags: int = 0, ) -> Union[_MonitorMessage, Awaitable[_MonitorMessage]]` to solve the following problem:
Receive and decode the given raw message from the monitoring socket and return a dict. Requires libzmq ≥ 4.0 The returned dict will have the following entries: event : int, the event id as described in libzmq.zmq_socket_monitor value : int, the event value associated with the event, see libzmq.zmq_socket_monitor endpoint : string, the affected endpoint .. versionchanged:: 23.1 Support for async sockets added. When called with a async socket, returns an awaitable for the monitor message. Parameters ---------- socket : zmq PAIR socket The PAIR socket (created by other.get_monitor_socket()) on which to recv the message flags : bitfield (int) standard zmq recv flags Returns ------- event : dict event description as dict with the keys `event`, `value`, and `endpoint`.
Here is the function:
def recv_monitor_message(
socket: zmq.Socket,
flags: int = 0,
) -> Union[_MonitorMessage, Awaitable[_MonitorMessage]]:
"""Receive and decode the given raw message from the monitoring socket and return a dict.
Requires libzmq ≥ 4.0
The returned dict will have the following entries:
event : int, the event id as described in libzmq.zmq_socket_monitor
value : int, the event value associated with the event, see libzmq.zmq_socket_monitor
endpoint : string, the affected endpoint
.. versionchanged:: 23.1
Support for async sockets added.
When called with a async socket,
returns an awaitable for the monitor message.
Parameters
----------
socket : zmq PAIR socket
The PAIR socket (created by other.get_monitor_socket()) on which to recv the message
flags : bitfield (int)
standard zmq recv flags
Returns
-------
event : dict
event description as dict with the keys `event`, `value`, and `endpoint`.
"""
_check_version((4, 0), 'libzmq event API')
# will always return a list
msg = socket.recv_multipart(flags)
# transparently handle asyncio socket,
# returns a Future instead of a dict
if isinstance(msg, Awaitable):
return _parse_monitor_msg_async(msg)
# 4.0-style event API
return parse_monitor_message(msg) | Receive and decode the given raw message from the monitoring socket and return a dict. Requires libzmq ≥ 4.0 The returned dict will have the following entries: event : int, the event id as described in libzmq.zmq_socket_monitor value : int, the event value associated with the event, see libzmq.zmq_socket_monitor endpoint : string, the affected endpoint .. versionchanged:: 23.1 Support for async sockets added. When called with a async socket, returns an awaitable for the monitor message. Parameters ---------- socket : zmq PAIR socket The PAIR socket (created by other.get_monitor_socket()) on which to recv the message flags : bitfield (int) standard zmq recv flags Returns ------- event : dict event description as dict with the keys `event`, `value`, and `endpoint`. |
172,848 | import json
from typing import Any, Dict, List, Union
Any = object()
The provided code snippet includes necessary dependencies for implementing the `dumps` function. Write a Python function `def dumps(o: Any, **kwargs) -> bytes` to solve the following problem:
Serialize object to JSON bytes (utf-8). Keyword arguments are passed along to :py:func:`json.dumps`.
Here is the function:
def dumps(o: Any, **kwargs) -> bytes:
"""Serialize object to JSON bytes (utf-8).
Keyword arguments are passed along to :py:func:`json.dumps`.
"""
return json.dumps(o, **kwargs).encode("utf8") | Serialize object to JSON bytes (utf-8). Keyword arguments are passed along to :py:func:`json.dumps`. |
172,849 | import json
from typing import Any, Dict, List, Union
Union: _SpecialForm = ...
List = _Alias()
Dict = _Alias()
The provided code snippet includes necessary dependencies for implementing the `loads` function. Write a Python function `def loads(s: Union[bytes, str], **kwargs) -> Union[Dict, List, str, int, float]` to solve the following problem:
Load object from JSON bytes (utf-8). Keyword arguments are passed along to :py:func:`json.loads`.
Here is the function:
def loads(s: Union[bytes, str], **kwargs) -> Union[Dict, List, str, int, float]:
"""Load object from JSON bytes (utf-8).
Keyword arguments are passed along to :py:func:`json.loads`.
"""
if isinstance(s, bytes):
s = s.decode("utf8")
return json.loads(s, **kwargs) | Load object from JSON bytes (utf-8). Keyword arguments are passed along to :py:func:`json.loads`. |
172,850 | import warnings
import warnings
warnings.warn("Importing from numpy.testing.utils is deprecated "
"since 1.15.0, import from numpy.testing instead.",
DeprecationWarning, stacklevel=2)
The provided code snippet includes necessary dependencies for implementing the `cast_bytes` function. Write a Python function `def cast_bytes(s, encoding='utf8', errors='strict')` to solve the following problem:
cast unicode or bytes to bytes
Here is the function:
def cast_bytes(s, encoding='utf8', errors='strict'):
"""cast unicode or bytes to bytes"""
warnings.warn(
"zmq.utils.strtypes is deprecated in pyzmq 23.",
DeprecationWarning,
stacklevel=2,
)
if isinstance(s, bytes):
return s
elif isinstance(s, str):
return s.encode(encoding, errors)
else:
raise TypeError("Expected unicode or bytes, got %r" % s) | cast unicode or bytes to bytes |
172,851 | import warnings
import warnings
warnings.warn("Importing from numpy.testing.utils is deprecated "
"since 1.15.0, import from numpy.testing instead.",
DeprecationWarning, stacklevel=2)
The provided code snippet includes necessary dependencies for implementing the `cast_unicode` function. Write a Python function `def cast_unicode(s, encoding='utf8', errors='strict')` to solve the following problem:
cast bytes or unicode to unicode
Here is the function:
def cast_unicode(s, encoding='utf8', errors='strict'):
"""cast bytes or unicode to unicode"""
warnings.warn(
"zmq.utils.strtypes is deprecated in pyzmq 23.",
DeprecationWarning,
stacklevel=2,
)
if isinstance(s, bytes):
return s.decode(encoding, errors)
elif isinstance(s, str):
return s
else:
raise TypeError("Expected unicode or bytes, got %r" % s) | cast bytes or unicode to unicode |
172,852 | from typing import Any
Any = object()
The provided code snippet includes necessary dependencies for implementing the `cast_int_addr` function. Write a Python function `def cast_int_addr(n: Any) -> int` to solve the following problem:
Cast an address to a Python int This could be a Python integer or a CFFI pointer
Here is the function:
def cast_int_addr(n: Any) -> int:
"""Cast an address to a Python int
This could be a Python integer or a CFFI pointer
"""
if isinstance(n, int):
return n
try:
import cffi # type: ignore
except ImportError:
pass
else:
# from pyzmq, this is an FFI void *
ffi = cffi.FFI()
if isinstance(n, ffi.CData):
return int(ffi.cast("size_t", n))
raise ValueError("Cannot cast %r to int" % n) | Cast an address to a Python int This could be a Python integer or a CFFI pointer |
172,853 | from typing import List, Tuple, Union
Union: _SpecialForm = ...
List = _Alias()
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 _seg_0() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:
return [
(0x0, '3'),
(0x1, '3'),
(0x2, '3'),
(0x3, '3'),
(0x4, '3'),
(0x5, '3'),
(0x6, '3'),
(0x7, '3'),
(0x8, '3'),
(0x9, '3'),
(0xA, '3'),
(0xB, '3'),
(0xC, '3'),
(0xD, '3'),
(0xE, '3'),
(0xF, '3'),
(0x10, '3'),
(0x11, '3'),
(0x12, '3'),
(0x13, '3'),
(0x14, '3'),
(0x15, '3'),
(0x16, '3'),
(0x17, '3'),
(0x18, '3'),
(0x19, '3'),
(0x1A, '3'),
(0x1B, '3'),
(0x1C, '3'),
(0x1D, '3'),
(0x1E, '3'),
(0x1F, '3'),
(0x20, '3'),
(0x21, '3'),
(0x22, '3'),
(0x23, '3'),
(0x24, '3'),
(0x25, '3'),
(0x26, '3'),
(0x27, '3'),
(0x28, '3'),
(0x29, '3'),
(0x2A, '3'),
(0x2B, '3'),
(0x2C, '3'),
(0x2D, 'V'),
(0x2E, 'V'),
(0x2F, '3'),
(0x30, 'V'),
(0x31, 'V'),
(0x32, 'V'),
(0x33, 'V'),
(0x34, 'V'),
(0x35, 'V'),
(0x36, 'V'),
(0x37, 'V'),
(0x38, 'V'),
(0x39, 'V'),
(0x3A, '3'),
(0x3B, '3'),
(0x3C, '3'),
(0x3D, '3'),
(0x3E, '3'),
(0x3F, '3'),
(0x40, '3'),
(0x41, 'M', 'a'),
(0x42, 'M', 'b'),
(0x43, 'M', 'c'),
(0x44, 'M', 'd'),
(0x45, 'M', 'e'),
(0x46, 'M', 'f'),
(0x47, 'M', 'g'),
(0x48, 'M', 'h'),
(0x49, 'M', 'i'),
(0x4A, 'M', 'j'),
(0x4B, 'M', 'k'),
(0x4C, 'M', 'l'),
(0x4D, 'M', 'm'),
(0x4E, 'M', 'n'),
(0x4F, 'M', 'o'),
(0x50, 'M', 'p'),
(0x51, 'M', 'q'),
(0x52, 'M', 'r'),
(0x53, 'M', 's'),
(0x54, 'M', 't'),
(0x55, 'M', 'u'),
(0x56, 'M', 'v'),
(0x57, 'M', 'w'),
(0x58, 'M', 'x'),
(0x59, 'M', 'y'),
(0x5A, 'M', 'z'),
(0x5B, '3'),
(0x5C, '3'),
(0x5D, '3'),
(0x5E, '3'),
(0x5F, '3'),
(0x60, '3'),
(0x61, 'V'),
(0x62, 'V'),
(0x63, 'V'),
] | null |
172,854 | from typing import List, Tuple, Union
Union: _SpecialForm = ...
List = _Alias()
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 _seg_1() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:
return [
(0x64, 'V'),
(0x65, 'V'),
(0x66, 'V'),
(0x67, 'V'),
(0x68, 'V'),
(0x69, 'V'),
(0x6A, 'V'),
(0x6B, 'V'),
(0x6C, 'V'),
(0x6D, 'V'),
(0x6E, 'V'),
(0x6F, 'V'),
(0x70, 'V'),
(0x71, 'V'),
(0x72, 'V'),
(0x73, 'V'),
(0x74, 'V'),
(0x75, 'V'),
(0x76, 'V'),
(0x77, 'V'),
(0x78, 'V'),
(0x79, 'V'),
(0x7A, 'V'),
(0x7B, '3'),
(0x7C, '3'),
(0x7D, '3'),
(0x7E, '3'),
(0x7F, '3'),
(0x80, 'X'),
(0x81, 'X'),
(0x82, 'X'),
(0x83, 'X'),
(0x84, 'X'),
(0x85, 'X'),
(0x86, 'X'),
(0x87, 'X'),
(0x88, 'X'),
(0x89, 'X'),
(0x8A, 'X'),
(0x8B, 'X'),
(0x8C, 'X'),
(0x8D, 'X'),
(0x8E, 'X'),
(0x8F, 'X'),
(0x90, 'X'),
(0x91, 'X'),
(0x92, 'X'),
(0x93, 'X'),
(0x94, 'X'),
(0x95, 'X'),
(0x96, 'X'),
(0x97, 'X'),
(0x98, 'X'),
(0x99, 'X'),
(0x9A, 'X'),
(0x9B, 'X'),
(0x9C, 'X'),
(0x9D, 'X'),
(0x9E, 'X'),
(0x9F, 'X'),
(0xA0, '3', ' '),
(0xA1, 'V'),
(0xA2, 'V'),
(0xA3, 'V'),
(0xA4, 'V'),
(0xA5, 'V'),
(0xA6, 'V'),
(0xA7, 'V'),
(0xA8, '3', ' ̈'),
(0xA9, 'V'),
(0xAA, 'M', 'a'),
(0xAB, 'V'),
(0xAC, 'V'),
(0xAD, 'I'),
(0xAE, 'V'),
(0xAF, '3', ' ̄'),
(0xB0, 'V'),
(0xB1, 'V'),
(0xB2, 'M', '2'),
(0xB3, 'M', '3'),
(0xB4, '3', ' ́'),
(0xB5, 'M', 'μ'),
(0xB6, 'V'),
(0xB7, 'V'),
(0xB8, '3', ' ̧'),
(0xB9, 'M', '1'),
(0xBA, 'M', 'o'),
(0xBB, 'V'),
(0xBC, 'M', '1⁄4'),
(0xBD, 'M', '1⁄2'),
(0xBE, 'M', '3⁄4'),
(0xBF, 'V'),
(0xC0, 'M', 'à'),
(0xC1, 'M', 'á'),
(0xC2, 'M', 'â'),
(0xC3, 'M', 'ã'),
(0xC4, 'M', 'ä'),
(0xC5, 'M', 'å'),
(0xC6, 'M', 'æ'),
(0xC7, 'M', 'ç'),
] | null |
172,855 | from typing import List, Tuple, Union
Union: _SpecialForm = ...
List = _Alias()
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 _seg_2() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:
return [
(0xC8, 'M', 'è'),
(0xC9, 'M', 'é'),
(0xCA, 'M', 'ê'),
(0xCB, 'M', 'ë'),
(0xCC, 'M', 'ì'),
(0xCD, 'M', 'í'),
(0xCE, 'M', 'î'),
(0xCF, 'M', 'ï'),
(0xD0, 'M', 'ð'),
(0xD1, 'M', 'ñ'),
(0xD2, 'M', 'ò'),
(0xD3, 'M', 'ó'),
(0xD4, 'M', 'ô'),
(0xD5, 'M', 'õ'),
(0xD6, 'M', 'ö'),
(0xD7, 'V'),
(0xD8, 'M', 'ø'),
(0xD9, 'M', 'ù'),
(0xDA, 'M', 'ú'),
(0xDB, 'M', 'û'),
(0xDC, 'M', 'ü'),
(0xDD, 'M', 'ý'),
(0xDE, 'M', 'þ'),
(0xDF, 'D', 'ss'),
(0xE0, 'V'),
(0xE1, 'V'),
(0xE2, 'V'),
(0xE3, 'V'),
(0xE4, 'V'),
(0xE5, 'V'),
(0xE6, 'V'),
(0xE7, 'V'),
(0xE8, 'V'),
(0xE9, 'V'),
(0xEA, 'V'),
(0xEB, 'V'),
(0xEC, 'V'),
(0xED, 'V'),
(0xEE, 'V'),
(0xEF, 'V'),
(0xF0, 'V'),
(0xF1, 'V'),
(0xF2, 'V'),
(0xF3, 'V'),
(0xF4, 'V'),
(0xF5, 'V'),
(0xF6, 'V'),
(0xF7, 'V'),
(0xF8, 'V'),
(0xF9, 'V'),
(0xFA, 'V'),
(0xFB, 'V'),
(0xFC, 'V'),
(0xFD, 'V'),
(0xFE, 'V'),
(0xFF, 'V'),
(0x100, 'M', 'ā'),
(0x101, 'V'),
(0x102, 'M', 'ă'),
(0x103, 'V'),
(0x104, 'M', 'ą'),
(0x105, 'V'),
(0x106, 'M', 'ć'),
(0x107, 'V'),
(0x108, 'M', 'ĉ'),
(0x109, 'V'),
(0x10A, 'M', 'ċ'),
(0x10B, 'V'),
(0x10C, 'M', 'č'),
(0x10D, 'V'),
(0x10E, 'M', 'ď'),
(0x10F, 'V'),
(0x110, 'M', 'đ'),
(0x111, 'V'),
(0x112, 'M', 'ē'),
(0x113, 'V'),
(0x114, 'M', 'ĕ'),
(0x115, 'V'),
(0x116, 'M', 'ė'),
(0x117, 'V'),
(0x118, 'M', 'ę'),
(0x119, 'V'),
(0x11A, 'M', 'ě'),
(0x11B, 'V'),
(0x11C, 'M', 'ĝ'),
(0x11D, 'V'),
(0x11E, 'M', 'ğ'),
(0x11F, 'V'),
(0x120, 'M', 'ġ'),
(0x121, 'V'),
(0x122, 'M', 'ģ'),
(0x123, 'V'),
(0x124, 'M', 'ĥ'),
(0x125, 'V'),
(0x126, 'M', 'ħ'),
(0x127, 'V'),
(0x128, 'M', 'ĩ'),
(0x129, 'V'),
(0x12A, 'M', 'ī'),
(0x12B, 'V'),
] | null |
172,856 | from typing import List, Tuple, Union
Union: _SpecialForm = ...
List = _Alias()
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 _seg_3() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:
return [
(0x12C, 'M', 'ĭ'),
(0x12D, 'V'),
(0x12E, 'M', 'į'),
(0x12F, 'V'),
(0x130, 'M', 'i̇'),
(0x131, 'V'),
(0x132, 'M', 'ij'),
(0x134, 'M', 'ĵ'),
(0x135, 'V'),
(0x136, 'M', 'ķ'),
(0x137, 'V'),
(0x139, 'M', 'ĺ'),
(0x13A, 'V'),
(0x13B, 'M', 'ļ'),
(0x13C, 'V'),
(0x13D, 'M', 'ľ'),
(0x13E, 'V'),
(0x13F, 'M', 'l·'),
(0x141, 'M', 'ł'),
(0x142, 'V'),
(0x143, 'M', 'ń'),
(0x144, 'V'),
(0x145, 'M', 'ņ'),
(0x146, 'V'),
(0x147, 'M', 'ň'),
(0x148, 'V'),
(0x149, 'M', 'ʼn'),
(0x14A, 'M', 'ŋ'),
(0x14B, 'V'),
(0x14C, 'M', 'ō'),
(0x14D, 'V'),
(0x14E, 'M', 'ŏ'),
(0x14F, 'V'),
(0x150, 'M', 'ő'),
(0x151, 'V'),
(0x152, 'M', 'œ'),
(0x153, 'V'),
(0x154, 'M', 'ŕ'),
(0x155, 'V'),
(0x156, 'M', 'ŗ'),
(0x157, 'V'),
(0x158, 'M', 'ř'),
(0x159, 'V'),
(0x15A, 'M', 'ś'),
(0x15B, 'V'),
(0x15C, 'M', 'ŝ'),
(0x15D, 'V'),
(0x15E, 'M', 'ş'),
(0x15F, 'V'),
(0x160, 'M', 'š'),
(0x161, 'V'),
(0x162, 'M', 'ţ'),
(0x163, 'V'),
(0x164, 'M', 'ť'),
(0x165, 'V'),
(0x166, 'M', 'ŧ'),
(0x167, 'V'),
(0x168, 'M', 'ũ'),
(0x169, 'V'),
(0x16A, 'M', 'ū'),
(0x16B, 'V'),
(0x16C, 'M', 'ŭ'),
(0x16D, 'V'),
(0x16E, 'M', 'ů'),
(0x16F, 'V'),
(0x170, 'M', 'ű'),
(0x171, 'V'),
(0x172, 'M', 'ų'),
(0x173, 'V'),
(0x174, 'M', 'ŵ'),
(0x175, 'V'),
(0x176, 'M', 'ŷ'),
(0x177, 'V'),
(0x178, 'M', 'ÿ'),
(0x179, 'M', 'ź'),
(0x17A, 'V'),
(0x17B, 'M', 'ż'),
(0x17C, 'V'),
(0x17D, 'M', 'ž'),
(0x17E, 'V'),
(0x17F, 'M', 's'),
(0x180, 'V'),
(0x181, 'M', 'ɓ'),
(0x182, 'M', 'ƃ'),
(0x183, 'V'),
(0x184, 'M', 'ƅ'),
(0x185, 'V'),
(0x186, 'M', 'ɔ'),
(0x187, 'M', 'ƈ'),
(0x188, 'V'),
(0x189, 'M', 'ɖ'),
(0x18A, 'M', 'ɗ'),
(0x18B, 'M', 'ƌ'),
(0x18C, 'V'),
(0x18E, 'M', 'ǝ'),
(0x18F, 'M', 'ə'),
(0x190, 'M', 'ɛ'),
(0x191, 'M', 'ƒ'),
(0x192, 'V'),
(0x193, 'M', 'ɠ'),
] | null |
172,857 | from typing import List, Tuple, Union
Union: _SpecialForm = ...
List = _Alias()
class Tuple(BaseTypingInstance):
def _is_homogenous(self):
def py__simple_getitem__(self, index):
def py__iter__(self, contextualized_node=None):
def py__getitem__(self, index_value_set, contextualized_node):
def _get_wrapped_value(self):
def name(self):
def infer_type_vars(self, value_set):
def _seg_4() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:
return [
(0x194, 'M', 'ɣ'),
(0x195, 'V'),
(0x196, 'M', 'ɩ'),
(0x197, 'M', 'ɨ'),
(0x198, 'M', 'ƙ'),
(0x199, 'V'),
(0x19C, 'M', 'ɯ'),
(0x19D, 'M', 'ɲ'),
(0x19E, 'V'),
(0x19F, 'M', 'ɵ'),
(0x1A0, 'M', 'ơ'),
(0x1A1, 'V'),
(0x1A2, 'M', 'ƣ'),
(0x1A3, 'V'),
(0x1A4, 'M', 'ƥ'),
(0x1A5, 'V'),
(0x1A6, 'M', 'ʀ'),
(0x1A7, 'M', 'ƨ'),
(0x1A8, 'V'),
(0x1A9, 'M', 'ʃ'),
(0x1AA, 'V'),
(0x1AC, 'M', 'ƭ'),
(0x1AD, 'V'),
(0x1AE, 'M', 'ʈ'),
(0x1AF, 'M', 'ư'),
(0x1B0, 'V'),
(0x1B1, 'M', 'ʊ'),
(0x1B2, 'M', 'ʋ'),
(0x1B3, 'M', 'ƴ'),
(0x1B4, 'V'),
(0x1B5, 'M', 'ƶ'),
(0x1B6, 'V'),
(0x1B7, 'M', 'ʒ'),
(0x1B8, 'M', 'ƹ'),
(0x1B9, 'V'),
(0x1BC, 'M', 'ƽ'),
(0x1BD, 'V'),
(0x1C4, 'M', 'dž'),
(0x1C7, 'M', 'lj'),
(0x1CA, 'M', 'nj'),
(0x1CD, 'M', 'ǎ'),
(0x1CE, 'V'),
(0x1CF, 'M', 'ǐ'),
(0x1D0, 'V'),
(0x1D1, 'M', 'ǒ'),
(0x1D2, 'V'),
(0x1D3, 'M', 'ǔ'),
(0x1D4, 'V'),
(0x1D5, 'M', 'ǖ'),
(0x1D6, 'V'),
(0x1D7, 'M', 'ǘ'),
(0x1D8, 'V'),
(0x1D9, 'M', 'ǚ'),
(0x1DA, 'V'),
(0x1DB, 'M', 'ǜ'),
(0x1DC, 'V'),
(0x1DE, 'M', 'ǟ'),
(0x1DF, 'V'),
(0x1E0, 'M', 'ǡ'),
(0x1E1, 'V'),
(0x1E2, 'M', 'ǣ'),
(0x1E3, 'V'),
(0x1E4, 'M', 'ǥ'),
(0x1E5, 'V'),
(0x1E6, 'M', 'ǧ'),
(0x1E7, 'V'),
(0x1E8, 'M', 'ǩ'),
(0x1E9, 'V'),
(0x1EA, 'M', 'ǫ'),
(0x1EB, 'V'),
(0x1EC, 'M', 'ǭ'),
(0x1ED, 'V'),
(0x1EE, 'M', 'ǯ'),
(0x1EF, 'V'),
(0x1F1, 'M', 'dz'),
(0x1F4, 'M', 'ǵ'),
(0x1F5, 'V'),
(0x1F6, 'M', 'ƕ'),
(0x1F7, 'M', 'ƿ'),
(0x1F8, 'M', 'ǹ'),
(0x1F9, 'V'),
(0x1FA, 'M', 'ǻ'),
(0x1FB, 'V'),
(0x1FC, 'M', 'ǽ'),
(0x1FD, 'V'),
(0x1FE, 'M', 'ǿ'),
(0x1FF, 'V'),
(0x200, 'M', 'ȁ'),
(0x201, 'V'),
(0x202, 'M', 'ȃ'),
(0x203, 'V'),
(0x204, 'M', 'ȅ'),
(0x205, 'V'),
(0x206, 'M', 'ȇ'),
(0x207, 'V'),
(0x208, 'M', 'ȉ'),
(0x209, 'V'),
(0x20A, 'M', 'ȋ'),
(0x20B, 'V'),
(0x20C, 'M', 'ȍ'),
] | null |
172,858 | from typing import List, Tuple, Union
Union: _SpecialForm = ...
List = _Alias()
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 _seg_5() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:
return [
(0x20D, 'V'),
(0x20E, 'M', 'ȏ'),
(0x20F, 'V'),
(0x210, 'M', 'ȑ'),
(0x211, 'V'),
(0x212, 'M', 'ȓ'),
(0x213, 'V'),
(0x214, 'M', 'ȕ'),
(0x215, 'V'),
(0x216, 'M', 'ȗ'),
(0x217, 'V'),
(0x218, 'M', 'ș'),
(0x219, 'V'),
(0x21A, 'M', 'ț'),
(0x21B, 'V'),
(0x21C, 'M', 'ȝ'),
(0x21D, 'V'),
(0x21E, 'M', 'ȟ'),
(0x21F, 'V'),
(0x220, 'M', 'ƞ'),
(0x221, 'V'),
(0x222, 'M', 'ȣ'),
(0x223, 'V'),
(0x224, 'M', 'ȥ'),
(0x225, 'V'),
(0x226, 'M', 'ȧ'),
(0x227, 'V'),
(0x228, 'M', 'ȩ'),
(0x229, 'V'),
(0x22A, 'M', 'ȫ'),
(0x22B, 'V'),
(0x22C, 'M', 'ȭ'),
(0x22D, 'V'),
(0x22E, 'M', 'ȯ'),
(0x22F, 'V'),
(0x230, 'M', 'ȱ'),
(0x231, 'V'),
(0x232, 'M', 'ȳ'),
(0x233, 'V'),
(0x23A, 'M', 'ⱥ'),
(0x23B, 'M', 'ȼ'),
(0x23C, 'V'),
(0x23D, 'M', 'ƚ'),
(0x23E, 'M', 'ⱦ'),
(0x23F, 'V'),
(0x241, 'M', 'ɂ'),
(0x242, 'V'),
(0x243, 'M', 'ƀ'),
(0x244, 'M', 'ʉ'),
(0x245, 'M', 'ʌ'),
(0x246, 'M', 'ɇ'),
(0x247, 'V'),
(0x248, 'M', 'ɉ'),
(0x249, 'V'),
(0x24A, 'M', 'ɋ'),
(0x24B, 'V'),
(0x24C, 'M', 'ɍ'),
(0x24D, 'V'),
(0x24E, 'M', 'ɏ'),
(0x24F, 'V'),
(0x2B0, 'M', 'h'),
(0x2B1, 'M', 'ɦ'),
(0x2B2, 'M', 'j'),
(0x2B3, 'M', 'r'),
(0x2B4, 'M', 'ɹ'),
(0x2B5, 'M', 'ɻ'),
(0x2B6, 'M', 'ʁ'),
(0x2B7, 'M', 'w'),
(0x2B8, 'M', 'y'),
(0x2B9, 'V'),
(0x2D8, '3', ' ̆'),
(0x2D9, '3', ' ̇'),
(0x2DA, '3', ' ̊'),
(0x2DB, '3', ' ̨'),
(0x2DC, '3', ' ̃'),
(0x2DD, '3', ' ̋'),
(0x2DE, 'V'),
(0x2E0, 'M', 'ɣ'),
(0x2E1, 'M', 'l'),
(0x2E2, 'M', 's'),
(0x2E3, 'M', 'x'),
(0x2E4, 'M', 'ʕ'),
(0x2E5, 'V'),
(0x340, 'M', '̀'),
(0x341, 'M', '́'),
(0x342, 'V'),
(0x343, 'M', '̓'),
(0x344, 'M', '̈́'),
(0x345, 'M', 'ι'),
(0x346, 'V'),
(0x34F, 'I'),
(0x350, 'V'),
(0x370, 'M', 'ͱ'),
(0x371, 'V'),
(0x372, 'M', 'ͳ'),
(0x373, 'V'),
(0x374, 'M', 'ʹ'),
(0x375, 'V'),
(0x376, 'M', 'ͷ'),
(0x377, 'V'),
] | null |
172,859 | from typing import List, Tuple, Union
Union: _SpecialForm = ...
List = _Alias()
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 _seg_6() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:
return [
(0x378, 'X'),
(0x37A, '3', ' ι'),
(0x37B, 'V'),
(0x37E, '3', ';'),
(0x37F, 'M', 'ϳ'),
(0x380, 'X'),
(0x384, '3', ' ́'),
(0x385, '3', ' ̈́'),
(0x386, 'M', 'ά'),
(0x387, 'M', '·'),
(0x388, 'M', 'έ'),
(0x389, 'M', 'ή'),
(0x38A, 'M', 'ί'),
(0x38B, 'X'),
(0x38C, 'M', 'ό'),
(0x38D, 'X'),
(0x38E, 'M', 'ύ'),
(0x38F, 'M', 'ώ'),
(0x390, 'V'),
(0x391, 'M', 'α'),
(0x392, 'M', 'β'),
(0x393, 'M', 'γ'),
(0x394, 'M', 'δ'),
(0x395, 'M', 'ε'),
(0x396, 'M', 'ζ'),
(0x397, 'M', 'η'),
(0x398, 'M', 'θ'),
(0x399, 'M', 'ι'),
(0x39A, 'M', 'κ'),
(0x39B, 'M', 'λ'),
(0x39C, 'M', 'μ'),
(0x39D, 'M', 'ν'),
(0x39E, 'M', 'ξ'),
(0x39F, 'M', 'ο'),
(0x3A0, 'M', 'π'),
(0x3A1, 'M', 'ρ'),
(0x3A2, 'X'),
(0x3A3, 'M', 'σ'),
(0x3A4, 'M', 'τ'),
(0x3A5, 'M', 'υ'),
(0x3A6, 'M', 'φ'),
(0x3A7, 'M', 'χ'),
(0x3A8, 'M', 'ψ'),
(0x3A9, 'M', 'ω'),
(0x3AA, 'M', 'ϊ'),
(0x3AB, 'M', 'ϋ'),
(0x3AC, 'V'),
(0x3C2, 'D', 'σ'),
(0x3C3, 'V'),
(0x3CF, 'M', 'ϗ'),
(0x3D0, 'M', 'β'),
(0x3D1, 'M', 'θ'),
(0x3D2, 'M', 'υ'),
(0x3D3, 'M', 'ύ'),
(0x3D4, 'M', 'ϋ'),
(0x3D5, 'M', 'φ'),
(0x3D6, 'M', 'π'),
(0x3D7, 'V'),
(0x3D8, 'M', 'ϙ'),
(0x3D9, 'V'),
(0x3DA, 'M', 'ϛ'),
(0x3DB, 'V'),
(0x3DC, 'M', 'ϝ'),
(0x3DD, 'V'),
(0x3DE, 'M', 'ϟ'),
(0x3DF, 'V'),
(0x3E0, 'M', 'ϡ'),
(0x3E1, 'V'),
(0x3E2, 'M', 'ϣ'),
(0x3E3, 'V'),
(0x3E4, 'M', 'ϥ'),
(0x3E5, 'V'),
(0x3E6, 'M', 'ϧ'),
(0x3E7, 'V'),
(0x3E8, 'M', 'ϩ'),
(0x3E9, 'V'),
(0x3EA, 'M', 'ϫ'),
(0x3EB, 'V'),
(0x3EC, 'M', 'ϭ'),
(0x3ED, 'V'),
(0x3EE, 'M', 'ϯ'),
(0x3EF, 'V'),
(0x3F0, 'M', 'κ'),
(0x3F1, 'M', 'ρ'),
(0x3F2, 'M', 'σ'),
(0x3F3, 'V'),
(0x3F4, 'M', 'θ'),
(0x3F5, 'M', 'ε'),
(0x3F6, 'V'),
(0x3F7, 'M', 'ϸ'),
(0x3F8, 'V'),
(0x3F9, 'M', 'σ'),
(0x3FA, 'M', 'ϻ'),
(0x3FB, 'V'),
(0x3FD, 'M', 'ͻ'),
(0x3FE, 'M', 'ͼ'),
(0x3FF, 'M', 'ͽ'),
(0x400, 'M', 'ѐ'),
(0x401, 'M', 'ё'),
(0x402, 'M', 'ђ'),
] | null |
172,860 | from typing import List, Tuple, Union
Union: _SpecialForm = ...
List = _Alias()
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 _seg_7() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:
return [
(0x403, 'M', 'ѓ'),
(0x404, 'M', 'є'),
(0x405, 'M', 'ѕ'),
(0x406, 'M', 'і'),
(0x407, 'M', 'ї'),
(0x408, 'M', 'ј'),
(0x409, 'M', 'љ'),
(0x40A, 'M', 'њ'),
(0x40B, 'M', 'ћ'),
(0x40C, 'M', 'ќ'),
(0x40D, 'M', 'ѝ'),
(0x40E, 'M', 'ў'),
(0x40F, 'M', 'џ'),
(0x410, 'M', 'а'),
(0x411, 'M', 'б'),
(0x412, 'M', 'в'),
(0x413, 'M', 'г'),
(0x414, 'M', 'д'),
(0x415, 'M', 'е'),
(0x416, 'M', 'ж'),
(0x417, 'M', 'з'),
(0x418, 'M', 'и'),
(0x419, 'M', 'й'),
(0x41A, 'M', 'к'),
(0x41B, 'M', 'л'),
(0x41C, 'M', 'м'),
(0x41D, 'M', 'н'),
(0x41E, 'M', 'о'),
(0x41F, 'M', 'п'),
(0x420, 'M', 'р'),
(0x421, 'M', 'с'),
(0x422, 'M', 'т'),
(0x423, 'M', 'у'),
(0x424, 'M', 'ф'),
(0x425, 'M', 'х'),
(0x426, 'M', 'ц'),
(0x427, 'M', 'ч'),
(0x428, 'M', 'ш'),
(0x429, 'M', 'щ'),
(0x42A, 'M', 'ъ'),
(0x42B, 'M', 'ы'),
(0x42C, 'M', 'ь'),
(0x42D, 'M', 'э'),
(0x42E, 'M', 'ю'),
(0x42F, 'M', 'я'),
(0x430, 'V'),
(0x460, 'M', 'ѡ'),
(0x461, 'V'),
(0x462, 'M', 'ѣ'),
(0x463, 'V'),
(0x464, 'M', 'ѥ'),
(0x465, 'V'),
(0x466, 'M', 'ѧ'),
(0x467, 'V'),
(0x468, 'M', 'ѩ'),
(0x469, 'V'),
(0x46A, 'M', 'ѫ'),
(0x46B, 'V'),
(0x46C, 'M', 'ѭ'),
(0x46D, 'V'),
(0x46E, 'M', 'ѯ'),
(0x46F, 'V'),
(0x470, 'M', 'ѱ'),
(0x471, 'V'),
(0x472, 'M', 'ѳ'),
(0x473, 'V'),
(0x474, 'M', 'ѵ'),
(0x475, 'V'),
(0x476, 'M', 'ѷ'),
(0x477, 'V'),
(0x478, 'M', 'ѹ'),
(0x479, 'V'),
(0x47A, 'M', 'ѻ'),
(0x47B, 'V'),
(0x47C, 'M', 'ѽ'),
(0x47D, 'V'),
(0x47E, 'M', 'ѿ'),
(0x47F, 'V'),
(0x480, 'M', 'ҁ'),
(0x481, 'V'),
(0x48A, 'M', 'ҋ'),
(0x48B, 'V'),
(0x48C, 'M', 'ҍ'),
(0x48D, 'V'),
(0x48E, 'M', 'ҏ'),
(0x48F, 'V'),
(0x490, 'M', 'ґ'),
(0x491, 'V'),
(0x492, 'M', 'ғ'),
(0x493, 'V'),
(0x494, 'M', 'ҕ'),
(0x495, 'V'),
(0x496, 'M', 'җ'),
(0x497, 'V'),
(0x498, 'M', 'ҙ'),
(0x499, 'V'),
(0x49A, 'M', 'қ'),
(0x49B, 'V'),
(0x49C, 'M', 'ҝ'),
(0x49D, 'V'),
] | null |
172,861 | from typing import List, Tuple, Union
Union: _SpecialForm = ...
List = _Alias()
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 _seg_8() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:
return [
(0x49E, 'M', 'ҟ'),
(0x49F, 'V'),
(0x4A0, 'M', 'ҡ'),
(0x4A1, 'V'),
(0x4A2, 'M', 'ң'),
(0x4A3, 'V'),
(0x4A4, 'M', 'ҥ'),
(0x4A5, 'V'),
(0x4A6, 'M', 'ҧ'),
(0x4A7, 'V'),
(0x4A8, 'M', 'ҩ'),
(0x4A9, 'V'),
(0x4AA, 'M', 'ҫ'),
(0x4AB, 'V'),
(0x4AC, 'M', 'ҭ'),
(0x4AD, 'V'),
(0x4AE, 'M', 'ү'),
(0x4AF, 'V'),
(0x4B0, 'M', 'ұ'),
(0x4B1, 'V'),
(0x4B2, 'M', 'ҳ'),
(0x4B3, 'V'),
(0x4B4, 'M', 'ҵ'),
(0x4B5, 'V'),
(0x4B6, 'M', 'ҷ'),
(0x4B7, 'V'),
(0x4B8, 'M', 'ҹ'),
(0x4B9, 'V'),
(0x4BA, 'M', 'һ'),
(0x4BB, 'V'),
(0x4BC, 'M', 'ҽ'),
(0x4BD, 'V'),
(0x4BE, 'M', 'ҿ'),
(0x4BF, 'V'),
(0x4C0, 'X'),
(0x4C1, 'M', 'ӂ'),
(0x4C2, 'V'),
(0x4C3, 'M', 'ӄ'),
(0x4C4, 'V'),
(0x4C5, 'M', 'ӆ'),
(0x4C6, 'V'),
(0x4C7, 'M', 'ӈ'),
(0x4C8, 'V'),
(0x4C9, 'M', 'ӊ'),
(0x4CA, 'V'),
(0x4CB, 'M', 'ӌ'),
(0x4CC, 'V'),
(0x4CD, 'M', 'ӎ'),
(0x4CE, 'V'),
(0x4D0, 'M', 'ӑ'),
(0x4D1, 'V'),
(0x4D2, 'M', 'ӓ'),
(0x4D3, 'V'),
(0x4D4, 'M', 'ӕ'),
(0x4D5, 'V'),
(0x4D6, 'M', 'ӗ'),
(0x4D7, 'V'),
(0x4D8, 'M', 'ә'),
(0x4D9, 'V'),
(0x4DA, 'M', 'ӛ'),
(0x4DB, 'V'),
(0x4DC, 'M', 'ӝ'),
(0x4DD, 'V'),
(0x4DE, 'M', 'ӟ'),
(0x4DF, 'V'),
(0x4E0, 'M', 'ӡ'),
(0x4E1, 'V'),
(0x4E2, 'M', 'ӣ'),
(0x4E3, 'V'),
(0x4E4, 'M', 'ӥ'),
(0x4E5, 'V'),
(0x4E6, 'M', 'ӧ'),
(0x4E7, 'V'),
(0x4E8, 'M', 'ө'),
(0x4E9, 'V'),
(0x4EA, 'M', 'ӫ'),
(0x4EB, 'V'),
(0x4EC, 'M', 'ӭ'),
(0x4ED, 'V'),
(0x4EE, 'M', 'ӯ'),
(0x4EF, 'V'),
(0x4F0, 'M', 'ӱ'),
(0x4F1, 'V'),
(0x4F2, 'M', 'ӳ'),
(0x4F3, 'V'),
(0x4F4, 'M', 'ӵ'),
(0x4F5, 'V'),
(0x4F6, 'M', 'ӷ'),
(0x4F7, 'V'),
(0x4F8, 'M', 'ӹ'),
(0x4F9, 'V'),
(0x4FA, 'M', 'ӻ'),
(0x4FB, 'V'),
(0x4FC, 'M', 'ӽ'),
(0x4FD, 'V'),
(0x4FE, 'M', 'ӿ'),
(0x4FF, 'V'),
(0x500, 'M', 'ԁ'),
(0x501, 'V'),
(0x502, 'M', 'ԃ'),
] | null |
172,862 | from typing import List, Tuple, Union
Union: _SpecialForm = ...
List = _Alias()
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 _seg_9() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:
return [
(0x503, 'V'),
(0x504, 'M', 'ԅ'),
(0x505, 'V'),
(0x506, 'M', 'ԇ'),
(0x507, 'V'),
(0x508, 'M', 'ԉ'),
(0x509, 'V'),
(0x50A, 'M', 'ԋ'),
(0x50B, 'V'),
(0x50C, 'M', 'ԍ'),
(0x50D, 'V'),
(0x50E, 'M', 'ԏ'),
(0x50F, 'V'),
(0x510, 'M', 'ԑ'),
(0x511, 'V'),
(0x512, 'M', 'ԓ'),
(0x513, 'V'),
(0x514, 'M', 'ԕ'),
(0x515, 'V'),
(0x516, 'M', 'ԗ'),
(0x517, 'V'),
(0x518, 'M', 'ԙ'),
(0x519, 'V'),
(0x51A, 'M', 'ԛ'),
(0x51B, 'V'),
(0x51C, 'M', 'ԝ'),
(0x51D, 'V'),
(0x51E, 'M', 'ԟ'),
(0x51F, 'V'),
(0x520, 'M', 'ԡ'),
(0x521, 'V'),
(0x522, 'M', 'ԣ'),
(0x523, 'V'),
(0x524, 'M', 'ԥ'),
(0x525, 'V'),
(0x526, 'M', 'ԧ'),
(0x527, 'V'),
(0x528, 'M', 'ԩ'),
(0x529, 'V'),
(0x52A, 'M', 'ԫ'),
(0x52B, 'V'),
(0x52C, 'M', 'ԭ'),
(0x52D, 'V'),
(0x52E, 'M', 'ԯ'),
(0x52F, 'V'),
(0x530, 'X'),
(0x531, 'M', 'ա'),
(0x532, 'M', 'բ'),
(0x533, 'M', 'գ'),
(0x534, 'M', 'դ'),
(0x535, 'M', 'ե'),
(0x536, 'M', 'զ'),
(0x537, 'M', 'է'),
(0x538, 'M', 'ը'),
(0x539, 'M', 'թ'),
(0x53A, 'M', 'ժ'),
(0x53B, 'M', 'ի'),
(0x53C, 'M', 'լ'),
(0x53D, 'M', 'խ'),
(0x53E, 'M', 'ծ'),
(0x53F, 'M', 'կ'),
(0x540, 'M', 'հ'),
(0x541, 'M', 'ձ'),
(0x542, 'M', 'ղ'),
(0x543, 'M', 'ճ'),
(0x544, 'M', 'մ'),
(0x545, 'M', 'յ'),
(0x546, 'M', 'ն'),
(0x547, 'M', 'շ'),
(0x548, 'M', 'ո'),
(0x549, 'M', 'չ'),
(0x54A, 'M', 'պ'),
(0x54B, 'M', 'ջ'),
(0x54C, 'M', 'ռ'),
(0x54D, 'M', 'ս'),
(0x54E, 'M', 'վ'),
(0x54F, 'M', 'տ'),
(0x550, 'M', 'ր'),
(0x551, 'M', 'ց'),
(0x552, 'M', 'ւ'),
(0x553, 'M', 'փ'),
(0x554, 'M', 'ք'),
(0x555, 'M', 'օ'),
(0x556, 'M', 'ֆ'),
(0x557, 'X'),
(0x559, 'V'),
(0x587, 'M', 'եւ'),
(0x588, 'V'),
(0x58B, 'X'),
(0x58D, 'V'),
(0x590, 'X'),
(0x591, 'V'),
(0x5C8, 'X'),
(0x5D0, 'V'),
(0x5EB, 'X'),
(0x5EF, 'V'),
(0x5F5, 'X'),
(0x606, 'V'),
(0x61C, 'X'),
(0x61D, 'V'),
] | null |
172,863 | from typing import List, Tuple, Union
Union: _SpecialForm = ...
List = _Alias()
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 _seg_10() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:
return [
(0x675, 'M', 'اٴ'),
(0x676, 'M', 'وٴ'),
(0x677, 'M', 'ۇٴ'),
(0x678, 'M', 'يٴ'),
(0x679, 'V'),
(0x6DD, 'X'),
(0x6DE, 'V'),
(0x70E, 'X'),
(0x710, 'V'),
(0x74B, 'X'),
(0x74D, 'V'),
(0x7B2, 'X'),
(0x7C0, 'V'),
(0x7FB, 'X'),
(0x7FD, 'V'),
(0x82E, 'X'),
(0x830, 'V'),
(0x83F, 'X'),
(0x840, 'V'),
(0x85C, 'X'),
(0x85E, 'V'),
(0x85F, 'X'),
(0x860, 'V'),
(0x86B, 'X'),
(0x870, 'V'),
(0x88F, 'X'),
(0x898, 'V'),
(0x8E2, 'X'),
(0x8E3, 'V'),
(0x958, 'M', 'क़'),
(0x959, 'M', 'ख़'),
(0x95A, 'M', 'ग़'),
(0x95B, 'M', 'ज़'),
(0x95C, 'M', 'ड़'),
(0x95D, 'M', 'ढ़'),
(0x95E, 'M', 'फ़'),
(0x95F, 'M', 'य़'),
(0x960, 'V'),
(0x984, 'X'),
(0x985, 'V'),
(0x98D, 'X'),
(0x98F, 'V'),
(0x991, 'X'),
(0x993, 'V'),
(0x9A9, 'X'),
(0x9AA, 'V'),
(0x9B1, 'X'),
(0x9B2, 'V'),
(0x9B3, 'X'),
(0x9B6, 'V'),
(0x9BA, 'X'),
(0x9BC, 'V'),
(0x9C5, 'X'),
(0x9C7, 'V'),
(0x9C9, 'X'),
(0x9CB, 'V'),
(0x9CF, 'X'),
(0x9D7, 'V'),
(0x9D8, 'X'),
(0x9DC, 'M', 'ড়'),
(0x9DD, 'M', 'ঢ়'),
(0x9DE, 'X'),
(0x9DF, 'M', 'য়'),
(0x9E0, 'V'),
(0x9E4, 'X'),
(0x9E6, 'V'),
(0x9FF, 'X'),
(0xA01, 'V'),
(0xA04, 'X'),
(0xA05, 'V'),
(0xA0B, 'X'),
(0xA0F, 'V'),
(0xA11, 'X'),
(0xA13, 'V'),
(0xA29, 'X'),
(0xA2A, 'V'),
(0xA31, 'X'),
(0xA32, 'V'),
(0xA33, 'M', 'ਲ਼'),
(0xA34, 'X'),
(0xA35, 'V'),
(0xA36, 'M', 'ਸ਼'),
(0xA37, 'X'),
(0xA38, 'V'),
(0xA3A, 'X'),
(0xA3C, 'V'),
(0xA3D, 'X'),
(0xA3E, 'V'),
(0xA43, 'X'),
(0xA47, 'V'),
(0xA49, 'X'),
(0xA4B, 'V'),
(0xA4E, 'X'),
(0xA51, 'V'),
(0xA52, 'X'),
(0xA59, 'M', 'ਖ਼'),
(0xA5A, 'M', 'ਗ਼'),
(0xA5B, 'M', 'ਜ਼'),
(0xA5C, 'V'),
(0xA5D, 'X'),
] | null |
172,864 | from typing import List, Tuple, Union
Union: _SpecialForm = ...
List = _Alias()
class Tuple(BaseTypingInstance):
def _is_homogenous(self):
def py__simple_getitem__(self, index):
def py__iter__(self, contextualized_node=None):
def py__getitem__(self, index_value_set, contextualized_node):
def _get_wrapped_value(self):
def name(self):
def infer_type_vars(self, value_set):
def _seg_11() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:
return [
(0xA5E, 'M', 'ਫ਼'),
(0xA5F, 'X'),
(0xA66, 'V'),
(0xA77, 'X'),
(0xA81, 'V'),
(0xA84, 'X'),
(0xA85, 'V'),
(0xA8E, 'X'),
(0xA8F, 'V'),
(0xA92, 'X'),
(0xA93, 'V'),
(0xAA9, 'X'),
(0xAAA, 'V'),
(0xAB1, 'X'),
(0xAB2, 'V'),
(0xAB4, 'X'),
(0xAB5, 'V'),
(0xABA, 'X'),
(0xABC, 'V'),
(0xAC6, 'X'),
(0xAC7, 'V'),
(0xACA, 'X'),
(0xACB, 'V'),
(0xACE, 'X'),
(0xAD0, 'V'),
(0xAD1, 'X'),
(0xAE0, 'V'),
(0xAE4, 'X'),
(0xAE6, 'V'),
(0xAF2, 'X'),
(0xAF9, 'V'),
(0xB00, 'X'),
(0xB01, 'V'),
(0xB04, 'X'),
(0xB05, 'V'),
(0xB0D, 'X'),
(0xB0F, 'V'),
(0xB11, 'X'),
(0xB13, 'V'),
(0xB29, 'X'),
(0xB2A, 'V'),
(0xB31, 'X'),
(0xB32, 'V'),
(0xB34, 'X'),
(0xB35, 'V'),
(0xB3A, 'X'),
(0xB3C, 'V'),
(0xB45, 'X'),
(0xB47, 'V'),
(0xB49, 'X'),
(0xB4B, 'V'),
(0xB4E, 'X'),
(0xB55, 'V'),
(0xB58, 'X'),
(0xB5C, 'M', 'ଡ଼'),
(0xB5D, 'M', 'ଢ଼'),
(0xB5E, 'X'),
(0xB5F, 'V'),
(0xB64, 'X'),
(0xB66, 'V'),
(0xB78, 'X'),
(0xB82, 'V'),
(0xB84, 'X'),
(0xB85, 'V'),
(0xB8B, 'X'),
(0xB8E, 'V'),
(0xB91, 'X'),
(0xB92, 'V'),
(0xB96, 'X'),
(0xB99, 'V'),
(0xB9B, 'X'),
(0xB9C, 'V'),
(0xB9D, 'X'),
(0xB9E, 'V'),
(0xBA0, 'X'),
(0xBA3, 'V'),
(0xBA5, 'X'),
(0xBA8, 'V'),
(0xBAB, 'X'),
(0xBAE, 'V'),
(0xBBA, 'X'),
(0xBBE, 'V'),
(0xBC3, 'X'),
(0xBC6, 'V'),
(0xBC9, 'X'),
(0xBCA, 'V'),
(0xBCE, 'X'),
(0xBD0, 'V'),
(0xBD1, 'X'),
(0xBD7, 'V'),
(0xBD8, 'X'),
(0xBE6, 'V'),
(0xBFB, 'X'),
(0xC00, 'V'),
(0xC0D, 'X'),
(0xC0E, 'V'),
(0xC11, 'X'),
(0xC12, 'V'),
(0xC29, 'X'),
(0xC2A, 'V'),
] | null |
172,865 | from typing import List, Tuple, Union
Union: _SpecialForm = ...
List = _Alias()
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 _seg_12() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:
return [
(0xC3A, 'X'),
(0xC3C, 'V'),
(0xC45, 'X'),
(0xC46, 'V'),
(0xC49, 'X'),
(0xC4A, 'V'),
(0xC4E, 'X'),
(0xC55, 'V'),
(0xC57, 'X'),
(0xC58, 'V'),
(0xC5B, 'X'),
(0xC5D, 'V'),
(0xC5E, 'X'),
(0xC60, 'V'),
(0xC64, 'X'),
(0xC66, 'V'),
(0xC70, 'X'),
(0xC77, 'V'),
(0xC8D, 'X'),
(0xC8E, 'V'),
(0xC91, 'X'),
(0xC92, 'V'),
(0xCA9, 'X'),
(0xCAA, 'V'),
(0xCB4, 'X'),
(0xCB5, 'V'),
(0xCBA, 'X'),
(0xCBC, 'V'),
(0xCC5, 'X'),
(0xCC6, 'V'),
(0xCC9, 'X'),
(0xCCA, 'V'),
(0xCCE, 'X'),
(0xCD5, 'V'),
(0xCD7, 'X'),
(0xCDD, 'V'),
(0xCDF, 'X'),
(0xCE0, 'V'),
(0xCE4, 'X'),
(0xCE6, 'V'),
(0xCF0, 'X'),
(0xCF1, 'V'),
(0xCF4, 'X'),
(0xD00, 'V'),
(0xD0D, 'X'),
(0xD0E, 'V'),
(0xD11, 'X'),
(0xD12, 'V'),
(0xD45, 'X'),
(0xD46, 'V'),
(0xD49, 'X'),
(0xD4A, 'V'),
(0xD50, 'X'),
(0xD54, 'V'),
(0xD64, 'X'),
(0xD66, 'V'),
(0xD80, 'X'),
(0xD81, 'V'),
(0xD84, 'X'),
(0xD85, 'V'),
(0xD97, 'X'),
(0xD9A, 'V'),
(0xDB2, 'X'),
(0xDB3, 'V'),
(0xDBC, 'X'),
(0xDBD, 'V'),
(0xDBE, 'X'),
(0xDC0, 'V'),
(0xDC7, 'X'),
(0xDCA, 'V'),
(0xDCB, 'X'),
(0xDCF, 'V'),
(0xDD5, 'X'),
(0xDD6, 'V'),
(0xDD7, 'X'),
(0xDD8, 'V'),
(0xDE0, 'X'),
(0xDE6, 'V'),
(0xDF0, 'X'),
(0xDF2, 'V'),
(0xDF5, 'X'),
(0xE01, 'V'),
(0xE33, 'M', 'ํา'),
(0xE34, 'V'),
(0xE3B, 'X'),
(0xE3F, 'V'),
(0xE5C, 'X'),
(0xE81, 'V'),
(0xE83, 'X'),
(0xE84, 'V'),
(0xE85, 'X'),
(0xE86, 'V'),
(0xE8B, 'X'),
(0xE8C, 'V'),
(0xEA4, 'X'),
(0xEA5, 'V'),
(0xEA6, 'X'),
(0xEA7, 'V'),
(0xEB3, 'M', 'ໍາ'),
(0xEB4, 'V'),
] | null |
172,866 | from typing import List, Tuple, Union
Union: _SpecialForm = ...
List = _Alias()
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 _seg_13() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:
return [
(0xEBE, 'X'),
(0xEC0, 'V'),
(0xEC5, 'X'),
(0xEC6, 'V'),
(0xEC7, 'X'),
(0xEC8, 'V'),
(0xECF, 'X'),
(0xED0, 'V'),
(0xEDA, 'X'),
(0xEDC, 'M', 'ຫນ'),
(0xEDD, 'M', 'ຫມ'),
(0xEDE, 'V'),
(0xEE0, 'X'),
(0xF00, 'V'),
(0xF0C, 'M', '་'),
(0xF0D, 'V'),
(0xF43, 'M', 'གྷ'),
(0xF44, 'V'),
(0xF48, 'X'),
(0xF49, 'V'),
(0xF4D, 'M', 'ཌྷ'),
(0xF4E, 'V'),
(0xF52, 'M', 'དྷ'),
(0xF53, 'V'),
(0xF57, 'M', 'བྷ'),
(0xF58, 'V'),
(0xF5C, 'M', 'ཛྷ'),
(0xF5D, 'V'),
(0xF69, 'M', 'ཀྵ'),
(0xF6A, 'V'),
(0xF6D, 'X'),
(0xF71, 'V'),
(0xF73, 'M', 'ཱི'),
(0xF74, 'V'),
(0xF75, 'M', 'ཱུ'),
(0xF76, 'M', 'ྲྀ'),
(0xF77, 'M', 'ྲཱྀ'),
(0xF78, 'M', 'ླྀ'),
(0xF79, 'M', 'ླཱྀ'),
(0xF7A, 'V'),
(0xF81, 'M', 'ཱྀ'),
(0xF82, 'V'),
(0xF93, 'M', 'ྒྷ'),
(0xF94, 'V'),
(0xF98, 'X'),
(0xF99, 'V'),
(0xF9D, 'M', 'ྜྷ'),
(0xF9E, 'V'),
(0xFA2, 'M', 'ྡྷ'),
(0xFA3, 'V'),
(0xFA7, 'M', 'ྦྷ'),
(0xFA8, 'V'),
(0xFAC, 'M', 'ྫྷ'),
(0xFAD, 'V'),
(0xFB9, 'M', 'ྐྵ'),
(0xFBA, 'V'),
(0xFBD, 'X'),
(0xFBE, 'V'),
(0xFCD, 'X'),
(0xFCE, 'V'),
(0xFDB, 'X'),
(0x1000, 'V'),
(0x10A0, 'X'),
(0x10C7, 'M', 'ⴧ'),
(0x10C8, 'X'),
(0x10CD, 'M', 'ⴭ'),
(0x10CE, 'X'),
(0x10D0, 'V'),
(0x10FC, 'M', 'ნ'),
(0x10FD, 'V'),
(0x115F, 'X'),
(0x1161, 'V'),
(0x1249, 'X'),
(0x124A, 'V'),
(0x124E, 'X'),
(0x1250, 'V'),
(0x1257, 'X'),
(0x1258, 'V'),
(0x1259, 'X'),
(0x125A, 'V'),
(0x125E, 'X'),
(0x1260, 'V'),
(0x1289, 'X'),
(0x128A, 'V'),
(0x128E, 'X'),
(0x1290, 'V'),
(0x12B1, 'X'),
(0x12B2, 'V'),
(0x12B6, 'X'),
(0x12B8, 'V'),
(0x12BF, 'X'),
(0x12C0, 'V'),
(0x12C1, 'X'),
(0x12C2, 'V'),
(0x12C6, 'X'),
(0x12C8, 'V'),
(0x12D7, 'X'),
(0x12D8, 'V'),
(0x1311, 'X'),
(0x1312, 'V'),
] | null |
172,867 | from typing import List, Tuple, Union
Union: _SpecialForm = ...
List = _Alias()
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 _seg_14() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:
return [
(0x1316, 'X'),
(0x1318, 'V'),
(0x135B, 'X'),
(0x135D, 'V'),
(0x137D, 'X'),
(0x1380, 'V'),
(0x139A, 'X'),
(0x13A0, 'V'),
(0x13F6, 'X'),
(0x13F8, 'M', 'Ᏸ'),
(0x13F9, 'M', 'Ᏹ'),
(0x13FA, 'M', 'Ᏺ'),
(0x13FB, 'M', 'Ᏻ'),
(0x13FC, 'M', 'Ᏼ'),
(0x13FD, 'M', 'Ᏽ'),
(0x13FE, 'X'),
(0x1400, 'V'),
(0x1680, 'X'),
(0x1681, 'V'),
(0x169D, 'X'),
(0x16A0, 'V'),
(0x16F9, 'X'),
(0x1700, 'V'),
(0x1716, 'X'),
(0x171F, 'V'),
(0x1737, 'X'),
(0x1740, 'V'),
(0x1754, 'X'),
(0x1760, 'V'),
(0x176D, 'X'),
(0x176E, 'V'),
(0x1771, 'X'),
(0x1772, 'V'),
(0x1774, 'X'),
(0x1780, 'V'),
(0x17B4, 'X'),
(0x17B6, 'V'),
(0x17DE, 'X'),
(0x17E0, 'V'),
(0x17EA, 'X'),
(0x17F0, 'V'),
(0x17FA, 'X'),
(0x1800, 'V'),
(0x1806, 'X'),
(0x1807, 'V'),
(0x180B, 'I'),
(0x180E, 'X'),
(0x180F, 'I'),
(0x1810, 'V'),
(0x181A, 'X'),
(0x1820, 'V'),
(0x1879, 'X'),
(0x1880, 'V'),
(0x18AB, 'X'),
(0x18B0, 'V'),
(0x18F6, 'X'),
(0x1900, 'V'),
(0x191F, 'X'),
(0x1920, 'V'),
(0x192C, 'X'),
(0x1930, 'V'),
(0x193C, 'X'),
(0x1940, 'V'),
(0x1941, 'X'),
(0x1944, 'V'),
(0x196E, 'X'),
(0x1970, 'V'),
(0x1975, 'X'),
(0x1980, 'V'),
(0x19AC, 'X'),
(0x19B0, 'V'),
(0x19CA, 'X'),
(0x19D0, 'V'),
(0x19DB, 'X'),
(0x19DE, 'V'),
(0x1A1C, 'X'),
(0x1A1E, 'V'),
(0x1A5F, 'X'),
(0x1A60, 'V'),
(0x1A7D, 'X'),
(0x1A7F, 'V'),
(0x1A8A, 'X'),
(0x1A90, 'V'),
(0x1A9A, 'X'),
(0x1AA0, 'V'),
(0x1AAE, 'X'),
(0x1AB0, 'V'),
(0x1ACF, 'X'),
(0x1B00, 'V'),
(0x1B4D, 'X'),
(0x1B50, 'V'),
(0x1B7F, 'X'),
(0x1B80, 'V'),
(0x1BF4, 'X'),
(0x1BFC, 'V'),
(0x1C38, 'X'),
(0x1C3B, 'V'),
(0x1C4A, 'X'),
(0x1C4D, 'V'),
(0x1C80, 'M', 'в'),
] | null |
172,868 | from typing import List, Tuple, Union
Union: _SpecialForm = ...
List = _Alias()
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 _seg_15() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:
return [
(0x1C81, 'M', 'д'),
(0x1C82, 'M', 'о'),
(0x1C83, 'M', 'с'),
(0x1C84, 'M', 'т'),
(0x1C86, 'M', 'ъ'),
(0x1C87, 'M', 'ѣ'),
(0x1C88, 'M', 'ꙋ'),
(0x1C89, 'X'),
(0x1C90, 'M', 'ა'),
(0x1C91, 'M', 'ბ'),
(0x1C92, 'M', 'გ'),
(0x1C93, 'M', 'დ'),
(0x1C94, 'M', 'ე'),
(0x1C95, 'M', 'ვ'),
(0x1C96, 'M', 'ზ'),
(0x1C97, 'M', 'თ'),
(0x1C98, 'M', 'ი'),
(0x1C99, 'M', 'კ'),
(0x1C9A, 'M', 'ლ'),
(0x1C9B, 'M', 'მ'),
(0x1C9C, 'M', 'ნ'),
(0x1C9D, 'M', 'ო'),
(0x1C9E, 'M', 'პ'),
(0x1C9F, 'M', 'ჟ'),
(0x1CA0, 'M', 'რ'),
(0x1CA1, 'M', 'ს'),
(0x1CA2, 'M', 'ტ'),
(0x1CA3, 'M', 'უ'),
(0x1CA4, 'M', 'ფ'),
(0x1CA5, 'M', 'ქ'),
(0x1CA6, 'M', 'ღ'),
(0x1CA7, 'M', 'ყ'),
(0x1CA8, 'M', 'შ'),
(0x1CA9, 'M', 'ჩ'),
(0x1CAA, 'M', 'ც'),
(0x1CAB, 'M', 'ძ'),
(0x1CAC, 'M', 'წ'),
(0x1CAD, 'M', 'ჭ'),
(0x1CAE, 'M', 'ხ'),
(0x1CAF, 'M', 'ჯ'),
(0x1CB0, 'M', 'ჰ'),
(0x1CB1, 'M', 'ჱ'),
(0x1CB2, 'M', 'ჲ'),
(0x1CB3, 'M', 'ჳ'),
(0x1CB4, 'M', 'ჴ'),
(0x1CB5, 'M', 'ჵ'),
(0x1CB6, 'M', 'ჶ'),
(0x1CB7, 'M', 'ჷ'),
(0x1CB8, 'M', 'ჸ'),
(0x1CB9, 'M', 'ჹ'),
(0x1CBA, 'M', 'ჺ'),
(0x1CBB, 'X'),
(0x1CBD, 'M', 'ჽ'),
(0x1CBE, 'M', 'ჾ'),
(0x1CBF, 'M', 'ჿ'),
(0x1CC0, 'V'),
(0x1CC8, 'X'),
(0x1CD0, 'V'),
(0x1CFB, 'X'),
(0x1D00, 'V'),
(0x1D2C, 'M', 'a'),
(0x1D2D, 'M', 'æ'),
(0x1D2E, 'M', 'b'),
(0x1D2F, 'V'),
(0x1D30, 'M', 'd'),
(0x1D31, 'M', 'e'),
(0x1D32, 'M', 'ǝ'),
(0x1D33, 'M', 'g'),
(0x1D34, 'M', 'h'),
(0x1D35, 'M', 'i'),
(0x1D36, 'M', 'j'),
(0x1D37, 'M', 'k'),
(0x1D38, 'M', 'l'),
(0x1D39, 'M', 'm'),
(0x1D3A, 'M', 'n'),
(0x1D3B, 'V'),
(0x1D3C, 'M', 'o'),
(0x1D3D, 'M', 'ȣ'),
(0x1D3E, 'M', 'p'),
(0x1D3F, 'M', 'r'),
(0x1D40, 'M', 't'),
(0x1D41, 'M', 'u'),
(0x1D42, 'M', 'w'),
(0x1D43, 'M', 'a'),
(0x1D44, 'M', 'ɐ'),
(0x1D45, 'M', 'ɑ'),
(0x1D46, 'M', 'ᴂ'),
(0x1D47, 'M', 'b'),
(0x1D48, 'M', 'd'),
(0x1D49, 'M', 'e'),
(0x1D4A, 'M', 'ə'),
(0x1D4B, 'M', 'ɛ'),
(0x1D4C, 'M', 'ɜ'),
(0x1D4D, 'M', 'g'),
(0x1D4E, 'V'),
(0x1D4F, 'M', 'k'),
(0x1D50, 'M', 'm'),
(0x1D51, 'M', 'ŋ'),
(0x1D52, 'M', 'o'),
(0x1D53, 'M', 'ɔ'),
] | null |
172,869 | from typing import List, Tuple, Union
Union: _SpecialForm = ...
List = _Alias()
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 _seg_16() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:
return [
(0x1D54, 'M', 'ᴖ'),
(0x1D55, 'M', 'ᴗ'),
(0x1D56, 'M', 'p'),
(0x1D57, 'M', 't'),
(0x1D58, 'M', 'u'),
(0x1D59, 'M', 'ᴝ'),
(0x1D5A, 'M', 'ɯ'),
(0x1D5B, 'M', 'v'),
(0x1D5C, 'M', 'ᴥ'),
(0x1D5D, 'M', 'β'),
(0x1D5E, 'M', 'γ'),
(0x1D5F, 'M', 'δ'),
(0x1D60, 'M', 'φ'),
(0x1D61, 'M', 'χ'),
(0x1D62, 'M', 'i'),
(0x1D63, 'M', 'r'),
(0x1D64, 'M', 'u'),
(0x1D65, 'M', 'v'),
(0x1D66, 'M', 'β'),
(0x1D67, 'M', 'γ'),
(0x1D68, 'M', 'ρ'),
(0x1D69, 'M', 'φ'),
(0x1D6A, 'M', 'χ'),
(0x1D6B, 'V'),
(0x1D78, 'M', 'н'),
(0x1D79, 'V'),
(0x1D9B, 'M', 'ɒ'),
(0x1D9C, 'M', 'c'),
(0x1D9D, 'M', 'ɕ'),
(0x1D9E, 'M', 'ð'),
(0x1D9F, 'M', 'ɜ'),
(0x1DA0, 'M', 'f'),
(0x1DA1, 'M', 'ɟ'),
(0x1DA2, 'M', 'ɡ'),
(0x1DA3, 'M', 'ɥ'),
(0x1DA4, 'M', 'ɨ'),
(0x1DA5, 'M', 'ɩ'),
(0x1DA6, 'M', 'ɪ'),
(0x1DA7, 'M', 'ᵻ'),
(0x1DA8, 'M', 'ʝ'),
(0x1DA9, 'M', 'ɭ'),
(0x1DAA, 'M', 'ᶅ'),
(0x1DAB, 'M', 'ʟ'),
(0x1DAC, 'M', 'ɱ'),
(0x1DAD, 'M', 'ɰ'),
(0x1DAE, 'M', 'ɲ'),
(0x1DAF, 'M', 'ɳ'),
(0x1DB0, 'M', 'ɴ'),
(0x1DB1, 'M', 'ɵ'),
(0x1DB2, 'M', 'ɸ'),
(0x1DB3, 'M', 'ʂ'),
(0x1DB4, 'M', 'ʃ'),
(0x1DB5, 'M', 'ƫ'),
(0x1DB6, 'M', 'ʉ'),
(0x1DB7, 'M', 'ʊ'),
(0x1DB8, 'M', 'ᴜ'),
(0x1DB9, 'M', 'ʋ'),
(0x1DBA, 'M', 'ʌ'),
(0x1DBB, 'M', 'z'),
(0x1DBC, 'M', 'ʐ'),
(0x1DBD, 'M', 'ʑ'),
(0x1DBE, 'M', 'ʒ'),
(0x1DBF, 'M', 'θ'),
(0x1DC0, 'V'),
(0x1E00, 'M', 'ḁ'),
(0x1E01, 'V'),
(0x1E02, 'M', 'ḃ'),
(0x1E03, 'V'),
(0x1E04, 'M', 'ḅ'),
(0x1E05, 'V'),
(0x1E06, 'M', 'ḇ'),
(0x1E07, 'V'),
(0x1E08, 'M', 'ḉ'),
(0x1E09, 'V'),
(0x1E0A, 'M', 'ḋ'),
(0x1E0B, 'V'),
(0x1E0C, 'M', 'ḍ'),
(0x1E0D, 'V'),
(0x1E0E, 'M', 'ḏ'),
(0x1E0F, 'V'),
(0x1E10, 'M', 'ḑ'),
(0x1E11, 'V'),
(0x1E12, 'M', 'ḓ'),
(0x1E13, 'V'),
(0x1E14, 'M', 'ḕ'),
(0x1E15, 'V'),
(0x1E16, 'M', 'ḗ'),
(0x1E17, 'V'),
(0x1E18, 'M', 'ḙ'),
(0x1E19, 'V'),
(0x1E1A, 'M', 'ḛ'),
(0x1E1B, 'V'),
(0x1E1C, 'M', 'ḝ'),
(0x1E1D, 'V'),
(0x1E1E, 'M', 'ḟ'),
(0x1E1F, 'V'),
(0x1E20, 'M', 'ḡ'),
(0x1E21, 'V'),
(0x1E22, 'M', 'ḣ'),
(0x1E23, 'V'),
] | null |
172,870 | from typing import List, Tuple, Union
Union: _SpecialForm = ...
List = _Alias()
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 _seg_17() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:
return [
(0x1E24, 'M', 'ḥ'),
(0x1E25, 'V'),
(0x1E26, 'M', 'ḧ'),
(0x1E27, 'V'),
(0x1E28, 'M', 'ḩ'),
(0x1E29, 'V'),
(0x1E2A, 'M', 'ḫ'),
(0x1E2B, 'V'),
(0x1E2C, 'M', 'ḭ'),
(0x1E2D, 'V'),
(0x1E2E, 'M', 'ḯ'),
(0x1E2F, 'V'),
(0x1E30, 'M', 'ḱ'),
(0x1E31, 'V'),
(0x1E32, 'M', 'ḳ'),
(0x1E33, 'V'),
(0x1E34, 'M', 'ḵ'),
(0x1E35, 'V'),
(0x1E36, 'M', 'ḷ'),
(0x1E37, 'V'),
(0x1E38, 'M', 'ḹ'),
(0x1E39, 'V'),
(0x1E3A, 'M', 'ḻ'),
(0x1E3B, 'V'),
(0x1E3C, 'M', 'ḽ'),
(0x1E3D, 'V'),
(0x1E3E, 'M', 'ḿ'),
(0x1E3F, 'V'),
(0x1E40, 'M', 'ṁ'),
(0x1E41, 'V'),
(0x1E42, 'M', 'ṃ'),
(0x1E43, 'V'),
(0x1E44, 'M', 'ṅ'),
(0x1E45, 'V'),
(0x1E46, 'M', 'ṇ'),
(0x1E47, 'V'),
(0x1E48, 'M', 'ṉ'),
(0x1E49, 'V'),
(0x1E4A, 'M', 'ṋ'),
(0x1E4B, 'V'),
(0x1E4C, 'M', 'ṍ'),
(0x1E4D, 'V'),
(0x1E4E, 'M', 'ṏ'),
(0x1E4F, 'V'),
(0x1E50, 'M', 'ṑ'),
(0x1E51, 'V'),
(0x1E52, 'M', 'ṓ'),
(0x1E53, 'V'),
(0x1E54, 'M', 'ṕ'),
(0x1E55, 'V'),
(0x1E56, 'M', 'ṗ'),
(0x1E57, 'V'),
(0x1E58, 'M', 'ṙ'),
(0x1E59, 'V'),
(0x1E5A, 'M', 'ṛ'),
(0x1E5B, 'V'),
(0x1E5C, 'M', 'ṝ'),
(0x1E5D, 'V'),
(0x1E5E, 'M', 'ṟ'),
(0x1E5F, 'V'),
(0x1E60, 'M', 'ṡ'),
(0x1E61, 'V'),
(0x1E62, 'M', 'ṣ'),
(0x1E63, 'V'),
(0x1E64, 'M', 'ṥ'),
(0x1E65, 'V'),
(0x1E66, 'M', 'ṧ'),
(0x1E67, 'V'),
(0x1E68, 'M', 'ṩ'),
(0x1E69, 'V'),
(0x1E6A, 'M', 'ṫ'),
(0x1E6B, 'V'),
(0x1E6C, 'M', 'ṭ'),
(0x1E6D, 'V'),
(0x1E6E, 'M', 'ṯ'),
(0x1E6F, 'V'),
(0x1E70, 'M', 'ṱ'),
(0x1E71, 'V'),
(0x1E72, 'M', 'ṳ'),
(0x1E73, 'V'),
(0x1E74, 'M', 'ṵ'),
(0x1E75, 'V'),
(0x1E76, 'M', 'ṷ'),
(0x1E77, 'V'),
(0x1E78, 'M', 'ṹ'),
(0x1E79, 'V'),
(0x1E7A, 'M', 'ṻ'),
(0x1E7B, 'V'),
(0x1E7C, 'M', 'ṽ'),
(0x1E7D, 'V'),
(0x1E7E, 'M', 'ṿ'),
(0x1E7F, 'V'),
(0x1E80, 'M', 'ẁ'),
(0x1E81, 'V'),
(0x1E82, 'M', 'ẃ'),
(0x1E83, 'V'),
(0x1E84, 'M', 'ẅ'),
(0x1E85, 'V'),
(0x1E86, 'M', 'ẇ'),
(0x1E87, 'V'),
] | null |
172,871 | from typing import List, Tuple, Union
Union: _SpecialForm = ...
List = _Alias()
class Tuple(BaseTypingInstance):
def _is_homogenous(self):
def py__simple_getitem__(self, index):
def py__iter__(self, contextualized_node=None):
def py__getitem__(self, index_value_set, contextualized_node):
def _get_wrapped_value(self):
def name(self):
def infer_type_vars(self, value_set):
def _seg_18() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:
return [
(0x1E88, 'M', 'ẉ'),
(0x1E89, 'V'),
(0x1E8A, 'M', 'ẋ'),
(0x1E8B, 'V'),
(0x1E8C, 'M', 'ẍ'),
(0x1E8D, 'V'),
(0x1E8E, 'M', 'ẏ'),
(0x1E8F, 'V'),
(0x1E90, 'M', 'ẑ'),
(0x1E91, 'V'),
(0x1E92, 'M', 'ẓ'),
(0x1E93, 'V'),
(0x1E94, 'M', 'ẕ'),
(0x1E95, 'V'),
(0x1E9A, 'M', 'aʾ'),
(0x1E9B, 'M', 'ṡ'),
(0x1E9C, 'V'),
(0x1E9E, 'M', 'ss'),
(0x1E9F, 'V'),
(0x1EA0, 'M', 'ạ'),
(0x1EA1, 'V'),
(0x1EA2, 'M', 'ả'),
(0x1EA3, 'V'),
(0x1EA4, 'M', 'ấ'),
(0x1EA5, 'V'),
(0x1EA6, 'M', 'ầ'),
(0x1EA7, 'V'),
(0x1EA8, 'M', 'ẩ'),
(0x1EA9, 'V'),
(0x1EAA, 'M', 'ẫ'),
(0x1EAB, 'V'),
(0x1EAC, 'M', 'ậ'),
(0x1EAD, 'V'),
(0x1EAE, 'M', 'ắ'),
(0x1EAF, 'V'),
(0x1EB0, 'M', 'ằ'),
(0x1EB1, 'V'),
(0x1EB2, 'M', 'ẳ'),
(0x1EB3, 'V'),
(0x1EB4, 'M', 'ẵ'),
(0x1EB5, 'V'),
(0x1EB6, 'M', 'ặ'),
(0x1EB7, 'V'),
(0x1EB8, 'M', 'ẹ'),
(0x1EB9, 'V'),
(0x1EBA, 'M', 'ẻ'),
(0x1EBB, 'V'),
(0x1EBC, 'M', 'ẽ'),
(0x1EBD, 'V'),
(0x1EBE, 'M', 'ế'),
(0x1EBF, 'V'),
(0x1EC0, 'M', 'ề'),
(0x1EC1, 'V'),
(0x1EC2, 'M', 'ể'),
(0x1EC3, 'V'),
(0x1EC4, 'M', 'ễ'),
(0x1EC5, 'V'),
(0x1EC6, 'M', 'ệ'),
(0x1EC7, 'V'),
(0x1EC8, 'M', 'ỉ'),
(0x1EC9, 'V'),
(0x1ECA, 'M', 'ị'),
(0x1ECB, 'V'),
(0x1ECC, 'M', 'ọ'),
(0x1ECD, 'V'),
(0x1ECE, 'M', 'ỏ'),
(0x1ECF, 'V'),
(0x1ED0, 'M', 'ố'),
(0x1ED1, 'V'),
(0x1ED2, 'M', 'ồ'),
(0x1ED3, 'V'),
(0x1ED4, 'M', 'ổ'),
(0x1ED5, 'V'),
(0x1ED6, 'M', 'ỗ'),
(0x1ED7, 'V'),
(0x1ED8, 'M', 'ộ'),
(0x1ED9, 'V'),
(0x1EDA, 'M', 'ớ'),
(0x1EDB, 'V'),
(0x1EDC, 'M', 'ờ'),
(0x1EDD, 'V'),
(0x1EDE, 'M', 'ở'),
(0x1EDF, 'V'),
(0x1EE0, 'M', 'ỡ'),
(0x1EE1, 'V'),
(0x1EE2, 'M', 'ợ'),
(0x1EE3, 'V'),
(0x1EE4, 'M', 'ụ'),
(0x1EE5, 'V'),
(0x1EE6, 'M', 'ủ'),
(0x1EE7, 'V'),
(0x1EE8, 'M', 'ứ'),
(0x1EE9, 'V'),
(0x1EEA, 'M', 'ừ'),
(0x1EEB, 'V'),
(0x1EEC, 'M', 'ử'),
(0x1EED, 'V'),
(0x1EEE, 'M', 'ữ'),
(0x1EEF, 'V'),
(0x1EF0, 'M', 'ự'),
] | null |
172,872 | from typing import List, Tuple, Union
Union: _SpecialForm = ...
List = _Alias()
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 _seg_19() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:
return [
(0x1EF1, 'V'),
(0x1EF2, 'M', 'ỳ'),
(0x1EF3, 'V'),
(0x1EF4, 'M', 'ỵ'),
(0x1EF5, 'V'),
(0x1EF6, 'M', 'ỷ'),
(0x1EF7, 'V'),
(0x1EF8, 'M', 'ỹ'),
(0x1EF9, 'V'),
(0x1EFA, 'M', 'ỻ'),
(0x1EFB, 'V'),
(0x1EFC, 'M', 'ỽ'),
(0x1EFD, 'V'),
(0x1EFE, 'M', 'ỿ'),
(0x1EFF, 'V'),
(0x1F08, 'M', 'ἀ'),
(0x1F09, 'M', 'ἁ'),
(0x1F0A, 'M', 'ἂ'),
(0x1F0B, 'M', 'ἃ'),
(0x1F0C, 'M', 'ἄ'),
(0x1F0D, 'M', 'ἅ'),
(0x1F0E, 'M', 'ἆ'),
(0x1F0F, 'M', 'ἇ'),
(0x1F10, 'V'),
(0x1F16, 'X'),
(0x1F18, 'M', 'ἐ'),
(0x1F19, 'M', 'ἑ'),
(0x1F1A, 'M', 'ἒ'),
(0x1F1B, 'M', 'ἓ'),
(0x1F1C, 'M', 'ἔ'),
(0x1F1D, 'M', 'ἕ'),
(0x1F1E, 'X'),
(0x1F20, 'V'),
(0x1F28, 'M', 'ἠ'),
(0x1F29, 'M', 'ἡ'),
(0x1F2A, 'M', 'ἢ'),
(0x1F2B, 'M', 'ἣ'),
(0x1F2C, 'M', 'ἤ'),
(0x1F2D, 'M', 'ἥ'),
(0x1F2E, 'M', 'ἦ'),
(0x1F2F, 'M', 'ἧ'),
(0x1F30, 'V'),
(0x1F38, 'M', 'ἰ'),
(0x1F39, 'M', 'ἱ'),
(0x1F3A, 'M', 'ἲ'),
(0x1F3B, 'M', 'ἳ'),
(0x1F3C, 'M', 'ἴ'),
(0x1F3D, 'M', 'ἵ'),
(0x1F3E, 'M', 'ἶ'),
(0x1F3F, 'M', 'ἷ'),
(0x1F40, 'V'),
(0x1F46, 'X'),
(0x1F48, 'M', 'ὀ'),
(0x1F49, 'M', 'ὁ'),
(0x1F4A, 'M', 'ὂ'),
(0x1F4B, 'M', 'ὃ'),
(0x1F4C, 'M', 'ὄ'),
(0x1F4D, 'M', 'ὅ'),
(0x1F4E, 'X'),
(0x1F50, 'V'),
(0x1F58, 'X'),
(0x1F59, 'M', 'ὑ'),
(0x1F5A, 'X'),
(0x1F5B, 'M', 'ὓ'),
(0x1F5C, 'X'),
(0x1F5D, 'M', 'ὕ'),
(0x1F5E, 'X'),
(0x1F5F, 'M', 'ὗ'),
(0x1F60, 'V'),
(0x1F68, 'M', 'ὠ'),
(0x1F69, 'M', 'ὡ'),
(0x1F6A, 'M', 'ὢ'),
(0x1F6B, 'M', 'ὣ'),
(0x1F6C, 'M', 'ὤ'),
(0x1F6D, 'M', 'ὥ'),
(0x1F6E, 'M', 'ὦ'),
(0x1F6F, 'M', 'ὧ'),
(0x1F70, 'V'),
(0x1F71, 'M', 'ά'),
(0x1F72, 'V'),
(0x1F73, 'M', 'έ'),
(0x1F74, 'V'),
(0x1F75, 'M', 'ή'),
(0x1F76, 'V'),
(0x1F77, 'M', 'ί'),
(0x1F78, 'V'),
(0x1F79, 'M', 'ό'),
(0x1F7A, 'V'),
(0x1F7B, 'M', 'ύ'),
(0x1F7C, 'V'),
(0x1F7D, 'M', 'ώ'),
(0x1F7E, 'X'),
(0x1F80, 'M', 'ἀι'),
(0x1F81, 'M', 'ἁι'),
(0x1F82, 'M', 'ἂι'),
(0x1F83, 'M', 'ἃι'),
(0x1F84, 'M', 'ἄι'),
(0x1F85, 'M', 'ἅι'),
(0x1F86, 'M', 'ἆι'),
(0x1F87, 'M', 'ἇι'),
] | null |
172,873 | from typing import List, Tuple, Union
Union: _SpecialForm = ...
List = _Alias()
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 _seg_20() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:
return [
(0x1F88, 'M', 'ἀι'),
(0x1F89, 'M', 'ἁι'),
(0x1F8A, 'M', 'ἂι'),
(0x1F8B, 'M', 'ἃι'),
(0x1F8C, 'M', 'ἄι'),
(0x1F8D, 'M', 'ἅι'),
(0x1F8E, 'M', 'ἆι'),
(0x1F8F, 'M', 'ἇι'),
(0x1F90, 'M', 'ἠι'),
(0x1F91, 'M', 'ἡι'),
(0x1F92, 'M', 'ἢι'),
(0x1F93, 'M', 'ἣι'),
(0x1F94, 'M', 'ἤι'),
(0x1F95, 'M', 'ἥι'),
(0x1F96, 'M', 'ἦι'),
(0x1F97, 'M', 'ἧι'),
(0x1F98, 'M', 'ἠι'),
(0x1F99, 'M', 'ἡι'),
(0x1F9A, 'M', 'ἢι'),
(0x1F9B, 'M', 'ἣι'),
(0x1F9C, 'M', 'ἤι'),
(0x1F9D, 'M', 'ἥι'),
(0x1F9E, 'M', 'ἦι'),
(0x1F9F, 'M', 'ἧι'),
(0x1FA0, 'M', 'ὠι'),
(0x1FA1, 'M', 'ὡι'),
(0x1FA2, 'M', 'ὢι'),
(0x1FA3, 'M', 'ὣι'),
(0x1FA4, 'M', 'ὤι'),
(0x1FA5, 'M', 'ὥι'),
(0x1FA6, 'M', 'ὦι'),
(0x1FA7, 'M', 'ὧι'),
(0x1FA8, 'M', 'ὠι'),
(0x1FA9, 'M', 'ὡι'),
(0x1FAA, 'M', 'ὢι'),
(0x1FAB, 'M', 'ὣι'),
(0x1FAC, 'M', 'ὤι'),
(0x1FAD, 'M', 'ὥι'),
(0x1FAE, 'M', 'ὦι'),
(0x1FAF, 'M', 'ὧι'),
(0x1FB0, 'V'),
(0x1FB2, 'M', 'ὰι'),
(0x1FB3, 'M', 'αι'),
(0x1FB4, 'M', 'άι'),
(0x1FB5, 'X'),
(0x1FB6, 'V'),
(0x1FB7, 'M', 'ᾶι'),
(0x1FB8, 'M', 'ᾰ'),
(0x1FB9, 'M', 'ᾱ'),
(0x1FBA, 'M', 'ὰ'),
(0x1FBB, 'M', 'ά'),
(0x1FBC, 'M', 'αι'),
(0x1FBD, '3', ' ̓'),
(0x1FBE, 'M', 'ι'),
(0x1FBF, '3', ' ̓'),
(0x1FC0, '3', ' ͂'),
(0x1FC1, '3', ' ̈͂'),
(0x1FC2, 'M', 'ὴι'),
(0x1FC3, 'M', 'ηι'),
(0x1FC4, 'M', 'ήι'),
(0x1FC5, 'X'),
(0x1FC6, 'V'),
(0x1FC7, 'M', 'ῆι'),
(0x1FC8, 'M', 'ὲ'),
(0x1FC9, 'M', 'έ'),
(0x1FCA, 'M', 'ὴ'),
(0x1FCB, 'M', 'ή'),
(0x1FCC, 'M', 'ηι'),
(0x1FCD, '3', ' ̓̀'),
(0x1FCE, '3', ' ̓́'),
(0x1FCF, '3', ' ̓͂'),
(0x1FD0, 'V'),
(0x1FD3, 'M', 'ΐ'),
(0x1FD4, 'X'),
(0x1FD6, 'V'),
(0x1FD8, 'M', 'ῐ'),
(0x1FD9, 'M', 'ῑ'),
(0x1FDA, 'M', 'ὶ'),
(0x1FDB, 'M', 'ί'),
(0x1FDC, 'X'),
(0x1FDD, '3', ' ̔̀'),
(0x1FDE, '3', ' ̔́'),
(0x1FDF, '3', ' ̔͂'),
(0x1FE0, 'V'),
(0x1FE3, 'M', 'ΰ'),
(0x1FE4, 'V'),
(0x1FE8, 'M', 'ῠ'),
(0x1FE9, 'M', 'ῡ'),
(0x1FEA, 'M', 'ὺ'),
(0x1FEB, 'M', 'ύ'),
(0x1FEC, 'M', 'ῥ'),
(0x1FED, '3', ' ̈̀'),
(0x1FEE, '3', ' ̈́'),
(0x1FEF, '3', '`'),
(0x1FF0, 'X'),
(0x1FF2, 'M', 'ὼι'),
(0x1FF3, 'M', 'ωι'),
(0x1FF4, 'M', 'ώι'),
(0x1FF5, 'X'),
(0x1FF6, 'V'),
] | null |
172,874 | from typing import List, Tuple, Union
Union: _SpecialForm = ...
List = _Alias()
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 _seg_21() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:
return [
(0x1FF7, 'M', 'ῶι'),
(0x1FF8, 'M', 'ὸ'),
(0x1FF9, 'M', 'ό'),
(0x1FFA, 'M', 'ὼ'),
(0x1FFB, 'M', 'ώ'),
(0x1FFC, 'M', 'ωι'),
(0x1FFD, '3', ' ́'),
(0x1FFE, '3', ' ̔'),
(0x1FFF, 'X'),
(0x2000, '3', ' '),
(0x200B, 'I'),
(0x200C, 'D', ''),
(0x200E, 'X'),
(0x2010, 'V'),
(0x2011, 'M', '‐'),
(0x2012, 'V'),
(0x2017, '3', ' ̳'),
(0x2018, 'V'),
(0x2024, 'X'),
(0x2027, 'V'),
(0x2028, 'X'),
(0x202F, '3', ' '),
(0x2030, 'V'),
(0x2033, 'M', '′′'),
(0x2034, 'M', '′′′'),
(0x2035, 'V'),
(0x2036, 'M', '‵‵'),
(0x2037, 'M', '‵‵‵'),
(0x2038, 'V'),
(0x203C, '3', '!!'),
(0x203D, 'V'),
(0x203E, '3', ' ̅'),
(0x203F, 'V'),
(0x2047, '3', '??'),
(0x2048, '3', '?!'),
(0x2049, '3', '!?'),
(0x204A, 'V'),
(0x2057, 'M', '′′′′'),
(0x2058, 'V'),
(0x205F, '3', ' '),
(0x2060, 'I'),
(0x2061, 'X'),
(0x2064, 'I'),
(0x2065, 'X'),
(0x2070, 'M', '0'),
(0x2071, 'M', 'i'),
(0x2072, 'X'),
(0x2074, 'M', '4'),
(0x2075, 'M', '5'),
(0x2076, 'M', '6'),
(0x2077, 'M', '7'),
(0x2078, 'M', '8'),
(0x2079, 'M', '9'),
(0x207A, '3', '+'),
(0x207B, 'M', '−'),
(0x207C, '3', '='),
(0x207D, '3', '('),
(0x207E, '3', ')'),
(0x207F, 'M', 'n'),
(0x2080, 'M', '0'),
(0x2081, 'M', '1'),
(0x2082, 'M', '2'),
(0x2083, 'M', '3'),
(0x2084, 'M', '4'),
(0x2085, 'M', '5'),
(0x2086, 'M', '6'),
(0x2087, 'M', '7'),
(0x2088, 'M', '8'),
(0x2089, 'M', '9'),
(0x208A, '3', '+'),
(0x208B, 'M', '−'),
(0x208C, '3', '='),
(0x208D, '3', '('),
(0x208E, '3', ')'),
(0x208F, 'X'),
(0x2090, 'M', 'a'),
(0x2091, 'M', 'e'),
(0x2092, 'M', 'o'),
(0x2093, 'M', 'x'),
(0x2094, 'M', 'ə'),
(0x2095, 'M', 'h'),
(0x2096, 'M', 'k'),
(0x2097, 'M', 'l'),
(0x2098, 'M', 'm'),
(0x2099, 'M', 'n'),
(0x209A, 'M', 'p'),
(0x209B, 'M', 's'),
(0x209C, 'M', 't'),
(0x209D, 'X'),
(0x20A0, 'V'),
(0x20A8, 'M', 'rs'),
(0x20A9, 'V'),
(0x20C1, 'X'),
(0x20D0, 'V'),
(0x20F1, 'X'),
(0x2100, '3', 'a/c'),
(0x2101, '3', 'a/s'),
(0x2102, 'M', 'c'),
(0x2103, 'M', '°c'),
(0x2104, 'V'),
] | null |
172,875 | from typing import List, Tuple, Union
Union: _SpecialForm = ...
List = _Alias()
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 _seg_22() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:
return [
(0x2105, '3', 'c/o'),
(0x2106, '3', 'c/u'),
(0x2107, 'M', 'ɛ'),
(0x2108, 'V'),
(0x2109, 'M', '°f'),
(0x210A, 'M', 'g'),
(0x210B, 'M', 'h'),
(0x210F, 'M', 'ħ'),
(0x2110, 'M', 'i'),
(0x2112, 'M', 'l'),
(0x2114, 'V'),
(0x2115, 'M', 'n'),
(0x2116, 'M', 'no'),
(0x2117, 'V'),
(0x2119, 'M', 'p'),
(0x211A, 'M', 'q'),
(0x211B, 'M', 'r'),
(0x211E, 'V'),
(0x2120, 'M', 'sm'),
(0x2121, 'M', 'tel'),
(0x2122, 'M', 'tm'),
(0x2123, 'V'),
(0x2124, 'M', 'z'),
(0x2125, 'V'),
(0x2126, 'M', 'ω'),
(0x2127, 'V'),
(0x2128, 'M', 'z'),
(0x2129, 'V'),
(0x212A, 'M', 'k'),
(0x212B, 'M', 'å'),
(0x212C, 'M', 'b'),
(0x212D, 'M', 'c'),
(0x212E, 'V'),
(0x212F, 'M', 'e'),
(0x2131, 'M', 'f'),
(0x2132, 'X'),
(0x2133, 'M', 'm'),
(0x2134, 'M', 'o'),
(0x2135, 'M', 'א'),
(0x2136, 'M', 'ב'),
(0x2137, 'M', 'ג'),
(0x2138, 'M', 'ד'),
(0x2139, 'M', 'i'),
(0x213A, 'V'),
(0x213B, 'M', 'fax'),
(0x213C, 'M', 'π'),
(0x213D, 'M', 'γ'),
(0x213F, 'M', 'π'),
(0x2140, 'M', '∑'),
(0x2141, 'V'),
(0x2145, 'M', 'd'),
(0x2147, 'M', 'e'),
(0x2148, 'M', 'i'),
(0x2149, 'M', 'j'),
(0x214A, 'V'),
(0x2150, 'M', '1⁄7'),
(0x2151, 'M', '1⁄9'),
(0x2152, 'M', '1⁄10'),
(0x2153, 'M', '1⁄3'),
(0x2154, 'M', '2⁄3'),
(0x2155, 'M', '1⁄5'),
(0x2156, 'M', '2⁄5'),
(0x2157, 'M', '3⁄5'),
(0x2158, 'M', '4⁄5'),
(0x2159, 'M', '1⁄6'),
(0x215A, 'M', '5⁄6'),
(0x215B, 'M', '1⁄8'),
(0x215C, 'M', '3⁄8'),
(0x215D, 'M', '5⁄8'),
(0x215E, 'M', '7⁄8'),
(0x215F, 'M', '1⁄'),
(0x2160, 'M', 'i'),
(0x2161, 'M', 'ii'),
(0x2162, 'M', 'iii'),
(0x2163, 'M', 'iv'),
(0x2164, 'M', 'v'),
(0x2165, 'M', 'vi'),
(0x2166, 'M', 'vii'),
(0x2167, 'M', 'viii'),
(0x2168, 'M', 'ix'),
(0x2169, 'M', 'x'),
(0x216A, 'M', 'xi'),
(0x216B, 'M', 'xii'),
(0x216C, 'M', 'l'),
(0x216D, 'M', 'c'),
(0x216E, 'M', 'd'),
(0x216F, 'M', 'm'),
(0x2170, 'M', 'i'),
(0x2171, 'M', 'ii'),
(0x2172, 'M', 'iii'),
(0x2173, 'M', 'iv'),
(0x2174, 'M', 'v'),
(0x2175, 'M', 'vi'),
(0x2176, 'M', 'vii'),
(0x2177, 'M', 'viii'),
(0x2178, 'M', 'ix'),
(0x2179, 'M', 'x'),
(0x217A, 'M', 'xi'),
(0x217B, 'M', 'xii'),
(0x217C, 'M', 'l'),
] | null |
172,876 | from typing import List, Tuple, Union
Union: _SpecialForm = ...
List = _Alias()
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 _seg_23() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:
return [
(0x217D, 'M', 'c'),
(0x217E, 'M', 'd'),
(0x217F, 'M', 'm'),
(0x2180, 'V'),
(0x2183, 'X'),
(0x2184, 'V'),
(0x2189, 'M', '0⁄3'),
(0x218A, 'V'),
(0x218C, 'X'),
(0x2190, 'V'),
(0x222C, 'M', '∫∫'),
(0x222D, 'M', '∫∫∫'),
(0x222E, 'V'),
(0x222F, 'M', '∮∮'),
(0x2230, 'M', '∮∮∮'),
(0x2231, 'V'),
(0x2260, '3'),
(0x2261, 'V'),
(0x226E, '3'),
(0x2270, 'V'),
(0x2329, 'M', '〈'),
(0x232A, 'M', '〉'),
(0x232B, 'V'),
(0x2427, 'X'),
(0x2440, 'V'),
(0x244B, 'X'),
(0x2460, 'M', '1'),
(0x2461, 'M', '2'),
(0x2462, 'M', '3'),
(0x2463, 'M', '4'),
(0x2464, 'M', '5'),
(0x2465, 'M', '6'),
(0x2466, 'M', '7'),
(0x2467, 'M', '8'),
(0x2468, 'M', '9'),
(0x2469, 'M', '10'),
(0x246A, 'M', '11'),
(0x246B, 'M', '12'),
(0x246C, 'M', '13'),
(0x246D, 'M', '14'),
(0x246E, 'M', '15'),
(0x246F, 'M', '16'),
(0x2470, 'M', '17'),
(0x2471, 'M', '18'),
(0x2472, 'M', '19'),
(0x2473, 'M', '20'),
(0x2474, '3', '(1)'),
(0x2475, '3', '(2)'),
(0x2476, '3', '(3)'),
(0x2477, '3', '(4)'),
(0x2478, '3', '(5)'),
(0x2479, '3', '(6)'),
(0x247A, '3', '(7)'),
(0x247B, '3', '(8)'),
(0x247C, '3', '(9)'),
(0x247D, '3', '(10)'),
(0x247E, '3', '(11)'),
(0x247F, '3', '(12)'),
(0x2480, '3', '(13)'),
(0x2481, '3', '(14)'),
(0x2482, '3', '(15)'),
(0x2483, '3', '(16)'),
(0x2484, '3', '(17)'),
(0x2485, '3', '(18)'),
(0x2486, '3', '(19)'),
(0x2487, '3', '(20)'),
(0x2488, 'X'),
(0x249C, '3', '(a)'),
(0x249D, '3', '(b)'),
(0x249E, '3', '(c)'),
(0x249F, '3', '(d)'),
(0x24A0, '3', '(e)'),
(0x24A1, '3', '(f)'),
(0x24A2, '3', '(g)'),
(0x24A3, '3', '(h)'),
(0x24A4, '3', '(i)'),
(0x24A5, '3', '(j)'),
(0x24A6, '3', '(k)'),
(0x24A7, '3', '(l)'),
(0x24A8, '3', '(m)'),
(0x24A9, '3', '(n)'),
(0x24AA, '3', '(o)'),
(0x24AB, '3', '(p)'),
(0x24AC, '3', '(q)'),
(0x24AD, '3', '(r)'),
(0x24AE, '3', '(s)'),
(0x24AF, '3', '(t)'),
(0x24B0, '3', '(u)'),
(0x24B1, '3', '(v)'),
(0x24B2, '3', '(w)'),
(0x24B3, '3', '(x)'),
(0x24B4, '3', '(y)'),
(0x24B5, '3', '(z)'),
(0x24B6, 'M', 'a'),
(0x24B7, 'M', 'b'),
(0x24B8, 'M', 'c'),
(0x24B9, 'M', 'd'),
(0x24BA, 'M', 'e'),
(0x24BB, 'M', 'f'),
(0x24BC, 'M', 'g'),
] | null |
172,877 | from typing import List, Tuple, Union
Union: _SpecialForm = ...
List = _Alias()
class Tuple(BaseTypingInstance):
def _is_homogenous(self):
def py__simple_getitem__(self, index):
def py__iter__(self, contextualized_node=None):
def py__getitem__(self, index_value_set, contextualized_node):
def _get_wrapped_value(self):
def name(self):
def infer_type_vars(self, value_set):
def _seg_24() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:
return [
(0x24BD, 'M', 'h'),
(0x24BE, 'M', 'i'),
(0x24BF, 'M', 'j'),
(0x24C0, 'M', 'k'),
(0x24C1, 'M', 'l'),
(0x24C2, 'M', 'm'),
(0x24C3, 'M', 'n'),
(0x24C4, 'M', 'o'),
(0x24C5, 'M', 'p'),
(0x24C6, 'M', 'q'),
(0x24C7, 'M', 'r'),
(0x24C8, 'M', 's'),
(0x24C9, 'M', 't'),
(0x24CA, 'M', 'u'),
(0x24CB, 'M', 'v'),
(0x24CC, 'M', 'w'),
(0x24CD, 'M', 'x'),
(0x24CE, 'M', 'y'),
(0x24CF, 'M', 'z'),
(0x24D0, 'M', 'a'),
(0x24D1, 'M', 'b'),
(0x24D2, 'M', 'c'),
(0x24D3, 'M', 'd'),
(0x24D4, 'M', 'e'),
(0x24D5, 'M', 'f'),
(0x24D6, 'M', 'g'),
(0x24D7, 'M', 'h'),
(0x24D8, 'M', 'i'),
(0x24D9, 'M', 'j'),
(0x24DA, 'M', 'k'),
(0x24DB, 'M', 'l'),
(0x24DC, 'M', 'm'),
(0x24DD, 'M', 'n'),
(0x24DE, 'M', 'o'),
(0x24DF, 'M', 'p'),
(0x24E0, 'M', 'q'),
(0x24E1, 'M', 'r'),
(0x24E2, 'M', 's'),
(0x24E3, 'M', 't'),
(0x24E4, 'M', 'u'),
(0x24E5, 'M', 'v'),
(0x24E6, 'M', 'w'),
(0x24E7, 'M', 'x'),
(0x24E8, 'M', 'y'),
(0x24E9, 'M', 'z'),
(0x24EA, 'M', '0'),
(0x24EB, 'V'),
(0x2A0C, 'M', '∫∫∫∫'),
(0x2A0D, 'V'),
(0x2A74, '3', '::='),
(0x2A75, '3', '=='),
(0x2A76, '3', '==='),
(0x2A77, 'V'),
(0x2ADC, 'M', '⫝̸'),
(0x2ADD, 'V'),
(0x2B74, 'X'),
(0x2B76, 'V'),
(0x2B96, 'X'),
(0x2B97, 'V'),
(0x2C00, 'M', 'ⰰ'),
(0x2C01, 'M', 'ⰱ'),
(0x2C02, 'M', 'ⰲ'),
(0x2C03, 'M', 'ⰳ'),
(0x2C04, 'M', 'ⰴ'),
(0x2C05, 'M', 'ⰵ'),
(0x2C06, 'M', 'ⰶ'),
(0x2C07, 'M', 'ⰷ'),
(0x2C08, 'M', 'ⰸ'),
(0x2C09, 'M', 'ⰹ'),
(0x2C0A, 'M', 'ⰺ'),
(0x2C0B, 'M', 'ⰻ'),
(0x2C0C, 'M', 'ⰼ'),
(0x2C0D, 'M', 'ⰽ'),
(0x2C0E, 'M', 'ⰾ'),
(0x2C0F, 'M', 'ⰿ'),
(0x2C10, 'M', 'ⱀ'),
(0x2C11, 'M', 'ⱁ'),
(0x2C12, 'M', 'ⱂ'),
(0x2C13, 'M', 'ⱃ'),
(0x2C14, 'M', 'ⱄ'),
(0x2C15, 'M', 'ⱅ'),
(0x2C16, 'M', 'ⱆ'),
(0x2C17, 'M', 'ⱇ'),
(0x2C18, 'M', 'ⱈ'),
(0x2C19, 'M', 'ⱉ'),
(0x2C1A, 'M', 'ⱊ'),
(0x2C1B, 'M', 'ⱋ'),
(0x2C1C, 'M', 'ⱌ'),
(0x2C1D, 'M', 'ⱍ'),
(0x2C1E, 'M', 'ⱎ'),
(0x2C1F, 'M', 'ⱏ'),
(0x2C20, 'M', 'ⱐ'),
(0x2C21, 'M', 'ⱑ'),
(0x2C22, 'M', 'ⱒ'),
(0x2C23, 'M', 'ⱓ'),
(0x2C24, 'M', 'ⱔ'),
(0x2C25, 'M', 'ⱕ'),
(0x2C26, 'M', 'ⱖ'),
(0x2C27, 'M', 'ⱗ'),
(0x2C28, 'M', 'ⱘ'),
] | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.