PostId
int64
4
11.8M
PostCreationDate
stringlengths
19
19
OwnerUserId
int64
1
1.57M
OwnerCreationDate
stringlengths
10
19
ReputationAtPostCreation
int64
-55
461k
OwnerUndeletedAnswerCountAtPostTime
int64
0
21.5k
Title
stringlengths
3
250
BodyMarkdown
stringlengths
5
30k
Tag1
stringlengths
1
25
Tag2
stringlengths
1
25
Tag3
stringlengths
1
25
Tag4
stringlengths
1
25
Tag5
stringlengths
1
25
PostClosedDate
stringlengths
19
19
OpenStatus
stringclasses
5 values
unified_texts
stringlengths
32
30.1k
OpenStatus_id
int64
0
4
11,567,597
07/19/2012 19:03:57
1,536,345
07/18/2012 23:14:29
1
0
what intent or activity is used to communicate from android device to hyerterminal
im making a simple chat app and im trying to test it, and I need to make that when i pres the button "res1" sends a message and when i pres the button "res2" to hyperterminal and display the answer text in hyperterminal. what intent activity or anything should i use to send the message trought usb to hyperterminal? heres the code , ive done anything for the communication. sorry for the lack of descripton or whatev im a complete noob. here is my activity code /** Called when the activity is first created. */ TextView conv; Button res1; Button res2; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.cybernavlayout1); conv = (TextView)findViewById(R.id.TxtConversa); res1 = (Button)findViewById(R.id.BtnRespuesta1); res2 = (Button)findViewById(R.id.BtnRespuesta2); res1.setOnClickListener(this); res2.setOnClickListener(this); conv.setMovementMethod(new ScrollingMovementMethod()); } @Override public boolean onCreateOptionsMenu(Menu menu) { // TODO Auto-generated method stub MenuInflater convswitch = getMenuInflater(); convswitch.inflate(R.menu.cybernavlayout1, menu); return true; } public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()){ case R.id.BtnRespuesta1: conv.append("\r\nDe Acuerdo."); break; case R.id.BtnRespuesta2: conv.append("\r\nNo estoy disponible."); break; } } }
hyperterminal
null
null
null
null
null
open
what intent or activity is used to communicate from android device to hyerterminal === im making a simple chat app and im trying to test it, and I need to make that when i pres the button "res1" sends a message and when i pres the button "res2" to hyperterminal and display the answer text in hyperterminal. what intent activity or anything should i use to send the message trought usb to hyperterminal? heres the code , ive done anything for the communication. sorry for the lack of descripton or whatev im a complete noob. here is my activity code /** Called when the activity is first created. */ TextView conv; Button res1; Button res2; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.cybernavlayout1); conv = (TextView)findViewById(R.id.TxtConversa); res1 = (Button)findViewById(R.id.BtnRespuesta1); res2 = (Button)findViewById(R.id.BtnRespuesta2); res1.setOnClickListener(this); res2.setOnClickListener(this); conv.setMovementMethod(new ScrollingMovementMethod()); } @Override public boolean onCreateOptionsMenu(Menu menu) { // TODO Auto-generated method stub MenuInflater convswitch = getMenuInflater(); convswitch.inflate(R.menu.cybernavlayout1, menu); return true; } public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()){ case R.id.BtnRespuesta1: conv.append("\r\nDe Acuerdo."); break; case R.id.BtnRespuesta2: conv.append("\r\nNo estoy disponible."); break; } } }
0
11,567,599
07/19/2012 19:04:04
632,905
02/24/2011 18:42:51
223
7
Resource to bitmap conversion results in poor quality
never really noticed it before but when i change the image of an imageview using setImageBitmap..using a bitmap which is decoded from resources using BitmapFactory...the quality of image deteriorates...and i dont know why? i even played around with BitmapFactoryOptions like..options.inPreferredConfig, options.inJustDecodeBounds,options.inDither....but results were pretty much the same..a poor quality image.. on the other if i just use setImageResource..the image doesnt deteriorates and is in best quality possible... so basically these two codes 1. Bitmap b=BitmapFactory.decodeResource(getResources(), R.drawable.keypad,options); iv.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.keypad)) 2. iv.setImageResource(R.drawable.messages); results in different image quality.. can anybody explain why? and how to solve this quality issue using code 1. thnx...i really want to work on my accept rate..coz all the questions i have posted have neva been answered...so plz answer this
android
null
null
null
null
null
open
Resource to bitmap conversion results in poor quality === never really noticed it before but when i change the image of an imageview using setImageBitmap..using a bitmap which is decoded from resources using BitmapFactory...the quality of image deteriorates...and i dont know why? i even played around with BitmapFactoryOptions like..options.inPreferredConfig, options.inJustDecodeBounds,options.inDither....but results were pretty much the same..a poor quality image.. on the other if i just use setImageResource..the image doesnt deteriorates and is in best quality possible... so basically these two codes 1. Bitmap b=BitmapFactory.decodeResource(getResources(), R.drawable.keypad,options); iv.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.keypad)) 2. iv.setImageResource(R.drawable.messages); results in different image quality.. can anybody explain why? and how to solve this quality issue using code 1. thnx...i really want to work on my accept rate..coz all the questions i have posted have neva been answered...so plz answer this
0
11,567,610
07/19/2012 19:04:44
1,538,835
07/19/2012 18:46:08
1
0
How can I delete and rewrite rows in a datatable and write them back from a datarow[] array in a different order?
I tried saving the datatable rows to a datarow[] array then deleting the datatable rows and rewrite them to the datatable from the datarow[] array in a different order. But when I delete them from the datatable I can't access them from the datarow[] array. I don't know if I'm doing this correct or if im totally off base but I'm in desperate need of help. This is what I'm trying to do: I have a datatable with 8 rows. I want to be able to somehow loop thru the 8 rows and reorder them based on certain criterias. For example, my rows have an Invoice number, line number, and Part number as the key fields. Depending on the criteria, I may need rows 6,7,8 to be in the beginning as rows 1,2,3 and shift the rest down. If anyone has an Idea please reply....this is an urgent issue. thank you, Sam
c#
datarow
null
null
null
null
open
How can I delete and rewrite rows in a datatable and write them back from a datarow[] array in a different order? === I tried saving the datatable rows to a datarow[] array then deleting the datatable rows and rewrite them to the datatable from the datarow[] array in a different order. But when I delete them from the datatable I can't access them from the datarow[] array. I don't know if I'm doing this correct or if im totally off base but I'm in desperate need of help. This is what I'm trying to do: I have a datatable with 8 rows. I want to be able to somehow loop thru the 8 rows and reorder them based on certain criterias. For example, my rows have an Invoice number, line number, and Part number as the key fields. Depending on the criteria, I may need rows 6,7,8 to be in the beginning as rows 1,2,3 and shift the rest down. If anyone has an Idea please reply....this is an urgent issue. thank you, Sam
0
11,567,504
07/19/2012 18:57:46
505,103
11/11/2010 22:02:41
1,410
90
umbraco - SQL CE - There is a file sharing violation. A different process might be using the file
I've installed Umbraco 4.7.2 configured to use SQL CE into a GoDaddy 4GH shared hosting account. Initially, the site ran as expected. However, I quickly realized that no subsequent/concurrent connections are allowed and am receiving the following: `System.Data.SqlServerCe.SqlCeException: There is a file sharing violation. A different process might be using the file. [ ..\App_Data\Umbraco.sdf ]` I've done some research and I understand that SQL CE doesn't allow multiple connections, but I find it hard to believe that Umbraco would offer SQL CE as an option if it wasn't capable of allowing multiple visitors to navigate a site. I've tried modifying the connection string per other resources and am not having any luck. Here's my current connection string: `datalayer=SQLCE4Umbraco.SqlCEHelper,SQLCE4Umbraco;data source=|DataDirectory|\Umbraco.sdf;file mode=read write;persist security info=false;` I've tried different file modes such as `Read Only` and `Shared Read` with no luck. How do you overcome this issue? Is this somehow a problem with the hosting environment or a problem with the connection string?
sql-server-ce
connection-string
umbraco
null
null
null
open
umbraco - SQL CE - There is a file sharing violation. A different process might be using the file === I've installed Umbraco 4.7.2 configured to use SQL CE into a GoDaddy 4GH shared hosting account. Initially, the site ran as expected. However, I quickly realized that no subsequent/concurrent connections are allowed and am receiving the following: `System.Data.SqlServerCe.SqlCeException: There is a file sharing violation. A different process might be using the file. [ ..\App_Data\Umbraco.sdf ]` I've done some research and I understand that SQL CE doesn't allow multiple connections, but I find it hard to believe that Umbraco would offer SQL CE as an option if it wasn't capable of allowing multiple visitors to navigate a site. I've tried modifying the connection string per other resources and am not having any luck. Here's my current connection string: `datalayer=SQLCE4Umbraco.SqlCEHelper,SQLCE4Umbraco;data source=|DataDirectory|\Umbraco.sdf;file mode=read write;persist security info=false;` I've tried different file modes such as `Read Only` and `Shared Read` with no luck. How do you overcome this issue? Is this somehow a problem with the hosting environment or a problem with the connection string?
0
11,567,507
07/19/2012 18:57:48
892,015
08/12/2011 14:59:13
25
1
How do I add a System V filter using the cups API?
I need to programmatically add a printer to cups that has a System V filter installed. Right now I am using the following code to create the request to add the printer: pstRequest = ippNew(); pstRequest->request.op.operation_id = CUPS_ADD_PRINTER; pstRequest->request.any.request_id = 1; ippAddString(pstRequest, IPP_TAG_OPERATION, IPP_TAG_CHARSET, "attributes-charset", NULL, "us-ascii"); ippAddString(pstRequest, IPP_TAG_OPERATION, IPP_TAG_LANGUAGE, "attributes-natural-language", NULL, "en"); ippAddString(pstRequest, IPP_TAG_OPERATION, IPP_TAG_NAME, "requesting-user-name", NULL, cupsUser()); ippAddString(pstRequest, IPP_TAG_OPERATION, IPP_TAG_URI, "device-uri", NULL, szUri); ippAddString(pstRequest, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, szPrinterUri); ippAddInteger(pstRequest, IPP_TAG_PRINTER, IPP_TAG_ENUM, "printer-state", IPP_PRINTER_IDLE); ippAddBoolean(pstRequest, IPP_TAG_PRINTER, "printer-is-accepting-jobs", true); For the sake of conversaion: szUri = "serial:/dev/pts/12?baud=2400+bits=7+parity=none+flow=none"; szPrinterUri = "ipp://localhost/printers/myptr"; This appears to correctly add the printer to the cups system because I can then send print to it using the following command: lp -d myptr test.print My first thought was to just copy the file that I wanted to use as the filter into the `/etc/cups/interfaces` directory and call it `myptr`. I did this, gave it the correct user, group, and permissions, and it didn't seem to work. I even tried sticking a `sleep 60` at the front of the script and it never showed up in `ps`. I've tried adding the printer using `lpadmin` as follows and it works correctly: lpadmin -h localhost -p myptr2 -v "serial:/dev/pts/12?baud=2400+bits=7+parity=none+flow=none" -i /tmp/my.serial.filter I have to call `cupsaccept` and `cupsenable` afterward, but the printer works and it sends the print through my filter. `lpadmin` correctly copies the `my.serial.filter` file from `/tmp` into `/etc/cups/interfaces` and names it `myptr2`, just as I did in my program, and, for the life of me, I cannot find any reference to the filter in any of the cups configuration files that makes me think I'm missing a step. Nevertheless, the `myptr2` printer that I add with `lpadmin` works correctly and the `myptr` printer that I add using the API, while it *does* print, does *not* print through the filter. Among the various Google searches I have made, I have read through the [CUPS Implementation][1] and the [HTTP and IPP APIs Documentation][2], and the closest that I have come to was that, in the former, there is a comment for the [CUPS-Add-Modify-Printer Operation][3]that reads: > The CUPS-Add-Modify-Printer request can optionally be followed by a PPD file or System V interface script to be used for the printer. The "ppd-name" attribute overrides any file that is attached to the end of the request with a local CUPS PPD file. This led me to try using ippAddString(pstRequest, IPP_TAG_PRINTER, IPP_TAG_NAME, "ppd-name", NULL, szFilter); with szFilter set to both `"/tmp/my.serial.filter"` and `"/etc/cups/interfaces/myptr"` (in separate tests, of course), but to no avail. Can anyone tell me where I might be going wrong? [1]: http://www.cups.org/documentation.php/spec-ipp.html [2]: http://www.cups.org/documentation.php/api-httpipp.html [3]: http://www.cups.org/documentation.php/spec-ipp.html#CUPS_ADD_MODIFY_PRINTER
c
linux
printing
cups
null
null
open
How do I add a System V filter using the cups API? === I need to programmatically add a printer to cups that has a System V filter installed. Right now I am using the following code to create the request to add the printer: pstRequest = ippNew(); pstRequest->request.op.operation_id = CUPS_ADD_PRINTER; pstRequest->request.any.request_id = 1; ippAddString(pstRequest, IPP_TAG_OPERATION, IPP_TAG_CHARSET, "attributes-charset", NULL, "us-ascii"); ippAddString(pstRequest, IPP_TAG_OPERATION, IPP_TAG_LANGUAGE, "attributes-natural-language", NULL, "en"); ippAddString(pstRequest, IPP_TAG_OPERATION, IPP_TAG_NAME, "requesting-user-name", NULL, cupsUser()); ippAddString(pstRequest, IPP_TAG_OPERATION, IPP_TAG_URI, "device-uri", NULL, szUri); ippAddString(pstRequest, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, szPrinterUri); ippAddInteger(pstRequest, IPP_TAG_PRINTER, IPP_TAG_ENUM, "printer-state", IPP_PRINTER_IDLE); ippAddBoolean(pstRequest, IPP_TAG_PRINTER, "printer-is-accepting-jobs", true); For the sake of conversaion: szUri = "serial:/dev/pts/12?baud=2400+bits=7+parity=none+flow=none"; szPrinterUri = "ipp://localhost/printers/myptr"; This appears to correctly add the printer to the cups system because I can then send print to it using the following command: lp -d myptr test.print My first thought was to just copy the file that I wanted to use as the filter into the `/etc/cups/interfaces` directory and call it `myptr`. I did this, gave it the correct user, group, and permissions, and it didn't seem to work. I even tried sticking a `sleep 60` at the front of the script and it never showed up in `ps`. I've tried adding the printer using `lpadmin` as follows and it works correctly: lpadmin -h localhost -p myptr2 -v "serial:/dev/pts/12?baud=2400+bits=7+parity=none+flow=none" -i /tmp/my.serial.filter I have to call `cupsaccept` and `cupsenable` afterward, but the printer works and it sends the print through my filter. `lpadmin` correctly copies the `my.serial.filter` file from `/tmp` into `/etc/cups/interfaces` and names it `myptr2`, just as I did in my program, and, for the life of me, I cannot find any reference to the filter in any of the cups configuration files that makes me think I'm missing a step. Nevertheless, the `myptr2` printer that I add with `lpadmin` works correctly and the `myptr` printer that I add using the API, while it *does* print, does *not* print through the filter. Among the various Google searches I have made, I have read through the [CUPS Implementation][1] and the [HTTP and IPP APIs Documentation][2], and the closest that I have come to was that, in the former, there is a comment for the [CUPS-Add-Modify-Printer Operation][3]that reads: > The CUPS-Add-Modify-Printer request can optionally be followed by a PPD file or System V interface script to be used for the printer. The "ppd-name" attribute overrides any file that is attached to the end of the request with a local CUPS PPD file. This led me to try using ippAddString(pstRequest, IPP_TAG_PRINTER, IPP_TAG_NAME, "ppd-name", NULL, szFilter); with szFilter set to both `"/tmp/my.serial.filter"` and `"/etc/cups/interfaces/myptr"` (in separate tests, of course), but to no avail. Can anyone tell me where I might be going wrong? [1]: http://www.cups.org/documentation.php/spec-ipp.html [2]: http://www.cups.org/documentation.php/api-httpipp.html [3]: http://www.cups.org/documentation.php/spec-ipp.html#CUPS_ADD_MODIFY_PRINTER
0
11,567,613
07/19/2012 19:04:53
1,199,289
02/09/2012 09:38:19
602
15
Different random number generation between OS
Does anyone have any experience with situations where set.seed gives different results depending on operating system (OS). I remember coming across a similar situation in a class on R before where some people were generating different random sequences using rnorm despite setting the starting seed to the same value. Now, I'm giving a course myself and have not run into the same issue with rnorm; all my students get the same sequence regardless of OS. Interestingly, the same issue seems to exist with the mvrnorm function of the MASS package. Any insight would be greatly appreciated - Marc This example: require(MASS) set.seed(123) a <- rnorm(10, mean=10, sd=3) b <- rnorm(10, mean=5, sd=2) df <- data.frame(a,b) C <- cov(df) M <- mvrnorm(n=10, c(10,5), C) df C M Yields on my Windows 7 OS 64-bit version of R 2.14.1.: > df a b 1 8.318573 7.448164 2 9.309468 5.719628 3 14.676125 5.801543 4 10.211525 5.221365 5 10.387863 3.888318 6 15.145195 8.573826 7 11.382749 5.995701 8 6.204816 1.066766 9 7.939441 6.402712 10 8.663014 4.054417 > C a b a 8.187336 3.431373 b 3.431373 4.310385 > M a b [1,] 13.270535 6.158603 [2,] 10.375011 5.737871 [3,] 13.514105 5.476411 [4,] 12.681956 5.020646 [5,] 12.352333 4.927746 [6,] 15.177508 6.810387 [7,] 8.114377 2.925225 [8,] 9.529744 4.834451 [9,] 12.903550 7.232715 [10,] 6.251907 3.481789
r
random
null
null
null
null
open
Different random number generation between OS === Does anyone have any experience with situations where set.seed gives different results depending on operating system (OS). I remember coming across a similar situation in a class on R before where some people were generating different random sequences using rnorm despite setting the starting seed to the same value. Now, I'm giving a course myself and have not run into the same issue with rnorm; all my students get the same sequence regardless of OS. Interestingly, the same issue seems to exist with the mvrnorm function of the MASS package. Any insight would be greatly appreciated - Marc This example: require(MASS) set.seed(123) a <- rnorm(10, mean=10, sd=3) b <- rnorm(10, mean=5, sd=2) df <- data.frame(a,b) C <- cov(df) M <- mvrnorm(n=10, c(10,5), C) df C M Yields on my Windows 7 OS 64-bit version of R 2.14.1.: > df a b 1 8.318573 7.448164 2 9.309468 5.719628 3 14.676125 5.801543 4 10.211525 5.221365 5 10.387863 3.888318 6 15.145195 8.573826 7 11.382749 5.995701 8 6.204816 1.066766 9 7.939441 6.402712 10 8.663014 4.054417 > C a b a 8.187336 3.431373 b 3.431373 4.310385 > M a b [1,] 13.270535 6.158603 [2,] 10.375011 5.737871 [3,] 13.514105 5.476411 [4,] 12.681956 5.020646 [5,] 12.352333 4.927746 [6,] 15.177508 6.810387 [7,] 8.114377 2.925225 [8,] 9.529744 4.834451 [9,] 12.903550 7.232715 [10,] 6.251907 3.481789
0
11,567,614
07/19/2012 19:05:08
1,252,672
03/06/2012 16:03:26
79
0
Converting C# application to C++ enum
I've used Enum.GetValues and Enum.GetName in my C# project and would like to know if there were somekind of alternative in the standard c++ library ?
c#
c++
enums
null
null
null
open
Converting C# application to C++ enum === I've used Enum.GetValues and Enum.GetName in my C# project and would like to know if there were somekind of alternative in the standard c++ library ?
0
11,567,616
07/19/2012 19:05:27
1,062,467
11/23/2011 17:47:47
42
3
RSS Feed tracking
We are generating our RSS feed on the fly using Content Management System(Sitecore). What would be best possible way to get traffic statistics(i.e. Tracking) on RSS Feed. Solutions which i am looking into right now are: 1. Use a redirect page to your RSS feed and add your google analytics code on this redirect page. 2. Tracking Image. Source: http://ryanfarley.com/blog/archive/2004/06/10/773.aspx Not sure about this solution. 3. Log hits into database based on IP address, browser information etc.
c#
asp.net
rss
sitecore6
null
null
open
RSS Feed tracking === We are generating our RSS feed on the fly using Content Management System(Sitecore). What would be best possible way to get traffic statistics(i.e. Tracking) on RSS Feed. Solutions which i am looking into right now are: 1. Use a redirect page to your RSS feed and add your google analytics code on this redirect page. 2. Tracking Image. Source: http://ryanfarley.com/blog/archive/2004/06/10/773.aspx Not sure about this solution. 3. Log hits into database based on IP address, browser information etc.
0
11,693,072
07/27/2012 17:52:21
1,196,150
02/08/2012 02:20:44
525
0
Include has_many records in query with Rails
I have a has_many (through accounts) association between the model User and the model Player. I would like to know what is the best way to query all the users, and for each returned record get the associated players usernames attributes (in comma separated values). So, if for example, a User named 'John' is associated with 3 players with usernames 'john_black', 'john_white', 'john_yellow'. I would like the query to return not just the User attributes but also an attribute called, for example, player_username, that would have this value: `john_black, john_white, john_yellow`. I have tried the following Arel query in the User model: select(`users`.*).select("GROUP_CONCAT(`players`.`username` SEPARATOR ',') AS comma_username").joins(:user) .joins(:accounts => :player ) Which gives me the following SQL: SELECT `users`.*, GROUP_CONCAT(`players`.`username` SEPARATOR ',') AS comma_username FROM `users` INNER JOIN `accounts` ON `accounts`.`user_id` = `users`.`id` INNER JOIN `players` ON `players`.`id` = `accounts`.`player_id` If I execute this in MySQL console it works, but if I try to fetch from the model, I don't get the comma separated values. What am I missing?
ruby-on-rails-3
activerecord
group-concat
null
null
null
open
Include has_many records in query with Rails === I have a has_many (through accounts) association between the model User and the model Player. I would like to know what is the best way to query all the users, and for each returned record get the associated players usernames attributes (in comma separated values). So, if for example, a User named 'John' is associated with 3 players with usernames 'john_black', 'john_white', 'john_yellow'. I would like the query to return not just the User attributes but also an attribute called, for example, player_username, that would have this value: `john_black, john_white, john_yellow`. I have tried the following Arel query in the User model: select(`users`.*).select("GROUP_CONCAT(`players`.`username` SEPARATOR ',') AS comma_username").joins(:user) .joins(:accounts => :player ) Which gives me the following SQL: SELECT `users`.*, GROUP_CONCAT(`players`.`username` SEPARATOR ',') AS comma_username FROM `users` INNER JOIN `accounts` ON `accounts`.`user_id` = `users`.`id` INNER JOIN `players` ON `players`.`id` = `accounts`.`player_id` If I execute this in MySQL console it works, but if I try to fetch from the model, I don't get the comma separated values. What am I missing?
0
11,693,073
07/27/2012 17:52:22
516,864
11/23/2010 01:40:38
192
7
UIPageControl doesn't properly react to taps
In my TestApp, I created a class "Carousel" which should let me create a swipe menu with a UIPageControl in an easy way (by simply creating an instance of the class Carousel). - Carousel is a subclass of UIView - At init, it creates an UIView, containing UIScrollView, UIPageControl - I can add further UIViews to the scroll view I don't know if this is the proper way to do it, but my example worked quite well in my TestApp. Swiping between pages works perfectly and the display of the current page in the UIPageControl is correct. If there were not one single problem: The UIPageControl sometimes reacts to clicks/taps (I only tested in Simulator so far!), sometimes it doesn't. Let's say most of the time it doesn't. I couldn't find out yet when it does, for me it's just random... As you can see below, I added [pageControl addTarget:self action:@selector(pageChange:) forControlEvents:UIControlEventValueChanged]; to my code. I thought this would do the proper handling of taps? But unfortunately, pageChange doesn't get always called (so the value of the UIPageControl doesn't change every time I click). I would appreciate any input on this because I couldn't find any solution on this yet. This is what I have so far: **Carousel.h** #import <UIKit/UIKit.h> @interface Carousel : UIView { UIScrollView *scrollView; UIPageControl *pageControl; BOOL pageControlBeingUsed; } - (void)addView:(UIView *)view; - (void)setTotalPages:(NSUInteger)pages; - (void)setCurrentPage:(NSUInteger)current; - (void)createPageControlAt:(CGRect)cg; - (void)createScrollViewAt:(CGRect)cg; @end **Carousel.m** #import "Carousel.h" @implementation Carousel - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { // Create a scroll view scrollView = [[UIScrollView alloc] init]; [self addSubview:scrollView]; scrollView.delegate = (id) self; // Init Page Control pageControl = [[UIPageControl alloc] init]; [pageControl addTarget:self action:@selector(pageChange:) forControlEvents:UIControlEventValueChanged]; [self addSubview:pageControl]; } return self; } - (IBAction)pageChange:(id)sender { CGRect frame = scrollView.frame; frame.origin.x = frame.size.width * pageControl.currentPage; frame.origin.y = 0; [scrollView scrollRectToVisible:frame animated:TRUE]; NSLog(@"%i", pageControl.currentPage); } - (void)addView:(UIView *)view { [scrollView addSubview:view]; } - (void)createPageControlAt:(CGRect)cg { pageControl.frame = cg; } - (void)setTotalPages:(NSUInteger)pages { pageControl.numberOfPages = pages; } - (void)setCurrentPage:(NSUInteger)current { pageControl.currentPage = current; } - (void)createScrollViewAt:(CGRect)cg { [scrollView setPagingEnabled:TRUE]; scrollView.frame = cg; scrollView.contentSize = CGSizeMake(scrollView.frame.size.width*pageControl.numberOfPages, scrollView.frame.size.height); [scrollView setShowsHorizontalScrollIndicator:FALSE]; [scrollView setShowsVerticalScrollIndicator:FALSE]; } - (void)scrollViewDidScroll:(UIScrollView *)scrollView { float frac = scrollView.contentOffset.x / scrollView.frame.size.width; NSUInteger page = lround(frac); pageControl.currentPage = page; } @end
objective-c
ios
uiscrollview
swipe
uipagecontrol
null
open
UIPageControl doesn't properly react to taps === In my TestApp, I created a class "Carousel" which should let me create a swipe menu with a UIPageControl in an easy way (by simply creating an instance of the class Carousel). - Carousel is a subclass of UIView - At init, it creates an UIView, containing UIScrollView, UIPageControl - I can add further UIViews to the scroll view I don't know if this is the proper way to do it, but my example worked quite well in my TestApp. Swiping between pages works perfectly and the display of the current page in the UIPageControl is correct. If there were not one single problem: The UIPageControl sometimes reacts to clicks/taps (I only tested in Simulator so far!), sometimes it doesn't. Let's say most of the time it doesn't. I couldn't find out yet when it does, for me it's just random... As you can see below, I added [pageControl addTarget:self action:@selector(pageChange:) forControlEvents:UIControlEventValueChanged]; to my code. I thought this would do the proper handling of taps? But unfortunately, pageChange doesn't get always called (so the value of the UIPageControl doesn't change every time I click). I would appreciate any input on this because I couldn't find any solution on this yet. This is what I have so far: **Carousel.h** #import <UIKit/UIKit.h> @interface Carousel : UIView { UIScrollView *scrollView; UIPageControl *pageControl; BOOL pageControlBeingUsed; } - (void)addView:(UIView *)view; - (void)setTotalPages:(NSUInteger)pages; - (void)setCurrentPage:(NSUInteger)current; - (void)createPageControlAt:(CGRect)cg; - (void)createScrollViewAt:(CGRect)cg; @end **Carousel.m** #import "Carousel.h" @implementation Carousel - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { // Create a scroll view scrollView = [[UIScrollView alloc] init]; [self addSubview:scrollView]; scrollView.delegate = (id) self; // Init Page Control pageControl = [[UIPageControl alloc] init]; [pageControl addTarget:self action:@selector(pageChange:) forControlEvents:UIControlEventValueChanged]; [self addSubview:pageControl]; } return self; } - (IBAction)pageChange:(id)sender { CGRect frame = scrollView.frame; frame.origin.x = frame.size.width * pageControl.currentPage; frame.origin.y = 0; [scrollView scrollRectToVisible:frame animated:TRUE]; NSLog(@"%i", pageControl.currentPage); } - (void)addView:(UIView *)view { [scrollView addSubview:view]; } - (void)createPageControlAt:(CGRect)cg { pageControl.frame = cg; } - (void)setTotalPages:(NSUInteger)pages { pageControl.numberOfPages = pages; } - (void)setCurrentPage:(NSUInteger)current { pageControl.currentPage = current; } - (void)createScrollViewAt:(CGRect)cg { [scrollView setPagingEnabled:TRUE]; scrollView.frame = cg; scrollView.contentSize = CGSizeMake(scrollView.frame.size.width*pageControl.numberOfPages, scrollView.frame.size.height); [scrollView setShowsHorizontalScrollIndicator:FALSE]; [scrollView setShowsVerticalScrollIndicator:FALSE]; } - (void)scrollViewDidScroll:(UIScrollView *)scrollView { float frac = scrollView.contentOffset.x / scrollView.frame.size.width; NSUInteger page = lround(frac); pageControl.currentPage = page; } @end
0
11,693,074
07/27/2012 17:52:25
1,015,595
10/26/2011 23:39:11
221
20
git: 'credential-cache' is not a git command
I followed [these instructions](https://help.github.com/articles/set-up-git) to the letter, including the part about password caching. It seems like the instructions are wrong, because every time I `git push origin master` I get this error: git: 'credential-cache' is not a git command. See 'get --help'. ... at which point I am forced to enter my username and password. After doing so, I am presented with the same error message again, followed by the output from `git push`. Here is the contents of my .gitconfig file: [user] name = myusername email = [email protected] [credential] helper = cache To be clear, after I installed get and ran Git Bash, here is exactly what I typed: git config --global user.name "myusername" git config --global user.email "[email protected]" git config --global credential.helper cache Please help. This is so frustrating!
git
github
git-bash
gitconfig
null
null
open
git: 'credential-cache' is not a git command === I followed [these instructions](https://help.github.com/articles/set-up-git) to the letter, including the part about password caching. It seems like the instructions are wrong, because every time I `git push origin master` I get this error: git: 'credential-cache' is not a git command. See 'get --help'. ... at which point I am forced to enter my username and password. After doing so, I am presented with the same error message again, followed by the output from `git push`. Here is the contents of my .gitconfig file: [user] name = myusername email = [email protected] [credential] helper = cache To be clear, after I installed get and ran Git Bash, here is exactly what I typed: git config --global user.name "myusername" git config --global user.email "[email protected]" git config --global credential.helper cache Please help. This is so frustrating!
0
11,693,076
07/27/2012 17:52:33
1,029,771
11/04/2011 13:35:51
141
1
Telerik's RadDataFilter not found
I am trying to start using Telerik's RadDataFilter. xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation" ... <telerik:RadDataFilter Name="radDataFilter" Source="{Binding FirstEntries}"/> But I get an error: The tag 'RadDataFilter' does not exist in XML namespace 'http://schemas.telerik.com/2008/xaml/presentation'. Line 44 Position 10. Could you please explain to me what I am missing? Thanks.
wpf
telerik
null
null
null
null
open
Telerik's RadDataFilter not found === I am trying to start using Telerik's RadDataFilter. xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation" ... <telerik:RadDataFilter Name="radDataFilter" Source="{Binding FirstEntries}"/> But I get an error: The tag 'RadDataFilter' does not exist in XML namespace 'http://schemas.telerik.com/2008/xaml/presentation'. Line 44 Position 10. Could you please explain to me what I am missing? Thanks.
0
11,693,077
07/27/2012 17:52:33
1,557,835
07/27/2012 13:36:29
1
0
Android's default backgrounds for EditText
When I set up background for my EditText this way: `et1.setBackgroundColor(Color.BLUE);` i get as a background ugly colored square box. How to use Android's default background for my EditText? Or is that some other way to fill backgound with color?
background
default
android-edittext
null
null
null
open
Android's default backgrounds for EditText === When I set up background for my EditText this way: `et1.setBackgroundColor(Color.BLUE);` i get as a background ugly colored square box. How to use Android's default background for my EditText? Or is that some other way to fill backgound with color?
0
11,692,666
07/27/2012 17:25:21
1,522,339
07/13/2012 01:01:00
11
3
.NET Canceling closing of a form prevents it from closed on Windows shutdown
Private Sub frmMain_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing e.Cancel = True Me.WindowState = FormWindowState.Minimized End Sub Hello! I am using this simple code above. However if the application is open while I am shutting down the computer, Windows waits until it's closed or wants me to terminate it in order to continue. I couldn't find a way to know if the user is trying to close application or the Windows is. All I know is, in both situations Windows sends close message to the window and this doesn't really help me. I can think of some other ways yet there should be a "clear" way of knowing. Thanks in advance :)
windows
vb.net
shutdown
formclosing
null
null
open
.NET Canceling closing of a form prevents it from closed on Windows shutdown === Private Sub frmMain_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing e.Cancel = True Me.WindowState = FormWindowState.Minimized End Sub Hello! I am using this simple code above. However if the application is open while I am shutting down the computer, Windows waits until it's closed or wants me to terminate it in order to continue. I couldn't find a way to know if the user is trying to close application or the Windows is. All I know is, in both situations Windows sends close message to the window and this doesn't really help me. I can think of some other ways yet there should be a "clear" way of knowing. Thanks in advance :)
0
11,693,078
07/27/2012 17:52:36
1,558,387
07/27/2012 17:42:22
1
0
Why do cluster plot labels use rows instead of names from ID column?
I am working with a data set (column 1=gene names and column 2 = expression values) and I'm trying to do a cluster plot but what I find is that the branches are labeled by row number rather than the gene ID from column 1. Using: attach(animals) d=dist(as.matrix(animals)) hc=hclust(d) plot(hc) I've tried to do kmeans clustering and end up getting this error: NAs introduced by coercion. Which indicates to me that I have not formatted my data file correctly. Anyone know what's going on here? [1]: http://i.stack.imgur.com/TzIBI.jpg
r
plot
hierarchical-clustering
null
null
null
open
Why do cluster plot labels use rows instead of names from ID column? === I am working with a data set (column 1=gene names and column 2 = expression values) and I'm trying to do a cluster plot but what I find is that the branches are labeled by row number rather than the gene ID from column 1. Using: attach(animals) d=dist(as.matrix(animals)) hc=hclust(d) plot(hc) I've tried to do kmeans clustering and end up getting this error: NAs introduced by coercion. Which indicates to me that I have not formatted my data file correctly. Anyone know what's going on here? [1]: http://i.stack.imgur.com/TzIBI.jpg
0
11,693,079
07/27/2012 17:52:42
89,766
04/11/2009 14:07:42
14,509
706
OpenCV process parts of an image
OpenCV n00b here, please bare with me. I'm trying to use a .png with an alpha channel to 'mask' the current frame from a video stream. My .png has black pixels in the areas that I don't want processed and alpha in others - currently it's saved a 4 colours image with 4 channels, but it might as well be a binary image. I'm doing background subtraction and contour finding on the image, so I imagine if I copy the black pixels from my 'mask' image into the current then there would be no contours found in the black areas. Is this a good approach ? If so, how can I copy the black/non transparent pixels from one cv::Mat on top of the other ?
c++
opencv
null
null
null
null
open
OpenCV process parts of an image === OpenCV n00b here, please bare with me. I'm trying to use a .png with an alpha channel to 'mask' the current frame from a video stream. My .png has black pixels in the areas that I don't want processed and alpha in others - currently it's saved a 4 colours image with 4 channels, but it might as well be a binary image. I'm doing background subtraction and contour finding on the image, so I imagine if I copy the black pixels from my 'mask' image into the current then there would be no contours found in the black areas. Is this a good approach ? If so, how can I copy the black/non transparent pixels from one cv::Mat on top of the other ?
0
11,693,013
07/27/2012 17:47:23
1,430,785
06/01/2012 13:25:56
22
0
Java: JScrollPane is not showing up while other JComponenet are
There is a JCheckBox called "**one**" and another called "**two**". There is also a JScrollPane called "**sp**". In it is a JTextArea. The point of the checkboxes is to hide and show certain parts of the program. I simplified the program and here I tediously explain what is supposed to happen just to make sure you understand the program. This is supposed to happen: Initially only **one** is visible and it is unselected. Whenever **one** is selected, **two** should be set visible. Whenever **two** is selected, **sp** should be set visible. When a checkbox is unselected, the corresponding component is set invisible. However, when one is unselected, **sp** is also set invisible. (**one** controlls **two** and **sp**). The problem: When **one** is selected, **two** is visible. But when **two** is selected, **sp** is not visible (it should be). When one is unselected while **two** is selected, **two** is invisible (this should happen). But when **one** is selected, **two** is visible and all of a sudden **sp** is now visible. After this point, the program functions as it was intended. What could be wrong? package tests; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Checkboxscrollpane extends JPanel { private JCheckBox one, two; private JScrollPane sp; private Checkboxscrollpane() { Listener listener = new Listener(); one = new JCheckBox(); one.addActionListener(listener); add(one); two = new JCheckBox(); two.addActionListener(listener); add(two); sp = new JScrollPane(new JTextArea("hello")); add(sp); one.setVisible(true); two.setVisible(false); sp.setVisible(false); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); one.setLocation(50, 50); two.setLocation(70, 70); sp.setLocation(90, 90); } private class Listener implements ActionListener { public void actionPerformed(ActionEvent e) { if (e.getSource() == one) { two.setVisible(one.isSelected()); } sp.setVisible(one.isSelected() && two.isSelected()); } } public static void main(String[] args) { JFrame frame = new JFrame(); frame.setSize(300, 200); frame.add(new Checkboxscrollpane()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }
java
jscrollpane
visibility
jcheckbox
null
null
open
Java: JScrollPane is not showing up while other JComponenet are === There is a JCheckBox called "**one**" and another called "**two**". There is also a JScrollPane called "**sp**". In it is a JTextArea. The point of the checkboxes is to hide and show certain parts of the program. I simplified the program and here I tediously explain what is supposed to happen just to make sure you understand the program. This is supposed to happen: Initially only **one** is visible and it is unselected. Whenever **one** is selected, **two** should be set visible. Whenever **two** is selected, **sp** should be set visible. When a checkbox is unselected, the corresponding component is set invisible. However, when one is unselected, **sp** is also set invisible. (**one** controlls **two** and **sp**). The problem: When **one** is selected, **two** is visible. But when **two** is selected, **sp** is not visible (it should be). When one is unselected while **two** is selected, **two** is invisible (this should happen). But when **one** is selected, **two** is visible and all of a sudden **sp** is now visible. After this point, the program functions as it was intended. What could be wrong? package tests; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Checkboxscrollpane extends JPanel { private JCheckBox one, two; private JScrollPane sp; private Checkboxscrollpane() { Listener listener = new Listener(); one = new JCheckBox(); one.addActionListener(listener); add(one); two = new JCheckBox(); two.addActionListener(listener); add(two); sp = new JScrollPane(new JTextArea("hello")); add(sp); one.setVisible(true); two.setVisible(false); sp.setVisible(false); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); one.setLocation(50, 50); two.setLocation(70, 70); sp.setLocation(90, 90); } private class Listener implements ActionListener { public void actionPerformed(ActionEvent e) { if (e.getSource() == one) { two.setVisible(one.isSelected()); } sp.setVisible(one.isSelected() && two.isSelected()); } } public static void main(String[] args) { JFrame frame = new JFrame(); frame.setSize(300, 200); frame.add(new Checkboxscrollpane()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }
0
11,693,014
07/27/2012 17:47:26
31,610
10/26/2008 17:16:50
16,236
386
How do you handle environment specific javascript files in Rails?
Let's say you have different settings in development vs. production ( different options, different timings for `setInterval`/`setTimeout` ). How do you handle changes between configurations? I was thinking of using a generator, and everytime I switch between environments, I could regenerate the relevant js files. What is your approach?
javascript
ruby-on-rails
assets
null
null
null
open
How do you handle environment specific javascript files in Rails? === Let's say you have different settings in development vs. production ( different options, different timings for `setInterval`/`setTimeout` ). How do you handle changes between configurations? I was thinking of using a generator, and everytime I switch between environments, I could regenerate the relevant js files. What is your approach?
0
11,693,084
07/27/2012 17:53:12
1,467,855
06/20/2012 00:32:10
30
2
How to query psql by date
I have a table that contains no date or time related fields. Still I want to query that table based on when records/rows were created. Is there a way to do this in PostgreSQL? I prefer an answer about doing it in PostgreSQL directly. But if that's not possible, can hibernate do it for PostgreSQL?
date
time
psql
null
null
null
open
How to query psql by date === I have a table that contains no date or time related fields. Still I want to query that table based on when records/rows were created. Is there a way to do this in PostgreSQL? I prefer an answer about doing it in PostgreSQL directly. But if that's not possible, can hibernate do it for PostgreSQL?
0
11,372,795
07/07/2012 06:21:21
1,023,866
11/01/2011 14:16:18
147
9
cocos-2d:My app crashes when i close it via task manager
I have Weird problem,When i close my app via task manager , my app gets crashed on the line int retVal = UIApplicationMain(argc, argv, nil, @"AppDelegate"); throwing **"Thread : 1 signal SIGKILL"** error,and i can't reopen my app at all. other times it works pretty well. Please some one help me with this problem. I am new to cocos-2d so please be gentle :( , thanks.
iphone
ios
cocos2d-iphone
null
null
null
open
cocos-2d:My app crashes when i close it via task manager === I have Weird problem,When i close my app via task manager , my app gets crashed on the line int retVal = UIApplicationMain(argc, argv, nil, @"AppDelegate"); throwing **"Thread : 1 signal SIGKILL"** error,and i can't reopen my app at all. other times it works pretty well. Please some one help me with this problem. I am new to cocos-2d so please be gentle :( , thanks.
0
11,372,814
07/07/2012 06:26:10
741,162
05/06/2011 05:55:00
89
0
Is there a command decompiling tool supports Windows/Linux/AIX like JAD does for JDK5 class?
I was using [JAD][1] for decompiling the .class file, but on AIX or Linux, jdk 5 class is not supported by JAD, (replied by @Thilo , in this [thread][2]). I know some decompiling tools are based on JAD, but is there such a tool both provides commandline interface(I know DJ has a GUI which I don't want it) that I can call it from Java and supports JDK5 .class? Thanks. [1]: http://www.varaneckas.com/jad/ [2]: http://stackoverflow.com/questions/11361955/jad-version-mismatch-major-minor-49-0-expected-45-3-whats-version-of
java
decompiling
null
null
null
null
open
Is there a command decompiling tool supports Windows/Linux/AIX like JAD does for JDK5 class? === I was using [JAD][1] for decompiling the .class file, but on AIX or Linux, jdk 5 class is not supported by JAD, (replied by @Thilo , in this [thread][2]). I know some decompiling tools are based on JAD, but is there such a tool both provides commandline interface(I know DJ has a GUI which I don't want it) that I can call it from Java and supports JDK5 .class? Thanks. [1]: http://www.varaneckas.com/jad/ [2]: http://stackoverflow.com/questions/11361955/jad-version-mismatch-major-minor-49-0-expected-45-3-whats-version-of
0
11,372,813
07/07/2012 06:26:02
1,150,527
01/15/2012 15:39:19
40
7
Yii Page Variation
I have a website that needs to have a variation of pages. For example: website.com/variation1/page1 website.com/variation2/page1 website.com/variation3/page1 All of which has the same DB and has the same function. The only difference is that these variations differs in page template ie. Header, Footer, Content, etc. This is for the purpose of analyzing page visits. With that, what is the best way to do this? In Yii, there is a common layout used so header/footer depends on the layout. In this case, the header/footer should be specific to each page so the user can just modify the header/footer/content of a specific page without affecting other pages. So, again what is the best approach for this? Thank you in advance.
yii
page
variations
null
null
null
open
Yii Page Variation === I have a website that needs to have a variation of pages. For example: website.com/variation1/page1 website.com/variation2/page1 website.com/variation3/page1 All of which has the same DB and has the same function. The only difference is that these variations differs in page template ie. Header, Footer, Content, etc. This is for the purpose of analyzing page visits. With that, what is the best way to do this? In Yii, there is a common layout used so header/footer depends on the layout. In this case, the header/footer should be specific to each page so the user can just modify the header/footer/content of a specific page without affecting other pages. So, again what is the best approach for this? Thank you in advance.
0
11,371,335
07/07/2012 00:35:27
1,472,538
06/21/2012 15:09:26
6
0
bash and awk performance with clear and cursor up command
I'm testing bash and awk script performace about clear vs tput clear and tput cuu1 (cursor up) commands. I implemented similar scripts in bash and in awk. bash: http://pastebin.com/0DSc0a71 awk: http://pastebin.com/WAJ9inRx admitted to have written them in a similar way, I analize the different execution times. into bash script: - clear bash command is as fast as tput clear command - and tput cuu1 is very expensive into awk script: - clear bash command is slower than tput clear command - and tput cuu1 is not expensive so it seems awk performs better tput command than bash. are there method difference between tput clear and clear command? why tput cuu1 is very expensive into bash script? is there similar x bash command like tput cuu1? I'm curious to know if x as expensive as tput cuu1 into bash script, and I expect that x bash command is slower than tput cuu1 command into awk script. is it right?
performance
bash
script
awk
difference
null
open
bash and awk performance with clear and cursor up command === I'm testing bash and awk script performace about clear vs tput clear and tput cuu1 (cursor up) commands. I implemented similar scripts in bash and in awk. bash: http://pastebin.com/0DSc0a71 awk: http://pastebin.com/WAJ9inRx admitted to have written them in a similar way, I analize the different execution times. into bash script: - clear bash command is as fast as tput clear command - and tput cuu1 is very expensive into awk script: - clear bash command is slower than tput clear command - and tput cuu1 is not expensive so it seems awk performs better tput command than bash. are there method difference between tput clear and clear command? why tput cuu1 is very expensive into bash script? is there similar x bash command like tput cuu1? I'm curious to know if x as expensive as tput cuu1 into bash script, and I expect that x bash command is slower than tput cuu1 command into awk script. is it right?
0
11,372,816
07/07/2012 06:27:19
1,066,604
11/26/2011 05:33:11
438
8
Hiding PopUp window On ONLOAD of parent window
In my site registration is done by step by step process. In my first step ,i opened an popup window using javascript and close this popup window automatically after the tasks in that window. Then i go to the next step by clicking a button.There have another button in second step to return back to first step. so when i come to first step by clicking on back button in second step ,the popup window in first step will loaded. I does not need to load this pop up window when return back to first step. How can i do this? This is the javacsript code : function show_gal(){ var windowSizeArray = [ "width=935,height=580", "width=935,height=600,scrollbars=yes" ]; var url1 = "<?php echo base_url();?>plugin/index.php"; var id = $("#hidtuid").val(); var url = url1+"?usrid=" + id; var windowName = "Image Upload"; var windowSize = windowSizeArray; window.open(url, windowName, windowSize); } This is the code in popup window after completing the task in popup window: window.close();
javascript
jquery
windows
null
null
null
open
Hiding PopUp window On ONLOAD of parent window === In my site registration is done by step by step process. In my first step ,i opened an popup window using javascript and close this popup window automatically after the tasks in that window. Then i go to the next step by clicking a button.There have another button in second step to return back to first step. so when i come to first step by clicking on back button in second step ,the popup window in first step will loaded. I does not need to load this pop up window when return back to first step. How can i do this? This is the javacsript code : function show_gal(){ var windowSizeArray = [ "width=935,height=580", "width=935,height=600,scrollbars=yes" ]; var url1 = "<?php echo base_url();?>plugin/index.php"; var id = $("#hidtuid").val(); var url = url1+"?usrid=" + id; var windowName = "Image Upload"; var windowSize = windowSizeArray; window.open(url, windowName, windowSize); } This is the code in popup window after completing the task in popup window: window.close();
0
11,499,671
07/16/2012 07:15:14
1,192,122
02/06/2012 11:16:12
6
0
Configure Tomcat for Kerberos and Impersonation
I would like to configure Tomcat to be able to connect to AD and authenticate users accordingly. In addition, I would also like to invoke some web services (in this case, Share Point) using the client credentials. So far, I've managed to successfully configure Tomcat to use SPNEGO authentication, as described in the tutorial at http://tomcat.apache.org/tomcat-7.0-doc/windows-auth-howto.html. Note that I have used Tomcat's SPNEGO authentication (not Source Forge's or Waffle). I did not use Source Forge's implementation since I wanted to keep things simple and use Tomcat's as provided out of the box. In addition, I wanted all the authentication and authorization to be handled by Tomcat, using the SPNEGO as the authentication method in `WEB.XML` and Tomcat's JNDI realm for authorization. Also I have not used WAFFLE, since this is Windows only. I'm using CXF as my Web Service stack. According to the CXF documentation at http://cxf.apache.org/docs/client-http-transport-including-ssl-support.html#ClientHTTPTransport%28includingSSLsupport%29-SpnegoAuthentication%28Kerberos%29, all you need to do to authenticate with the a web service (in my case, Share Point) is to use: <conduit name="{http://example.com/}HelloWorldServicePort.http-conduit" xmlns="http://cxf.apache.org/transports/http/configuration"> <authorization> <AuthorizationType>Negotiate</AuthorizationType> <Authorization>CXFClient</Authorization> </authorization> </conduit> and configure CXFClient in jaas.conf (in my case, where Tomcat's server JAAS configuration is located, such that my `jass.conf` looks like: CXFClient { com.sun.security.auth.module.Krb5LoginModule required client=true useTicketCache=true debug=true; }; com.sun.security.jgss.krb5.initiate { com.sun.security.auth.module.Krb5LoginModule required doNotPrompt=true principal="HTTP/[email protected]" useKeyTab=true keyTab="C:/Program Files/Apache/apache-tomcat-7.0.27/conf/tomcatsrv.keytab" storeKey=true debug=true; }; com.sun.security.jgss.krb5.accept { com.sun.security.auth.module.Krb5LoginModule required doNotPrompt=true principal="HTTP/[email protected]" useKeyTab=true keyTab="C:/Program Files/Apache/apache-tomcat-7.0.27/conf/tomcatsrv.keytab" storeKey=true debug=true; }; Yet, when I'm invoking the web service, it is invoked under the service username (i.e. Tomcat's username configured in AD and in `tomcatsrv.keytab`), rather than the client's username (e.g. duncan.attard). So my question is this: Is there some way in which the client's username can be delegated (or use some sort of impersonation) to CXF so that when I invoke Share Point's web service (e.g. I want to upload a file using Copy.asmx), the file is uploaded as `duncan.attard` and not as `tomcat.srv`. Thanks all, your help is much appreciated.
cxf
tomcat7
windows-authentication
kerberos
spnego
null
open
Configure Tomcat for Kerberos and Impersonation === I would like to configure Tomcat to be able to connect to AD and authenticate users accordingly. In addition, I would also like to invoke some web services (in this case, Share Point) using the client credentials. So far, I've managed to successfully configure Tomcat to use SPNEGO authentication, as described in the tutorial at http://tomcat.apache.org/tomcat-7.0-doc/windows-auth-howto.html. Note that I have used Tomcat's SPNEGO authentication (not Source Forge's or Waffle). I did not use Source Forge's implementation since I wanted to keep things simple and use Tomcat's as provided out of the box. In addition, I wanted all the authentication and authorization to be handled by Tomcat, using the SPNEGO as the authentication method in `WEB.XML` and Tomcat's JNDI realm for authorization. Also I have not used WAFFLE, since this is Windows only. I'm using CXF as my Web Service stack. According to the CXF documentation at http://cxf.apache.org/docs/client-http-transport-including-ssl-support.html#ClientHTTPTransport%28includingSSLsupport%29-SpnegoAuthentication%28Kerberos%29, all you need to do to authenticate with the a web service (in my case, Share Point) is to use: <conduit name="{http://example.com/}HelloWorldServicePort.http-conduit" xmlns="http://cxf.apache.org/transports/http/configuration"> <authorization> <AuthorizationType>Negotiate</AuthorizationType> <Authorization>CXFClient</Authorization> </authorization> </conduit> and configure CXFClient in jaas.conf (in my case, where Tomcat's server JAAS configuration is located, such that my `jass.conf` looks like: CXFClient { com.sun.security.auth.module.Krb5LoginModule required client=true useTicketCache=true debug=true; }; com.sun.security.jgss.krb5.initiate { com.sun.security.auth.module.Krb5LoginModule required doNotPrompt=true principal="HTTP/[email protected]" useKeyTab=true keyTab="C:/Program Files/Apache/apache-tomcat-7.0.27/conf/tomcatsrv.keytab" storeKey=true debug=true; }; com.sun.security.jgss.krb5.accept { com.sun.security.auth.module.Krb5LoginModule required doNotPrompt=true principal="HTTP/[email protected]" useKeyTab=true keyTab="C:/Program Files/Apache/apache-tomcat-7.0.27/conf/tomcatsrv.keytab" storeKey=true debug=true; }; Yet, when I'm invoking the web service, it is invoked under the service username (i.e. Tomcat's username configured in AD and in `tomcatsrv.keytab`), rather than the client's username (e.g. duncan.attard). So my question is this: Is there some way in which the client's username can be delegated (or use some sort of impersonation) to CXF so that when I invoke Share Point's web service (e.g. I want to upload a file using Copy.asmx), the file is uploaded as `duncan.attard` and not as `tomcat.srv`. Thanks all, your help is much appreciated.
0
11,499,672
07/16/2012 07:15:19
645,226
03/04/2011 18:17:33
1,528
106
Why does a single Ajax call work fine, but consecutive Ajax calls fail?
**Setup:** I have a Datatable, whose each row is clickable. When a row is clicked, an ajax call is made which returns some data. Sometimes the ajax call takes a little time, depending on the amount of data being returned. It is all working fine. **Problem:** The problem occurs when the rows are clicked quickly, one after the other. In short, before the previous ajax call returns, if the row is clicked (i.e. a new ajax call is made), I get an error. Uncaught TypeError: Property 'callback' of object [object Window] is not a function (The ajax call returns a JSONP data) It looks like somehow the ajax calls are getting mingled (?), but I am not sure of this. Can anyone please tell me why does this happen? Please let me know if any more information is required to clarify the issue. Thanks
jquery
ajax
jquery-ajax
jsonp
null
null
open
Why does a single Ajax call work fine, but consecutive Ajax calls fail? === **Setup:** I have a Datatable, whose each row is clickable. When a row is clicked, an ajax call is made which returns some data. Sometimes the ajax call takes a little time, depending on the amount of data being returned. It is all working fine. **Problem:** The problem occurs when the rows are clicked quickly, one after the other. In short, before the previous ajax call returns, if the row is clicked (i.e. a new ajax call is made), I get an error. Uncaught TypeError: Property 'callback' of object [object Window] is not a function (The ajax call returns a JSONP data) It looks like somehow the ajax calls are getting mingled (?), but I am not sure of this. Can anyone please tell me why does this happen? Please let me know if any more information is required to clarify the issue. Thanks
0
11,499,586
07/16/2012 07:09:05
1,228,489
02/23/2012 13:46:38
44
2
Why is div in div
I am trying to learn HTML/CSS by trying to make simple website in HTML/CSS. I have so far build some basic skeleton but there is something I cant solve. I have a problem where div's articlelisting, sidebar1, sidebar2 are placed inside a div footer, but I want to div's articlelisting, sidebar1, sidebar2 be outside footer. Here is relevant code: HTML: <!-- article listing --> <div class="articlelisting"> articlelisting </div> <!-- sidebar 1 --> <div class="sidebar1"> sidebar1 </div> <!-- sidebar 2 --> <div class="sidebar2"> sidebar2 </div> <!-- footer --> <div class="footer"> footer </div> CSS: .articlelisting { display: inline; width: 48%; float: left; } .sidebar1 { display: inline; width: 24%; float: right; } .sidebar2 { display: inline; margin-right: 15px; width: 24%; float: right; } .footer { width: 100%; border: solid 1px red; }
html
css
html5
css3
null
null
open
Why is div in div === I am trying to learn HTML/CSS by trying to make simple website in HTML/CSS. I have so far build some basic skeleton but there is something I cant solve. I have a problem where div's articlelisting, sidebar1, sidebar2 are placed inside a div footer, but I want to div's articlelisting, sidebar1, sidebar2 be outside footer. Here is relevant code: HTML: <!-- article listing --> <div class="articlelisting"> articlelisting </div> <!-- sidebar 1 --> <div class="sidebar1"> sidebar1 </div> <!-- sidebar 2 --> <div class="sidebar2"> sidebar2 </div> <!-- footer --> <div class="footer"> footer </div> CSS: .articlelisting { display: inline; width: 48%; float: left; } .sidebar1 { display: inline; width: 24%; float: right; } .sidebar2 { display: inline; margin-right: 15px; width: 24%; float: right; } .footer { width: 100%; border: solid 1px red; }
0
11,499,587
07/16/2012 07:09:05
1,520,252
07/12/2012 09:08:07
1
0
how to make the email body some text on new line in iphone application
I am sending email from iphone application i want that in body field right now MyScroe and My Time are showing on same line i want that they should be on separate line each how to show that NSString * emailBody = [NSString stringWithFormat:@"My Score: %d/%d, My Time: %@", numberOfCorrectAnswer, [[[DataManager sharedInstance] questions] count], time]; [picker setMessageBody:emailBody isHTML:NO];
iphone
xcode
null
null
null
null
open
how to make the email body some text on new line in iphone application === I am sending email from iphone application i want that in body field right now MyScroe and My Time are showing on same line i want that they should be on separate line each how to show that NSString * emailBody = [NSString stringWithFormat:@"My Score: %d/%d, My Time: %@", numberOfCorrectAnswer, [[[DataManager sharedInstance] questions] count], time]; [picker setMessageBody:emailBody isHTML:NO];
0
11,499,588
07/16/2012 07:09:10
1,367,669
05/01/2012 11:42:02
26
0
How to get the data from different tables from different data models using telerik open access
I am using Telerik open Access,I have three different data models like UserDataModel->account_details ProfileDataModel->biographic_details ContactsDataModel->contact_groups I have three different tables in different datamodels.I want to load the data from all the tables,I used joins and wrote the lambda expression,but it is throwing an exception that "InvalidOperationException unhandled by user code".can u tell me how to retrieve the the data from different tables in diferent datamodels.
asp.net-mvc
visual-studio-2010
telerik-open-access
null
null
null
open
How to get the data from different tables from different data models using telerik open access === I am using Telerik open Access,I have three different data models like UserDataModel->account_details ProfileDataModel->biographic_details ContactsDataModel->contact_groups I have three different tables in different datamodels.I want to load the data from all the tables,I used joins and wrote the lambda expression,but it is throwing an exception that "InvalidOperationException unhandled by user code".can u tell me how to retrieve the the data from different tables in diferent datamodels.
0
11,499,680
07/16/2012 07:16:01
1,503,495
07/05/2012 09:19:26
22
0
How to Store cookies upon an action of login and retrieve cookies inside a <s:textfield /> tag in any of the jsp pages
I am new to cookies management. I just want to start with a simple scenario. When user successfully login to his account a uid (which is fetched from the uid of the corresponding row in Users table from database) is generated and stored on the hard disk of the user system as a cookie. After login user is redirected to his home page. User go to another accessible page say myinfo.jsp. myinfo.jsp contains a textfield in which the uid to be displayed which is to be retrieved form the cookies stored on harddisk. I want when a user navigates to myinfo.jsp he should see his uid in the textfield. I am using J2EE technologies. Can someone suggest a way how to do this simple task. Or can someone please put some `to the point to my this simple task` tutorial's link. I ll be thankfull for any help or hint. Thanks.
jsp
java-ee
cookies
null
null
null
open
How to Store cookies upon an action of login and retrieve cookies inside a <s:textfield /> tag in any of the jsp pages === I am new to cookies management. I just want to start with a simple scenario. When user successfully login to his account a uid (which is fetched from the uid of the corresponding row in Users table from database) is generated and stored on the hard disk of the user system as a cookie. After login user is redirected to his home page. User go to another accessible page say myinfo.jsp. myinfo.jsp contains a textfield in which the uid to be displayed which is to be retrieved form the cookies stored on harddisk. I want when a user navigates to myinfo.jsp he should see his uid in the textfield. I am using J2EE technologies. Can someone suggest a way how to do this simple task. Or can someone please put some `to the point to my this simple task` tutorial's link. I ll be thankfull for any help or hint. Thanks.
0
11,499,691
07/16/2012 07:16:29
1,528,135
07/16/2012 07:09:16
1
0
How to take rows from Oracle seperated by comma
This is what im getting ============================ parent MenuName Name menu2 type menuId menu2Id -------------------------------------------------------------- 26 General Currency Add 3 27 29 26 General Currency Delete 3 27 31 26 General Currency Update 3 27 30 26 General Currency View 3 27 28 26 General Country Add 3 32 34 26 General Country Delete 3 32 36 26 General Country Update 3 32 35 I want to get like this =================== MenuId MenuName Name Privilege ------------------------------------------------ 27 General Currency Add,Delete,Update,View 32 General Country Add,Delete,Update Please help with this Thx in advance.
sql
oracle
query
null
null
null
open
How to take rows from Oracle seperated by comma === This is what im getting ============================ parent MenuName Name menu2 type menuId menu2Id -------------------------------------------------------------- 26 General Currency Add 3 27 29 26 General Currency Delete 3 27 31 26 General Currency Update 3 27 30 26 General Currency View 3 27 28 26 General Country Add 3 32 34 26 General Country Delete 3 32 36 26 General Country Update 3 32 35 I want to get like this =================== MenuId MenuName Name Privilege ------------------------------------------------ 27 General Currency Add,Delete,Update,View 32 General Country Add,Delete,Update Please help with this Thx in advance.
0
11,499,695
07/16/2012 07:16:43
1,354,064
04/24/2012 15:07:15
16
2
crystal report move table to next page
I am using c# crystal report,i have some text in header section below comes is a table in sub-report below table is footer section,if table rows grows in size,end rows get cutoff,what i want to do is if table rows grew in size it should get display in next page and below that footer section should be display. Do anyone knows how to achieved it. Thanks in advance.
c#
crystal-reports-2008
null
null
null
null
open
crystal report move table to next page === I am using c# crystal report,i have some text in header section below comes is a table in sub-report below table is footer section,if table rows grows in size,end rows get cutoff,what i want to do is if table rows grew in size it should get display in next page and below that footer section should be display. Do anyone knows how to achieved it. Thanks in advance.
0
11,298,185
07/02/2012 17:15:15
1,496,652
07/02/2012 16:42:49
1
0
How to get a full, seemless rotation with Impress.js?
I'm using impress.js to create a 3D effect in which you are inside four pages, as if they were four walls in a room. To view the next page, a simple -90 degree rotation is used. The pages are already laid out with impressjs using: //page 1 <div id="title" class="step" data-x="0" data-y="0" data-z="0"> //page 2 <div id="about" class="step" data-x="2000" data-y="0" data-z="2000" data-rotate-y="-90"> //page 3 <div id="our_work" class="step" data-x="0" data-y="0" data-z="4000" data-rotate-y="-180"> //page 4 <div id="contact" class="step" data-x="-2000" data-y="0" data-z="2000" data-rotate-y="-270"> This works, except that the transition from page four to one takes the "long way" around. As in, the rotation is displayed as a 270 degree rotation instead of -90 as the others. If I change page 1 rotation to -360 to solve this, transition from page one to page two is broken. How would I go about making a full circle of transitions?
rotation
impress.js
null
null
null
null
open
How to get a full, seemless rotation with Impress.js? === I'm using impress.js to create a 3D effect in which you are inside four pages, as if they were four walls in a room. To view the next page, a simple -90 degree rotation is used. The pages are already laid out with impressjs using: //page 1 <div id="title" class="step" data-x="0" data-y="0" data-z="0"> //page 2 <div id="about" class="step" data-x="2000" data-y="0" data-z="2000" data-rotate-y="-90"> //page 3 <div id="our_work" class="step" data-x="0" data-y="0" data-z="4000" data-rotate-y="-180"> //page 4 <div id="contact" class="step" data-x="-2000" data-y="0" data-z="2000" data-rotate-y="-270"> This works, except that the transition from page four to one takes the "long way" around. As in, the rotation is displayed as a 270 degree rotation instead of -90 as the others. If I change page 1 rotation to -360 to solve this, transition from page one to page two is broken. How would I go about making a full circle of transitions?
0
11,298,162
07/02/2012 17:13:15
1,338,499
04/17/2012 10:40:12
8
0
Rails 3.2 with Ajax implementation
I am a beginner with Ruby on Rails. I have been able to build a small application with the help of ROR.<br></br><br></br> I want to fetch and load some of my data without loading the whole page. On click of different links, data should be uploaded in the respective div. I am trying to provide :remote=>true property on the link. But this property is not rendering an attribute properly.<br></br><br></br> After following multiple links on Rails with Ajax, I found that in view links should be given as:<br></br> <%= link_to cateogary.cateogary_name, :controller => "cateogaries", :action => "show_async", :id => cateogary_id, :remote => true %> This should be converted to: <a href="/cateogaries/12/show_async data-remote=true"> While, this is converted to: <a href="/cateogaries/12/show_async?remote=true"> What could be its probable reason? Please forward some good link which provides complete Ajax implementation in ROR.
ruby-on-rails
ajax
ruby-on-rails-3.2
null
null
null
open
Rails 3.2 with Ajax implementation === I am a beginner with Ruby on Rails. I have been able to build a small application with the help of ROR.<br></br><br></br> I want to fetch and load some of my data without loading the whole page. On click of different links, data should be uploaded in the respective div. I am trying to provide :remote=>true property on the link. But this property is not rendering an attribute properly.<br></br><br></br> After following multiple links on Rails with Ajax, I found that in view links should be given as:<br></br> <%= link_to cateogary.cateogary_name, :controller => "cateogaries", :action => "show_async", :id => cateogary_id, :remote => true %> This should be converted to: <a href="/cateogaries/12/show_async data-remote=true"> While, this is converted to: <a href="/cateogaries/12/show_async?remote=true"> What could be its probable reason? Please forward some good link which provides complete Ajax implementation in ROR.
0
11,298,163
07/02/2012 17:13:19
1,238,934
02/28/2012 22:00:36
285
6
android event after landscape calculation
I enabled onConfigChanges event and properly handling when device turns from portrait into lanscape. However, after onConfigChanges, when page is calculated again and finishes it, which event is fired? Thank you
java
android
null
null
null
null
open
android event after landscape calculation === I enabled onConfigChanges event and properly handling when device turns from portrait into lanscape. However, after onConfigChanges, when page is calculated again and finishes it, which event is fired? Thank you
0
11,298,190
07/02/2012 17:15:33
1,477,444
06/23/2012 22:42:18
29
1
Why im getting big red X with white background in the pictureBox instead the animated gif?
I checked on the hard disk the animated gif is created and i opened it in internet explorer and it worked. So i dont understand why im getting this white with big x red. I used breakpoint and didnt get any errors so far. The real creation of the animated gif in this class is this line number 175: unfreez.MakeGIF(myGifList, previewFileName, 8, true); And the animated gif is realy exist and created.In line 210 im calling the function that load the animated gif to the pictureBox: pictureBoxImage(previewFileName); And this is the pictureBoxImage function where i used breakpoint and it didnt show any errors: public void pictureBoxImage(string pbImage) { Image img2 = null; try { using (img = Image.FromFile(pbImage)) { //get the old image thats loaded from the _memSt memorystream //and dispose it Image i = this.pictureBox1.Image; this.pictureBox1.Image = null; if (i != null) i.Dispose(); //grab the old stream MemoryStream m = _memSt; //save the new image to this stream _memSt = new MemoryStream(); img.Save(_memSt, System.Drawing.Imaging.ImageFormat.Gif); if (m != null) m.Dispose(); //create our image to display img2 = Image.FromStream(_memSt); } if (img2 != null) pictureBox1.Image = img2; //label2.Text = numberOfFiles.ToString(); //label6.Text = nameOfStartFile.ToString(); //label4.Text = nameOfEndFile.ToString(); //File.Delete(pbImage); } catch (Exception err) { Logger.Write("Animation Error >>> " + err); } } Cant figure out why ? The red x and white background. I didnt copy to here the whole class but i will if its needed but the animated gif is created good and working on internet explorer so the class is working but the showing on the pictureBox dosent work for some reason.
c#
null
null
null
null
null
open
Why im getting big red X with white background in the pictureBox instead the animated gif? === I checked on the hard disk the animated gif is created and i opened it in internet explorer and it worked. So i dont understand why im getting this white with big x red. I used breakpoint and didnt get any errors so far. The real creation of the animated gif in this class is this line number 175: unfreez.MakeGIF(myGifList, previewFileName, 8, true); And the animated gif is realy exist and created.In line 210 im calling the function that load the animated gif to the pictureBox: pictureBoxImage(previewFileName); And this is the pictureBoxImage function where i used breakpoint and it didnt show any errors: public void pictureBoxImage(string pbImage) { Image img2 = null; try { using (img = Image.FromFile(pbImage)) { //get the old image thats loaded from the _memSt memorystream //and dispose it Image i = this.pictureBox1.Image; this.pictureBox1.Image = null; if (i != null) i.Dispose(); //grab the old stream MemoryStream m = _memSt; //save the new image to this stream _memSt = new MemoryStream(); img.Save(_memSt, System.Drawing.Imaging.ImageFormat.Gif); if (m != null) m.Dispose(); //create our image to display img2 = Image.FromStream(_memSt); } if (img2 != null) pictureBox1.Image = img2; //label2.Text = numberOfFiles.ToString(); //label6.Text = nameOfStartFile.ToString(); //label4.Text = nameOfEndFile.ToString(); //File.Delete(pbImage); } catch (Exception err) { Logger.Write("Animation Error >>> " + err); } } Cant figure out why ? The red x and white background. I didnt copy to here the whole class but i will if its needed but the animated gif is created good and working on internet explorer so the class is working but the showing on the pictureBox dosent work for some reason.
0
11,298,192
07/02/2012 17:15:46
831,533
07/06/2011 12:13:47
33
0
Facebook post text on wall - access token always NULL
I am dealing for a long time with this problem. I have registered my app on facebook but I stil getting this error: {"error":{"message":"An active access token must be used to query information about the current user.","type":"OAuthException","code":2500} my code : facebook = new Facebook("3************0"); facebook.authorize(this, new String[] { "publish_stream","user_status"}, new FaceDialog()); // dialog will shown and I log in into facebook String token = facebook.getAccessToken(); // returns null Bundle parameters = new Bundle(); parameters.putByteArray("message", "Haloooo".getBytes()); parameters.putByteArray("description", "test test test".getBytes()); response = facebook.request("me"); response = facebook.request("me/feed", param, "POST"); Does someone solved this problem ?
java
facebook-access-token
facebook-java-api
facebook-java-sdk
null
null
open
Facebook post text on wall - access token always NULL === I am dealing for a long time with this problem. I have registered my app on facebook but I stil getting this error: {"error":{"message":"An active access token must be used to query information about the current user.","type":"OAuthException","code":2500} my code : facebook = new Facebook("3************0"); facebook.authorize(this, new String[] { "publish_stream","user_status"}, new FaceDialog()); // dialog will shown and I log in into facebook String token = facebook.getAccessToken(); // returns null Bundle parameters = new Bundle(); parameters.putByteArray("message", "Haloooo".getBytes()); parameters.putByteArray("description", "test test test".getBytes()); response = facebook.request("me"); response = facebook.request("me/feed", param, "POST"); Does someone solved this problem ?
0
11,298,193
07/02/2012 17:15:51
1,418,367
05/25/2012 22:37:16
1
0
Creating multiple objects on one-to-one relationship
Helo, I had stuck with this problem. Just to make things simple i'll explain it shorter. Student has_many :grades belongs_to :class Grade belongs_to :student belongs_to :rubric Rubric belongs_to :course has_many :students, :through => :class To create new grade we need to find existent students. We can call @course.students to do so. Also, grade should be created with rubric_id. I've already found out how to do nested forms. But how to pass plural student id's to new grades? How to build controller and view to do so?
ruby-on-rails
ruby-on-rails-3
null
null
null
null
open
Creating multiple objects on one-to-one relationship === Helo, I had stuck with this problem. Just to make things simple i'll explain it shorter. Student has_many :grades belongs_to :class Grade belongs_to :student belongs_to :rubric Rubric belongs_to :course has_many :students, :through => :class To create new grade we need to find existent students. We can call @course.students to do so. Also, grade should be created with rubric_id. I've already found out how to do nested forms. But how to pass plural student id's to new grades? How to build controller and view to do so?
0
11,298,194
07/02/2012 17:15:52
1,496,692
07/02/2012 17:08:35
1
0
Problems seeting up a simple countdown timer
can somebody tell me what I am doing wrong? I am new to jquery and I would like to have some feedback. Basically what I want is some sort of a countdown timer that would display how many days are left till an event happens. The event is a set date. thank you for your help <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Almost Vacation</title> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <script> $('document').on('ready', calc); function calc(){ var myDate = new Date(); myDate.setMonth(05, 06); var today = new Date(); today.getDay(); var x = myDate - today; $('#aantal p').text(x); } </script> <style type="text/css"> p { color:red; font-size:1.8em; margin:-90px 10px 5px; } </style> </head> <body> <img src="http://fed.cmd.hro.nl/upload/files/1011/y1/q4/w3/slapende_student.jpg" width="462" height="275" /> <p>Vacation starts in<span id="aantal">&nbsp;</span> Days</p> </body> </html>
javascript
jquery
dom
null
null
null
open
Problems seeting up a simple countdown timer === can somebody tell me what I am doing wrong? I am new to jquery and I would like to have some feedback. Basically what I want is some sort of a countdown timer that would display how many days are left till an event happens. The event is a set date. thank you for your help <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Almost Vacation</title> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <script> $('document').on('ready', calc); function calc(){ var myDate = new Date(); myDate.setMonth(05, 06); var today = new Date(); today.getDay(); var x = myDate - today; $('#aantal p').text(x); } </script> <style type="text/css"> p { color:red; font-size:1.8em; margin:-90px 10px 5px; } </style> </head> <body> <img src="http://fed.cmd.hro.nl/upload/files/1011/y1/q4/w3/slapende_student.jpg" width="462" height="275" /> <p>Vacation starts in<span id="aantal">&nbsp;</span> Days</p> </body> </html>
0
11,298,196
07/02/2012 17:15:56
1,342,730
04/19/2012 00:09:03
1,550
101
Why should we only use 'static' inside a class or a function (C++)?
I was recently reading Stroustrups *The C++ Programming Language* and in the section about Linkage in chapter 9 I came across the following paragraph: "In C and older C++ programs, the keyword static is (confusingly) used to mean "use internal linkage". Don't use static except inside functions and classes." The problem is that reading further on, the author did not elaborate on why this is bad practice. I use static functions from time to time in my code usually for some simple calculation that is not needed outside the compilation unit, but I never realised this was frowned upon and it is not obvious to me why it is bad. Can anyone shed light on this for me please??
c++
static
keywords
linkage
null
null
open
Why should we only use 'static' inside a class or a function (C++)? === I was recently reading Stroustrups *The C++ Programming Language* and in the section about Linkage in chapter 9 I came across the following paragraph: "In C and older C++ programs, the keyword static is (confusingly) used to mean "use internal linkage". Don't use static except inside functions and classes." The problem is that reading further on, the author did not elaborate on why this is bad practice. I use static functions from time to time in my code usually for some simple calculation that is not needed outside the compilation unit, but I never realised this was frowned upon and it is not obvious to me why it is bad. Can anyone shed light on this for me please??
0
11,298,197
07/02/2012 17:15:57
731,255
04/29/2011 14:32:31
1,175
6
Ruby on Rails - how to correctly map and link to a new controller?
I am trying to create this controller: def calculate # Do some calculations here respond_to do |format| format.json{head status} end end and I have a HAML file in which I make my HTML and in there I want to link to something like this: =link_to("stats" , controller_path_url) where controller_path is a rake routes path that is shown. My question is how do I make this sort of uniquely named controller function to be mapped and show its path when I do rake routes? Is there something I have to do in routes.rb? What should I change there? Thanks!
ruby-on-rails
ruby
haml
null
null
null
open
Ruby on Rails - how to correctly map and link to a new controller? === I am trying to create this controller: def calculate # Do some calculations here respond_to do |format| format.json{head status} end end and I have a HAML file in which I make my HTML and in there I want to link to something like this: =link_to("stats" , controller_path_url) where controller_path is a rake routes path that is shown. My question is how do I make this sort of uniquely named controller function to be mapped and show its path when I do rake routes? Is there something I have to do in routes.rb? What should I change there? Thanks!
0
11,571,527
07/20/2012 01:08:26
1,275,777
03/17/2012 13:29:55
18
12
How to benchmark android application?
At work I am using Ubuntu and at home I am using windows 7. I would like to know how can I benchmark my android application on Ubuntu and windows 7.
java
android
benchmarking
null
null
null
open
How to benchmark android application? === At work I am using Ubuntu and at home I am using windows 7. I would like to know how can I benchmark my android application on Ubuntu and windows 7.
0
11,571,534
07/20/2012 01:10:09
1,392,588
05/13/2012 20:12:41
1
0
Wordpress Background Slider
Hello im trying to setup a background slider on my wordpress theme here http://22twenty.com/wordpress this is the slider: http://wordpress.org/extend/plugins/site-background-slider/ im sure its something with the theme as it worked in another. Is there something that needs to be coded into the theme for custom backgrounds to work? (ie: not ones in the css) Hope someone can help If you need more info leave a comment and ill get back as soon as possible Denver
wordpress
background
slider
gallery
null
null
open
Wordpress Background Slider === Hello im trying to setup a background slider on my wordpress theme here http://22twenty.com/wordpress this is the slider: http://wordpress.org/extend/plugins/site-background-slider/ im sure its something with the theme as it worked in another. Is there something that needs to be coded into the theme for custom backgrounds to work? (ie: not ones in the css) Hope someone can help If you need more info leave a comment and ill get back as soon as possible Denver
0
11,571,538
07/20/2012 01:10:30
355,226
06/01/2010 09:11:16
2,160
211
SugarCRM Adding Additional Details Info icon in Detail View
in SugarCRM some modules like "Calls" has an "i" (Additional Details) icon in detail view which shows some additional details about that record. I want to display same kind for other modules like customer visits with some custom details of the records. Any hints or guidance will be helpful.
sugarcrm
null
null
null
null
null
open
SugarCRM Adding Additional Details Info icon in Detail View === in SugarCRM some modules like "Calls" has an "i" (Additional Details) icon in detail view which shows some additional details about that record. I want to display same kind for other modules like customer visits with some custom details of the records. Any hints or guidance will be helpful.
0
11,571,535
07/20/2012 01:10:09
1,532,892
07/17/2012 20:06:50
1
0
Phonegap Remote Server Post Security
I have a phonegap app that uses jquery to post to a remote server, running on Google App Engine. What's the best way to ensure that only my phonegap app can post to this remote server? I've been scouring the web for an answer but can't find anything concrete. Normally I believe you'd check the referrer to ensure that the request is coming from a whitelisted domain but in this scenario there is no domain because it's a phonegap app. This question is similar but it's gone unanswered: http://stackoverflow.com/questions/10756947/security-issues-with-phonegap-remote-server-access
google-app-engine
phonegap
null
null
null
null
open
Phonegap Remote Server Post Security === I have a phonegap app that uses jquery to post to a remote server, running on Google App Engine. What's the best way to ensure that only my phonegap app can post to this remote server? I've been scouring the web for an answer but can't find anything concrete. Normally I believe you'd check the referrer to ensure that the request is coming from a whitelisted domain but in this scenario there is no domain because it's a phonegap app. This question is similar but it's gone unanswered: http://stackoverflow.com/questions/10756947/security-issues-with-phonegap-remote-server-access
0
11,571,536
07/20/2012 01:10:14
612,192
02/10/2011 22:12:38
18
0
Getting search engine result count faster than my way?
This is what I've written so far. It's hacky, but it works. It grabs from bing.com with the url and then parses it with BeautifulSoup to find the results section. from urllib3 import HTTPConnectionPool from bs4 import BeautifulSoup http_pool = HTTPConnectionPool("www.bing.com") def count_results(string): string = string.replace(" ", "+") url = '/search?q="%s"' % string r = http_pool.urlopen("GET", url) soup = BeautifulSoup(r.data) open("test.txt", "w+").write(r.data) if "No results found" in soup.prettify(): return 0 count = soup.find(id="count") if count == None: # something went wrong return 0 count = count.text.split(" ")[0] # remove " results" count = count.replace(",", "") # remove ","'s count = int(count) return count It works, but it's pretty slow. I'm using it to compare somewhat random phrases on whether or not they likely make any sense, and ranking them based off how many results I get. I'm testing it with hundreds of phrases and even though I'm using multithreading, this is still really slow. Is there any way that I can query for only the number of results to speed up the process? Is there some API to do this that I don't have to pay for?
python
search
results
null
null
null
open
Getting search engine result count faster than my way? === This is what I've written so far. It's hacky, but it works. It grabs from bing.com with the url and then parses it with BeautifulSoup to find the results section. from urllib3 import HTTPConnectionPool from bs4 import BeautifulSoup http_pool = HTTPConnectionPool("www.bing.com") def count_results(string): string = string.replace(" ", "+") url = '/search?q="%s"' % string r = http_pool.urlopen("GET", url) soup = BeautifulSoup(r.data) open("test.txt", "w+").write(r.data) if "No results found" in soup.prettify(): return 0 count = soup.find(id="count") if count == None: # something went wrong return 0 count = count.text.split(" ")[0] # remove " results" count = count.replace(",", "") # remove ","'s count = int(count) return count It works, but it's pretty slow. I'm using it to compare somewhat random phrases on whether or not they likely make any sense, and ranking them based off how many results I get. I'm testing it with hundreds of phrases and even though I'm using multithreading, this is still really slow. Is there any way that I can query for only the number of results to speed up the process? Is there some API to do this that I don't have to pay for?
0
11,571,245
07/20/2012 00:27:56
640,558
03/02/2011 04:50:28
2,262
50
Is there a way to prevent a form from being submitted if it is not auto completed?
I'm learning jquery and its awesome! Its very easy to do complex stuff but I'm unsure how to prevent someone from submitting a form(or warning them) if a autocomplete fails. I have a form on my site that gets autocompleted with existing data from my database and when they submit it provides info on that entry. If they add something thats not in the database then my server will bounce them back to the form page and let them know of the error but I want to do something to warn them while they are filling out the form. Is there a jquery-ish easy way to do this? The approach I was thinking of was to pass a value along with the autocomplete and if that key does not exist to use jquery to provide a error message and hide the submit button but not sure if its the best way(feels like a cheap hack). Any suggestions?
javascript
jquery
html
null
null
null
open
Is there a way to prevent a form from being submitted if it is not auto completed? === I'm learning jquery and its awesome! Its very easy to do complex stuff but I'm unsure how to prevent someone from submitting a form(or warning them) if a autocomplete fails. I have a form on my site that gets autocompleted with existing data from my database and when they submit it provides info on that entry. If they add something thats not in the database then my server will bounce them back to the form page and let them know of the error but I want to do something to warn them while they are filling out the form. Is there a jquery-ish easy way to do this? The approach I was thinking of was to pass a value along with the autocomplete and if that key does not exist to use jquery to provide a error message and hide the submit button but not sure if its the best way(feels like a cheap hack). Any suggestions?
0
11,546,278
07/18/2012 16:41:17
1,483,119
06/26/2012 14:49:35
13
0
CSS: Extend an image
I have an image that looks like this: ![My image][1] Is it possible to extend this image (perhaps inside a div) so that it would look something like this: ![enter image description here][2] Thanks! [1]: http://i.stack.imgur.com/QDCz4.png [2]: http://i.stack.imgur.com/hnIxE.png
css
image
background
extend
null
null
open
CSS: Extend an image === I have an image that looks like this: ![My image][1] Is it possible to extend this image (perhaps inside a div) so that it would look something like this: ![enter image description here][2] Thanks! [1]: http://i.stack.imgur.com/QDCz4.png [2]: http://i.stack.imgur.com/hnIxE.png
0
10,940,392
06/07/2012 21:51:56
474,780
10/13/2010 16:58:20
1,473
76
Explicitly set document.domain on every page
Is is a good idea to set document.domain on every page of your site. For example if your site is 'www.example.com'. But you also work with 'en.example.com' and 'fr.example.com' and 'www.example.com:8444'. All these domains make it difficult to work with when you have to deal with xss issues. So is it a terrible idea to explicity set document.domain = 'example.com' on all pages?
xss
null
null
null
null
null
open
Explicitly set document.domain on every page === Is is a good idea to set document.domain on every page of your site. For example if your site is 'www.example.com'. But you also work with 'en.example.com' and 'fr.example.com' and 'www.example.com:8444'. All these domains make it difficult to work with when you have to deal with xss issues. So is it a terrible idea to explicity set document.domain = 'example.com' on all pages?
0
11,349,470
07/05/2012 17:29:55
1,504,727
07/05/2012 17:08:37
1
0
How to display images from SDcard to Gallery in Android emulator
i added image files to the Android Eclips DDMS platform. after launching the emulator and clicking on the Gallery icon no image was displayed. instead "No media was found" message was displayd. any help to fix this. Thank you
android
null
null
null
null
null
open
How to display images from SDcard to Gallery in Android emulator === i added image files to the Android Eclips DDMS platform. after launching the emulator and clicking on the Gallery icon no image was displayed. instead "No media was found" message was displayd. any help to fix this. Thank you
0
11,349,471
07/05/2012 17:29:57
1,269,169
07/04/2011 21:09:54
38
2
Why won't Internet explorer style (with css) invalid elements?
This works in chromium (and I assume every other major browser) -html- <invalid></invalid> -css- invalid { color: red; } `<invalid>` represents an invalid element (not part of the html standard) here is an example: http://jsfiddle.net/myhonor/4H7Hj/ But when I try this in IE, it doesn't work. why is this and is there a way fix this (is it a DTD thing?)
html
css
internet-explorer
null
null
null
open
Why won't Internet explorer style (with css) invalid elements? === This works in chromium (and I assume every other major browser) -html- <invalid></invalid> -css- invalid { color: red; } `<invalid>` represents an invalid element (not part of the html standard) here is an example: http://jsfiddle.net/myhonor/4H7Hj/ But when I try this in IE, it doesn't work. why is this and is there a way fix this (is it a DTD thing?)
0
11,349,496
07/05/2012 17:32:17
1,300,874
03/29/2012 13:14:19
1
0
GWT Progress Bar while buffering PDF content before displaying on browser
In my GWT app I have written a servlet to download/stream a PDF file. Following is the code. protected void updateResponse(HttpServletResponse response, InputStream dataStream, long contentLength, KnownContentTypes contentType, String filename, int cacheSeconds) { response.setHeader("Content-Type", contentType.getTypeString()); response.setHeader("Content-Length", String.valueOf(contentLength)); response.setHeader("Content-disposition", "inline;filename=" + filename); response.setHeader("Cache-Control", "max-age=" + cacheSeconds); byte[] buffer = new byte[BUFFER_SIZE]; try { ServletOutputStream out = response.getOutputStream(); while ((dataStream.read(buffer)) != -1) { out.write(buffer); } } catch (IOException e) { sendError(response); } } The pdf is successfully rendered on the browser. The problem is some pdf's are really large in size and since this is called on window.open all I see is a blank browser. I want to display a dynamic message like '1MB of 5MB downloaded' and display/render the entire PDF file once all bytes are streamed. Please let me know how to do this. I am new to GWT and any help will be appreciated. Thanks.
gwt
servlets
download
progress-bar
null
null
open
GWT Progress Bar while buffering PDF content before displaying on browser === In my GWT app I have written a servlet to download/stream a PDF file. Following is the code. protected void updateResponse(HttpServletResponse response, InputStream dataStream, long contentLength, KnownContentTypes contentType, String filename, int cacheSeconds) { response.setHeader("Content-Type", contentType.getTypeString()); response.setHeader("Content-Length", String.valueOf(contentLength)); response.setHeader("Content-disposition", "inline;filename=" + filename); response.setHeader("Cache-Control", "max-age=" + cacheSeconds); byte[] buffer = new byte[BUFFER_SIZE]; try { ServletOutputStream out = response.getOutputStream(); while ((dataStream.read(buffer)) != -1) { out.write(buffer); } } catch (IOException e) { sendError(response); } } The pdf is successfully rendered on the browser. The problem is some pdf's are really large in size and since this is called on window.open all I see is a blank browser. I want to display a dynamic message like '1MB of 5MB downloaded' and display/render the entire PDF file once all bytes are streamed. Please let me know how to do this. I am new to GWT and any help will be appreciated. Thanks.
0
11,349,499
07/05/2012 17:32:24
1,296,218
03/27/2012 17:31:05
1
0
Caching a background in Windows Metro App
I'm working on a WinJS Windows Metro application and on one of my pages I'm getting a URL to an image to display as a background. I can get that working just fine by using url(the URL of the image) and setting that as the style.backgroundImage. I need to use that same image on a linked page, but that means I have to make another HTTP request, which I'm trying to avoid. I looked into alternatives and found LocalFolder as an option. The only issue is I don't know how to access the file and set it as a background. Is that the right way to go about caching data to reduce webcalls? Here's the code I'm using: function saveBackground(url) { localFolder.createFileAsync("background.jpg", Windows.Storage.CreationCollisionOption.replaceExisting).then(function (newFile) { var uri = Windows.Foundation.Uri(url); var downloader = new Windows.Networking.BackgroundTransfer.BackgroundDownloader(); var promise = downloader.createDownload(uri, newFile); promise.startAsync().then(function () { //set background here. var wrapper = document.getElementById("wrapper").style; localFolder.getFileAsync("background.jpg").then(function (image) { console.log(image.path); var path = image.path.split(""); var newLocation = []; //This is just to make the backslashes work out for the url() for (var i = 0; i < path.length; i++) { if (path[i] != '\\') { newLocation.push(path[i]); } else { newLocation.push('\\\\'); } } console.log(newLocation); var newPath = newLocation.join(""); var target = "url(" + newPath + ")"; wrapper.backgroundImage = target; console.log(wrapper.backgroundImage); wrapper.backgroundSize = "cover"; }); }); }); }
javascript
microsoft-metro
null
null
null
null
open
Caching a background in Windows Metro App === I'm working on a WinJS Windows Metro application and on one of my pages I'm getting a URL to an image to display as a background. I can get that working just fine by using url(the URL of the image) and setting that as the style.backgroundImage. I need to use that same image on a linked page, but that means I have to make another HTTP request, which I'm trying to avoid. I looked into alternatives and found LocalFolder as an option. The only issue is I don't know how to access the file and set it as a background. Is that the right way to go about caching data to reduce webcalls? Here's the code I'm using: function saveBackground(url) { localFolder.createFileAsync("background.jpg", Windows.Storage.CreationCollisionOption.replaceExisting).then(function (newFile) { var uri = Windows.Foundation.Uri(url); var downloader = new Windows.Networking.BackgroundTransfer.BackgroundDownloader(); var promise = downloader.createDownload(uri, newFile); promise.startAsync().then(function () { //set background here. var wrapper = document.getElementById("wrapper").style; localFolder.getFileAsync("background.jpg").then(function (image) { console.log(image.path); var path = image.path.split(""); var newLocation = []; //This is just to make the backslashes work out for the url() for (var i = 0; i < path.length; i++) { if (path[i] != '\\') { newLocation.push(path[i]); } else { newLocation.push('\\\\'); } } console.log(newLocation); var newPath = newLocation.join(""); var target = "url(" + newPath + ")"; wrapper.backgroundImage = target; console.log(wrapper.backgroundImage); wrapper.backgroundSize = "cover"; }); }); }); }
0
11,471,558
07/13/2012 13:33:47
1,304,830
03/31/2012 09:09:58
16
2
What's the best way on Android to create a photo gallery (fullscreen)
I wonder what's the best way to create a photo gallery for my app. I get the pictures from an RSS feed and I want to display each of them in fullscreen. What should I use ? I tried with an ImageView but the images are resized in a bad way (they don't keep the original dimensions) I used this answer to implement my gallery : http://stackoverflow.com/questions/5312909/android-gallery-fullscreen Thank's
android
imageview
photo-gallery
null
null
null
open
What's the best way on Android to create a photo gallery (fullscreen) === I wonder what's the best way to create a photo gallery for my app. I get the pictures from an RSS feed and I want to display each of them in fullscreen. What should I use ? I tried with an ImageView but the images are resized in a bad way (they don't keep the original dimensions) I used this answer to implement my gallery : http://stackoverflow.com/questions/5312909/android-gallery-fullscreen Thank's
0
11,471,530
07/13/2012 13:32:23
1,523,633
07/13/2012 13:09:33
1
0
Chat Application using skype API in my windows Application
I want to integrate skype chat in my windows application. basically this is the requirement. i want to do some chat with my friends in windows application using Skype chat. all the connections are getting from skype address book. skype application should run on my windows application. Thanks & regards Casper
asp.net
skype
null
null
null
07/14/2012 16:12:37
not constructive
Chat Application using skype API in my windows Application === I want to integrate skype chat in my windows application. basically this is the requirement. i want to do some chat with my friends in windows application using Skype chat. all the connections are getting from skype address book. skype application should run on my windows application. Thanks & regards Casper
4
11,471,533
07/13/2012 13:32:34
417,791
08/11/2010 22:20:03
2,009
104
Use jar's inside war's WEB-INF/lib as depenendencies
The problem is that I would like to use ***.jar** files located inside **WEB-INF/lib** of one of my project's dependencies that comes packaged as war. I would like to use those files at compile time. Is it possible? Essantialy it looks more/less like this: **MyProject** pom.xml: <dependencies> ................ <dependency> <groupId>a.b.c</groupId> <artifactId>service</artifactId> <version>1.0.0</version> <type>war</type> <scope>provided</scope> </dependency> ............... </dependencies> **service.war** structure: | --WEB-INF | ---lib | ---lib1.jar <- I need this file on compile time for **MyProject**
web-applications
maven
dependencies
null
null
null
open
Use jar's inside war's WEB-INF/lib as depenendencies === The problem is that I would like to use ***.jar** files located inside **WEB-INF/lib** of one of my project's dependencies that comes packaged as war. I would like to use those files at compile time. Is it possible? Essantialy it looks more/less like this: **MyProject** pom.xml: <dependencies> ................ <dependency> <groupId>a.b.c</groupId> <artifactId>service</artifactId> <version>1.0.0</version> <type>war</type> <scope>provided</scope> </dependency> ............... </dependencies> **service.war** structure: | --WEB-INF | ---lib | ---lib1.jar <- I need this file on compile time for **MyProject**
0
11,471,306
07/13/2012 13:18:10
39,068
11/19/2008 19:18:37
3,193
103
What language feature can allow transition from visitor to sequence?
I will use C# syntax since I am familiar with it, but it is not really language-specific. Let's say we have a method void Visit(Tree tree, Action<Node> action) So it takes a `tree`, and it calls `action` on each node in the tree. Now, one other option to go with it would be IEnumerable<Node> ToEnumerable(Tree tree) which converts `tree` to a flat lazy sequence we can go over and call `action` on each node. Now, if we have an API with `ToEnumerable`, it is pretty trivial to provide `Visit` on top of it. However, is there a concept/feature in any language that will allow to provide `ToEnumerable` on top of `Visit` in this scenario (as lazy sequence, so list is not created in advance)?
language-agnostic
ienumerable
sequence
visitor
null
null
open
What language feature can allow transition from visitor to sequence? === I will use C# syntax since I am familiar with it, but it is not really language-specific. Let's say we have a method void Visit(Tree tree, Action<Node> action) So it takes a `tree`, and it calls `action` on each node in the tree. Now, one other option to go with it would be IEnumerable<Node> ToEnumerable(Tree tree) which converts `tree` to a flat lazy sequence we can go over and call `action` on each node. Now, if we have an API with `ToEnumerable`, it is pretty trivial to provide `Visit` on top of it. However, is there a concept/feature in any language that will allow to provide `ToEnumerable` on top of `Visit` in this scenario (as lazy sequence, so list is not created in advance)?
0
11,471,562
07/13/2012 13:34:11
1,480,458
06/25/2012 15:50:36
1
1
How can I catch this XmlException thrown from third party library?
I'm using the Exchange Web Services managed API and about once a day it throws an `XmlException` that I have no idea how to catch. Here are the exception details. System.Xml.XmlException was unhandled Message="'', hexadecimal value 0x1F, is an invalid character. Line 1, position 1." Source="System.Xml" LineNumber=1 LinePosition=1 SourceUri="" StackTrace: at System.Xml.XmlTextReaderImpl.Throw(Exception e) at System.Xml.XmlTextReaderImpl.Throw(String res, String[] args) at System.Xml.XmlTextReaderImpl.Throw(Int32 pos, String res, String[] args) at System.Xml.XmlTextReaderImpl.ThrowInvalidChar(Int32 pos, Char invChar) at System.Xml.XmlTextReaderImpl.ParseText(Int32& startPos, Int32& endPos, Int32& outOrChars) at System.Xml.XmlTextReaderImpl.ParseText() at System.Xml.XmlTextReaderImpl.ParseDocumentContent() at System.Xml.XmlTextReaderImpl.Read() at Microsoft.Exchange.WebServices.Data.EwsXmlReader.Read() at Microsoft.Exchange.WebServices.Data.EwsXmlReader.Read(XmlNodeType nodeType) at Microsoft.Exchange.WebServices.Data.EwsXmlReader.InternalReadElement(XmlNamespace xmlNamespace, String localName, XmlNodeType nodeType) at Microsoft.Exchange.WebServices.Data.EwsXmlReader.ReadStartElement(XmlNamespace xmlNamespace, String localName) at Microsoft.Exchange.WebServices.Data.ServiceRequestBase.ReadResponse(EwsServiceXmlReader ewsXmlReader) at Microsoft.Exchange.WebServices.Data.HangingServiceRequestBase.ParseResponses(Object state) at System.Threading._ThreadPoolWaitCallback.WaitCallback_Context(Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading._ThreadPoolWaitCallback.PerformWaitCallbackInternal(_ThreadPoolWaitCallback tpWaitCallBack) at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback(Object state) InnerException: From the stacktrace I don't see anything that would allow me to catch and fix the issue. How can I catch this?
c#
exception
ews
exchangewebservices
null
null
open
How can I catch this XmlException thrown from third party library? === I'm using the Exchange Web Services managed API and about once a day it throws an `XmlException` that I have no idea how to catch. Here are the exception details. System.Xml.XmlException was unhandled Message="'', hexadecimal value 0x1F, is an invalid character. Line 1, position 1." Source="System.Xml" LineNumber=1 LinePosition=1 SourceUri="" StackTrace: at System.Xml.XmlTextReaderImpl.Throw(Exception e) at System.Xml.XmlTextReaderImpl.Throw(String res, String[] args) at System.Xml.XmlTextReaderImpl.Throw(Int32 pos, String res, String[] args) at System.Xml.XmlTextReaderImpl.ThrowInvalidChar(Int32 pos, Char invChar) at System.Xml.XmlTextReaderImpl.ParseText(Int32& startPos, Int32& endPos, Int32& outOrChars) at System.Xml.XmlTextReaderImpl.ParseText() at System.Xml.XmlTextReaderImpl.ParseDocumentContent() at System.Xml.XmlTextReaderImpl.Read() at Microsoft.Exchange.WebServices.Data.EwsXmlReader.Read() at Microsoft.Exchange.WebServices.Data.EwsXmlReader.Read(XmlNodeType nodeType) at Microsoft.Exchange.WebServices.Data.EwsXmlReader.InternalReadElement(XmlNamespace xmlNamespace, String localName, XmlNodeType nodeType) at Microsoft.Exchange.WebServices.Data.EwsXmlReader.ReadStartElement(XmlNamespace xmlNamespace, String localName) at Microsoft.Exchange.WebServices.Data.ServiceRequestBase.ReadResponse(EwsServiceXmlReader ewsXmlReader) at Microsoft.Exchange.WebServices.Data.HangingServiceRequestBase.ParseResponses(Object state) at System.Threading._ThreadPoolWaitCallback.WaitCallback_Context(Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading._ThreadPoolWaitCallback.PerformWaitCallbackInternal(_ThreadPoolWaitCallback tpWaitCallBack) at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback(Object state) InnerException: From the stacktrace I don't see anything that would allow me to catch and fix the issue. How can I catch this?
0
11,471,565
07/13/2012 13:34:33
1,523,672
07/13/2012 13:26:40
1
0
Phonegap/JQuery HTML not rendered correctly
I'm using Ajax to gather HTML from a webserver, which is then used to populate a div within the app. The HTML populates, however the CSS is ignored and whats displayed is a plain HTML output to the screen instead of the JQuery CSS. Thing is, when I manually enter the HTML into the div and then load up the whole thing works great. Any help is greatly appreciated Ajax call: <script type="text/javascript" charset="utf-8"> $(document).bind('pageinit', function(){ $.ajax({ url: "http://www.bytelyte.com/TAM/getDetails.php", dataType: 'html', success: function(text_results){ console.log(text_results); $('.class-items').append(text_results); } }); }); </script> And the div being populated: <div data-role="content"> <div class="class-items"> </div> </div>
css
jquery-mobile
phonegap
null
null
null
open
Phonegap/JQuery HTML not rendered correctly === I'm using Ajax to gather HTML from a webserver, which is then used to populate a div within the app. The HTML populates, however the CSS is ignored and whats displayed is a plain HTML output to the screen instead of the JQuery CSS. Thing is, when I manually enter the HTML into the div and then load up the whole thing works great. Any help is greatly appreciated Ajax call: <script type="text/javascript" charset="utf-8"> $(document).bind('pageinit', function(){ $.ajax({ url: "http://www.bytelyte.com/TAM/getDetails.php", dataType: 'html', success: function(text_results){ console.log(text_results); $('.class-items').append(text_results); } }); }); </script> And the div being populated: <div data-role="content"> <div class="class-items"> </div> </div>
0
11,471,574
07/13/2012 13:35:00
992,173
10/12/2011 19:47:25
173
2
Is it good practice to define a model when using data from a plist file?
Should I read/write data directly from/to a plist file in the view controller or is it better to define a class for the model and then use its methods to read/write data? Thanks
objective-c
ios
uiviewcontroller
plist
null
null
open
Is it good practice to define a model when using data from a plist file? === Should I read/write data directly from/to a plist file in the view controller or is it better to define a class for the model and then use its methods to read/write data? Thanks
0
11,471,526
07/13/2012 13:31:58
1,472,843
06/21/2012 17:17:02
8
0
Yii - about jquery ajax
I ve writing shop application, and i've question as you know ajax in Yii looks like <?php echo CHtml::ajaxLink( '', array("cart/add/id/$item->id"), array( 'update'=>'#cart', ), array('class' => "button_basket") ); ?> This code updates div with id = cart. But how i can update other elements on the page, for example on Cart page, i removing via ajax one item and i need to update Total price, what is the best way to do that? Sorry for my english)
php
ajax
jquery-ajax
frameworks
yii
null
open
Yii - about jquery ajax === I ve writing shop application, and i've question as you know ajax in Yii looks like <?php echo CHtml::ajaxLink( '', array("cart/add/id/$item->id"), array( 'update'=>'#cart', ), array('class' => "button_basket") ); ?> This code updates div with id = cart. But how i can update other elements on the page, for example on Cart page, i removing via ajax one item and i need to update Total price, what is the best way to do that? Sorry for my english)
0
11,401,121
07/09/2012 18:44:06
698,070
04/08/2011 05:46:23
208
8
How to make a list with multiple column in each row in Sencha touch?
I want a list with multiple columns in each row. The row also can consist the image. I am able to get the values from store. But unable to display them in a proper way. i need the view like below: ![Image][1] [1]: http://i.stack.imgur.com/07Fmo.jpg But without check box and bell image is also fine Please help. Thanks in advance
phonegap
sencha-touch-2
null
null
null
null
open
How to make a list with multiple column in each row in Sencha touch? === I want a list with multiple columns in each row. The row also can consist the image. I am able to get the values from store. But unable to display them in a proper way. i need the view like below: ![Image][1] [1]: http://i.stack.imgur.com/07Fmo.jpg But without check box and bell image is also fine Please help. Thanks in advance
0
11,401,124
07/09/2012 18:44:18
863,975
07/26/2011 17:35:27
192
10
Partial View content is not refreshed
I have recently moved to MVC and am having some trouble getting around refreshing partial views. I have an Index View in the HomeController, that renders 3 different Partial Views(Top, Left, Right). Whenever, there is an error during some operation, I want to display the error in the Top View |----------------------------| | Top | |----------------------------| | | | | Left | Right | | | | |______________|_____________| To implement this, I call the Index of the HomeController and store the error message in HomeControllers ViewBag.ErrorMessage. When I load the Top Partial View, I pass this error message to it, and display it there by storing it in TopController's ViewBag. When I run this in debug mode, I can see that the error message propagates all the way to the Top Controllers Index View, however, nothing changes on the display. So, I'm concluding that this has something to do with rendering the content since I know that the content does get updated. Here's some code to look at - ##Homecontroller.cs public ActionResult Index(string message = "") { ViewBag.ErrorMessage = message; return View(); } ##Index.cshtml (Home) <div id="topDiv"> @Html.Action("Index", "Top", new { message = @ViewBag.ErrorMessage }); </div> <div id="leftDiv"> @Html.Action("Index", "Left"); </div> <div id="rightDiv"> @Html.Action("Index", "Right"); </div> ##TopController.cs public ActionResult Index(string message="") { ViewBag.DisplayMsg = message; return PartialView(); } ##Index.cshtml (Top) <div id="errorMsgBox"> @ViewBag.DisplayMsg </div> ##How Home/Index is called in case of errors- try { data= utils.getdata(); return View(data); } catch (Exception ex) { return RedirectToAction("Index", "Home", new { message = ex.Message } ); } Does anyone know what the deal is? Any better way to propagate errors?
asp.net-mvc-3
razor
partial-views
null
null
null
open
Partial View content is not refreshed === I have recently moved to MVC and am having some trouble getting around refreshing partial views. I have an Index View in the HomeController, that renders 3 different Partial Views(Top, Left, Right). Whenever, there is an error during some operation, I want to display the error in the Top View |----------------------------| | Top | |----------------------------| | | | | Left | Right | | | | |______________|_____________| To implement this, I call the Index of the HomeController and store the error message in HomeControllers ViewBag.ErrorMessage. When I load the Top Partial View, I pass this error message to it, and display it there by storing it in TopController's ViewBag. When I run this in debug mode, I can see that the error message propagates all the way to the Top Controllers Index View, however, nothing changes on the display. So, I'm concluding that this has something to do with rendering the content since I know that the content does get updated. Here's some code to look at - ##Homecontroller.cs public ActionResult Index(string message = "") { ViewBag.ErrorMessage = message; return View(); } ##Index.cshtml (Home) <div id="topDiv"> @Html.Action("Index", "Top", new { message = @ViewBag.ErrorMessage }); </div> <div id="leftDiv"> @Html.Action("Index", "Left"); </div> <div id="rightDiv"> @Html.Action("Index", "Right"); </div> ##TopController.cs public ActionResult Index(string message="") { ViewBag.DisplayMsg = message; return PartialView(); } ##Index.cshtml (Top) <div id="errorMsgBox"> @ViewBag.DisplayMsg </div> ##How Home/Index is called in case of errors- try { data= utils.getdata(); return View(data); } catch (Exception ex) { return RedirectToAction("Index", "Home", new { message = ex.Message } ); } Does anyone know what the deal is? Any better way to propagate errors?
0
11,401,133
07/09/2012 18:44:50
931
08/10/2008 18:42:39
2,025
52
GWT: Returning multiple styles for the same CSS field
In a CssResource, Can I return multiple style class names from the same method? [please forgive any mistakes in code - I'm trying to recreate at home, from memory]. I have the following library code (which I can't change): void render(ClientBundle1 bundle) { setInnerHtml("<div class=\" + bundle.css().style() + \"/>"); } The bundle is straight forward: interface ClientBundle1 extends ClientBundle { @Source("css1.css") CssResource1 css(); } and the css resource: interface CssResource1 extends CssResource { style1(); } and the css1.css: .style1 {width=10; height=20} Now - I'd like to _*partially*_ override "style1" with another style (only override the height, not the width) of from my own css (css2.css). However, my css2.css is declared like this: .style2 {height=30} So I'd like to partially override css1.style1 with css2.style2 (different class name). If this was vanilla HTML, I would've just written: ...import css1 then css2... <div class="style1 style2"/> However, since this is GWT, I would need something like this: interface ClientBundle2 extends ClientBundle1 { @Source("css1.css", "css2.css") CssResource2 css(); } and the css resource: interface CssResource2 extends CssResource1 { @Classname("style1", "style2") style(); } but of course, the above isn't possible in GWT. Is there a way of assigning two style class names per a single style method?
css
gwt
styles
cssresource
null
null
open
GWT: Returning multiple styles for the same CSS field === In a CssResource, Can I return multiple style class names from the same method? [please forgive any mistakes in code - I'm trying to recreate at home, from memory]. I have the following library code (which I can't change): void render(ClientBundle1 bundle) { setInnerHtml("<div class=\" + bundle.css().style() + \"/>"); } The bundle is straight forward: interface ClientBundle1 extends ClientBundle { @Source("css1.css") CssResource1 css(); } and the css resource: interface CssResource1 extends CssResource { style1(); } and the css1.css: .style1 {width=10; height=20} Now - I'd like to _*partially*_ override "style1" with another style (only override the height, not the width) of from my own css (css2.css). However, my css2.css is declared like this: .style2 {height=30} So I'd like to partially override css1.style1 with css2.style2 (different class name). If this was vanilla HTML, I would've just written: ...import css1 then css2... <div class="style1 style2"/> However, since this is GWT, I would need something like this: interface ClientBundle2 extends ClientBundle1 { @Source("css1.css", "css2.css") CssResource2 css(); } and the css resource: interface CssResource2 extends CssResource1 { @Classname("style1", "style2") style(); } but of course, the above isn't possible in GWT. Is there a way of assigning two style class names per a single style method?
0
11,401,134
07/09/2012 18:44:52
667,236
03/19/2011 11:06:50
202
0
Javascript - Coverting string to Int returns NaN error
This is my code. It alert()'s NaN everytime. function updateScore(action){ var cookieArray = document.cookie.split(";"); var encodedURL = cookieArray[2]; var decodedURL = decodeURIComponent(encodedURL); //check if cookie exists if (decodedURL == "undefined"){ setCookie("rrcookie_score","0",1) } var oldScore = decodedURL.split('='); //alert(oldScore[1]); var oldScoreInt = parseInt(oldScore); var newScore = oldScoreInt + 1; alert(newScore); }
javascript
parseint
null
null
null
null
open
Javascript - Coverting string to Int returns NaN error === This is my code. It alert()'s NaN everytime. function updateScore(action){ var cookieArray = document.cookie.split(";"); var encodedURL = cookieArray[2]; var decodedURL = decodeURIComponent(encodedURL); //check if cookie exists if (decodedURL == "undefined"){ setCookie("rrcookie_score","0",1) } var oldScore = decodedURL.split('='); //alert(oldScore[1]); var oldScoreInt = parseInt(oldScore); var newScore = oldScoreInt + 1; alert(newScore); }
0
11,401,138
07/09/2012 18:45:04
690,143
04/03/2011 19:18:56
97
3
Issue with AWS Elastic Load Balancing sticky sessions - subdomains are being served from different servers?
I'm quite new to load balancing and I'm having some problems with getting Amazon's Elastic Load Balancer to play nice with subdomains. I have two EC2 servers behind my load balancer. When I go to *mydomain.com* and *www.mydomain.com*, the two urls are served from different EC2 servers. I need both *www.mydomain.com* and *mydomain.com* to be served from the same server so that sessions work properly. I have the load balancer "stickyness" set to LBCookieStickinessPolicy like so: ![enter image description here][1] And my two EC2 instances are both "In Service" behind my load balancer: ![enter image description here][2] I don't know if it's useful for troubleshooting, but my apache configuration looks like: ![enter image description here][3] When I view the sessions in Firebug, I see the following... For mydomain.com: ![enter image description here][4] For www.mydomain.com (notice the additional "www.") ![enter image description here][5] I'm not sure why, but there are actually two AWSELB cookies set when viewing the cookies for www.mydomain.com. I'm using the Zend Framework, and I'm setting my cookie_domain like so: Zend_Session::start(array('cookie_domain' => '.mydomain.com')); This has worked fine in the past before moving the site to the two load balanced EC2 servers. Our site uses a few subdomains, such as api.mydomain.com and my.mydomain.com, which made the cookie_domain important. And, granted, this might be OK. It's quite possible that once we get the load balancer session "sticky" to work properly between subdomains, session variables will work as expected (hopefully!). Any ideas why our site is being served from different servers when the "www." is added to the domain name? Thanks! [1]: http://i.stack.imgur.com/IMDju.png [2]: http://i.stack.imgur.com/aLRZC.png [3]: http://i.stack.imgur.com/VJioY.png [4]: http://i.stack.imgur.com/JuOZm.png [5]: http://i.stack.imgur.com/TQ92Q.png
session
amazon-web-services
load-balancing
subdomains
null
null
open
Issue with AWS Elastic Load Balancing sticky sessions - subdomains are being served from different servers? === I'm quite new to load balancing and I'm having some problems with getting Amazon's Elastic Load Balancer to play nice with subdomains. I have two EC2 servers behind my load balancer. When I go to *mydomain.com* and *www.mydomain.com*, the two urls are served from different EC2 servers. I need both *www.mydomain.com* and *mydomain.com* to be served from the same server so that sessions work properly. I have the load balancer "stickyness" set to LBCookieStickinessPolicy like so: ![enter image description here][1] And my two EC2 instances are both "In Service" behind my load balancer: ![enter image description here][2] I don't know if it's useful for troubleshooting, but my apache configuration looks like: ![enter image description here][3] When I view the sessions in Firebug, I see the following... For mydomain.com: ![enter image description here][4] For www.mydomain.com (notice the additional "www.") ![enter image description here][5] I'm not sure why, but there are actually two AWSELB cookies set when viewing the cookies for www.mydomain.com. I'm using the Zend Framework, and I'm setting my cookie_domain like so: Zend_Session::start(array('cookie_domain' => '.mydomain.com')); This has worked fine in the past before moving the site to the two load balanced EC2 servers. Our site uses a few subdomains, such as api.mydomain.com and my.mydomain.com, which made the cookie_domain important. And, granted, this might be OK. It's quite possible that once we get the load balancer session "sticky" to work properly between subdomains, session variables will work as expected (hopefully!). Any ideas why our site is being served from different servers when the "www." is added to the domain name? Thanks! [1]: http://i.stack.imgur.com/IMDju.png [2]: http://i.stack.imgur.com/aLRZC.png [3]: http://i.stack.imgur.com/VJioY.png [4]: http://i.stack.imgur.com/JuOZm.png [5]: http://i.stack.imgur.com/TQ92Q.png
0
11,401,141
07/09/2012 18:45:18
21,704
09/24/2008 14:48:41
2,012
54
Visual Studio keeps adding property to my csproj. Why?
I'm using Visual Studio 2012 RC to work with my C# solution. All my configuration-specific settings are stored within a single .props file which is then included by all my .csproj files. Yet VS insists on putting this right in front of the include: <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'"> <IntermediateOutputPath>C:\Users\xyz\AppData\Local\Temp\vs855E.tmp\Debug\</IntermediateOutputPath> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'"> <IntermediateOutputPath>C:\Users\xyz\AppData\Local\Temp\vs855E.tmp\Release\</IntermediateOutputPath> </PropertyGroup> <Import Project="$(MSBuildProjectDirectory)\..\Common.props" /> Why is that? FYI, my common file looks like this: http://pastebin.com/Uued1XY0
.net
visual-studio
msbuild
visual-studio-2012
csproj
null
open
Visual Studio keeps adding property to my csproj. Why? === I'm using Visual Studio 2012 RC to work with my C# solution. All my configuration-specific settings are stored within a single .props file which is then included by all my .csproj files. Yet VS insists on putting this right in front of the include: <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'"> <IntermediateOutputPath>C:\Users\xyz\AppData\Local\Temp\vs855E.tmp\Debug\</IntermediateOutputPath> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'"> <IntermediateOutputPath>C:\Users\xyz\AppData\Local\Temp\vs855E.tmp\Release\</IntermediateOutputPath> </PropertyGroup> <Import Project="$(MSBuildProjectDirectory)\..\Common.props" /> Why is that? FYI, my common file looks like this: http://pastebin.com/Uued1XY0
0
11,386,971
07/08/2012 21:44:31
658,031
03/13/2011 23:52:31
1,743
55
Locking a custom button size
I am drving from `Button` and I want this new custom button to be always 20 by 20 pixels. I wrote in the default and my own implemented constractor both the `Width` and `Height` to be 20 but this does not change anything if I drag the control from toolbox into designer or I programatically add the control to form. public partial class PinButton : Button { public PinButtonData Data { get; set; } public PinButton() { InitializeComponent(); Height = 20; Width = 20; } public PinButton(PinButtonData data) { InitializeComponent(); Height = 20; Width = 20; Data = data; } }
c#
winforms
usercontrols
null
null
null
open
Locking a custom button size === I am drving from `Button` and I want this new custom button to be always 20 by 20 pixels. I wrote in the default and my own implemented constractor both the `Width` and `Height` to be 20 but this does not change anything if I drag the control from toolbox into designer or I programatically add the control to form. public partial class PinButton : Button { public PinButtonData Data { get; set; } public PinButton() { InitializeComponent(); Height = 20; Width = 20; } public PinButton(PinButtonData data) { InitializeComponent(); Height = 20; Width = 20; Data = data; } }
0
11,385,200
07/08/2012 17:37:47
1,147,002
01/13/2012 05:23:39
33
1
Your Thoughts: Entity Framework Data Context via a DataHelper class (centralized context and transactions)
I want to get opinions on the code I have put together for a centralized DataContext via a DataHelper class that I have created to be re-used on projects. **NOTE** - there is a ton of code here, sorry about that, but I really wanted to layout out the complete approach and uses for my ideas. I'm an not saying this is the right approach, but it works for me so far (still playing with the approach, nothing in production yet, but very similar to stuff I have built over the years) and I really want to get constructive feedback from the community on what I have built to see if it is insane, great, can be improved, etc... A few thoughts I put into this: 1. Data Context needs to be stored in a common memory space, easily accessible 2. Transactions should take the same approach 3. It must be disposed of properly 4. Allows for better separation of business logic for Saving and Deleting in transactions. Here is the code for each item: 1 - First the data context stored in either the current HttpContext.Current.Items collection (so it only lives for the life of the page and only is fired up once at the first requested) or if the HttpContext doesn't exist uses a ThreadSlot (in which case that code most clean it up itself, like a console app using it...): <!-- language: c# --> public static class DataHelper { /// <summary> /// Current Data Context object in the HTTPContext or Current Thread /// </summary> public static TemplateProjectContext Context { get { TemplateProjectContext context = null; if (HttpContext.Current == null) { LocalDataStoreSlot threadSlot = Thread.GetNamedDataSlot("DataHelper.CurrentContext"); if (Thread.GetData(threadSlot) == null) { context = new TemplateProjectContext(); Thread.SetData(threadSlot, context); } else { context = (TemplateProjectContext)Thread.GetData(threadSlot); } } else { if (HttpContext.Current.Items["DataHelper.CurrentContext"] == null) { context = new TemplateProjectContext(); HttpContext.Current.Items["DataHelper.CurrentContext"] = context; } else { context = (TemplateProjectContext)HttpContext.Current.Items["DataHelper.CurrentContext"]; } } return context; } set { if (HttpContext.Current == null) { if (value == null) { Thread.FreeNamedDataSlot("DataHelper.CurrentContext"); } else { LocalDataStoreSlot threadSlot = Thread.GetNamedDataSlot("DataHelper.CurrentContext"); Thread.SetData(threadSlot, value); } } else { if (value == null) HttpContext.Current.Items.Remove("DataHelper.CurrentContext"); else HttpContext.Current.Items["DataHelper.CurrentContext"] = value; } } } ... 2 - To support transactions, I use a similar approach, and also include helper methods to Begin, Commit and Rollback: <!-- language: c# --> /// <summary> /// Current Transaction object in the HTTPContext or Current Thread /// </summary> public static DbTransaction Transaction { get { if (HttpContext.Current == null) { LocalDataStoreSlot threadSlot = Thread.GetNamedDataSlot("currentTransaction"); if (Thread.GetData(threadSlot) == null) { return null; } else { return (DbTransaction)Thread.GetData(threadSlot); } } else { if (HttpContext.Current.Items["currentTransaction"] == null) { return null; } else { return (DbTransaction)HttpContext.Current.Items["currentTransaction"]; } } } set { if (HttpContext.Current == null) { LocalDataStoreSlot threadSlot = Thread.GetNamedDataSlot("currentTransaction"); Thread.SetData(threadSlot, value); } else { HttpContext.Current.Items["currentTransaction"] = value; } } } /// <summary> /// Begins a transaction based on the common connection and transaction /// </summary> public static void BeginTransaction() { DataHelper.Transaction = DataHelper.CreateSqlTransaction(); } /// <summary> /// Creates a SqlTransaction object based on the current common connection /// </summary> /// <returns>A new SqlTransaction object for the current common connection</returns> public static DbTransaction CreateSqlTransaction() { return CreateSqlTransaction(DataHelper.Context.Connection); } /// <summary> /// Creates a SqlTransaction object for the requested connection object /// </summary> /// <param name="connection">Reference to the connection object the transaction should be created for</param> /// <returns>New transaction object for the requested connection</returns> public static DbTransaction CreateSqlTransaction(DbConnection connection) { if (connection.State != ConnectionState.Open) connection.Open(); return connection.BeginTransaction(); } /// <summary> /// Rolls back and cleans up the current common transaction /// </summary> public static void RollbackTransaction() { if (DataHelper.Transaction != null) { DataHelper.RollbackTransaction(DataHelper.Transaction); if (HttpContext.Current == null) { Thread.FreeNamedDataSlot("currentTransaction"); } else { HttpContext.Current.Items.Remove("currentTransaction"); } } } /// <summary> /// Rolls back and disposes of the requested transaction /// </summary> /// <param name="transaction">The transaction to rollback</param> public static void RollbackTransaction(DbTransaction transaction) { transaction.Rollback(); transaction.Dispose(); } /// <summary> /// Commits and cleans up the current common transaction /// </summary> public static void CommitTransaction() { if (DataHelper.Transaction != null) { DataHelper.CommitTransaction(DataHelper.Transaction); if (HttpContext.Current == null) { Thread.FreeNamedDataSlot("currentTransaction"); } else { HttpContext.Current.Items.Remove("currentTransaction"); } } } /// <summary> /// Commits and disposes of the requested transaction /// </summary> /// <param name="transaction">The transaction to commit</param> public static void CommitTransaction(DbTransaction transaction) { transaction.Commit(); transaction.Dispose(); } 3 - Clean and easy Disposal <!-- language: c# --> /// <summary> /// Cleans up the currently active connection /// </summary> public static void Dispose() { if (HttpContext.Current == null) { LocalDataStoreSlot threadSlot = Thread.GetNamedDataSlot("DataHelper.CurrentContext"); if (Thread.GetData(threadSlot) != null) { DbTransaction transaction = DataHelper.Transaction; if (transaction != null) { DataHelper.CommitTransaction(transaction); Thread.FreeNamedDataSlot("currentTransaction"); } ((TemplateProjectContext)Thread.GetData(threadSlot)).Dispose(); Thread.FreeNamedDataSlot("DataHelper.CurrentContext"); } } else { if (HttpContext.Current.Items["DataHelper.CurrentContext"] != null) { DbTransaction transaction = DataHelper.Transaction; if (transaction != null) { DataHelper.CommitTransaction(transaction); HttpContext.Current.Items.Remove("currentTransaction"); } ((TemplateProjectContext)HttpContext.Current.Items["DataHelper.CurrentContext"]).Dispose(); HttpContext.Current.Items.Remove("DataHelper.CurrentContext"); } } } 3b - I'm building this in MVC, so I have a "base" Controller class that all my controllers inherit from - this way the Context only lives from when first accessed on a request, and until the page is disposed, that way its not too "long running" <!-- language: c# --> using System.Web.Mvc; using Core.ClassLibrary; using TemplateProject.Business; using TemplateProject.ClassLibrary; namespace TemplateProject.Web.Mvc { public class SiteController : Controller { protected override void Dispose(bool disposing) { DataHelper.Dispose(); base.Dispose(disposing); } } } 4 - So I am big on business classes, separation of concerns, reusable code, all that wonderful stuff. I have an approach that I call "Entity Generic" that can be applied to any entity in my system - for example, Addresses and Phones A Customer can have 1 or more of each, along with a Store, Person, or anything really - so why add street, city, state, etc to every thing that needs it when you can just build an Address entity, that takes a Foreign Type and Key (what I call EntityType and EntityId) - then you have a re-usable business object, supporting UI control, etc - so you build it once and re-use it everywhere. This is where the centralized approach I am pushing for here really comes in handy and I think makes the code much cleaner than having to pass the current data context/transaction into every method. Take for example that you have a Page for a customer, the Model includes the Customer data, Contact, Address and a few Phone Numbers (main, fax, or cell, whatever) When getting a Customer Edit Model for the page, here is a bit of the code I have put together (see how I use the DataHelper.Context in the LINQ): <!-- language: c# --> public static CustomerEditModel FetchEditModel(int customerId) { if (customerId == 0) { CustomerEditModel model = new CustomerEditModel(); model.MainContact = new CustomerContactEditModel(); model.MainAddress = new AddressEditModel(); model.ShippingAddress = new AddressEditModel(); model.Phone = new PhoneEditModel(); model.Cell = new PhoneEditModel(); model.Fax = new PhoneEditModel(); return model; } else { var output = (from c in DataHelper.Context.Customers where c.CustomerId == customerId select new CustomerEditModel { CustomerId = c.CustomerId, CompanyName = c.CompanyName }).SingleOrDefault(); if (output != null) { output.MainContact = CustomerContact.FetchEditModelByPrimary(customerId) ?? new CustomerContactEditModel(); output.MainAddress = Address.FetchEditModelByType(BusinessEntityTypes.Customer, customerId, AddressTypes.Main) ?? new AddressEditModel(); output.ShippingAddress = Address.FetchEditModelByType(BusinessEntityTypes.Customer, customerId, AddressTypes.Shipping) ?? new AddressEditModel(); output.Phone = Phone.FetchEditModelByType(BusinessEntityTypes.Customer, customerId, PhoneTypes.Main) ?? new PhoneEditModel(); output.Cell = Phone.FetchEditModelByType(BusinessEntityTypes.Customer, customerId, PhoneTypes.Cell) ?? new PhoneEditModel(); output.Fax = Phone.FetchEditModelByType(BusinessEntityTypes.Customer, customerId, PhoneTypes.Fax) ?? new PhoneEditModel(); } return output; } } And here is a sample of the the phone returning the Edit model to be used: <!-- language: c# --> public static PhoneEditModel FetchEditModelByType(byte entityType, int entityId, byte phoneType) { return (from p in DataHelper.Context.Phones where p.EntityType == entityType && p.EntityId == entityId && p.PhoneType == phoneType select new PhoneEditModel { PhoneId = p.PhoneId, PhoneNumber = p.PhoneNumber, Extension = p.Extension }).FirstOrDefault(); } Now the page has posted back and this all needs to be save, so the Save method in my control just lets the business object handle this all: <!-- language: c# --> [Authorize(Roles = SiteRoles.SiteAdministrator + ", " + SiteRoles.Customers_Edit)] [HttpPost] public ActionResult Create(CustomerEditModel customer) { return CreateOrEdit(customer); } [Authorize(Roles = SiteRoles.SiteAdministrator + ", " + SiteRoles.Customers_Edit)] [HttpPost] public ActionResult Edit(CustomerEditModel customer) { return CreateOrEdit(customer); } private ActionResult CreateOrEdit(CustomerEditModel customer) { if (ModelState.IsValid) { SaveResult result = Customer.SaveEditModel(customer); if (result.Success) { return RedirectToAction("Index"); } else { foreach (KeyValuePair<string, string> error in result.ErrorMessages) ModelState.AddModelError(error.Key, error.Value); } } return View(customer); } And inside the Customer business object - it handles the transaction centrally and lets the Contact, Address and Phone business classes do their thing and really not worry about the transaction: <!-- language: c# --> public static SaveResult SaveEditModel(CustomerEditModel model) { SaveResult output = new SaveResult(); DataHelper.BeginTransaction(); try { Customer customer = null; if (model.CustomerId == 0) customer = new Customer(); else customer = DataHelper.Context.Customers.Single(c => c.CustomerId == model.CustomerId); if (customer == null) { output.Success = false; output.ErrorMessages.Add("CustomerNotFound", "Unable to find the requested Customer record to update"); } else { customer.CompanyName = model.CompanyName; if (model.CustomerId == 0) { customer.SiteGroup = CoreSession.CoreSettings.CurrentSiteGroup; customer.CreatedDate = DateTime.Now; customer.CreatedBy = SiteLogin.Session.ActiveUser; DataHelper.Context.Customers.AddObject(customer); } else { customer.ModifiedDate = DateTime.Now; customer.ModifiedBy = SiteLogin.Session.ActiveUser; } DataHelper.Context.SaveChanges(); SaveResult result = Address.SaveEditModel(model.MainAddress, BusinessEntityTypes.Customer, customer.CustomerId, AddressTypes.Main, false); if (!result.Success) { output.Success = false; output.ErrorMessages.Concat(result.ErrorMessages); } result = Address.SaveEditModel(model.ShippingAddress, BusinessEntityTypes.Customer, customer.CustomerId, AddressTypes.Shipping, false); if (!result.Success) { output.Success = false; output.ErrorMessages.Concat(result.ErrorMessages); } result = Phone.SaveEditModel(model.Phone, BusinessEntityTypes.Customer, customer.CustomerId, PhoneTypes.Main, false); if (!result.Success) { output.Success = false; output.ErrorMessages.Concat(result.ErrorMessages); } result = Phone.SaveEditModel(model.Fax, BusinessEntityTypes.Customer, customer.CustomerId, PhoneTypes.Fax, false); if (!result.Success) { output.Success = false; output.ErrorMessages.Concat(result.ErrorMessages); } result = Phone.SaveEditModel(model.Cell, BusinessEntityTypes.Customer, customer.CustomerId, PhoneTypes.Cell, false); if (!result.Success) { output.Success = false; output.ErrorMessages.Concat(result.ErrorMessages); } result = CustomerContact.SaveEditModel(model.MainContact, customer.CustomerId, false); if (!result.Success) { output.Success = false; output.ErrorMessages.Concat(result.ErrorMessages); } if (output.Success) { DataHelper.Context.SaveChanges(); DataHelper.CommitTransaction(); } else { DataHelper.RollbackTransaction(); } } } catch (Exception exp) { DataHelper.RollbackTransaction(); ErrorHandler.Handle(exp, true); output.Success = false; output.ErrorMessages.Add(exp.GetType().ToString(), exp.Message); output.Exceptions.Add(exp); } return output; } Notice how each Address, Phone, Etc is handled by its own business class, here is the Phone's save method - notice how it doesn't actually do the save here unless you tell it to (save is handled in the Customer's method so save is called just once for the context) <!-- language: c# --> public static SaveResult SaveEditModel(PhoneEditModel model, byte entityType, int entityId, byte phoneType, bool saveChanges) { SaveResult output = new SaveResult(); try { if (model != null) { Phone phone = null; if (model.PhoneId != 0) { phone = DataHelper.Context.Phones.Single(x => x.PhoneId == model.PhoneId); if (phone == null) { output.Success = false; output.ErrorMessages.Add("PhoneNotFound", "Unable to find the requested Phone record to update"); } } if (string.IsNullOrEmpty(model.PhoneNumber)) { if (model.PhoneId != 0 && phone != null) { DataHelper.Context.Phones.DeleteObject(phone); if (saveChanges) DataHelper.Context.SaveChanges(); } } else { if (model.PhoneId == 0) phone = new Phone(); if (phone != null) { phone.EntityType = entityType; phone.EntityId = entityId; phone.PhoneType = phoneType; phone.PhoneNumber = model.PhoneNumber; phone.Extension = model.Extension; if (model.PhoneId == 0) { phone.CreatedDate = DateTime.Now; phone.CreatedBy = SiteLogin.Session.ActiveUser; DataHelper.Context.Phones.AddObject(phone); } else { phone.ModifiedDate = DateTime.Now; phone.ModifiedBy = SiteLogin.Session.ActiveUser; } if (saveChanges) DataHelper.Context.SaveChanges(); } } } } catch (Exception exp) { ErrorHandler.Handle(exp, true); output.Success = false; output.ErrorMessages.Add(exp.GetType().ToString(), exp.Message); output.Exceptions.Add(exp); } return output; } FYI - SaveResult is just a little container class that I used to get detailed information back if a save fails: <!-- language: c# --> public class SaveResult { private bool _success = true; public bool Success { get { return _success; } set { _success = value; } } private Dictionary<string, string> _errorMessages = new Dictionary<string, string>(); public Dictionary<string, string> ErrorMessages { get { return _errorMessages; } set { _errorMessages = value; } } private List<Exception> _exceptions = new List<Exception>(); public List<Exception> Exceptions { get { return _exceptions; } set { _exceptions = value; } } } The other piece to this is the re-usable UI code for the Phone, Address, etc - which handles all the validation, etc in just one location too. So, let your thoughts flow and thanks for taking the time to read/review this huge post!
c#
asp.net-mvc
entity-framework
null
null
07/09/2012 00:33:05
too localized
Your Thoughts: Entity Framework Data Context via a DataHelper class (centralized context and transactions) === I want to get opinions on the code I have put together for a centralized DataContext via a DataHelper class that I have created to be re-used on projects. **NOTE** - there is a ton of code here, sorry about that, but I really wanted to layout out the complete approach and uses for my ideas. I'm an not saying this is the right approach, but it works for me so far (still playing with the approach, nothing in production yet, but very similar to stuff I have built over the years) and I really want to get constructive feedback from the community on what I have built to see if it is insane, great, can be improved, etc... A few thoughts I put into this: 1. Data Context needs to be stored in a common memory space, easily accessible 2. Transactions should take the same approach 3. It must be disposed of properly 4. Allows for better separation of business logic for Saving and Deleting in transactions. Here is the code for each item: 1 - First the data context stored in either the current HttpContext.Current.Items collection (so it only lives for the life of the page and only is fired up once at the first requested) or if the HttpContext doesn't exist uses a ThreadSlot (in which case that code most clean it up itself, like a console app using it...): <!-- language: c# --> public static class DataHelper { /// <summary> /// Current Data Context object in the HTTPContext or Current Thread /// </summary> public static TemplateProjectContext Context { get { TemplateProjectContext context = null; if (HttpContext.Current == null) { LocalDataStoreSlot threadSlot = Thread.GetNamedDataSlot("DataHelper.CurrentContext"); if (Thread.GetData(threadSlot) == null) { context = new TemplateProjectContext(); Thread.SetData(threadSlot, context); } else { context = (TemplateProjectContext)Thread.GetData(threadSlot); } } else { if (HttpContext.Current.Items["DataHelper.CurrentContext"] == null) { context = new TemplateProjectContext(); HttpContext.Current.Items["DataHelper.CurrentContext"] = context; } else { context = (TemplateProjectContext)HttpContext.Current.Items["DataHelper.CurrentContext"]; } } return context; } set { if (HttpContext.Current == null) { if (value == null) { Thread.FreeNamedDataSlot("DataHelper.CurrentContext"); } else { LocalDataStoreSlot threadSlot = Thread.GetNamedDataSlot("DataHelper.CurrentContext"); Thread.SetData(threadSlot, value); } } else { if (value == null) HttpContext.Current.Items.Remove("DataHelper.CurrentContext"); else HttpContext.Current.Items["DataHelper.CurrentContext"] = value; } } } ... 2 - To support transactions, I use a similar approach, and also include helper methods to Begin, Commit and Rollback: <!-- language: c# --> /// <summary> /// Current Transaction object in the HTTPContext or Current Thread /// </summary> public static DbTransaction Transaction { get { if (HttpContext.Current == null) { LocalDataStoreSlot threadSlot = Thread.GetNamedDataSlot("currentTransaction"); if (Thread.GetData(threadSlot) == null) { return null; } else { return (DbTransaction)Thread.GetData(threadSlot); } } else { if (HttpContext.Current.Items["currentTransaction"] == null) { return null; } else { return (DbTransaction)HttpContext.Current.Items["currentTransaction"]; } } } set { if (HttpContext.Current == null) { LocalDataStoreSlot threadSlot = Thread.GetNamedDataSlot("currentTransaction"); Thread.SetData(threadSlot, value); } else { HttpContext.Current.Items["currentTransaction"] = value; } } } /// <summary> /// Begins a transaction based on the common connection and transaction /// </summary> public static void BeginTransaction() { DataHelper.Transaction = DataHelper.CreateSqlTransaction(); } /// <summary> /// Creates a SqlTransaction object based on the current common connection /// </summary> /// <returns>A new SqlTransaction object for the current common connection</returns> public static DbTransaction CreateSqlTransaction() { return CreateSqlTransaction(DataHelper.Context.Connection); } /// <summary> /// Creates a SqlTransaction object for the requested connection object /// </summary> /// <param name="connection">Reference to the connection object the transaction should be created for</param> /// <returns>New transaction object for the requested connection</returns> public static DbTransaction CreateSqlTransaction(DbConnection connection) { if (connection.State != ConnectionState.Open) connection.Open(); return connection.BeginTransaction(); } /// <summary> /// Rolls back and cleans up the current common transaction /// </summary> public static void RollbackTransaction() { if (DataHelper.Transaction != null) { DataHelper.RollbackTransaction(DataHelper.Transaction); if (HttpContext.Current == null) { Thread.FreeNamedDataSlot("currentTransaction"); } else { HttpContext.Current.Items.Remove("currentTransaction"); } } } /// <summary> /// Rolls back and disposes of the requested transaction /// </summary> /// <param name="transaction">The transaction to rollback</param> public static void RollbackTransaction(DbTransaction transaction) { transaction.Rollback(); transaction.Dispose(); } /// <summary> /// Commits and cleans up the current common transaction /// </summary> public static void CommitTransaction() { if (DataHelper.Transaction != null) { DataHelper.CommitTransaction(DataHelper.Transaction); if (HttpContext.Current == null) { Thread.FreeNamedDataSlot("currentTransaction"); } else { HttpContext.Current.Items.Remove("currentTransaction"); } } } /// <summary> /// Commits and disposes of the requested transaction /// </summary> /// <param name="transaction">The transaction to commit</param> public static void CommitTransaction(DbTransaction transaction) { transaction.Commit(); transaction.Dispose(); } 3 - Clean and easy Disposal <!-- language: c# --> /// <summary> /// Cleans up the currently active connection /// </summary> public static void Dispose() { if (HttpContext.Current == null) { LocalDataStoreSlot threadSlot = Thread.GetNamedDataSlot("DataHelper.CurrentContext"); if (Thread.GetData(threadSlot) != null) { DbTransaction transaction = DataHelper.Transaction; if (transaction != null) { DataHelper.CommitTransaction(transaction); Thread.FreeNamedDataSlot("currentTransaction"); } ((TemplateProjectContext)Thread.GetData(threadSlot)).Dispose(); Thread.FreeNamedDataSlot("DataHelper.CurrentContext"); } } else { if (HttpContext.Current.Items["DataHelper.CurrentContext"] != null) { DbTransaction transaction = DataHelper.Transaction; if (transaction != null) { DataHelper.CommitTransaction(transaction); HttpContext.Current.Items.Remove("currentTransaction"); } ((TemplateProjectContext)HttpContext.Current.Items["DataHelper.CurrentContext"]).Dispose(); HttpContext.Current.Items.Remove("DataHelper.CurrentContext"); } } } 3b - I'm building this in MVC, so I have a "base" Controller class that all my controllers inherit from - this way the Context only lives from when first accessed on a request, and until the page is disposed, that way its not too "long running" <!-- language: c# --> using System.Web.Mvc; using Core.ClassLibrary; using TemplateProject.Business; using TemplateProject.ClassLibrary; namespace TemplateProject.Web.Mvc { public class SiteController : Controller { protected override void Dispose(bool disposing) { DataHelper.Dispose(); base.Dispose(disposing); } } } 4 - So I am big on business classes, separation of concerns, reusable code, all that wonderful stuff. I have an approach that I call "Entity Generic" that can be applied to any entity in my system - for example, Addresses and Phones A Customer can have 1 or more of each, along with a Store, Person, or anything really - so why add street, city, state, etc to every thing that needs it when you can just build an Address entity, that takes a Foreign Type and Key (what I call EntityType and EntityId) - then you have a re-usable business object, supporting UI control, etc - so you build it once and re-use it everywhere. This is where the centralized approach I am pushing for here really comes in handy and I think makes the code much cleaner than having to pass the current data context/transaction into every method. Take for example that you have a Page for a customer, the Model includes the Customer data, Contact, Address and a few Phone Numbers (main, fax, or cell, whatever) When getting a Customer Edit Model for the page, here is a bit of the code I have put together (see how I use the DataHelper.Context in the LINQ): <!-- language: c# --> public static CustomerEditModel FetchEditModel(int customerId) { if (customerId == 0) { CustomerEditModel model = new CustomerEditModel(); model.MainContact = new CustomerContactEditModel(); model.MainAddress = new AddressEditModel(); model.ShippingAddress = new AddressEditModel(); model.Phone = new PhoneEditModel(); model.Cell = new PhoneEditModel(); model.Fax = new PhoneEditModel(); return model; } else { var output = (from c in DataHelper.Context.Customers where c.CustomerId == customerId select new CustomerEditModel { CustomerId = c.CustomerId, CompanyName = c.CompanyName }).SingleOrDefault(); if (output != null) { output.MainContact = CustomerContact.FetchEditModelByPrimary(customerId) ?? new CustomerContactEditModel(); output.MainAddress = Address.FetchEditModelByType(BusinessEntityTypes.Customer, customerId, AddressTypes.Main) ?? new AddressEditModel(); output.ShippingAddress = Address.FetchEditModelByType(BusinessEntityTypes.Customer, customerId, AddressTypes.Shipping) ?? new AddressEditModel(); output.Phone = Phone.FetchEditModelByType(BusinessEntityTypes.Customer, customerId, PhoneTypes.Main) ?? new PhoneEditModel(); output.Cell = Phone.FetchEditModelByType(BusinessEntityTypes.Customer, customerId, PhoneTypes.Cell) ?? new PhoneEditModel(); output.Fax = Phone.FetchEditModelByType(BusinessEntityTypes.Customer, customerId, PhoneTypes.Fax) ?? new PhoneEditModel(); } return output; } } And here is a sample of the the phone returning the Edit model to be used: <!-- language: c# --> public static PhoneEditModel FetchEditModelByType(byte entityType, int entityId, byte phoneType) { return (from p in DataHelper.Context.Phones where p.EntityType == entityType && p.EntityId == entityId && p.PhoneType == phoneType select new PhoneEditModel { PhoneId = p.PhoneId, PhoneNumber = p.PhoneNumber, Extension = p.Extension }).FirstOrDefault(); } Now the page has posted back and this all needs to be save, so the Save method in my control just lets the business object handle this all: <!-- language: c# --> [Authorize(Roles = SiteRoles.SiteAdministrator + ", " + SiteRoles.Customers_Edit)] [HttpPost] public ActionResult Create(CustomerEditModel customer) { return CreateOrEdit(customer); } [Authorize(Roles = SiteRoles.SiteAdministrator + ", " + SiteRoles.Customers_Edit)] [HttpPost] public ActionResult Edit(CustomerEditModel customer) { return CreateOrEdit(customer); } private ActionResult CreateOrEdit(CustomerEditModel customer) { if (ModelState.IsValid) { SaveResult result = Customer.SaveEditModel(customer); if (result.Success) { return RedirectToAction("Index"); } else { foreach (KeyValuePair<string, string> error in result.ErrorMessages) ModelState.AddModelError(error.Key, error.Value); } } return View(customer); } And inside the Customer business object - it handles the transaction centrally and lets the Contact, Address and Phone business classes do their thing and really not worry about the transaction: <!-- language: c# --> public static SaveResult SaveEditModel(CustomerEditModel model) { SaveResult output = new SaveResult(); DataHelper.BeginTransaction(); try { Customer customer = null; if (model.CustomerId == 0) customer = new Customer(); else customer = DataHelper.Context.Customers.Single(c => c.CustomerId == model.CustomerId); if (customer == null) { output.Success = false; output.ErrorMessages.Add("CustomerNotFound", "Unable to find the requested Customer record to update"); } else { customer.CompanyName = model.CompanyName; if (model.CustomerId == 0) { customer.SiteGroup = CoreSession.CoreSettings.CurrentSiteGroup; customer.CreatedDate = DateTime.Now; customer.CreatedBy = SiteLogin.Session.ActiveUser; DataHelper.Context.Customers.AddObject(customer); } else { customer.ModifiedDate = DateTime.Now; customer.ModifiedBy = SiteLogin.Session.ActiveUser; } DataHelper.Context.SaveChanges(); SaveResult result = Address.SaveEditModel(model.MainAddress, BusinessEntityTypes.Customer, customer.CustomerId, AddressTypes.Main, false); if (!result.Success) { output.Success = false; output.ErrorMessages.Concat(result.ErrorMessages); } result = Address.SaveEditModel(model.ShippingAddress, BusinessEntityTypes.Customer, customer.CustomerId, AddressTypes.Shipping, false); if (!result.Success) { output.Success = false; output.ErrorMessages.Concat(result.ErrorMessages); } result = Phone.SaveEditModel(model.Phone, BusinessEntityTypes.Customer, customer.CustomerId, PhoneTypes.Main, false); if (!result.Success) { output.Success = false; output.ErrorMessages.Concat(result.ErrorMessages); } result = Phone.SaveEditModel(model.Fax, BusinessEntityTypes.Customer, customer.CustomerId, PhoneTypes.Fax, false); if (!result.Success) { output.Success = false; output.ErrorMessages.Concat(result.ErrorMessages); } result = Phone.SaveEditModel(model.Cell, BusinessEntityTypes.Customer, customer.CustomerId, PhoneTypes.Cell, false); if (!result.Success) { output.Success = false; output.ErrorMessages.Concat(result.ErrorMessages); } result = CustomerContact.SaveEditModel(model.MainContact, customer.CustomerId, false); if (!result.Success) { output.Success = false; output.ErrorMessages.Concat(result.ErrorMessages); } if (output.Success) { DataHelper.Context.SaveChanges(); DataHelper.CommitTransaction(); } else { DataHelper.RollbackTransaction(); } } } catch (Exception exp) { DataHelper.RollbackTransaction(); ErrorHandler.Handle(exp, true); output.Success = false; output.ErrorMessages.Add(exp.GetType().ToString(), exp.Message); output.Exceptions.Add(exp); } return output; } Notice how each Address, Phone, Etc is handled by its own business class, here is the Phone's save method - notice how it doesn't actually do the save here unless you tell it to (save is handled in the Customer's method so save is called just once for the context) <!-- language: c# --> public static SaveResult SaveEditModel(PhoneEditModel model, byte entityType, int entityId, byte phoneType, bool saveChanges) { SaveResult output = new SaveResult(); try { if (model != null) { Phone phone = null; if (model.PhoneId != 0) { phone = DataHelper.Context.Phones.Single(x => x.PhoneId == model.PhoneId); if (phone == null) { output.Success = false; output.ErrorMessages.Add("PhoneNotFound", "Unable to find the requested Phone record to update"); } } if (string.IsNullOrEmpty(model.PhoneNumber)) { if (model.PhoneId != 0 && phone != null) { DataHelper.Context.Phones.DeleteObject(phone); if (saveChanges) DataHelper.Context.SaveChanges(); } } else { if (model.PhoneId == 0) phone = new Phone(); if (phone != null) { phone.EntityType = entityType; phone.EntityId = entityId; phone.PhoneType = phoneType; phone.PhoneNumber = model.PhoneNumber; phone.Extension = model.Extension; if (model.PhoneId == 0) { phone.CreatedDate = DateTime.Now; phone.CreatedBy = SiteLogin.Session.ActiveUser; DataHelper.Context.Phones.AddObject(phone); } else { phone.ModifiedDate = DateTime.Now; phone.ModifiedBy = SiteLogin.Session.ActiveUser; } if (saveChanges) DataHelper.Context.SaveChanges(); } } } } catch (Exception exp) { ErrorHandler.Handle(exp, true); output.Success = false; output.ErrorMessages.Add(exp.GetType().ToString(), exp.Message); output.Exceptions.Add(exp); } return output; } FYI - SaveResult is just a little container class that I used to get detailed information back if a save fails: <!-- language: c# --> public class SaveResult { private bool _success = true; public bool Success { get { return _success; } set { _success = value; } } private Dictionary<string, string> _errorMessages = new Dictionary<string, string>(); public Dictionary<string, string> ErrorMessages { get { return _errorMessages; } set { _errorMessages = value; } } private List<Exception> _exceptions = new List<Exception>(); public List<Exception> Exceptions { get { return _exceptions; } set { _exceptions = value; } } } The other piece to this is the re-usable UI code for the Phone, Address, etc - which handles all the validation, etc in just one location too. So, let your thoughts flow and thanks for taking the time to read/review this huge post!
3
11,386,973
07/08/2012 21:45:00
1,461,963
06/17/2012 15:01:08
16
5
My WebPages not consistent with Firefox and Chrome
I have made a website.It worked all fine during the whole development and testing phase of over 20 days during which I viewed the pages always in firefox and they were all fine.But today suddenly I encountered a problem with firefox. The table data are not centered and the borders are not rounded as they used to be earlier.But they are all fine in Google Chrome..You can view the screenshots : [Mozilla Firefox][1] (It not used to be like this !) [Google Chrome][2] Please tell me how to fix it..I have cleared all the cache and session of firefox but still its the same [1]: http://imageshack.us/photo/my-images/13/screenshot002bl.jpg/ [2]: http://imageshack.us/photo/my-images/707/screenshot001gtd.jpg/
firefox
google-chrome
null
null
null
null
open
My WebPages not consistent with Firefox and Chrome === I have made a website.It worked all fine during the whole development and testing phase of over 20 days during which I viewed the pages always in firefox and they were all fine.But today suddenly I encountered a problem with firefox. The table data are not centered and the borders are not rounded as they used to be earlier.But they are all fine in Google Chrome..You can view the screenshots : [Mozilla Firefox][1] (It not used to be like this !) [Google Chrome][2] Please tell me how to fix it..I have cleared all the cache and session of firefox but still its the same [1]: http://imageshack.us/photo/my-images/13/screenshot002bl.jpg/ [2]: http://imageshack.us/photo/my-images/707/screenshot001gtd.jpg/
0
11,386,963
07/08/2012 21:43:51
250,560
01/14/2010 08:42:59
1,259
57
Lifting functions in scala
I want to define lifting with implicits. Suppose we have a function A => B, I want to define how to lift it to Maybe, i.e. Maybe[A] => Maybe[B]. This can be simply done with implicit conversions. However, if I want to do the same with functions with two or more parameters, I have a problem. The only solutionI know is to duplicate the code. I want to implement such lifting for arbitrary functions with any number of parameters without duplication. Is this possible in Scala?
scala
null
null
null
null
null
open
Lifting functions in scala === I want to define lifting with implicits. Suppose we have a function A => B, I want to define how to lift it to Maybe, i.e. Maybe[A] => Maybe[B]. This can be simply done with implicit conversions. However, if I want to do the same with functions with two or more parameters, I have a problem. The only solutionI know is to duplicate the code. I want to implement such lifting for arbitrary functions with any number of parameters without duplication. Is this possible in Scala?
0
11,386,964
07/08/2012 21:43:55
1,510,601
07/08/2012 21:33:08
1
0
limiting a touch event in Corona SDK
Kind of desperate here. I'm trying to make a runner game in Corona SDK and I fail in making a transition from jumping animation to running (back after a jump). local function touched(event) if(event.phase == "began")then char.accel = monster.accel + 20 char:prepare("jumping") char:play() else char:prepare("running") char:play() end end In this code if the playing person keeps touching screen the animation of jumping keeps repeating on ground, is there a way to limit the touching event in time? Also tried implementing the animations via another construction: if(onGround) then if(wasOnGround) then else monster:prepare("running") monster:play() end else monster:prepare("jumping") monster:play() end But the jump animation for some reason displays only the first frame. Any help would be immensely appreciated! Thanks in advance.
sprite
corona
coronasdk
null
null
null
open
limiting a touch event in Corona SDK === Kind of desperate here. I'm trying to make a runner game in Corona SDK and I fail in making a transition from jumping animation to running (back after a jump). local function touched(event) if(event.phase == "began")then char.accel = monster.accel + 20 char:prepare("jumping") char:play() else char:prepare("running") char:play() end end In this code if the playing person keeps touching screen the animation of jumping keeps repeating on ground, is there a way to limit the touching event in time? Also tried implementing the animations via another construction: if(onGround) then if(wasOnGround) then else monster:prepare("running") monster:play() end else monster:prepare("jumping") monster:play() end But the jump animation for some reason displays only the first frame. Any help would be immensely appreciated! Thanks in advance.
0
9,586,331
03/06/2012 15:10:40
217,844
11/24/2009 14:28:55
640
22
PostgreSQL PL/Python: call stored procedure in virtualenv
When I call a PostgreSQL PL/Python stored procedure in my Python application, it seems to be executed in a separate process running as user `postgres`. So far, this only had the side effect that I had to make my logfile writable for both myself and the database user, so application and stored procedure can both write to it. Now however, I started using [`virtualenv`][1] and added a number of `.pth` files to my `~/.virtualenvs/virt_env/lib/python2.7/site-packages/` folder that add the paths to my modules to the Python path. When the stored procedure is executed, user `postgres` is not in the same virtual environment as I am, so the stored procedure does not find my modules. I can modify `PYTHONPATH` in the [global PostgreSQL environment][2], but I have to change that every time I switch virtual environments - which is kinda against the purpose of virtualenv... How can I extend the Python path for stored procedures ? [1]: http://www.virtualenv.org/en/latest/index.html [2]: http://stackoverflow.com/questions/8032293/how-to-install-3rd-party-module-for-postgres-pl-python
python
postgresql
stored-procedures
virtualenv
plpython
null
open
PostgreSQL PL/Python: call stored procedure in virtualenv === When I call a PostgreSQL PL/Python stored procedure in my Python application, it seems to be executed in a separate process running as user `postgres`. So far, this only had the side effect that I had to make my logfile writable for both myself and the database user, so application and stored procedure can both write to it. Now however, I started using [`virtualenv`][1] and added a number of `.pth` files to my `~/.virtualenvs/virt_env/lib/python2.7/site-packages/` folder that add the paths to my modules to the Python path. When the stored procedure is executed, user `postgres` is not in the same virtual environment as I am, so the stored procedure does not find my modules. I can modify `PYTHONPATH` in the [global PostgreSQL environment][2], but I have to change that every time I switch virtual environments - which is kinda against the purpose of virtualenv... How can I extend the Python path for stored procedures ? [1]: http://www.virtualenv.org/en/latest/index.html [2]: http://stackoverflow.com/questions/8032293/how-to-install-3rd-party-module-for-postgres-pl-python
0
11,386,957
07/08/2012 21:43:12
637,541
02/28/2011 10:53:29
86
2
Is since_id a supported parameter for Order count?
To receive a list of Orders one of the many parameters you can pass to restrict results is `since_id`. I've noticed that [the Order API documentation](http://api.shopify.com/order.html) for receiving a count of Orders lists many of those same filter parameters, like `created_at_min` and co. `since_id` is not listed as one of the available URL parameters. However, at least using the `shopify_api` gem, passing `since_id` works as expected: ShopifyAPI::Order.count({since_id: 1234}) Is this an omission in the documentation, or is it an unsupported feature? Cheers, Nick
shopify
null
null
null
null
null
open
Is since_id a supported parameter for Order count? === To receive a list of Orders one of the many parameters you can pass to restrict results is `since_id`. I've noticed that [the Order API documentation](http://api.shopify.com/order.html) for receiving a count of Orders lists many of those same filter parameters, like `created_at_min` and co. `since_id` is not listed as one of the available URL parameters. However, at least using the `shopify_api` gem, passing `since_id` works as expected: ShopifyAPI::Order.count({since_id: 1234}) Is this an omission in the documentation, or is it an unsupported feature? Cheers, Nick
0
11,262,184
06/29/2012 12:55:02
791,209
06/09/2011 15:16:57
1
1
SharePoint 2010 Custom XSL View Rendering with Jquery and Ratings Field
I'm developing a SharePoint 2010 Internet facing web site with FAQ capabilities. I've got a Custom list containing ID, Title (rennamed to "Question"), Answer and Fileds for Rating. I would like writing a XSL Stylesheet in order to customize the list view rendering in the following way: - FAQ Items should be displayed as an accordion, with JQuery - Each FAQ could be rated by any users. So, I wrote this XSL : <xsl:stylesheet xmlns:x="http://www.w3.org/2001/XMLSchema" xmlns:d="http://schemas.microsoft.com/sharepoint/dsp" version="1.0" exclude-result-prefixes="xsl msxsl ddwrt js" xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime" xmlns:asp="http://schemas.microsoft.com/ASPNET/20" xmlns:__designer="http://schemas.microsoft.com/WebParts/v2/DataView/designer" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:SharePoint="Microsoft.SharePoint.WebControls" xmlns:js="urn:custom-javascript" > <xsl:import href="/_layouts/xsl/main.xsl"/> <xsl:output method="html" indent="yes"/> <xsl:template match="/"> <script type="text/javascript" language="javascript" > $(document).ready(function () { $('#faqAnswerAccordion').accordion({ autoHeight: false, collapsible: true }); }); </script> <a id="top"></a> <div id="faqAnswerAccordion"> <xsl:apply-templates select="//Row" mode="Item" /> </div> </xsl:template> <xsl:template mode="Item" match="Row[../../@TemplateType='100']"> <xsl:param name="Fields" select="."/> <xsl:param name="Collapse" select="."/> <xsl:param name="Position" select="1"/> <xsl:param name="Last" select="1"/> <xsl:variable name="thisNode" select="."/> <h3 id="header_{@ID}"> <a id="{@ID}" href="#" ><xsl:value-of select="@Title" disable-output-escaping="yes"/></a> </h3> <div> <p> <xsl:value-of select="@Answer" disable-output-escaping="yes"/> </p> <p> Please rate this FAQ: <xsl:apply-templates select="$Fields[@Name='AverageRating']" mode="PrintField"> <xsl:with-param name="thisNode" select="."/> <xsl:with-param name="Position" select="$Position"/> </xsl:apply-templates> </p> </div> </xsl:template> </xsl:stylesheet> With that stylesheet, the Jquery Accordion is not generated, but rating star are present. If I replace the following template definition <xsl:template match="/"> By <xsl:template match="View"> So, Jquery Accordion work fine, but the Rating Stars are not. Any Ideas ? Thank a lot.
sharepoint
xslt
sharepoint2010
null
null
null
open
SharePoint 2010 Custom XSL View Rendering with Jquery and Ratings Field === I'm developing a SharePoint 2010 Internet facing web site with FAQ capabilities. I've got a Custom list containing ID, Title (rennamed to "Question"), Answer and Fileds for Rating. I would like writing a XSL Stylesheet in order to customize the list view rendering in the following way: - FAQ Items should be displayed as an accordion, with JQuery - Each FAQ could be rated by any users. So, I wrote this XSL : <xsl:stylesheet xmlns:x="http://www.w3.org/2001/XMLSchema" xmlns:d="http://schemas.microsoft.com/sharepoint/dsp" version="1.0" exclude-result-prefixes="xsl msxsl ddwrt js" xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime" xmlns:asp="http://schemas.microsoft.com/ASPNET/20" xmlns:__designer="http://schemas.microsoft.com/WebParts/v2/DataView/designer" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:SharePoint="Microsoft.SharePoint.WebControls" xmlns:js="urn:custom-javascript" > <xsl:import href="/_layouts/xsl/main.xsl"/> <xsl:output method="html" indent="yes"/> <xsl:template match="/"> <script type="text/javascript" language="javascript" > $(document).ready(function () { $('#faqAnswerAccordion').accordion({ autoHeight: false, collapsible: true }); }); </script> <a id="top"></a> <div id="faqAnswerAccordion"> <xsl:apply-templates select="//Row" mode="Item" /> </div> </xsl:template> <xsl:template mode="Item" match="Row[../../@TemplateType='100']"> <xsl:param name="Fields" select="."/> <xsl:param name="Collapse" select="."/> <xsl:param name="Position" select="1"/> <xsl:param name="Last" select="1"/> <xsl:variable name="thisNode" select="."/> <h3 id="header_{@ID}"> <a id="{@ID}" href="#" ><xsl:value-of select="@Title" disable-output-escaping="yes"/></a> </h3> <div> <p> <xsl:value-of select="@Answer" disable-output-escaping="yes"/> </p> <p> Please rate this FAQ: <xsl:apply-templates select="$Fields[@Name='AverageRating']" mode="PrintField"> <xsl:with-param name="thisNode" select="."/> <xsl:with-param name="Position" select="$Position"/> </xsl:apply-templates> </p> </div> </xsl:template> </xsl:stylesheet> With that stylesheet, the Jquery Accordion is not generated, but rating star are present. If I replace the following template definition <xsl:template match="/"> By <xsl:template match="View"> So, Jquery Accordion work fine, but the Rating Stars are not. Any Ideas ? Thank a lot.
0
11,262,186
06/29/2012 12:55:19
966,898
09/27/2011 11:12:32
91
9
how to start and close console application?
console application: Dim myno As Integer = 1010 Console.WriteLine(Convert.ToString(myno)) Dim sw As New StreamWriter("filename.txt", True) sw.Write(Convert.ToString(myno)) sw.Flush() sw.Close() Console.ReadLine() windows application: Dim mm As New System.Diagnostics.Process Dim info As New System.Diagnostics.ProcessStartInfo(Application.StartupPath & "\ConsoleApplication1.exe") mm.StartInfo = info mm.Start() Dim f As New FileInfo(Application.StartupPath & "\filename.txt") Dim s As StreamReader = f.OpenText TextBox1.Text = s.ReadToEnd If Not String.IsNullOrEmpty(TextBox1.Text) Then mm.Kill() End If but C app dont write in textfile and W app start but dont close, thanks in advanced
vb.net
console-application
null
null
null
null
open
how to start and close console application? === console application: Dim myno As Integer = 1010 Console.WriteLine(Convert.ToString(myno)) Dim sw As New StreamWriter("filename.txt", True) sw.Write(Convert.ToString(myno)) sw.Flush() sw.Close() Console.ReadLine() windows application: Dim mm As New System.Diagnostics.Process Dim info As New System.Diagnostics.ProcessStartInfo(Application.StartupPath & "\ConsoleApplication1.exe") mm.StartInfo = info mm.Start() Dim f As New FileInfo(Application.StartupPath & "\filename.txt") Dim s As StreamReader = f.OpenText TextBox1.Text = s.ReadToEnd If Not String.IsNullOrEmpty(TextBox1.Text) Then mm.Kill() End If but C app dont write in textfile and W app start but dont close, thanks in advanced
0
11,262,190
06/29/2012 12:55:48
298,288
03/21/2010 04:18:08
969
11
Change x axis labeling independent of x values?
Imagine I am plotting e.g. this: plot(1:1500,1:1500) This will look like the image below, with the x axis starting at 0 and going up to 1500. Now I don't want to have that labeling, but instead the x axis labeling shall start with e.g. 1 and then end at 151 (increase by 1/10 for every point on the x axis, additionaly on offset of 1). I just want to change the labeling of the x axis, I don't want to change the x input vector to the plot function nor do I want to plot other points. I just want the x labeling to start at a different offset and increase in another step size, independent of the x values passed to the plot function. Is that possible? How? It would make some things easier for me. Thanks for any hint! ![enter image description here][1] [1]: http://i.stack.imgur.com/bsew4.png
matlab
axis
axis-labels
null
null
null
open
Change x axis labeling independent of x values? === Imagine I am plotting e.g. this: plot(1:1500,1:1500) This will look like the image below, with the x axis starting at 0 and going up to 1500. Now I don't want to have that labeling, but instead the x axis labeling shall start with e.g. 1 and then end at 151 (increase by 1/10 for every point on the x axis, additionaly on offset of 1). I just want to change the labeling of the x axis, I don't want to change the x input vector to the plot function nor do I want to plot other points. I just want the x labeling to start at a different offset and increase in another step size, independent of the x values passed to the plot function. Is that possible? How? It would make some things easier for me. Thanks for any hint! ![enter image description here][1] [1]: http://i.stack.imgur.com/bsew4.png
0
11,262,168
06/29/2012 12:54:03
223,686
12/03/2009 09:23:05
1,360
55
How can I execute a method of a class that has been uploaded?
The goal is to implement a web application that can execute methods of `.class` files that has been uploaded. The uploaded class file is available as a `byte[]`. The public class in this `.class` file implements a specific interface. After the upload, I'd like to call a method (interface implementation). Is there a way to do so in a running java application? If yes, how? *Btw. I'm aware of the security risks.*
java
reflection
classloader
null
null
null
open
How can I execute a method of a class that has been uploaded? === The goal is to implement a web application that can execute methods of `.class` files that has been uploaded. The uploaded class file is available as a `byte[]`. The public class in this `.class` file implements a specific interface. After the upload, I'd like to call a method (interface implementation). Is there a way to do so in a running java application? If yes, how? *Btw. I'm aware of the security risks.*
0
11,262,170
06/29/2012 12:54:11
1,459,924
06/15/2012 23:33:43
10
0
Getting the CurrentUserID from Websecurity directly after login
I have a form where the user can register for an account (it is the default template of VS11) and after everything is filled in and the user clicks to register, it creates the account (which works great). After this step I want to get the UserID which he was assigned, but it doesn't work. I've put a breakpoint there to see the values of both "currentuserid" and "WebSecurity.CurrentUserId" but they only have a -1 value. Next step is the user gets redirected to the next page, and on that page these functions work. I thought I would be able to get the UserID as the user has already gotten logged in in the first line of the code I provided here. So my question is, why doesn't it work here? I am very noobish with this, so I am obviously missing something. WebSecurity.Login(username, password); int currentuserid = WebSecurity.CurrentUserId; <here I wish to update other tables but I need the user ID> Response.Redirect("~/Welcome.cshtml"); Thanks!
asp.net
web-security
visual-studio-2012
null
null
null
open
Getting the CurrentUserID from Websecurity directly after login === I have a form where the user can register for an account (it is the default template of VS11) and after everything is filled in and the user clicks to register, it creates the account (which works great). After this step I want to get the UserID which he was assigned, but it doesn't work. I've put a breakpoint there to see the values of both "currentuserid" and "WebSecurity.CurrentUserId" but they only have a -1 value. Next step is the user gets redirected to the next page, and on that page these functions work. I thought I would be able to get the UserID as the user has already gotten logged in in the first line of the code I provided here. So my question is, why doesn't it work here? I am very noobish with this, so I am obviously missing something. WebSecurity.Login(username, password); int currentuserid = WebSecurity.CurrentUserId; <here I wish to update other tables but I need the user ID> Response.Redirect("~/Welcome.cshtml"); Thanks!
0
11,262,171
06/29/2012 12:54:14
1,025,976
11/02/2011 15:42:34
2
2
How to Create a magnifier view on top of a TableView to see the Celltext Magnified
Can Any help me out how to create a magnifier view, i want to place that middle of the Table View on top of it,..So when i scroll the table,when the text comes to the middle of that point,the table celltext should get maginified. Any Help Can be greatly Appreciated...Thank you
uitableview
uitableviewcell
cgcontext
magnification
null
null
open
How to Create a magnifier view on top of a TableView to see the Celltext Magnified === Can Any help me out how to create a magnifier view, i want to place that middle of the Table View on top of it,..So when i scroll the table,when the text comes to the middle of that point,the table celltext should get maginified. Any Help Can be greatly Appreciated...Thank you
0
11,262,193
06/29/2012 12:56:03
1,426,232
05/30/2012 14:13:28
4
0
How to handle mouse and key events in android for remote PC?
I am implementing the android client application for windows pc. Where the server program is written in java. The desktop images are rendered in android screen using the ImageView tag. So how to capture the touch events[touched at particular folder to open the folder at remote PC] and send the same to server. Could you please help me. Regards, Mini.
android
null
null
null
null
null
open
How to handle mouse and key events in android for remote PC? === I am implementing the android client application for windows pc. Where the server program is written in java. The desktop images are rendered in android screen using the ImageView tag. So how to capture the touch events[touched at particular folder to open the folder at remote PC] and send the same to server. Could you please help me. Regards, Mini.
0
11,262,194
06/29/2012 12:56:05
677,845
12/22/2010 19:21:55
288
4
PHP: What does "a or b" expression mean?
Came across this code: <?php require_once 'HTTP/Session/Container/DB.php'; $s = new HTTP_Session_Container_DB('mysql://user:password@localhost/db'); ini_get('session.auto_start') or session_start(); //HERE. ?? ?> ini_get('session.auto_start') or session_start(); What does this kind of express mean in PHP? [ a OR b] ? Thanks.
php
php5
null
null
null
null
open
PHP: What does "a or b" expression mean? === Came across this code: <?php require_once 'HTTP/Session/Container/DB.php'; $s = new HTTP_Session_Container_DB('mysql://user:password@localhost/db'); ini_get('session.auto_start') or session_start(); //HERE. ?? ?> ini_get('session.auto_start') or session_start(); What does this kind of express mean in PHP? [ a OR b] ? Thanks.
0
11,262,199
06/29/2012 12:56:22
1,045,704
11/14/2011 13:49:58
1,126
35
How to achieve this substring?
There is a string having a dot form like this : `1.1.3` I want to get the `substring` of this string from the beginning untill the position of the last "." - 1 , that is `1.1` . How to achieve that ?
php
null
null
null
null
06/29/2012 13:02:21
not a real question
How to achieve this substring? === There is a string having a dot form like this : `1.1.3` I want to get the `substring` of this string from the beginning untill the position of the last "." - 1 , that is `1.1` . How to achieve that ?
1
11,262,202
06/29/2012 12:56:37
1,374,181
05/04/2012 05:37:00
69
0
How to stop video after specific time period?
I want my app to stop playing video after specific time period (say 30 sec) & show me a menu of some options i.e. to collapse media-element at the same time. I don't how to do this. Please guide me. Thanks in advance.
windows-phone-7
null
null
null
null
null
open
How to stop video after specific time period? === I want my app to stop playing video after specific time period (say 30 sec) & show me a menu of some options i.e. to collapse media-element at the same time. I don't how to do this. Please guide me. Thanks in advance.
0
11,588,046
07/20/2012 23:09:15
1,541,943
07/20/2012 23:03:15
1
0
How to pass value from the database when a table cell is selected
I am really new in the programming field and I need your help in completing my Master project . I have some URL stored in the database and I am retrieving it in a table view with a navigation controller. When I click on a table cell I want that URL value to go in my detail view conteoller and it opens a uiwebview . The URL values in the database are coming when I am scanning a barcode , that is these values can be anything. Can you help me guys , if you want I can paste all the code in here . Anyone ?
objective-c
xcode
null
null
null
null
open
How to pass value from the database when a table cell is selected === I am really new in the programming field and I need your help in completing my Master project . I have some URL stored in the database and I am retrieving it in a table view with a navigation controller. When I click on a table cell I want that URL value to go in my detail view conteoller and it opens a uiwebview . The URL values in the database are coming when I am scanning a barcode , that is these values can be anything. Can you help me guys , if you want I can paste all the code in here . Anyone ?
0
11,588,048
07/20/2012 23:09:40
222,403
12/01/2009 20:24:42
2,090
166
Refinerycms error when trying to acccess the dashboard
I'm trying to access the dashboard in my refinerycms app and i'm getting the following error: NoMethodError in Refinery/admin/dashboard#index Showing /var/www/vhosts/tomstestsite.us/PersonalTrainingKT/app/views/refinery/admin/dashboard/_recent_activity.html.erb where line #4 raised: undefined method `edit_group_fitness_classes_admin_group_fitness_clas_path' for #<ActionDispatch::Routing::RoutesProxy:0x0000000f11bfc0> Extracted source (around line #4): 1: <div id='recent_activity'> 2: <h2><%= t('.latest_activity') %></h2> 3: <% if (activity = @recent_activity.collect { |a| 4: activity_message_for(a) 5: }.reject(&:blank?)).present? %> 6: <ul class='clickable'> 7: <% activity.each do |message| %> Trace of template inclusion: app/views/refinery/admin/dashboard/_records.html.erb, app/views/refinery/admin/dashboard/index.html.erb Rails.root: /var/www/vhosts/tomstestsite.us/PersonalTrainingKT Application Trace | Framework Trace | Full Trace app/views/refinery/admin/dashboard/_recent_activity.html.erb:4:in `block in _app_views_refinery_admin_dashboard__recent_activity_html_erb__1848110473525801039_122287880' app/views/refinery/admin/dashboard/_recent_activity.html.erb:3:in `collect' app/views/refinery/admin/dashboard/_recent_activity.html.erb:3:in `_app_views_refinery_admin_dashboard__recent_activity_html_erb__1848110473525801039_122287880' app/views/refinery/admin/dashboard/_records.html.erb:1:in `_app_views_refinery_admin_dashboard__records_html_erb__4550726393400955740_116529040' app/views/refinery/admin/dashboard/index.html.erb:3:in `_app_views_refinery_admin_dashboard_index_html_erb__2977375506195649235_124556040' I'm guessing that changing edit_group_fitness_classes_admin_group_fitness_clas_path to edit_group_fitness_classes_admin_group_fitness_class_path will fix my problem, but I can't figure out where it's calling that path so i can change it. group fitness classes is an engine i created.
ruby-on-rails
ruby
ruby-on-rails-3
refinerycms
null
null
open
Refinerycms error when trying to acccess the dashboard === I'm trying to access the dashboard in my refinerycms app and i'm getting the following error: NoMethodError in Refinery/admin/dashboard#index Showing /var/www/vhosts/tomstestsite.us/PersonalTrainingKT/app/views/refinery/admin/dashboard/_recent_activity.html.erb where line #4 raised: undefined method `edit_group_fitness_classes_admin_group_fitness_clas_path' for #<ActionDispatch::Routing::RoutesProxy:0x0000000f11bfc0> Extracted source (around line #4): 1: <div id='recent_activity'> 2: <h2><%= t('.latest_activity') %></h2> 3: <% if (activity = @recent_activity.collect { |a| 4: activity_message_for(a) 5: }.reject(&:blank?)).present? %> 6: <ul class='clickable'> 7: <% activity.each do |message| %> Trace of template inclusion: app/views/refinery/admin/dashboard/_records.html.erb, app/views/refinery/admin/dashboard/index.html.erb Rails.root: /var/www/vhosts/tomstestsite.us/PersonalTrainingKT Application Trace | Framework Trace | Full Trace app/views/refinery/admin/dashboard/_recent_activity.html.erb:4:in `block in _app_views_refinery_admin_dashboard__recent_activity_html_erb__1848110473525801039_122287880' app/views/refinery/admin/dashboard/_recent_activity.html.erb:3:in `collect' app/views/refinery/admin/dashboard/_recent_activity.html.erb:3:in `_app_views_refinery_admin_dashboard__recent_activity_html_erb__1848110473525801039_122287880' app/views/refinery/admin/dashboard/_records.html.erb:1:in `_app_views_refinery_admin_dashboard__records_html_erb__4550726393400955740_116529040' app/views/refinery/admin/dashboard/index.html.erb:3:in `_app_views_refinery_admin_dashboard_index_html_erb__2977375506195649235_124556040' I'm guessing that changing edit_group_fitness_classes_admin_group_fitness_clas_path to edit_group_fitness_classes_admin_group_fitness_class_path will fix my problem, but I can't figure out where it's calling that path so i can change it. group fitness classes is an engine i created.
0
11,588,050
07/20/2012 23:09:42
785,259
06/06/2011 01:02:00
495
0
Two-step to One-step initialization and erro handling
This may seem like an odd question. Im currently moving certain objects from a two-step to a one-step initialiation scheme. Basically moving what was done in the .initialize() .terminate() member functions into the constructors and destructors. My issue is that, it is important to know whether or not these classes initialized certain attributes correctly that depend on external factors. An example is my Window class which creates a WinAPI window. Previously using the two step method I would have .initialize() return a boolean of whether or not the window was created properly. if(myWindow.initialize()) { // proceed with application } else { // exit } Is there anyway to relay this information from the constructor without creating and having to call a second method, such as didMyWindowInitializeCorrectly()? At first I was hoping something along the lines of if(Window *myWindow = new Window) { // proceed with application } else { // exit } But this won't work because the Window object will still instantiate even though the window creation failed. Is the only solution to have the constructor throw an exception and then catch it and proceed? I've looked at a lot of threads and people's opinions of C++ exceptions seems pretty split so im unsure of what is the best approach. Is there anyway to handle this situation with an if statement?
c++
exception-handling
constructor
initialization
null
null
open
Two-step to One-step initialization and erro handling === This may seem like an odd question. Im currently moving certain objects from a two-step to a one-step initialiation scheme. Basically moving what was done in the .initialize() .terminate() member functions into the constructors and destructors. My issue is that, it is important to know whether or not these classes initialized certain attributes correctly that depend on external factors. An example is my Window class which creates a WinAPI window. Previously using the two step method I would have .initialize() return a boolean of whether or not the window was created properly. if(myWindow.initialize()) { // proceed with application } else { // exit } Is there anyway to relay this information from the constructor without creating and having to call a second method, such as didMyWindowInitializeCorrectly()? At first I was hoping something along the lines of if(Window *myWindow = new Window) { // proceed with application } else { // exit } But this won't work because the Window object will still instantiate even though the window creation failed. Is the only solution to have the constructor throw an exception and then catch it and proceed? I've looked at a lot of threads and people's opinions of C++ exceptions seems pretty split so im unsure of what is the best approach. Is there anyway to handle this situation with an if statement?
0
11,588,051
07/20/2012 23:10:08
1,541,944
07/20/2012 23:03:35
1
0
How to overflow background Image off screen
Right now I'm coding a site where all of the content is positioned in the center of the page. I want a little plane icon to be positioned with its trail running off the right side of the screen. See link: http://lukeclum.com/projecttest/regline/index.html However, the image keeps creating a horizontal scroll bar for the rest of the image. How do i can i place an image where the remaining part of the image is only visible upon resizing the browser. See attached code: .home-planepath { position:absolute; left:50%; width:100%; height:62px; z-index: 1; margin-top:442px; margin-left: -440px; overflow: hidden; background:url(images/home-planepath.png) no-repeat; }
css
image
position
width
overflow
null
open
How to overflow background Image off screen === Right now I'm coding a site where all of the content is positioned in the center of the page. I want a little plane icon to be positioned with its trail running off the right side of the screen. See link: http://lukeclum.com/projecttest/regline/index.html However, the image keeps creating a horizontal scroll bar for the rest of the image. How do i can i place an image where the remaining part of the image is only visible upon resizing the browser. See attached code: .home-planepath { position:absolute; left:50%; width:100%; height:62px; z-index: 1; margin-top:442px; margin-left: -440px; overflow: hidden; background:url(images/home-planepath.png) no-repeat; }
0
11,588,053
07/20/2012 23:10:20
1,162,385
01/21/2012 14:36:59
51
0
Active and inactive headings on accordion
I have made this accordion to teach myself some jQuery with a help of a user from stack overflow: http://jsfiddle.net/LQsV5/ I was wondering how I could add the feature to change the tabs, so when the tab is closed, the background picture of the heading is grey and when the accordion is open, it stays like it is in the above example? Thank you.
jquery
html
null
null
null
null
open
Active and inactive headings on accordion === I have made this accordion to teach myself some jQuery with a help of a user from stack overflow: http://jsfiddle.net/LQsV5/ I was wondering how I could add the feature to change the tabs, so when the tab is closed, the background picture of the heading is grey and when the accordion is open, it stays like it is in the above example? Thank you.
0
11,573,296
07/20/2012 05:18:15
1,114,546
12/24/2011 12:07:44
10
0
How to clear the IOException Error in j2me midlet when connect http and send sms vias?
i am working on j2me Mobile application part.i have to send message using http connection and sms format(using sms gateway).when i am trying to do this,the **java.io.IOException: Resource limit exceeded for file handles** is throwing in my console. please help me , how to avoid this?This is my connectivity code: public boolean sendViaHTTP(String message) { System.out.println("enter HTTP Via"); HttpConnection httpConn = null; String url = "http://xxx.com/test.php"; System.out.println("URL="+url); InputStream is = null; OutputStream os = null; try { // Open an HTTP Connection object httpConn = (HttpConnection)Connector.open(url); // Setup HTTP Request to POST httpConn.setRequestMethod(HttpConnection.POST); httpConn.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Confirguration/CLDC-2.0"); httpConn.setRequestProperty("Accept_Language","en-US"); //Content-Type is must to pass parameters in POST Request httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); String value = System.getProperty("com.nokia.network.access"); os = httpConn.openOutputStream(); String params; params = "message=" + message; os.write(params.getBytes());// input writes in server side // Read Response from the Server StringBuffer sb = new StringBuffer(); is = httpConn.openDataInputStream(); int chr; while ((chr = is.read()) != -1) sb.append((char) chr); Response = sb.toString(); //switchDisplayable("", getForm()); //System.out.println("REsponse="+Response); } catch(IOException ex) { System.out.println(ex); return false; } catch (Exception ex) { System.out.println(ex); return false; } finally { try { if(is!= null) is.close(); if(os != null) os.close(); if(httpConn != null) httpConn.close(); } catch (Exception ex) { System.out.println(ex); } } return true; }
java
java-me
midp
null
null
null
open
How to clear the IOException Error in j2me midlet when connect http and send sms vias? === i am working on j2me Mobile application part.i have to send message using http connection and sms format(using sms gateway).when i am trying to do this,the **java.io.IOException: Resource limit exceeded for file handles** is throwing in my console. please help me , how to avoid this?This is my connectivity code: public boolean sendViaHTTP(String message) { System.out.println("enter HTTP Via"); HttpConnection httpConn = null; String url = "http://xxx.com/test.php"; System.out.println("URL="+url); InputStream is = null; OutputStream os = null; try { // Open an HTTP Connection object httpConn = (HttpConnection)Connector.open(url); // Setup HTTP Request to POST httpConn.setRequestMethod(HttpConnection.POST); httpConn.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Confirguration/CLDC-2.0"); httpConn.setRequestProperty("Accept_Language","en-US"); //Content-Type is must to pass parameters in POST Request httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); String value = System.getProperty("com.nokia.network.access"); os = httpConn.openOutputStream(); String params; params = "message=" + message; os.write(params.getBytes());// input writes in server side // Read Response from the Server StringBuffer sb = new StringBuffer(); is = httpConn.openDataInputStream(); int chr; while ((chr = is.read()) != -1) sb.append((char) chr); Response = sb.toString(); //switchDisplayable("", getForm()); //System.out.println("REsponse="+Response); } catch(IOException ex) { System.out.println(ex); return false; } catch (Exception ex) { System.out.println(ex); return false; } finally { try { if(is!= null) is.close(); if(os != null) os.close(); if(httpConn != null) httpConn.close(); } catch (Exception ex) { System.out.println(ex); } } return true; }
0
11,586,730
07/20/2012 20:46:45
1,539,378
07/19/2012 23:42:52
1
0
Constructing a predictive algorithm (NN?) with various amounts of features for each training point in R
I am relatively new to machine learning but have been trying to train an algorithm to predict if an account will close or not using thousands of data points and many features (I will post an example of data below). I am using data from the month before the account closed but the problem is that accounts have been around for different amounts of time. So, whereas for one account I might only have performance data up to 1 year, for another account I might have 1 month, 3 month, 1 year, 3 year, 5 year and even 10 year. I am looking for some help on how I can build an algorithm that incorporates the different amounts of data for each account. I was thinking about using a neural net because I have always been interested in them but I am open to any suggestions. I can really just use help in any way on this problem. There were 94 features but I cut it down to 19 to start playing around with it. I will gladly accept any advice on how to approach this problem. [1]: http://i.stack.imgur.com/y1VVj.jpg
performance
r
machine-learning
classification
finance
07/21/2012 05:57:13
off topic
Constructing a predictive algorithm (NN?) with various amounts of features for each training point in R === I am relatively new to machine learning but have been trying to train an algorithm to predict if an account will close or not using thousands of data points and many features (I will post an example of data below). I am using data from the month before the account closed but the problem is that accounts have been around for different amounts of time. So, whereas for one account I might only have performance data up to 1 year, for another account I might have 1 month, 3 month, 1 year, 3 year, 5 year and even 10 year. I am looking for some help on how I can build an algorithm that incorporates the different amounts of data for each account. I was thinking about using a neural net because I have always been interested in them but I am open to any suggestions. I can really just use help in any way on this problem. There were 94 features but I cut it down to 19 to start playing around with it. I will gladly accept any advice on how to approach this problem. [1]: http://i.stack.imgur.com/y1VVj.jpg
2
11,588,057
07/20/2012 23:10:30
1,260,310
03/09/2012 22:36:04
235
7
javascript getelementbyid form encytype
I am trying to write some markup to a div using javascript and it is not accepting the following markup <form action="upload.php" method="post" enctype="multipart/form-data">. Is there something about that enctype that could be causing the problem or do I have a typo? Thanks for any suggestions. Jsfiddle http://jsfiddle.net/smkqW/6/ Does not work with above text in; works if you take it out. javascript <a href="javascript:void(0)" onclick="takePic('1');">Track Progress</a><div id = "puthere"></div> html function takePic(type){ alert(type); var text = 'hello world<form action="upload.php" method="post" enctype="multipart/form-data">'; var target = 'puthere'; document.getElementById(target).innerHTML = text; //return false;
javascript
upload
enctype
null
null
null
open
javascript getelementbyid form encytype === I am trying to write some markup to a div using javascript and it is not accepting the following markup <form action="upload.php" method="post" enctype="multipart/form-data">. Is there something about that enctype that could be causing the problem or do I have a typo? Thanks for any suggestions. Jsfiddle http://jsfiddle.net/smkqW/6/ Does not work with above text in; works if you take it out. javascript <a href="javascript:void(0)" onclick="takePic('1');">Track Progress</a><div id = "puthere"></div> html function takePic(type){ alert(type); var text = 'hello world<form action="upload.php" method="post" enctype="multipart/form-data">'; var target = 'puthere'; document.getElementById(target).innerHTML = text; //return false;
0
11,627,856
07/24/2012 09:24:26
803,518
06/17/2011 15:34:51
1,111
68
File System Watcher only checks complete files
I'm setting up a system which monitors a directory for images and then processes them. From time to time PDFs may be dropped into the watched directory, in this case I convert them to an image and continue as normal. However once the image has been processed it moves it into a complete folder but if the PDF to image conversion isn't complete then my code throws an IO Exception because it can't move a file which is being used by another process. Is it possible when specifying the notify filters to only process "complete" files. By complete I mean it has finished copying, moving, or being created. I am guessing that this conflict occurs because the worker than handles the files is running on different threads. public void Start() { if (string.IsNullOrWhiteSpace(this.fileDirectory)) { throw new Exception("No file directory specified."); } // watch for any type of file activity const NotifyFilters Filters = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.CreationTime; // set up the watcher based on the app.config file var watcher = new FileSystemWatcher() { Path = this.fileDirectory, NotifyFilter = Filters, EnableRaisingEvents = true }; // event handler for new files watcher.Created += this.NewFileCreated; // file system watcher doesn't "see" current files, manually get these this.ProcessExistingFiles(); } private void NewFileCreated(object source, FileSystemEventArgs e) { Task.Run(() => this.ProcessFile(e.FullPath)); } private void ProcessExistingFiles() { var files = Directory.GetFiles(this.fileDirectory); Parallel.ForEach(files, this.ProcessFile); }
c#
multithreading
file-io
null
null
null
open
File System Watcher only checks complete files === I'm setting up a system which monitors a directory for images and then processes them. From time to time PDFs may be dropped into the watched directory, in this case I convert them to an image and continue as normal. However once the image has been processed it moves it into a complete folder but if the PDF to image conversion isn't complete then my code throws an IO Exception because it can't move a file which is being used by another process. Is it possible when specifying the notify filters to only process "complete" files. By complete I mean it has finished copying, moving, or being created. I am guessing that this conflict occurs because the worker than handles the files is running on different threads. public void Start() { if (string.IsNullOrWhiteSpace(this.fileDirectory)) { throw new Exception("No file directory specified."); } // watch for any type of file activity const NotifyFilters Filters = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.CreationTime; // set up the watcher based on the app.config file var watcher = new FileSystemWatcher() { Path = this.fileDirectory, NotifyFilter = Filters, EnableRaisingEvents = true }; // event handler for new files watcher.Created += this.NewFileCreated; // file system watcher doesn't "see" current files, manually get these this.ProcessExistingFiles(); } private void NewFileCreated(object source, FileSystemEventArgs e) { Task.Run(() => this.ProcessFile(e.FullPath)); } private void ProcessExistingFiles() { var files = Directory.GetFiles(this.fileDirectory); Parallel.ForEach(files, this.ProcessFile); }
0
11,627,857
07/24/2012 09:24:34
1,503,205
07/05/2012 07:20:59
1
0
My rails app runs too slow. why? please help me
Here's code. Can anyone find why? This program is to show photos from one's friend's albums. I think this program uses facebook api 3times, so there might be important point. But i dont have any idea about things instead of this code. graph = Koala::Facebook::API.new(session[:access_token]) freegraph = Koala::Facebook::API.new friends = graph.get_object("me/friends") friendsIds = Array.new friends.each do |f| friendsIds << f["id"] end fsinfo = freegraph.get_objects(friendsIds) @realFriends = Array.new fsinfo.each do |f| if f[1]["gender"].present? && (f[1]["gender"] != "male") @realFriends << f[1] end end rFids = @realFriends.map do |rF| rF["id"] end albums = graph.get_object("albums?ids="+rFids.join(",")) album_ids = Array.new albums.each do |user| album_ids += user[1]["data"].map do |a| a["id"] end end randAlbumIds = Array.new 20.times do randAlbumIds << album_ids.at(rand(album_ids.count)) end imgList = graph.get_object("photos?ids="+randAlbumIds.join(",")) imgObjs = Array.new imgList.each do |img| imgObjs += img[1]["data"] end if params[:tags].present? @photos = imgObjs.select do |i| i["tags"].present? end else @photos = imgObjs end
ruby-on-rails
facebook
algorithm
koala
null
null
open
My rails app runs too slow. why? please help me === Here's code. Can anyone find why? This program is to show photos from one's friend's albums. I think this program uses facebook api 3times, so there might be important point. But i dont have any idea about things instead of this code. graph = Koala::Facebook::API.new(session[:access_token]) freegraph = Koala::Facebook::API.new friends = graph.get_object("me/friends") friendsIds = Array.new friends.each do |f| friendsIds << f["id"] end fsinfo = freegraph.get_objects(friendsIds) @realFriends = Array.new fsinfo.each do |f| if f[1]["gender"].present? && (f[1]["gender"] != "male") @realFriends << f[1] end end rFids = @realFriends.map do |rF| rF["id"] end albums = graph.get_object("albums?ids="+rFids.join(",")) album_ids = Array.new albums.each do |user| album_ids += user[1]["data"].map do |a| a["id"] end end randAlbumIds = Array.new 20.times do randAlbumIds << album_ids.at(rand(album_ids.count)) end imgList = graph.get_object("photos?ids="+randAlbumIds.join(",")) imgObjs = Array.new imgList.each do |img| imgObjs += img[1]["data"] end if params[:tags].present? @photos = imgObjs.select do |i| i["tags"].present? end else @photos = imgObjs end
0
11,627,859
07/24/2012 09:24:39
1,548,133
07/24/2012 09:07:50
1
0
Return to main latex file after correcting error in GVim
Using the vim-latexsuite for Gvim, I am editing a fairly large document. It contains of a main document that contains \begin{document}, \end{document} etc. in between there is a lot of sections that are writeen in another documents and imported with \input{blahblah} the problem is that when i compile using \ll, and there is an error in one of the imported documents, this document is opened in the current tab, along with the errorlog etc. This is of course done so that I can correct the error easily. ... but after correcting the error, I am now positioned in another document in the tab that was previously my maindocument. This document does not have the preamble and therefore I have to reopen the main document in order to recompile to see if my correction works. It seems to me that i should be easy to recompile on the spot after I have corrected the error. How can I do that?
vim
macros
latex
recompile
null
null
open
Return to main latex file after correcting error in GVim === Using the vim-latexsuite for Gvim, I am editing a fairly large document. It contains of a main document that contains \begin{document}, \end{document} etc. in between there is a lot of sections that are writeen in another documents and imported with \input{blahblah} the problem is that when i compile using \ll, and there is an error in one of the imported documents, this document is opened in the current tab, along with the errorlog etc. This is of course done so that I can correct the error easily. ... but after correcting the error, I am now positioned in another document in the tab that was previously my maindocument. This document does not have the preamble and therefore I have to reopen the main document in order to recompile to see if my correction works. It seems to me that i should be easy to recompile on the spot after I have corrected the error. How can I do that?
0
11,627,860
07/24/2012 09:24:42
351,545
05/27/2010 03:03:07
498
6
Is it possible to write a multi-parameter function through function literal in scala ?
As we know that we can define a multi-parameter function in scala, like this: def func(s: String*) = println(s) My question is how to rewrite the above in **function literal** style. Or is it impossible to do that ? **Note**: `(s: Stirng) => pirntln(s)` is not correct .
scala
multiparameter
null
null
null
null
open
Is it possible to write a multi-parameter function through function literal in scala ? === As we know that we can define a multi-parameter function in scala, like this: def func(s: String*) = println(s) My question is how to rewrite the above in **function literal** style. Or is it impossible to do that ? **Note**: `(s: Stirng) => pirntln(s)` is not correct .
0
11,627,862
07/24/2012 09:24:44
1,547,822
07/24/2012 07:04:26
1
0
When click on Back button some times re send(POST) happens without loading the page as it is.I wont to prevent from posting data again
When click on Back button most of the times it is posting the data again to the server side. What I am thinking is, when click on back button it should load the previous page as it is without post data again. But it is not the way it is behaving. So what I exactly need is the back button should display the previous page without resend the data to the server again. Please let me know if there are any header changes or configurations to do to prevent this. Thanks Chamil
internet-explorer
java-ee
null
null
null
null
open
When click on Back button some times re send(POST) happens without loading the page as it is.I wont to prevent from posting data again === When click on Back button most of the times it is posting the data again to the server side. What I am thinking is, when click on back button it should load the previous page as it is without post data again. But it is not the way it is behaving. So what I exactly need is the back button should display the previous page without resend the data to the server again. Please let me know if there are any header changes or configurations to do to prevent this. Thanks Chamil
0
11,626,496
07/24/2012 07:55:44
982,439
10/06/2011 15:08:50
81
1
email encoding issue with c#
I have the following string I need to use for a confirmation email 'from' address. This is the spanish translation which is causing a problem when viewing within a web client. Shown below. Confirmació[email protected] becomes =?utf-8?Q?Confirmaci=C3=B3n model.FromAddresses = new EmailAddress { Address = fromAddressComponents[0], DisplayName = fromAddressComponents[1] }; Value taken from a resource string, shown below <data name="BookingConfirmation_FromAddress" xml:space="preserve"> <value>Confirmació[email protected]</value> </data> Can you see how to avoid this? I know it's because of the ó but I'm not sure how to avoid this problem! Thanks, James
c#
asp.net
.net
null
null
null
open
email encoding issue with c# === I have the following string I need to use for a confirmation email 'from' address. This is the spanish translation which is causing a problem when viewing within a web client. Shown below. Confirmació[email protected] becomes =?utf-8?Q?Confirmaci=C3=B3n model.FromAddresses = new EmailAddress { Address = fromAddressComponents[0], DisplayName = fromAddressComponents[1] }; Value taken from a resource string, shown below <data name="BookingConfirmation_FromAddress" xml:space="preserve"> <value>Confirmació[email protected]</value> </data> Can you see how to avoid this? I know it's because of the ó but I'm not sure how to avoid this problem! Thanks, James
0
11,431,255
07/11/2012 11:02:51
1,302,274
03/30/2012 02:48:26
632
51
AGImagePickerController
Has anyone tried `AGImagePickerController` here? Im having trouble, when I present the picker then exit then return to the picker, it sometimes/mostly crash. Are there other ways to optimize its performance in terms of loading the images. It also loads slow. Any one who had experience with this problem, and have solve this, hope you could share your solutions. Thankyou very much.
iphone
ios
xcode
null
null
null
open
AGImagePickerController === Has anyone tried `AGImagePickerController` here? Im having trouble, when I present the picker then exit then return to the picker, it sometimes/mostly crash. Are there other ways to optimize its performance in terms of loading the images. It also loads slow. Any one who had experience with this problem, and have solve this, hope you could share your solutions. Thankyou very much.
0
11,627,871
07/24/2012 09:25:10
1,266,273
03/13/2012 10:53:49
17
1
Django admin sites - location of admin.py
I am writing django project which has several small apps. I want to use default admin site, so my admin.py will be very simple. Unfortunatelly it doesn't work if I put it to project directory - it has to be in app directory. Now I have two options: - Put one admin.py in one of app's directory - it will work but it's logically not correct - Put several admin.py files in each app directory (containing only models from certain app) Is there some way to force django to look for this file in project root directory?
django
django-admin
null
null
null
null
open
Django admin sites - location of admin.py === I am writing django project which has several small apps. I want to use default admin site, so my admin.py will be very simple. Unfortunatelly it doesn't work if I put it to project directory - it has to be in app directory. Now I have two options: - Put one admin.py in one of app's directory - it will work but it's logically not correct - Put several admin.py files in each app directory (containing only models from certain app) Is there some way to force django to look for this file in project root directory?
0