예제 #1
0
def validate_clr_types(signature_types, var_signature=False):
    if not isinstance(signature_types, tuple):
        signature_types = (signature_types, )
    for t in signature_types:
        if type(t) is type(
                System.IComparable
        ):  # type overloaded on generic arity, eg IComparable and IComparable[T]
            t = t[()]  # select non-generic version
        clr_type = clr.GetClrType(t)
        if t == Void:
            raise TypeError("Void cannot be used in signature")
        is_typed = clr.GetPythonType(clr_type) == t
        # is_typed needs to be weakened until the generated type
        # gets explicitly published as the underlying CLR type
        is_typed = is_typed or (hasattr(t, "__metaclass__") and t.__metaclass__
                                in [ClrInterface, ClrClass])
        if not is_typed:
            raise Exception, "Invalid CLR type %s" % str(t)
        if not var_signature:
            if clr_type.IsByRef:
                raise TypeError(
                    "Byref can only be used as arguments and locals")
            # ArgIterator is not present in Silverlight
            if hasattr(System, "ArgIterator") and t == System.ArgIterator:
                raise TypeError(
                    "Stack-referencing types can only be used as arguments and locals"
                )
예제 #2
0
 def emit_fields(self, typebld):
     if hasattr(self, "_clrfields"):
         for fldname in self._clrfields:
             field_type = self._clrfields[fldname]
             validate_clr_types(field_type)
             typebld.DefineField(fldname, clr.GetClrType(field_type),
                                 FieldAttributes.Public)
예제 #3
0
def restore_clr(p_name, p_class):
    """
    Restore the function signature by the CLR type signature
    :return (is_static, spec, sig_note)
    """
    clr_type = clr.GetClrType(p_class)
    if p_name == '__new__':
        methods = [c for c in clr_type.GetConstructors()]
        if not methods:
            return False, p_name + '(self, *args)', 'cannot find CLR constructor'  # "self" is always first argument of any non-static method
    else:
        methods = [m for m in clr_type.GetMethods() if m.Name == p_name]
        if not methods:
            bases = p_class.__bases__
            if len(bases) == 1 and p_name in dir(bases[0]):
                # skip inherited methods
                return False, None, None
            return False, p_name + '(self, *args)', 'cannot find CLR method'
            # "self" is always first argument of any non-static method

    parameter_lists = []
    for m in methods:
        parameter_lists.append([p.Name for p in m.GetParameters()])
    params = restore_parameters_for_overloads(parameter_lists)
    is_static = False
    if not methods[0].IsStatic:
        params = ['self'] + params
    else:
        is_static = True
    return is_static, build_signature(p_name, params), None
예제 #4
0
				def onUpdate():
					shortenedUri = None

					if NetworkInterface.GetIsNetworkAvailable():
						try:
							request = WebRequest.Create(Uri(String.Concat("http://nazr.in/api/shorten.json?url=", urlEncode(uri.ToString()))))
							response = None
							stream = None
							streamReader = None

							try:
								response = request.GetResponse()
								stream = response.GetResponseStream()
								streamReader = StreamReader(stream)
								jsonDictionary = JsonDecoder.decode(streamReader.ReadToEnd())

								if jsonDictionary is not None and clr.GetClrType(Dictionary[String, Object]).IsInstanceOfType(jsonDictionary) and jsonDictionary.ContainsKey("url"):
									shortenedUri = Uri(jsonDictionary["url"])

							finally:
								if streamReader is not None:
									streamReader.Close()

								if stream is not None:
									stream.Close()
			
								if response is not None:
									response.Close()

						except Exception, e:
							Trace.WriteLine(e.clsException.Message)
							Trace.WriteLine(e.clsException.StackTrace)
