Ejemplo n.º 1
0
    #
    # You should have received a copy of the GNU General Public License
    # along with Ladybug; If not, see <http://www.gnu.org/licenses/>.
    #
    # @license GPL-3.0+ <http://spdx.org/licenses/GPL-3.0+>
    """

    # add IronPython path to sys
    import sys
    IronPythonLib = 'C:\Program Files (x86)\IronPython 2.7\Lib'
    sys.path.append(IronPythonLib)

    # Now that the path to IronPython is established we can import libraries
    import os
    import clr
    clr.AddReference('DynamoCore')

    def getPackagePath(packageName):
        #Get path to dynamo package using the package name
        dynamoPath = clr.References[2].Location.split('\\')[2].replace(
            ' ', '\\')
        appdata = os.getenv('APPDATA')
        return '%s\%s\packages\%s\extra\\' % (appdata, dynamoPath, packageName)

    # append ladybug path to sys.path
    sys.path.append(getPackagePath('Ladybug'))

    ###### start you code from here ###
    outputsDescription = """
            location: A list of text summarizing the location data in the weather file (use this to construct the sun path).
from pydhi.helpers import safe_length

import clr

clr.AddReference('System.Collections')
from System import Int32
from System.Collections.Generic import List

def test_safe_length_returns_length_for_python_list():

    a = [1,2,6]

    n = safe_length(a)

    assert n==3

def test_safe_length_returns_length_for_net_list():

    a = List[Int32]()
    a.Add(1)
    a.Add(2)
    a.Add(6)

    n = safe_length(a)

    assert n==3
Ejemplo n.º 3
0
#coding=utf-8
from PA_runtime import *
import clr
clr.AddReference('System.Core')
clr.AddReference('System.Xml.Linq')
clr.AddReference('System.Data.SQLite')
del clr

import pickle
from System.Xml.Linq import *
import System.Data.SQLite as SQLite

import os
import sqlite3

