Monday, May 21, 2012

rails - how to make a GET request to action with parameters

I'm hoping this problem is a fairly simple one as I am relatively new to rails development.
I am trying to make a get request from a controller with a specified action and pass required parameters. This is the relevant code in the helper class:



module ChartsHelper
def chart_tag (action, height, params = {})
params[:format] ||= :json
path = charts_path(action, params)
content_tag(:div, :'data-chart' => path, :style => "height: #{height}px;") do
image_tag('loading.gif', :size => '32x32', :class => 'spinner')
end
end
end


and the corresponding action in the ChartsController:



class ChartsController < ApplicationController

def week_events_bar_chart
days = (params[:days] || 30).to_i
render :json => {
:type => 'AreaChart',
:cols => [['string', 'Date'], ['number', 'subscriptions']],
:rows => (1..days).to_a.inject([]) do |memo, i|
date = i.days.ago.to_date
t0, t1 = date.beginning_of_day, date.end_of_day
subscriptions = Kpsevent.all.count
memo << [date, subscriptions]
memo
end.reverse,
:options => {
:chartArea => { :width => '90%', :height => '75%' },
:hAxis => { :showTextEvery => 30 },
:legend => 'bottom',
}
}
end
end


The routes file has the following:



resource :charts do
get 'week_events_bar_chart'
end


However I get the following output when trying to perform this request:



 Started GET "/charts.week_events_bar_chart?days=14" for 127.0.0.1 at Tue May 22 00:31:48 +1200 2012
Processing by ChartsController#index as
Parameters: {"days"=>"14"}


And the controller action is never called.
Is anyone able to help with this problem?



EDIT: rake routes output:



week_events_bar_chart_charts GET    /charts/week_events_bar_chart(.:format) {:controller=>"charts", :action=>"week_events_bar_chart"}
POST /charts(.:format) {:controller=>"charts", :action=>"create"}
new_charts GET /charts/new(.:format) {:controller=>"charts", :action=>"new"}
edit_charts GET /charts/edit(.:format) {:controller=>"charts", :action=>"edit"}
GET /charts(.:format) {:controller=>"charts", :action=>"show"}
PUT /charts(.:format) {:controller=>"charts", :action=>"update"}
DELETE /charts(.:format) {:controller=>"charts", :action=>"destroy"}




Open two jquery datepickers simultaneously

I have two input fields containing a class that triggers a datepicker to open. Both work fine independently, i.e when I click on one or the other but I want for both datepickers to open when either input field is clicked.