예제 #5
0
파일: script.py 프로젝트: kjanik11/pyRevit
    def _print_combined_sheets_in_order(self):
        # todo: Revit does not follow the order of sheets as set by ViewSet
        print_mgr = doc.PrintManager
        print_mgr.PrintRange = PrintRange.Select
        viewsheet_settings = print_mgr.ViewSheetSetting

        sheet_set = ViewSet()

        for sheet in self.sheets_lb.ItemsSource:
            sheet_set.Insert(sheet.revit_sheet)

        # Collect existing sheet sets
        cl = FilteredElementCollector(doc)
        viewsheetsets = cl.OfClass(clr.GetClrType(
            ViewSheetSet)).WhereElementIsNotElementType().ToElements()
        all_viewsheetsets = {vss.Name: vss for vss in viewsheetsets}

        sheetsetname = 'OrderedPrintSet'

        with Transaction(doc, 'Update Ordered Print Set') as t:
            t.Start()
            # Delete existing matching sheet set
            if sheetsetname in all_viewsheetsets:
                viewsheet_settings.CurrentViewSheetSet = all_viewsheetsets[
                    sheetsetname]
                viewsheet_settings.Delete()

            viewsheet_settings.CurrentViewSheetSet.Views = sheet_set
            viewsheet_settings.SaveAs(sheetsetname)
            t.Commit()

        print_mgr.PrintToFile = True
        print_mgr.CombinedFile = True
        print_mgr.PrintToFileName = op.join(r'C:', 'Ordered Sheet Set.pdf')
        print_mgr.SubmitPrint()
예제 #6
0
파일: script.py 프로젝트: BimRoss/pyRevit
    def _list_views(self):
        open_doc = self._get_linked_model_doc()
        if open_doc:
            cl_sheets = FilteredElementCollector(open_doc)
            view_cl = cl_sheets.OfClass(clr.GetClrType(
                View)).WhereElementIsNotElementType().ToElements()

            all_views = [v for v in view_cl if not v.IsTemplate]
            view_type = str(self.viewtype_cb.SelectedItem)
            filtered_views = []

            if 'Floor Plans' in view_type:
                filtered_views = self._filter_views(all_views,
                                                    ViewType.FloorPlan)
            elif 'Reflected Ceiling Plans' in view_type:
                filtered_views = self._filter_views(all_views,
                                                    ViewType.CeilingPlan)
            elif 'Sections' in view_type:
                filtered_views = self._filter_views(all_views,
                                                    ViewType.Section)
            elif 'Elevations' in view_type:
                filtered_views = self._filter_views(all_views,
                                                    ViewType.Elevation)

            self.linkedsheets_lb.ItemsSource = filtered_views
    def collect_signatures(self, val):
        doc = val.__doc__
        type_obj = None
        if isinstance(val, type) or isinstance(val, _OldClassType):
            type_obj = val
            val = val.__init__

        try:
            args, vargs, varkw, defaults = inspect.getargspec(val)
        except TypeError:
            # we're not doing inspect on a Python function...
            if sys.platform == 'cli':
                if type_obj is not None:
                    clr_type = clr.GetClrType(type_obj)
                    ctors = clr_type.GetConstructors()
                    return [self.get_ipy_sig(type_obj, ctor) for ctor in ctors]
                elif type(val) is types.BuiltinFunctionType:
                    return [self.get_ipy_sig(target, target.Targets[0]) for target in val.Overloads.Functions]
                elif type(val) is builtin_method_descriptor_type:
                    val = PythonOps.GetBuiltinMethodDescriptorTemplate(val)
                    return [self.get_ipy_sig(target, target.Targets[0]) for target in val.Overloads.Functions]
            raise

        remove_self = type_obj is not None or (type(val) is types.MethodType and 
                        ((sys.version >= '3.0' and val.__self__ is not None) or
                        (sys.version < '3.0' and val.im_self is not None)))

        if remove_self:
            # remove self for instance methods and types
            args = args[1:]
            
        if defaults is not None:
            defaults = [repr(default) for default in defaults]
        return [(doc, args, vargs, varkw, defaults)]
예제 #8
0
def find_first_floorplan():
    view_list = list(FilteredElementCollector(doc).OfClass(clr.GetClrType(ViewPlan)) \
                                                 .WhereElementIsNotElementType()      \
                                                 .ToElements())
    for view in view_list:
        if view.ViewType == ViewType.FloorPlan:
            return view
