Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-10 of 11 total  RSS 

Simple date picker for Merb 0.9.3

Bare-bones date picker for Merb. Drop it in global_helpers.rb. Must be called from inside a form_for block.

def date_control(col, attrs = {})

  attrs.merge!(:name => attrs[:name] || control_name(col))
  attrs.merge!(:id   => attrs[:id]   || control_id(col))

  date = @_obj.send(col) || Time.new
  
  # TODO: Handle :selected option
  #attrs.merge!(:selected => attrs[:selected] || control_value(col))
  
  errorify_field(attrs, col)

  month_attrs = attrs.merge(
    :selected   => date.month.to_s, 
    :name       => attrs[:name] + '[month]',
    :id         => attrs[:id] + '_month',
    :collection => [1,2,3,4,5,6,7,8,9,10,11,12]
  )
  
  day_attrs = attrs.merge(
    :selected   => date.day.to_s, 
    :name       => attrs[:name] + '[day]',
    :id         => attrs[:id] + '_day',
    :collection => (1..31).to_a,
    :label      => nil
  )
  
  year_attrs = attrs.merge(
    :selected   => date.year.to_s,
    :name       => attrs[:name] + '[year]',
    :id         => attrs[:id] + '_year',
    :collection => (1970..2020).to_a,
    :label      => nil
  )
  
  optional_label(month_attrs) {
     select_field(month_attrs) 
  } + select_field(day_attrs) + select_field(year_attrs)
end

Code to disable YUI calendar previous and next month links icons

WARNING: THIS CODE DOES NOT WORK WITH SOME EDGE CASES. Sometimes, particularly with overlapping end of months, this code will show an arrow even when all dates on the previous / next pane are out of bounds.

This solution does not require modifying the yui source and works on YUI version 2.5.0. It will disable the next and previous arrows based on the out of bounds dates you specify with mindate and maxdate when you configure the calendar. Requires YUI dom.

1) attach an onRender event when you configure the calendar and before you call render

oCal.renderEvent.subscribe(hideOOBArrows, oCal);


2) add the following function:

function hideOOBArrows(type, args, oCal) {
	var lastDateOnThisPane = oCal.toDate(oCal.cellDates[oCal.cellDates.length-1]);
	var firstDateOnNextPane = new Date(lastDateOnThisPane);
	firstDateOnNextPane.setDate(lastDateOnThisPane.getDate()+(oCal.isDateOOM(lastDateOnThisPane) ? -6 : 1));

	if (oCal.isDateOOB(firstDateOnNextPane)) {
		var rightArrow = YAHOO.util.Dom.getElementsByClassName(oCal.Style.CSS_NAV_RIGHT, "a", oCal.oDomContainer)[0];
		YAHOO.util.Dom.setStyle(rightArrow, "display", "none");
	}

	var firstDateOnThisPane = oCal.toDate(oCal.cellDates[0]);
	var lastDateOnPreviousPane = new Date(firstDateOnThisPane);
	lastDateOnPreviousPane.setDate(firstDateOnThisPane.getDate() + (oCal.isDateOOM(firstDateOnThisPane) ? 6 : -1));
	if (oCal.isDateOOB(lastDateOnPreviousPane)) {
		var leftArrow = YAHOO.util.Dom.getElementsByClassName(oCal.Style.CSS_NAV_LEFT, "a", oCal.oDomContainer)[0];
		YAHOO.util.Dom.setStyle(leftArrow, "display", "none");
	}
}

days in month

// returns number of days in specified month

def days_in_month(month)
  (Date.new(Time.now.year,12,31).to_date<<(12-month)).day
end

Pulling allday events from the public calendar of an exchange 2003 server vb.net webdav

