Tuesday, April 10, 2012

How save filename of uploaded file in model

I need save without full path to file also filename.
I doing so:


class Photo(models.Model):
     photo = models.ImageField(upload_to = settings.PATH_PHOTOS_SOURCE)
     user = models.ForeignKey(UserProfile, editable=False)
     item = models.ForeignKey(Item, default=0)
     filename = models.CharField(max_length=100, default='', editable=False)
 
     def save(self, *args, **kwargs):
         self.filename = os.path.basename(self.photo.url)
         super(Photo, self).save(*args, **kwargs)
 


It's work, but exist cases, when file with existing name already exist, and offcourse in disk write file example_1.jpg, example_2.jpg, but in filename saving incorrect filename example.jpg


I changed my save method so:


def save(self, *args, **kwargs):
     super(Photo, self).save(*args, **kwargs)        
     self.filename = os.path.basename(self.photo.url)
     super(Photo, self).save()
 


It's work, but i don't like this code, maybe is more elegant code.


I tried to do this with signals, but i had problem with save recursion.



Answer:

Instead of settings.PATH_PHOTOS_SOURCE, pass a function to upload_to.
def upload_path_handler(self, filename):
    return os.path.join(settings.PATH_PHOTOS_SOURCE,
                        os.path.basename(self.photo.url))
# in model
photo = models.ImageField(upload_to=upload_path_handler)
If you want to use model instance id for filename, ref Django admin file upload with current model id
You may need to consider possible value of photo.url to make sure its safe to directly use it as filename.

why the reference of temporary object is valid here?

#include <iostream>
#include <string>
using namespace std;
class test
{
public:
string a;
public:
test(string b){a=b;}
friend string operator+(test);
};
string operator+(string &c,test a)
{
c=c+a.a;
return c;
}
void main()
{
test d("the ");
test e("world!");
string s="Hello ";
s=s+d+e;
cout<<s<<endl;
}


the second last line s=s+d+e; after the fist overloaded operator + it returned a temporary object,and the second overloaded operator + unexpectedly worked!But the first parameter of operator+ function is a reference. why the reference of temporary object is valid here,or there is something i have missed?



P.S: It's compiled by VC++6.0 and here is the running result.enter image description here





Assigning a string of characters to a char array

I Want to know why the first statements works and why not second one in c++



char a[10]="iqbal";  // it works

a="iqbal"; // does not work




Where are the latest Internet Explorer Application Compatibility VPC Images?

Does anyone know where the latest Internet Explorer Application Compatibility VPC Images are?


These ones expired 1st October 2010


http://www.microsoft.com/downloads/en/details.aspx?FamilyId=21EABB90-958F-4B64-B5F1-73D0A413C8EF&displaylang=en


UPDATED : If you're reading Microsoft..


This is not the user experience developers want. If it would not be too much trouble could you make new VPC images available as soon as old ones expire. Thank you.



Answer 1:

Looks as though they have updated them
Windows XP Images These images were last updated on October 13, 2010, and expire on January 11, 2011.
  • IE6-on-XPSP3.exe contains a Windows XP SP3 with IE6 VHD file. Expires January 11, 2011
  • IE7-on-XPSP3.exe contains a Windows XP SP3 with IE7 VHD file. Expires January 11, 2011
  • IE8-on-XPSP3.exe contains a Windows XP SP3 with IE8 VHD file. Expires January 11, 2011

Answer 2:


It seems they have expired agian and as yet I can't find updated versions. The one I have was set to expire on 4th April and sure enough I can't event get thenm to run for an hour.
I'm really wishing that final 6% of my user base would upgrade from ie6!!!

Are there some existing impressive ExtJS examples online?

I'm trying to convince my boss to use EXTJS for our client side scripting, are there any eye poppers out there? I've already found some old examples but none are very impressive. The closest to impressive is that I've found is cubedrive. These are the kinds of examples I'm looking for.





ASP.NET - jQuery ajax calls queue instead of running concurrently?

I have to do some processing on a file loaded by the user. This process can take a long time based on the number of pages within the file. I am planning on using jQuery UIs progressbar and telling the user how many pages have been processed. However, my progress check does not return until the first ajax call is complete. Both calls complete properly are connecting to the corresponding web methods.