def LogOutputErrorDetails(exception, output_, verbose=True):
    output = global_test_mode.PrefixedOutputForGlobalTestMode(
        output_, EXCEPTION_MESSAGE_HANDLER_PREFIX)
    exceptionMessage = (str(exception.message) if isinstance(
        exception, exceptions.Exception) else str(exception.Message) if
                        isinstance(exception, System.Exception) else str.Empty)
    output()
    output("Exception: [" + type(exception).__name__ + "] " + exceptionMessage)
    try:
        clsException = GetClrException(exception)
        if clsException is not None:
            clsExceptionType = clr.GetClrType(type(clsException))
            output(".NET exception: [" + str(clsExceptionType.Name) + "] " +
                   str(clsException.Message))
            if verbose:
                interpretedFrameInfo = GetInterpretedFrameInfo(
                    clsException.Data)
                if interpretedFrameInfo is not None:
                    output()
                    output("Further exception information:")
                    output()
                    for i in interpretedFrameInfo:
                        if str(i) != "CallSite.Target":
                            output("\t" + str(i))
    except:
        output("Could not obtain further exception information.")
    return
예제 #10
0
	def OpenRuleSet(self, filename):
		""" <summary>
		   Opens the rule set.
		 </summary>
		 <param name = "filename">The filename.</param>
		 <returns></returns>
		"""
		newRuleSet = None
		ruleReader = None
		try:
			ruleReader = StreamReader(filename)
			ruleDeserializer = XmlSerializer(clr.GetClrType(ruleSet))
			newRuleSet = ruleDeserializer.Deserialize(ruleReader)
			newRuleSet.rulesDir = Path.GetDirectoryName(filename) + Path.DirectorySeparatorChar
			newRuleSet.filer = self
			numRules = newRuleSet.ruleFileNames.Count
			newRuleSet.rules = self.LoadRulesFromFileNames(newRuleSet.rulesDir, newRuleSet.ruleFileNames, )
			SearchIO.output(Path.GetFileName(filename) + " successfully loaded")
			if numRules == numLoaded:
				SearchIO.output(" and all (" + numLoaded + ") rules loaded successfully.")
			else:
				SearchIO.output("     but " + (numRules - numLoaded) + " rules did not load.")
			newRuleSet.initializeFileWatcher(newRuleSet.rulesDir)
			if (str.IsNullOrWhiteSpace(newRuleSet.name)) or (newRuleSet.name == "Untitled"):
				newRuleSet.name = Path.GetFileNameWithoutExtension(filename)
		except Exception, ioe:
			SearchIO.output("***XML Serialization Error***")
			SearchIO.output(ioe.ToString())
예제 #11
0
def explodeAndRemoveAllGroups():
    t = Transaction(doc, 'Remove All Groups')
    t.Start()
    reportAndPrint(
        '---------------------------- EXPLODING AND REMOVING GROUPS -----------------------------\n'
    )
    cl = FilteredElementCollector(doc)
    grpTypes = list(cl.OfClass(clr.GetClrType(GroupType)).ToElements())
    grps = []
    attachedGrps = []
    for gt in grpTypes:
        for grp in gt.Groups:
            grps.append(grp)
    for g in grps:
        if g.LookupParameter('Attached to'):
            attachedGrps.append(g.GroupType)
        g.UngroupMembers()
    for agt in attachedGrps:
        doc.Delete(agt.Id)
    for gt in grpTypes:
        try:
            doc.Delete(gt.Id)
        except:
            continue
    t.Commit()
예제 #12
0
def restore_clr(p_name, p_class):
    """
    Restore the function signature by the CLR type signature
    """
    clr_type = clr.GetClrType(p_class)
    if p_name == '__new__':
        methods = [c for c in clr_type.GetConstructors()]
        if not methods:
            return p_name + '(*args)', 'cannot find CLR constructor'
    else:
        methods = [m for m in clr_type.GetMethods() if m.Name == p_name]
        if not methods:
            bases = p_class.__bases__
            if len(bases) == 1 and p_name in dir(bases[0]):
                # skip inherited methods
                return None, None
            return p_name + '(*args)', 'cannot find CLR method'

    parameter_lists = []
    for m in methods:
        parameter_lists.append([p.Name for p in m.GetParameters()])
    params = restore_parameters_for_overloads(parameter_lists)
    if not methods[0].IsStatic:
        params = ['self'] + params
    return build_signature(p_name, params), None