Here is the script part of the code



    $(document).ready(function() {

$( ".datefields" ).datepicker({ dateFormat: 'dd/mm/yy',numberOfMonths: 1, yearRange: "2012:2014", changeYear: true, changeMonth: true});


and this is the html



<div id="quoteformcollection">
<h1>Collection</h1>

<input type"text" class="startTbl locationfields" id="AutoLocStart" value="Please Type a Collection Location"onclick="clearVal(this);"/>
<input type="hidden" id="DepotStart" value=""/></td>

<input type="text" class="datefields" id="collectiondate" value="21/05/2012"/>
<input type"text" class="timefields" value="12:00" />
</div>

<div id="quoteformreturn">
<h1>Return</h1>

<input type"text" class="locationfields" value="Enter the city or location for return" />
<input type"text" id="returndate" class="datefields" value="21/05/2012" />
<input type"text" class="timefields" value="12:00" />
</div>


I have tried looking for an answer myself but am quite new to jquery and struggling a bit so any help would be much appreciated.



I would also like for whatever value is selected in the first datepicker, for the default date in the second to be incremented by x number of days, which again I am not sure of the best way to go about it.



Any advice would be hugely appreciated!





Edit all files in subdirectories with python

I am trying to recursively loop through a series of directories (about 3 levels deep). In each directory is a series of text files, I want to replace a line of text with the directory path if the line contains a certain string so for example.



/path/to/text/file/fName.txt


If a line in fName in fName.txt text contains the string 'String1' I want to replace this line with 'some text' + file where file is the last part of the path.



This seems like it should be easy in python but I can't seem to manage it.



Thanks.





Double and tripple button is shown (DOMNodeInserted)

I have a weird problem:



I am developing a chrome extension that adds a custom button beside the "like" button in facebook. Until now, with alot of help I found a way to run the script even when posts are added to the news feed (without a page refresh). But the problem is that in the timline/ ticker (live feed window in the right) the button duplicates itself over time.



My current script:



$(document).ready(function(){
$(".like_link,.cmnt_like_link").after(
'<span class="dot"> · </span>' +
'<button class="taheles_link stat_elem as_link" title="???? ???&acute;?" type="submit" name="taheles" onclick="apply_taheles()" data-ft="{&quot;tn&quot;:&quot;&gt;&quot;,&quot;type&quot;:22}">' +
'<span class="taheles_default_message">???&acute;?</span><span class="taheles_saving_message">?? ????</span>' +
'</button>'
);

$(".taheles_saving_message").hide();

$(document).bind('DOMNodeInserted', function(event) {
$(event.target).find(".like_link,.cmnt_like_link").after(
'<span class="dot"> · </span>' +
'<button class="taheles_link stat_elem as_link" title="???? ???&acute;?" type="submit" name="taheles" onclick="apply_taheles()" data-ft="{&quot;tn&quot;:&quot;&gt;&quot;,&quot;type&quot;:22}">' +
'<span class="taheles_default_message">???&acute;?</span><span class="taheles_saving_message">?? ????</span>' +
'</button>'
);
$(event.target).find(".taheles_saving_message").hide();
});
});


like_link is the button that is shown in posts/comments in the news feed/any other place. cmnt_like_link is the button that is shown in comments.



If I use #contentArea in the selectors, the custom button is not even added to the ticker. If I use document (current) it is shown in the ticker but duplicates itself. I am wondering what the problem is. I tried to look at the chrome developer panel but with no luck.





Typing generic interfaces

I'm trying to create two interface hierarchies, one for the business model objects and one for the ui. I know it's important to have loose coupling between the layers but part of the application will require drawing diagrams so I need the model objects to be readily available to their corresponding graphical representations and I have a common layer holding interfaces for the model objects..



Common class library code:

Public interface IBase {}
Public interface IBookObject : IBase {}
Public interface ITapeObject : IBase {}

Public class Book : IBookObject {}

Graphics layer code:

Public interface IModelObject<T>

{

T ModelObject { get; set; } // might be a book or tape , etc

}


Public class GraphicObject<T> : IModelObject<T>

{

Public T ModelObject { get; set; }

}


Code use:

IBookObject bk = new Book();

Var go = new GraphicObject<IBookObject>(); // will fail later

//var go = new GraphicObject<IBase>(); // will succeed later

go.ModelObject = bk;

If( go is IModelObject<IBase>) // can't use is IModelObject<IBookObject> as go might be GraphicObject<ITapeObject>

{
Debug.WriteLine("Success");
}


So if I want to test for IBase (and then access ModelObject), I have to make sure that the original object was created with IBase and not a derived interface, and this seems like a cause of bugs later. my questions are:



1) Am I doing something horrible?! :) I might be overlooking a better approach..



2) failing that, is there some way of using the new contravariance c# 4 techniques to make the is line test for any interface deriving from IBase? Alternatively I think it would work if IBook didn't inherit from IBase, but Book (and Tape) implemented both IBook and IBase separately.



3) failing that, is there any way to prevent construction of GraphicObject<IBookObject>() and GraphicObject<ITapeObject>()?



Thank you!





Is const_cast(iterator->second) safe?

I want to know if this code is safe and doesnt have any undefined behavior.



 QueueMap::const_iterator it = m_3playersQueue.find(s->m_GameCode);
if(it == m_3playersQueue.end())
{
std::deque<Session*> stack;
stack.push_back(s);

m_3playersQueue[s->m_GameCode] = stack;
return;
}

const_cast<std::deque<Session*>&>(it->second).push_back(s);

QueueMap is of type std::tr1::unordered_map< uint32, std::deque<Session*> >


Thanks





How to insert a block into a node or template in Drupal 7?

In Drupal 6, it was easy to insert a block into a template with the following code:



$block = module_invoke('views', 'block', 'view', 'block_name');
print $block['content'];


However, using the same instructions in Drupal 7 does not seem to work. I have looked around and cannot find the new method.



Does Drupal 7 have a routine that can allow for pro grammatically inserting a block into a template or node?