Translate

2013年12月10日 星期二

[QGIS][2.x] Example of iterating layers, attributes and features

layermap = QgsMapLayerRegistry.instance().mapLayers()
   
for (name,layer) in layermap.iteritems():
    if layer.type() != QgsVectorLayer.VectorLayer:
        continue
     
    if "SampleLayer" in layer.name():
        dP = layer.dataProvider()
     
        for attr in dP.fields():
            if (attr.name() == "SampleAttr"):
                SampleAttrId = dP.fieldNameIndex(attr.name())
                break
 
 
    layer.select(dP.attributeIndexes())
     
    FetSet = layer.getFeatures()
 
    for feat in FetSet:
        SampleAttrStr = str(feat[SampleAttrId])
        SampleAttrValue = float(str(feat[SampleAttrId]))

[VBA] Ceiling

https://github.com/walter426/VbaUtilities/blob/master/MathUtilities.bas

Public Function Ceiling(X)
    Ceiling = Int(X) - (X - Int(X) > 0)
End Function

2013年12月2日 星期一

[VBA] Generate a concatenated string of related records (SQL Query Use)

Reference: http://allenbrowne.com/func-concat.html

https://github.com/walter426/VbaUtilities/
Useful user-defined SQL Query function to do record concatenation.

Example:
SELECT [2G_Bcch].CELL, First(ConcatRelated("bcchno"," 2G_HO_Bcch","CELL = """ & [2G_Bcch].[CELL] & """","",";")) AS BcchSet
FROM 2G_Bcch
GROUP BY [2G_Bcch].CELL;


Below is the version added a little bit of modification to suit to my vba utilities,

Code:
Public Function ConcatRelated(strField As String, _
    strTable As String, _
    Optional strWhere As String, _
    Optional strOrderBy As String, _
    Optional strSeparator = ", ") As Variant
On Error GoTo Err_ConcatRelated
    'Purpose:   Generate a concatenated string of related records.
    'Return:    String variant, or Null if no matches.
    'Arguments: strField = name of field to get results from and concatenate.
    '           strTable = name of a table or query.
    '           strWhere = WHERE clause to choose the right values.
    '           strOrderBy = ORDER BY clause, for sorting the values.
    '           strSeparator = characters to use between the concatenated values.
    'Notes:     1. Use square brackets around field/table names with spaces or odd characters.
    '           2. strField can be a Multi-valued field (A2007 and later), but strOrderBy cannot.
    '           3. Nulls are omitted, zero-length strings (ZLSs) are returned as ZLSs.
    '           4. Returning more than 255 characters to a recordset triggers this Access bug:
    '               http://allenbrowne.com/bug-16.html
    Dim rs As DAO.Recordset         'Related records
    Dim rsMV As DAO.Recordset       'Multi-valued field recordset
    Dim strSql As String            'SQL statement
    Dim strOut As String            'Output string to concatenate to.
    Dim lngLen As Long              'Length of string.
    Dim bIsMultiValue As Boolean    'Flag if strField is a multi-valued field.
    
    'Initialize to Null
    ConcatRelated = Null
    
    'Build SQL string, and get the records.
    strSql = "SELECT " & strField & " FROM " & strTable
    If strWhere <> vbNullString Then
        strSql = strSql & " WHERE " & strWhere
    End If
    If strOrderBy <> vbNullString Then
        strSql = strSql & " ORDER BY " & strOrderBy
    End If
    Set rs = DBEngine(0)(0).OpenRecordset(strSql, dbOpenDynaset)
    'Determine if the requested field is multi-valued (Type is above 100.)
    bIsMultiValue = (rs(0).Type > 100)
    
    'Loop through the matching records
    Do While Not rs.EOF
        If bIsMultiValue Then
            'For multi-valued field, loop through the values
            Set rsMV = rs(0).Value
            Do While Not rsMV.EOF
                If Not IsNull(rsMV(0)) Then
                    strOut = strOut & rsMV(0) & strSeparator
                End If
                rsMV.MoveNext
            Loop
            Set rsMV = Nothing
        ElseIf Not IsNull(rs(0)) Then
            strOut = strOut & rs(0) & strSeparator
        End If
        rs.MoveNext
    Loop
    rs.Close
    
    'Return the string without the trailing separator.
    lngLen = Len(strOut) - Len(strSeparator)
    If lngLen > 0 Then
        ConcatRelated = Left(strOut, lngLen)
    End If

Exit_ConcatRelated:
    'Clean up
    Set rsMV = Nothing
    Set rs = Nothing
    Exit Function

Err_ConcatRelated:
    Call ShowMsgBox("Error " & Err.Number & ": " & Err.Description, vbExclamation, "ConcatRelated()")
    Resume Exit_ConcatRelated
    
End Function

2013年11月16日 星期六

[PyQt] Create Widget Grid(2D-array)

https://github.com/walter426/PyQtUtilities/

There are many GUI which require to display a group of widget(e.g. button, checkbox...) in a grid format.

Below is  an user-defined PyQt object to handle this kind of requirement,

Example:

self.WidgetList_QWG = QWidgetGrid('QCheckBox', '', Tbl_WidgetArgu_set, GridDirection = 0, MaxRowCnt = 15)
self.WidgetListt_scrollArea.setWidget(self.WidgetList_QWG)

Code:

from PyQt4.QtCore import *
from PyQt4.QtGui import *

import math


class QWidgetGrid(QWidget):
    def __init__(self, WidgetType, WidgetTypeName, WidgetArguSet, GridDirection = 0, MaxRowCnt = 0, MaxColCnt = 0):
        QWidget.__init__(self)
        
        if GridDirection > 1:
            return
        
        if MaxRowCnt == 0 and MaxColCnt == 0:
            return
            
        TblCnt = len(WidgetArguSet)
        
        if TblCnt <= 0:
            return
        
        
        if MaxRowCnt > 0 and MaxColCnt == 0:
            MaxColCnt = int(math.ceil(float(TblCnt)/float(MaxRowCnt)))
            
        elif MaxColCnt > 0 and MaxRowCnt == 0:
            MaxRowCnt = int(math.ceil(float(TblCnt)/float(MaxColCnt)))
                
        self.QGL = QGridLayout()
        

        tbl_idx = 0
        
        #From Top to Bottom, than Left to Right
        if GridDirection == 0:
            ColCnt = int(math.ceil(float(TblCnt)/float(MaxRowCnt)))
            
            for col_idx in range(0, ColCnt):
                RowCnt = MaxRowCnt

                if col_idx >= ColCnt - 1 and (TblCnt % MaxRowCnt) > 0:
                    RowCnt = TblCnt % MaxRowCnt
                
                for row_idx in range(0, RowCnt):
                    str_Widget_curr =  'self.' + WidgetTypeName + '_' + str(tbl_idx)
                    str_CreateWidget = str_Widget_curr + ' = ' + WidgetType + '('
                    
                    for k in range(0, len(WidgetArguSet[tbl_idx])):
                        str_CreateWidget += WidgetArguSet[tbl_idx][k] + ', '
                    
                    
                    str_CreateWidget = str_CreateWidget.rstrip(',') + ')'
                    exec(str_CreateWidget)     
                    exec('self.QGL.addWidget(' + str_Widget_curr + ', ' + str(row_idx) + ', ' + str(col_idx) + ')')
                    
                    tbl_idx += 1
        
        
        #From Left to Right, Top to Bottom
        elif GridDirection == 1:
            RowCnt = int(math.ceil(float(TblCnt)/float(MaxColCnt)))
            
            for row_idx in range(0, RowCnt):
                ColCnt = MaxColCnt

                if row_idx >= RowCnt - 1 and (TblCnt % MaxColCnt) > 0:
                    ColCnt = TblCnt % MaxColCnt
                
                for col_idx in range(0, ColCnt):
                    str_Widget_curr =  'self.' + WidgetTypeName + '_' + str(tbl_idx)
                    str_CreateWidget = str_Widget_curr + ' = ' + WidgetType + '('
                    
                    for k in range(0, len(WidgetArguSet[tbl_idx])):
                        str_CreateWidget += WidgetArguSet[tbl_idx][k] + ', '
                        
                        
                    str_CreateWidget = str_CreateWidget.rstrip(',') + ')'
                    exec(str_Widget_curr + ' = ' + WidgetType +'(' + str_CreateWidget + ')')     
                    exec('self.QGL.addWidget(' + str_Widget_curr + ', ' + str(row_idx) + ', ' + str(col_idx) + ')')
                    
                    tbl_idx += 1
        
        
        self.setLayout(self.QGL)
    
    def __del__(self):
        return

2013年10月22日 星期二

[VBA] Delete an Array Element

Public Sub DeleteArrayItem(arr As Variant, index As Long)
    Dim i As Long
    
    For i = index To UBound(arr) - 1
        arr(i) = arr(i + 1)
    Next
    
    ' VB will convert this to 0 or to an empty string.
    arr(UBound(arr)) = Empty
    ReDim Preserve arr(LBound(arr) To UBound(arr) - 1)
    
End Sub


2013年10月9日 星期三

[VBA] Concatenate multiple tables of identical structure

https://github.com/walter426/VbaUtilities/blob/master/SqlUtilities.bas

'Create table which is cancatenated from multiple tables of the same structure
Public Function CreateTbl_ConcatTbls(Tbl_src_Set As Variant, Tbl_des_name As String, Optional Type_Set As Variant = "") As String
    On Error GoTo Err_CreateTbl_ConcatTbls
   
    Dim FailedReason As String

    If UBound(Tbl_src_Set) < 0 Then
        FailedReason = "No table in the table set"
        GoTo Exit_CreateTbl_ConcatTbls
    End If

   
    Dim Tbl_src_name As Variant
   
    For Each Tbl_src_name In Tbl_src_Set
        If TableExist(Tbl_src_name & "") = False Then
            FailedReason = Tbl_src_name & " does not exist!"
            GoTo Exit_CreateTbl_ConcatTbls
        End If
   
    Next
   

    'Initialize Tbl_des
    DelTable (Tbl_des_name)
   
    Dim SQL_cmd As String
   
    Tbl_src_name = Tbl_src_Set(0)
   
    SQL_cmd = "SELECT " & Chr(34) & "null" & Chr(34) & " AS [Type], " & Tbl_src_name & ".* " & vbCrLf & _
                "INTO " & Tbl_des_name & " " & vbCrLf & _
                "FROM " & Tbl_src_name & " " & vbCrLf & _
                "WHERE 1 = 0 " & vbCrLf & _
                ";"
               
    RunSQL_CmdWithoutWarning (SQL_cmd)


    'Start Append
    Dim tbl_idx As Integer
    Dim SQL_Seq_Type As String
   
    For tbl_idx = 0 To UBound(Tbl_src_Set)
        Tbl_src_name = Tbl_src_Set(tbl_idx)
       
        If VarType(Type_Set) > vbArray And Type_Set(tbl_idx) = "" Then
            SQL_Seq_Type = ""
        Else
            SQL_Seq_Type = Chr(34) & Type_Set(tbl_idx) & Chr(34) & " AS [Type], "
        End If
       
        SQL_cmd = "INSERT INTO " & Tbl_des_name & " " & vbCrLf & _
                    "SELECT " & SQL_Seq_Type & "[" & Tbl_src_name & "].* " & vbCrLf & _
                    "FROM [" & Tbl_src_name & "] " & vbCrLf & _
                    ";"
       
        RunSQL_CmdWithoutWarning (SQL_cmd)
       
    Next
   
   
    If UBound(Type_Set) < 0 Then
        SQL_cmd = "ALTER TABLE [" & Tbl_des_name & "] " & vbCrLf & _
                    "DROP COLUMN [Type]" & vbCrLf & _
                    ";"

        RunSQL_CmdWithoutWarning (SQL_cmd)
       
    End If
   
   
Exit_CreateTbl_ConcatTbls:
    CreateTbl_ConcatTbls = FailedReason
    Exit Function

Err_CreateTbl_ConcatTbls:
    FailedReason = Err.Description
    Resume Exit_CreateTbl_ConcatTbls
   
End Function

2013年9月24日 星期二

[VBA] Logarithm of base 10

https://github.com/walter426/VbaUtilities/blob/master/MathUtilities.bas

As there is not built-in function for logarithm of base 10, so it is required to build it from the default natural  Logarithm function in VBA

Public Function Log10(X)
    Log10 = Log(X) / Log(10#)
End Function