Related
I have the following code where i am tryin to use mod operator to list 5 items on the line and then move to next line, On the single line it should display 5 items and then in next line, it should display the remaining items, if the remaining items are more than 5, it should go to 3rd line then
i am trying this code: but it not doing anything
<cfset items = "1,2,3,4,5,6,7,8,9,0">
<cfif listLen(items) mod 5>
<cfoutput>
#items##Chr(10)##chr(13)#TEST
</cfoutput>
</cfif>
it is displaying all in one line
There are a couple of things wrong with your code.
You are not looping over the list to display each item.
Chr(10) and Chr(13) (linefeed and carriage return) do not display in HTML and your browser.
I modified your code like this:
<cfset counter = 0>
<cfset items = "1,2,3,4,5,6,7,8,9,0,a,b,c">
<cfloop index="thisItem" list="#items#">
<cfset counter = counter + 1>
<cfif counter mod 5>
<cfoutput>#thisItem#, </cfoutput>
<cfelse>
<cfoutput>#thisItem#<br></cfoutput>
</cfif>
</cfloop>
Try it here
and here is an example of that same logic using cfscript syntax:
<cfscript>
counter = 0;
items = "1,2,3,4,5,6,7,8,9,0,a,b,c";
for (counter = 1; counter lte listlen(items); counter++) {
if (counter mod 5) {
writeOutput('#listGetAt(items,counter)#, ');
} else {
writeOutput('#listGetAt(items,counter)#<br>');
}
}
</cfscript>
Try it here
The code I have given you here can be cleaned up a bit but hopefully it is easy to understand for you.
Here is another approach if you are on CF10+:
<cfscript>
// Items List
items_list = "1,2,3,4,5,6,7,8,9,0,a,b,c";
// Convert to array
items_array = items_list.listToArray( "," );
// Item Count
itemCount = arrayLen( items_array );
// Display
for ( i = 1; i <= itemCount; i += 5) {
writeOutput( items_array.slice( i, i + 5 - 1 > itemCount ? itemCount % 5 : 5 ).toList( "," ) & "<br>" );
}
</cfscript>
Here is the TryCF.
Here is another approach.
<cfset items = "1,2,3,4,5,6,7,8,9,0,a,b,c">
<cfoutput>
<cfloop from="1" to="#listLen(items)#" index="i">
#listGetAt(items,i)#
<cfif i mod 5 eq 0>
<br>
<cfelseif i neq listLen(items)>
,
</cfif>
</cfloop>
</cfoutput>
Results in
1 , 2 , 3 , 4 , 5
6 , 7 , 8 , 9 , 0
a , b , c
We are working with millisecond conversion of time duration which is saved in database (Format : mm:ss ).The duration value we can access through the command #bignews.Control_CountdownDuration#.
<div class="slideBox" data-duration="#bignews.Control_CountdownDuration#">
The current value(mm:ss) is not sufficient for proper working of data-duration.
Can anyone guide me to complete the task ?
A comination of createTimeSpan() and dateDiff() will do the job.
Input here goes into the variables minutes and seconds:
<cfset cmpBase = createTimeSpan(0, 0, 0, 0)>
<cfset cmpValue = createTimeSpan(0, 0, minutes, seconds)>
<cfset diffInSeconds = dateDiff("s", cmpBase, cmpValue)>
<cfset diffInMilliseconds = (diffInSeconds * 1000)>
Assuming your source value is stored as string like mm:ss, this would be:
<cfset minutes = getToken(bignews.Control_CountdownDuration, 1, ":")>
<cfset seconds = getToken(bignews.Control_CountdownDuration, 2, ":")>
<cfset cmpValue = createTimeSpan(0, 0, minutes, seconds)>
<cfset cmpBase = createTimeSpan(0, 0, 0, 0)>
<cfset diffInSeconds = dateDiff("s", cmpBase, cmpValue)>
<cfset diffInMilliseconds = (diffInSeconds * 1000)>
<div class="slideBox" data-duration="#diffInMilliseconds#">
(Validation left out for readability.)
On a side note: You should probably work with the total number of seconds (see variable diffInSeconds) since you don't have the milliseconds precision anyway.
This is my first post to SO, a resource that is incredibly valuable!
I am trying to determine if a value (state code) exists in a list of codes and if so, set a new variable that represents the division (ie. sales territory, no match = 15). The code below works, but I want to improve my skills and do this as efficiently as possible. So my question is there a "better" way to achieve the same result?
<cfset state = "LA">
<cfset division = 15>
<cfset position = 0>
<cfset aStates = ArrayNew(1)>
<cfset aStates[1] = "MA,ME,NH,RI,VT">
<cfset aStates[2] = "CT,DE,NJ,NY,DE">
<cfset aStates[3] = "DC,MD,VA,WV">
<cfset aStates[4] = "TN">
<cfset aStates[5] = "NC,SC">
<cfset aStates[6] = "GA">
<cfset aStates[7] = "FL">
<cfset aStates[8] = "AL,KY,LA,MS">
<cfset aStates[9] = "IL,WI">
<cfset aStates[10] = "CO,MN,ND,SD,WY">
<cfset aStates[11] = "IN,OH,MI">
<cfset aStates[12] = "ID,OR,UT,WA">
<cfset aStates[13] = "AZ,HI,NV">
<cfset aStates[14] = "CA">
<cfset position = 0>
<cfloop array="#aStates#" index="lStates">
<cfset position = position+1>
<cfif ListFindNoCase(lStates,variables.state) NEQ 0>
<cfset division = position>
</cfif>
</cfloop>
<cfdump var="#aStates#" label="states array">
<cfoutput>State: #state#</cfoutput>
<cfoutput>Division: #division#</cfoutput>
With the current structure, you are relying on string comparisons, so there is not too much room for improvement.
Unless there is a specific reason you must hard code the values, a more flexible approach is to store the information the database. Create tables to store the "states" and "divisions", and another table to store the relationships:
States
StateID | Code | Name
1 | ME | Maine
2 | GA | Georgia
3 | CA | California
4 | NH | New Hampshire
...
Divisions
DivisionID | Name
1 | Sales Territory
...
DivisionStates
DivisionID | StateID
1 | 1
1 | 4
6 | 2
14 | 3
...
Then use an OUTER JOIN to retrieve the selected state and division. Assuming #state# will always contain a valid entry, something along these lines (not tested):
SELECT s.Name AS StateName
, CASE WHEN d.Name IS NULL THEN 'No Match' ELSE d.Name END AS DivisionName
FROM States s
LEFT JOIN DivisionStates ds ON ds.StateID = s.StateID
LEFT JOIN Divisions d ON d.DivisionID = ds.DivisionID
WHERE s.Code = <cfqueryparam value="#state#" cfsqltype="cf_sql_varchar">
I do not know the source of the #state# variable, but I am guessing it may be passed via a form <select>. If it is currently hard coded, you could simplify things further by using querying the "states" table, and using it to populate the list. Also, consider using the ID as the list value, rather than the state "code".
I thought of an approach in this by placing the states into a Struct; with the state codes as keys.
<cfscript>
state = "LA";
division = 15;
states_divisions_map = {
MA: 1, ME: 1, NH: 1, RI: 1, VT: 1,
CT: 2, NJ: 2, NY: 2, DE: 2,
DC: 3, MD: 3, VA: 3, WV: 3,
TN: 4,
NC: 5, SC: 5,
GA: 6,
FL: 7,
AL: 8, KY: 8, LA: 8, MS: 8,
IL: 9, WI: 9,
CO: 10, MN: 10, ND: 10, SD: 10, WY: 10,
IN: 11, OH: 11, MI: 11,
ID: 12, OR: 12, UT: 12, WA: 12,
AZ: 13, HI: 13, NV: 13,
CA: 14
};
if(StructKeyExists (states_divisions_map, state) ){
division = states_divisions_map[state];
}
writeDump(var: states_divisions_map, label: "States");
writeOutput("State: #state#");
writeOutput("Division: #division#");
</cfscript>
This way you can quickly check for the state without all the loops.
Observation: In your original code, DE is present twice.
ListContains() is like ListFind(), but it searches for a list element that contains the the text you're looking for anywhere in it. (ListFind() looks for a list element that entirely matches the string. Generally ListFind() is the better tool but not in this case.
(CF does have an ArrayContains, but it doesn't work for this task, it merely tells you if the array contains an exactly matched element.)
Because you're searching for unique two-char state-codes, this is a perfect use of the function.
<cfset aStates = ArrayNew(1)>
<cfset aStates[1] = "MA,ME,NH,RI,VT">
<cfset aStates[2] = "CT,DE,NJ,NY,DE">
<cfset aStates[3] = "DC,MD,VA,WV">
<cfset aStates[4] = "TN">
<cfset aStates[5] = "NC,SC">
<cfset aStates[6] = "GA">
<cfset aStates[7] = "FL">
<cfset aStates[8] = "AL,KY,LA,MS">
<cfset aStates[9] = "IL,WI">
<cfset aStates[10] = "CO,MN,ND,SD,WY">
<cfset aStates[11] = "IN,OH,MI">
<cfset aStates[12] = "ID,OR,UT,WA">
<cfset aStates[13] = "AZ,HI,NV">
<cfset aStates[14] = "CA">
<cfset lstates = arraytolist(astates,"|")>
<cfset division = listcontainsnocase(lstates,"CO","|")>
<cfoutput>Division: #division#<br>
State: #state#</cfoutput>
We set the delimiter to | (pipe), but you can use anything, other than the default (comma), because you're using that for you're sub-delimiter.
For future reference, if you're using CF 9 (I believe) or after, you can use array shorthand for quickly building arrays.
<cfset aStates=["MA,ME,NH,RI,VT","CT,DE,NJ,NV,DE","DC,MD,VA,WV"]> ...
While it may seem merely like a stylistic difference, it saves a lot of time.
Structures can be created similarly.
<cfset MyDogIs = {Size = "medium", Color = "Black", HasPaws = ["FL","FR","BL","BR"]}>
(And you can nest implicit array and structs within another!)
Thank you all for your input. I am answering this question myself with the code I decided to use since it is based on piece supplied by multiple answers/comments. I hope this is the correct way to do this, if not please advise.
The divisions were not stored in the db as they are a set it and forget it mapping that has not changed in years and I thought I'd save a call to the DB. If they were subject to change I would have taken a table approach suggested by #leigh
Thanks to #matt-busche for the improved loop, ucase() and break recommendations, and #cfqueryparam for the short hand array suggestion.
Here's what I went with. The code is actually a function in a cfc that processes a form submission but I have pasted only the relevant part.
<cfset form.division = 15>
<cfset aDivisions = ["MA,ME,NH,RI,VT",
"CT,DE,NJ,NY,DE",
"DC,MD,VA,WV",
"TN",
"NC,SC",
"GA",
"FL",
"AL,KY,LA,MS",
"IL,WI",
"CO,MN,ND,SD,WY",
"IN,OH,MI",
"ID,OR,UT,WA",
"AZ,HI,NV",
"CA"]>
<cfloop from="1" to="#ArrayLen(aDivisions)#" index="i">
<cfif ListFind(aDivisions[i],Ucase(arguments.sForm.state)) NEQ 0>
<cfset form.division = i>
<cfbreak>
</cfif>
</cfloop>
The query below works and gets me the correct results.
<cfset month = URL.month>
<cfset year = URL.year>
<cfquery datasource="testing_1" name="allDepartments">
SELECT CAST(employeedept AS INT) as dept,
ROUND(AVG(case when rating1>0 THEN CAST(rating1 AS FLOAT) ELSE null END), 2) as q1,
ROUND(AVG(case when rating2>0 THEN CAST(rating2 AS FLOAT) ELSE null END), 2) as q2,
ROUND(AVG(case when rating3>0 THEN CAST(rating3 AS FLOAT) ELSE null END), 2) as q3,
ROUND(AVG(case when rating4>0 THEN CAST(rating4 AS FLOAT) ELSE null END), 2) as q4,
ROUND(AVG(case when rating5>0 THEN CAST(rating5 AS FLOAT) ELSE null END), 2) as q5
FROM CSEReduxResponses
WHERE execoffice_date BETWEEN DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-1, 0)
AND DATEADD(MONTH, DATEDIFF(MONTH, -1, GETDATE())-1, -1)
AND execoffice_status = 1
group by employeedept
order by employeedept
</cfquery>
I want to get the execoffice_date to give me the data for a month ago, which is why I'm
using GETDATE. But if the url changes month=5&year=2014 to month=3&year=2014 it will give me the
same results in the query the same time.
What I would like to get the query to get the data depending on the url month and year.
How would I accomplish this?
If you are given url.year and url.month, this will get you the current month.
StartDate = CreateDate(url.year, url.month, 1);
EndDate = DateAdd("m", 1, StartDate); // you really do want the 1st of next month
Use them like this:
and execoffice_date >= <cfqueryparam cfsqltype="cf_sql_date" value="#StartDate#">
and execoffice_date < <cfqueryparam cfsqltype="cf_sql_date" value="#EndDate#">
For previous months, use date add on those variables.
I want to change the DayOfWeek() function so that I can get dates according to my own desired first day of the week. So what I am doing in this code is that I am setting a startDate, endDate and selectDays that I want to check. Here is my code:
<cfscript>
function Mydayofweek(date, day_1)
{
return (((DayOfWeek(date) + (7 -day_1)) MOD 7) +1);
}
</cfscript>
<cfset startDate = '07/01/2013'>
<cfset endDate = '07/25/2013'>
<Cfset mydates = ''>
<cfset selectDays = '2,6'>
<cfset MyWeekFirstDay = 6> <!---I selected Friday = 6 --->
<cfset new = ''>
<cfoutput>
<cfloop list="#selectDays#" delimiters="," index="d">
<cfset new &= '#Mydayofweek(d, MyWeekFirstDay)#,' >
</cfloop>
<cfif new NEQ ''>
<cfset ScheduleDate = left(new, (len(new)-1) )>
</cfif>
<cfdump var="#ScheduleDate#"><br />
</cfoutput>
<cfset AppendToMyDates = false>
<cfloop from="#startDate#" to="#endDate#" index="day">
<cfif AppendToMyDates is false and DayOfWeek(day) is ListFirst(selectDays)>
<cfset AppendToMyDates = true>
</cfif>
<cfif listfind(ScheduleDate, DayOfWeek(day), ',') NEQ 0 and AppendToMyDates is true>
<cfset mydates &= "#dateformat(day, 'mmm, dd, yyyy dddd')#,<br />">
</cfif>
</cfloop><cfoutput>#mydates#</cfoutput>
This is written in ColdFusion. That code generates this output:
4,1
Jul, 03, 2013 Wednesday,
Jul, 07, 2013 Sunday,
Jul, 10, 2013 Wednesday,
Jul, 14, 2013 Sunday,
Jul, 17, 2013 Wednesday,
Jul, 21, 2013 Sunday,
Jul, 24, 2013 Wednesday,
The Output Should be like this because i select Friday = 1 to Thursday = 7 so the above days selectDays = '2,6' should now point to selectDays = '7,4' with respect to my first days 2,6
7,4
Jul, 06, 2013 Saturday,
Jul, 10, 2013 Wednesday,
Jul, 13, 2013 Saturday,
Jul, 17, 2013 Wednesday,
Jul, 20, 2013 Saturday,
Jul, 24, 2013 Wednesday,
I have set my selectDays = '2,6' it means I want to get dates of Saturday and Wednesday because I have set 6 as my week first day and it start from Friday (by default it was sunday). My days start from Sunday Sunday = 1 , Monday = 2 , Tuesday = 3 , Wednesday = 4 , Thursday = 5 , Friday = 6 , Saturday = 7 and now I changed my date start from Friday = 1 , Saturday = 2 ,Sunday = 3 , Monday = 4 , Tuesday = 5 , Wednesday = 6 , Thursday = 7 in script function. Actually I think there is error in my script function that i don't understand. Please help me out to find the problem and it's solution thanks
UPDATED
You just need to call your script into your loop. No need to make any function just change the code like this one.
Copy this code hope this will solve your problem.
<cfscript>
function Mydayofweek(date, day_1)
{
return (((DayOfWeek(date) + (7 -day_1)) MOD 7) +1);
}
</cfscript>
<cfset startDate = '07/01/2013'>
<cfset endDate = '07/25/2013'>
<Cfset mydates = ''>
<cfset selectDays = '2,6'>
<cfset MyWeekFirstDay = 6><!---I selected Friday = 6 --->
<cfloop from="#startDate#" to="#endDate#" index="day">
<cfif listfind(selectDays, Mydayofweek(day,MyWeekFirstDay), ',') NEQ 0 >
<cfset mydates &= "#dateformat(day, 'mmm, dd, yyyy dddd')#,<br />">
</cfif>
</cfloop>
<cfoutput>#mydates#</cfoutput>
With the new information that selectDays might not always be the same, I'd do something like this:
<cfset AppendToMyDates = false>
<cfloop from="#startDate#" to="#endDate#" index="day">
<cfif AppendToMyDates is false and DayOfWeek(day) is ListFirst(SelectDays)>
<cfset AppendToMyDates = true>
</cfif>
<cfif listfind(selectDays, DayOfWeek(day), ',') NEQ 0 and AppendToMyDates is true>
<cfset mydates &= "#dateformat(day, 'mmm, dd, yyyy dddd')#,<br />">
</cfif>
</cfloop>
Edit starts here
If you want the start of the week to be a variable, you want to write your own version of DayOfWeek() with a different name. The structure would be something like this:
<cffunction name="DayOfWeekModified returntype="numeric">
<cfargument name="WeekStartsOn" type="numeric" required="yes">
<cfscript>
var DayNumber = 0;
code to generate it based on arguments.WeekStartsOn
return DayNumber;
<cfscript>
<cffunction>
You then call this function instead of DayOfWeek() in your loop.
The issue you are having is with your cfif condition. You are looping over the dates and then checking if the given date is a Wednesday or Friday and the results you are getting are correct. Since you want to start with a Friday (ignoring the first Wednesday) you need to add that to your code. This may work for you:
<cfset startDate = '06/11/2013'>
<cfset endDate = '06/25/2013'>
<cfset mydates = ''>
<cfset selectDays = '6,4'>
<cfloop from="#startDate#" to="#endDate#" index="day">
<cfif listfind(selectDays, DayOfWeek(day), ',') NEQ 0>
<cfif mydates NEQ "" OR DayOfWeek(day) EQ "6">
<cfset mydates &= "#dateformat(day, 'mmm, dd, yyyy dddd')#,<br />">
</cfif>
</cfif>
</cfloop>
<cfoutput>#mydates#</cfoutput>
I added an additional cfif condition around the setting of mydates. This code mydates NEQ "" is checking to see if mydates is not empty, meaning we have already satisified the next condition. If mydates is empty then also check to see if the given date is a Friday with DayOfWeek(day) EQ "6". This should guarantee that the first date entered in mydates is a Friday.
Not sure how I feel about this code but it seemed to work for me with your example.