예제 #13
0
def removeAllExternalLinks():
    t = Transaction(doc, 'Remove All External Links')
    t.Start()
    reportAndPrint(
        '------------------------------ REMOVE ALL EXTERNAL LINKS -------------------------------\n'
    )
    if doc.PathName:
        modelPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(
            doc.PathName)
        transData = TransmissionData.ReadTransmissionData(modelPath)
        externalReferences = transData.GetAllExternalFileReferenceIds()
        cl = FilteredElementCollector(doc)
        impInstances = list(
            cl.OfClass(clr.GetClrType(ImportInstance)).ToElements())
        imported = []
        for refId in externalReferences:
            try:
                lnk = doc.GetElement(refId)
                if isinstance(lnk, RevitLinkType) or isinstance(
                        lnk, CADLinkType):
                    doc.Delete(refId)
            except Exception as e:
                reportAndPrintError('External Link', refId, e)
                continue
    else:
        reportAndPrintError(
            'Model must be saved for external links to be removed.')
    t.Commit()
예제 #14
0
def is_clr_type(clr_type):
    if not clr_type: return False
    try:
        clr.GetClrType(clr_type)
        return True
    except TypeError:
        return False
예제 #15
0
def shake_filled_regions():
    cl = FilteredElementCollector(doc)
    fregions = cl.OfClass(clr.GetClrType(FilledRegion)).WhereElementIsNotElementType().ToElements()

    for fr in fregions:
        fr.Location.Move(XYZ(0.01, 0, 0))
        fr.Location.Move(XYZ(-0.01, 0, 0))
예제 #16
0
    def test_type_from_reflection_emit(self):
        import clr
        import System
        if is_netcoreapp:
            clr.AddReference("System.Reflection.Emit")

        sr = System.Reflection
        sre = System.Reflection.Emit
        array = System.Array
        cab = array[sre.CustomAttributeBuilder]([
            sre.CustomAttributeBuilder(
                clr.GetClrType(System.Security.SecurityTransparentAttribute).
                GetConstructor(System.Type.EmptyTypes), array[object]([]))
        ])
        if is_netcoreapp:  # no System.AppDomain.DefineDynamicAssembly
            ab = sre.AssemblyBuilder.DefineDynamicAssembly(
                sr.AssemblyName("temp"), sre.AssemblyBuilderAccess.Run,
                cab)  # tracking: 291888
        else:
            ab = System.AppDomain.CurrentDomain.DefineDynamicAssembly(
                sr.AssemblyName("temp"), sre.AssemblyBuilderAccess.RunAndSave,
                "temp", None, None, None, None, True, cab)  # tracking: 291888

        mb = ab.DefineDynamicModule("temp", "temp.dll")
        tb = mb.DefineType("EmittedNS.EmittedType", sr.TypeAttributes.Public)
        tb.CreateType()

        clr.AddReference(ab)
        import EmittedNS
        EmittedNS.EmittedType()
예제 #17
0
 def _construct(self, argv):
     if self._module is None:
         raise KeyError("No class has been provided!")
     module = self._module
     inpt = clr.GetClrType(module)
     types = []
     true_args = []
     for x in argv:
         if hasattr(x, '_instance'):
             types.append(x._instance.GetType())
             true_args.append(x._instance)
         else:
             types.append(type(x))
             true_args.append(x)
     try:
         check = inpt.GetConstructor(
             Array[Type](types)) if len(types) > 0 else inpt.GetConstructor(
                 Type.EmptyTypes)
         if check is None:
             raise KeyError(
                 "No overload of the provided class constructor exists given the provided argument types!"
             )
         else:
             #return the retrieved method as an instance of LFModuleInstanceWrapper
             return LFModuleInstanceWrapper(
                 check.Invoke(Array[Object](true_args)))
     except Exception as e:
         print e.InnerException
         raise e
     return self
예제 #18
0
파일: script.py 프로젝트: kjanik11/pyRevit
    def _get_ordered_schedule_sheets(self):
        schedule_view = self.selected_schedule
        cl_sheets = FilteredElementCollector(doc, schedule_view.Id)
        sheets = cl_sheets.OfClass(clr.GetClrType(
            ViewSheet)).WhereElementIsNotElementType().ToElements()

        return self._order_sheets_by_schedule_data(schedule_view, sheets)
예제 #19
0
 def get_Subclass_of(rt):
     for y in [getattr(Ast, x) for x in dir(Ast)]:
         yt = clr.GetClrType(y)
         if rt == yt: continue
         if yt.IsAbstract: continue
         if yt.IsSubclassOf(rt):
             yield yt.Name