# 账号信息
SQL_CREATE_TABLE_WA_MFORENSICS_060100 = '''
    create table if not exists WA_MFORENSICS_060100(
        COLLECT_TARGET_ID TEXT,  
        BROWSE_TYPE TEXT,
        ACCOUNT_ID TEXT,
        ACCOUNT TEXT,
        REGIS_NICKNAME TEXT,
        PASSWORD TEXT,
        INSTALL_TIME INT,
        AREA TEXT,
        CITY_CODE TEXT,
        FIXED_PHONE TEXT,
        MSISDN TEXT,
        EMAIL_ACCOUNT TEXT,
        CERTIFICATE_TYPE TEXT,
Ejemplo n.º 4
0
import clr
clr.AddReference("System.Windows.Forms")
clr.AddReference("System.Drawing")
clr.AddReference("System.ComponentModel")

import System.Drawing
import System.Windows.Forms

from System.Drawing import *
from System.Windows.Forms import *


class Form1(Form):
    def __init__(self):
        self.InitializeComponent()

    def InitializeComponent(self):
        resources = System.Resources.ResourceManager(
            "Form1", System.Reflection.Assembly.GetEntryAssembly())
        self._splitContainer1 = System.Windows.Forms.SplitContainer()
        self._splitContainer2 = System.Windows.Forms.SplitContainer()
        self._button1 = System.Windows.Forms.Button()
        self._pictureBox1 = System.Windows.Forms.PictureBox()
        self._splitContainer1.BeginInit()
        self._splitContainer1.Panel1.SuspendLayout()
        self._splitContainer1.Panel2.SuspendLayout()
        self._splitContainer1.SuspendLayout()
        self._splitContainer2.BeginInit()
        self._splitContainer2.Panel2.SuspendLayout()
        self._splitContainer2.SuspendLayout()
        self._pictureBox1.BeginInit()
Ejemplo n.º 5
0
import clr
clr.AddReference("System.Windows.Forms")

from System import Uri, Threading
from System.Drawing import Size, Point, Color
import System.Windows.Forms as WinForms
from System import Decimal as ClrDecimal
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import clr

clr.AddReference("System")
clr.AddReference("QuantConnect.Algorithm")
clr.AddReference("QuantConnect.Indicators")
clr.AddReference("QuantConnect.Common")

from System import *
from QuantConnect import *
from QuantConnect.Algorithm import *
from QuantConnect.Indicators import *
import decimal as d


### <summary>
### In this example we look at the canonical 15/30 day moving average cross. This algorithm
### will go long when the 15 crosses above the 30 and will liquidate when the 15 crosses
### back below the 30.
import clr
clr.AddReference("System.Core")
clr.AddReference("OpenCV.Net")
clr.AddReference("Bonsai.Vision")
from System import Tuple, Math, Single, Array
import math
from System.Linq import Enumerable
from OpenCV.Net import Point, Point2f
from Bonsai.Vision import ConnectedComponentCollection

base = None
NaNPoint = Point2f(float.NaN, float.NaN)
centroidLoc = NaNPoint
centroidVel = NaNPoint
distThd = 20


def FindBasePoint(inputPointArray):
    pointList = Enumerable.OrderBy(inputPointArray, lambda x: x.X)
    firstPoint = Enumerable.First(pointList)
    return firstPoint


def VDistFromLastFrame(pt1, pt2):
    #dx = (pt2.X - pt1.X)
    dy = (pt2.Y - pt1.Y)
    return dy


@returns(
    ConnectedComponentCollection
Ejemplo n.º 8
0
import clr
clr.AddReference("RevitNodes")
import Revit
clr.ImportExtensions(Revit.Elements)

clr.AddReference("RevitServices")
import RevitServices
from RevitServices.Persistence import DocumentManager

clr.AddReference("RevitAPI")
import Autodesk
from Autodesk.Revit.DB import *

import System
from System.Collections.Generic import *

doc = DocumentManager.Instance.CurrentDBDocument

collector = FilteredElementCollector(doc)
ofClass = collector.OfClass(Wall).ToElements()

ActiveView = FilteredElementCollector(doc, doc.ActiveView.Id).OfClass(Wall).ToElements()

builtInCategory = FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Walls).WhereElementIsNotElementType().ToElements()

wallList = []
for w in builtInCategory:
    if w.Name.Equals("SW48"):
        wallList.append(w)

walls = list(filter(lambda x : x.Name.Equals("SW48"), builtInCategory))
Ejemplo n.º 9
0
e_a = str("\xe9")
a_a = str("\xe0")

__title__ = 'Beam tagging\nCANOPY'

__doc__ = 'Ce programme remplit les arases inferieures mini et maxi des poutres '\
      '(parametres AI_Min et AI_Max) de la vue active du projet CANOPY'

# from pyrevit import revit, DB, UI
# from pyrevit import script
# from pyrevit import forms

import clr
import math
from pyrevit import forms
clr.AddReference('RevitAPI')
clr.AddReference('RevitAPIUI')
from Autodesk.Revit.DB import *
from Autodesk.Revit.UI import *

doc = __revit__.ActiveUIDocument.Document

options = __revit__.Application.Create.NewGeometryOptions()

BP_collector = FilteredElementCollector(doc)\
          .OfCategory(BuiltInCategory.OST_ProjectBasePoint)\
          .WhereElementIsNotElementType()\
          .ToElements()

beam_collector = FilteredElementCollector(doc,doc.ActiveView.Id)\
          .OfCategory(BuiltInCategory.OST_StructuralFraming)\
# Enable Python support and load DesignScript library
import clr
clr.AddReference('ProtoGeometry')
from Autodesk.DesignScript.Geometry import *

# The inputs to this node will be stored as a list in the IN variables.
dataEnteringNode = IN
ElementList = []
if isinstance(IN[0], list):
    ElementList.extend(IN[0])
else:
    ElementList.append(IN[0])

ElementList = UnwrapElement(ElementList)
ParametersListParam = []
for a in ElementList:
    ParametersListParam.append(a.Parameters)

ParametersList = []
while len(ParametersList) != len(ParametersListParam):
    ParametersList.append([])
for list in ParametersListParam:
    for item in list:
        ParametersList[ParametersListParam.index(list)].append(
            item.Definition.Name)

OUT = ParametersList
Ejemplo n.º 11
0
except ImportError:
    compas.raise_if_ironpython()

try:
    from compas_rhino.etoforms import PropertyListForm

except:
    try:
        from Rhino.UI.Dialogs import ShowPropertyListBox

    except ImportError:
        compas.raise_if_ironpython()
else:
    try:
        import clr
        clr.AddReference('Rhino.UI')
        import Rhino.UI

    except ImportError:
        compas.raise_if_ironpython()


__all__ = ['VertexModifier']


def rhino_update_named_values(names, values, message='', title='Update named values'):
    try:
        dialog = PropertyListForm(names, values)
    except:
        values = ShowPropertyListBox(message, title, names, values)
    else:
Ejemplo n.º 12
0
# IronPython imports to enable Excel interop,
import clr
clr.AddReference("Microsoft.Office.Interop.Excel")
import Microsoft.Office.Interop.Excel as Excel
from System.Runtime.InteropServices import Marshal

# import system things needed below
from System.IO import Directory, Path
from System import DateTime

# use the ANSYS function GetProjectDirectory to figure out what directory you are in
# and set that to the current directory
projDir = GetProjectDirectory()
Directory.SetCurrentDirectory(projDir)

# Open up a log file to put useful information in
logFile = open("TowerTool.log", "w")

# Put a header in the log file
logFile.write("================================================\n")
logFile.write("Tower Tool Run Log File\n")
logFile.write("================================================\n")
logFile.write("Start time: " + DateTime.Now.ToString('yyyy-mm-dd hh:mm:ss') +
              "\n")
logFile.write("Proj Dir: %s\n\n" % projDir)

# Use the Excel GetActiveObject funtion to get the object for the excel session
ex = Marshal.GetActiveObject("Excel.Application")
# Make Excel visible
ex.Visible = True
# Define the active workbook and worksheet
Ejemplo n.º 13
0
# ================ system imports
import clr

import sys
# sys.path.append(r"C:\Program Files\Dynamo 0.8")
pyt_path = r'C:\Program Files (x86)\IronPython 2.7\Lib'
sys.path.append(pyt_path)
sys.path.append(IN[0].DirectoryName)  # type: ignore

import System
from System import Array
from System.Collections.Generic import *

# ================ Revit imports
clr.AddReference('RevitAPIUI')
from Autodesk.Revit.UI import *

clr.AddReference('RevitAPI')
import Autodesk
from Autodesk.Revit.DB import *

clr.AddReference("RevitServices")
import RevitServices
from RevitServices.Persistence import DocumentManager
from RevitServices.Transactions import TransactionManager

# ================ Python imports
import math
from math import sqrt

import el_exceptions
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
#

import clr
import System

clr.AddReference("System.Core")
from System.IO import HandleInheritability
import System.IO.Pipes as Pipes
import System.Security.Principal as Principal
import System.Security.AccessControl as AccessControl

MAX_NUMBER_OF_INSTANCES = 16
PIPE_IO_BUFFER_SIZE = 8192

IN = Pipes.PipeDirection.In
OUT = Pipes.PipeDirection.Out


def CreateNamedPipeServer(pipeName):
    worldsid = Principal.SecurityIdentifier(
        Principal.WellKnownSidType.WorldSid, None)
Ejemplo n.º 15
0
import clr
clr.AddReference('RevitAPI')
import Autodesk
from Autodesk.Revit.DB import *

clr.AddReference('RevitServices')
import RevitServices
from RevitServices.Persistence import DocumentManager
doc = DocumentManager.Instance.CurrentDBDocument

elements = FilteredElementCollector(doc).OfClass(ViewSchedule)

name, guid, owner, creator, changeby = [], [], [], [], []

for x in elements:
    ws = WorksharingUtils.GetWorksharingTooltipInfo(doc, x.Id)
    name.append(x.Name.ToString())
    guid.append(x.UniqueId)
    owner.append(ws.Owner)
    creator.append(ws.Creator)
    changeby.append(ws.LastChangedBy)

flist = map(list, zip(*(name, guid, owner, creator, changeby)))

l1, l2 = [], []

for x in flist:
    if '<Revision Schedule> 2889' in x:
        l1.append(x)
    else:
        l2.append(x)
Ejemplo n.º 16
0
'''
This module is home to the ButtonDataGridView class.