I researched this a little bit already, and I found this answer to another question which pretty much stated that if both calls use the Session they wont process concurrently. I only use the Session in one of the calls though.



What am I missing?



This is the initial call that starts the processing of the file. I set the UpdateProgressBar to run a second after the processing of the file starts.



setTimeout("UpdateProgressBar();", 1000);

$.ajax({
type: "POST",
async: true,
data: // my params go here
url: // path to web method
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
// Do stuff when file is finished processing
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
if (errorThrown != null)
alert(textStatus + " : " + errorThrown);
}
});


This is the UpdateProgressBar function:



function UpdateProgressBar() {
$.ajax({
type: "POST",
async: true,
data: // my params go here
url: // path to web method
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
var totalPages = parseInt($('[id$=lbl_PageCount]').text());
var pagesProcessed = result.d;
var percentProcessed = pagesProcessed / totalPages;

$('#div_ProgressBar').progressbar("value", percentProcessed);

if (pagesProcessed < totalPages)
setTimeout("UpdateProgressBar();", 800);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
if (errorThrown != null)
alert(textStatus + " : " + errorThrown);
}
});


Edit:



This is the WebMethod called by UpdateProgressBar. The other WebMethod does use Session, but as you can see this one does not. They both access a dll, however, I tried testing without using the dll for the update and it did not make a difference.



[WebMethod]
public static int CheckPDFProcessingProgress(// params go here)
{
int pagesProcessed = 1;

try
{
OrderService _orderService = new OrderService();
pagesProcessed = _orderService.GetMailingPDFPagesProcessedProgress(PersonID);
}
catch (Exception ex)
{
// log error
}

return pagesProcessed;
}




How to test Rspec in controller

In controller,


def admin_search
    @admins = User.find(:all,:joins=>[:roles],:conditions=>["name IN (?) and email like '#{params[:email]}%'",["content team","ops team"]]).paginate(:page => params[:page], :per_page => 10)
 end
 


please suggest me some code in rspec



Answer:


First of all, it's better to extract find(:all, ...) call to User model. Call it search, for instance.
class User < ActiveRecord::Base
  scope :search_by_email, lambda { |email|
    joins(:roles).where(["name IN (?) and email like '#{email}%'",["content team","ops team"]])
  }
end
Use it in the controller then:
def admin_search
   @admins = User.search_by_email(params[:email]).paginate(:page => params[:page], :per_page => 10)
end
Now, you can test the search_by_email method in isolation - check, that it returns result for "content team" and "ops team" only, correctly works with empty email string and so on.
I don't think you have to test paginate method, as it should be already tested in kaminari, will_paginate or whatever you use. But if you want to be sure, that it is being called, than you can use mock expectations (should_receive) in the controller specs.
EDIT: How the specs could look like
describe User do
  describe ".search_by_email" do
    let(:content_team) { Role.create! name: "content team" }
    let(:ops_team)     { Role.create! name: "ops team"     }
    let(:another_team) { Role.create! name: "another team" }

    it "should search in content team" do
      content_team_user = User.create! email: "joe.black@example.com", roles: [content_team]
      User.search_by_email("black").should == [content_team_user]
    end

    it "should search in ops team" do
      ops_team_user = User.create! email: "joe.black@example.com", roles: [ops_team]
      User.search_by_email("black").should == [ops_team_user]
    end

    it "should not search in other teams" do
      other_team_user = User.create! email: "joe.black@example.com", roles: [another_team]
      User.search_by_email("black").should == []
    end

    it "should not search by empty string" do
      content_team_user = User.create! email: "joe.black@example.com", roles: [content_team_user]
      User.search_by_email("").should == []
      User.search_by_email(nil).should == []
    end

    # more specs for search...
  end
end


describe UsersController do
  describe "admin search" do
    let(:admin_user) { double(:admin_user).as_null_object }
    let(:search_string) { 'joe' }

    it "should search for admin users" do
      User.should_receive(:search_by_email).with(search_string).and_return([admin_user])
      get :admin_search, email: search_string
      assigns(:admins).should == [admin_user]
    end
  end
end