예제 #20
0
def get_type(fw_object):
    """Return CLR type of an object.

    Args:
        fw_object: Dotnet Framework Object Instance
    """
    return clr.GetClrType(fw_object)
  def ActiveProtocols(self, instance):
    """Returns the list of NeighborProtocols running on the requested routing instance """
    defaultInstanceName = L3Discovery.RoutingInstance.DefaultInstanceName(self.GetVendor())
    instanceName = defaultInstanceName
    if instance : instanceName = instance.Name
    if self._runningRoutingProtocols.get(instanceName, None) == None:
      self._runningRoutingProtocols[instanceName] = []
    if len(self._runningRoutingProtocols[instanceName]) == 0 :
      # // -- check running routing protocols
      cmd = "show ip protocols"
      if instanceName != defaultInstanceName : 
        cmd = "show ip protocols vrf {0}".format(instanceName)
      response = str.lower(Session.ExecCommand(cmd));
     
      mathcedProtocolNames = []
      matches = re.finditer(r"(?<=routing protocol is ).([a-z]{0,99})", response, re.MULTILINE | re.IGNORECASE)
      for matchNum, match in enumerate(matches, start=1):
        for groupNum in range(0, len(match.groups())):
          groupNum = groupNum + 1     
          mathcedProtocolNames.append(match.group(groupNum)) 
      supportedProtocols = System.Enum.GetValues(clr.GetClrType(L3Discovery.NeighborProtocol))
      for thisProtocol in supportedProtocols :
        if str(thisProtocol).lower() in mathcedProtocolNames : 
          # In case we are checking the global routing instance. we must perform further checks
          # because "show ip protocols" reports all protocols across all VRFs unfortunately
          if instanceName == defaultInstanceName : 
            if thisProtocol == L3Discovery.NeighborProtocol.BGP:
              b = Session.ExecCommand("show ip bgp summary")
              if b : self._runningRoutingProtocols[ instanceName ].Add(thisProtocol)
            elif thisProtocol == L3Discovery.NeighborProtocol.OSPF:
              o = Session.ExecCommand("show ip ospf neighbor")
              if o : self._runningRoutingProtocols[ instanceName ].Add(thisProtocol)
            elif thisProtocol == L3Discovery.NeighborProtocol.EIGRP:
              e = Session.ExecCommand("show ip eigrp neighbor")
              if e : self._runningRoutingProtocols[ instanceName ].Add(thisProtocol)
            elif thisProtocol == L3Discovery.NeighborProtocol.RIP:
              e = Session.ExecCommand("show ip rip neighbor")
              if e : self._runningRoutingProtocols[ instanceName ].Add(thisProtocol)
          else:
            self._runningRoutingProtocols[ instanceName ].Add(thisProtocol)
    
      # STATIC 
      cmd = "show ip route static"
      if instanceName != defaultInstanceName:
        cmd = "show ip route vrf {0} static".format(instanceName)
      response = Session.ExecCommand(cmd);  
      if response : 
        self._runningRoutingProtocols[instance.Name].append(NeighborProtocol.STATIC)  
        
 
      # CDP - only for default instance
      if instanceName == defaultInstanceName:
        response = Session.ExecCommand("show cdp")
        cdpEnabled = not ("not enabled" in response)
        if cdpEnabled: 
          self._runningRoutingProtocols[instanceName].Add(NeighborProtocol.CDP)
          
    result =  self._runningRoutingProtocols[instanceName]
    return result