@author: Cory Banack
'''

import clr

clr.AddReference('System.Windows.Forms')
from System.Windows.Forms import DataGridView

# =============================================================================
class ButtonDataGridView(DataGridView):
   ''' 
   The ButtonDataGridView is a specialized DataGridView subclass that replaces 
   its regular "enter" keystroke behaviour with a mouse click event on a button.

   The clicked button is provided in the constructor of the ButtonDataGridView.
   '''  

   # ==========================================================================   
   def __init__(self, button):
      '''
      Initializes a new ButtonDataGridView.  The given button is the .NET
      Button object that should be 'clicked' anytime the user presses enter on
      this DataGridView.   It must not be None.
      '''
      if button is None:
         raise Exception("None is not allow as an argument here.")
      self.__button = button
   
Ejemplo n.º 17
0
"""

# Author: Robert Wall

import numpy as np
import geopandas as gpd
import datetime as dt
import os
import clr
from . import config

# Set path to MIKE SDK
sdk_path = config.MIKE_SDK
dfs_dll = config.MIKE_DFS
eum_dll = config.MIKE_EUM
clr.AddReference(os.path.join(sdk_path, dfs_dll))
clr.AddReference(os.path.join(sdk_path, eum_dll))
clr.AddReference('System')

# Import .NET libraries
import DHI.Generic.MikeZero.DFS as dfs
from DHI.Generic.MikeZero import eumUnit, eumItem, eumQuantity
import System
from System import Array

from . import _utils


class Mesh(object):
    """
    MIKE21 .mesh
Ejemplo n.º 18
0
import os
import sys
import clr
import time
import random
import datetime
import shutil
clr.AddReference('IronPython.SQLite.dll')
clr.AddReference('IronPython.Modules.dll')

#---------------------------------------
# [Required] Script Information
#---------------------------------------
ScriptName = 'Friday Night Jams - Singles'
Website = 'https://www.StreamlabsChatbot.com'
Description = 'Friday Night Jams - Singles (!fnjs)'
Creator = 'DrWhistler'
Version = '1.0.0.0'

#---------------------------------------
# Set Variables
#---------------------------------------
m_Response = 'This is a test message'
m_Command = '!fnjs'
m_CooldownSeconds = 10
m_CommandPermission = 'Moderator'
m_CommandInfo = ''

userId = ""

Ejemplo n.º 19
0
import sys
import os
from time import sleep
# sys.path.append(r'C:\Python24\Lib')
sys.path.append(
    r'C:\Users\martin.carufel\AppData\Local\Programs\Python\Python37-32\Lib\site-packages'
)
sys.path.append('C:/Drive-W/Internal_tools/Libraries/IOLibrary/trunk/out')
from IOWrapper import IOWrapper
import clr
clr.AddReference("System.Drawing")
clr.AddReference("System.Windows.Forms")
from System.Drawing import Point, Size
from System.Windows.Forms import Application, Button, Form, Label

io_out_port = os.environ['ev_io_out_port']
io_in_port = os.environ['ev_io_in_port']

io = IOWrapper()
# io.IO_Connect_Device(1, io_in_port)
io.IO_Connect_Device(2, io_out_port)
io.IO_Read_Map('DS4-Analog Harness_3.xml')


class ButtonLib(Form):
    def __init__(self, text='', posX=0, posY=0, linkedOutput=''):
        self.text = text
        self.button = Button()
        self.posX = posX
        self.posY = posY
        self.linkedOutput = linkedOutput
Ejemplo n.º 20
0
from pyrevit.framework import List
from pyrevit import revit, DB
import clr

clr.AddReference('RevitAPI')
clr.AddReference('RevitAPIUI')
clr.AddReference("System")
from Autodesk.Revit.DB import FilteredElementCollector
from Autodesk.Revit.DB import BuiltInCategory, ElementId
from System.Collections.Generic import List

doc = __revit__.ActiveUIDocument.Document

__doc__ = 'Check if the PA - View Classification Parameter Exists'\
          'Can be modified to check other parameters too'

# View and Sheets Collector
views = DB.FilteredElementCollector(doc)\
              .OfCategory(BuiltInCategory.OST_Viewports)\
              .ToElements()
print('We found ' + str(len(views)) + ' views')
sheets = DB.FilteredElementCollector(doc)\
              .OfCategory(BuiltInCategory.OST_Sheets)\
              .ToElements()
print('We found ' + str(len(sheets)) + ' sheets')
# See if the parameter exists
print('-------------------------------------------')
for view in views:
    a = view.LookupParameter('PA - View Classification')
    if not a:
        print('PA - View Classification Parameter in views Missing')
Ejemplo n.º 21
0
#coding: utf-8
'''
This module contains a variety of generally useful utility methods.