// description of your code here
This is code that pulls all day events from an exchange 2003 server using webdav.
Dim Request As System.Net.HttpWebRequest
        Dim Response As System.Net.HttpWebResponse
        Dim MyCredentialCache As System.Net.CredentialCache
        Dim strPassword As String
        Dim strDomain As String
        Dim strUserName As String
        Dim strCalendarURI As String
        Dim strQuery As String
        Dim bytes() As Byte
        Dim RequestStream As System.IO.Stream
        Dim ResponseStream As System.IO.Stream
        Dim ResponseXmlDoc As System.Xml.XmlDocument
        Dim HrefNodes As System.Xml.XmlNodeList
        Dim SizeNodes As System.Xml.XmlNodeList
        Dim SubjectNodeList As System.Xml.XmlNodeList
        Dim LocationNodeList As System.Xml.XmlNodeList
        Dim StartTimeNodeList As System.Xml.XmlNodeList
        Dim EndTimeNodeList As System.Xml.XmlNodeList
        Dim BusyStatusNodeList As System.Xml.XmlNodeList
        Dim InstanceTypeNodeList As System.Xml.XmlNodeList
        Dim output As String = ""

        Try
            ' Initialize variables.
            strUserName = "user"
            strPassword = "password"
            strDomain = "domain"
            
            strCalendarURI = "http://mail-server/public/Office Calendar/"

            Dim ddate As DateTime = Today

            Dim sStartTime As String = String.Format("{0:yyyy/MM/dd}", ddate) & " 07:00:00' "
            Dim sEndTime As String = String.Format("{0:yyyy/MM/dd}", ddate.AddDays(1)) & " 07:00:00' "

            strQuery = "<?xml version=""1.0""?>" & _
                   "<g:searchrequest xmlns:g=""DAV:"">" & _
                   "<g:sql>SELECT ""urn:schemas:calendar:alldayevent"", ""urn:schemas:calendar:location"", ""urn:schemas:httpmail:subject"", " & _
                   """urn:schemas:calendar:dtstart"", ""urn:schemas:calendar:dtend"", " & _
                   """urn:schemas:calendar:busystatus"", ""urn:schemas:calendar:instancetype"" " & _
                   "FROM Scope('SHALLOW TRAVERSAL OF """ & strCalendarURI & """') " & _
                   "WHERE ""DAV:contentclass"" = 'urn:content-classes:appointment' " & _
                   "AND ""urn:schemas:calendar:alldayevent"" = TRUE " & _
                   "AND ""urn:schemas:calendar:dtstart"" &lt;= '" & sStartTime & _
                    "AND ""urn:schemas:calendar:dtend"" &gt;= '" & sEndTime & _
                    "ORDER BY ""urn:schemas:calendar:dtstart"" ASC" & _
                   "</g:sql></g:searchrequest>"



            MyCredentialCache = New System.Net.CredentialCache
            MyCredentialCache.Add(New System.Uri(strCalendarURI), _
                "NTLM", _
                New System.Net.NetworkCredential(strUserName, strPassword, strDomain) _
                )

            ' Create the PUT HttpWebRequest object.
            Request = CType(System.Net.WebRequest.Create(strCalendarURI), _
                            System.Net.HttpWebRequest)

            ' Add the network credentials to the request.
            Request.Credentials = MyCredentialCache

            ' Specify the SEARCH method.
            Request.Method = "SEARCH"

            ' Encode the body using UTF-8.
            bytes = System.Text.Encoding.UTF8.GetBytes(strQuery)

            ' Set the content header length.  This must be
            ' done before writing data to the request stream.
            Request.ContentLength = bytes.Length

            ' Get a reference to the request stream.
            RequestStream = Request.GetRequestStream()

            ' Write the message body to the request stream.
            RequestStream.Write(bytes, 0, bytes.Length)

            ' Close the Stream object to release the connection
            ' for further use.
            RequestStream.Close()

            ' Set the Content Type header.
            Request.ContentType = "text/xml"

            ' Set the Translate header.
            Request.Headers.Add("Translate", "F")

            ' Send the SEARCH method request and get the
            ' response from the server.
            Response = CType(Request.GetResponse(), System.Net.HttpWebResponse)

            ' Get the XML response stream.
            ResponseStream = Response.GetResponseStream()

            ' Create the XmlDocument object from the XML response stream.
            ResponseXmlDoc = New System.Xml.XmlDocument
            ResponseXmlDoc.Load(ResponseStream)
            
            ' Build a list of the DAV:href XML nodes, corresponding to the folders
            ' in the mailbox.  The DAV: namespace is typically assgigned the a:
            ' prefix in the XML response body.
            HrefNodes = ResponseXmlDoc.GetElementsByTagName("a:href")

            ' Build a list of the urn:schemas:httpmail:subject XML nodes,
            ' corresponding to the calendar item subjects returned in the search request.
            ' The urn:schemas:httpmail: namespace is typically
            ' assigned the e: prefix in the XML response body.
            SubjectNodeList = ResponseXmlDoc.GetElementsByTagName("e:subject")

            ' Build a list of the urn:schemas:calendar:location XML nodes,
            ' corresponding to the calendar item locations returned in the search request.
            ' The urn:schemas:calendar: namespace is typically
            ' assigned the d: prefix in the XML response body.
            LocationNodeList = ResponseXmlDoc.GetElementsByTagName("d:location")

            ' Build a list of the urn:schemas:calendar:dtstart XML nodes,
            ' corresponding to the calendar item locations returned in the search request.
            StartTimeNodeList = ResponseXmlDoc.GetElementsByTagName("d:dtstart")

            ' Build a list of the urn:schemas:calendar:dtend XML nodes,
            ' corresponding to the calendar item locations returned in the search request.
            EndTimeNodeList = ResponseXmlDoc.GetElementsByTagName("d:dtend")

            ' Build a list of the urn:schemas:calendar:busystatus XML nodes,
            ' corresponding to the calendar item locations returned in the search request.
            BusyStatusNodeList = ResponseXmlDoc.GetElementsByTagName("d:busystatus")

            ' Build a list of the urn:schemas:calendar:instancetype XML nodes,
            ' corresponding to the calendar item locations returned in the search request.
            InstanceTypeNodeList = ResponseXmlDoc.GetElementsByTagName("d:instancetype")

            ' Loop through the returned items (if any).
            If SubjectNodeList.Count > 0 Then

                Dim i As Integer
                For i = 0 To SubjectNodeList.Count - 1

                    ' Display the subject.

                    output = output & SubjectNodeList(i).InnerText & ControlChars.CrLf
                    Console.WriteLine(" " + SubjectNodeList(i).InnerText)

                    ' Display the location.
                    'Console.WriteLine("  Location:      " + LocationNodeList(i).InnerText)

                    ' Display the start time.
                    'Console.WriteLine("  Start time:    " + StartTimeNodeList(i).InnerText)

                    ' Display the end time.
                    'Console.WriteLine("  End time:      " + EndTimeNodeList(i).InnerText)

                    ' Display the busy status.
                    'Console.WriteLine("  Busy status:   " + BusyStatusNodeList(i).InnerText)

                    ' Display the instance type.
                    'If InstanceTypeNodeList(i).InnerText = "0" Then
                    '    Console.WriteLine("  Instance type: 0-Single appointment")
                    'ElseIf InstanceTypeNodeList(i).InnerText = "1" Then
                    '    Console.WriteLine("  Instance type: 1-Master recurring appointment")
                    'ElseIf InstanceTypeNodeList(i).InnerText = "2" Then
                    '    Console.WriteLine("  Instance type: 2-Single instance, recurring appointment")
                    'ElseIf InstanceTypeNodeList(i).InnerText = "3" Then
                    '    Console.WriteLine("  Instance type: 3-Exception to a recurring appointment")
                    'Else
                    '    Console.WriteLine("  Instance type: Unknown")
                    '    Console.WriteLine("")
                    'End If

                Next

            Else
                Console.WriteLine("No calendar items found ...")

            End If

            ' Clean up.
            ResponseStream.Close()
            Response.Close()

        Catch ex As Exception

            ' Catch any exceptions. Any error codes from the
            ' SEARCH method requests on the server will be caught
            ' here, also.
            Console.WriteLine(ex.Message)

        End Try

        SaveTextFile("C:\test.txt", output)
        emailCalendar()
        Me.Close()

A calendar control helper using Yahoo Calendar

// description of your code here

I've never found a very good calendar control that is easy to configure and update and I spendt what seemed like forever creating this one, so hopefully someone else finds it useful...

#code is in 3 parts:
#
#first this goes in the helper for the application or the controller that you want to use the calendar helper
#
#
#so, for example it would go in /app/helpers/application_helper.rb
#
#def calendar_field(object_name,field_name,cal_number,date=Date.today)
##################################
#Function to update the dates in a calendar control when a user makes a selection
#Takes:  1) object_name (class of the object that the date is for)
#        2) field_name (name of the field in the database)
#        3) cal_number (an integer marking the cardinality of this calendar, so if it's the first, use
#           1, if it's the third, use 3
#        4) default date (must be a Date object)
#Returns: an html/javascript string that produces a hidden field with the name object_name[field_name] and the ID object_name_field_name     that contains the date selected on the calendar
# if you want to have multiple instances of an object just make it object_name[0] and object_name[1], just like any other helper
##################################
  
  ret = '<input type="hidden"'
  ret +=      'name="' + object_name + '[' + field_name + ']"'
  ret +=      'id="' + object_name + '_' + field_name + '"'
  ret +=      'value="' + date.strftime("%Y-%m-%d") + '">'
  ret +=    '<select id="' + object_name + '_' + field_name + '[0]"'
  ret +=       ' onChange="updateDate($(\'' + object_name + '_' + field_name + '[2]' + '\').value + \',\' + $(\'' + object_name + '_' + field_name + '[0]' + '\').value + \',\' + $(\'' + object_name + '_' + field_name + '[1]' + '\').value,\'' + object_name + '_' + field_name + '\',cal' + cal_number + ');">'
  ret +=       '<option value=\'1\'>Jan</option>'
  ret +=       '<option value=\'2\'>Feb</option>'
  ret +=       '<option value=\'3\'>Mar</option>'
  ret +=       '<option value=\'4\'>Apr</option>'
  ret +=       '<option value=\'5\'>May</option>'
  ret +=       '<option value=\'6\'>Jun</option>'
  ret +=       '<option value=\'7\'>Jul</option>'
  ret +=       '<option value=\'8\'>Aug</option>'
  ret +=       '<option value=\'9\'>Sep</option>'
  ret +=       '<option value=\'10\'>Oct</option>'
  ret +=       '<option value=\'11\'>Now</option>'
  ret +=       '<option value=\'12\'>Dec</option>'
  ret +=     '</select>'
  ret +=   '<input type="text"'
  ret +=      'id=\'' + object_name + '_' + field_name + '[1]\''
  ret +=      'value="' + date.strftime("%d") + '"'
  ret +=      ' onChange="updateDate($(\'' + object_name + '_' + field_name + '[2]' + '\').value + \',\' + $(\'' + object_name + '_' + field_name + '[0]' + '\').value + \',\' + $(\'' + object_name + '_' + field_name + '[1]' + '\').value,\'' + object_name + '_' + field_name + '\',cal' + cal_number + ');">'
  ret +=   '<select id=\'' + object_name + '_' + field_name + '[2]\''
  ret +=       ' onChange="updateDate($(\'' + object_name + '_' + field_name + '[2]' + '\').value + \',\' + $(\'' + object_name + '_' + field_name + '[0]' + '\').value + \',\' + $(\'' + object_name + '_' + field_name + '[1]' + '\').value,\'' + object_name + '_' + field_name + '\',cal' + cal_number + ');">'
  ret +=       '<option value=\'2006\'>2006</option>'
  ret +=       '<option value=\'2007\'>2007</option>'
  ret +=       '<option value=\'2008\'>2008</option>'
  ret +=       '<option value=\'2009\'>2009</option>'
  ret +=   '</select>'
  ret +=    image_tag 'icons/Calendar24', :onClick => "Element.show('" + object_name + "_" + field_name + "_div')"
  ret +=   '<div id="' + object_name + '_' + field_name + '_div" style="display:none"></div>'
  ret +=   '<script type="text/javascript">'
  ret +=       'cal' + cal_number + ' = new YAHOO.widget.Calendar('
  ret +=       '"cal' + cal_number + '",'
  ret +=       '"' + object_name + '_' + field_name + '_div","' + date.strftime("%m/%Y") + '","' + format_time(date) + '");'
  ret +=       'cal' + cal_number + '.onSelect = function(e){updateDate(e,\'' + object_name + '_' + field_name + '\',cal' + cal_number + ',true);Element.hide(\'' + object_name + '_' + field_name + '_div\');};'
  ret +=       'cal' + cal_number + '.render();'
  ret +=       'updateDate(\'' + date.strftime("%Y,%m,%d") + '\',\'' + object_name + '_' + field_name + '\',cal' + cal_number + ');'
  ret +=   '</script>'

#next is the javascript file that actually updates the dates on the calendar control when you change them in the select box or vice versa.
#
#It should go in /public/javascripts/application.js
#
function updateDate(date, field_id, calendar_id, from_cal)
{
/********************************
Function to update the dates in a calendar control when a user makes a selection
Takes:  1) a date in 'YYYY,MM,DD' format, 
        2) the id of the hidden field that houses the final calendar date
        3) calendar object related to the date
        4) a boolean 'from_cal' - 
            *note - this is to set a break when the calendar control has set the date.  If it is not set to
            true when a calendar control (graphic) sets the date, it will result in an infinite loop

Returns: none
*********************************/
    if (from_cal != true)
    {
        from_cal = false;
    }
    
    date += ''
    $(field_id).value = date.replace(RegExp(",","g"),"-");
    
    dateParts = $(field_id).value.split("-")
    $(field_id + '[2]').value = dateParts[0]
    $(field_id + '[0]').value = dateParts[1]
    $(field_id + '[1]').value = dateParts[2]
    
    if (from_cal != true)
    {
       calendar_id.select(dateParts[1] + '/' + dateParts[2] + '/' + dateParts[0])
       calendar_id.setMonth(dateParts[1])
       calendar_id.subtractMonths(1)
       calendar_id.setYear(dateParts[0])
       calendar_id.render();
    }
}

#Usage example:
#
#You need to download and import the yahoo calendar controls to get this to work
<%= javascript_include_tag 'yahoo/yahoo'%>
<%= javascript_include_tag 'dom/dom'%>
<%= javascript_include_tag 'event/event'%>
<%= javascript_include_tag 'calendar/calendar'%>

#Then simply add a field like so:

<div class="calendar">Season Start Date:<br>
    <%= calendar_field('season','start_date','1') %>
</div>

#Here is the stylesheet that I am using for it, most of this is from Yahoo with some slight modifications

styles.css

/********************
Styles for Calendar Control
********************/
#body #content div.calendar {font-size:.8em;}
#body #content div.calendar input {width:40px; margin:0px 5px; font-size:.8em;}
#body #content div.calendar select {width:auto; font-size:.8em;}
#body #content div.calendar img {vertical-align:middle;}

/*
Copyright (c) 2006, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
Version 0.11.3
*/

.yui-cal2upwrapper {*height:1%;} /* IE */
.yui-cal2upwrapper:after {content:'.';clear:both;display:block;visibility:hidden;height:0;} /* others */

.yui-calcontainer {
	float:left;
	padding:5px;
	background-color:#F7F9FB;
	border:1px solid #7B9EBD;
        position:relative;
}

.yui-calcontainer .title {
	font:100% sans-serif;
	color:#000;
	font-weight:bold;
	margin-bottom:5px;
	height:auto;
	position:relative;
}

.yui-calcontainer .title .close-icon {
	position:absolute;
	right:0;
	top:0;
	border:none;
}

.yui-calcontainer .cal2up {
	float:left;
}

.yui-calendar .calnavleft {
	position:absolute;
	background-repeat:no-repeat;
	cursor:pointer;
	top:2px;
	bottom:0;
	width:9px;
	height:12px;   
	left:2px;
}

.yui-calendar .calnavright {
	position:absolute;
	background-repeat:no-repeat;
	cursor:pointer;
	top:2px;
	bottom:0;
	width:9px;
	height:12px;  
	right:2px;
}

/* Calendar element styles */

.yui-calendar {
	font:50% sans-serif !important;
        width:auto !important;
	text-align:center;
	border-spacing:0;
	border-collapse:separate;
        position:absolute;
        background-color:#FFFFFF;
}

.yui-calendar td.calcell {
	padding:.05em !important;
	border:1px solid #E0E0E0;
	background-color:#FFF;
        text-align:center !important;
}

.yui-calendar td.calcell a {
	color:#003DB8;
	text-decoration:none;
}

.yui-calendar td.calcell.today {
	border:1px solid #000;
}

.yui-calendar td.calcell.oom {
	cursor:default;
	color:#999;
	background-color:#EEE;
	border:1px solid #E0E0E0;
}

.yui-calendar td.calcell.selected {
	color:#003DB8;
	background-color:#FFF19F;
	border:1px solid #FF9900;
}

.yui-calendar td.calcell.calcellhover {
	cursor:pointer;
	color:#FFF;
	background-color:#FF9900;
	border:1px solid #FF9900;
}

.yui-calendar td.calcell.calcellhover a {
	color:#FFF;
}

.yui-calendar td.calcell.restricted {
	text-decoration:line-through;
}

.yui-calendar td.calcell.previous {
	color:#CCC;
}

.yui-calendar td.calcell.highlight1 { background-color:#CCFF99; }
.yui-calendar td.calcell.highlight2 { background-color:#99CCFF; }
.yui-calendar td.calcell.highlight3 { background-color:#FFCCCC; }
.yui-calendar td.calcell.highlight4 { background-color:#CCFF99; }


.yui-calendar .calhead {
	border:1px solid #E0E0E0;
	vertical-align:middle;
	background-color:#FFF;
}

.yui-calendar .calheader {
	position:relative;
	width:100%;
	text-align:center;
}

.yui-calendar .calheader img {
	border:none;
}

.yui-calendar .calweekdaycell {
	color:#666;
	font-weight:normal;
}

.yui-calendar .calfoot {
	background-color:#EEE;
}

.yui-calendar .calrowhead, .yui-calendar .calrowfoot {
	color:#666;
	font-size:9px;
	font-style:italic;
	font-weight:normal;
	width:15px;
}

.yui-calendar .calrowhead {
	border-right-width:2px;
}

/*Specific changes for calendar running under fonts/reset */
.yui-calendar a:hover {background:inherit;}
p#clear {clear:left; padding-top:10px;}



One final thing, I use an image from KDE for the calendar image, you can replace it with whatever you want. The image is included in the helper file

Hope someone finds this useful

Calendario de tareas Repetitivas

Otro programa de calendario que muestra las tareas repetitivas semanalmente durante un tiempo determinado

#include <fstream>

using namespace std;

char nmeses[12][11]={ "Enero",
	 				"Febrero",
					"Marzo",
					"Abril",
					"Mayo",
					"Junio",
					"Julio",
					"Agosto",
					"Septiembre",
					"Octubre",
					"Noviembre",
					"Diciembre"};

char ndias[7][10]={ "Domingo",
	 				"Lunes",
	 				"Martes",
					 "Miercoles",
					 "Jueves",
					 "Viernes",
					 "Sabado",
					 };
					
int meses[12]={31,28,31,30,31,30,31,31,30,31,30,31};


int main(){
	int i,j,k,l;
	int cont=6;
	
	int clases[9][200][2];
	int contc[9]={0,0,0,0,0,0,0,0,0};
	int semana[9][4]={ {2,2,3,-1},
					   {2,2,4,-1},
					   {3,5,5,-1},
					   {3,5,5,-1},
					   {1,4,4,-1},
					   {4,4,5,-1},
					   {2,4,5,-1},
					   {1,1,3,3},
					   {1,1,3,3}};
	ofstream arc("clases.txt");
		
	for (i=0;i<12;i++){
		for (j=1;j<=meses[i];j++,cont++){			
			if (! ((i==0 && j>0 && j<24) || (i==2 && j>=21 && j<28))){
			for (k=0;k<9;k++){
				for (l=0;l<4 && semana[k][l]!=-1;l++){
					if (cont%7==semana[k][l]){
					   clases[k][contc[k]][0]=i;
					   clases[k][contc[k]][1]=j;
					   contc[k]++;	
		   			}
				}
			} 
			}
		}	
	}

	for (i=0;i<contc[4];i++){

			arc<<i+1<<",7A, "<<clases[4][i][1]<<"/"<<clases[4][i][0]+1<<"/2005"<<endl;
			arc<<i+1<<",7B, "<<clases[5][i][1]<<"/"<<clases[5][i][0]+1<<"/2005"<<endl;
			arc<<i+1<<",7C, "<<clases[6][i][1]<<"/"<<clases[6][i][0]+1<<"/2005"<<endl<<endl;									
	}
	arc.close();
	return 0;
}

Calendar Loops

this program is very usefull when you need to know the list of dates of a repetitive task in the week.

I create this program to fill the records of my teaches in a school.

#include <stdio.h>


int meses[12]={31,28,31,30,31,30,31,31,30,31,30,31};
int dias[365][3];
/*
0 Lunes
1 Martes
2 Miercoles
3 Jueves
4 Viernes
5 Sabado
6 Domingo
*/

int cursos[7][4]={{0,0,0,0},{2,2,0,0},{1,0,1,1},{0,1,0,0},{0,0,2,2},{0,0,0,0},{0,0,0,0}};

int main(){
    int i,j,k;
    dias[0][0]=5;
    for (i=1;i<365;i++){
        dias[i][0]=(dias[i-1][0]+1)%7;                       
    }    
    k=0;
    for (i=0;i<12;i++){
        for (j=1;j<=meses[i];j++){
            dias[k][1]=i;    
            dias[k][2]=j;
            k++;
        }
    }
    
    for (i=0;i<365;i++){
       // bool salto=false;
        for (j=0;j<4;j++){

            for (k=0;k<cursos[dias[i][0]][j];k++){
                printf("6-%c \t %i - %i \n",'A'+j,dias[i][2]+1,dias[i][1]+1);
//                salto=true;
            }               
        }    
       // if (salto)
       //    printf("\n");
    }
    
    return 0;
}

View Code for Calendar Helper

This is the view template for an action that has all the events in @events
it links to the event, too ( I used the trestle generator, and the calendar helper plugin )

<%=
calendar({:year => @year, :month => @month}) do |d|
  cell_text = "#{d.mday}<br />" 
  cell_attrs = {:class => 'day'}
  @events.each do |e|
    if e.starts_at.mday == d.mday
      cell_text << link_to( e.title, :action => 'show', :id => e ) << "<br />" 
      cell_attrs[:class] = 'specialDay'
    end
  end
  [cell_text, cell_attrs]
end
%>


Here is the controller action snippet if you need it. This could probably be improved by only finding the events in the certain month you are looking at.

  def show
    @event = Event.find(params[:id])
  end
  
  def calendar
    @year = @params[:year].to_i
    @month = @params[:month].to_i

    @events = Event.find(:all)
  end


Here is my migration for my events table.
class CreateEvents < ActiveRecord::Migration
  def self.up
    create_table :events do |t|
       t.column "title", :string
       t.column "description", :text
       t.column "starts_at", :datetime
       t.column "ends_at", :datetime
       t.column "recurring", :boolean
       t.column "created_by", :string
       t.column "updated_by", :string
       t.column "updated_on", :datetime
       t.column "created_on", :datetime
    end
  end

  def self.down
    drop_table :events
  end
end

Determining the Number of Days in a Month with Javascript

Essentially, writing some code to determine the number of days in a given month of a given year with javascript is not the worlds most difficult task. It is the type of exercise that one would expect to be given as a newbie developer during a lab or lecture. The solution normally involves determining if the month is February, an month with 30 days or a month with 31 days, then (if February) checking if the year is a leap year. All these tests add up, however, and add several lines of code to your .js file. They are also unnecessary!

Apparently, the javascript Date function allows you to overflow the day number parameter that you pass, creating a date in the next month. Deliberately overflowing the day parameter and checking how far the resulting date overlaps into the next month is a quick way to tell how many days there were in the queried month. Here is a function that does this:

function daysInMonth(iMonth, iYear)
{
	return 32 - new Date(iYear, iMonth, 32).getDate();
}


N.B.: iMonth is zero based, so 0 represents January, 1 represents February, 2 represents March and 11 represents December. iYear is not zero based, this is the actual calendar year number. (2006 is actually 2006)

Pray that the browser developers know the correct way to determine whether a year is a leap year! (It's more complicated than a simple mod 4 == 0) Here is a quote from Wikipedia's page on leap years: "The Gregorian calendar, the current standard calendar in most of the world, adds a 29th day to February in all years evenly divisible by 4, except for centennial years (those ending in '00'), which receive the extra day only if they are evenly divisible by 400. Thus 1600, 2000 and 2400 are leap years but 1700, 1800, 1900 and 2100 are not."

To test this function, February in the years 2100, 2005, 2004, 2003, 2001, 2000 and 1999 should be checked. All of these should return 28, except for 2004 and 2000.

<button onclick="alert(daysInMonth(1, 2100));">February 2100</button>
<button onclick="alert(daysInMonth(1, 2005));">February 2005</button>
<button onclick="alert(daysInMonth(1, 2004));">February 2004</button>
<button onclick="alert(daysInMonth(1, 2003));">February 2003</button>
<button onclick="alert(daysInMonth(1, 2001));">February 200