예제 #22
0
        def __clrtype__(self):
            global called

            baseType = super(MyType, self).__clrtype__()
            typegen = Snippets.Shared.DefineType(
                "faux type property" + str(TYPE_COUNTER), baseType, True,
                False)
            typebld = typegen.TypeBuilder

            for ctor in baseType.GetConstructors():
                ctorparams = ctor.GetParameters()
                ctorbld = typebld.DefineConstructor(
                    ctor.Attributes, ctor.CallingConvention,
                    tuple([p.ParameterType for p in ctorparams]))
                ilgen = ctorbld.GetILGenerator()
                ilgen.Emit(OpCodes.Ldarg, 0)
                for index in range(len(ctorparams)):
                    ilgen.Emit(OpCodes.Ldarg, index + 1)
                ilgen.Emit(OpCodes.Call, ctor)
                ilgen.Emit(OpCodes.Ret)

            #Add the property
            prop_type = clr.GetClrType(System.UInt64)
            field_builder = typebld.DefineField("NOT_SO_DYNAMIC", prop_type,
                                                FieldAttributes.Public)
            prop_method_attribs = (MethodAttributes.Public
                                   | MethodAttributes.SpecialName
                                   | MethodAttributes.HideBySig)
            #Property getter
            prop_getter_builder = typebld.DefineMethod("get_NOT_SO_DYNAMIC",
                                                       prop_method_attribs,
                                                       prop_type, None)
            getilgen = prop_getter_builder.GetILGenerator()
            getilgen.Emit(OpCodes.Ldarg_0)
            getilgen.Emit(OpCodes.Ldfld, field_builder)
            getilgen.Emit(OpCodes.Ret)
            #Propery setter
            prop_setter_builder = typebld.DefineMethod("set_NOT_SO_DYNAMIC",
                                                       prop_method_attribs,
                                                       None, (prop_type, ))
            setilgen = prop_setter_builder.GetILGenerator()
            setilgen.Emit(OpCodes.Ldarg_0)
            setilgen.Emit(OpCodes.Ldarg_1)
            setilgen.Emit(OpCodes.Stfld, field_builder)
            setilgen.Emit(OpCodes.Ret)
            #Actual property
            prop_builder = typebld.DefineProperty("NOT_SO_DYNAMIC",
                                                  PropertyAttributes.None,
                                                  prop_type, None)
            prop_builder.SetGetMethod(prop_getter_builder)
            prop_builder.SetSetMethod(prop_setter_builder)

            #Hook the C# property up to the Python version
            new_type = typebld.CreateType()
            fldinfo = new_type.GetField("NOT_SO_DYNAMIC")
            setattr(self, "NOT_SO_DYNAMIC", ReflectedField(fldinfo))

            called = True
            return new_type
예제 #23
0
def updateDeviceState(device, boolValue):
    if not isinstance(device, devapi.Device):
        return False

    if not clr.GetClrType(devapi.UpdateDevice(device, boolValue)):
        return False

    return True
예제 #24
0
def test_serializable_clionly():
    import clr
    import System
    from IronPythonTest import ExceptionsTest
    path = clr.GetClrType(ExceptionsTest).Assembly.Location
    mbro = System.AppDomain.CurrentDomain.CreateInstanceFromAndUnwrap(
        path, "IronPythonTest.EngineTest")
    AssertError(AssertionError, mbro.Run, 'raise AssertionError')
예제 #25
0
 def getAllViews(self):
     global totalView
     viewInstancesFilter = ElementClassFilter(clr.GetClrType(rView))
     collector = FilteredElementCollector(doc)
     textsId = collector.WherePasses(viewInstancesFilter).ToElementIds()
     totalView = textsId.Count
     print totalView, " views picked"
     return textsId
예제 #26
0
def test_references():
    refs = clr.References
    atuple = refs + (clr.GetClrType(int).Assembly, ) # should be able to append to references_tuple
    #AssertError(TypeError, refs.__add__, "I am not a tuple")

    s = str(refs)
    temp = ',' + newline
    AreEqual(s, '(' + temp.join(map((lambda x:'<'+x.ToString()+'>'), refs)) + ')' + newline)
 def _get_item_by_partial_text(self, partial_text, item_type=None):
     items = self._get_multiple_items_by_partial_text(partial_text)
     try:
         if item_type is None:
             return next(items)
         return next((item for item in items if item.GetType() == clr.GetClrType(item_type)))
     except StopIteration:
         raise ItemNotFoundError(u"Item with partial text '{}' was not found".format(partial_text))
예제 #28
0
def existViewName(vname):
    vInstancesFilter = ElementClassFilter(clr.GetClrType(View))
    collector = FilteredElementCollector(doc)
    vs = collector.WherePasses(vInstancesFilter)
    for ele in vs:
        if ele.Name == vname:
            return True
    return False
