text stringlengths 8 267k | meta dict |
|---|---|
Q: ios force device rotation here is my code:
if ([[UIApplication sharedApplication] statusBarOrientation] != UIInterfaceOrientationLandscapeLeft) {
[appDelegate makeTabBarHidden:TRUE];
self.navigationController.navigationBarHidden = YES;
[UIView beginAnimations:@"newAlbum" context:NULL];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(addResultGraph)];
[[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationLandscapeLeft animated:YES];
// Then rotate the view and re-align it:
CGAffineTransform landscapeTransform = CGAffineTransformMakeRotation( 90.0 * M_PI / -180.0 );
landscapeTransform = CGAffineTransformTranslate( landscapeTransform, +90.0, +90.0 );
[self.navigationController.view setTransform:landscapeTransform];
[UIView commitAnimations];
}
and with this, from a portrait mode, the new viewcontroller is shown in landscapeleft mode, and everything is ok, but my problem is: if I rotate the device from landscape mode in portrait, the statusbar appears in portrait mode and the viewcontroller remains in landscape mode....
how can I solve this?
thanks in advance!
A: You may re-implement shouldAutorotateToInterfaceOrientation method and do something like
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationLandscapeLeft);
}
This way you enable only left orientation and, if you rotate your device to portrait, the interface won't rotate
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501891",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What can happen when I forcly terminate thread at Winsock connect function? What can happen when I use TerminateThread while Winsock connect function is in progress?
I need to immediately shutdown the thread which is currently connecting to the socket but I don't know what can happen to the network adapter.
The connect function has unfortunately no timeout parameter and the default system timeout value is too high. So is there any risk to interrupt this API function?
I've used Delphi tag just because I'm writing my application in Delphi, but it's much more Winsock and Windows API question.
Thanks
A: The only way to abort a connect() call is to close the socket from another thread context. Otherwise, use ConnectEx() with overlapped I/O, like Martin said.
A: By calling TerminateThread you create huge memory and resource leak. It may be OK if you do this just before your program exits (though it is not nice anyway...). But if you do this several times during program execution, your program finally crashes - no memory. Network adapter and its driver will be OK, they are protected well from buggy user mode programs.
A: Use ConnectEx() in an overlapped call? You could either use an event object, (a TEvent, say), in hEvent and wait on both that and some terminator event with WaitForMultipleObjects() or use a completion routine and wait on the terminator with WaitForSingleObjectEx() in a loop,that ignores WSA_OUTPUT_PENDING and IO_COMPLETION as results.
I guess it would be easier in this case to just wait with WaitForMultipleObjects().
Rgds,
Martin
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501892",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: MVC3 - Ajax actionlink - OnBegin, onComplete Using MVC3, C#, and the Razor View Engine:
I have a form that has an Ajax Action link. In the options I'm trying to specify OnBegin and OnComplete javascript function calls. In this question, I took out the meat of the functions and simply added alerts so that I could verify that the functions where being hit. What I really want to do with these functions is to use $.blockUI for the duration of the ajax call.
The pertinent code looks like this:
@Ajax.ActionLink("my test link", "myAction", new { Controller = "myController" }, new AjaxOptions { OnBegin = "ajaxStart", OnComplete = "ajaxStop" })
<script type="text/javascript">
function ajaxStart() {
alert("start");
}
function ajaxStop() {
alert("stop");
}
</script>
For some reason, the two functions never get called as specified. I have tried it with and without the parentheses, sucha as this:
@Ajax.ActionLink("my test link", "myAction", new { Controller = "myController" }, new AjaxOptions { OnBegin = "ajaxStart()", OnComplete = "ajaxStop()" })
Neither work.
Any ideas?
Thanks,
Tony
A: You can try to put the <script> bloc before the Ajax.ActionLink method call.
Use this syntax for the ajax link:
@Ajax.ActionLink("my test link", "myAction", "myController", new AjaxOptions { OnBegin = "ajaxStart", OnComplete = "ajaxStop" })
and remember to put the import of jquery.unobtrusive-ajax.min.js in your view or in _Layout.cshtml
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
A: Make sure you have included the following script to your page:
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
and that you have enabled unobtrusive ajax in your web.config:
<appSettings>
...
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
In ASP.NET MVC 3 unobtrusive javascript is used with jQuery so uif you don't include the proper scripts, the HTML5 data-* attributes that are emitted by the html helpers are not interpreted and there is no AJAX request being sent.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501896",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Is it possible to use the SeekBar component in YouTube ActionScript 3.0 Player API? I'm fiddling around with the YouTube ActionScript 3.0 Player API. It's pretty cool and simple but one thing i can't seem to get to work, nor find any info on the web:
I want to use the SeekBar component with the Youtube API. I tried this, which works with the FLVPlayback component:
var seek:MovieClip = new SeekBar();
player.seekBar = seek;
So i think i might search wrong, try something impossible or thinking to easy? A push in the right direction will be appreciated.
A: It is possible and here is a tutorial explaining how to do it:
http://tutorialzine.com/2010/07/youtube-api-custom-player-jquery-css/
You can just implement your own seek bar, then when it's dragged or whatever get the value of the bar and apply it to the youtube object like so:
elements.player.seekTo();
See the tutorial for more information.
A: I created my own seekbar in the Flash IDE (can be a simple movieclip with 100x10px dimensions). It has a certain widht (variable) and can be clicked on. This is the function to skip to the movie position clicked.
private function controlsSeek():void {
// Get distance in pixels where the mouse is clicked
var mouseGlobalPosition = new Point(mouseX,mouseY);
var mouseLocalPosition = playerControls.seekbar.globalToLocal(mouseGlobalPosition);
// Afstand van de balk vanaf het nulpunt
var pixelsClicked:int = mouseLocalPosition.x;
// Percentage aan de hand van het aantal pixels
var pixelsPercentage:int = (pixelsClicked / playerControls.seekbar.seekbarLoadedBackground.width) * 100;
// Converteer pixels naar het aantal seconden waar de film heen moet
var pixelsToSeconds:int = Math.ceil(pixelsPercentage * (player.getDuration() * 0.01));
player.seekTo(pixelsToSeconds, true);
}
It works for me, if someone has a better solution or idea please throw it at me. If you use this method and it works oké, please let me know also.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501898",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to get number of returned rows from a database After I perform a database query, and some rows are echoed, it seems that I can't get the number of rows which are shown, after the query. Tried to use mysql_num_rows() but my $result is like this:
$result = $conn->query($sql) or die();
so I think that the problem is that I've used the built-in MySQLi() class, and for some reason
mysql_num_rows() is not working in accordance with this $result. How can I get it to work with the current $result I'm using, or is there any other way to return the number of rows using the MySQLi() class to create the $result??
A: mysql and mysqli are NOT interchangeable. They're two completely different modules, maintain their own separate connections, and are results/handles from one are NOT useable in the other. They may both use the same underlying mysql libraries and talk to the same database, but they're utterly independent of each other.
If you're using MySQLi, then stick with MySQLi functions, which for your problem would be to use http://php.net/manual/en/mysqli-stmt.num-rows.php
A: Note1: If you only need the number of rows in your table, it is better to do the folowing:
$result = $conn->query("SELECT COUNT(*) FROM `table`");
$row = $result->fetch_row();
echo '#: ', $row[0];
Note 2: Don't mix up mysqli_field_count and mysqli_stmt_num_rows. For example :
id firstname
1 foo
2 bar
3 baz
*
*field_count is 2
*num_rows is 3
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501900",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: HTML elements overlap in IE 7 ONLY I have a page that looks great in every browser except IE 7, where the table in the center overlaps the grey section below. I have a fixed height on the center section for continuity between pages, so that needs to stay in place.
http://www.bikramyoga.cz/rozvrh.htm
I have tried to add a min-height, max-height, etc, !important declarations and the like, and nothing seems to keep the table within the 510px container.
A: I have run into this problem a couple of times. Try adding:
<div style="clear: both;"></div>
Right after:
<ul id="legend">
<li><img class="rozvrh" src="img/dot.png" alt="czech class">Česká lekce</li>
<li><img class="rozvrh" src="img/box.png" alt="english class">Anglická lekce</li>
<li><img class="rozvrh" src="img/dud.png" alt="babysitting">Česká lekce s hlídáním dětí</li>
</ul>
</div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501903",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How to calculate height and width of inner browser without including browser menu bar using jquery I want to calculate height and width of inner body of browser including browser scroll bar but without including browser menu toolbars using jquery.
After calculating height and width i want to set some header, body and footer. Also when I re size(expand and minimize) outside and inside scroll appears which keeps my header, body, and footer fixed.
So what do I have to do in order to make it work cross-browser?
A: It sounds like you're trying to manually position your header and footer based on the size of the window. Why not use CSS to just position: fixed or position: absolute to let the browser position it for you?
This will position header and footer at top and bottom of your document.
#header {
position: absolute;
top: 0;
}
#footer {
position: absolute;
bottom: 0;
}
Or, this will position at top and bottom of the window:
#header {
position: fixed;
top: 0;
}
#footer {
position: fixed;
bottom: 0;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501907",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Cannot get Core Data to Delete Table View Row I am getting the following error:
Unresolved error (null), (null)
Any ideas what this could be related to - I am trying to allow the users a swipe option to delete an item from Core Data... Adding & Displaying the data works - however deleting shows the error...
@implementation List
@synthesize eventsArray;
@synthesize managedObjectContext, fetchedResultsController, List;
...
- (void)viewDidLoad
{
[super viewDidLoad];
if (managedObjectContext == nil)
{
managedObjectContext = [(ApplicationAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
}
UIBarButtonItem *editButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:@selector(editAction)];
self.navigationItem.leftBarButtonItem = editButton;
[editButton release];
UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target: self action:@selector(addAction)];
self.navigationItem.rightBarButtonItem = addButton;
[addButton release];
}
- (void)viewDidUnload
{
[super viewDidUnload];
self.fetchedResultsController.delegate = nil;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
List = [[NSMutableArray alloc] init];
NSError *error;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Items" inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
NSArray *fetchedObjects = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
for (NSManagedObject *info in fetchedObjects)
{
[List insertObject:[info valueForKey:@"Name"] atIndex:0];
}
[fetchRequest release];
[self.tableView reloadData];
}
...
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [List count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
// Get and display the values for the keys; the key is the attribute name from the entity
cell.textLabel.text = [List objectAtIndex:indexPath.row];
// Add a standard disclosure for drill-down navigation
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete)
{
NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
[context deleteObject:[self.fetchedResultsController objectAtIndexPath:indexPath]];
// Save the context.
NSError *error = nil;
if (![context save:&error])
{
/*
Replace this implementation with code to handle the error appropriately.
abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
*/
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
} }
}
- (void)dealloc
{
[fetchedResultsController release];
[List release];
[super dealloc];
}
@end
A: Firstly, you have the name of your view controller implementation as 'List' but also seem to have an ivar named List. Check the name of the view controller class as this should be the name after the @implementation declarative.
Also, if the name of your NSArray is List then the usual coding convention is to keep ivars starting with lower case. Keeping class names with upper case and ivars with lower case should help avoid confusion in the future.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501913",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Entity Framework CodeFirst Multiple type of users I have task to build application for user registration. I have 3 types of user (profiles)
1. "Normal" user
2. "Company" user
3. "Company2" user - similar like 2. but with few additional fields..
All users share some specific info, like e-mail and password (Login data), role, registration date etc.... So, I'm trying to "design" classes for this type of app using only EF Code First approach, but with no luck..
Do I need table (class) for :
USER - all kind of users with all their Login data (email and password) and UserType
USERTYPE - list of all user types (1,2,3)
USER_DETAILS - details of normal user
COMPANY_DETAILS - details of company
COMPANY2_DETAILS -details of company2
My problem is how to reference USER table with USER_DETAILS, COMPANY_DETAILS, COMPANY2_DETAILS. I hope so that you understand my problem :)
My classes (user management and profile) is implemented like http://codefirstmembership.codeplex.com/ example.
Thank you in advance!
A: You can use a normal inheritance model with Entity Framework.
I would just use a base class User that contains the login data (please don't store the password in the DB though, use a hash - Membership should do this for you already) and other user info, then you can add another class CompanyUser that inherits from User and contains the additional properties. Finally CompanyUser2 (needs a better name) can inherit from CompanyUser.
Having this in place there are different models you can use on how EF maps your classes to tables:
1.) Table-per-Hierarchy
2.) Table-per-Type
3.) Table per Concrete Type
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501920",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Local push notifications wp7 Please turn me in right direction. I want to create local notifications for checking incoming messages from website.
I can't pay for the server, but does anybody knows how to create local push notifications server in wp7?
A: You can't create a "local" push notification server. You could however use background agents to perform a similar task and use the ShellToast and ShellTile APIs to achieve a similar result.
There is a background agent sample on MSDN here: http://msdn.microsoft.com/en-us/library/ff431744(v=vs.92).aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501922",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: PHP messing with HTML Charset Encoding I have this very strange problem. I have a site that contains some German letters and when it's only html without php the symbols are property displayed with encoding when i change it to UTF-8 they dont display and instead of Ö I get �. When I put the html inside php and start it with Zend studio on Wamp with the charset=iso-8859-1 encoding I get � instead of Ö ( I want to add that this same Ö is a value of a radio button). When it's in a tag it displays properly. Can you tell me how to fix this issue. I look at other sites and they have UTF-8 Encoding and displaying properly the same symbol. I tried to change the php edior encoding but it doesn't matter I suppose -> everything is displaying properly inside Zend Studio's editor... Thank you in advance.
A: You have probably come to mix encoding types.
For example. A page that is sent as iso-8859-1, but get UTF-8 text encoding from MySQL or XML would typically fail.
To solve this problem you must keep control on input ecodings type in relation to the type of encoding you have chosen to use internal.
If you send it as an iso-8859-1, your input from the user is also iso-8859-1.
header("Content-type:text/html; charset: iso-8859-1");
And if mysql sends latin1 you do not have to do anything.
But if your input is not iso-8859-1 you must converted it, before it's sending to the user or to adapt it to Mysql before it's store.
mb_convert_encoding($text, mb_internal_encoding(), 'UTF-8'); // If it's UTF-8 to internal encoding
Short it means that you must always have input converted to fit internal encoding and convereter output to match the external encoding.
This is the internal encoding I have chosen to use.
mb_internal_encoding('iso-8859-1'); // Internal encoding
This is a code i use.
mb_language('uni'); // Mail encoding
mb_internal_encoding('iso-8859-1'); // Internal encoding
mb_http_output('pass'); // Skip
function convert_encoding($text, $from_code='', $to_code='')
{
if (empty($from_code))
{
$from_code = mb_detect_encoding($text, 'auto');
if ($from_code == 'ASCII')
{
$from_code = 'iso-8859-1';
}
}
if (empty($to_code))
{
return mb_convert_encoding($text, mb_internal_encoding(), $from_code);
}
return mb_convert_encoding($text, $to_code, $from_code);
}
function encoding_html($text, $code='')
{
if (empty($code))
{
return htmlentities($text, ENT_NOQUOTES, mb_internal_encoding());
}
return mb_convert_encoding(htmlentities($text, ENT_NOQUOTES, $code), mb_internal_encoding(), $code);
}
function decoding_html($text, $code='')
{
if (empty($code))
{
return html_entity_decode($text, ENT_NOQUOTES, mb_internal_encoding());
}
return mb_convert_encoding(html_entity_decode($text, ENT_NOQUOTES, $code), mb_internal_encoding(), $code);
}
A: Can you check what is the value of HTTP header Charset in Response Headers. Though the information is old(2009), i don't know if it still holds: the default charset in PHP is UTF-8 if you don't provide the content-type header with charset. Source
Hence set the header explicitly:
header("Content-type:text/html; charset: iso-8859-1");
A: Updated I need to get my encode/decode de-confused.
When you're in PHP try decoding the string in UTF-8 before output.
$str = 'I ãm UTF-8';
echo(utf8_decode($str));
This worked for me:
<?php $str = 'I ãm UTF-8: ÖMG!'; ?>
Test: <input type = 'text' value = '<?php echo(htmlspecialchars(utf8_decode($str))); ?>'>
Value in Input (via Cut n Paste):
I ãm UTF-8: ÖMG!
A: Why don't you use
Ö
instead of your Ö?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501924",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Comparable Comparator Java Here is my Code
class ComparableTest
{
public static void main(String[] args)
{
BOX[] box = new BOX[5];
box[0] = new BOX(10,8,6);
box[1] = new BOX(5,10,5);
box[2] = new BOX(8,8,8);
box[3] = new BOX(10,20,30);
box[4] = new BOX(1,2,3);
Arrays.sort(box);
for(int i=0;i<box.length;i++)
System.out.println(box[i]);
}
}
Also i have a class BOX that implements Comparable.
Now i have a few question that i would like you all to help me out with.
1.Are the methods declared in comparable interface,system defined, as in can i have any method in the comparable, or it has to be compareTo only?
2.I did not provide the implementation of Arrays.sort method, how does it sort my elements then?
3.When i use Comparator instead of comparable, then I use:
class comparatorTest
{
public static void main(String args[])
{
Student[] students = new Student[5];
Student[0] = new Student(“John”,”2000A1Ps234”,23,”Pilani”);
Student[1] = new Student(“Meera”,”2001A1Ps234”,23,”Pilani”);
Student[2] = new Student(“Kamal”,”2001A1Ps344”,23,”Pilani”);
Student[3] = new Student(“Ram”,”2000A2Ps644”,23,”Pilani”);
Student[4] = new Student(“Sham”,”2000A7Ps543”,23,”Pilani”);
// Sort By Name
Comparator c1 = new studentbyname();
Arrays.sort(students,c1);
for(int i=0;i<students.length;i++)
System.out.println(students[i]);
}
}
//In the above code, studentbyname implements comparator, but box stil implements comparable .i.e
class studentbyname implements comparator
{
public int compare(Object o1,Object o2)
{
Student s1 = (Student) o1;
Student s2 = (Student) o2;
return s1.getName().compareTo(s2.getName());
}
}
Now i am doing Arrays.sort(students,c1), why am i passing c1 now?
A: *
*In order to meet the Comparable contract, you must have at least the compareTo method. You may have as many addition methods in your class as you would like.
*It sorts the elements in the natural order based on the Comparable interface. So sort is calling compareTo between the elements to see in which order to place them.
*Providing a Comparator to the sort method allows sort to order elements that either (a) don't implement Comparable or (b) where you want to order them in some other order than the "natural order" as defined by the class's Comparable implementation.
When you pass a Comparator to sort, it calls the Comparator's compare method rather than the elements' compareTo method (if implemented).
see What is an interface
see Comparator
see Comparable
A: *
*You can define as many methods as you want in a Comparable, as long as you implement compareTo. This method can be used in many situations where the class is checked for comparation. For example, when inserting instances into an ordered TreeSet. compareTo provides a general ordering rule for all instances of the class.
*Arrays.sort orders the array in the natural order of its elements. That is, using compareTo.
*You can use Comparator to define a custom ordering rule. Like when you have a table you can sort by any of its columns. You could define a Comparator for each of its columns, and you could still have a class-inherent ordering rule (as in related to the reality the Class represents) defined in the class' compareTo.
A: Implementing Comparable obligates you to provide an implementation for compareTo().
All elements in the Object array passed to the Arrays.sort(Object[]) method must implement Comparable. If you want to use a Comparator instead, you have to use an Arrays.sort() method that takes a Comparator as a parameter. The method you use in your example above takes a Comparator as the second parameter - hence the need to provide c1 in the method call.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501926",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: change color and width of some painted lines in an UIImageView I'm painting some black lines in an UIImageView (in touchesBegan and touchesMoved methods) and there is one UISlider for modifying the width of these lines and some buttons for modifying the color of them.
How can that be done using CoreGraphics?
...
UIGraphicsBeginImageContext(theImage.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, theNewWidth);
...
Thanks
A: First, you shouldn't be trying to draw on a UIImageView. Instead, create your own subclass of UIView and override -drawRect:. When the events for those UI controls are fired, just call -setNeedsDisplay on your view class to ask it to be redrawn. Also, set some properties on your view class (e.g., lineWidth, lineColor).
In -drawRect:, use Core Graphics to redraw your view with the new values the user specified.
You can look at the Quartz 2D Programming Guide for all the information you need about drawing with Core Graphics. Also, check out the QuartzDemo sample project from Apple. It demonstrates many, if not all, of Core Graphics's capabilities.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501930",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Access token Google+ I'm experiencing few issues with the new-released Google+ API to retrieve an access token...
I have been following the documentation, I got a Code ("4/blablabla") but when I send the POST request to get an access token, I get a "(400) Bad Request" response...
Here is my piece of code :
// We have a request code, now we want an access token
StringBuilder authLink = new StringBuilder();
authLink.Append("https://accounts.google.com/o/oauth2/token");
authLink.AppendFormat("?code={0}", gplusCode);
authLink.AppendFormat("&client_id={0}", myClientId);
authLink.AppendFormat("&client_secret={0}", mySecret);
authLink.AppendFormat("&redirect_uri={0}", myRedirectUri);
authLink.Append("&scope=https://www.googleapis.com/auth/plus.me");
authLink.Append("&grant_type=authorization_code");
OAuthBase oAuth = new OAuthBase();
string normalizedUrl, normalizedRequestParameters;
string oAuthSignature = oAuth.GenerateSignature(new Uri(authLink.ToString()), appKey, appSecret, code, null, HttpMethod.POST.ToString(), oAuth.GenerateTimeStamp(), oAuth.GenerateNonce(), OAuthBase.SignatureTypes.HMACSHA1, out normalizedUrl, out normalizedRequestParameters);
oAuthSignature = oAuth.UrlEncode(oAuthSignature);
// Rebuild query url with authorization
string url = string.Format("{0}?{1}&oauth_signature={2}", normalizedUrl, normalizedRequestParameters, oAuthSignature);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url.ToString());
request.Method = HttpMethod.POST.ToString();
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = 0;
// Send the request and get the response
try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
// Do stuff ...
A: You forgot the POST request. Try this:
string url = "https://accounts.google.com/o/oauth2/token";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url.ToString());
request.Method = HttpMethod.POST.ToString();
request.ContentType = "application/x-www-form-urlencoded";
// You mus do the POST request before getting any response
UTF8Encoding utfenc = new UTF8Encoding();
byte[] bytes = utfenc.GetBytes(parameters); // parameters="code=...&client_id=...";
Stream os = null;
try // send the post
{
webRequest.ContentLength = bytes.Length; // Count bytes to send
os = webRequest.GetRequestStream();
os.Write(bytes, 0, bytes.Length); // Send it
}
try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
// Do stuff ...
This will give you a Json with the access token. Also you can see my question, that I asked today and solved later.
A: The Google+ API uses OAuth 2.0 for authorization. You seem to be implementing a mix of OAuth 2.0 and OAuth 1.0: your code calculates an OAuth 1.0 oauth_signature for the OAuth 2.0 request which is obsolete in OAuth 2.0.
Take a look at the OAuth 2.0 specification draft and try to follow the example in Google's OAuth 2.0 documentation exactly. Or just use Google's .NET library
which comes with OAuth 2.0 support.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501938",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How do I remove specific elements from HTML with HTML Agility Pack for ASP.NET (vb) There seems to be no documentation on the codeplex page and for some reason intellisense doesn't show me available methods or anything at all for htmlagilitypack (for example when I type MyHtmlDocument.DocumentNode. - there is no intellisense to tell me what I can do next)
I need to know how to remove ALL < a > tags and their content from the body of the HTML document I cannot just use Node.InnerText on the Body because that still returns content from A tags.
Here is example HTML
<html>
<body>
I was born in <a name=BC>Toronto</a> and now I live in barrie
</body>
</html>
I need to return
I was born in and now I live in barrie
Thanks, I appreciate the help!
Thomas
A: Something along the lines of (sorry my code is C# but I hope it will help nonetheless)
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml("some html markup here");
HtmlNodeCollection links = doc.DocumentNode.SelectNodes("//a[@name]");
foreach(HtmlNode link in links)
{
link.Remove();
}
//then one of the many doc.Save(...) overrides to actually get the result of the operation.
A: This gets you the result you require. This uses Recursive method to drill down all your html nodes and you can simply remove more nodes by adding a new if statment.
Public Sub Test()
Dim document = New HtmlDocument() With { _
Key .OptionOutputAsXml = True _
}
document.LoadHtml("<html><body>I was born in <a name=BC>Toronto</a> and now I live in barrie</body></html>")
For i As var = 0 To document.DocumentNode.ChildNodes.Count - 1
RecursiveMethod(document.DocumentNode.ChildNodes(i))
Next
Console.Out.WriteLine(document.DocumentNode.InnerHtml.Replace(" ", " "))
End Sub
Public Sub RecursiveMethod(child As HtmlNode)
For x As var = 0 To child.ChildNodes.Count - 1
Dim node = child.ChildNodes(x)
If node.Name = "a" Then
node.RemoveAll() //removes all the child nodes of "a"
node.Remove() //removes the actual "a" node
Else
If node.HasChildNodes Then
RecursiveMethod(node)
End If
End If
Next
End Sub
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501942",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android: ContentProvider for each table / handling one-to-many relationships When using a content provider for SQLite database access
*
*Is it better practice to have a content provider for each table or to use one for all tables?
*How to handle one-to-many relationships when creating new records?
A: As for first question: you don't need to create content provider for every table. You can use in with multiple tables, but the complexity of provider increased with each table.
A: A ContentProvider is not a database
A ContentProvider is a way to publicly (or semi-publicly) access data as content. This may be done in a number of ways, via file access, SQLite or even web access. A ContentProvider in and of itself is not a database, but you can program a database for it. You may also have multiple ContentProviders accessing the same database, but distributing different levels of access, or the same content in different ways according to the requestor.
What you are really asking is not a ContentProvider question, but a database question "How to handle relationships in an SQLite database" because the ContentProvider doesn't use any database code unless you tell it to via an SQLiteOpenHelper and other similar classes. So, you simply have to program your database access correctly and your SQLite database will work as desired.
A database is a database
In the old days, databases were simply flat files where each table was often its own entity to allow for growth. Now, with DBMS, there is very little reason to ever do that. SQLite is just like any other database platform in this regard and can house as many tables as you have space to hold them.
SQLite
There are certain features that SQLite handles well, some that it handles - but not well, and some that it does not handle at all. Relationships are one of those things that were left out of some versions of Android's SQLite, because it shipped without foreign key support. This was a highly requested feature and it was added in SQLite 3.6.22 which didn't ship until Android 2.2. There are still many reported bugs with it, however, in its earliest incarnations.
Android pre 2.2
Thankfully being SQL compliant and a simple DBMS (not RDBMS at this time), there are some easy ways to work around this, after all, a foreign key is just a field in another table.
*
*You can enforce database INSERT and UPDATE statements by creating CONSTRAINTs when you use your CREATE TABLE statement.
*You can query the other table for the appropriate _id to get your foreign key.
*You can query your source table with any appropriate SELECT statement using an INNER JOIN, thus enforcing a pseudo-relationship.
Since Android's version of SQLite does not enforce relationships directly, if you wanted to CASCADE ON DELETE you would have to do it manually. But this can be done via another simple SQL statement. I have essentially written my own library to enforce these kinds of relationships, as it all must be done manually. I must say, however, the efficiency of SQLite and SQL as a whole makes this very quick and easy.
In essence, the process for any enforced relationship goes as follows:
*
*In a query that requires a foreign key, use a JOIN.
*In an INSERT use a CONSTRAINT on the foreign key field of NOT NULL
*In an UPDATE on the primary key field that is a foreign key in another TABLE, run a second UPDATE on the related TABLE that has the foreign key. (CASCADE UPDATE)
*For a DELETE with the same parameters, do another DELETE with the where being foreign_key = _id (make sure you get the _id before you DELETE the row, first).
Android 2.2+
Foreign keys is supported, but is off by default. First you have to turn them on:
db.execSQL("PRAGMA foreign_keys=ON;");
Next you have to create the relationship TRIGGER. This is done when you create the TABLE, rather than a separate TRIGGER statement. See below:
// Added at the end of CREATE TABLE statement in the MANY table
FOREIGN KEY(foreign_key_name) REFERENCES one_table_name(primary_key_name)
For further information on SQLite and its capabilities, check out SQLite official site. This is important as you don't have all of the JOINs that you do in other RDBMS. For specific information on the SQLite classes in Android, read the documentation.
A: A Content Provider is roughly equivalent to the concept of a database. You'd have multiple tables in a database, so having multiple tables in your content provider makes perfect sense.
One to many relationships can be handled just like in any other database. Use references and foreign keys like you would with any other database. You can use things like CASCADE ON DELETE to make sure records are deleted when the records they reference in other tables are also deleted.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501945",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Understanding Pickling in Python I have recently got an assignment where I need to put a dictionary (where each key refers to a list) in pickled form. The only problem is I have no idea what pickled form is. Could anyone point me in the right direction of some good resources to help me learn this concept?
A: http://docs.python.org/library/pickle.html#example
import pickle
data1 = {'a': [1, 2.0, 3, 4+6j],
'b': ('string', u'Unicode string'),
'c': None}
selfref_list = [1, 2, 3]
selfref_list.append(selfref_list)
output = open('data.pkl', 'wb')
# Pickle dictionary using protocol 0.
pickle.dump(data1, output)
# Pickle the list using the highest protocol available.
pickle.dump(selfref_list, output, -1)
output.close()
A: Pickling in Python is used to serialize and de-serialize Python objects, like dictionary in your case. I usually use cPickle module as it can be much faster than the Pickle module.
import cPickle as pickle
def serializeObject(pythonObj):
return pickle.dumps(pythonObj, pickle.HIGHEST_PROTOCOL)
def deSerializeObject(pickledObj):
return pickle.loads(pickledObj)
A: Pickling is a mini-language that can be used to convert the relevant state from a python object into a string, where this string uniquely represents the object. Then (un)pickling can be used to convert the string to a live object, by "reconstructing" the object from the saved state founding the string.
>>> import pickle
>>>
>>> class Foo(object):
... y = 1
... def __init__(self, x):
... self.x = x
... return
... def bar(self, y):
... return self.x + y
... def baz(self, y):
... Foo.y = y
... return self.bar(y)
...
>>> f = Foo(2)
>>> f.baz(3)
5
>>> f.y
3
>>> pickle.dumps(f)
"ccopy_reg\n_reconstructor\np0\n(c__main__\nFoo\np1\nc__builtin__\nobject\np2\nNtp3\nRp4\n(dp5\nS'x'\np6\nI2\nsb."
What you can see here is that pickle doesn't save the source code for the class, but does store a reference to the class definition. Basically, you can almost read the picked string… it says (roughly translated) "call copy_reg's reconstructor where the arguments are the class defined by __main__.Foo and then do other stuff". The other stuff is the saved state of the instance. If you look deeper, you can extract that "string x" is set to "the integer 2" (roughly: S'x'\np6\nI2). This is actually a clipped part of the pickled string for a dictionary entry… the dict being f.__dict__, which is {'x': 2}. If you look at the source code for pickle, it very clearly gives a translation for each type of object and operation from python to pickled byte code.
Note also that there are different variants of the pickling language. The default is protocol 0, which is more human-readable. There's also protocol 2, shown below (and 1,3, and 4, depending on the version of python you are using).
>>> pickle.dumps([1,2,3])
'(lp0\nI1\naI2\naI3\na.'
>>>
>>> pickle.dumps([1,2,3], -1)
'\x80\x02]q\x00(K\x01K\x02K\x03e.'
Again, it's still a dialect of the pickling language, and you can see that the protocol 0 string says "get a list, include I1, I2, I3", while the protocol 2 is harder to read, but says the same thing. The first bit \x80\x02 indicates that it's protocol 2 -- then you have ] which says it's a list, then again you can see the integers 1,2,3 in there. Again, check the source code for pickle to see the exact mapping for the pickling language.
To reverse the pickling to a string, use load/loads.
>>> p = pickle.dumps([1,2,3])
>>> pickle.loads(p)
[1, 2, 3]
A: Pickling is just serialization: putting data into a form that can be stored in a file and retrieved later. Here are the docs on the pickle module:
http://docs.python.org/release/2.7/library/pickle.html
A: The pickle module implements a fundamental, but powerful algorithm for serializing and de-serializing a Python object structure.
Pickling - is the process whereby a Python object hierarchy is converted into a byte stream, and Unpickling - is the inverse operation, whereby a byte stream is converted back into an object hierarchy.
Pickling (and unpickling) is alternatively known as serialization, marshalling, or flattening.
import pickle
data1 = {'a': [1, 2.0, 3, 4+6j],
'b': ('string', u'Unicode string'),
'c': None}
selfref_list = [1, 2, 3]
selfref_list.append(selfref_list)
output = open('data.pkl', 'wb')
# Pickle dictionary using protocol 0.
pickle.dump(data1, output)
# Pickle the list using the highest protocol available.
pickle.dump(selfref_list, output, -1)
output.close()
To read from a pickled file -
import pprint, pickle
pkl_file = open('data.pkl', 'rb')
data1 = pickle.load(pkl_file)
pprint.pprint(data1)
data2 = pickle.load(pkl_file)
pprint.pprint(data2)
pkl_file.close()
source - https://docs.python.org/2/library/pickle.html
A: Sometimes we want to save the objects to retrieve them later (Even after the Program that generated the data has terminated). Or we want to transmit the object to someone or something else outside our application. Pickle module is used for serializing and deserializing the object.
serializing object (Pickling): Create a representation of an object.
deserializing object (Unpickling): Re-load the object from representation.
dump: pickle to file
load: unpickle from file
dumps: returns a pickled representation. We can store it in a variable.
loads: unpickle from the supplied variable.
Example:
import pickle
print("Using dumps and loads to store it in variable")
list1 = [2, 4]
dict1 = {1: list1, 2: 'hello', 3: list1}
pickle_dict = pickle.dumps(dict1)
print(pickle_dict)
dict2 = pickle.loads(pickle_dict)
print(dict2)
# obj1==obj2 => True
# obj1 is obj2 => False
print(id(dict1.get(1)), id(dict1.get(3)))
print(id(dict2.get(1)), id(dict2.get(3)))
print("*" * 100)
print("Using dump and load to store it in File ")
cars = ["Audi", "BMW", "Maruti 800", "Maruti Suzuki"]
file_name = "mycar.pkl"
fileobj = open(file_name, 'wb')
pickle.dump(cars, fileobj)
fileobj.close();
file_name = "mycar.pkl"
fileobj = open(file_name, 'rb')
mycar = pickle.load(fileobj)
print(mycar)
A: Pickling allows you to serialize and de-serializing Python object structures. In short, Pickling is a way to convert a python object into a character stream so that this character stream contains all the information necessary to reconstruct the object in another python script.
import pickle
def pickle_data():
data = {
'name': 'sanjay',
'profession': 'Software Engineer',
'country': 'India'
}
filename = 'PersonalInfo'
outfile = open(filename, 'wb')
pickle.dump(data,outfile)
outfile.close()
pickle_data()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501947",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "68"
} |
Q: What is x86_thread_state64_t & thread_act_t? I was looking into source code of StarRuntime and I came across two terms x86_thread_state64_t & thread_act_t.
I tried to Google it but there is not much documentation.
I see it being used consistently in apple open source projects?
Can someone explain me what are they?
A: x86_thread_state64_t should be something like this
struct x86_thread_state64_t {
uint64_t rax, rbx, rcx, rdx,
rdi, rsi, rbp, rsp,
r8, r9, r10, r11,
r12, r13, r14, r15,
rip, rflags,
cs, fs, gs;
};
and
thread_act_t is
struct thread *thread_act_t;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501953",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ASP.Net - looping/conditional statements in Layouts Coming from PHP and more specifically many of the MVC frameworks out their, I've been use to using basic foreach and if constructs in PHP directly in the layout. Now that I'm learning ASP.NET I'm presented with more proprietary concepts like a ListView to control looping, etc...
So to give an example of what I want to do..
<div id="container">
<h1 class="header">Title</h1>
<% For Each item In ItemsCollection %>
<% If item.Name IsNot Nothing %>
<h3>This is the layout for <%= item.Name %></h3>
<% End If %>
<p><%= item.Content %></p>
<% Next %>
</div>
Then there isn't a lot I have to handle in the Code Behind file... besides making ItemsCollection available.
Is This considered Bad Practice? Should I spend the time learning the proprietary controls for ASP.NET? Are there specific limitations of this approach?
A: This may be subjective, but there are tons of documentation about why the standard controls such as the ListView were created. The primary benefits is separation of concerns, and avoidance of "spaghetti code", which is exactly what your sample is.
I believe that if you're going to be developing in .NET is is well worth your time to learn the controls, and the background for these controls. A lot of the power, productivity, code clarity, and ease of .NET development is hinged around such design principles. Whether they are "Correct" or "right" compared to other environments is debatable.
All of the above beside...
The short version is that if you're going to be developing in .NET using the WebForms model, you should code like a .NET WebForms developer, if for no other reason than that it's likely that a .NET WebForms developer will need to maintain your code some day. We've all been trained to expect certain things, and stuff like this drives us nuts when maintaining other people's code.
Edit
Of course, if you go with ASP.NET MVC, you'll be in your comfort zone and my opinion will not apply.
A: If you go with the vanilla ASP.NET framework, your example is not best practice and you should stick with the server-side control model. ASP.NET was designed to be used primarily as a server-side control model. What you describe more closely matches traditional ASP pages.
For example, a Repeater control would match your example code perfectly.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.repeater.aspx
Rough example:
Markup:
<asp:Repeater id="Repeater1" runat="server">
<HeaderTemplate>
<div id="container">
<h1 class="header">Title</h1>
</HeaderTemplate>
<ItemTemplate>
<h3>This is the layout for <%# DataBinder.Eval(Container.DataItem, "Name") %></h3>
<p><%# DataBinder.Eval(Container.DataItem, "Content") %></p>
</ItemTemplate>
<FooterTemplate>
</div>
</FooterTemplate>
</asp:Repeater>
Code behind:
protected void Page_Load(Object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// create or retrieve some bindable datasource
// ArrayList values = ....
Repeater1.DataSource = values;
Repeater1.DataBind();
}
}
That is a matching server side control model to your example. The Repeater will by design iterate through your item collection and create the same end result. It basically spits out the header template, iterates your collection using the item template, and then spits out the footer template. There are lots of other options as well, this is simply a quick example.
A: There's no need to embed code and markup like this in ASP.NET (With some exceptions ;)).
Instead, you can have a ListView control that you can bind to a DataSource; for example:
<h3>ListView Example</h3>
<asp:ListView ID="VendorsListView"
DataSourceID="VendorsDataSource"
DataKeyNames="VendorID"
OnItemDataBound="VendorsListView_ItemDataBound"
runat="server">
<ItemTemplate>
<tr runat="server">
<td>
<asp:Label ID="VendorIDLabel" runat="server" Text='<%# Eval("VendorID") %>' />
</td>
<td>
<asp:Label ID="AccountNumberLabel" runat="server" Text='<%# Eval("AccountNumber") %>' />
</td>
<td>
<asp:Label ID="NameLabel" runat="server" Text='<%# Eval("Name") %>' /></td>
<td>
<asp:CheckBox ID="PreferredCheckBox" runat="server"
Checked='<%# Eval("PreferredVendorStatus") %>' Enabled="False" />
</td>
</tr>
</ItemTemplate>
</asp:ListView>
<!-- This example uses Microsoft SQL Server and connects -->
<!-- to the AdventureWorks sample database. Add a LINQ -->
<!-- to SQL class to the project to map to a table in -->
<!-- the database. -->
<asp:LinqDataSource ID="VendorsDataSource" runat="server"
ContextTypeName="AdventureWorksClassesDataContext"
Select="new (VendorID, AccountNumber, Name, PreferredVendorStatus)"
TableName="Vendors" Where="ActiveFlag == @ActiveFlag">
<WhereParameters>
<asp:Parameter DefaultValue="true" Name="ActiveFlag" Type="Boolean" />
</WhereParameters>
</asp:LinqDataSource>
Taken from here.
UPDATE: As far as conditional statements, you can handle the ItemDataBound event:
protected void VendorsListView_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
ListViewDataItem dataItem = (ListViewDataItem)e.Item;
string vendorID= (string)DataBinder.Eval(dataItem, "VendorID");
// ...
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501957",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: php get iscsi output linux I am trying to use exec(), system(), passthru() or anything to read in the output of iscsiadm -m session, am not having much luck, and a little lost.
What I (think i) know:
*
*It is not a sudoers or permission problem, as the results are the same in a terminal or browser (and my sudoers is already successfully setup to use iscsiadm for login/out)
*Executing the following command from a terminal, iscsiadm -m session > /tmp/scsi_sess yields an empty scsi_sess file
What I need to know:
*
*Where is the output getting sent, that I can not read it with a bash or php script but can see it in the terminal?
*How can I read the output, or get output sent somewhere that I can read it?
A: With your syntax you're catching only the stdout. You should redirect the stderr on the stdout with
iscsiadm -m session 2>&1 /tmp/scsi_sess
Remember, when you do a redirect with > file and you still see output, that output is from stderr and not from stdout
http://en.wikipedia.org/wiki/Standard_streams
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501959",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Cant start aptana studio 3 version - 3.0.4 on windows 7 64bit
everytime i started it manage to get til splash screen, then it crash. cant remember when this start to happen, prolly after i updated to 3.0.4. this is the log:
!SESSION 2011-09-21 22:44:41.826
eclipse.buildId=unknown java.version=1.6.0_24 java.vendor=Sun
Microsystems Inc. BootLoader constants: OS=win32, ARCH=x86, WS=win32,
NL=en_MY Command-line arguments: -os win32 -ws win32 -arch x86
!ENTRY org.eclipse.osgi 4 0 2011-09-21 22:44:43.676 !MESSAGE An
unexpected runtime error has occurred. !STACK 0
org.eclipse.swt.SWTError: No more handles at
org.eclipse.swt.SWT.error(SWT.java:4109) at
org.eclipse.swt.SWT.error(SWT.java:3998) at
org.eclipse.swt.SWT.error(SWT.java:3969) at
org.eclipse.swt.widgets.Widget.error(Widget.java:468) at
org.eclipse.swt.widgets.TaskBar.createHandle(TaskBar.java:99) at
org.eclipse.swt.widgets.TaskBar.(TaskBar.java:92) at
org.eclipse.swt.widgets.Display.getSystemTaskBar(Display.java:2499)
at
org.eclipse.ui.internal.Workbench$TaskBarDelegatingProgressMontior.getTaskItem(Workbench.java:300)
at
org.eclipse.ui.internal.Workbench$TaskBarDelegatingProgressMontior.handleTaskBarProgressUpdated(Workbench.java:316)
at
org.eclipse.ui.internal.Workbench$TaskBarDelegatingProgressMontior.worked(Workbench.java:265)
at
org.eclipse.ui.internal.Workbench$StartupProgressBundleListener.bundleChanged(Workbench.java:417)
at
org.eclipse.osgi.framework.internal.core.BundleContextImpl.dispatchEvent(BundleContextImpl.java:919)
at
org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:227)
at
org.eclipse.osgi.framework.eventmgr.ListenerQueue.dispatchEventSynchronous(ListenerQueue.java:149)
at
org.eclipse.osgi.framework.internal.core.Framework.publishBundleEventPrivileged(Framework.java:1349)
at
org.eclipse.osgi.framework.internal.core.Framework.publishBundleEvent(Framework.java:1300)
at
org.eclipse.osgi.framework.internal.core.BundleHost.startWorker(BundleHost.java:380)
at
org.eclipse.osgi.framework.internal.core.AbstractBundle.start(AbstractBundle.java:284)
at
org.eclipse.osgi.framework.util.SecureAction.start(SecureAction.java:417)
at
org.eclipse.osgi.internal.loader.BundleLoader.setLazyTrigger(BundleLoader.java:265)
at
org.eclipse.core.runtime.internal.adaptor.EclipseLazyStarter.postFindLocalClass(EclipseLazyStarter.java:106)
at
org.eclipse.osgi.baseadaptor.loader.ClasspathManager.findLocalClass(ClasspathManager.java:453)
at
org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.findLocalClass(DefaultClassLoader.java:216)
at
org.eclipse.osgi.internal.loader.BundleLoader.findLocalClass(BundleLoader.java:393)
at
org.eclipse.osgi.internal.loader.BundleLoader.findClassInternal(BundleLoader.java:469)
at
org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:422)
at
org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:410)
at
org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.loadClass(DefaultClassLoader.java:107)
at java.lang.ClassLoader.loadClass(Unknown Source) at
org.eclipse.osgi.internal.loader.BundleLoader.loadClass(BundleLoader.java:338)
at
org.eclipse.osgi.framework.internal.core.BundleHost.loadClass(BundleHost.java:232)
at
org.eclipse.osgi.framework.internal.core.AbstractBundle.loadClass(AbstractBundle.java:1197)
at
org.eclipse.equinox.internal.ds.model.ServiceComponent.createInstance(ServiceComponent.java:457)
at
org.eclipse.equinox.internal.ds.model.ServiceComponentProp.createInstance(ServiceComponentProp.java:264)
at
org.eclipse.equinox.internal.ds.model.ServiceComponentProp.build(ServiceComponentProp.java:325)
at
org.eclipse.equinox.internal.ds.InstanceProcess.buildComponent(InstanceProcess.java:588)
at
org.eclipse.equinox.internal.ds.ServiceReg.getService(ServiceReg.java:53)
at
org.eclipse.osgi.internal.serviceregistry.ServiceUse$1.run(ServiceUse.java:120)
at java.security.AccessController.doPrivileged(Native Method) at
org.eclipse.osgi.internal.serviceregistry.ServiceUse.getService(ServiceUse.java:118)
at
org.eclipse.osgi.internal.serviceregistry.ServiceRegistrationImpl.getService(ServiceRegistrationImpl.java:447)
at
org.eclipse.osgi.internal.serviceregistry.ServiceRegistry.getService(ServiceRegistry.java:430)
at
org.eclipse.osgi.framework.internal.core.BundleContextImpl.getService(BundleContextImpl.java:667)
at
org.osgi.util.tracker.ServiceTracker.addingService(ServiceTracker.java:442)
at
org.osgi.util.tracker.ServiceTracker$Tracked.customizerAdding(ServiceTracker.java:896)
at
org.osgi.util.tracker.AbstractTracked.trackAdding(AbstractTracked.java:261)
at
org.osgi.util.tracker.AbstractTracked.trackInitial(AbstractTracked.java:184)
at org.osgi.util.tracker.ServiceTracker.open(ServiceTracker.java:339)
at org.osgi.util.tracker.ServiceTracker.open(ServiceTracker.java:273)
at
org.eclipse.core.internal.runtime.InternalPlatform.getBundleGroupProviders(InternalPlatform.java:223)
at
org.eclipse.core.runtime.Platform.getBundleGroupProviders(Platform.java:1261)
at
org.eclipse.ui.internal.ide.IDEWorkbenchPlugin.getFeatureInfos(IDEWorkbenchPlugin.java:281)
at
org.eclipse.ui.internal.ide.WorkbenchActionBuilder.makeFeatureDependentActions(WorkbenchActionBuilder.java:1178)
at
org.eclipse.ui.internal.ide.WorkbenchActionBuilder.makeActions(WorkbenchActionBuilder.java:1001)
at
org.eclipse.ui.application.ActionBarAdvisor.fillActionBars(ActionBarAdvisor.java:147)
at
org.eclipse.ui.internal.ide.WorkbenchActionBuilder.fillActionBars(WorkbenchActionBuilder.java:335)
at
org.eclipse.ui.internal.WorkbenchWindow.fillActionBars(WorkbenchWindow.java:3533)
at
org.eclipse.ui.internal.WorkbenchWindow.(WorkbenchWindow.java:414)
at
org.eclipse.ui.internal.tweaklets.Workbench3xImplementation.createWorkbenchWindow(Workbench3xImplementation.java:31)
at
org.eclipse.ui.internal.Workbench.newWorkbenchWindow(Workbench.java:1881)
at org.eclipse.ui.internal.Workbench.access$14(Workbench.java:1879)
at
org.eclipse.ui.internal.Workbench$21.runWithException(Workbench.java:1199)
at
org.eclipse.ui.internal.StartupThreading$StartupRunnable.run(StartupThreading.java:31)
at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:35) at
org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:134)
at
org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:4041)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3660)
at
org.eclipse.ui.application.WorkbenchAdvisor.openWindows(WorkbenchAdvisor.java:803)
at
org.eclipse.ui.internal.Workbench$31.runWithException(Workbench.java:1567)
at
org.eclipse.ui.internal.StartupThreading$StartupRunnable.run(StartupThreading.java:31)
at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:35) at
org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:134)
at
org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:4041)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3660)
at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:2548) at
org.eclipse.ui.internal.Workbench.access$4(Workbench.java:2438) at
org.eclipse.ui.internal.Workbench$7.run(Workbench.java:671) at
org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
at
org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:664)
at
org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:149)
at com.aptana.rcp.IDEApplication.start(IDEApplication.java:125) at
org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
at
org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
at
org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
at
org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:369)
at
org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:179)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at
java.lang.reflect.Method.invoke(Unknown Source) at
org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:620) at
org.eclipse.equinox.launcher.Main.basicRun(Main.java:575) at
org.eclipse.equinox.launcher.Main.run(Main.java:1408)
!ENTRY org.eclipse.ui.workbench 4 0 2011-09-21 22:44:43.680 !MESSAGE
!STACK 0 org.eclipse.swt.SWTError: No more handles at
org.eclipse.swt.SWT.error(SWT.java:4109) at
org.eclipse.swt.SWT.error(SWT.java:3998) at
org.eclipse.swt.SWT.error(SWT.java:3969) at
org.eclipse.swt.widgets.Widget.error(Widget.java:468) at
org.eclipse.swt.widgets.TaskBar.createHandle(TaskBar.java:99) at
org.eclipse.swt.widgets.TaskBar.(TaskBar.java:92) at
org.eclipse.swt.widgets.Display.getSystemTaskBar(Display.java:2499)
at
org.eclipse.ui.internal.Workbench$TaskBarDelegatingProgressMontior.getTaskItem(Workbench.java:300)
at
org.eclipse.ui.internal.Workbench$TaskBarDelegatingProgressMontior.handleTaskBarProgressUpdated(Workbench.java:316)
at
org.eclipse.ui.internal.Workbench$TaskBarDelegatingProgressMontior.worked(Workbench.java:265)
at
org.eclipse.ui.internal.Workbench$StartupProgressBundleListener.bundleChanged(Workbench.java:417)
at
org.eclipse.osgi.framework.internal.core.BundleContextImpl.dispatchEvent(BundleContextImpl.java:919)
at
org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:227)
at
org.eclipse.osgi.framework.eventmgr.ListenerQueue.dispatchEventSynchronous(ListenerQueue.java:149)
at
org.eclipse.osgi.framework.internal.core.Framework.publishBundleEventPrivileged(Framework.java:1349)
at
org.eclipse.osgi.framework.internal.core.Framework.publishBundleEvent(Framework.java:1300)
at
org.eclipse.osgi.framework.internal.core.BundleHost.startWorker(BundleHost.java:380)
at
org.eclipse.osgi.framework.internal.core.AbstractBundle.start(AbstractBundle.java:284)
at
org.eclipse.osgi.framework.util.SecureAction.start(SecureAction.java:417)
at
org.eclipse.osgi.internal.loader.BundleLoader.setLazyTrigger(BundleLoader.java:265)
at
org.eclipse.core.runtime.internal.adaptor.EclipseLazyStarter.postFindLocalClass(EclipseLazyStarter.java:106)
at
org.eclipse.osgi.baseadaptor.loader.ClasspathManager.findLocalClass(ClasspathManager.java:453)
at
org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.findLocalClass(DefaultClassLoader.java:216)
at
org.eclipse.osgi.internal.loader.BundleLoader.findLocalClass(BundleLoader.java:393)
at
org.eclipse.osgi.internal.loader.BundleLoader.findClassInternal(BundleLoader.java:469)
at
org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:422)
at
org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:410)
at
org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.loadClass(DefaultClassLoader.java:107)
at java.lang.ClassLoader.loadClass(Unknown Source) at
org.eclipse.osgi.internal.loader.BundleLoader.loadClass(BundleLoader.java:338)
at
org.eclipse.osgi.framework.internal.core.BundleHost.loadClass(BundleHost.java:232)
at
org.eclipse.osgi.framework.internal.core.AbstractBundle.loadClass(AbstractBundle.java:1197)
at
org.eclipse.equinox.internal.ds.model.ServiceComponent.createInstance(ServiceComponent.java:457)
at
org.eclipse.equinox.internal.ds.model.ServiceComponentProp.createInstance(ServiceComponentProp.java:264)
at
org.eclipse.equinox.internal.ds.model.ServiceComponentProp.build(ServiceComponentProp.java:325)
at
org.eclipse.equinox.internal.ds.InstanceProcess.buildComponent(InstanceProcess.java:588)
at
org.eclipse.equinox.internal.ds.ServiceReg.getService(ServiceReg.java:53)
at
org.eclipse.osgi.internal.serviceregistry.ServiceUse$1.run(ServiceUse.java:120)
at java.security.AccessController.doPrivileged(Native Method) at
org.eclipse.osgi.internal.serviceregistry.ServiceUse.getService(ServiceUse.java:118)
at
org.eclipse.osgi.internal.serviceregistry.ServiceRegistrationImpl.getService(ServiceRegistrationImpl.java:447)
at
org.eclipse.osgi.internal.serviceregistry.ServiceRegistry.getService(ServiceRegistry.java:430)
at
org.eclipse.osgi.framework.internal.core.BundleContextImpl.getService(BundleContextImpl.java:667)
at
org.osgi.util.tracker.ServiceTracker.addingService(ServiceTracker.java:442)
at
org.osgi.util.tracker.ServiceTracker$Tracked.customizerAdding(ServiceTracker.java:896)
at
org.osgi.util.tracker.AbstractTracked.trackAdding(AbstractTracked.java:261)
at
org.osgi.util.tracker.AbstractTracked.trackInitial(AbstractTracked.java:184)
at org.osgi.util.tracker.ServiceTracker.open(ServiceTracker.java:339)
at org.osgi.util.tracker.ServiceTracker.open(ServiceTracker.java:273)
at
org.eclipse.core.internal.runtime.InternalPlatform.getBundleGroupProviders(InternalPlatform.java:223)
at
org.eclipse.core.runtime.Platform.getBundleGroupProviders(Platform.java:1261)
at
org.eclipse.ui.internal.ide.IDEWorkbenchPlugin.getFeatureInfos(IDEWorkbenchPlugin.java:281)
at
org.eclipse.ui.internal.ide.WorkbenchActionBuilder.makeFeatureDependentActions(WorkbenchActionBuilder.java:1178)
at
org.eclipse.ui.internal.ide.WorkbenchActionBuilder.makeActions(WorkbenchActionBuilder.java:1001)
at
org.eclipse.ui.application.ActionBarAdvisor.fillActionBars(ActionBarAdvisor.java:147)
at
org.eclipse.ui.internal.ide.WorkbenchActionBuilder.fillActionBars(WorkbenchActionBuilder.java:335)
at
org.eclipse.ui.internal.WorkbenchWindow.fillActionBars(WorkbenchWindow.java:3533)
at
org.eclipse.ui.internal.WorkbenchWindow.(WorkbenchWindow.java:414)
at
org.eclipse.ui.internal.tweaklets.Workbench3xImplementation.createWorkbenchWindow(Workbench3xImplementation.java:31)
at
org.eclipse.ui.internal.Workbench.newWorkbenchWindow(Workbench.java:1881)
at org.eclipse.ui.internal.Workbench.access$14(Workbench.java:1879)
at
org.eclipse.ui.internal.Workbench$21.runWithException(Workbench.java:1199)
at
org.eclipse.ui.internal.StartupThreading$StartupRunnable.run(StartupThreading.java:31)
at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:35) at
org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:134)
at
org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:4041)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3660)
at
org.eclipse.ui.application.WorkbenchAdvisor.openWindows(WorkbenchAdvisor.java:803)
at
org.eclipse.ui.internal.Workbench$31.runWithException(Workbench.java:1567)
at
org.eclipse.ui.internal.StartupThreading$StartupRunnable.run(StartupThreading.java:31)
at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:35) at
org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:134)
at
org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:4041)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3660)
at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:2548) at
org.eclipse.ui.internal.Workbench.access$4(Workbench.java:2438) at
org.eclipse.ui.internal.Workbench$7.run(Workbench.java:671) at
org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
at
org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:664)
at
org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:149)
at com.aptana.rcp.IDEApplication.start(IDEApplication.java:125) at
org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
at
org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
at
org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
at
org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:369)
at
org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:179)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at
java.lang.reflect.Method.invoke(Unknown Source) at
org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:620) at
org.eclipse.equinox.launcher.Main.basicRun(Main.java:575) at
org.eclipse.equinox.launcher.Main.run(Main.java:1408)
!ENTRY org.eclipse.osgi 4 0 2011-09-21 22:44:43.955 !MESSAGE
Application error !STACK 1 org.eclipse.swt.SWTError: No more handles
at org.eclipse.swt.SWT.error(SWT.java:4109) at
org.eclipse.swt.SWT.error(SWT.java:3998) at
org.eclipse.swt.SWT.error(SWT.java:3969) at
org.eclipse.swt.widgets.Widget.error(Widget.java:468) at
org.eclipse.swt.widgets.TaskBar.createHandle(TaskBar.java:99) at
org.eclipse.swt.widgets.TaskBar.(TaskBar.java:92) at
org.eclipse.swt.widgets.Display.getSystemTaskBar(Display.java:2499)
at
org.eclipse.ui.internal.WorkbenchWindow.createProgressIndicator(WorkbenchWindow.java:3331)
at
org.eclipse.ui.internal.WorkbenchWindow.createDefaultContents(WorkbenchWindow.java:1110)
at
org.eclipse.ui.internal.WorkbenchWindowConfigurer.createDefaultContents(WorkbenchWindowConfigurer.java:623)
at
org.eclipse.ui.application.WorkbenchWindowAdvisor.createWindowContents(WorkbenchWindowAdvisor.java:268)
at
org.eclipse.ui.internal.WorkbenchWindow.createContents(WorkbenchWindow.java:1016)
at org.eclipse.jface.window.Window.create(Window.java:431) at
org.eclipse.ui.internal.Workbench$22.runWithException(Workbench.java:1208)
at
org.eclipse.ui.internal.StartupThreading$StartupRunnable.run(StartupThreading.java:31)
at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:35) at
org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:134)
at
org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:4041)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3660)
at
org.eclipse.ui.application.WorkbenchAdvisor.openWindows(WorkbenchAdvisor.java:803)
at
org.eclipse.ui.internal.Workbench$31.runWithException(Workbench.java:1567)
at
org.eclipse.ui.internal.StartupThreading$StartupRunnable.run(StartupThreading.java:31)
at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:35) at
org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:134)
at
org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:4041)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3660)
at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:2548) at
org.eclipse.ui.internal.Workbench.access$4(Workbench.java:2438) at
org.eclipse.ui.internal.Workbench$7.run(Workbench.java:671) at
org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
at
org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:664)
at
org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:149)
at com.aptana.rcp.IDEApplication.start(IDEApplication.java:125) at
org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
at
org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
at
org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
at
org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:369)
at
org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:179)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at
java.lang.reflect.Method.invoke(Unknown Source) at
org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:620) at
org.eclipse.equinox.launcher.Main.basicRun(Main.java:575) at
org.eclipse.equinox.launcher.Main.run(Main.java:1408)
A: Try downloading and installing:
*
*Sun 64-bit JRE
*Eclipse Classic for Windows 64-bit
*Install Aptana Studio as a plugin into Eclipse Classic.
Cheers,
Max
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501963",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: When would a class ever have more than one designated initializer? Reading through Apple's documentation on Tips and Techniques for Framework Developers, I came across this statement about designated initializers:
A designated initializer is an init method of a class that invokes an
init method of the superclass. (Other initializers invoke the init
methods defined by the class.) Every public class should have one or
more designated initializers.
(Emphasis added.)
Based on my understanding—and indeed, the very use of the word "designated"—a class should have only one designated initializer. But according to the documentation, multiple designated initializers are acceptable.
Assuming that you have two (or more) designated initializers, their role is to call the superclass's designated initializer in order to guarantee proper object initialization. But if both designated initializers are calling the same superclass's designated initializer, then why was there the need for more than one in the first place? Shouldn't the class be refactored to funnel all the other init methods to the singular designated initializer?
I'm just a bit confused as to what use case or design pattern would call for multiple designated initializers?
A: You would do this when you want to have a different initialization for different objects of the same class. One example is class clusters, like NSNumber. It has quite a few initializers for the different types of numbers they can hold. To provide the most accurate representation, the class should hold its value in the same format it received it in, instead of casting. This means the initializers can't simply call a common initializer and return. They need to do some custom work. This makes them a designated initializer.
Another example would be a document class which needs to do some initialization only for new files and some other initialization only for documents being opened. Both of these initializers will call their super implementation, which in turn calls the plain init method to do common initialization. However, since they do more than simply calling another initializer with a default value, they are considered designated initializers.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501965",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Provider "gps" unknown exception while trying to removeTestProvider Does anyone know why or has resolved this issue I'm having:
09-21 11:49:45.007: WARN/System.err(22711): java.lang.IllegalArgumentException: Provider "gps" unknown
09-21 11:49:45.007: WARN/System.err(22711): at android.os.Parcel.readException(Parcel.java:1251)
09-21 11:49:45.007: WARN/System.err(22711): at android.os.Parcel.readException(Parcel.java:1235)
09-21 11:49:45.007: WARN/System.err(22711): at android.location.ILocationManager$Stub$Proxy.removeTestProvider(ILocationManager.java:889)
09-21 11:49:45.007: WARN/System.err(22711): at android.location.LocationManager.removeTestProvider(LocationManager.java:1008)
This answer does not solve since I don't even get into the deprecated method. It fails first while trying to remove the provider.
Is this a bug?
EDIT:
In my code I check the existence of the provider "gps" in the list:
final String TEST_PROVIDER = LocationManager.GPS_PROVIDER; // "gps"
if (mLocationManager.getProvider(TEST_PROVIDER) != null) {
mLocationManager.removeTestProvider(TEST_PROVIDER);
}
Weird thing is that it was working before.
A: I think removeTestProvider(TEST_PROVIDER) only works after you've called addTestProvider(TEST_PROVIDER).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501967",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Merging JPA entity returns old values I have 2 JPA entities that have a bidirectional relationship between them.
@Entity
public class A {
@ManyToOne(cascade={CascadeType.PERSIST, CascadeType.MERGE})
B b;
// ...
}
and
@Entity
public class B {
@OneToMany(mappedBy="b",cascade={CascadeType.PERSIST, CascadeType.MERGE})
Set<A> as = new HashSet<A>();
// ...
}
Now I update some field values of a detached A which also has relationships to some Bs and vice versa and merge it back by
public String save(A a) {
A returnedA = em.merge(a);
}
returnedA now has the values of A prior to updating them.
I suppose that
FINEST: Merge clone with references A@a7caa3be
FINEST: Register the existing object B@cacf2dfb
FINEST: Register the existing object A@a7caa3be
FINEST: Register the existing object A@3f2584b8
indicates that the referenced As in B (which still have the old values) are responsible for overwriting the new ones?
Does anyone have a hint how to prevent this to happen?
Any idea is greatly appreciated!
Thanks in advance.
A: Dirk, I've had a similar problem and the solution (I might not be leveraging the API correctly) was intensive. Eclipselink maintains a cache of objects and if they are not updated (merged/persisted) often the database reflects the change but the cascading objects are not updated (particularly the parents).
(I've declared A as the record joining multiple B's)
Entities:
public class A
{
@OneToMany(cascade = CascadeType.ALL)
Collection b;
}
public class B
{
@ManyToOne(cascade = {CascadeType.MERGE, CascadeType.REFRESH}) //I don't want to cascade a persist operation as that might make another A object)
A a;
}
In the case above a workaround is:
public void saveB(B b) //"Child relationship"
{
A a = b.getA();//do null checks as needed and get a reference to the parent
a.getBs().add(b); //I've had the collection be null
//Persistence here
entityInstance.merge(a); // or persist this will cascade and use b
}
public void saveA(A a)
{
//Persistence
entityInstance.merge(a) // or persist
}
What you're doing here is physically cascading the merge down the chain from the top. It is irritating to maintain, but it does solve the problem. Alternatively you can deal with it by checking if it is detached and refreshing/replacing but I've found that to be less desirable and irritating to work with.
If someone has a better answer as to what the correct setup is I would be happy to hear it. Right now I've taken this approach for my relational entities and it is definitely irritating to maintain.
Best of luck with it, I'd love to hear a better solution.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501968",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: how to start new instance of second project in new process I'm looking to show window (WPF) that is defined in separate class library project as new separate process. Is there any way to do this?
I need to start the second project instance in new process, because there stay occupied memory when I start it by this way:
secondProject.WPFWindow win = new secondProject.WPFWindow();
win.Show();
I have ONE solution with multiple projects.
*
*StartUp project is WPF app., output type: Windows application (exe file).
*All other projects are WFP app., output type: Class library (dll file).
Now I am running "applications" (other projects in this one solution built as dll) by this code:
secondProject.WPFWindow win = new secondProject.WPFWindow();
win.Show();
I want is runnig that apps in new process... Normally I would use Process.Start(), but I can't is this case because it needs exe file as agrument and I have (and want) DLLs.
A: You could pass command line arguments to the main .exe to tell it which of the 'sub-apps' to run. Then the main .exe can just launch itself in a new process and tell the new instance which sub-app to run. For example in the main .exe app, put logic like this in your Application class:
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
//See if exactly one command line argument was passed
if (e.Args.Length == 1)
{
//See if the argument is one of our 'known' values
switch (e.Args[0])
{
case "launchApp2":
secondProject.WPFWindow win2 = new secondProject.WPFWindow();
win2.Show();
break;
case "launchApp3":
thirdProject.OtherWPFWindow win3 = new thirdProject.OtherWPFWindow();
win3.Show();
break;
}
}
//Probably want to call the base class always?
base.OnStartup(e);
}
}
Then anytime you want to launch one of the sub-app in a new process, you can do so like this:
public void LaunchApp2()
{
//Start a new process that is ourself and pass a command line parameter to tell
// that new instance to launch App2
Process.Start(Assembly.GetEntryAssembly().Location, "launchApp2");
}
A: Let's assume you have a solution with 2 projects - one project compiles to an application (EXE), while the second compiles to a class library (DLL). I'll assume that the DLL has some type defined (say, a window) which you want to start from the EXE.
The simplest way to do this, is simply add a reference to the DLL. Right-click on the EXE project in the Solution Explorer, and choose Add Reference.... Wait a minute while the dialog opens. From the Projects tab, select the DLL project. Click OK.
Now, in your EXE project, WPFWindow will available as an imported type. You need to add a
using secondProject;
to the top of each code file that uses WPFWindow. I normally do this automatically using the keyboard shortcut CTRL + Period.
The method I've described is the standard method of using DLLs in C#. You can load them manually, but that is a little more complex, and likely isn't what you want to do.
Edit:
Alexei is correct. I think what we have here is an XY Problem. What you're trying to do is probably very easy, but the approach (instantiating a window defined in a DLL) is not.
Be aware that any code you run (in your case, your WPFWindow) has to originate from an application, even though the code itself is defined in a DLL. A DLL by itself normally provides no information to the operating system about how to run any of the code contained within.
Consider adding another EXE project which runs your WPFWindow which you call using Process. This suggestion might be wrong, though, as we still don't know what your end goal is. You're asking "How do I flap my wings like a bird?" when the correct question could be "How do I buy a plane ticket?"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501974",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How to skip email confirmation for users who uses Devise rpx conecteable I am working on a mini project and i dont know how to skip email confirmation for users who uses devise_rpx_connectable_to sign in, Every time i try to sign in using this services it sends email confirmation to those users.
A: you can always override this method in User class:
def confirmation_required?
!confirmed?
end
for example you can check there if rpx_identifier.blank?
try this code:
def confirmation_required?
!confirmed? and rpx_identifier.blank?
end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501976",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to configure Include/Lib directories of VC++ devenv.com command line? I'm building a VC++ 9.0 project from command line (using devenv.com):
devenv.com myproject.sln /Build "Release|Win32"
I need to add additional include path to it. How can I do this?
A: I gave up using devenv.com for the same reason. I use msbuild instead.
*
*Add your include and lib to your project
*launch vcvarsall.bat
*call msbuild.exe
I have Visual Studio 2010. I created a small batch file that is in my path (because I have many dev environments on my computer).
@c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\vcvarsall.bat %*
And I actually wrap msbuild.exe with this simple batch file :
@for %%i in (*.sln) do @msbuild %%i /v:m /nologo %*
With the trailing %*, you can add other parameters when needed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501978",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to parse a local xml file mentioned below in sencha touch mobile As i am new to Sencha touch mobile stuck in parsing a normal xml file and pass it to a store object and populate in a panel view. Can any one help me out how to parse a XML file kept locally in the project(as mentioned below data.xml) or as a string. Below is the XML and thanks in advance.
data.XML:-
<dataSrc>
<section>
<elem>
<id>1677</id>
<name>
<![CDATA[ United Kingdom]]>
</name>
</elem>
</section>
<section>
<elem>
<id>1678</id>
<name>
<![CDATA[ United Arab Emirates]]>
</name>
</elem>
</section>
.......
</dataSrc>
A: Have a model with the xml properties and a store with a xml proxy.
Ext.regModel('elem', {
fields: [
{name: 'id', type: 'string'},
{name: 'name', type: 'string'}
]
});
var myStore = new Ext.data.Store({
model: 'elem',
proxy: {
type: 'xml',
url : '/data.xml',
reader: {
type: 'xml',
root: 'dataSrc',
record: 'elem'
}
},
autoLoad: true
});
Then you have the contents of the xml parsed in the store. Read all about this at http://dev.sencha.com/deploy/touch/docs/?class=Ext.data.Store
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501984",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to nest anchor links via jQuery? Looking for a great way to add anchor links within my HTML document after my pattern of H3 and the last p element block.
This is my original HTML
<div id="container">
<h3 id="faqa">title</h3>
<p>content</p>
<h3 id="faqb">title</h3>
<p>content</p>
<p>content</p>
<h3 id="faqc">title</h3>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<h3 id="faqd">title</h3>
<p>content</p>
</div>
And I want...
<div id="container">
<h3 id="faqa">title</h3>
<p>content</p>
<p align="right"><a href="#">back to top</a>
<h3 id="faqb">title</h3>
<p>content</p>
<p>content</p>
<p align="right"><a href="#">back to top</a>
<h3 id="faqc">title</h3>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p align="right"><a href="#">back to top</a>
<h3 id="faqd">title</h3>
<p>content</p>
<p align="right"><a href="#">back to top</a>
</div>
Here is my honest effort so far, but no answer as of yet...
$("#container").each (function() {
if($(this).find('h3[id*="faq"]')){
var $mpage = window.location.pathname;
$(this).find("p:last").append('<p align="right"><a href="'+$mpage+'">Back to top</a>
</p>');
}
});
The jQuery API has an excellent guide on prepend and append, but neither of them help me in this specific case. Thanks for any light on the situation, I got about 40 of these anchors I have to add ;(
Thanks again for any help!
A: How about:
$("#container h3").each(function() {
if($(this).prev("p").length) {
$(this).before("<p><a href='#'>fake link</a></p>");
}
});
Demo.
EDIT based on our esteemed @Felix Kling's input:
$("h3").prev("p").after("<p><a href='#'>Back to top</a></p>");
Demo.
A: var link = '<p align="right"><a href="#">back to top</a></p>';
$('#container h3').each(function() {
$(this).nextUntil('h3', 'p').last().after(link);
});
should do the trick.
DEMO
Update: karim's answer is nice and short and you should go with this one Edit: Apparently, as nice as the answer seems, it does not add a link to the last paragraph of the last heading.
I will still leave this answer here, as it shows a different way of approaching the problem.
karim's mindset basically is: Take every h3 and add the link if it was preceded by a paragraph.
Mine was: Take every h3 and find the last following paragraph (before the next h3) and append the link.
He thought upwards, I downwards ;)
A: //get all h3
var h3 = $("#container").find("h3[id^='faq']");
//store anchor html
var anchor = '<p align="right"><a href="#">back to top</a>';
//if h3 exist
if(h3.size()){
// for every p before a h3 and the last p append anchor
h3.prev("p").add("p:last").after(anchor);
}
Demo: http://jsfiddle.net/TDSSd/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501986",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Compare Packed decimal Julian date with (Packed decimal Current Julian date-7days) using JCL- SYNCSORT? I have a requirement as below.
In my Input file, I have Packed decimal Julian date[YYYYDDD format] in 23rd position (position 23, length 4).
*
*If my the input Julian date is less than (Current Julian date - 7 days) then write the records into Out File1.
*Else Write the records into Out file2.
Can anybody let me know how to Compare Packed decimal Julian date with (Packed decimal Current Julian date-7days) using JCL- SYNCSORT?
A: You can use this...
SYSIN DD *
SORT FIELDS=COPY,
OUTFIL FNAMES=01,
INCLUDE=(23,4,PD,EQ,DATE3P-7)
OUTFILF FNAMES=02,SAVE
DATE3P gives the current date in P'YYYYDDD' packed decimal format.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501989",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Help Importing CSV file with Variable Columns per Row into SQL Table using Import tool or SSIS I am stuck with a CSV file with over 100,000 rows that contains product images from a provider. Here are the details of the issue, I would really appreciate some tips to help resolve this. Thanks.
The File has 1 Row per product and the following 4 columns.
ID,URL,HEIGHT,WIDTH
example: 1,http://i.img.com,100,200
Problem starts when a product has multiple images.
Instead of having 1 row per image the file has more columns in same row.
example:
1,http://i.img.com,100,200,//i.img.com,20,100,//i.img.com,30,50
Note that only first image has "http://" remaining images start with "//"
There is no telling how many images per product hence no way to tell how many total columns per row or max columns.
How can I import this using SSIS or sql import wizard.
Also I need to do this on regular intervals.
Thank you for your help.
A: I don't think that you can use any standard SSIS task or wizard to do this. You're going to have to write some custom code which parses each line. You can do this in SSIS using VB code or you can import the file into a staging table that's just a single column to hold each row and do the parsing in SQL. SSIS will probably be faster for this kind of operation.
Another possibility is to preprocess the file using regex or a search-and-replace command. Try to get double-quotes around the image list then you should be able to import the whole file fine, with the quoted part going into a single column. Catching the start of the string should be easy enough given the "http:\" for which you can search. Determining where the end quote goes might be more of a problem.
A third potential solution would be to get the source to fix the data. Even if you can't get the images in separate rows (or another file with separate rows, which would be ideal), maybe you can get the double-quotes added from the source as part of the export. This would likely be less error-prone than using the search-and-replace method.
Good luck!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501990",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Remove duplicates from a list of objects without relying on a set In java, and there is one catch here. The objects are already compiled and the hash() and equals() methods therefore cannot be over written. Throwing it into a set, then back into a list will not work because the criteria for uniqueness isn't currently defined in equals() and this cannot be overridden.
A: You should still be able to create subclasses and create equals and hashcode methods that work, unless the classes/methods are final.
If that is the case, you could use composition, basically create a wrapper for the things you are putting in the collection, and have the wrapper's equals and hashcode implement the contract correctly, for the thing being wrapped.
You are in a tough position, because what I am reading is that the original classes are not following the contract for equals and hashcode which is a real problem in Java. It's a pretty serious bug.
A: Write a custom Comparator for your objects and use Collections.sort() to sort your list. And then remove duplicates by going though a list in a loop.
A: a compareTo method would return -1, 0, 1; if 0, remove from list.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501991",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Widget in Adobe AIR position bottom-right Thanks in advance.
I'm a graphic designer.
I have to make a widget that shows some icons.
I've made an icon that starts in systemtray, all I need is to make the window application that start at bottom over the icon.
I don't know anything about flex...
I've done this so far in application.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<application xmlns="http://ns.adobe.com/air/application/1.0">
<id>com.widgetStatus.widgetStatus</id>
<filename>widgetStatus</filename>
<name>widgetStatus</name>
<description>Test</description>
<version>0.1a</version>
<initialWindow>
<content>html/index.html</content>
<title>widgetStatus</title>
<systemChrome>none</systemChrome>
<transparent>true</transparent>
<visible>true</visible>
<minimizable>false</minimizable>
<resizable>false</resizable>
<width>400</width>
<height>300</height>
<x>1268</x>
<y>646</y>
</initialWindow>
<icon>
<image128x128>/icons/widget128.png</image128x128>
<image48x48>/icons/widget48.png</image48x48>
<image32x32>/icons/widget32.png</image32x32>
<image16x16>/icons/widget16.png</image16x16>
</icon>
The application starts over the systray but only with my resolution obliuvsly.
Now I need to do something like that:
Positioning Flex/AIR Desktop App Window to the bottom right corner
How can I work with that script in flex? I understand that I can put the code into xml.
Thanks.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501994",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Cannot call WCF service methods from php script I have WCF service.
When I try to access it from .NET page all works fine. However I cannot find a way to access it from php script.
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="NewBinding0">
<reliableSession inactivityTimeout="01:00:00" />
<security mode="TransportWithMessageCredential">
<transport clientCredentialType="Basic" />
<message clientCredentialType="UserName" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="RegisterBehavior">
<serviceDebug includeExceptionDetailInFaults="true" />
<serviceMetadata httpsGetEnabled="true" />
<serviceThrottling maxConcurrentCalls="48" maxConcurrentSessions="5000"
maxConcurrentInstances="5000" />
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom"
customUserNamePasswordValidatorType="..."
cacheLogonTokens="true" cachedLogonTokenLifetime="01:00:00" />
</serviceCredentials>
</behavior>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="RegisterBehavior" name="Riepas.WCFRiepas">
<endpoint address="..."
binding="wsHttpBinding" bindingConfiguration="NewBinding0" contract="...">
</endpoint>
<endpoint address="mex" binding="mexHttpsBinding" name="mex"
contract="IMetadataExchange">
</endpoint>
</service>
</services>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
/>
Tried connecting from php, but it just hang. :(
$client = new SoapClient("wsdl", array(
'login' => "...",
'password' => "...",
'soap_version' => SOAP_1_2));
$functions = $client->__getFunctions ();
var_dump ($functions);
$parameters = array("ReqVal" => "nu?");
//$result = $client->__soapCall("GetStr", $parameters);
//$result = $client->GetStr($parameters);
Functions returns normaly.
A: In order to use the php soapclient, you need to use basicHttpBinding, not wsHttpBinding.
For a very simple complete working example, see my Echo Service, which includes a php client.
This downside of this is that your service will not implement WS-Reliable Messaging or WS-Security. However, if you need those, there is an open source party module called the WSO2 Web Services Framework for PHP that supposedly handles wsHttpBinding.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501995",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Accessing the indices of non-zero elements in a UBLAS sparse vector How can I know the index of the first non-zero element in a sparse_vector in ublas and each subsequent nonzero element as well? The function begin() gives me an iterator that can be used to know the first non-zero value stored, not its index in the vector.
A: Here is the answer, after Oswin Krause, from the ublas mainling list:
Iterators offer a method index() which returns the desired result. But
remember that only the const_iterator is really sparse!
for(SparseVector::const_iterator pos = sparseVec.begin(); pos !=
sparseVec.end();++pos){ std::cout << pos.index()<< " "<< *pos; }
A: This seems impossible to achieve without a linear scan over the vector. The API simply doesn't expose the non-zero indices. (I'd write to the authors if I were you, since they are withholding information that can be very useful when serializing sparse vectors.)
I've had similar problems with UBLAS's sparse matrices in the past, eventually forcing me to roll my own.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501996",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Vim details autocomplete for Rails I found nice detail autocomplete for python
Is there analog with description of methods for Ruby on Rails?
A: There is a nice article "Using VIM as a complete Ruby on Rails IDE" which references rails.vim. This seems to be the de-facto standard on Rails for VIM. (However, I have not used it yet, but will try it soon.) This allows you to do a lot of Rails related tasks, but does not help with auto completion.
There is another article "Ruby Autocomplete in Vim" (which is sadly no longer available) which is what you are searching for. I do not know, if it is sufficient clever to understand all the plugin magic and meta-programming stuff of Rails. It mentions Rails at least in its configuration for vim.
So good luck :-)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501997",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Displaying logic from one model in the view of another in Rails? I have a model, Statistic, that has 6 statistics for a Character model. Users can enter values for Strength, Intelligence and so on. I've written a method for automatically calculating bonuses or penalties based on the score entered. Here's the logic for a Constitution bonus, from my Statistic model:
def con_modifier
(constitution.to_i - 10) / 2
end
I display the information gathered from the Statistic model in my Character view, and I want to see the bonus, so I defined it in the Show method in my Character model like so:
@con_modifier = @character.statistic.con_modifier
I'm able to view it in the Character view with no issues. But here's my problem. I have another model, Fortitude, which will need to take this number and use it to calculate the total value for a Fortitude save. So far, here's what I've got:
def total
fortitude_base.to_i + @con_modifier + magic.to_i + misc.to_i
end
But then I get this error:
nil can't be coerced into Fixnum
So obviously it isn't calling up the correct information. Any ideas? Do I need to define it in my Fortitudes controller as well, or can I simply define it in the Fortitude model and call it in the view that way? The Fortitude is being displayed in my Character view, so I thought defining this logic in the Show method in the Character model would simply work, but I've been hammering my head against this problem for a couple days now, with no progress. Thanks!
A: Pass the modifier as an argument:
def total(con_mod)
fortitude_base.to_i + con_mod + magic.to_i + misc.to_i
end
Then use it elsewhere:
@fortitude = Fortitude.whatever
@saving_throw = @fortitude.total(@character.statistic.con_modifier)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501998",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Extjs getting fields values from extended FormPanel The submit button for my formPanel works by using scope:this as it is an extended formPanela nd ext.getCmp(formid) doesn't work.
In my submit function, it successfully works using this.getForm().submit(....). However when trying to get the field values, this.getForm().getFields() doesn't work, flagging that it is not a function.
the buttons & handler function is nested within the formPanel setup.
Can anyone shed light on how to get the values in this manner?
Submit function:
{
text: 'Submit',
id: "submitBtn",
handler: this.submit,
scope: this
}
....
,submit : function(url, waitMsg) {
//this.getForm.getFields()
this.getForm().submit({
url: url
,scope: this
,waitMsg: 'Please wait'
,success: this.onSuccess
//,failure: this.onFailure
});
}
A:
submit : function(url, waitMsg) {
//this.getForm.getFields() -- should work now
this.getForm().submit({
url: url
,scope: this
,waitMsg: 'Please wait'
,success: this.onSuccess
//,failure: this.onFailure
});
}.createDelegate(this)
A: I've resolved this by not using the submit action but by using a simple Ext.Ajax.request:
,submit : function() {
var data = this.getForm().getValues();
Ext.Ajax.request({
url: '...',
method: 'GET',
timeout:180000,
params: {
param1: Ext.encode(this.getForm().getValues())
}
.
})
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502000",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: emulator not showing in adb devices if i start an emulator using the android SDK r12 it does not show up in the adb devices list
win7 64 // android 2.2 (not an actual hardware device - just the emulator)
what could be the problem?
A: You can also try to :
adb kill-server
adb start-server
to restart the adb server. Maybe something went wrong with the adb-server. This happens a lot, and many such issues can be solved by restarting the server.
A: Make sure that you are at the path and give command.
android-sdk_r12-windows\android-sdk-windows\platform-tools>adb devices
I am also using win7 64 It is working for me. If you are getting any error. Mention it.
Also make sure that USB debugging is enabled in your device.
Settings>Applications>Development>USB debugging
Can you able to see device in eclipse?
If not then close your emulator and open it again.
A: Sometimes even adb itself bugs, for me always works good old pkill:
pkill -9 adb
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502011",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "46"
} |
Q: MySQL GRANT to User@'host' not behaving as expected EDIT: I reinstalled MySQL and this fixed itself. No idea what the issue was.
I ran the following commands in MySQL from the command line:
1. REVOKE ALL PRIVILEGES ON MyDB.* FROM user@'%';
2. DROP USER user@'%";
3. GRANT INSERT,SELECT,DELETE,UPDATE ON MyDB.* TO user@'%' IDENTIFIED BY 'somepassword';
4. FLUSH PRIVILEGES;
The grants for the user are:
GRANT USAGE ON . to 'user'@'%' IDENTIFIED BY PASSWORD
GRANT SELECT,INSERT,UPDATE,DELETE ON 'MyDB'.* TO 'user'@'%'
But then I get the following error message when I try to do an update.
UPDATE command denied to user 'user'@'somehost' for table 'sometable'
Relevant info:
SELECT,INSERT, and DELETE all work properly.
I am using C# with Connector/NET
'somehost' is on the same network as the server (different computer).
'sometable' is in MyDB.
If I log in to the server with 'user' on the host machine, update queries work just fine.
EDIT:
If I grant UPDATE,SELECT,INSERT,DELETE to user@'somehost.net', UPDATE queries work without a problem.
Any ideas?
A: After taking away all the grants, first you should give the usage privilege to the user.
GRANT USAGE on MyDB.* to 'user'@'localhost'
Usage privilege tells the server that this user is allowed to use MySQL
A: Reinstalling fixed the issue. Not sure what the problem was.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502014",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: So what is special about Powershell PSC1 files? On my PowerShell shortcut I have the following:
C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe -psc "C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI\vim.psc1" -noe -c ". \"C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI\Scripts\Initialize-PowerCLIEnvironment.ps1\""
Yet, I would prefer to add the registration of snapins and to run the init of the PowerCLI environment to my profile.
So in my profile I add the following:
Add-PSSnapin VMware.VimAutomation.Core
& "C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI\Scripts\Initialize-PowerCLIEnvironment.ps1"
Yet, the Get-VICommand is no longer available using this method. Why?
A: PSC1 files are "PowerShell Console files." They are XML configuration files that tell PowerShell which snapins to load automatically. The other way to do that would be to call Import-Module or Add-PSSnapin in your Profile.ps1 script.
You can create your own psc1 files using Export-Console.
A: Try like this:
add-pssnapin VMware.VimAutomation.Core
. 'C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI\Scripts\Initialize-PowerCLIEnvironment.ps1' # dot sourcing!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502019",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Storing PHP 5.3 sessions into PostgreSQL 8.4 I'm using CentOS 6.0 Linux 64 bit with the stock packages:
# rpm -qa|grep php
php-cli-5.3.2-6.el6_0.1.x86_64
php-5.3.2-6.el6_0.1.x86_64
php-xml-5.3.2-6.el6_0.1.x86_64
php-pgsql-5.3.2-6.el6_0.1.x86_64
php-pear-1.9.0-2.el6.noarch
php-pdo-5.3.2-6.el6_0.1.x86_64
php-common-5.3.2-6.el6_0.1.x86_64
# rpm -qa|grep postgres
postgresql-devel-8.4.7-1.el6_0.1.x86_64
postgresql-docs-8.4.7-1.el6_0.1.x86_64
postgresql-libs-8.4.7-1.el6_0.1.x86_64
postgresql-8.4.7-1.el6_0.1.x86_64
postgresql-server-8.4.7-1.el6_0.1.x86_64
and would like to change my own PHP script from using
$_SERVER['REMOTE_USER'] to using $_SESSION,
but don't have any experience with PHP sessions yet.
I'd like the (quite extensive) user data to be stored into
the PostgreSQL and only save a "user id" in $_SESSION.
However this doc says "This extension is considered unmaintained and dead".
Does anybody please have any advice, what to do here?
Maybe I can save session data into the db myself (and how)?
A: You can override PHP's session save/load handlers with your own: http://php.net/manual/en/function.session-set-save-handler.php
This lets you save the session data to a database, or chip it onto a stone tablet if you'd like. The choice of underlying storage medium/database is irrelevant, as long as your code sends/receives the session data properly.
A: Simple flat version :
sql("INSERT INTO sessions (session,userid) VALUES('".json_encode($_SESSION["toomuchuserinfo"])."','".$_SESSION['userid']."');");
$r=sql("SELECT session FROM sessions where userid='".$_SESSION['userid']."';");
$_SESSION["toomuchuserinfo"]=json_decode($r[0][0]);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502020",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Hibernate mapping (inheritance) I'm trying to map some objects in Hibernate. One of these objects is father and the others are children. In other words they implement inheritance.
The father is as follow:
public class Person {
private String id;
private String name;
private String surname;
getters and setters ;
}
and children...
public class Employee {
private BigDecimal salary;
private String seccion;
private Employee employee;
private Customer customer;
getters and setters
}
public class Customer {
private BigDecima CreditLimit;
getter and setter
}
Then... I want to map these classes in the following database schema...
Table
Person
ID / NAME / SURNAME / ID_EMPLOYEE / ID_CUSTOMER
Employee
ID_PERSON / SALARY / SECCION
Customer
ID_PERSON / CREDIT_LIMIT
My idea is each persona can be or not a customer/employee. In other words Customer and Employee are properties of Person but these properties will be store in independents tables in the database.
For get the credit limit of a persona I can do persona.getCustomer().getCreditLimit();
Always making control if the Person is a Customer or is not.
I hope you can help me and excuse me my English is pretty poor. I'm from Argentina.
Thanks in advance.
Nicolas
A: You could map that with two One-To-One associations on Person.
As a side note, if you've got control over that schema, I'd reccomend going for Inheritance Mapping and Table-per-subclass, using a type column as discriminator on the person table. Here is a tutorial on inheritance mapping.
A: What you are looking for is known as Polymorphic Mapping, the example here is what you need.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502021",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to select from a subselect on NHibernate How can I map this SQL using NHibernate Criteria API?
Sql:
SELECT COUNT(*) FROM (
SELECT FirstName, LastName FROM Employees GROUP BY FirstName, LastName
) AS Query
This is a very very simple query, my query has a SubSelect much more complex.
So, any idea?
A: I found a solution for the question, it's a very big hack but it works as expected.
I had to get the generated SQL and surround it with the SELECT COUNT(*) query. Here is the code to do that:
public ISQLQuery BuildCountQuery(ICriteria criteria)
{
CriteriaImpl c = (CriteriaImpl)criteria;
SessionImpl s = (SessionImpl)c.Session;
string entityOrClassName = ExtractRealClassName(c);
SessionFactoryImpl factory = (SessionFactoryImpl)s.SessionFactory;
String[] implementors = factory.GetImplementors(entityOrClassName);
string implementor = implementors.Length == 0 ? null : implementors[0];
var persister = (IOuterJoinLoadable)factory.GetEntityPersister(implementor);
CriteriaLoader loader = new CriteriaLoader(persister, factory, c, implementor, s.EnabledFilters);
SqlString sql = loader.SqlString.Insert(0, "SELECT COUNT(*) FROM (");
sql = sql.Append(") AS Query");
var parameters = loader.Translator.CollectedParameters;
var sqlQuery = this.session.CreateSQLQuery(sql.ToString());
for (int i = 0; i < parameters.Count; i++)
sqlQuery.SetParameter(i, parameters.ElementAt(i).Value, parameters.ElementAt(i).Type);
return sqlQuery;
}
private string ExtractRealClassName(CriteriaImpl criteria)
{
Type rootEntityType = criteria.GetRootEntityTypeIfAvailable();
if (rootEntityType.GetInterfaces().Contains(typeof(INHibernateProxy)))
return criteria.GetRootEntityTypeIfAvailable().BaseType.FullName;
else
return criteria.EntityOrClassName;
}
A: DetachedCriteria criteriaEmployees = DetachedCriteria.For<Employees>();
criteriaEmployees.SetProjection(Projections.CountDistinct("FirstName"));
ICriteria executableCriteria = criteriaEmployees.GetExecutableCriteria(Session);
int count = executableCriteria.UniqueResult<int>();
A: DetachedCriteria can be used to create subqueries. Some examples are in the documentation.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502023",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Settings background for EDITTEXT cutting words in Android I am having a strange issue, the words are cutting inside EDITTEXT i have set an image as background. Plz help me... for example here ffsds, is being cut, I want it to shift to bit right so that it doesnt get cut.
A: Increase paddingLeft value of edit text.
...
android:paddingLeft="100dp"
...
in xml layout.
A: Increasing the left padding is the easy solution. But if this smiley image is always on the left of the edittext, you can set the image by using the attribute android:drawableLeft on the edittext.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502025",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Castle windsor Adding conditional dependency I have 2 implementations of the same interface and want to use implementation1 if the user is logged in or implementation2 if the user is not logged in. How can I configure this with castle windsor?
A: You could add a handler selector, which would be able to select between available implementations depending on e.g. whether Thread.CurrentPrincipal was set (or HttpContext.Current.Request.IsAuthenticated in ASP.NET/MVC if I remember correctly).
The handler selector would probably look somewhat like this:
public class MyAuthHandlerSelector : IHandlerSelector
{
public bool HasOpinionAbout(string key, Type service)
{
return service == typeof(ITheServiceICareAbout);
}
public IHandler SelectHandler(string key, Type service, IHandler[] handlers)
{
return IsAuthenticated
? FindHandlerForAuthenticatedUser(handlers)
: FindGuestHandler(handlers);
}
bool IsAuthenticated
{
get { return Thread.CurrentPrincipal != null; }
}
// ....
}
Only downside of handler selectors is that they're not pulled from the container - i.e. they're added as an instance to the container at registration time, so they don't get to have dependencies injected, lifestyle managed, etc., but there are ways to mitigate that - take a look at F.T.Windsor if you're interested in seeing how that can be done.
A: One way to solve this would be, Register the service with key and then resolve as you need.
public interface ISample
{
int Calculate(int a, int b);
}
class SampleB : ISample
{
public int Calculate(int a, int b)
{
return a + b + 10;
}
}
class SampleA : ISample
{
public int Calculate(int a, int b)
{
return a + b;
}
}
The registration:
container.Register(Component.For<ISample>().ImplementedBy<SampleA>().Named("SampleA").LifeStyle.Transient);
container.Register(Component.For<ISample>().ImplementedBy<SampleB>().Named("SampleB").LifeStyle.Transient);
// Resolve when SampleA needed.
var sampleA = container.Resolve<ISample>("SampleA");
// Resolve when SampleB needed.
var sampleB = container.Resolve<ISample>("SampleB");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502026",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: best fitting curve from plot in R I have a probability density function in a plot called ph that i derived from two samples of data, by the help of a user of stackoverflow, in this way
few <-read.table('outcome.dat',head=TRUE)
many<-read.table('alldata.dat',head=TRUE)
mh <- hist(many$G,breaks=seq(0,1.,by=0.03), plot=FALSE)
fh <- hist(few$G, breaks=mh$breaks, plot=FALSE)
ph <- fh
ph$density <- fh$counts/(mh$counts+0.001)
plot(ph,freq=FALSE,col="blue")
I would like to fit the best curve of the plot of ph, but i can't find a working method.
how can i do this? I have to extract the vaule from ph and then works on they? or there is same function that works on
plot(ph,freq=FALSE,col="blue")
directly?
A: Assuming you mean that you want to perform a curve fit to the data in ph, then something along the lines of
nls(FUN, cbind(ph$counts, ph$mids),...) may work. You need to know what sort of function 'FUN' you think the histogram data should fit, e.g. normal distribution. Read the help file on nls() to learn how to set up starting "guess" values for the coefficients in FUN.
If you simply want to overlay a curve onto the histogram, then smoo<-spline(ph$mids,ph$counts);
lines(smoo$x,smoo$y)
will come close to doing that. You may have to adjust the x and/or y scaling.
A: Do you want a density function?
x = rnorm(1000)
hist(x, breaks = 30, freq = FALSE)
lines(density(x), col = "red")
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502027",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Total characters (not code units) of a String in Java considering Supplementary Characters How can you obtain the total characters of a String, considering that it could have supplementary characters which takes 2 code units to be encoded.
Example:
String strTest = "a"; //Supplementary character
System.out.println(strTest.length());
Output:
3
As we can see if we use length() we obtain 3 instead of 2. What I want to obtain is the number of characters for a given String, not the number of code units.
A: Use:
string.codePointCount(0, string.length())
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502030",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How do I move an object back into my view I accidentally removed an object from a view into the canvas. How can I add it back? I have a simple example, but this happened on a bigger scale, so I don't what to recreate all the objects.
When I drag it back it isn't in the view it's just overtop of it.
Thanks
A: You need to expand the folder view on the left side where you currently just see the icons, click the little arrow next to the search bar on the bottom left corner of that section. Then, in that section, grab the view and you can drag the view under the larger view "folder" of the page. Hope that helps, its a little hard to explain.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502033",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: DEP preventing my COM DLL from working I'm trying to use a COM DLL (written in Delphi 7) within my Delphi 7 IntraWeb application but it's failing due to DEP. I'm pretty much certain it's DEP that is preventing me from using the DLL because if I compile and run my IntraWeb app as a StandAlone Server, everything works fine. But, compiling and runnning it as an ISAPI DLL, it fails.
On WinXP (using IIS 6) I can add DllHost.exe to DEP and everything works. Of course, I really don't want to do that. On Win7/2008 (IIS 7) this isn't an option.
Can someone point me in a direction that can help me get my COM DLL to work when called from an IntraWeb ISAPI DLL?
Do I need to do something to the COM DLL? Are there any permissions I can add somewhere?
Thanks,
Michael
A: i would host the dll inside a local executable, calling methods until the crash happens. You would do this with DEP enabled on your own machine.
Unfortunately Delphi 7 itself crashes with Data Execution Prevention enabled, in addition to memory violations in the RTL/VCL that TOndrej mentioned.
That is what you'll need to do to get your COM dll working with DEP - find the bugs and fix them.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502036",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: TextBox Input Constraints Problem I have input constraints on textbox that it will only accept the int and until it can be parsed by Int64. The question is it clears out because he is assigning to String.Empty but what if its is not parsable by Int64 then i want to suppress that keypress. I tried adding code to keydown event that i have but it will also suppress the Int keys.
public static void SetInt64Input(Control tb)
{
tb.KeyDown += (sender, e) => {
if (!IsIntKeyOrAlwaysAcceptableKey(e))
//if not int key suppress it; Ex: A,B,.etc
e.SuppressKeyPress = true;
};
tb.TextChanged += (s, e) => ClearAllNonInt64Inputs(tb);
}
private static void ClearAllNonInt64Inputs(Control tb)
{
long i;
if (!Int64.TryParse(tb.Text, out i))
tb.Text = String.Empty;
else
tb.Text = Int64.Parse(tb.Text).ToString();
}
i tried doing
if(!Int64.TryParse(((TextBox)sender).Text,out junk)
e.SuppressKeyPress = true;
but it dint work.
A: i am not sure whats the question.sorry.
But if the input is not parsable due to its out of length of Int64 (more than 4 bytes), then i think restricting the numbers of characters in the Textbox may help. And if its not parsable due to a non-integer value, then use of IsNotDigit function will be helpfull in keypress event.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502038",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Release locks on crash in Java I am writing a client-server application using Java-RMI. Some server-side ressources have to be accessed in mutual exclusion (I am using locks for that purpose).
Now I was wondering what happens when:
*
*The client calls a remote method on the server
*The remote method acquires a lock for a critical section
*The client crashes before the remote method exits the critical section
Will any locks acquired by the remote method call associated to that client be released? Or will it just be impossible for other clients to acquire the lock afterwards?
Thanks for your answers
A: What happens is that the remote method keeps executing until it is done, and releases the locks when it exits the critical section. Then it attempts to return the results (if any) to the client, and fails because the connection has been broken.
There is no particular hazard here ...
Of course, if the server is using Lock objects rather than primitive locks / mutexes, then it needs to do the lock releases in a finally block to deal with the case where it fails due to some unexpected exception. But this is a different issue. The client crashing won't trigger that scenario.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502045",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Can scripts in iframe interact with scripts in the main page I have an editor with an SWF multi-image uploader. Since not everyone will need to upload pictures in their article, i need to dynamically load this image uploader when necessary. I have to load it in an iframe because the uploader needs some external scripts to be loaded ahead. And since i need it's callback variable for my editor to use I want to know whether scripts in iframe can interacts with scripts in the main page. Or if i can't do that, what's the alternative way to do this?
A: If they are on the same domain, yes.
The parent object is the parent window of the iframe.
If you had a variable a in the global scope of the parent window, you could manipulate it in the iframe like this:
parent.a = "new value";
Similarly, if a is a function in the global scope of the parent window, you could call it like this:
parent.a(args);
A: postMessage in Html5, supported by Internet Explorer 8.0+, Firefox 3.0+, Safari 4.0+, Chrome 1.0+ and Opera 9.5+, is how I have been using it. If you don't mind the lack of support in IE7 and earlier versions, here's how to implement it.
Javascript in the main window:
window.addEventListener("message", receiveMessage, false);
function receiveMessage(event){
var source = event.source.frameElement; //this is the iframe that sent the message
var message = event.data; //this is the message
//do something with message
}
Javascript in the iframe;
var message='hello, big window!'; //could be of any type, string, number, array, object, have fun
window.parent.postMessage(message,'*'); //the '*' has to do with cross-domain messaging. leave it like it is for same-domain messaging.
Of course you could do it the other way round, having the main window sending messages to the iframe, and have some cross-window dialogue that way.
A: To extend Andy's answer Can scripts in iframe interact with scripts in the main page :
Use jQuery.postMessage plugin http://benalman.com/code/projects/jquery-postmessage/docs/files/jquery-ba-postmessage-js.html
Browsers Tested Internet Explorer 6-8, Firefox 3, Safari 3-4, Chrome, Opera 9.
A:
Can scripts in iframe interact with scripts in the main page
Only if the iframe and its parent have the exact same domain, due to the same origin policy (MDC link).
A: If the iframe is from a different domain, but you have control over the content, you can communicate between the two in a couple different ways. The simplest is to "talk" through key/value pairs in the URL of the iFrame, since both the parent and the iFrame have access to that.
A more complicated approach is to use iFrame proxy's, which is described really well here: http://www.julienlecomte.net/blog/2007/11/31/ which uses Yahoo Pipes to send messages back and forth quite nicely.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502047",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Loading content from Wordpress posts dynamically from clicked images I'm trying to insert content from separate Wordpress posts into an info box when an image is clicked. I'm using a modified template for this section of the site, where the images are populated from an array.
I have successfully made this work using the .load() method with jQuery and a static URL.
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('.dynagrid a').click(function(event){
// stop normal link click
event.preventDefault();
});
jQuery('.dynagrid a').click(function(){
jQuery('div.project-info').fadeToggle(function(){
jQuery(".infotext").load('/cowshed/akg .infotext > *', function() {
jQuery('div.project-info').fadeToggle()
});
});
});
});
My problem lies in making the loaded URL dynamic for each image - with each image loading different information. My plan was to grab the <alt> information for each image as a variable and insert this e.g. jQuery(".infotext").load('/cowshed/+alt+ .infotext >*'); and match it to the permalink of the desired post but everything I've tried has failed.
I've looked for hours for a solution on this and I fear my inexperience in jQuery is making this much harder than it may actually be.
Here's the page so far: Cowshed Tools
Can anyone see a solution and shed some light?
A: jQuery(".infotext").load('/cowshed/akg .infotext > *', function() {
^^^^^^^^^^^^^^^^^^^^^^^^^^
The indicated part should be the URL that'll provide the content you're loading into the .infotext element. You've got what looks like an unholy mishmash of url and CSS selectors, which is NOT a valid URL. Given you want to load things dynamically, it should be something:
.load('http://example.com/fetchcontent?contentID=' + this.alt, function () ....);
The url doesn't have to be absolute like that, but it should be a valid URL for your server.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502048",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is it possible to add images in datagridview cell dynamically? i am developing a small application in which i have to include images with other data from SQL but the images should be come from local disk depending on file name from database. is it possible to do it? how?
A: use TamplateField
<asp:GridView ID="myGridView" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<img src="<%#Eval("FileName")%>" alt="NoImage">
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Note you should set image tag source to relative path not physical path
Edit
in case of winforms as you mentioned in your comment you can use DataGridViewImageColumn in your DataGridVeiw and set its DataPropertyName property to a an Image instance.
check my simple example
class MyDataSource
{
// its value come from your database but now I will set it manually
public String imgurl
{
get;
set;
}
public Image img
{
get
{
return Image.FromFile(imgurl);
}
}
}
in from load
List<MyDataSource> mydatasource = new List<MyDataSource>();
mydatasource.Add(new urls() { imgurl = @"C:\image1.jpg" });
mydatasource.Add(new urls() { imgurl = @"C:\image2.jpg" });
mydatasource.Add(new urls() { imgurl = @"C:\image3.jpg" });
mydatasource.Add(new urls() { imgurl = @"C:\image4.jpg" });
//bind this collection to your datagridview
dataGridView1.DataSource = mydatasource;
in this sample I set DataPropertyName of DataGridViewImageColumn to img property
A: If I understood your question correctly, you have the image urls in the database and want to display those images in the gridview. If that is so, my suggestion would be to add an "asp:Image" tag to the gridview statically and update the "ImageUrl" attr using "Bind" method.
Hope this helps!!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502053",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Register file type for app does not work correctly I am using the following intent filter for my app.
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:mimeType="*/*" />
<data android:pathPattern=".*\\.etxt" />
</intent-filter>
But to my surprise, the app now wants to open other types too, like apk files. What is my mistake?
A: Try
<data android:pathPattern=".\\*.etxt" />
not <data android:pathPattern=".*\\.etxt" />
and please let me know if it works
A: I found this
"These attributes are meaningful only if the scheme and host attributes are also specified for
the filter."
so you should have scheme and host if you want to use android:pathPattern
it is on the official documentation
http://developer.android.com/guide/topics/manifest/data-element.html
Note this:
If a scheme is not specified for the intent filter, all the other URI attributes are ignored
so you will have to add scheme and host
A: I think I found a solution. At least, it works for Dropbox now.
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="file"/>
<data android:host="*"/>
<data android:mimeType="application/*"/>
<data android:pathPattern=".*\\.etxt" />
</intent-filter>
A: This has been some time ago, but I still do not have a proper solution. The solution in the answer below works in Dropbox, but will not open the app in Google mail, or in any file manager. And yes, the path pattern is correct.
I tried with mimeType text/* only, nothing else. This will not work, unless you name the files with extension *.txt. I cannot go this way, since in Windows there is a counterpart, which registers *.etxt for the files.
Then I tried with an additional scheme "content". This works for Google mail if I select a general mimeType, but will offer the app, if the user clicks on the new mail icon in the status bar. So it is too general.
In short, I did not find a way to solve this. It seems to depend on the way, the file managers and mail programs form an intent, and this is not predictable. I guess, it is simply an omission in the Android system.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502057",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: getting linking error due to different library for ios and iphonesimulator? I am using libiVisualizationChart.a library, there are separate libraries for iphoneos and iphonesimulator. I have added both the libraries in xcode project and mentioned both the library paths in Library Search Path, but I am able to build for simulator only not for device.
Can any one help me why I am getting the linking error?
Error:
"_OBJC_CLASS_$_VSColor", referenced from:
objc-class-ref-to-VSColor in ChartView.o
"_OBJC_CLASS_$_VSTransform3D", referenced from:
objc-class-ref-to-VSTransform3D in ChartView.o
A: Make sure that they are weak linked. In your project settings, under Build Phases, there is "Link Binary With Libraries" find the two libraries and set them to optional. This should clear up that linking error.
A: You can try by changing the order of libraries in the Library Search Path in build settings.
For device build iphoneos library should be above to iphonesimulator library and vice-versa.
let it should work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502058",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: ASP.NET DataGrid - Display nested array data I have a class like so:
public class ApplicationInformation
{
public string ApplicationName { get; set; }
public List<UserInformation> Users { get; set; }
}
I want to display a List<ApplicationInformation> in a DataGrid. So I tried this:
.aspx:
<asp:DataGrid ID="tbl" runat="server">
</asp:DataGrid>
.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
tbl.DataSource = Global.Data;
tbl.DataBind();
}
But that table only has a column titled ApplicationName. I want to have a column for each property in ApplicationInformation and UserInformation, and a separate row for every UserInformation in the list in the List<ApplicationInformation>.
I hope that made sense...
I looked into templates a bit, but couldn't figure out how to do this. I suppose I could always just loop through everything and create a separate array with all the data I need, but I'd have to make another class, and it just doesn't seem like that's the best way.
EDIT
For example, if I have a List<ApplicationInformation> like so:
{
{ ApplicationInformation
ApplicationName = "App 1"
{ UserInformation
UserName = "John Smith"
ApplicationHost = "JOHN-PC"
}
{ UserInformation
UserName = "Mindy from the network"
ApplicationHost = "MINDY-PC"
}
}
{ ApplicationInformation
ApplicationName = "App 2"
{ UserInformation
UserName = "John Smith"
ApplicationHost = "JOHN-PC"
}
{ UserInformation
UserName = "Bob Jones"
ApplicationHost = "BOB-PC"
}
}
}
Then I want the table to appear like this:
Application Name | User Name | Application Host
-------------------------------------------------------
App 1 | John Smith | JOHN-PC
App 1 | Mindy fro...| MINDY-PC
App 2 | John Smmith | JOHN-PC
App 2 | Bob Jones | BOB-PC
A: You can either handle ItemDataBound event or use linq to create an anonymous object and bind it to DataGrid
A: You may construct anonymous or typed list via Linq:
if (!IsPostBack)
{
List<ApplicationInformation> app = new List<ApplicationInformation>()
{
new ApplicationInformation()
{
ApplicationName="App 1",
Users=new List<UserInformation>()
{
new UserInformation()
{
UserName = "John Smith",
ApplicationHost = "JOHN-PC"
},
new UserInformation()
{
UserName = "Mindy from the network",
ApplicationHost = "MINDY-PC"
}
}
},
new ApplicationInformation()
{
ApplicationName="App 2",
Users=new List<UserInformation>()
{
new UserInformation()
{
UserName = "John Smith",
ApplicationHost = "JOHN-PC"
},
new UserInformation()
{
UserName = "Bob",
ApplicationHost = "BOB-PC"
}
}
}
};
var result = from ele in app
from user in ele.Users
select new
{
ApplicationName=ele.ApplicationName,
UserName=user.UserName ,
ApplicationHost=user.ApplicationHost
};
GridView1.DataSource = result.ToList();
GridView1.DataBind();
}
A: You need to handle RowDataBound as Junaid suggested but you need to have a template column which in itself could be another Datagrid or a List of some sort to Bind List<UserInformation> to it.
For example (Untested code):
void CustomersGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
//find nested grid
GridView nestedGrid = e.FindControl("NestedGridID") as GridView;
nestedGrid.DataSource = DataBinder.Eval(e.DataItem,"Users");
nestedGrid.DataBind();
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502067",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Java Security Testing Is there such a thing as automated security testing in Java? If so, how is it implemented? Is it just JUnit tests written to try and exploit known server vulnerabilities, or are their security-centric testing frameworks?
As a segue I'm also interested in this OWASP Security Testing Framework, but can't tell if they're using "framework" in a classic sense (meaning a set of guidelines and procedures to follow), or in a software context (where they are actually providing automated security testing components).
Thanks to any that can shed some light on this for me!
A: Don't know is it exactly what you are looking for, but there is a blog post by Stephen Colebourne (author of joda-time and future new standard java8 date-time API) about testing security permissions with junit: Stephen Colebourne's blog: Testing a security permission
A: Fuzz testing never hurts: http://www.ibm.com/developerworks/java/library/j-fuzztest/index.html
Fuzz testing helps you make sure that your application is secure against any opportunity for user input.
Fuzz testing is a little awkward for JUnit tests in a way, because they are "random". You might want to loop and run a number of fuzz tests on each input avenue in a test suite.
A: Tools like Sonar and FindBugs can also be an automated way to find at least some security issues (FindBugs is at quite effective at finding risks of SQL injection and such).
A: There are commercial tools such as VeraCode that do security scanning. I don't work for them but my company uses it. It seems quite thorough.
A: Automated security testing is hard but that doesn't mean its not worth doing.
My suggestion for web apps - use your existing Unit and Integration tests (like Selenium) and then proxy them through a security tool like OWASP ZAP (Zed Attack Proxy).
See http://code.google.com/p/zaproxy/wiki/SecRegTests for more details.
Simon (ZAP Project Lead)
A: It depends what your Java app actually is. If you are building a web service/API, for example, OWASP have a separate Top 10 just for API's which have things listed in a different priority than the regular top 10. See OWASP Project API Security
According to Nordic API's, you might find that it involves a lot of manual testing since you can't automate much of, good explanation of the API top 10 here: https://nordicapis.com/testing-owasps-top-10-api-security-vulnerabilities/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502069",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: How can I create an array of the directory contents in Dropbox with PHP I need to create an array of the directory contents in Dropbox with PHP and save it in a variable. Any thoughts?
Edit:
With this I mean from a web server, not locally.
A: This should help
function getDirOptions($path) {
$back = "";
if ($handle = opendir($path)) {
while (false !== ($res = readdir($handle))) {
$options.="<OPTION VALUE='$res'>$res</OPTION>";
}
closedir($handle);
}
$back = "<SELECT NAME='dir'>$options</SELECT>";
return $back;
}
A: You'll want to be using the Dropbox API, there's a PHP library for it.
Specifically, you'll need the getMetaData function.
$files_in_directory = $DropboxObject->getMetaData ("directory/you/want", true);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502071",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: loading images from a background thread using blocks I have the following method, which basically calls a request to load an array of NSData of images in the background thread:
[query findObjectsInBackgroundWithBlock:^(NSArray * objects, NSError * error){
}];
In this case objects is an array of the NSData. The issue is that if I have 100 images to load (100 elements in the array). This means that the user will have to wait for quite some time to see any image showing up in a UITableView. What I want to do is for them to see an image once it is available/loaded.. do I have to then change the code so that it does 100 background threads to load the image?
A: you could implement something like this in your cellForRowAtIndexPath:
That way you load each image in the background and as soon as its loaded the corresponding cell is updated on the mainThread.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^(void) {
NSData *data0 = [NSData dataWithContentsOfURL:someURL];
UIImage *image = [UIImage imageWithData:data0];
dispatch_sync(dispatch_get_main_queue(), ^(void) {
UIImageView* imageView = (UIImageView*)[cell viewWithTag:100];
imageView.image = image;
});
});
A: You can create NSInvocationOperation and set it to NSOperationQueue
for example:
Initializing NSOperationQueue:
NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];
After create NSInvocationOperation:
NSInvocationOperation* downloadOperation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(selectorToDownloadImage:) object:YouData];
[operationQueue addOperation:downloadOperation];
[downloadOperation release];
A: No, you don't have to create that many background threads. Use NSOperationQueue.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502073",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Opencv push_back function in Mat I`m having serious problem.
class Set
{
Point_<int> point;
int val;
double *module;
};
Mat m;
Set s;
m.push_back(s);
It says
see reference to function template instantiation 'void cv::Mat::push_back(const _Tp &)' being compiled
When i add after push_back it brings me:
see reference to class template instantiation 'cv::Mat_<_Tp>' being compiled
A: Gotta admit that I'm not familiar with OpenCV, but reasoning from this documentation, push_back member function of the Mat class seems to be a template function and it needs to know the type of the object you are going to "push back". So possibly try this:
m.push_back<Set>(s);
If doesn't work, the last suggestion would be
Mat<Set> m;
Set s;
m.push_back(s);
A: You could write
#include<vector>
class Set
{
Point_<int> point;
int val;
double *module;
};
std::vector<Set> m;
Set s;
m.push_back(s);
A: I don't think you can push_back anything that is not OpenCV primitive types. Why not just use a STL container?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502074",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Script to find the snapshot job for my replication publisher Is there a way, via script, to see what the name of the job is that will fire the snapshot for my replication?
This is for my Development environment. I am rebuilding my databases automatically via a visual studio database project. I have my replication setup automated, but I still have to fire the snapshot job manually in the morning.
I would like to be able to call:
sp_start_job 'JobThatWillTakeTheSnapShotForMyPublisher'
The problem is that the name of the job changes after every time I run my auto deploy (it adds a number to the end of the job name.)
If there is no way to find this out, is there a way to deterministically set the name of the job myself?
A: You can find snapshot jobid in replication tables syspublications for transactional replication and sysmergepublications for merge replication, for example:
declare @jobId uniqueidentifier
use <MyPublicationDB>
set @jobId = (
select snapshot_jobid from syspublications
where name = '<MyPublication>')
select @jobId
A: This is what I came up with:
declare @jobId uniqueidentifier
declare @jobName sysname
select @jobId = jobs.job_id, @jobName = jobs.name
from msdb.dbo.sysjobs jobs (nolock)
join msdb.dbo.syscategories categories (nolock)
on jobs.category_id = categories.category_id
where categories.name = 'REPL-Snapshot'
and jobs.name like '%MyPublisherNameHere%'
select @jobId, @jobName
exec sp_start_job @job_id = @jobId
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502078",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Releasing Objects In an NSOperation I've subclassed NSOperation and add instances of it to an NSOperationQue when I need it.
In the main function of the NSOperation I create an AudioBufferList and then free it when I'm done.
In the memory allocation section of instruments it's showing that instances of these AudioBufferLists are constantly climbing. The living number of bytes constantly climbs and the mdata part of the buffer appears to be the culprit.
This is a segment of my code.
Am I correctly releasing my bufferlist or could instruments be reporting incorrectly?
-(void)main
{
//autorelase stuff in here
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
AudioBufferList *bufferList;
bufferList = (AudioBufferList *) malloc (
sizeof (AudioBufferList) + sizeof (AudioBuffer) * (1)
);
if (NULL == bufferList) {NSLog (@"*** malloc failure for allocating bufferList memory"); return;}
// initialize the mNumberBuffers member
bufferList->mNumberBuffers = 2;
// initialize the mBuffers member to 0
AudioBuffer emptyBuffer = {0};
size_t arrayIndex;
for (arrayIndex = 0; arrayIndex < 2; arrayIndex++) {
bufferList->mBuffers[arrayIndex] = emptyBuffer;
}
// set up the AudioBuffer structs in the buffer list
bufferList->mBuffers[0].mNumberChannels = 1;
bufferList->mBuffers[0].mDataByteSize = numberofframestoread * sizeof (AudioUnitSampleType);
bufferList->mBuffers[0].mData = (AudioUnitSampleType*)calloc(numberofframestoread, sizeof(AudioUnitSampleType));
if (2 == 2) {
bufferList->mBuffers[1].mNumberChannels = 1;
bufferList->mBuffers[1].mDataByteSize = numberofframestoread * sizeof (AudioUnitSampleType);
bufferList->mBuffers[1].mData = (AudioUnitSampleType*)calloc(numberofframestoread, sizeof(AudioUnitSampleType));
}
AudioUnitSampleType *inSamplesChannelLeft=bufferList->mBuffers[0].mData;
AudioUnitSampleType *inSamplesChannelRight=bufferList->mBuffers[1].mData;
// do stuff with buffer here
free(bufferList);
bufferlist=nil;
[pool release]
}
A: Your mData is the culprit, make sure you free those as well since you allocate them as calloc.
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
const size_t nBuffers = 2;
AudioBufferList *bufferList;
bufferList = (AudioBufferList *) malloc (
sizeof (AudioBufferList) + sizeof (AudioBuffer) * (nBuffers - 1)
);
if (NULL == bufferList) {NSLog (@"*** malloc failure for allocating bufferList memory"); [pool drain]; return;}
// initialize the mNumberBuffers member
bufferList->mNumberBuffers = nBuffers;
//...
bufferList->mBuffers[0].mData = (AudioUnitSampleType*)calloc(numberofframestoread, sizeof(AudioUnitSampleType));
//...
bufferList->mBuffers[1].mData = (AudioUnitSampleType*)calloc(numberofframestoread, sizeof(AudioUnitSampleType));
//...
//Free mData here
for(size_t i = 0; i < nBuffers; i++)
free(bufferList->mBuffers[i].mData);
free(bufferList);
[pool drain];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502080",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Bilingual mvc application I'm following the example here : http://www.codeproject.com/KB/aspnet/BilingualMvc3Part2.aspx
Edit:
This solution works for Firefox, and IE, but not in Chrome. It is changing the culture (en to fr) but not appending the rest of the current route.
Anyone seen this before?
A: My GAC was not cleared, and the temp service created by visual studio had not been restarted. I have retested IE, firefox, and chrome with this solution and am not having any more troubles.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502081",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Cannot get certain COMs to register using Visual Studio Deployment I'm deploying an MSI that includes several C++ COMs. We're adapting it to work on Windows 7/Server 2008, and for some reason self registering the COMs no longer works. As a result, I've changed them all to be COMRelativePath.
This seemed to have worked, but 3 of the components are, mysteriously, not registering. During the build of the installer I see this message for those that are not registering:
WARNING: Unable to create registration information for file named 'ComponentThatWontRegister.dll'
Having done extensive research and tried every work-around, I cannot get past this. I've tried setting both RegCap.exe and devenv to run in various compatibility modes and elevated to administrative privelages. I've tried Visual Studio 2010, same issue.
The odd thing is that most of the COMs register just fine and they are ALL set the same way; it's only a very few that are having this issue. I've gone through the COMs item by item and I can't find anything that would make one fail and another succeed. Also, on the same system if I register the com using regsvr32 it works so long as I run the command prompt as administrator.
A: This indicates that the error can occur if two or more components in the msi have the same progid. Could this be the cause?
A: If these are ATL controls, some may link with ATL.DLL, some not. Depending on the deployment target versus build machine, you may get an ATL.DLL that is UAC aware whilst the static regsitrar using ones are not, when compiled against an older platform SDK.
Compare the linker options of the components that fail to the ones that succeed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502082",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to check if a Flex application is run on a developer machine? I know I could use "BrowserManager.getInstance()" to find out which from URL is my app running, but it doesn't work as I would expect (you can't read url in one line - you have to wait for an event).
Is it possible to do it in some simple way? Like you do in Flash:
if (this.getDepth() == -16384)
A: This is how I do it
var lc:LocalConnection = new LocalConnection();
switch ( lc.domain ){
case "":
case "localhost":
trace('on a dev machine')
break;
case 'your.domain.com':
default:
trace('not dev so fall through')
}
A one liner could be done like
if(new LocalConnection().domain == "localhost" )
A: import flash.system.Security;
Security.sandboxType == Security.REMOTE
That tells you when it's running on the web.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502083",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to create an Asynchronous Script Component in SSIS? I might be blind, but I don't see how to CREATE the script component. I'm not asking why do an asynchronous, how to work with it, etc. I just want to know how to add it to my package, or how to transform an already existing component into an asynchronous one!
I'm using VS2008 with MSSQL 2008 R2.
A: I found how :
*
*Go in the Script Transformation Editor
*Select "Inputs and Outputs" from the leftmost part of the screen.
*Select your Output.
*Set "SynchronousInputID" to "None".
Thanks to this site.
A: Creating an Asynchronous Transformation with the Script Component
First bullet point under "Configuring Inputs, Outputs, and Output Columns"
Set the SynchronousInputID property of each output to zero to indicate
that the output does not simply pass through data from an upstream
component or transform it in place in the existing rows and columns.
It is this setting that makes the outputs asynchronous to the input.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502084",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: jquery events on non-present elements Is it bad to tie events to ids that aren't on the page in certain circumstances (based on PHP)? Will it cause code errors and slowness, or will jQuery automatically ignore them?
Should I instead put something like the following on every element that might not be there?
if ( $('#element') ){
$('#element').click(function(event) {}
}
My page setup is a certain edit box is not loaded under certain conditions to keep functions from being tried.. I set it up with a conditional php include because it's based on circumstances in the database that I don't really want to pass through to the front-end.
Right now all the js for the on page is in a single file with a number of functions.
A: $("selector") will always return a jquery object that has the list of elements that have matched your selector.
if($("#nonexistantelement")) { /* this always happens*/ }
Whatever is inside your if will always be true, because Objects are truthy. If you really wanted do that then you'd want to say something like:
if($("#nonexistantelement").length > 0) { /* this only happens if you have something */ }
That will tell you if you have actually matched to your elements. But there is no harm in just calling .click(function) on an empty jquery set. Because all jquery does is iterate over the elements matched by the selector and apply that listener. If there are no elements in the set, then it doesn't get applied, and as essentially a noop.
Now if you want to bind callbacks to elements that dont exist yet, then look into .live() and delegate()
A: When jQuery selector doesn't return any elements, no events are being bound. So you're making no harm by not writing if statement.
This means that internally jQuery binds event handler to all matched elements. When there are none, no handler will get bound to any element. This means: you don't have to check element existence in your code.
Future reference
Whenever you're doing
if ( $('#element') ){
$('#element').click(function(event) { /* blah blah */ });
}
you should rather save selector results
var result = $('#element');
// check number of elements (zero equals false, anything else equals true)
if (result.length) {
result.click(function(event) {
// blah blah
});
}
result.length is same as result.size().
Binding event handlers to non existing elements
If your interface will generate new elements and you'd like them to have eevent handlers attached when they get added to DOM, then you should use delegate() function. There's also live() function but use the first one whenever possible, because it is a better alternative. There are numerous resources on the net why this is true. This Stackoverflow answer for instance.
Note: As of jQuery 1.7, .delegate() has been superseded by the .on() method. For earlier versions, however, it remains the most effective means to use event delegation.
See jQuery documentation.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502094",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Tomcat & Apache with mod_jk partly working I have a grails app running on a tomcat server that is pointed to by apache 2.2 http server. Using mod_jk I've gotten it to work using myapp.com:9090 to get to the app. However myapp.com just gives me 503 with the error:
"Could not reliably determine the server's fully qualified domain name, using 193.xx.xxx.xxx for ServerName."
But this is the only error I get.
The virtual host looks like this:
<VirtualHost 193.xx.xxx.xxx:80>
ServerName www.myapp.se
ServerAlias myapp.se
DocumentRoot "D:/apache-tomcat-7.0.5/webapps/ROOT"
JkMount /* worker1
</VirtualHost>
In the httpd.conf i load the module like this:
# Load module
LoadModule jk_module modules/mod_jk.so
# Where to find workers.properties
JkWorkersFile conf/workers.properties
# Where to put jk logs
JkLogFile logs/mod_jk.log
# Set the jk log level [debug/error/info]
JkLogLevel emerg
# Select the log format
JkLogStampFormat "[%a %b %d %H:%M:%S %Y] "
# JkOptions indicate to send SSL KEY SIZE,
JkOptions +ForwardKeySize +ForwardURICompat -ForwardDirectories
# JkRequestLogFormat set the request format
JkRequestLogFormat "%w %V %T"
And the workers.properties looks like this:
workers.tomcat_home="D:/apache-tomcat-7.0.5"
workers.java_home="C:/Program Files/Java/jdk1.6.0_22"
ps=/
worker.list=worker1
worker.worker1.port=8010
worker.worker1.host=localhost
worker.worker1.type=ajp13
worker.worker1.lbfactor=1
A: Have you tried mod_proxy_ajp? I have a Grails app in production that uses Apache 2.2, Tomcat 6x, Grails 1.3.7 with Apache proxying to Tomcat w/o issue using mod_proxy_ajp. If you're not restricted to using mod_jk, I recommend giving this a try. And I have this working on Centos 5.5, Ubuntu 10.4LTS and Win2k3 environments, FYI.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502096",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Animating UILabel with CoreAnimation / QuartzCore in iOS App I actually stuck on a problem with animating a UILabel in my iOS Application.
After 2 days of searching the web for code snippets, still no result.
Every sample I found was about how to animate UIImage, adding it as a subview to UIView by layer. Is there any good example about animating a UILabel?
I found a nice solution for a blinking animation by setting the alpha property, like this:
My function:
- (void)blinkAnimation:(NSString *)animationID finished:(BOOL)finished target:(UIView *)target
{
NSString *selectedSpeed = [[NSUserDefaults standardUserDefaults] stringForKey:@"EffectSpeed"];
float speedFloat = (1.00 - [selectedSpeed floatValue]);
[UIView beginAnimations:animationID context:target];
[UIView setAnimationDuration:speedFloat];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(blinkAnimation:finished:target:)];
if([target alpha] == 1.0f)
[target setAlpha:0.0f];
else
[target setAlpha:1.0f];
[UIView commitAnimations];
}
Call my function on the UILabel:
[self blinkAnimation:@"blinkAnimation" finished:YES target:labelView];
But how about a Pulse, or scaling animation?
A: Unfortunately font size is not an animatable property of NSView. In order to scale a UILabel, you'll need to use more advanced Core Animation techniques, using CAKeyframeAnimation:
*
*Import the QuartzCore.framework into your project, and #import <QuartzCore/QuartzCore.h> in your code.
*Create a new CAKeyframeAnimation object that you can add your key frames to.
*Create a CATransform3D value defining the scaling operation (don't get confused by the 3D part--you use this object to do any transformations on a layer).
*Make the transformation one of the keyframes in the animation by adding it to the CAKeyframeAnimation object using its setValues method.
*Set a duration for the animation by calling its setDuration method
*Finally, add the animation to the label's layer using [[yourLabelObject layer] addAnimation:yourCAKeyframeAnimationObject forKey:@"anyArbitraryString"]
The final code could look something like this:
// Create the keyframe animation object
CAKeyframeAnimation *scaleAnimation =
[CAKeyframeAnimation animationWithKeyPath:@"transform"];
// Set the animation's delegate to self so that we can add callbacks if we want
scaleAnimation.delegate = self;
// Create the transform; we'll scale x and y by 1.5, leaving z alone
// since this is a 2D animation.
CATransform3D transform = CATransform3DMakeScale(1.5, 1.5, 1); // Scale in x and y
// Add the keyframes. Note we have to start and end with CATransformIdentity,
// so that the label starts from and returns to its non-transformed state.
[scaleAnimation setValues:[NSArray arrayWithObjects:
[NSValue valueWithCATransform3D:CATransform3DIdentity],
[NSValue valueWithCATransform3D:transform],
[NSValue valueWithCATransform3D:CATransform3DIdentity],
nil]];
// set the duration of the animation
[scaleAnimation setDuration: .5];
// animate your label layer = rock and roll!
[[self.label layer] addAnimation:scaleAnimation forKey:@"scaleText"];
I'll leave the repeating "pulse" animation as an exercise for you: hint, it involves the animationDidStop method!
One other note--the full list of CALayer animatable properties (of which "transform" is one) can be found here. Happy tweening!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502098",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: AS3: scripting a cross domain loaded swf I'm having some strange inter-domain loading behaviour. I need to give my loading swf access to my loaded swf's classes and methods across domains, but despite all my applicationDomain settings and cross domain settings, I'm not being able to cast it to a usable type across domains, but it works perfectly same domain.
The scenario:
Application on domain A loads a skin from domain B (actually all part of a massive domain structure (test.domain.co.uk, assets.domain.co.uk, etc), but for Flash's purposes they are different). Currently some of the files are on a testing environment and will move through several environments before it goes live, so I'm keeping all security calls relatively loose. There are crossdomain.xml files all over the place.
the loading code:
_skinLoader = new Loader();
addChild(_skinLoader);
var context:LoaderContext = new LoaderContext();
context.applicationDomain = new ApplicationDomain(ApplicationDomain.currentDomain);
_skinLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, skinError, false, 0, true);
_skinLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, skinLoaded);
var skinurl:String = "http://www.domainB/skins/skin.swf";
var request : URLRequest = new URLRequest(skinurl);
_skinLoader.load(request, context);
the COMPLETE event code:
onSkinLoaded(e:Event):void{
addChild(_skinLoader);
_skin = e.currentTarget.content as ISkin;
trace("SHELL: Skin loaded:"+_skin); //======== traces out null when x-domain but traces out[object SkinObject] on the same domain or in the IDE
trace("SHELL: Skin target:"+e.currentTarget.content); //===== traces out [object SkinObject] on both
...............
}
So it works when the skin is on the same domain as the shell application, but not when they are separate. As you may tell from the code above the skin implements ISkin and extends and abstract class ASkin; to deal with security I have the following as the constructor of the skin class (which is the base class of the fla).
public function SkinObject(){
Security.allowDomain(this.root.loaderInfo.loaderURL);
super();
}
Other info:
*
*Traces in the skin constructor class fire
*When the skin is on the same domain if I test (e.currentTarget.content is ISkin) I get true, when on separate domains, I get false
*There are no security events
*I have tried setting the loader context to new ApplicationDomain as well.
A: Ok. I've discovered the answer on one of the brilliant senocular's pages: http://www.senocular.com/flash/tutorials/contentdomains/?page=1
Essentially the problem can be overcome by merging the Security Domains of the two swfs and to set the applicationDomain to the same. Below is a quote from the above page (example urls have a / in them to prevent them becoming links):
To load another SWF into the security domain of your own, you would need to call Loader.load with an instance of a LoaderContext object. The securityDomain property of that LoaderContext is set to a reference to the current security domain. This is accessible through SecurityDomain.currentDomain. In setting this value, the loader SWF expresses trust in the SWF that is to be loaded, while that SWF expresses trust through a policy file.
h/ttp://host.example.com/parent.swf:
trace(new LocalConnection().domain); // host.example.com
var loader:Loader = new Loader();
// create a LoaderContext that indicates that
// the loaded SWF will be loaded into this
// security domain
var context:LoaderContext = new LoaderContext(true);
context.securityDomain = SecurityDomain.currentDomain;
var url:String = "http://trusting.example.com/child.swf";
loader.load(new URLRequest(url), context);
h/ttp://trusting.example.com/crossdomain.xml:
<?xml version="1.0"?>
<cross-domain-policy>
<allow-access-from domain="host.example.com"/>
</cross-domain-policy>
h/ttp://trusting.example.com/child.swf:
trace(new LocalConnection().domain); // host.example.com
Using the domain property of a LocalConnection instance, the security domain is checked for each SWF. Though the child SWF originated from the trusting.example.com domain, it's shown as being within the host.example.com domain because the parent SWF loaded it into its own security domain.
I hope that helps someone from spending 3 days going around and around in circles. Thank you senocular!
A: This line of code will not do what you expect it to:
Security.allowDomain(this.root.loaderInfo.loaderURL);
I'm pretty sure that the root URL of the swf you're loading from domain B to A will still be domain B, otherwise the crossdomain policy system wouldn't even work in the first place, because any/all swfs loaded from X domain to A domain would automatically become a child of domain A (with this logic).
You need to write a crossdomain policy file and place it in both domain A and domain B giving explicit permission for domain B to interact with A, and A with B. Here is an example of a crossdomain policy file that will grant permission to anyone loading the swfs in the domain.
<?xml version="1.0" ?>
<cross-domain-policy>
<allow-access-from domain="*" />
</cross-domain-policy>
Taken from this question/answer:
Can someone post a well formed crossdomain.xml sample?
A: DomainA swf:
When loading the swf from domainB is loading crossdomain.xml from domainB.
if this will not help then:
inside SWF on DomainA add:
System.allowDomain ( 'DomainB' );
crossdomain.xml basicaly needed for images / videos and other type of files.
Swf;s needs to be taked care sepparately:
inside SWF on DomainB add:
System.allowDomain ( 'DomainA' );
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502100",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Selecting all checkboxes with jQuery I simply want to check all of the check boxes on a page if a user clicks the "Select All" button.
In the body:
<button id="checkall">Select All</button>
jQuery:
<head>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#checkall').click(function () {
$("input[type=checkbox]").each( function() {
$(this).attr('checked', true);
});
});
</script>
</head>
And the checkboxes are generated by a little bit of php:
echo '<li>';
echo '<input type="checkbox" name="checkbox[]" value="'.$x.'" />'.$x.'<br/>';
echo '</li>';
Can anyone tell me what I'm doing wrong?
A: You dont need the each statement. Just select all checkboxes and set the property checked = true.
$(document).ready(function(){
$('#checkall').click(function () {
$("input:checkbox").prop('checked', true);
});
});
Note jQuery.prop() is a feature added to 1.6 and up. If you are on a version of jQuery prior to 1.6 you will need the following.
$(document).ready(function(){
$('#checkall').click(function () {
$("input:checkbox").attr('checked','checked');
});
});
A: Instead of selecting checkbox with tag name better assign it some class and select it with classname
$(document).ready(function(){
$('#checkall').click(function () {
$(".checkbox").each( function(i,chkbox) {
$(chkbox).attr('checked', true);
});
});
});
php code
echo '<li>';
echo '<input type="checkbox" class="checkbox" name="checkbox[]" value="'.$x.'" />'.$x.'<br/>';
echo '</li>';
A: You just miss a }); for the .each(function(){} statement! There was no error else!
$(document).ready(function () {
$('#checkall').click(function () {
$("input[type=checkbox]").each(function () {
$(this).attr('checked', 'checked');
// or
// $(this).attr('checked', true);
}); // you missed this one!!!
});
});
A: This Will Work, Short and handy Code
<script>
$('#check_all').click(function () {
$( this ).closest('form').find(':checkbox').prop( 'checked' , this.checked ? true : false );
})
</script>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502104",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Best practice create a C# Object which reflect and generate a Serialized string This question may be asked or answered before but I feel that none of the hits really apply.
I would like to create a little class with attributes which will correspond to name and attributes in a output familiar to xml stream. The class should help the program to create a xml-alike string.
string test = "<graph caption='SomeHeader' attribute9='#someotherinfo'>" +
"<set name='2004' value='37800' color='AFD8F8' />" +
"<set name='2005' value='21900' color='F6BD0F' />" +
"<set name='2006' value='32900' color='8BBA00' />" +
"<set name='2007' value='39800' color='FF8E46' />" +
"</graph>";
I think you got the idea. I have a static amount of known attributes which will be used in the tags. The only Tags here is set and graph.
I would like to do something like this,
Helper o = new Helper()
List<Tag> tag = new List<Tag>();
foreach (var someitem in somedatabaseresult)
{
tag.Add(New Graph() { Caption = someitem.field , attribute9 = someitem.otherField });
foreach (var detail in someitem)
{
tag.Add(new Set() { name = detail.Year, value = detail.Value color = detail.Color });
}
}
o.Generate(); // Which will create the structure of result sample above
// and for future extension..
// o.GenerateXml();
// o.GenerateJson();
Please remember that this code is pesudo, just taken from my head. A result of that I have some ideas but it take a day to code and test what best (or whorse).
What would be best practice to solve this task?
[EDIT]
This mysterious "Helper" is the (unluckily typed) class who contains a list of Graph, a list of Set and also (what I think about) contains all available attributes per Graph/Set object. The work of the foreach-loops above are mentioned to fill the Helper class with the data.
[EDIT2]
Result here,
https://gist.github.com/1233331
A: Why not just create a couple of classes: Graph and Set. Graph would have a property of List<Set>.
In your foreach you can then create an instance or Graph and add instances of Set to its list.
When you're done use the XML Serializer to serialize the Graph object out to XML. Nice and easy to then output to another format as well if your needs change later e.g. serialize to JSON.
Edit following comment:
From top my head so may not be 100% correct...
var myGraph = BuildMeAGraph();
var serializer = new XmlSerializer(typeof(Graph));
var writer = XmlWriter.Create("myfile.xml");
serializer.Serialize(writer, myGraph);
But something like that should write it out to a file. If you want the XML in memory then write it out to an XMLTextWriter based on a memory stream instead and then you can write the contents to a string variable or do whatever you need with it.
A: If you want to create an XML, out of the object tree, then I think, you could try this:
XDocument doc = new XDocument
(
somedatabaseresult.Select
( someitem =>
new XElement("graph",
new XAttribute("Caption", ""),
new XAttribute("attribute9", "#something"),
someitem.Select
(detail =>
new XElement("Set",
new XAttribute("name", "2003"),
new XAttribute("value", "34784"),
new XAttribute("color", "#003300")
)
)
);
//save to file as XML
doc.Save("output.xml");
//save to local variable as XML string
string test = doc.ToString();
I wrote the save value for tags, as you've used in your code. However, I think you would like this:
new XAttribute("name", detail.name),
new XAttribute("value", detail.value),
new XAttribute("color", detail.color)
Or whatever value you want to give to each attribute from the object detail.
A: Use the XmlSerializer.
A: I'd use the ExpandoObject, but I don't see the reason for what you are doing.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502106",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Device Type identification from MAC address Can I determine if a device is IPhone/IPad/IPod or Android from its MAC address ? MAC addresses can be used to identify the manufacturer but can I distinguish a Macbook pro from an IPhone ?
A: Unless Apple uses unique wifi chipset suppliers for a Macbook that would never be used for an iphone (e.g. samsung for iphone and toshiba for macbook), a mac address will only ever tell you who manufactured the particular wifi chip in use. Maybe certain ranges of mac addresses would only ever show up in one type of device, but you'd have to compile that list yourself.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502107",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Java-Based Regression Testing How is regression testing performed in Java? Are there automated regression test frameworks or do you just write (JUnit) unit tests that help ensure against regressions?
Is there a way or set of best practices for coding unit tests so that they also serve the dual purpose of being regression tests, or do you need to keep regression tests separate from your unit tests?
A: Regression testing has nothing to do with a language. It is a technique that is used to ensure future code changes do not break existing features. In Java you can use junit or testng or anything else. Typically a regression test is a functional test and is not a pure unit test.
A: JUnit is generally aimed for unit tests rather than full-scale functional testing (of which regression testing is an example if one is looking at the system as a whole).
However, it is not uncommon to use a separate test suit to perform "heavy" functional and integration tests that connect to actual backends, etc., and verify results against expectations.
One reason for the use of JUnit here is the ability to go from 'mocked tests' to actual functional tests using dependency injection. You could provide, for example, a mock collaborator in the lighter test, and an actual collaborator instance in the full functional test.
A: A regression test is any test that catches regressions.
If you want acceptance tests I've heard good things about FitNesse.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502113",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: what causes "Installation Error: Unknown Reason -110" when installing Market applications? When I install applications from Android Market, I get an Installation error (Unknown reason -110). I can't seem to find out what this error code means, are there any resources available to look up error codes on Android?
Somebody wrote the code and must know what this error code means, but where can I look to find out the meaning of this or other error codes?
A: If your phone is rooted and you're using Titanium and you recently use the "freeze" option on some of your system apps, this could cause your error message 110. The solution is to "de-freeze" the system app, reboot your phone and you should be good to go.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502114",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to use session in TestCase in Django? I would like to read some session variables from a test (Django TestCase)
How to do that in a clean way ?
def test_add_docs(self):
"""
Test add docs
"""
# I would access to the session here:
self.request.session['documents_to_share_ids'] = [1]
response = self.client.get(reverse(self.document_add_view_id, args=[1]), follow=True)
self.assertEquals(response.status_code, 200)
A: If you need to initialize a session for the request in tests to manipulate it directly:
from django.contrib.sessions.middleware import SessionMiddleware
from django.http import HttpRequest
request = HttpRequest()
middleware = SessionMiddleware()
middleware.process_request(request)
request.session.save()
A: As of Django 1.7+ this is much easier. Make sure you set the session as a variable instead of referencing it directly.
def test_something(self):
session = self.client.session
session['somekey'] = 'test'
session.save()
andreaspelme's workaround is only needed in older versions of django. See docs
A: Unfortunately, this is not a easy as you would hope for at the moment. As you might have noticed, just using self.client.session directly will not work if you have not called other views that has set up the sessions with appropriate session cookies for you. The session store/cookie must then be set up manually, or via other views.
There is an open ticket to make it easier to mock sessions with the test client: https://code.djangoproject.com/ticket/10899
In addition to the workaround in the ticket, there is a trick that can be used if you are using django.contrib.auth. The test clients login() method sets up a session store/cookie that can be used later in the test.
If you have any other views that sets sessions, requesting them will do the trick too (you probably have another view that sets sessions, otherwise your view that reads the sessions will be pretty unusable).
from django.test import TestCase
from django.contrib.auth.models import User
class YourTest(TestCase):
def test_add_docs(self):
# If you already have another user, you might want to use it instead
User.objects.create_superuser('admin', 'foo@foo.com', 'admin')
# self.client.login sets up self.client.session to be usable
self.client.login(username='admin', password='admin')
session = self.client.session
session['documents_to_share_ids'] = [1]
session.save()
response = self.client.get('/') # request.session['documents_to_share_ids'] will be available
A: If testing my django project with pytest, I can not see any modifications to the session that are made in the view. (That is because the Sessions middleware doesn't get called.)
I found the following approach to be useful:
from unittest.mock import patch
from django.test import Client
from django.contrib.sessions.backends import db
def test_client_with_session():
client = Client()
session = {} # the session object that will persist throughout the test
with patch.object(db, "SessionStore", return_value=session):
client.post('/url-that-sets-session-key/')
assert session['some_key_set_by_the_view']
client.get('/url-that-reads-session-key/')
This approach has the benefit of not requiring database access.
A: You should be able to access a Client's session variales through its session property, so I guess self.client.session['documents_to_share_ids'] = [1] should be what you are looking for!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502116",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "22"
} |
Q: Problem with selecting the item in ListView? I've designed one application. It lists all the installed application's on device or emulator which is you're using.See this. It's my result from emulator. In that List the that i can checked the item when i select checkbox only. But, i can't select any item by pressing that item. Am design this program extends by Activity only. And, also am using Adapter for listing that. How can i select the item by pressing item. How can i done this? Advance thanks.
A: Because your list view contains a checkbox, android is letting the user interact with that view rather than "selecting the item". In other words, the click is being handled by the view which contains the checkbox rather than the listview.
You could try handling the touch event in the view and then calling the parent activity and asking it to select the item.
A: Set OnClickMethod to your selected layout then change background of selected layout.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:onClick="ChangeBackGround">
instead your listview
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502117",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: HOW 2 place text on an -tag? Im just wondering how to place html-text on a . Shall I use the absolute -position for this matter?
Just so you know Im gonna use the img in a fluid-grid layout.
Thanks for yr ideas?
A: To place text on an image tag on hover use this...
<img src="#" title="YOUR TEXT HERE" alt="" width="" height="" />
The title will display when someone hovers over the image. The alt tag is what is shown when the image for some reason or another cannot be displayed. These are both useful attributes to use as some screen readers will use the title tag.
If you want actual text over the image you could do something like...
<img src="#" title="YOUR TEXT HERE" alt="" width="100" height="100" /><span style="margin: 20px 0 0 -80px;">YOUR TEXT</span>
This will display the text 20 pixels from the top of your image and 20 pixels in considering your image is 100x100px.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502123",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Flip Text on Success or After a certain time delay with Jquery How could I set up a function using jquery that would allow me to flip the text in a certain container say "#rndbtn" either on success of a .post form or after a certain time like 6000ms.
I am encountering a problem where the request is taking too long so certain browsers will fire off the call again after 60 seconds so I would like it to just flip the text to alert the user it failed after that time rather than tax my server again and again.
$.post("/sendreq", { arg1: arg1, arg2: arg2} ,
function(data,status,xhr) {
if (this.console && typeof console.log != "undefined"){
console.log(status);
console.log(data);
console.log(xhr);
}
if (data == "Error") {
$("#rndbtn").text('Failed');
}
else if (status == "error") {
if (this.console && typeof console.log != "undefined"){
console.log(xhr.status + " " + xhr.statusText + " " +data );
}
$("#rndbtn").text('Failed');
}
else {
if (type!=0) {
if (type!=4) {
$("#rndbtn").text('Sent Successfully');
}
else {
$("#rndbtn").text('Added to List');
}
}
else {
$("#rndbtn").text('Reset Successfully');
}
}
$("#rndbtn").attr("href","");
});
}
A: $(function() {
//Calling after post
var isSuccess = false;
$.post('/ther/url/here', function(responseData) {
//will get called after the Ajax call was successfull
isSuccess = true;
$('#rndbtn').text('foo');
});
//This will fire 6 seconds after the dom had loaded.
setTimeout(function() {
if(isSuccess === false) {
$('#rndbtn').text('foo');
}
}, 6000);
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502124",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Multiple domain names pointing on same name server I have 2 domain names. Can I point both domains to the same name server without having any adverse effect. Please let me know. Thanks.
A: You may use Addon domain or parked domain.Any adverse effect is nothing.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502126",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How it's better to add generatable sources files to qmake project? There is somefile.h.in and script somefile.h.pl which generates number of files like "somefile.h.gen" or "somefile_other.cpp.gen2".
How to add source generation phase in qmake? In plain Makefile I'd just put things like
somefile.o: somefile.cpp somefile.h somefile.h.gen
...
soemfile.h.gen: somefile.h.in somefile.h.pl
./somefile.h.pl < somefile.h.in # writes somefile.h.gen and friends
A: I need to use QMAKE_EXTRA_COMPILERS feature:
PREPROCESS_FILES = somefile.h.in
preprocess.name = Generate various files based on somefile.h.in
preprocess.input = PREPROCESS_FILES
preprocess.output = ${QMAKE_FILE_BASE}.gen
preprocess.commands = perl $$PWD/somefile.h.pl $$PWD/somefile.h.in
preprocess.CONFIG += no_link
QMAKE_EXTRA_COMPILERS += preprocess
PRE_TARGETDEPS += somefile.h.gen
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502127",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: HTML upload file without using browse button Can you make the HTML input file typeable? Instead of requiring to hit browse?
A: I can't necessarily speak for every browser in existence, but for every one that I'm aware of you can not without a browser add-on (flash, silverlight, etc.). This is a security feature to prevent a malicious web-site from "stealing" files from your local system with clever scripts.
A: Not that I know of.
You can drag a file onto/into the input.
But if it was type-able you could technically get any file off their machine without them knowing.
A: This is a decision made by developers of browsers. Some make the fields manually editable, some only let you use the dialog. (It is worth noting that in Chrome/Mac (for instance), while the field itself isn't editable, you can type in the dialogue box).
You can't change this as a page author.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502131",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Enabling SOAP Message Inspection for a Single Operation How can I force an IMessageInspector to fire only when a specific operation is called, rather than firing whenever a call to the service is made? Currently, I am applying a custom IEndpointBehavior to the endpoint which calls this IMessageInspector, but this is not exactly what I would like to do...
A: The message inspectors are bound to the dispatch runtime object, which is a single one for each endpoint, not operation. If a parameter inspector works, then you can use it (it's bound to the operation), but if you need a message inspector, then it cannot be bound to a single operation. But you can, inside your inspector, check whether the operation is what you expect (based on the Action header, which is unique per operation), as shown in the code below.
public class StackOverflow_7502134
{
[ServiceContract]
public interface ITest
{
[OperationContract]
string Echo(string text);
[OperationContract]
int Add(int x, int y);
}
public class Service : ITest
{
public string Echo(string text)
{
return text;
}
public int Add(int x, int y)
{
return x + y;
}
}
public class MyInspector : IEndpointBehavior, IDispatchMessageInspector
{
string[] operationNames;
public MyInspector(params string[] operationNames)
{
this.operationNames = operationNames ?? new string[0];
}
public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
{
}
public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
}
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{
endpointDispatcher.DispatchRuntime.MessageInspectors.Add(this);
}
public void Validate(ServiceEndpoint endpoint)
{
}
public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
{
// by default, action == <serviceContractNamespace>/<serviceContractName>/<operationName>
string operationName = request.Headers.Action.Substring(request.Headers.Action.LastIndexOf('/') + 1);
if (this.operationNames.Contains(operationName))
{
Console.WriteLine("Inspecting request to operation {0}", operationName);
Console.WriteLine(request);
Console.WriteLine();
return operationName;
}
else
{
return null;
}
}
public void BeforeSendReply(ref Message reply, object correlationState)
{
string operationName = correlationState as string;
if (operationName != null)
{
Console.WriteLine("Inspecting reply from operation {0}", operationName);
Console.WriteLine(reply);
Console.WriteLine();
}
}
}
public static void Test()
{
string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
MyInspector inspector = new MyInspector("Add"); // inspecting Add, not Echo
host.AddServiceEndpoint(typeof(ITest), new BasicHttpBinding(), "").Behaviors.Add(inspector);
host.Open();
Console.WriteLine("Host opened");
ChannelFactory<ITest> factory = new ChannelFactory<ITest>(new BasicHttpBinding(), new EndpointAddress(baseAddress));
ITest proxy = factory.CreateChannel();
Console.WriteLine("Calling Echo");
Console.WriteLine(proxy.Echo("Hello world"));
Console.WriteLine();
Console.WriteLine("Calling Add");
Console.WriteLine(proxy.Add(4, 5));
((IClientChannel)proxy).Close();
factory.Close();
Console.Write("Press ENTER to close the host");
Console.ReadLine();
host.Close();
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502134",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Intraweb class not found at runtime I've beenworking with the IntraWeb framework on Borland C++Builder. Sometimes it happens that an application crashes because of a strange uncaught exception:
An unhandled application error has occured within My IntraWeb Application.
...
Error message raised by the application: Class TIWTimer not found
This happens when a new session is started. For example, by entering the address in a browser.
Also, the message appears in the classic IntraWeb error web page
The class that cannot be found is either TIWTimer or TIWButton but I think this is irrelevant.
The problem seems to occur randomly and sometimes goes away with a rebuild, but other times it will go away by rewriting the code or starting from a new project.
So, the question is, how come the link error is not found at link-time?
Why does it occur at all, since those classes belong to the standard IW library?
Has anyone had the same issue?
How can it be solved?
A: Use Intraweb XII in C++Builder XE2, it has good improvement and bug fixes.
in this version you can assign urls to forms, for example:
myhost/login.htm or myhost/login.aspx
for more information see this
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502142",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: There are cross signs all over the google maps I am using google maps api and there are cross signs on map. How to fix this?
A: In Wrox Example both satelligh and steetview are set to ture.
Only one view can be set to true at a time.
If you set both then you will see cross mark. Not a very helpfull exception message :)
A: To use google maps in your android application you should obtain maps api key and paste it in layout definition.
Sample layout code
<com.google.android.maps.MapView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:enabled="true"
android:clickable="true"
android:apiKey="YOUR_API_KEY" />
Please remember that api key will be different for production and dev environments as you would use probably different certificates to sign application (eclipse automatically use debug certificate to sign any application deployed in dev mode).
I've faced also issue on testing applications signed with debug certificate on real devices, on emulator map was showed properly whereas on real device I must use other, non debug certificate and install application manually (not using eclipse).
Detailed instructions how to obtain your API key are provided at this site
A: Ok, the problem is mapView.setStreetView(true); I don't know why, but when I remove this line they dissappered.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502147",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to make FB Recommend button clickable more than once? I want to allow users to spam their own walls so I need the facebook recommend/like button to be clickable more than once. I'm using the iframe implemntation.
Is this actually possible?
A: No. One user can only 'Like' or 'Recommend' once. There is a difference in the way the button shows up if the user has already clicked on 'Like' or 'Recommend'.
FWIW, here is how it looks: Before Liking, After Liking
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502149",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: CPU utilization of Node.js on Amazon EC2 Seeing as how node is single threaded, If I have node server running on an amazon EC2 instance with 4 EC2 Compute units will it run any faster / handle more load than if I have 2 EC2 Compute units?
Does CPU utilization on amazon require a program to be multithreaded to fully use all resources?
A: Amazon's concept of total "EC2 Compute Units" for an instance type does not map directly to a CPU or core. It is the number of cores multiplied by the speed of each core in EC2 compute units (their own relative measurement).
Amazon does list how many virtual cores each instance type has:
http://docs.amazonwebservices.com/AWSEC2/latest/UserGuide/index.html?instance-types.html
Your best option is to use all of the cores as others point out. However, if you end up with a single threaded solution, then you will want to focus on the speed of the individual cores, not the total EC2 compute units of all the cores added together.
A: In Node.js, your code is single-threaded, but calls that e.g. access the file system or a database server do not use the main node.js thread. The main thread keeps executing while other threads are waiting for 4GB to be read from disk to RAM or for the DB server to return a response. Once the action finishes, the supplied callback is put in a queue to execute in the main thread. More or less, anyway.
The advantage being that in a server situation, you have one very fast thread that can handle thousands of concurrent requests without putting any one entirely on hold or spawning an OS thread for each client request-response cycle.
More to the point, you should benchmark your specific use case on EC2 -- multiple processors may be useful when running a single instance of node if the app does a lot of IO.
A: To fully utilize compute resources of N cores, you need at least N threads ready to do useful work. This has nothing to do with EC2; it's just the way computers work. I assume from your question that you are choosing between the m1.medium and m1.large instance types, which have 1 and 2 dedicated cores, respectively (the m1.small is half of a shared core, and the m1.xlarge is the full dedicated 4-core box). Thus, you need at least 2 processes doing useful work in order to utilize the larger box (unless you just want access to more memory / io).
Each Node.js process is single threaded by design. This lets it provide a clean programming paradigm free of locking semantics. This is very much by design.
For a Node.js app to utilize multiple cores, it must spawn multiple processes. These processes would then use some form of messaging (pipes, sockets, etc) to communicate -- versus "shared memory" where code can directly mutate memory locations visible to multiple processes, something that would require locking semantics.
In practice, this is dirt simple easy to set up. Back in Node.JS v0.6.X the "cluster" module was integrated into the standard distribution, making it easy to set up multiple node workers that can listen on a single port. Note that this "cluster" module is NOT the same as the learnboost "cluster" module which has a different API and owns the "cluster" name in the NPMjs registry.
http://nodejs.org/docs/latest/api/cluster.html
if (cluster.isMaster) {
// Fork workers.
for (var i = 0; i < numCPUs; i++) {
cluster.fork();
}
} else {
http.Server(function(req, res) { ... }).listen(8000);
}
A:
If I have node server running on an amazon EC2 instance with 4 EC2 Compute units will it run any faster / handle more load than if I have 2 EC2 Compute units?
No, if you are using node.js in a server capacity you will only have access to a single core.
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337, "127.0.0.1");
console.log('Server running at http://127.0.0.1:1337/');
Spawns a single listener, that doesn't mean only a single connection though. Node.js breaks conventional thought that way. The Event Loop will not block connections unless you code improperly. This post helps to explain the event loop and how important it is to understand it. Took me a while to really 'get' the implications.
Does CPU utilization on amazon require a program to be multithreaded to fully use all resources?
Yes, properly configured apache/nginx will take advantage of multi-cpu configurations. node.js servers are being developed that will also take advantage of these kind of configurations.
A: The short answer to your question is that adding more cores in order to improve your node performance will not work, if all you do is write "standard" single threaded javascript (you will be bound by a single CPU).
The reason is that node.js uses an event loop for processing, so if all you are doing is starting up a single node.js process without anything else, it will not be multi-threaded and thus not use more than one CPU (core).
However, you can use the node.js cluster API to fork the node process so you can take advantage of multiple CPUs (cores): https://nodejs.org/docs/latest/api/cluster.html. If you write your code that way, then having more compute units will help you.
There is one caveat, in that EC2 compute units are detailed per instance. For some instances you can get more "compute units" per virtual core. So if you pick an instance that has 2 compute units per virtual core versus one that has one per core, you will be able to execute node on a CPU that has more compute units. However, it looks like after 2 compute units the computing power is split per core which means you won't get any benefit from the multiple cores.
A: Just a quick addition to those above making good points as to the function of modern (old thread here) Node.JS, not only is Node implemented on top of V8, and LibUV, making use of a internal thread pool, but ACTUALLY, your JS code can be multi threaded. No, I don't just mean the thread_workers API. It is possible, even probably, that some of your dependencies, are using C++/V8/NAPI bindings for JS, and directly using the underlying thread pool.
For example:
You'll see that the standard bcrypt library on npm implements its blowfish utilities with multithreading in C++. Many people don't read the docs right, and are confused as to why running some cryptographic work from libraries in other worker threads doen't speed up their service.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502151",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "23"
} |
Q: MYSQL User Set Permissions host from SSH How do you set a users host permission via SSH for MySql?
I've managed to accidentally set the wrong domain/ip for my root user in WebMin > MySQL Server permissions. Like I went into hosts to allow remote access and put the wrong address. Now even Webmin cannot get into he database with the credentials.
A: Login to server via SSH.
Use following command to enter mysql:
mysql --skip-grant-tables -u root -p
skip-grant-tables will cause mysql to abandon privilege system for this session.
Then use grant command to grant any privilege to your root user:
grant all privileges on *.* to 'root'@'my-host-or-ip'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502153",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to model many-to-many relationships with a relationship entity in EF 4.1 Code First Popular example: In the issue tracker JIRA, issues can be linked to other issues. The link itself has some data attached, in particular a type.
Example:
Issue A -> depends on -> Issue B
Issue B <- is depended on by <- Issue A
We are introducing the same kind of relationship for an entity in our C# ASP.NET MVC application using EF 4.1 CodeFirst, and I'm wondering how to best model this relationship?
Details:
There are some particularities about this situation:
*
*A link has some data attached, so we can't simply model a many-to-many relationship between issues and issues. We rather have to introduce a new entity Link, which represents a relationship between two issues.
*A link, by definition, links two instances of the same entity, it is a "two-to-many" relationship (a link has two issues, an issue can have many links).
*The link is directed, which means, if Issue A depends on Issue B, then Issue B is depended on by Issue A.
We will certainly have a Link entity that looks like this:
public class Link
{
public int ID { get; set; }
public Issue IssueA { get; set; }
public Issue IssueB { get; set; }
public LinkType Type { get; set; }
}
The Issue class might look like this:
public class Issue
{
public int ID { get; set; }
public virtual ICollection<Link> Links { get; set; }
}
Currently there would be only one link type: dependency. So, the link type would look like this:
public class LinkType
{
public int ID { get; set; }
public string ForwardName { get; set; } // depends on
public string BackwardName { get; set; } // is depended on by
}
Now for the big question:
If I want EF to automatically manage Issue.Links, I have to tell it what Foreign key on the Link table to use. Either I use IssueA, or I use IssueB. I can't use both, can I?
Either I define:
modelBuilder.Entity<Issue>().HasMany(i => i.Links).WithRequired(l => l.IssueA);
or I define:
modelBuilder.Entity<Issue>().HasMany(i => i.Links).WithRequired(l => l.IssueB);
Possible approaches - I am curious about your feedback on whether some of them will lead to troubles, cannot be implemented, or whether any of these approaches can be regarded as "best practice":
*
*Add two Collections to the Issue, ICollection<Link> OutgoingLinks, ICollection<Link> IncomingLinks. This way the collections can be maintained by EF, but from a business logic point of view they don't make much sense.
*Only add one collection and configure EF 4.1 to add incoming and outgoing links to it, if that is possible.
*Only add one collection and implement it on my own:
ICollection<Link> AllLinks { return _context.Links.Where(l => l.IssueA == this || l.IssueB == this).ToList(); }
The problem with this approach is that the domain entity executes data access tasks which is bad in terms of seperation of concerns.
*Any other?
A: Option (1) is the way to go in my opinion, together with a readonly helper perhaps which combines the two collections:
public class Issue
{
public int ID { get; set; }
public virtual ICollection<Link> OutgoingLinks { get; set; }
public virtual ICollection<Link> InComingLinks { get; set; }
public IEnumerable<Link> Links // not mapped because readonly
{
get { return OutgoingLinks.Concat(InComingLinks); }
}
}
Option (2) isn't possible because you cannot map one navigation property to two different ends/navigation properties.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502159",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: After removing a sheet from an excel workbook with Apache Poi, a sheet remains? I'm using workbook.removeSheetAt() to remove a certain named sheet from a workbook. However, the workbook contains a new sheet called "Sheet3" after writing it out to disk. What gives? I'm not creating this new sheet anywhere in my code. Note: I am using XSSFWorkbook and all the other XSSF stuff.
Some more info: Here is a snippet from workbook.xml inside the output xlsx. I am deleting sheet with index=2, ostensibly sheetId=3. The template workbook I am starting with only has four sheets.
<sheets>
<sheet r:id="rId1" sheetId="1" name="Sheet1"/>
<sheet r:id="rId2" sheetId="2" name="Params" state="hidden"/>
<sheet r:id="rId4" sheetId="4" name="Warnings" state="hidden"/>
<sheet r:id="rId3" sheetId="5" name="Sheet3"/>
</sheets>
A: Apache POI is using index based sheets (kinda like an array). If you have a sheet at a position that is greater than x, there must exist a sheet at position x even if it is blank. You could try moving the sheets where n > x to position n - 1 using setSheetOrder
Seems like there is a bug report similar to this: Bug Report
What about hiding the sheet: setSheetHidden
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502161",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: MasterPage And ContentPage Body Css Problem? I have a Masterpage and I have a content page from this masterpage.. I must use different css for body tag for only this contentpage? How can ı do this?
this is my masterpage's css
body, div, ul, ol, li, p, h1, h2, h3, span, pre, a, img, blockquote, table, tbody, tfoot, thead, tr, th, td, pre, code {
margin:0px; padding:0px; border:0 none; outline:0; vertical-align:baseline;}
I dont want this css code for my contentpage.. How can ı do this?
A: As far as im aware the only way you can do this would be to create a 2nd master page for this particular content page.
I would suggest removing the styles from the master page & include them in each content page as needed, your master page should apply to every page the same, without causing any issues
A: You could create a control in the Master page with the CSS included. Such as:
<%@ Master Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML
1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server" >
<title>Master page title</title>
</head>
<asp:contentplaceholder id="CSS" runat="server">
<style type="text/css">
body, div, ul, ol, li, p, h1, h2, h3, span, pre, a, img, blockquote, table, tbody, tfoot, thead, tr, th, td, pre, code {
margin:0px; padding:0px; border:0 none; outline:0; vertical-align:baseline;}
</style>
<body>
</body>
</html>
You could then place a Content control on the client page overriding the master and just omit the content control on the rest of the pages (they will inherit the default).
I would recommend using a separate CSS file instead of embedding it directly, but you can accomplish that easily as well.
A: Sorry, but I'll suggest you include this css in the page you need it, not in the masterpage, since you don't want it in every pages... I guess this is not the answer you expected, but that's how CSS is work :S
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502162",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Replacing non UTF8 characters In php, I need to replace all non-UTF8 characters in a string. However, not by some equivalent (like the iconv function with //TRANSLIT) but by some chosen character (like "_" or "*" for example).
Typically I want the user to be able to see the position were the invalid characters were found.
I didn't find any functions that do this, so I was going to use:
*
*use iconv with //IGNORE
*do a diff on the two strings and insert the wanted character where the non-UTF8 ones where
Do you see a better way to do that, is there some functions in php that can be combined to have this behavior ?
Thanks for you help.
A: Here are 2 functions to help you achieve something close to what you want :
//reject overly long 2 byte sequences, as well as characters above U+10000 and replace with ?
$some_string = preg_replace('/[\x00-\x08\x10\x0B\x0C\x0E-\x19\x7F]'.
'|[\x00-\x7F][\x80-\xBF]+'.
'|([\xC0\xC1]|[\xF0-\xFF])[\x80-\xBF]*'.
'|[\xC2-\xDF]((?![\x80-\xBF])|[\x80-\xBF]{2,})'.
'|[\xE0-\xEF](([\x80-\xBF](?![\x80-\xBF]))|(?![\x80-\xBF]{2})|[\x80-\xBF]{3,})/S',
'?', $some_string );
//reject overly long 3 byte sequences and UTF-16 surrogates and replace with ?
$some_string = preg_replace('/\xE0[\x80-\x9F][\x80-\xBF]'.
'|\xED[\xA0-\xBF][\x80-\xBF]/S','?', $some_string );
note that you can change the replacement (which currently is '?' with anything else by changing the string located at preg_replace('blablabla', **'?'**, $some_string)
the original article : http://magp.ie/2011/01/06/remove-non-utf8-characters-from-string-with-php/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502164",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: What is the difference between inheritance and composition? As title says, the meaning of both eludes me.
A: Inheritance expresses a is-a relationship, while composition expresses a has-a relationship between the two classes.
An example for composition is a polygon. It has a ordered sequence of Points. In C++ terms:
struct Polygon {
std::vector<Point> points;
};
While an logic_error is a exception:
struct logic_error : public exception {
};
A: Just google Inheritance vs Composition you'll get alot of results.
Using java as an example
public class Banana extends Fruit{ //<---Inheritance Banana is-a Fruit
private Peel bananaPeel; //<--Composition banana has a Peel
public Peel getPeel(){
return bananaPeel;
}
}
A: As pmr pointed out, inheritence is a is-a relationship, composition is a has-a relationship.
Composition is usually used for wrapping classes and to express relationships between classes that contain one another.
Inheritance is used for polymorphism, where you have a base class and you want to extend or change its functionality.
A: Inheritance means inheriting something from a parent.
For example, you may inherit your mother's eyes or inherit your father's build.
It means deriving properties, characteristics and behaviors from a parent class. So you can parent.walk(), parent.sleep(), parent.sleep() or whatever.
Containership or maybe composition is a bit hard to explain.
Or maybe a car has a brake. The car is composed of a brake. But the brake isn't inheriting from a brake..different concepts. I know very weird explanation..but that's how much I can do I guess.
Let's look at this code:
class Parent
{
public :
void sleep() ; void eat() ; void walk() ;
string eyeColor; int height ;
};
class Child: public Parent
{
}
So the Child class can inherit the functions and attributes of the Parent but of course it may have the eye color of the mother or father.. Even if the childs' attributes are different it can still do whatever the Parent can do.
Now composition is another thing. A Child can have a toy or a Parent can have a child. So I could do:
class Toy
{
string model ;
};
class Child
{
Toy transformersToy ;
};
So the Child has the transformers toy now.. but does Child inherit the transformersToy.model attribute? No, because it isn't inheriting.
A: inheritance is a relationship between classes, containership is relationship between instance of classes.
A: inheritance is the dynamic polymorphism, that these days change its functionality to a technic of a code reuse. but the composition is a technic for ensuring capability of implementation.
A: One main point I see is the ownership on the objects. Inheritance doesnt own/give any thing it just gives the characteristics of the base class. While Composition gives the owner ship to the created object.
In the first example polygon has a vector of points. So polygon owns/contains points in it.
While in inheritance you can have/use/extend the existing characteristics of the base class.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502167",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: No number appears in Listbox I want to make a thread based prime number calculator.
The problem is that the UI freezes and no number occures.
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;
namespace PrimeNumbers
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
//private delegate void AddListItem(int item);
Thread t;
bool interrupt;
public MainWindow()
{
InitializeComponent();
}
private void btss_Click(object sender, RoutedEventArgs e)
{
if (t == null)
{
t = new Thread(this.calculate);
t.Start();
btss.Content = "Stop";
}
else
{
t.Interrupt();
}
}
private void calculate()
{
int currval = 2;
while (!interrupt)
{
for (int i = 2; i < currval/2; i++)
{
if (2 % i != 0)
{
AddListBoxItem(currval);
}
}
currval++;
}
}
private void AddListBoxItem(int item)
{
if (this.lbPrimes.Dispatcher.Thread == Thread.CurrentThread)
{
lbPrimes.Items.Add(item.ToString());
}
else
{
lbPrimes.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
new Action(
delegate()
{
lbPrimes.Items.Add(item.ToString());
}
));
}
}
}
}
A: remove begin you need to invoke it i mean
" lbPrimes.Dispatcher.Invoke(.. " instaed of " lbPrimes.Dispatcher.BeginInvoke(.."
That shows the numbers but you need something like the below code if you want a correct solution.
/// <summary>
/// /// Interaction logic for MainWindow.xaml
/// /// </summary>
public partial class MainWindow : Window
{
//private delegate void AddListItem(int item);
Thread t;
private long num = 3;
private bool interrupt = true;
private bool NotAPrime = false;
public MainWindow()
{
InitializeComponent();
}
private void AddListBoxItem(int item)
{
lbPrimes.Dispatcher.BeginInvoke
(DispatcherPriority.Send,
new Action(delegate()
{
lbPrimes.Items.Add(item.ToString());
}));
}
private void btss_Click(object sender, RoutedEventArgs e)
{
if (!interrupt)
{
interrupt = true;
btss.Content = "Resume";
}
else
{
interrupt = false;
btss.Content = "Stop";
btss.Dispatcher.BeginInvoke(
DispatcherPriority.Normal,
new Action(calculate));
}
}
public void calculate()
{
NotAPrime = false;
for (long i = 3; i <= Math.Sqrt(num); i++)
{
if (num % i == 0)
{
NotAPrime = true;
break;
}
}
if (!NotAPrime)
{
lbPrimes.Items.Add(num.ToString());
}
num += 2;
if (!interrupt)
{
btss.Dispatcher.BeginInvoke(
System.Windows.Threading.DispatcherPriority.SystemIdle,
new Action(this.calculate));
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502168",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can I allow for "breaks" in a for loop with node.js? I have a massive for loop and I want to allow I/O to continue while I'm processing. Maybe every 10,000 or so iterations. Any way for me to allow for additional I/O this way?
A: A massive for loop is just you blocking the entire server.
You have two options, either put the for loop in a new thread, or make it asynchronous.
var data = [];
var next = function(i) {
// do thing with data [i];
process.nextTick(next.bind(this, i + 1));
};
process.nextTick(next.bind(this, 0));
I don't recommend the latter. Your just implementing naive time splicing which the OS level process scheduler can do better then you.
var exec = require("child_process").exec
var s = exec("node " + filename, function (err, stdout, stderr) {
stdout.on("data", function() {
// handle data
});
});
Alternatively use something like hook.io to manage processes for you.
Actually you probably want to aggressively redesign your codebase if you have a blocking for loop.
A: Maybe something like this to break your loop into chunks...
Instead of:
for (var i=0; i<len; i++) {
doSomething(i);
}
Something like:
var i = 0, limit;
while (i < len) {
limit = (i+10000);
if (limit > len)
limit = len;
process.nextTick(function(){
for (; i<limit; i++) {
doSomething(i);
}
});
}
}
The nextTick() call gives a chance for other events to get in there, but it still does most looping synchronously which (I'm guessing) will be a lot faster than creating a new event for every iteration. And obviously, you can experiment with the number (10,000) till you get the results you want.
In theory, you could also use setTimeout() rather than nextTick(), in case it turns out that giving other processes a somewhat bigger "time-slice" helps. That gives you one more variable (the timeout milliseconds) that you can use for tuning.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502172",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do you close a Qt child process and get the child process to execute cleanup code? I am starting a process in Linux/Qt and then starting some child processes using QProcess. Then eventually I want to close the child processes gracefully (aka execute some clean up code).
The child processes are using QSharedMemory and right now when I call QProcess::close() the child processes are closing without calling QSharedMemory::detach() and the result is that all the processes are closed... but there is left over shared memory that is not cleaned up.
I have the code for the child process and in the code there is the function cleanup(). How does the parent process close the QProcess in such a manner so that the child process will execute cleanup()?
A: I got the child to execute Qt cleanup code using unix signal handlers.
Here's a high level explanation:
*
*the parent opens the child process using QProcess
*processing occurs
*the parent closes the child process using QProcess::terminate() which raises the SIGTERM signal on the child
*
*(don't use QProcess::close() because it doesn't raise the SIGTERM signal)
*the child implements a unix signal handler for SIGTERM
*from the unix signal handler the qApp->exit(0); occurs
*qApp emits a Qt signal "aboutToQuit()"
*connect the child process cleanup() slot to the qApp aboutToQuit() signal
Child process code to handle unix SIGTERM signal:
static void unixSignalHandler(int signum) {
qDebug("DBG: main.cpp::unixSignalHandler(). signal = %s\n", strsignal(signum));
/*
* Make sure your Qt application gracefully quits.
* NOTE - purpose for calling qApp->exit(0):
* 1. Forces the Qt framework's "main event loop `qApp->exec()`" to quit looping.
* 2. Also emits the QCoreApplication::aboutToQuit() signal. This signal is used for cleanup code.
*/
qApp->exit(0);
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
MAINOBJECT mainobject;
/*
* Setup UNIX signal handlers for some of the common signals.
* NOTE common signals:
* SIGINT: The user started the process on the command line and user ctrl-C.
* SIGTERM: The user kills the process using the `kill` command.
* OR
* The process is started using QProcess and SIGTERM is
* issued when QProcess::close() is used to close the process.
*/
if (signal(SIGINT, unixSignalHandler) == SIG_ERR) {
qFatal("ERR - %s(%d): An error occurred while setting a signal handler.\n", __FILE__,__LINE__);
}
if (signal(SIGTERM, unixSignalHandler) == SIG_ERR) {
qFatal("ERR - %s(%d): An error occurred while setting a signal handler.\n", __FILE__,__LINE__);
}
// executes mainbobject.cleanupSlot() when the Qt framework emits aboutToQuit() signal.
QObject::connect(qApp, SIGNAL(aboutToQuit()),
&mainobject, SLOT(cleanupSlot()));
return a.exec();
}
Conclusion:
I confirmed that this solution works.
I think this is a good solution because:
*
*let's the parent close the child process in such a way that the child process executes cleanup
*if the parent closes mistakenly and leaves the child process running, the user/sysadmin can kill the leftover child process using kill command and the child process will still cleanup after itself before closing
p.s. "why not just do the cleanup code directly in the signal handler entry point?"
The short answer is because you can't. Here's an explanation as to why you can't execute your Qt cleanup code in the unix signal handler function. From Qt documentation "Calling Qt Functions From Unix Signal Handlers":
You can't call Qt functions from Unix signal handlers. The standard
POSIX rule applies: You can only call async-signal-safe functions from
signal handlers. See Signal Actions for the complete list of functions
you can call from Unix signal handlers.
A: You could try connecting the processExited() signal to a slot to handle detaching from the shared memory yourself, as far as I'm aware there's nothing in QProcess that will directly trigger the detach method.
A: I believe you need to implement a small protocol here. You need a way to tell to the child process to exit gracefully. If you have the source for both, you may try to implement such a signal using QtDBus library.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502174",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Program aborting due to malloc(0) in regex expression Can anyone tell me why my program is aborting? I am compiling it with efence which aborts on malloc(0), as the GDB backtrace suggests, the regcomp is doing a malloc(0)
1218 void extractTime(int extractStartTime)
1219 {
1220 char * charPtr, * numberFormatErr;
1221 regex_t re;
1222
1223 ( extractStartTime == 1 ) ? ( charPtr = getenv("EF_ERRTRACK_START") ) :
1224 ( charPtr = getenv("EF_ERRTRACK_END") );
1225
1226 if ( charPtr == NULL )
1227 return;
1228
1229 double envVal = strtod(charPtr, &numberFormatErr);
1230
1231 if ( (numberFormatErr == charPtr) || (*numberFormatErr != '\0') ) {
1232 ( extractStartTime == 1 ) ? EF_Print("eFence exited: EF_ERRTRACK_START is not a number\n") :
1233 EF_Print("eFence exited: EF_ERRTRACK_END is not a number\n");
1234 exit(1);
1235 }
1236 else if ( envVal < 0 ) {
1237 ( extractStartTime == 1 ) ? EF_Print("eFence exited: EF_ERRTRACK_START a negative number\n") :
1238 EF_Print("eFence exited: EF_ERRTRACK_END is a negative number\n");
1239 exit(1);
1240 }
1241
1242 /* If we are here then it is a valid number, now lets check if it is exponential or not */
1243
1244 regcomp(&re, "^([0-9]+[.]?[0-9]*|[0-9]*[.][0-9]+)[eE][+-]?[0-9]+$", REG_EXTENDED);
1245
1246 if ( regexec(&re, charPtr, 0, 0, 0) == 0 )
1247 {
1248 /* It is an exponential number, then already parsed by strtod earlier*/
1249 sprintf(charPtr, "%lf", envVal);
1250 }
1251
Here is the GDB backtrace:
(gdb) r
Starting program: /tmp/efence/ikatrack1_dev
[Thread debugging using libthread_db enabled]
Electric Fence 2.1 Copyright (C) 1987-1998 Bruce Perens.
ElectricFence Aborting: Allocating 0 bytes, probably a bug.
[New Thread 0x4001e350 (LWP 1528)]
Program received signal SIGILL, Illegal instruction.
[Switching to Thread 0x4001e350 (LWP 1528)]
0x4008734c in kill () from /devel/lib/libc.so.6
(gdb) bt
#0 0x4008734c in kill () from /devel/lib/libc.so.6
#1 0x0000b86c in EF_Abort (pattern=0x1000 <Address 0x1000 out of bounds>)
at print.c:137
#2 0x00009564 in memalign (alignment=4, userSize=0) at efence.c:533
#3 0x0000a5bc in malloc (size=0) at efence.c:1027
#4 0x400fe5bc in re_node_set_alloc (set=0x4025cfd8, size=0)
at regex_internal.c:959
#5 0x400ff2ac in register_state (dfa=0x25, newstate=0x4025cfc8, hash=86528)
at regex_internal.c:1550
#6 0x40102d64 in re_acquire_state_context (err=0xbebd7b88, dfa=0x40196f74,
nodes=0xbebd7b74, context=0) at regex_internal.c:1706
#7 0x4010c060 in re_compile_internal (preg=0xbebd7bf0,
pattern=0xcb74 "^([0-9]+[.]?[0-9]*|[0-9]*[.][0-9]+)[eE][+-]?[0-9]+$",
length=<value optimized out>, syntax=242428) at regcomp.c:989
#8 0x4010d5f8 in __regcomp (preg=0xbebd7bf0,
pattern=0xcb74 "^([0-9]+[.]?[0-9]*|[0-9]*[.][0-9]+)[eE][+-]?[0-9]+$",
cflags=1) at regcomp.c:480
#9 0x0000ae1c in extractTime (extractStartTime=1) at efence.c:1244
#10 0x0000aa1c in efence_ctor () at efence.c:1144
#11 0x0000c528 in __libc_csu_init (argc=1, argv=0xbebd7de4, envp=0xbebd7dec)
at elf-init.c:83
#12 0x40070fe8 in __libc_start_main (main=0x8c54 <main>, argc=1,
ubp_av=0xbebd7de4, init=0xc4d0 <__libc_csu_init>,
---Type <return> to continue, or q <return> to quit---
fini=0xc4c0 <__libc_csu_fini>, rtld_fini=0x4000ea50 <_dl_fini>,
stack_end=0xbebd7de4) at libc-start.c:179
#13 0x00008bcc in _start ()
From GDB backtrace, i can see that the problem lies in frame #4:
#4 0x400fe5bc in re_node_set_alloc (set=0x4025cfd8, size=0) where it is doing a malloc(0) but how come and why is it doing?
A: Change your electric fence settings (EF_ALLOW_MALLOC_0) to ignore this.
malloc(0) is not illegal. Read the error message again, it says "probably a bug". It aborts so that you will investigate. Once you've determined that it isn't actually a bug, skip it and keep running.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502178",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: ILMerge question I'm trying to merge multiple assemblies into one as my 'Proxy' assembly for a WCF service. Currently, users of the Proxy need to reference the assembly containing the data contracts, and also my domain assembly because of my inheritance schemes.
I'd like to use ILMerge for this. In particular, the ILMerge-Tasks project looks promising, especially this line from their project home:
ILMerge-Tasks Project Home:
...It even includes a post-build event that merges ILMerge and the task dll so that you can use the task without ILMerge.exe being present.
This is precisely what i'd like to accomplish, but i really have no idea how to go about it. Please help!
Other relevant (perhaps) info:
*
*We are using automated builds in TFS, so not having ilmerge.exe present will be a big plus
Update:
So I included the ILMerge.MSBUild.Tasks.dll in my project and added the following to my build file (taken from ilmerge project home):
<Target Name="AfterBuild">
<UsingTask TaskName="ILMerge.MSBuild.Tasks.ILMerge"
AssemblyFile="ILMerge.MSBuild.Tasks.ILMerge"/>
<ItemGroup>
<MergeAsm Include="BarProject.dll" />
<MergeAsm Include="FooProject.dll" />
</ItemGroup>
<ILMerge InputAssemblies="@(MergeAsm)" OutputFile="FooBar.dll" />
</Target>
But now I get the following error:
The "UsingTask" task was not found. Check the following: 1.) The name of the task in the project file is the same as the name of the task class. 2.) The task class is "public" and implements the Microsoft.Build.Framework.ITask interface. 3.) The task is correctly declared with in the project file, or in the *.tasks files located in the "C:\Windows\Microsoft.NET\Framework\v4.0.30319" directory.
A: Solved.
*
*I did NOT use the configuration above
*I did NOT use the ILMerge.MSBuild.Tasks.dll
Here's the steps I took:
*
*Added a reference to ILMerge.exe (the one from Microsoft Research) to my project
*Added this PostBuild entry to my MSBuild file (.csproj):
ILMerge /out:FooBar.dll Bar.dll Foo.dll
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502179",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.