@author: Cory Banack
'''

import clr
from time import strftime
import re
import sys

clr.AddReference('System')
from System.IO import File, StreamReader, StreamWriter, StringWriter
from System.Text import Encoding
from System.Net import HttpStatusCode, WebException, WebRequest

clr.AddReference('System.Drawing')
from System.Drawing import Graphics, Bitmap

clr.AddReference('System.Web')
from System.Web import HttpUtility

clr.AddReference('IronPython')
from IronPython.Compiler import CallTarget0

# unmodifiable cache for speeding up calls to natural_compare
__keys_cache = None


#==============================================================================
Ejemplo n.º 22
0
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#

import logging

log = logging.getLogger(__name__)
log.addHandler(logging.NullHandler())

from pymeasure.instruments import Instrument, RangeException
from pymeasure.instruments.validators import truncated_range, strict_discrete_set
import clr
clr.AddReference('mcl_SolidStateSwitch_NET45')
from mcl_SolidStateSwitch_NET45 import USB_Digital_Switch

import numpy as np
import time


class USB_2SP2T_DCH():
    """ Represents the USB-2SP2T-DCH solid state switch and provides a high level
    interface to the SCIPI commands. Requires that the mcl_SolidStateSwitch_NET45 be in the path
    or same directory as the running code.

    """
    def __init__(self, SN=None):
        self.connection = USB_Digital_Switch()
        if SN is not None:
Ejemplo n.º 23
0
# -*- coding: utf-8 -*-
__author__ = 'xiaoyuge'

import os
import PA_runtime
from PA_runtime import *
import clr
try:
    clr.AddReference('System.Data.SQLite')
    clr.AddReference('model_im')
except:
    pass
del clr

import System.Data.SQLite as SQLite
import model_im

import os
import hashlib
from System.Text import Encoding
from PA_runtime import *
import json
import traceback
import time

fid = 3


class JuxingParse(model_im.IM):
    def __init__(self, dir, extractDeleted, extractSource):
        self.dir = dir
Ejemplo n.º 24
0
# Licensed to the .NET Foundation under one or more agreements.
# The .NET Foundation licenses this file to you under the Apache 2.0 License.
# See the LICENSE file in the project root for more information.

import clr
import System

clr.AddReference("System.Core")
clr.AddReference("Microsoft.Scripting")
clr.AddReference("IronPython")
clr.AddReference("Microsoft.Dynamic")

from Microsoft.Scripting.Generation import Snippets
from IronPython.Compiler import CallTarget0

paramTypes = System.Array[System.Type]([])

ilgen = Snippets.Shared.CreateDynamicMethod("test", System.Object, paramTypes,
                                            False)
ilgen.Emit(System.Reflection.Emit.OpCodes.Ret)
ilgen.CreateDelegate[CallTarget0](
    clr.Reference[System.Reflection.MethodInfo]())
Ejemplo n.º 25
0
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import os
import clr
#import codecs
from Python.Runtime import PyObjectConversions
from Python.Runtime.Codecs import RawProxyEncoder
from System.IO import (MemoryStream, StreamWriter, StreamReader)
from System.Text import UTF8Encoding
file_path, _ = os.path.split(os.path.realpath(__file__))
clr.AddReference(os.path.join(file_path, '../Asap2/bin/Debug/Asap2.dll'))

from Asap2 import *


# https://github.com/pythonnet/pythonnet/issues/514
class ListAsRawEncoder(RawProxyEncoder):
    __namespace__ = "MyNameSpace"

    def CanEncode(self, clr_type):
        return clr_type.Name == "List`1" and clr_type.Namespace == "System.Collections.Generic"


class ErrorHandler(IErrorReporter):
    __namespace__ = "MyNameSpace"

    def __init__(self):
        self.informations = 0
        self.warnings = 0
        self.errors = 0
#
#   to run:
#       ipy.exe ad-sample.py
#   v2.2, Updated: 02-08-2014
##############################################

import types
import os.path
import urllib
import urllib2
import traceback
import base64
import System
import clr
import math
clr.AddReference("System.DirectoryServices")
clr.AddReference('System.Management.Automation')

from System.Management.Automation import RunspaceInvoke
# +---------------------------------------------------------------------------

# create a runspace to run shell commands from
RUNSPACE = RunspaceInvoke()

BASE_URL='https://your-url-here'        #make sure to NOT to end in /

API_DEVICE_URL=BASE_URL+'/api/device/'
API_IP_URL    =BASE_URL+'/api/ip/'

USER    ='******'
PASSWORD='******'
#Copyright(c) 2015, Konrad K Sobon
# @arch_laboratory, http://archi-lab.net

import clr
clr.AddReference('ProtoGeometry')
from Autodesk.DesignScript.Geometry import *

# Import DocumentManager and TransactionManager
clr.AddReference("RevitServices")
import RevitServices
from RevitServices.Persistence import DocumentManager
from RevitServices.Transactions import TransactionManager

from System.Collections.Generic import *

# Import RevitAPI
clr.AddReference("RevitAPI")
import Autodesk
from Autodesk.Revit.DB import *
from Autodesk.Revit.DB.Analysis import *

doc = DocumentManager.Instance.CurrentDBDocument
uiapp = DocumentManager.Instance.CurrentUIApplication
app = uiapp.Application

# Import ToDSType(bool) extension method
clr.AddReference("RevitNodes")
import Revit
clr.ImportExtensions(Revit.Elements)

#The inputs to this node will be stored as a list in the IN variable.
Ejemplo n.º 28
0
import sys
import os
import thread
import clr
import wpf
from modulebase import xmlobject, xdist
from modulebuilder import *

clr.AddReference("System.Xml")
from System.Xml import XmlDocument



class configloader():
    def __init__(self):
        #configs(string, buildconfig)
        self.configs = {}
        #configs(string, buildprojects)
        self.projects = {}

    def load(self):
        #do init
        self.loadConfigs()
        self.loadProjects()

    #lookfor builder.*.xml => self.configs{configfile, buildconfig(configfile)}
    def loadConfigs(self):
        for root, dirs, files in os.walk(os.getcwd(), topdown = True):
            for f in files:
                fname = os.path.splitext(f)
                if len(fname) > 1 and fname[1].lower() == '.xml' and fname[0][:7].lower() == 'builder':
Ejemplo n.º 29
0
def icon_to_base64(icon=None, size=None, mode=QtCore.Qt.KeepAspectRatio, fmt='PNG'):
    """Convert the icon to a :class:`QtCore.QByteArray` encoded as Base64_.

    This function is useful if you want to save icons in a database, use it in a
    data URI scheme_, or if you want to use icons in your GUI and rather than loading
    icons from a file on the hard disk you define your icons in a Python module as
    Base64_ variables. Loading the icons from the hard disk means that you must also
    distribute the icons with your Python code if you share your code.

    .. _Base64: https://en.wikipedia.org/wiki/Base64
    .. _scheme: https://en.wikipedia.org/wiki/Data_URI_scheme

    Parameters
    ----------
    icon : :class:`object`, optional
        An icon with a data type that is handled by :func:`get_icon`. If :obj:`None`
        then a dialog window is created to allow the user to select an icon file
        that is saved in a folder.
    size : :class:`int`, :class:`float`, :class:`tuple` of :class:`int` or :class:`QtCore.QSize`, optional
        Rescale the icon to the specified `size` before converting it to Base64_.
        If the value is :obj:`None` then do not rescale the icon.
        If an :class:`int` then set the width and the height to be the `size` value.
        If a :class:`float` then a scaling factor.
        If a :class:`tuple` then the (width, height) values.
    mode : QtCore.Qt.AspectRatioMode_, optional
        How to maintain the aspect ratio if rescaling. The default mode is to keep the aspect ratio.
    fmt : :class:`str`, optional
        The icon format to use when converting. The supported values are: ``BMP``,
        ``JPG``, ``JPEG`` and ``PNG``.

    Returns
    -------
    :class:`QtCore.QByteArray`
        The Base64_ representation of the icon.

    Raises
    ------
    :exc:`IOError`
        If the icon file cannot be found.
    :exc:`ValueError`
        If the icon format, `fmt`, to use for converting is not supported.
    """
    fmt = fmt.upper()
    ALLOWED_FORMATS = ['BMP', 'JPG', 'JPEG', 'PNG']
    if fmt not in ALLOWED_FORMATS:
        raise ValueError('Invalid format {}. Must be one of: {}'.format(fmt, ', '.join(ALLOWED_FORMATS)))

    if isinstance(icon, str) and '|' in icon:
        # extract an icon from a Windows DLL/EXE file
        # uses ctypes and the .NET Framework to convert the icon to base64
        # import here in case pythonnet is not installed
        import clr
        import ctypes

        clr.AddReference('System.Drawing')
        from System.Drawing.Imaging import ImageFormat

        shell32 = ctypes.windll.shell32

        img_fmts = {
            'BMP':  ImageFormat.Bmp,
            'JPG':  ImageFormat.Jpeg,
            'JPEG': ImageFormat.Jpeg,
            'PNG':  ImageFormat.Png,
        }

        s = icon.split('|')
        path = s[0]
        icon_index = int(s[1])
        if icon_index < 0:
            raise IOError('The icon index must be >= 0')

        if not os.path.isfile(path):
            err_msg = "Cannot find DLL/EXE file '{}'".format(s[0])
            if os.path.split(path)[0]:  # then it wasn't just the filename that was specified
                raise IOError(err_msg)

            filename = os.path.splitext(os.path.basename(path))[0]
            path = 'C:/Windows/System32/{}.dll'.format(filename)
            if not os.path.isfile(path):
                path = 'C:/Windows/{}.exe'.format(filename)
                if not os.path.isfile(path):
                    raise IOError(err_msg)

        # extract the handle to the "large" icon
        path_ptr = ctypes.c_char_p(path.encode())
        handle_large = ctypes.c_int()
        res = shell32.ExtractIconExA(path_ptr, icon_index, ctypes.byref(handle_large), ctypes.c_void_p(), 1)
        if res != 1:
            # Check if the icon index is valid
            max_index = shell32.ExtractIconExA(path_ptr, -1, ctypes.c_void_p(), ctypes.c_void_p(), 0) - 1
            if icon_index > max_index:
                msg = 'Requested icon {}, the maximum icon index allowed is {}'.format(icon_index, max_index)
            else:
                msg = "ExtractIconExA: Cannot extract icon {} from '{}'".format(icon_index, path)
            raise IOError(msg)

        # get the icon bitmap and convert it to base64
        handle = clr.System.Int32(handle_large.value)
        handle_ptr = clr.System.IntPtr.op_Explicit(handle)
        bmp = clr.System.Drawing.Bitmap.FromHicon(handle_ptr)
        stream = clr.System.IO.MemoryStream()
        bmp.Save(stream, img_fmts[fmt])
        base = QtCore.QByteArray(clr.System.Convert.ToBase64String(stream.GetBuffer()).encode())

        # clean up
        ctypes.windll.user32.DestroyIcon(handle_large)
        stream.Dispose()
        return base

    # ensure that a QApplication exists in order to access Qt classes
    app = application()

    if icon is None:
        title = 'Select an icon file to convert to Base64'
        filters = {'Images': ('bmp', 'jpg', 'jpeg', 'png'), 'All files': '*'}
        icon = prompt.filename(title=title, filters=filters)
        if icon is None:
            return QtCore.QByteArray()
        icon = str(icon)

    icon = get_icon(icon)
    try:
        default_size = icon.availableSizes()[-1]  # use the largest size as the default size
    except IndexError:
        prompt.critical('Invalid icon file.')
        return QtCore.QByteArray()

    pixmap = icon.pixmap(default_size)
    if size is not None:
        pixmap = rescale_icon(pixmap, size, mode)

    array = QtCore.QByteArray()
    buffer = QtCore.QBuffer(array)
    buffer.open(QtCore.QIODevice.WriteOnly)
    pixmap.save(buffer, fmt)
    buffer.close()
    return array.toBase64()
Ejemplo n.º 30
0
# -*- coding: utf-8 -*-

from System import Action, Uri
from System.Threading.Tasks import Task
from System.Diagnostics import Process

import clr
clr.AddReference("PresentationFramework")
from System.Windows.Controls import TextBlock, ScrollViewer, ScrollBarVisibility
from System.Windows.Documents import Run, Hyperlink, LineBreak

import rssparser


#テキストブロックをUIスレッド上で作成して表示する
def show(rssItems):
    def _OnRequestNavigate(sender, e):
        Task.Run.Overloads[Action](lambda: Process.Start(e.Uri.AbsoluteUri))

    #タイトルだけ拾ってテキストブロックを構成する
    def _getTextBlock(rss):

        result = TextBlock()
        for item in rss:
            run = Run(item.Title)
            hlink = Hyperlink(run)

            hlink.NavigateUri = Uri(item.Url)
            hlink.Foreground = harriet.Setting.ChatWindowColor.Foreground
            hlink.RequestNavigate += _OnRequestNavigate