예제 #29
0
def restore_clr(p_name, p_class, update_imports_for=None):
    """
    Restore the function signature by the CLR type signature
    :return (is_static, spec, sig_note, overloaded: bool)
    """
    clr_type = clr.GetClrType(p_class)

    if p_name == '__new__':
        p_name = '__init__'
        methods = [c for c in clr_type.GetConstructors()]
        if not methods:
            yield False, p_name + '(self, *args)', 'cannot find CLR constructor', 'None'  # "self" is always first argument of any non-static method
            return
    else:
        methods = [m for m in clr_type.GetMethods() if m.Name == p_name]
        if not methods:
            bases = p_class.__bases__
            if len(bases) == 1 and p_name in dir(bases[0]):
                # skip inherited methods
                yield False, None, None, 'None'
                return

            yield False, None, None, 'None'  #p_name + '(self, *args)', 'cannot find CLR method', 'None'
            return
            # "self" is always first argument of any non-static method

    parameter_lists = []
    parameter_types = []
    method_returns = []
    for m in methods:
        parameter_lists.append([p.Name for p in m.GetParameters()])
        parameter_types.append([
            resolve_generic_type_params(t.ParameterType,
                                        update_imports_for=update_imports_for)
            for t in m.GetParameters()
        ])
        return_type = m.ReturnType if m.Name != '.ctor' else clr_type
        method_returns.append([
            resolve_generic_type_params(return_type,
                                        update_imports_for=update_imports_for)
        ])

    for (params, method_return) in restore_parameters_for_overloads(
            parameter_lists, parameter_types, method_returns):
        is_static = False
        if not methods[0].IsStatic:
            params = ['self'] + params
        else:
            is_static = True

        # We return Pandas DataFrames when calling QCAlgorithm's History method from Python
        if p_class.__name__ == 'QCAlgorithm' and p_name == 'History':
            method_return[0] = 'pandas.DataFrame'
            update_imports_for.used_imports['pandas'] = '*'

        yield is_static, build_signature(
            p_name, params,
            method_return=method_return[0]), None, method_return[0]
예제 #30
0
def __build_module():
    def function_description(description, params):
        rc = ['', description, "Input:"]
        for param in params.Input:
            s = "\t{0} [{1}] - {2}"
            if param.Optional:
                s = "\t{0} (in, optional) [{1}] - {2}"
            rc.append(
                s.format(param.Name.lower(), param.TypeName,
                         param.Description))
        if params.Output.Count == 1:
            param = params.Output[0]
            rc.append("Returns: [{0}] - {1}".format(param.TypeName,
                                                    param.Description))
        elif params.Output.Count > 1:
            rc.append("Returns:")
            for out in params.Output:
                s = "\t{0} [{1}] - {2}"
                rc.append(
                    s.format(out.Name.lower(), out.TypeName, out.Description))
        return '\n'.join(rc)

    import sys, types, re
    core_module = sys.modules['ghpythonlib.components']
    translate_from = u"|+-*\u2070\u00B9\u00B2\u00B3\u2074\u2075\u2076\u2077\u2078\u2079"
    translate_to = "X__x0123456789"
    transl = dict(zip(translate_from, translate_to))
    for obj in GH.Instances.ComponentServer.ObjectProxies:
        if obj.Exposure == GH.Kernel.GH_Exposure.hidden or obj.Obsolete:
            continue
        t = clr.GetClrType(GH.Kernel.IGH_Component)
        if not (t.IsAssignableFrom(obj.Type)):
            continue
        m = core_module
        library_id = obj.LibraryGuid
        assembly = GH.Instances.ComponentServer.FindAssembly(library_id)
        if assembly is None: continue
        if not assembly.IsCoreLibrary:
            module_name = assembly.Assembly.GetName().Name.split('.', 1)[0]
            if module_name.upper().startswith("GH_"):
                module_name = module_name[3:]
            if module_name in core_module.__dict__:
                m = core_module.__dict__[module_name]
            else:
                m = namespace_object()
                setattr(core_module, module_name, m)
        name = obj.Desc.Name
        if "LEGACY" in name or "#" in name: continue
        name = re.sub(
            "[^a-zA-Z0-9]", lambda match: transl[match.group()]
            if (match.group() in transl) else '', name)
        if not name[0].isalpha(): name = 'x' + name
        function = __make_function__(function_helper(obj, name))
        setattr(m, name, function)
        comp = obj.CreateInstance()
        a = m.__dict__[name]
        a.__name__ = name
        a.__doc__ = function_description(obj.Desc.Description, comp.Params)