text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Recommended sizes for Media Queries, to cover tablets phones laptops and desktops What are the best Media Query sizes to use to be sure you've targeted tablets, phones, laptops and desktops as best you can?
For example: The iPhone and Droid have a screen size of 320X480, therefore it would be good to make sure the design looks good at those sizes, since a lot of phones out there are this size. What other sizes would it be good to target? I'm not looking JUST for iphone/ipad sizes, but in general. Especially since there's more Android devices out there now than iOS devices, and Android devices tend to be of so many different sizes.
@media screen and (max-width: 480px) {
/* would target landscape for the droid, iphone 3, etc. */
}
@media screen and (max-width: 320px) {
/* would target portrait for the droid, iphone 3, etc. */
}
A: Here is a great link to screen sizes.
Personally, since the iPad is by FAR the most popular tablet device, design the medium screen size (1024x768) to that specification (iPad 2 size) - any larger than that and you're running in to desktop size.
For Smart Phone size I would go with 960x640, although that will probably increase for iphone and android within the next year if not sooner.
A: you can look at mine, http://dev.bowdenweb.com/a/css/media-queries-boilerplate.css but i took most of them from hard boiled media queries, http://www.stuffandnonsense.co.uk/blog/about/hardboiled_css3_media_queries
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564585",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: jQuery mobile navigation obscuring "click" events to HTML image map I am using jQuery mobile for navigation, including back buttons, so the following is set:
$.mobile.page.prototype.options.addBackBtn = true;
In order to use jQuery mobile navigation to get to pages linked from an HTML image map, I was using the following code, bound to pagecreate:
$(page).find('MAP').bind('click', function(e) {
alert("Map click");
});
$(page).find('AREA').bind('click', function(e) {
alert("Area click");
e.preventDefault();
$.mobile.changePage($(this).attr('href'));
});
What seems to happen is the first time my image map loads, everything works as expected, and when I touch one of the areas, I get both alerts, first "Area click" then "Map click", and then the nice jQuery mobile nav animation takes me where I'm going.
However, whether I use jQuery mobile's back button (enabled by the addBackBtn option above) or the browser's back button to return to the image map, these events no longer seem to fire. The area objects neither cause their original, pre-override behavior of acting like a regular hyperlink, nor do I get any of my alerts.
This is in Webkit browsers on a couple of iOS and Android phones - somehow desktop browsers do not exhibit this issue.
Anyone know the bug/fix/workaround for having my HTML image map continue to work, even after it's been navigated away from and back again by jQuery mobile? All help greatly appreciated.
A: The issue turns out to be that, when you use jQuery mobile for navigation, it can sometimes end up injecting duplicate IDs into the DOM, which is why they advise you to never use IDs in the first place.
Unfortunately, images must refer to their maps by id (or name), so using the above approach you can end up manipulating one map, while your img tag is pointing at another one with the same ID that is somewhere else in the DOM.
The fix isn't pretty, but it's to set the id of the map to something unique, and then set the usemap attribute of the corresponding image, before trying to update the handlers of each map area.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564591",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Assigning negative value to char Why does the following code print "?" ?
Also how can -1 be assigned to an unsigned char?
char test;
unsigned char testu; //isn't it supposed to hold values in range 0 - 255?
test = -1;
testu = -1;
cout<<"TEST CHAR = "<<test<<endl;
cout<<"TESTU CHAR = "<<testu<<endl;
A: When you assign a negative value to an unsigned variable, the result is that it wraps around. -1 becomes 255 in this case.
A: I don't know C or C++, but my intuition is telling me that it's wrapping -1 to 255 and printing ÿ, but since that's not in the first 128 characters it prints ? instead. Just a guess.
To test this, try assigning -191 and see if it prints A (or B if my math is off).
A: unsigned simply affects how the internal representation of the number (chars are numbers, remember) is interpreted. So -1 is 1111 1111 in two's complement notation, which when put into an unsigned char changes the meaning (for the same bit representation) to 255.
The question mark is probably the result of your font/codepage not mapping the (extended) ASCII value 255 to a character it can display.
I don't think << discerns between an unsigned char and a signed char, since it interprets their values as ASCII codes, not plain numbers.
Also, it depends on your compiler whether chars are signed or unsigned by default; actually, the spec states there's three different char types (plain, signed, and unsigned).
A: Signed/unsigned is defined by the use of the highest order bit of that number.
You can assign a negative integer to it. The sign bit will be interpreted in the signed case (when you perform arithmetics with it). When you treat it it like a character it will simply take the highest order bit as if it was an unsigned char and just produce an ASCII char beyond 127 (decimal):
unsigned char c = -2;
is equivalent to:
unsigned char c = 128;
WHEN the c is treated as a character.
-1 is an exception: it has all 8 bits set and is treated as 255 dec.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564595",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: popviewcontroller is not calling viewWillappear I'm using the following code to display the previous view when a user is clicking on a button
[self.navigationController popViewControllerAnimated:YES];
In the previous view, I overwrite viewWillAppear to initialized few things. However, it seems like viewWillAppear is not being called. I put NSLog in viewDidload, viewWillAppear, viewDidAppear and only viewDidAppear is being called. Is this normal behavior? If yes, what event should I override so I can do my initialization? Thank you.
As requested -viewWillAppear for the previous view
- (void)viewWillAppear:(BOOL)animated{
NSLog(@"ViewWillAppear");
//[[GameStore defaultStore] resetGame];
[self setHangmanImage];
NSLog([[[GameStore defaultStore] selectedList] label]);
[labelListName setText:[NSString stringWithFormat:@"List Name: %@", [[[GameStore defaultStore] selectedList] label]]];
[labelCurrentIndex setHidden:YES];
[labelCurrentWord setHidden:YES];
[[self navigationController] setNavigationBarHidden:NO];
[FlurryAnalytics logEvent:@"GameViewController - viewWillAppear"];
[self getNewQuestion];
NSLog(@"ViewWillAppear finish");
[super viewWillAppear:YES];
}
I setup the UINavigationalController in the app delegate using the following code
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
HomeViewController *hv = [[HomeViewController alloc] init];
UINavigationController *navController = [[UINavigationController alloc]
initWithRootViewController:hv];
// You can now release the itemsViewController here,
// UINavigationController will retain it
[hv release];
// Place navigation controller's view in the window hierarchy
[[self window] setRootViewController:navController];
[navController release];
// Override point for customization after application launch.
[self.window makeKeyAndVisible];
return YES;
}
UPDATE
I don't know what happened but last night after trying to run the app one more time in the simulator and its still having this issue, I decided to save everything and shut my computer down since it was getting late.
This morning I turned my computer back on opened up xcode, clean the project and build and run it and I the problem is fixed and -viewWillAppear is called. I didn't change anything and its working. I added NSLog in -willShowView and its not getting called. I don't know why all of a sudden viewWillAppear is being called.
A: I've just hit a problem very much the same and after some testing discovered that calling popViewControllerAnimated: in a block (from a network response in AFNetworking) viewDidAppear isn't called in the parent view.
The solution that worked for me here was to call it in the main thread instead.
dispatch_async(dispatch_get_main_queue(), ^{
// If not called on the main thread then the UI doesn't invoke the parent view's viewDidAppear
[self.navigationController popViewControllerAnimated:YES];
});
A: Make sure your navigation controller's delegate is set and then use this function to call viewWillAppear in the class whose viewWillAppear you want to call:
- (void)navigationController:(UINavigationController *)navigationController
willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
[self viewWillAppear:animated];
}
A: I have just hit this problem as well the root cause of this problem is because I put self.navigationController.delegate = self on viewDidLoad. My solution is to put the delegation on viewWillAppear :
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
self.navigationController.delegate = self;
}
After that popViewController will hit viewWillAppear.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564596",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: How to query previous rows of a table in a select statement if the table is resorted by a non-primary key I have a table named Clients with three columns - RowID, ClientNumber, and ClientNote where RowID is the primary key. Each ClientNumber has multiple ClientNotes so that the data looks like this:
RowId ClientNumber ClientNote
1 678 Note 1
2 678 Note 2
3 123 Note 3
4 123 Note 4
5 123 Note 1
6 F45 Note 3
7 F45 Note 6
I am trying to return a table that sorts the data by ClientNumber, and also adds a column that could be used to print different color backgrounds if needed:
ClientNumber ClientNote Color
123 Note 3 Blue
123 Note 4 Blue
123 Note 1 White
678 Note 1 White
678 Note 2 White
F45 Note 3 Blue
F45 Note 6 Blue
I am trying to use a CASE statement, where my base case (row 1) is set to Blue, and I would like to then access the previous row to query data to make a decision on color.
Here is my code:
SELECT ClientNumber , ClientNote,
CASE
WHEN (SELECT @rownum:=@rownum+1 rownum) = 1
THEN 'Blue'
WHEN @rownum != 1 AND (SELECT ClientNumber FROM Clients WHERE @rownum - 1 < @rownum ORDER BY ClientNumber ASC LIMIT 1) = ClientNumber AND (SELECT 'Color' FROM Clients WHERE @rownum - 1 < @rownum ORDER BY ClientNumber ASC LIMIT 1) = 'White'
THEN 'White'
WHEN @rownum != 1 AND (SELECT ClientNumber FROM Clients WHERE @rownum - 1 < @rownum ORDER BY ClientNumber ASC LIMIT 1) = ClientNumber AND (SELECT 'Color' FROM Clients WHERE @rownum - 1 < @rownum ORDER BY ClientNumber ASC LIMIT 1) = 'Blue'
THEN 'Blue'
WHEN @rownum != 1 AND (SELECT ClientNumber FROM Clients WHERE @rownum - 1 < @rownum ORDER BY ClientNumber ASC LIMIT 1) != ClientNumber AND (SELECT 'Color' FROM Clients WHERE @rownum - 1 < @rownum ORDER BY ClientNumber ASC LIMIT 1) = 'Blue'
THEN 'White'
WHEN @rownum != 1 AND (SELECT ClientNumber FROM Clients WHERE @rownum - 1 < @rownum ORDER BY ClientNumber ASC LIMIT 1) != ClientNumber AND (SELECT 'Color' FROM Clients WHERE @rownum - 1 < @rownum ORDER BY ClientNumber ASC LIMIT 1) = 'White'
THEN 'Blue'
END
AS Color
FROM (SELECT @rownum:=0) r, Clients
ORDER BY ClientNumber ASC
Essentially, I am just looking back to see if the previous ClientNumber matches or not, and inserting a color based on the previous color. I am having a problem querying the ClientNumber on the previous row in my new table. I am using MySQL-server, and I don't know a lot about SQL.
The other problem I am having is querying the color of the previous row. Since I am using a CASE statement, I think I might have to access the column information instead of using the name of the column, but I am not sure if this is necessary.
The problem and solution are pretty basic, but the syntax is killing me!! I've tried just about everything I can think of (the above code is the latest version) except joins, which I don't even really understand.
Any explanation of how to access "previous" (if they can really be called that in a database) rows and CASE statement results would really be appreciated.
A: MS-SQL is not FoxPro where you can do SCAN ... END SCAN and sequentially iterate through all the records and/or even move the pointer to any row you want. So I don't think the "refer to the previous row" aproach will work on the SQL server. You can use ADO.NET or anything else that fetches the data in some form of a DataTable or simply a collection of rows in a WinForms application. This will allow you more flexibility in referring to a previous row (or any row) while iterating the rows sequentially.
Honestly I still don't understand the algorithm that decides the colours (maybe you should present the algorithm and not the code). However there are ways to go through the rows of a table in SQL using cursors but I don't think that's enough for you; anyway if it helps you may want to take a look at this other thread.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564604",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Sencha Touch Passcode Is there a control in Sencha Touch to show a passcode field like shown in picture below?
A: No theres no native component who does exactly this. But you can build it by yourself: its a form with 4 input fields and a dozen buttons. See documentation for more details: http://docs.sencha.com/touch/1-1/#!/api/Ext.form.FormPanel
A: No, you have to build and design this one completly by yourself.
Note: To get rid of the browser controls, you have to enforce that the application is running form the homescreen. You can control (with some Javascript) if the application is running MobileSafari or as a "Web App". (see: http://cubiq.org/add-to-home-screen as an example of such an implementation)
But, however, I would not recommend using such a component. A) This can confuse people and B) Can intent users to type in their regular passcode. As a developer I wouldn't be comfortable with that situation.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564607",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to remove the dots in eclipse projects? I am working on android projects using Eclipse IDE. Since two days my files are opening with all dots and symbols. Can you please tell us what is the reason for that? How to remove those symbols?
Thank you,
A: From the Window menu Prefrences + Editors + Text Editors + Unchecked the Show Whitespace characters.
A: Try this
A: You can just go to Preferences -> Java -> Editor -> Save Actions and configure it to remove trailing whitespace
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564628",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: NSNotification Scrolling - User vs Programmatic I have a program with an NSTextView (actually, a custom subclass) into which a lot of lines of data are likely to be programmatically inserted. (It reads a stream of serial data from a USB port.) I have a checkbox for enabling/disabling autoscrolling. I want to allow the user to break out of autoscrolling simply by trying to scroll back up. So, I need a notification that tells me when the user has scrolled, not just when the bounds have changed, since this happens every time more serial data gets inserted. Is this possible?
A: Surely you could use the notification that tells you when any scrolling takes place, and then check if the text view is scrolled entirely to the bottom? If it is, turn auto-scrolling on. If not, turn it off.
A: It's not the best, but this works in my case. I think it could be done a little cleaner with some NSEvent manipulation, but I realized that I can check to see if the user has started scrolling by checking the current scroll position against the total document rectangle height.
NSRect totalRect = [[serialScrollView contentView] documentRect];
NSRect visibleRect = [[serialScrollView contentView] documentVisibleRect];
NSInteger totalHeight = totalRect.size.height;
NSInteger visibleHeight = visibleRect.size.height;
NSInteger position = visibleRect.origin.y;
NSInteger scrollPoint = position + visibleHeight;
if (totalHeight != scrollPoint)
[autoscrolls setState:0];
So basically, if the scroll position becomes anything other than what the program expects it to be from programmatic writes, it turns autoscrolling off. A cool thing about this implementation is that if you ad an else [autoscrolls setState:1];, it turns autoscrolling back on when you scroll back down to catch up with the stream. This emulates the scrolling behavior in the terminal when you're running a shell script with lots of output, like a yum install on Fedora or that sort of thing.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564635",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: cmd's character set C:\Users\Kolink>php -r "echo 'é';"
Ú
C:\Users\Kolink>echo é
é
As you can see, a program outputting an é results in a Ú, but using the echo command gives the desired character.
And, can I configure PHP (maybe some command at the start of the script) to output the correct character?
A: CMD.exe works in a different codepage than PHP. By the way, it is also a different codepage than the default Windows codepage. This is for compatibility with older MS-DOS programs. In my country Windows uses Windows-1250 and cmd.exe uses DOS Latin2. I suppose in the UK this would be Windows-1252 and DOS Latin1 respectively.
To get the same results you have to use the same codepage in PHP and in cmd.exe. Check what codepage is used by PHP and set cmd.exe to the same codepage. To do this, use the following command: mode con cp select=<codepagenumber> or chcp <codepagenumber>. This will change the codepage only for the current instance of cmd.exe.
Here is a short list of some typical codepages and their numbers:
DOS Latin1 850
DOS Latin2 852
Windows-1250 1250
Windows-1252 1252
UTF-8 65001
ISO-8859-1 28591
ISO-8859-2 28592
As @Christophe Weis pointed out in comments, you can lookup the identifiers of other code pages at Code page identifiers page.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564643",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Does twilio-csharp work in Mono? Hello I've recently been messing around with Twilio and their official twilio-csharp library. I'm using it on mono 2.10.5(x86-64) on Linux and I'm having problems getting a basic example working.
My code:
var twilio = new TwilioRestClient("[accountsid]", "[authkey]");
var msg = twilio.SendSmsMessage("+1316313XXXX, "+1918917XXXX", "I'm a monkey Mr. Anderson");
Seems to be very simple but when running it, the msg object returned is null and no message gets sent. Is this something I'm doing wrong or does the library not work in Mono?
A: The problem is detailed in this page: http://www.mono-project.com/UsingTrustedRootsRespectfully
Basically, Mono doesn't ship with any root certificate authorities. So, the quick and dirty fix is to trust all certificates:
ServicePointManager.ServerCertificateValidationCallback =
delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{ return true; };
It's not very secure, but depending on your uses, it may not matter.
A: In case it's helpful for anyone else that come across this question, I added monotouch/for android projects to this fork of twilio-csharp:
https://github.com/joelmartinez/twilio-csharp
pull request to fold the changes into the main project is pending as of the writing of this answer :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564645",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: std::enable_if specialisation failing I've been messing around with enable_if, and I seem to have stumbled upon some inconsistent behaviour. This is in VS2010. I've reduced it to the following sample.
#include <type_traits>
using namespace std;
// enable_if in initial template definition
template <class T, class Enable = enable_if<true>> struct foo {};
foo<int> a; //OK
// explicit specialisation
template <class T, class Enable = void> struct bar;
template <class T> struct bar<T, void> {};
bar<int> b; //OK
// enable_if based specialisation
template <class T, class Enable = void> struct baz;
template <class T> struct baz<T, std::enable_if<true>> {};
baz<int> c; //error C2079: 'c' uses undefined struct 'baz<T>'
Is this a bug in the code or the compiler?
A: std::enable_if<true> should be typename std::enable_if<true>::type.
std::enable_if<true> always names a type (as does std::enable_if<false>). In order to get substitution to fail when the condition is false you need to use the type nested typedef, which is only defined if the condition is true.
A: Your problem has very little to do with enable_if
// you declare a structure named baz which takes 2 template parameters, with void
// as the default value of the second one.
template <class T, class Enable = void> struct baz;
// Partial specialization for a baz with T and an std::enable_if<true>
template <class T> struct baz<T, std::enable_if<true>> {};
// Declare a baz<int, void> (remember the default parameter?):
baz<int> c; //error C2079: 'c' uses undefined struct 'baz<T>'
baz<int, void> has an incomplete type at that point. The same problem will occur without enable_if:
template <class T, class U = void>
struct S;
template <class T>
struct S<T, int>
{ };
S<double> s;
And, as James said, you're using enable_if incorrectly. Boost's documentation for enable_if does a great job explaining it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564647",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to pass 2 variables to Flash? First off, I'm using Flash CS5.5, AS3.
I'm trying to pass variables representing name and email address to a swf file. The swf takes a picture with the users webcam and sends the image to save.php for further processing. Currently I have text fields for the user to enter name and email, but I'd like to eliminate them and add the info behind the scenes. Basically this is what I'm trying to accomplish:
1.Page loads and stores name and email address in variables(index.php).
2.I'd like to pass name and email address variables to flash to be included with
the image the swf sends to a php file for processing (save.php)
3.Page loads flash content(take_picture.swf) and does it's thing.
I've got this working in a similar situation using Zend AMF, where the swf gets all the info passed back from another page accessing the database. Here I have the data I need without accessing the database. I've tried many variations using FlashVars, but nothing has worked yet. One thing I seem to be missing is when I publish the fla, there is no ac_fl_runcontent in the html code Flash publishes. And there is no <embed src=... either. This div is the body of the html file Flash gives me:
<div id="flashContent">
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="760" height="1000" id="take_picture" align="middle">
<param name="movie" value="take_picture.swf" />
<param name="quality" value="high" />
<param name="bgcolor" value="#ffffff" />
<param name="play" value="true" />
<param name="loop" value="true" />
<param name="wmode" value="window" />
<param name="scale" value="showall" />
<param name="menu" value="true" />
<param name="devicefont" value="false" />
<param name="salign" value="" />
<param name="allowScriptAccess" value="sameDomain" />
<!--[if !IE]>-->
<object type="application/x-shockwave-flash" data="take_picture.swf" width="760" height="1000">
<param name="movie" value="take_picture.swf" />
<param name="quality" value="high" />
<param name="bgcolor" value="#ffffff" />
<param name="play" value="true" />
<param name="loop" value="true" />
<param name="wmode" value="window" />
<param name="scale" value="showall" />
<param name="menu" value="true" />
<param name="devicefont" value="false" />
<param name="salign" value="" />
<param name="allowScriptAccess" value="sameDomain" />
<!--<![endif]-->
<a href="http://www.adobe.com/go/getflash">
<img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" />
</a>
<!--[if !IE]>-->
</object>
<!--<![endif]-->
</object>
</div>
I've tried <param name="FlashVars" value="first_name=<?php echo $first_name; ?>&email=<?php echo $email ?>" /> with something along the lines of this.loaderInfo.parameters.first_name and this.loaderInfo.parameters[first_name] in the actions panel along with some other things but haven't gotten it to work yet. Any help would be appreciated.
Thanks very much,
Mark
EDIT: This is my latest attempt:
var f_name:String;
var paramObj:Object = LoaderInfo(this.root.loaderInfo).parameters;
f_name = String(paramObj[first_name]);
first_name.text=f_name;
With this in the html:
<param name="FlashVars" value="first_name=<?php echo $first_name; ?>"/>
A: Here's something simple to give you an idea:
Embed:
<object width="800" height="600">
<param name="flashvars" value="first_name=blah&email=blah" />
<embed src="clipping.swf?first_name=blah&email=blah" width="800" height="600" />
</object>
AS3:
var parsed:Object = root.loaderInfo.parameters;
trace(
parsed.first_name,
parsed.email
);
A: the best/easiest way to add a SWF to your html page is SWFObject.
just add the script to your file
<script type="text/javascript" src="swfobject.js"></script>
you can then add all necessary attributes/params like this:
<script type="text/javascript">
// <![CDATA[
var width = 800;
var height = 600;
var flashVersion = "9.0.115";
var movie = "clipping.swf";
var movieName = "flashMovie";
var bgColor = "#ffffff";
var express = "expressInstall.swf";
var replaceDiv = "flashContent";
var flashvars = {};
flashvars.first_name = "<?php echo $first_name; ?>";
flashvars.email = "<?php echo $email; ?>";
var params = {};
params.bgcolor = bgColor;
params.menu = "false";
params.scale = "noscale";
params.allowFullScreen = "true";
params.allowScriptAccess = "always";
var attributes = {};
attributes.id = movieName;
swfobject.embedSWF(movie, replaceDiv, width, height, flashVersion, express, flashvars, params, attributes);
// ]]>
</script>
i think this is not so confusing as to edit both EMBED and OBJECT tag and you only have to change an attribute once and SWFObject does the rest. definitely worth taking a look...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564649",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PyGTK - webkit.WebView not working with Ubuntu 11.04 here is code snippets:
import gtk, webkit, os
w = gtk.Window()
w.set_title("Example Editor")
w.connect("destroy", gtk.main_quit)
w.resize(500, 500)
editor = webkit.WebView()
editor.load_html_string("<p>This is a <b>test</b>", "file:///")
editor.set_editable(True)
def on_action(action):
editor.execute_script(
"document.execCommand('%s', false, false);" % action.get_name())
actions = gtk.ActionGroup("Actions")
actions.add_actions([
("bold", gtk.STOCK_BOLD, "_Bold", "<ctrl>B", None, on_action),
("italic", gtk.STOCK_ITALIC, "_Italic", "<ctrl>I", None, on_action),
("underline", gtk.STOCK_UNDERLINE, "_Underline", "<ctrl>U", None, on_action),
])
ui_def = """
<toolbar name="toolbar_format">
<toolitem action="bold" />
<toolitem action="italic" />
<toolitem action="underline" />
</toolbar>
"""
ui = gtk.UIManager()
ui.insert_action_group(actions)
ui.add_ui_from_string(ui_def)
vb = gtk.VBox()
vb.pack_start(ui.get_widget("/toolbar_format"), False)
vb.pack_start(editor, True)
w.add(vb)
w.show_all()
gtk.main()
Above example is simple test editor, designed by gtk webkit view.
In Ubuntu 10.04, editor is editable and cursor is visible on webkitview but after switching on ubuntu 11.04, editor is not editable and cursor is not visible.
Note: I'm using classic gnome of Ubuntu 11.04 (not unity)
What could be the problem ? How could I solve this?
any help would be appreciable,
Thanks in advance!
A: I have the same issue as described above, however I'm using Ubuntu 11.10 (Gnome3)
If I add the content editable=true attribute to the p tag, it works as expected.
self.editor.load_html_string("<p contenteditable=\"true\">This is a test", "file:///")
contenteditable=true is inherited, so all child are editable.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564651",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Testing application using ActivityInstrumentationcase2 when I am testing my application using ActivityInstrumentationcase2 on my emulator it is working fine, but when i run it on the device it is showing
java.lang.SecurityException: Injecting to another application requires INJECT_EVENTS permission
but I have given that permission in the manifest file.
My code is:
package cybercom.datamatics.baba.test;
import static android.test.ViewAsserts.assertOnScreen;
import android.app.Activity;
import android.app.Instrumentation;
import android.content.Intent;
import android.test.InstrumentationTestCase;
import android.test.TouchUtils;
import android.test.suitebuilder.annotation.MediumTest;
import android.view.View;
import cybercom.datamatics.baba.CDIS_SMSActivity;
import cybercom.datamatics.baba.Compose;
public class CDIS_SMSTests extends InstrumentationTestCase
{
@MediumTest
public void testActivity()
{
Instrumentation instrumentation = getInstrumentation();
Instrumentation.ActivityMonitor monitor =instrumentation.addMonitor(CDIS_SMSActivity.class.getName(),null,false);
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setClassName(instrumentation.getTargetContext(),CDIS_SMSActivity.class.getName());
instrumentation.startActivitySync(intent);
Activity currentActivity = getInstrumentation().waitForMonitorWithTimeout(monitor,5);
assertNotNull(currentActivity);
View view = currentActivity.findViewById(cybercom.datamatics.baba.R.id.Composemessage);
assertNotNull(view);
View origin = currentActivity.getWindow().getDecorView();
assertOnScreen(origin, view);
instrumentation.removeMonitor(monitor);
monitor = instrumentation.addMonitor(Compose.class.getName(),null,false);
Intent ointent = new Intent();
ointent.setClassName(instrumentation.getTargetContext(),Compose.class.getName());
ointent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
instrumentation.startActivitySync(ointent);
Activity nextActivity = getInstrumentation().waitForMonitorWithTimeout(monitor,5);
assertNotNull(nextActivity);
View numberview = nextActivity.findViewById(cybercom.datamatics.baba.R.id.number);
assertNotNull(numberview);
View nextview = nextActivity.getWindow().getDecorView();
assertOnScreen(nextview, numberview);
TouchUtils.clickView(this,numberview);
instrumentation.sendStringSync("9964973058");
View messageview = nextActivity.findViewById(cybercom.datamatics.baba.R.id.message);
assertNotNull(messageview);
TouchUtils.clickView(this,messageview);
assertOnScreen(nextview, messageview);
instrumentation.sendStringSync("hi");
View sendview = nextActivity.findViewById(cybercom.datamatics.baba.R.id.send);
assertNotNull(sendview);
assertOnScreen(nextview, sendview);
TouchUtils.clickView(this,sendview);
}
}
A: Check that you are clicking where you think you are - in my case this was using the Robotium method Solo.clickOnView.
When I debugged into the code, I found the View.getLocationOnScreen method for the view I was trying to click was populating the values as 0,0, which is clearly outside the bounds of my app (and yours). I'm still not sure why the view was reporting these values, but it was a child of a GridView inside a DialogFragment, and thankfully I could work out the correct offsets using the GridView, the code to get the correct screen location from such a view is as below:
private int[] getLocationOnScreen(View view) {
Rect r = new Rect();
view.getGlobalVisibleRect(r);
int[] xy = new int[2];
View viewParent = (View) view.getParent();
viewParent.getLocationOnScreen(xy);
xy[0] += r.left;
xy[1] += r.top;
viewParent.getGlobalVisibleRect(r);
xy[0] -= r.left;
xy[1] -= r.top;
return xy;
}
A: This problem can also happens with emulator.
you have to check that your screen is not locked.
When screen is locked, the app you are testing doesn't have the focus, so UI commands are sent to the lockscreen, not to your application. This raises the security exception.
Adding the permission would not fix the problem, the only solution is to unlock the screen manually or programmaticaly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564652",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to implement a secured login/logout in Codeigniter? I am making a secured login for the system I am creating with CI since there should be an admin control of the system.
My approach was that I made a file on the application/core directory named MY_System.php where I got this line of code:
class MY_System extends CI_Controller
{
function __construct()
{
parent::__construct();
}
}
Then I also have Admin_Controller.php where I got this code :
class Admin_Controller extends MY_System
{
function __construct()
{
parent::__construct();
$this->is_logged_in();
}
function is_logged_in()
{
$is_logged_in = $this->session->userdata('is_logged_in');
if(!isset($is_logged_in) || $is_logged_in != true)
{
redirect(base_url(). 'login');
}
}
}
The 2 files above are saved inside the core folder of the framework.
While on the controllers directory of the system, I got several controllers let's say Person in instance where I have this code:
class Person extends Admin_Controller
{
function __construct()
{
parent::__construct();
}
}
I believe that in this way, whenever the are pages of the system that shall be restricted I would use the Admin_Controller as the parent of the classes so that the users can't directly access the pages.
Now, my problem is that as I would click logout, the session will be destroyed and the user's data are emptied thus, the user must be redirected to the login page but it doesn't go that way because whenever I would click the back button of the browser right after I click logout, the previous page where the user was would still show up but when I click the links on those page, that's the time when the user will be redirected to the login page. What I want is that, after clicking logout and if he/she attempts and clicks the back button of the browser, he/she must be redirected to the login page.
Does anyone know the solution for my problem? Any help is appreciated. Thanks in advance.
A: Try doing this instead:
redirect(site_url('login'), 'refresh');
A: Try adding the follwing HTTP Header to your pages:
Cache-Control no-cache, no-store, must-revalidate
This will force your browser to redownload the page (= re-execute your controller which should check the is_logged_in variable and redirect to the login page)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564653",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Deploy JAX-WS web services on Tomcat i have jaxws hello world webservice.i want to deploy it to tomcat(as war file).any one please suggest me the best way to do so(explain elaborately). hello world jaxws in here
http://www.mkyong.com/webservices/jax-ws/jax-ws-hello-world-example-document-style/
and there is tutorial on how to deploy it in tomcat
http://www.mkyong.com/webservices/jax-ws/deploy-jax-ws-web-services-on-tomcat/
i have downloaded the source code from above link and deployed war in tomcat.but tomcat was unable to start the webservice.
A: i dont have an idea what crank is .but the exact error is like this.
i deploy war into tomcat start tomcat.i am unable to start this war,it shows following message
FAIL - Application at context path /helloworld could not be started.
in command promt it shows following error
SEVERE:Error listenerstart
SEVERE:Context [/helloworld] startup failed due to previous errors
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564658",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Downloading multiple files simultaneously in Android applications I'm writing an application for Android which let users browse a list of files and download them.
For every download, I created a thread and I download the file with an HttpURLConnection instance (by reading from the connection in a while loop).
This method works fine with one active download. But when user starts more than one, download performance degrades dramatically. Most of the time, these parallel downloads consume all the bandwidth and the users is unable to browse files (which uses another HttpUrlConnection to load the files list).
Any suggestions on refining the download system?
Thanks.
P.S.: The method that popular browsers such as Google Chrome and Firefox do seems good. Anyone knows how they work?
A: Alas, i don't know of a way to throttle certain connections. However, a practical approach would be to implement a queue of downloads to control the number of simultaneous downloads. In your case, you would probably want to only let 1 thing download at a time. This can be implemented a few different ways.
Here's a way to do it with Handlers and a Looper: http://mindtherobot.com/blog/159/android-guts-intro-to-loopers-and-handlers/
Edit 1:
See mice's comment. It may be smarter to have a max of 2 threads downloading at a time.
A: You might want to check out the DownloadManager class in the android SDK.. Its only available above or equal api level 2.3 though.
http://developer.android.com/reference/android/app/DownloadManager.html
Some tutorials you might want to see..
http://jaxenter.com/downloading-files-in-android.1-35572.html
http://www.vogella.de/blog/2011/06/14/android-downloadmanager-example/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564664",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: Retrieve the Current User name in sharepoint using webservices I have designed a infopath form ,in that form load option I need to retrieve the current USERNAME. Who logged in the site must retrieve using WebServices only.
So I did that using UserProfileServices.asmx service and GetProfileByName Method.
But I'm getting different USERNAMES ,Sometimes my USERNAME Sometimes form Admin etc.....Please let me know how can I do this....
A: Please specify what "sometimes" means... And where did you get different Usernames from (WebService or from the InfoPath userName() function)?
If it's the function, this is default behavior if you fill out the form using the client (InfoPath Filler). If it's the WebService make sure you also append the domain to the userName() like this
concat("MyDomain\"; userName())
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564665",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Java - Date format with Turkish or other months I want to format dates with month names with localized label in different languages including Turkish,
how do I set formatted labels for months
A: Use the SimpleDateFormat constructor taking a Locale.
SimpleDateFormat sdf = new SimpleDateFormat("dd MMMM yyyy", new Locale("tr"));
String date = sdf.format(new Date());
System.out.println(date); // 27 Eylül 2011
The Locale accepts an ISO-639-1 language code.
A: public static void main(String Args[]) {
String text = "Çar, 11 Eyl 2013 19:28:14 +03:00";
try {
Date sdf = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss", new Locale("tr")).parse(text);
SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String date = DATE_FORMAT.format(sdf);
System.out.println(date);
} catch (ParseException ex) {
Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564666",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: I can't get Cucumber to work in Windows 7 I'm going through the Rails 3 in Action eBook and they've put a lot of emphasis on testing but I can't seem to get Cucumber to work for some reason.
I keep getting a Rake aborted! Stack level too deep error when I use to rake cucumber:ok command.
Anyone know what might be causing this?
Here's my gem file:
source 'http://rubygems.org'
gem 'rails', '3.1.1.rc1'
# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'
gem 'sqlite3'
# Gems used only for assets and not required
# in production environments by default.
group :assets do
gem 'sass-rails', " ~> 3.1.0"
gem 'coffee-rails', "~> 3.1.0"
gem 'uglifier', '>= 1.0.3'
end
gem 'jquery-rails'
group :test, :development do
gem 'rspec-rails', '~> 2.5'
end
group :test do
gem 'cucumber-rails'
gem 'capybara'
gem 'database_cleaner'
end
A: Use
bundle exec rake cucumber:ok
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564669",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to get the extension of an url I need to get the extension of the URL, for example(.xhtml) using jQuery?
A: jQuery doesn't come into play here.
If you can guarantee your URL ends with an extension...
var path = window.location.pathname,
ext = path.substr(path.lastIndexOf('.') + 1);
...or...
var ext = window.location.pathname.split('.').pop();
...otherwise this will return the full path. You could fix that by making it a bit more verbose...
var path = window.location.pathname.split('.'),
ext;
if (path.length > 1) {
ext = path.pop();
}
A: You could take a look at this SO post - it describes how to get the current URL using JQuery. Getting the extension would be relatively simple after that:
$(document).ready(function() {
var ext = window.location.pathname.split('.').pop();
});
Other SO posts also show how to use the path.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564671",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How to check that ads are being played, before the real video plays? I am working on a site, which airs ads before the real video plays.
The business requirement is that the ads should play before the video plays.
I am Using watir for testing. can you help me in this regard.
Thanks.
A: You may want to investigate Sikuli I've seen other threads where people were using it in combination with watir to work with things like flash. However, since it works based on visual recognition, I expect it would not work at all with video (a changing image that might only be 'right' for a fraction of a second) while it is playing unless there is some aspect of the screen that is relatively static that could be used to know the video play is in progress. See this blog posting for more info
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564678",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Moving source files to a new project.. how to keep alive the SVN history of older committed versions in new project I am moving source files from a web app project in netbeans to a new maven web app project in netbeans. Since my project was under the subversion repositories I need to merge my new created project with the committed versions of old project in the repository so as to keep the history still alive. How do I merge the two projects in subversion repository
A: I infer from your question that your old project (let's call this project A) is under source control and your new project (project B) is not. If that is indeed the case, you have a couple options.
As you suggest in your follow-up comment, import B as a subtree of A. By definition then you have achieved your goal of maintaining the history of A (because you have not changed A). Note that there are two principal ways to do this import: the one-shot import and the import-in-place. You can read details about both in the Tortoise manual here but you can start with this table I put together to illustrate the differences:
In a nutshell, the one-shot import (done via SVN >> Import) sounds like a time saver but in reality it takes the same number of steps as the import-in-place (done via SVN >> Add) and the latter is both more flexible (due to item 2 in the table) and more to the task (items 3, 4, and 5).
Another possibility implied by your question is that you want to start a new project in the repository for B (done via the same import choices as above) and you then want to move the tree for A underneath B. This is a simple drag-and-drop operation in Windows Explorer. But use the right-mouse button to drag so that you get a context menu when you release the mouse button over your target. Then select the SVN Move versioned item(s) here choice. This action actually spawns both a delete action and an add action, as you will see if you then open the commit dialog on a parent common to both source and target directories. Subversion retains knowledge of the move implicitly, though: after you commit view the log from the new location and uncheck the box at the bottom labeled stop on copy/rename you will see the complete history.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564681",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Android java how to make a edit text transparent but the text still visible? How can i make a EditText box invisiable but the text still visiable
<EditText android:layout_height="wrap_content" android:visibility="invisible" android:text="TestttttttttttttttttTTTTTTTTTTTTTTTTTTTTTTTT" android:layout_width="wrap_content" android:id="@+id/editText1" android:layout_above="@+id/trait1" android:layout_alignParentLeft="true" android:layout_marginBottom="78dp">
<requestFocus></requestFocus>
</EditText>
is my code but android:visibility="invisible" makes it all invisible
A: android:background="@null"
or
android:background="@android:color/transparent"
A: Instead of below code
android:visibility="invisible"
use this code
android:background="#00ffffff"
A: if you want to make a view semi-transparent then use this code
android:background="#80ffffff"
A: try it..
write it on onCreate();
EditText.setBackgroundColor(Color.TRANSPARENT);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564682",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: C++ strange behaviour Please check this code..
class ex
{
int i;
public:
ex(int ii = 0):i(ii){}
~ex(){cout<<"dest"<<endl;}
void show()
{
cout<<"show fun called"<<endl;
}
};
int main(int argc , char *argv[])
{
ex *ob = NULL;
ob->show();
return 0;
}
what happens when we call show method.
Thanks..
A: ex *ob = NULL;
ob->show();
You're dereferencing a null pointer which causes undefined behaviour. This is bad.
If it's not clear where the dereference is then understand that the -> operator translates to
(*ob).show().
A: It is undefined behavior.
That being said, on most compilers, you will be able to call methods on null pointers as long as
1) they don't access members.
2) they are not virtual.
Most compilers will translate
ob->show()
into
call ob::show
which is a valid method present in the application space. Since you're not accessing members, there's no reason for a crash.
A: Calling the show method on the object pointed by a null pointer is classified as "Undefined Behavior" and it means that whatever happens you cannot tell that C++ is wrong because the mistake in on your side.
Undefined behavior means that the compiler writers do not need to care about the consequences of your bad programming... so they are free to just ignore those cases. Often undefined behavior is thought to mean "crash" but this is quite far from truth. Executing code with undefined behavior may crash, may do nothing, may apparently do nothing and make your program to crash one million instructions later in a perfectly fine place or it may even running apparently fine and without crashes at all but silently corrupting your data.
One main assumption of the C++ language is that the programmers make no mistake. In other languages this is not true and you get "runtime error angels" that will check and stop your program when you made a mistake... in C++ instead those checks are considered too expensive and therefore instead of "runtime error angels" you get "undefined behavior daemons" that in case of an error will have fun of you.
This, added to the high complexity of C++, is the reason for which I think that C++ is a very bad choice for beginners (beginners make a lot of mistakes) and make impossible to learn C++ by experimentation (because consequences of errors are non deterministic).
In your specific case, given that compiler writers are lazy (not a bad quality for a programmer) I'd guess that on x86 architectures the code wouldn't probably do any damage and it will probably execute as if the pointer was to a valid object.
This is of course just speculation as it depends on the compiler, the hardware and the compiler options. Probably there are out there good compilers that have a compiling debug option that will generate code that crashes instead.
A: The behaviour is undefined. How the program will actually behave is implementation-dependent. I expect that most implementations try to execute the code without checking the pointer. So your initial example should run smoothly since it does not reference any local member of the class.
It is interesting to check what the following code does:
class ex
{
int i;
public:
ex(int ii = 0):i(ii){}
~ex(){cout<<"dest"<<endl;}
virtual void show()
{
cout<<"show fun called"<<endl;
}
};
int main(int argc , char *argv[])
{
ex *ob = NULL;
ob->show();
return 0;
}
If the method is virtual maybe the runtime needs to access some local data of the object, leading to a null pointer or bad address exception.
EDIT
I tested the following slightly modified example with GCC on cygwin:
#include <iostream>
using namespace std;
class ex
{
int i;
public:
ex(int ii = 0):i(ii){}
~ex(){cout<<"dest"<<endl;}
void show()
{
cout<<"show fun called"<<endl;
}
virtual void vshow()
{
cout<<"vshow fun called"<<endl;
}
};
int main(int argc , char *argv[])
{
ex *ob = NULL;
ob->show();
ob->vshow();
return 0;
}
and, in fact, the output is:
show fun called
Segmentation fault (Core dumped)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564696",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to set time range in a day using UIDatePickerView I am using UIDatePickerView, just like we can set the date range using "maximumDate" and "minimumDate", is there any way to set time range in a day like from 9.00 am to 6.00 pm ?
A: Not really. minimumDate and maximumDate can include a time of day (NSDate is more like a timestamp than a calendar date), but this only has an effect if they are both on the same day because otherwise all (clock) times are possible within the date range.
A: Actually you should set the time using these two as well. NSDate objects have both date and time components. You should do something like this:
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
//set the date using setDate: setMonth: setYear:
[dateComponents setHour:9]; //setHour:18 for maximumDate
NSDate *targetDate = [gregorian dateFromComponents::dateComponents];
[dateComponents release];
[gregorian release];
datepick.minimumDate = targetDate;
If that doesnt help, have a look at these Qs:
UI Datepicker range. iPhone
How to set time on NSDate?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564701",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: compile error on android In file included from
/home/imagetech/Android/android-ndk-r3/build/platforms/android-5/arch-arm/usr/include/stdio.h:55,
from test_cl.cpp:21:
/home/imagetech/Android/android-ndk-r3/build/platforms/android-5/arch-arm/usr/include/sys/types.h:88:
error: conflicting declaration 'typedef unsigned int size_t'
/home/imagetech/Android/android-ndk-r3/build/platforms/android-5/arch-arm/usr/include/machine/_types.h:44:
error: 'size_t' has a previous declaration as 'typedef long unsigned int size_t'
A: why dont you try different name "size_t" since i think the same declaration is present in the _types.h file. so it is giving the conflict.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564703",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: c++ visual studio 2010 exe in resource get Rebased? Has anyone noticed that if you import an exe as resource it gets rebased and also seems that its PE header gets rebuilt?
There are times that this is irritating. Does anybody knows how to disable the rebasing!?
steps to reproduce in c++:
1) compile a hello world and manually set its base address (in properties) to lets say 0x1000000
2) make a second project and include the hello world into resources. Also manually set its base address as above.
3) build second project
4) extract the exe from resources and check it with a Pe editor! it gets set back to 0x400000. Why?!
A: How are you including the EXE as a resource into the second project?
Using these defines:
#define BINFILE 222
#define IDR_MYFILE 101
If I reference the executable in my .rc file as pointing to the original file, e.g.:
IDR_MYFILE BINFILE "S:\\mysource\\t1\\Release\\t1.exe"
Then, upon extraction, my embedded EXE resource is not rebased, but maintains what I had built it with.
A: You might be interested in a binary builder that'll covert your exe file as a const unsigned char [] array.
That way, VisualStudio will not have a chance to snoop into your resources.
For example, this one:
http://sourceforge.net/projects/juce/files/juce/1.52/prebuilt%20binaries/BinaryBuilder.exe/download
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564706",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: How to check if one graphic is overlapping another? I've looked on Google and still couldn't find anything. I had an idea for a simple Snake type game or like a 'Coin Collection' game using 2D graphics, but if a coin is a graphic and the moving character is a graphic, how do I check if the character goes over the coin? I'm stumped. Any ideas?
A: For a crude implementation have all your sprites backed by a Rectangle2D object, and use the intersects method to test for collision. Caveat, this is very crude!
A: Yes, the classic Picking and Selection problem. It's a bit long to explain here - please read http://download.oracle.com/javase/tutorial/2d/advanced/user.html . And also, the easiest is to use contains(MousePoint) .
See this Picking in java 2d .
A: I can't think of any way to do this using the graphics package; moreover, I think this is something you should do in your model rather than your graphics.
The problem you're looking at is generally called "collision detection". There are many different approaches to this; looking around online for some guides would be useful. However, I think one simple approach is to think of each object (coin, snake...etc) as a rectangle, making the math really simple. Circles (for the coin) should not be too bad either.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564709",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Rotation of a line based on fixed point in flex4
As in the figure i have three lines out of which line1 and line2 are fixed.
line3 is derived from line1 based on some angle say 70.I try to rotate the line3 but it deviate from the point x1 and x2.
I try the code like this
<s:Line xFrom="200" xTo="600" yFrom="310" yTo="310"/>
<s:Line xFrom="200" xTo="600" yFrom="310" yTo="310" rotation="70"/>
My doubts are
- how to rotate line3 based on the point x1 and x2.
- how to find out the intersection point(x2,y2) of line2 and line3.
thanks in advance
A: I believe this is what you're looking for:
<s:Group x="200" y="310">
<s:Line width="300">
<s:stroke><s:SolidColorStroke color="red"/></s:stroke>
</s:Line>
<s:Line width="300" rotation="-70">
<s:stroke><s:SolidColorStroke color="blue"/></s:stroke>
</s:Line>
</s:Group>
The important you have to remember when rotating is the center of rotation, and that's top-left in this case (as J_A_X pointed out). So we just wrapped it in a Group at your x1,y1 position.
Now, I don't believe using it this way is exactly what you need, as you also asked for the intersection between line2 and line3. This calls for some math, and we can use math too to actually rotate the lines accordingly.
I will assume that line1 and line2 are horizontal, like in your drawing.
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
initialize="computeStuff(70)">
<s:Line id="line1" xFrom="200" yFrom="310" xTo="400" yTo="310"><s:stroke><s:SolidColorStroke color="red"/></s:stroke></s:Line>
<s:Line id="line2" xFrom="200" yFrom="210" xTo="400" yTo="210"><s:stroke><s:SolidColorStroke color="green"/></s:stroke></s:Line>
<s:Line id="line3" xFrom="200" yFrom="310"><s:stroke><s:SolidColorStroke color="blue"/></s:stroke></s:Line>
<s:Rect id="intersection" width="5" height="5"><s:fill><s:SolidColor color="red"/></s:fill></s:Rect>
<s:HSlider id="slider" minimum="-90" maximum="90" value="70" change="computeStuff(slider.value)"/>
<fx:Script>
<![CDATA[
private function computeStuff(angle:Number):void {
var u:Number = angle/180 * Math.PI;
var len:Number = 300;
line3.xTo = line3.xFrom + len * Math.cos(u);
line3.yTo = line3.yFrom - len * Math.sin(u);
// intersection:
var d:Number = -(line3.yTo - line3.yFrom) / (line3.xTo - line3.xFrom);
intersection.x = line2.xFrom + (line3.yFrom - line2.yFrom) / d;
intersection.y = line2.yFrom;
}
]]>
</fx:Script>
</s:Application>
A: I don't think rotation will work when you specify absolute line position. Have you tried doing something like this:
<s:Line x="200" y="310" width="400"/>
<s:Line x="200" y="310" width="400" rotation="70"/>
By default, flex should use the top-left of the component as a rotation point. If the code above doesn't work, try to wrap it in a Group:
<s:Group rotation="70">
<s:Line x="200" y="310" width="400"/>
</s:Group>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564715",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Is there something that starts a cron in java? I have some java written to do a very very simple operation. It needs to happen once every three hours and is not connected to any user action, it's just something that revolves every three hours.
For this reason, I'm having trouble troubleshooting. The operation isn't happening. Assuming the java is intact, is there something that is supposed to "start" the cron? Or should I expect it to just be going once the server is restarted?
<bean id="queueJob" class="org.springframework.scheduling.quartz.JobDetailBean">
<property name="jobClass" value="com.campbiche.pb.service.scheduler.BaseQuartzScheduler" />
<property name="jobDataAsMap">
<map>
<entry key="processorName" value="scheduleListingActions" />
<entry key="methodName" value="revolveQueue" />
</map>
</property>
</bean>
<bean id="queueCronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail" ref="queueJob" />
<!-- run every 1 miunute -->
<property name="cronExpression" value="*/1 * * * * ?" />
</bean>
Working in SpringSource. The Cron is set to one minute for testing. "" has already been added to a schedulerfactorybean bean as well but I did not include the code here for brevity.
A: It will be triggered when CronTriggerBean is instantiated.
One more thing I recall, and confirmed after looking in the docs(3.x), that you need to add your queueCronTrigger to SchedulerFactoryBean.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564716",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Devise Sign in Sign Out link Error I followed the wiki to create the links but get this error: Granted I am fairly new to Rails and Devise
uninitialized constant ApplicationController::UserSession
Extracted source (around line #1):
1: <% if user_signed_in? %>
2: <li>
3: <%= link_to('Logout', destroy_user_session_path, :method => :delete) %>
4: </li>
Trace of template inclusion: app/views/layouts/_header.html.erb, app/views/layouts/application.html.erb
app/controllers/application_controller.rb:10:in `current_user_session'
app/controllers/application_controller.rb:16:in `current_user'
app/views/devise/menu/_login_items.html.erb:1:in`_app_views_devise_menu__login_items_html_erb__1251633497065791740_2169375180__3843613137737702562'
app/views/layouts/_header.html.erb:13:in `_app_views_layouts__header_html_erb___2695761790912056148_2169430740_3591649723346667383'
app/views/layouts/application.html.erb:10:in `_app_views_layouts_application_html_erb__2958864439808398489_2169528520__269406770402330689'
A: I had the same problem because I was migrating from authlogic to devise and I forgot to delete the authlogic specific methods in the application controller, like
private
def current_user_session
return @current_user_session if defined?(@current_user_session)
@current_user_session = UserSession.find
end
def current_user
return @current_user if defined?(@current_user)
@current_user = current_user_session && current_user_session.record
end
def require_user
unless current_user
store_location
flash[:notice] = "You must be logged in to access this page"
redirect_to new_user_session_url
return false
end
end
def require_no_user
if current_user
store_location
flash[:notice] = "You must be logged out to access this page"
redirect_to account_url
return false
end
end
def store_location
session[:return_to] = request.request_uri
end
def redirect_back_or_default(default)
redirect_to(session[:return_to] || default)
session[:return_to] = nil
end
I hope this can help you.
A: Not sure if this is the problem, but have you tried setting :method => :delete to :method => :get? I would also suggest setting the link_to to button_to since you are trying to "do something" and not necessarily "go somewhere."
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564717",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Replace string in between occurrences I have a string I want to display inside the uiwebview that may look like this:
"blah blah blah [IMG]you.png[/IMG] blah blah [IMG]me.png[/IMG]"
I want it replaced like this:
"blah blah blah <img src=\"you.png\"> blah blah <img src=\"me.png\">"
I can already get the string between the [IMG]...[/IMG] the problem is that it can only get the first set of [IMG]...[/IMG] and the rest of the occurrence cannot.
NSRange startRange = [finalQuestionString rangeOfString:@"[IMG]"];
if (startRange.location != NSNotFound) {
NSRange targetRange;
targetRange.location = startRange.location + startRange.length;
targetRange.length = [finalQuestionString length] - targetRange.location;
NSRange endRange = [finalQuestionString rangeOfString:@"[/IMG]" options:0
range:targetRange];
if (endRange.location != NSNotFound) {
targetRange.length = endRange.location - targetRange.location;
NSString *imageFile = [finalQuestionString
substringWithRange:targetRange];//the extracted filename
}
}
so how can I get all the occurrences of [IMG]...[/IMG] and replace it with
"<img src=\"file.png\">"
any help would be appreciated. Thanks!
A: Since [IMG] will always become <img src=\" and [/IMG] will always become \">", why not do something like this:
NSString *originalString = @"blah blah blah [IMG]you.png[/IMG] blah blah [IMG]me.png[/IMG]";
NSString *tempString = [originalString stringByReplacingOccurrencesOfString:@"[IMG]" withString:@"<img src=\""];
NSString *finalString = [tempString stringByReplacingOccurrencesOfString:@"\"[/IMG]" withString:@"\'>'"];
Memory management is left as an exercise for the reader :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564725",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: css progress bar I have a question in regards to a progress bar. I've read pretty much all the posts here but it appears I can't make any of them work in my scenario.
I have the following which shows numbers such as 50/500 where 50 is the actual number and 500 is the max.
$SQL = "SELECT * FROM db_ships WHERE ship_id = $user[ship_id] LIMIT 1";
$result = mysql_query($SQL);
while ($db_field = mysql_fetch_assoc($result)) {
print $db_field['shields'] . " / ";
print $db_field['max_shields'] . "";
Most progress bars that I see depict timeframes, I need to visually show the fraction
print $db_field['shields'] . " / ";
print $db_field['max_shields'] . "";
How can I place this so I can have a progress bar depicting the progress?
I am sorry I am not good at css. Any help would be greatly appreciated.
A: One simple way of doing it is placing a div inside a larger div and setting the percentage width of the inner div. Here's a fiddle showing what I mean.
You can get the percentage of max_shields by writing (Assuming they are both numbers)
$percentage = $db_field['shields'] * ($db_field['max_shields'] / 100);
Apply the percentage as the width of the inner div.
<div id="progress-inner" style="width: <?php echo $percentage; ?>%;"></div>
It would be a breeze to animate that progress bar using jQuery animate if you wanted to.
A: echo "<div class=\"progressbar_container\"><div class=\"progressbar\" style=\"width: ".($db_field['shields']/$db_field['max_shields']*100)."%\"></div></div>";
And define styles as needed. Maybe a border for the container and a background colour for the main bar. That's all there is to a basic progress bar.
A: <style type="text/css">
.table, th
{
background-color:Blue;
border-collapse:collapse;
}
<table class="table" >
<tr id = "row1" >
<td id ="cell1" class="td"></td>
</tr>
</table>
<script language="javascript" type="text/javascript" >
var i = 1;
var timerID = 0;
timerID = setTimeout("progress()",200);
var scell = '';
var sbase = '';
sbase = document.getElementById("cell1").innerHTML;
function progress()
{
var tend = "</tr></table>";
var tstrt = "<table><tr>";
scell = scell + "<td style='width:15;height:25' bgcolor=blue>";
document.getElementById("cell1").innerHTML = sbase + tstrt + scell + tend;
if( i < 50)
{
i = i + 1;
timerID = setTimeout("progress()",200);
}
else
{
if(timerID)
{
document.getElementById("cell1")
.innerHTML=document.getElementById("cell1").innerHTML
+ "</tr></table>";
clearTimeout(timerID);
}
}
}
</script>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564727",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Getting User Details from MGTwitterEngine I am developing an application which has a Twitter login. I have integrated MGTwitterEngine for that, and everything is working fine.
My problem is that when the user logs in, I need some details -- whatever info is returned by MGTwitterEngine for that logged-in user.
When I had a look in the library docs, I found the below delegate method which might give some user information, but when I log in ,this method never gets called.
- (void)userInfoReceived:(NSArray *)userInfo forRequest:(NSString *)connectionIdentifier {
NSLog(@"User Info Received: %@", userInfo);
}
Can somebody please suggest to me how to get the user's information from MGTwitterEngine or how I should use this method?
_engine = [[SA_OAuthTwitterEngine alloc] initOAuthWithDelegate:self];
_engine.consumerKey = @"PzkZj9g57ah2bcB58mD4Q";
_engine.consumerSecret = @"OvogWpara8xybjMUDGcLklOeZSF12xnYHLE37rel2g";
UIViewController *controller = [SA_OAuthTwitterController controllerToEnterCredentialsWithTwitterEngine: _engine delegate: self];
if (controller)
[self presentModalViewController: controller animated: YES];
else {
tweets = [[NSMutableArray alloc] init];
[self updateStream:nil];
}
A: I found the answer of my question:-
- (void) OAuthTwitterController: (SA_OAuthTwitterController *) controller authenticatedWithUsername: (NSString *) username {
NSLog(@"Authenticated with user %@", username);
[_engine getUserInformationFor:username];//this line to be added to get userInfo method called
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564732",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Drupal 7 webform submission to remote MSSQL server When users fill up a form on my Drupal 7 site, I need that information to go into a remote MS SQL server db. It's essentially a reservation system, so they fill up details like date/time and name, and when they click submit, these fields need to be pushed into a remote MS SQL db.
I'd like to know a) if this is possible and b) how do I go about implementing this?
A: A. Yes it is possible.
B. I recommend the below way, which is also the "Drupal" way of doing it.
*
*Establish a connection to the remote database. Have a look here if you want to do it in your code, or have a look here if you want Drupal to take care of it by configuring settings.php. The key to switching between databases are db_set_active($database).
*Run the queries you'd like to run against the MSSQL database. Just remember to put switch between the databases using db_set_active().
A: You can create a custom form in Drupal easily using its Form API in a custom module. In the submit handler for your form, you can insert the submitted data to your MS SQL database using any library avaiable in your PHP environment. Connection to the database is the tricky part, especially if your Drupal host is not running a Microsoft OS. In Drupal 7 running on IIS, you can use Drupal's Database API with the MS SQL driver. If your are not on IIS or Drupal 7, this is also doable without Drupal's Database API using PDO ODBC with unixODBC and FreeTDS. I did it, but I had a major issue when using typed bound parameters in my query, see Using typed bound parameters with PHP PDO-ODBC, unixODBC and FreeTDS.
That said, integration of applications at the database level is a bad idea. Such integration is tightly coupled. Any change to the schema of your MS SQL database or they way actual data are stored in columns will break your form submission. The best would be to have your reservation system provides a remote API to insert new data.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564735",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: problem of callback from C++ to JS I'm a newer to NPAPI. I come across one problem.
in my plugin, I need to return some data from C++ to JavaScript, yes,that's callback. but the callback thread and the main thread are separate threads. So I use NPN_PluginThreadAsyncCall, but the problem can not be solved also. When callback, the firefox crashed...
Can anyone help me?
the bellow codes are in the callback thread, Can anyone tell me, why it crashed?
npnfuncs->pluginthreadasynccall(instance,callBackfunc,(void*)pdata);
/////////////////////////////////////////////////////////////////////
void callBackfunc(void* arg)
{
NPObject *winobj;
npnfuncs->getvalue(instance,NPNVWindowNPObject,&winobj);
NPVariant handler;
NPIdentifier id1 = npnfuncs->getstringidentifier("MyTest".c_str());
npnfuncs->getproperty(instance, winobj, id1, &handler);
NPObject* handlerObj= NPVARIANT_TO_OBJECT(handler);
NPVariant prototype;
NPIdentifier id2 = npnfuncs->getstringidentifier("prototype");
npnfuncs->getproperty(instance, serviceHandlerObj, id2, &prototype);
NPObject* prototypeObj= NPVARIANT_TO_OBJECT(prototype);
NPIdentifier id = npnfuncs->getstringidentifier("fun".c_str());
NPVariant voidResponse;
int status=npnfuncs->invoke(instance,prototypeObj,id,args,argCount,&voidResponse);
return;
}
thanks
Best Regards
greatsea
A: ... What is "MyTest".c_str() supposed to be? This is C++, no? c_str() is a method of a std::string class, and I don't see that being sued here, so trying to do a .c_str() on it shouldn't even compile, unless there is something going on here that I really don't understand.
Also be aware that at least Safari 5.1 has stopped supporting NPN_PluginThreadAsyncCall and different methods need to be used to make cross-thread callbacks. I don't know if other browsers have or will or not; so far it doesn't seem so.
Is there a reason you're not just using FireBreath for your plugin? It solves all of these problems for you and lets you just focus on your plugin...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564736",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Passing Arrow and Tab keys to Delphi Form in a DLL When a Delphi Form is declared and instantiated inside a DLL and the DLL loaded by the host application, Arrow and Tab keys are not passed across the Host/DLL boundary. This means that TEdit boxes and TMemo controls that may be used on the form will not respond to these key strokes. Is there anyway to ensure that these key strokes are passed from the main application form to the form in the dll? Note there may be multiple DLLs, each containing a form. KeyPreview makes no difference.
A: Looking at this question, and your previous one, I would say that your basic problem is that you are not using runtime packages.
If you were using runtime packages then you would have a single instance of the VCL and module boundaries would not matter.
Without runtime packages you have separate VCL instances. For the VCL form navigation to work correctly you need each control to be recognised as a VCL control. This is not possible when you have multiple VCL instances.
A: Forms in DLL's miss this support, as well as support of menu shortcuts (actions). You can write some code to simulate this behaviour.
////////////////////////////////////////////////////////////////
// If you display a form from inside a DLL/COM server, you will miss
// the automatic navigation between the controls with the "TAB" key.
// The "KeyPreview" property of the form has to be set to "True".
procedure TForm1.FormKeyPress(Sender: TObject; var Key: Char);
var
bShift: Boolean;
begin
// Check for tab key and switch focus to next or previous control.
// Handle this in the KeyPress event, to avoid a messagebeep.
if (Ord(Key) = VK_TAB) then
begin
bShift := Hi(GetKeyState(VK_SHIFT)) <> 0;
SelectNext(ActiveControl, not(bShift), True);
Key := #0; // mark as handled
end;
end;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564737",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Has anyone faced this error -- Out of memory (Needed 48984 bytes)? Has anyone faced this error: Out of memory (Needed 48984 bytes) before?
Here are the details:
I have a DLL file that contains some mathematical algorithms implemented. These algorithms need around 10k values for their calculation. So we have stored 10k values ina MYSQL database. The DLL uses MYSQL C APIs to import the 10k values and does calculations. It works fine but if I keep the DLL running continuously I get following error -- Out of memory (Needed 48984 bytes).
I hope this explanation would help you to understand issue. I cannot share the code as I have only DDL file.
A: It sounds like you have a monumental memory leak. Maybe there is a method in the DLL that you should be using to release the 10k values read from the MySQL database?
A: [SOLVED]:
max_allowed_packet when dump the DB, must be smaller when restore the DB
example
max_allowed_packet = 16M #when dump DB
max_allowed_packet = 32M #when restore DB
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564740",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: PHP file_get_contents changing file name I need to get a file from the server and I'm doing it like this:
file_get_contents($path.$fileName);
It works well with most of the files, until I started experiencing some issues in particular cases like the following:
Where the $path is a string like this: "/path/to/app/and/file/folder/" (not a url but a realpath)
and $fileName is: "PCard__0000_Front_(2).jpg"
The error I get is:
/path/to/app/and/file/folder/PCard__0000_Front_(2).jpg)
[function.file-get-contents]: failed to open stream: No such file or
directory
Now if I call the function with a string: file_get_contents("/path/to/app/and/file/folder/PCard__0000_Front_(2).jpg") it works well
Please some advise on what am I doing wrong, I would really like to understand why this happens.
Thanks!
P.S. I have seen some others say to use curl instead but I would really appreciate if someone could shed some light into why this is happening and how can I solve it using file_get_contents no matter how much better the other function could be.
A: The error message is clear and obvious.
There is no such file /path/to/app/and/file/folder/PCard__0000_Front_(2).jpg
So, for some reason you are changing the filename from PCard__0000_Front_(2).jpg to PCard__0000_Front_(2).jpg.
A solution: do not change the filename.
A: Judging by the output of the error message with the filename showing, PCard__0000_Front_(2).jpg
perhaps there's a need for urldecode($filename)
SOLUTION
As suggested by a comment (thank you) the solution for the proper file name would be
html_entity_decode($filename)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564746",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Will an image or document be cached when it is viewed through UIWebView in iOS? Typically when we load a image or document through a browser, the image gets cached in a temp folder. Is this the same case for Mobile safari and other browsers in MObile?
And if that is the case, if the phone is rooted, will user be able to access them?
Will an image or document be cached when it is viewed through UIWebView in iOS?
A: No, the class doing the caching is NSURLRequest. You can remove the cache for a particular request
[[NSURLCache sharedURLCache] removeCachedResponseForRequest:request];
or for all of them
[[NSURLCache sharedURLCache] removeAllCachedResponses];
or set an empty cache before performing any request
NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:0 diskPath:nil];
[NSURLCache setSharedURLCache:sharedCache];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564748",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to get all elements with a given property? I'd like to get all <input /> elements with the placeholder property set, how could I do this without jquery? it should support IE6+, and other popular browsers.
A: Assuming all the fields have an ID
DEMO
var fieldsWithPlaceholder = [];
var inputs = document.getElementsByTagName("input");
for (var i=0, n=inputs.length;i<n;i++) {
if (inputs[i].getAttribute("placeholder") !=null) {
fieldsWithPlaceholder.push(inputs[i].id);
}
}
alert(fieldsWithPlaceholder);
Update: you can as posted elsewhere test for null, undefined or blank in one go:
if (inputs[i].getAttribute("placeholder")) { // there is something there
A: Use getElementsByTagName, filter for those with a placeholder property value that isn't undefined.
Incidentally, there is a big difference between attributes and properties, which are you really after? If you are setting an attribute called placeholder in the HTML, then you should use getAttribute. However, if you are setting the property of a DOM element (which is what I presumed from your post) then you should use the property directly. Hopefully you aren't mixing the two.
In some browsers, attributes and properties are kept synchronised but in others they aren't. For example, Firefox will not create element properties for non–standard attributes (i.e. those that aren't specified in the related markup standard), nor will it create or modify standard attributes based on property changes in versions that aren't consistent with HTML5.
A: get all the elements of type input first
document.getElementsByTagName("input")
loop over the above list and then use the
getAttribute on each of the element as follows getAttribute("placeholder") if it is not null or undefined then the input has it set.
A: Try something like this:
var myEls = [],
allEls = document.getElementsByTagName('input');
for (var i=0; i < allEls.length; i++) {
if (allEls[i].placeholder)
myEls.push(allEls[i]);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564752",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: VBA/javascript. script to automate browser actions First of all. I'm a dummy in programming.
I was trying to use JavaScript and VBA in Excel to automate some IE actions to go to some page and download Excel files from that page, as I need to do this everyday.
*
*The excel file to be downloaded does not have a link.
*The VBA script did well in auto login, but when the IE goes to a second page ( different URL ), it always pops up a run time error 70 -- permission denied. I tried to modified the security in IE options but not working.
*I use JavaScript to do the auto login and it worked well too, but again after the IE goes to a diff page, it seems stop working.
*So I suspect that it might be that my script did not grab the new html document when url changes.
VBA:
Sub vbadownload()
Dim objIE As SHDocVw.InternetExplorer ' internet controls
Dim htmlDoc As MSHTML.HTMLDocument ' html object lib
Dim htmlInput As MSHTML.HTMLInputElement
Dim htmlDiv As MSHTML.HTMLDivElement
Dim htmlColl As MSHTML.IHTMLElementCollection
Set objIE = New SHDocVw.InternetExplorer
''''''''''' first log in
With objIE
.Navigate "mainpage.com" ' log in page
.Visible = 1
Do While .READYSTATE <> 4: DoEvents: Loop
Application.Wait (Now + TimeValue("0:00:01"))
'set user name and password
Set htmlDoc = .Document
Set htmlColl = htmlDoc.getElementsByTagName("INPUT")
Do While htmlDoc.READYSTATE <> "complete": DoEvents: Loop
For Each htmlInput In htmlColl
If htmlInput.Name = "username" Then
htmlInput.Value = "xxxx" 'username
Else
If htmlInput.Name = "password" Then
htmlInput.Value = "xxxx" 'password
End If
End If
Next htmlInput
'click login
Set htmlDoc = .Document
Set htmlColl = htmlDoc.getElementsByTagName("input")
Do While htmlDoc.READYSTATE <> "complete": DoEvents: Loop
For Each htmlInput In htmlColl
If Trim(htmlInput.Type) = "submit" Then
htmlInput.Click 'click
Exit For
End If
Next htmlInput
' now it goes to second page after submit
' and I want click some button on second page, it says permission denied.
' so how do i make below codes work on current page without typing new url. ( as the url actually does not change, I guess because it's js webpage? I don't know)
Set htmlDoc = .Document
Set htmlColl = htmlDoc.getElementsByTagName("div")
Do While htmlDoc.READYSTATE <> "complete": DoEvents: Loop
For Each htmlDiv In htmlColl
If Trim(htmlDiv.ID) = "123" Then
htmlDiv.Click 'click
Exit For
End If
Next htmlDiv
End With
JavaScript
var ie = new ActiveXObject("InternetExplorer.Application");
ie.visible=true;
ie.navigate("www.sample.com");
while(ie.busy)(WScript.sleep(100));
var doc1 = ie.document;
var window1 = doc1.window;
var form1 = doc1.forms[0];
form1.username.value="xxx";
form1.password.value="xxxx";
form1.submit();
/* again, from here, it goes to second page, and it stops working.
* how do I get/parse current html document? */
var div1 = doc1.getElementsByTagName("div");
for (var i=0; i<div1.length; ++i)
{
if (div1[i].className="fff")
{div1[i].click()}
}
A: Every time you refresh the page (by submitting a form or using .navigate) you need to repeat your "sleep" loop so that you wait for the page to complete loading, and then grab a new reference to the document object. After you navigate it's a new page, so you can't just continue to use the "old" document reference.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564753",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to check whether the wifi is connected to specific SSID I read this solution : How to check network connection enable or disable in WIFI and 3G(data plan) in mobile? .BUT, it just check whether wifi network is connected or not. How to check whether the wifi is connected to the specific SSID or not?
A: The code is similar, again use a system service, make sure you are connected to something and get the SSID:
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
if (WifiInfo.getDetailedStateOf(wifiInfo.getSupplicantState()) == NetworkInfo.DetailedState.CONNECTED) {
String ssid = wifiInfo.getSSID();
}
A: public static boolean IsWiFiConnected(Context context) {
ConnectivityManager connectivity = (ConnectivityManager) context
.getApplicationContext().getSystemService(
Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getTypeName().equals("WIFI")
&& info[i].isConnected())
return true;
}
}
}
return false;
}
A: The best that worked for me:
Menifest:
<receiver android:name="com.AEDesign.communication.WifiReceiver" >
<intent-filter android:priority="100">
<action android:name="android.net.wifi.STATE_CHANGE" />
</intent-filter>
</receiver>
Class:
public class WifiReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
if(info!=null){
if(info.isConnected()){
//Do your work.
//To check the Network Name or other info:
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
String ssid = wifiInfo.getSSID();
}
}
Permissions:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564755",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: bar scanner for MonoTouch? I've been looking into making an iOS app which uses the camera to take a photograph of a barcode (such as code 39) and reading them in properly.
Was just looking at a few libraries, not sure if any work as I'd like but they're all using objective-c for iOS.
Thought maybe I should ask if there is a solution in MonoTouch since that is how I want to make the app for iOS?
A: There is a similar thread running on MonoTouch mailing-list.
RedLaser latest (newer than mono's git repository) bindings are available at: https://github.com/chrisbranson/monotouch-bindings
with sample code available at: https://github.com/chrisbranson/RedLaserSample
Another suggestion was using: https://github.com/GoranHalvarsson/BarcodeReader-MonoTouch
Other people have using the (commercial) LineaPro SDK (some MonoTouch bindings are available on github too).
A: Here is another one by Redth:
https://github.com/Redth/ZXing.Net.Mobile
His example usage:
var scanner = new ZXing.Mobile.MobileBarcodeScanner();
scanner.Scan().ContinueWith((result) => {
if (result != null)
Console.WriteLine("Scanned Barcode: " + result.Text);
});
A: You can use Monotouch to bind the native objective-c libary to your monotouch project.
You can find detail information about this topic here:
http://ios.xamarin.com/Documentation/Binding_New_Objective-C_Types (NOT AVAILABLE ANYMORE)
You can find a ready to use binding for RedLaser on Github:
https://github.com/mono/monotouch-bindings
A: Mine also works:
http://www.jmawebtechstore.com/p/21/ios-monotouch-barcode-scanner-reader (WEB CONTENT NOT AVAILABLE ANYMORE)
I have a whole barcode scanning app available with source code. My app saves barcodes to the database and photos to the photo album.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564756",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: When to return a pointer, pass a pointer as a parameter or not use them at all? I am currently experimenting with C, and I am having a really hard time understanding how to use pointers in functions. I understand what is happening when I initialize a pointer then dereferencing it, however, I get a little confused when I have to use them in functions as follows:
I have three functions here, but I do not know exactly when to use which. I am still relatively new to C.
int returnSomething(int a, int b)
int returnSomething(int *ptrA, int *ptrB)
int* returnSomething(int *ptrA, int *ptrB);
edit:
Is there a major difference between the three?
A: You need to adapt your usage to every situation.
The first case, you take two ints by value as parameters and return an int. Because your parameters are by value, any changes applied to them will only have function scope.
For example:
int returnSomething(int a, int b)
{
a = 0;
b = 0;
return 0;
}
//....
int x = 3;
int y = 4;
returnSomething(a,b);
// x will still be 3, y will still be 4
In the second case, because you pass parameters as pointers, you will be able to change the values.
int returnSomething(int* a, int* b)
{
*a = 0;
*b = 0;
return 0;
}
//....
int x = 3;
int y = 4;
returnSomething(&a,&b);
// x and y will be 0 here
The third case, besides passing parameters by their pointer, you return a pointer to an int. This means inside the function you have to allocate memory and free it when you are done. I don't recommend using this, there usually are workarounds to doing it.
int* returnSomething(int* a, int* b)
{
int* x = malloc(sizeof(int));
*x = 1;
return x;
}
//....
int x = 3;
int y = 4;
int* z = returnSomething(&a,&b);
free(z);
The answer is, it depends on what you want to do. If you need to change the parameters value in the method, pass by reference or by pointer. I wouldn't recommend using the last method.
Also, this applies because you're dealing with POD types. If you have your own struct, it will be more efficient passing it by pointer or returning a pointer, since a new copy won't have to be made.
A: Let's explain passing by reference to you first; it's a lot less complicated to deal with.
Say you have:
int increment(int &a)
{
a = a + 1;
return a;
}
increment(foo); // foo = foo + 1;
(NOTE: To make it easier to understand, I've sacrificed some 'correctness'.)
This does two things:
*
*The third line increments a by 1. But notice - we put &a in the function declaration. This means that the value passed to increment() "by reference" is also incremented by 1. In other words, foo increases by 1, just like a.
*The fourth line returns the value of a - a number, such as 1, 2, 42, -21, etc.
One more thing: Passing by reference is C++; you can't use it in C, but it's a good concept to learn before you start messing with pointers.
Passing a pointer is basically just passing by value... except you're passing the location in memory (0x12345678), as opposed to the actual foo.
int pincrement(int *p)
{
*p = *p + 1;
return *p;
}
pincrement(&foo); // foo = foo + 1;
This does the same thing as our first program - it increments the value of foo.
*
*The &foo tells you the address of foo in memory. This information is passed to p. So:
p = &foo;
*On the third line, the value pointed to by *p is incremented. In other words, foo is incremented by 1.
*The fourth line returns the value of foo - a number, such as 1, 2, 42, -21, etc.
For returning pointers, you could use them to return strings:
char *HelloWorld()
{
return "Hello, World!";
}
A: The answer to your question has more to do with memory considerations and good code design i.e. whether you'd like to conserve resources and if you are aware of what's going on in your code at any one instance in time.
1) when you pass by value ( int returnSomething(int a, int b) ) every parameter is a copy and any changes made to them doesn't affect the original variable outside of the function (The parameters have function scope), and the function returns a value which you can then use to initialise a variable.
2) When you pass by pointer, you're passing an address to a location in memory so remember that as a matter of good code design you have to insulate that location against modification by another external (lock semantics) process. This especially applies to your provided examples:
int returnSomething(int *ptrA, int *ptrB)
int* returnSomething(int *ptrA, int *ptrB);
wherein changes made to *ptrA and *ptrB within the function persists after the function exits. The only difference between the two is that one of the functions return a value which you can then use to initialise a variable ( int returnSomething(int *ptrA, int *ptrB) ), the other returns another address to a location in memory that maybe subject to change and/or garbage headaches depending on your program design (you create memory inside the function for the return type and assign that address to a pointer variable, the pointer variable itself can be arbitrarily changed to point to another location in memory, e.t.c.). I'll expand on Luchian's last example by adding: imagine some somewhere else in your code you pass the *z variable to another function which then tries to use the memory pointed to by that address, you now have a pointer variable pointing to nothing which you then try to use.
It all boils down to good code design. If you understand the pros and cons of pointers and use them appropriately then you'll have no issues.
A: Luchian Grigore has written some good description above. I would like to give you a small thought to further simplify your thinking.
When ever you pass a argument to a function in C, try to think what exactly goes on to the stack ( in case 1, actual integer variables gets pushed onto stack and in case 2 & 3 adresses of those integer variables gets pushed ), now to this combine that fact that changes made to variables on stack vanish as soon as the control returns from funciton and stack unwindes.
So in simple terms if you plan to change the varibales being passed inside the function and expect to use those changes later then consider passing the address of those varibles, else simply pass variables.
A: For int, always pass by value unless it is not possible to do so.
i.e int returnSomething(int a, int b).
When you are passing some custom big struct, pass it and return it as a pointer unless it is not possible to do so.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564757",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Email relaying with php | craigslist's anonymous email generator I wanted to create (or at least learn/know how it is done) application(or configuration?) that does similar to what craigslist does when people choose to hide their email with the "anonymous" option when making posts. I suspect that it is done with what's called email relaying. I'd like to find out how it is done in process - from when user enter their email to receiving an email via an anonymous email address. I come from a "LAMP" background at an intermediate level so please bear with me and kindly explain.
Your responses/comments/suggestions/pointers are greatly appreciated.
Thank you
A: The easiest way to do this is to receive email with your php app. There are a wide range of ways to do this, collecting using cron, piping from an email server directly into your app or using a third party like CloudMailin.
I wrote a blog post explaining some of the methods you can use to receive incoming email using php here. The post discusses rails but the principals are the same for most languages and frameworks.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564759",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Fadein Hover with fadeout to orginal state or onclick stay in hover state Hello I'm new to jQuery and Javascript!!
What I have to do is:
website with jquery and thumbnails.
When the page is loaded all the thumbnails have to be on 60% of opacity. As soon as you go with your mouse over a thumb it needs to fade to 100%, if you move with your mouse out the thumbnail needs to fade back up on 60% of opacity.
When the user click on a thumbnail it have to stay at 100% of opacity. As soon as the user click on another thumbnail the 'old' thumbnail has to fade back to 60% and the 'new' one has to stay at 100%. (it already has 100% opacity because you go with your mouse over it).
A: $(document).ready(function(){
$("#image").mouseover(function (){
$(this).fadeTo("slow", 1)
});
$("#image").mouseout(function (){
$(this).fadeTo("slow", 0.6);
});
});
Have a look on jsFiddle I have set up a test to show how this works
A: Here you go, a demo:
http://jsfiddle.net/sg3s/UtU8G/
On hover fade to animation, do not hover out if locked, on click fade others out and lock this one.
Edit
As a bonus, here is a version where you can lock multiple tumbnails using ctrl.
http://jsfiddle.net/sg3s/UtU8G/6/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564762",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Use maven's "version" property in java and nsis code we require the software version number of a maven project both in the java code and in the NSIS installer script. Following the DRY principle, the version number should be stored in the maven pom only. What is the best way to get this version number in the Java code as well as in the NSIS script? Updates on the version number should of course be distributed without the developer having to care about it.
The current approach: Wherever the version number is needed, ${"versionNr"} is inserted as a substitute. Then, during the maven build phase, all java and NSIS source files are filtered and the key is replaced by the version number. To avoid changes in the checked in source code, the filtered files are actually copied to a different location not within the scm. Having the original source and the source filtered by maven causes a lot of confusion, which I would like to avoid.
Any hints?
A: I typically put the version parameter (like ${project.version}) in a properties-file and only apply filtering on that one file in the maven build. Like
app.version=${project.version}
Then I use this properties file in the code to get the version.
A: pom.properties gets built into JAR file (to META-INF/maven/<groupId>/<artifactId>/pom.properties) when the project is packaged up. It looks something like:
#Generated by Maven
#Mon Sep 26 09:03:19 EST 2011
version=1.0-SNAPSHOT
groupId=my.project.group.id
artifactId=my-artifactid
You could read this as a resource in your Java code, and use Property API to read the version out.
Not sure whether NSIS scripts can read property files, but according to the source code of the NSIS plugin it creates a few !defines, including PROJECT_VERSION which gets the project version straight from the POM. Maybe you can use this.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564765",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to add Welcome before username In moss 2007 the welcome control used to appear like "Welcome Username". But in sharepoint 2010 only user name appears in ribbon. How can I add "Welcome" before username in sharepoint 2010 welcome control.
A: You could try the reverse of what Wictor did in Having fun with the SharePoint Welcome.ascx control. While he wanted to get rid of "Welcome," you could set TextType to PostCacheSubstitutionTextType.WelcomeUser to include it. However, as mentioned in this comment, be sure to create your own control and modify your master page, rather than changing Welcome.ascx directly.
Another option would be jQuery. If you are using v4.master, the selector for the user name should be: div.s4-trc-container-menu span.ms-welcomeMenu a.ms-menu-a span. Once you grab the element, you could prepend "Welcome " to the text.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564767",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: NIB in bundle is missing with name MainWindow-iPad I have a Tab bar application having 6 tabs. When I debug and runthe app, it crashes by giving following message in console :
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Could not load NIB in bundle: 'NSBundle </Users/priyachaturvedi/Library/Application Support/iPhone Simulator/4.2/Applications/7C5CE523-A843-443A-9B0B-BDF2336EA7D0/Aljex Mobile-iPad.app> (loaded)' with name 'MainWindow-iPad''
I have already searched out the answersin the following links
How to fix iPhone Simulator trying to launch a Nib that isn't there?
How are XIBs loaded for localized apps?
and
Could not load NIB in bundle
and many other but nothing worked for me.
any one have any idea why this is happening to me???
Thanks in advance !!!
A: Suppose you already checked filenames and so on. So I exclude hypothesis of filenames mismatch. Where might be a problem? You might by mistake excluded MainWindow-iPad.xib from being copied into your app during build (linking) time. How to check that?
*
*Insure MainWindow-iPad.xib is in your project.
*In project in section Products select your app and in context menu choose Show in Finder. In Finder in context menu choose Show Package Contents. Ensure your MainWindow-iPad.xib is there. If it isn't there, go to step 3. If MainWindow-iPad.xib is in package, double check file names, the problem seems to be in filenames mismatch.
*If it isn't there find MainWindow-iPad.xib in your project, select it and ensure checkbox of your target in Inspector isn't deselected. You might did that by mistake. Check this checkbox and rebuild.
A: I have the same problem too. I realise that when you enter the name of the xib file, it has to be "MainWindow-ipad" without the xib extension in your app targ
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564769",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Accessing a Javascript's Variables: Problem involving Javascript, JQuery, and PHP/MySQL & Scope I'm learning how to build a WordPress Google Map plugin. I've got a map with a form. The user makes selections on the form, data will be pulled from a MySQL database, and then markers will be added to the map.
I've got 3 main parts to my project:
a) A PHP file that has the form and the MySQL SELECT statement for handling the form's selections.
b) A Javascript script that builds the Google Map, and calculates the map's bounds
c) A jQuery script that has datepickers. It also serializes the form's selections and posts them to the PHP page.
My problem is that, in addition to the form data, I need the latlongs of the 4 corners of the Google Map in order to select the data from the database. I know how to calculate the bounds using Google Maps' functions in script (b). My problem is that I don't know how to return the variables in (b)
var maxLat = ne.lat();
var maxLong = ne.lng();
var minLat = sw.lat();
var minLong = sw.lng();
back to the PHP page. These values aren't in the form that I'm serializing. They are in the javascript script file (b), not the jQuery script (c) that has the post functions. Also, the variables are calculated after the map loads. So, I can't just leave the variables outside of a function and access them from script (c).
What's the best way to give the PHP access to these variables?
Should I try to do a separate post for these values? Is there a way to allow script (c) access to the variables in script (b), and then add them on to the the form's post data somehow?
Please advise what's the best way to tackle this problem. Thank you.
A: If there is no possibility to let (c) wait for (b), another POST will probably have to do. You can use jQuery's $.post for that. POSTs are quite easy with that. Just be sure to pass an array of your Lons and Lats to it. You may also supply a callback function that will be executed once the POST succeeded.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564772",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to check condition in first class on the string of second class? I want to check the conditon in my first class on the base of second class string.i mean i have a string mystr in second class which contain the value like "sarab".Now i want to use condition in first class that if mystr="anything..".But i am not able to check the condtion.I dont know how to use second class string.Actually i have made one method in second class where i store the string value.Please tell me how i check the value of the string.My second class code is like that:
second.m
(void)mystrmethod
{
mystr=[[NSMutableString alloc]init];
mystr=@"sarab";
NSLog(@" %@ ",mystr);
}
Now i want to check this str in my first class.
Thank you
A: make this string variable global. then u can use this.
A: In your firstclass you need to import the second class like
#import "second.h"
and then you need to make an object of it like
Second *obj=[[Second alloc]init];
and then you can check the string value using
if{ [obj.mystr isEqualToString @"sarab"]}{
//then do something here
}
but all this work only if you define the string first and then compare it ..
hope this helps...
A: Declare your string in the appdelegate file and access it where ever you want using :
appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
if([appDelegate.<yourString> isEqualToString:@"<compareString>"]){
NSLog(@"appDelegate.<yourString> = %@",appDelegate.<yourString>);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564775",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Should I turn this into a module? In my Rails 3.1 app. Ive got a few controller's calling this block of code:
twitter_entertainment_users = Rails.cache.fetch('twitter_entertainment_users', :expires_in => 24.hours) do
begin
Timeout.timeout(10.seconds) do
Twitter.suggestions('entertainment')
puts "#{Twitter.rate_limit_status.remaining_hits.to_s} Twitter API request(s) remaining this hour"
end
rescue Twitter::NotFound
end
end
Instead of re-typing this block of code everywhere. Should I have this in a module instead? i.e. to keep things DRY?
If so, where should this go? I read somewhere about putting module code in app/concerns/foobar.rb.
Any other approach? Looking for suggestions / articles.
A: it's always better not to repeat your code. That way when you change something, you only have to do it in one place. (And believe me - you don't want to do it five times over and then just hope you didn't miss anything.)
Put it somewhere where all the controllers can access it. Consider making a module (or a folder) for all the helper methods you might need and keep them in one place. That way you always know where to look.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564776",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Problems using literals and codeblocks with c# to interact with powershell 2.0 If I try to run a Powershell Command through c# I get the following error:
"The term 'select' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again."
If the Command was executed directly with Powershell(.exe) all works fine!
The command I try to run looks like i.g:
"Get-Mailbox -Organization 'CoolOrganizationNameGoesHere' | select ServerName"
It seems that there is a problem with the "Pipe" |,
I have wasted hours on searching at major search engines with the wildest keyword combinations,
but I've found nothing that works.
The last thing I have tried is setting the PSLanguageMode property of the published IIS-Application for Powershell, The result is still the same as written before.
Maybe there is WinRM wrong configured? Or my local Powershell configuration is corrupted?
Is there any well written documentation on C# (or any other .Net language) using Powershell with remote access
and using the Pipe | "command"?
Can anybody tell me what is wrong, that's like to find the needle in a haystack!
Thanks!
A: Trick could be in the way you create your command. If you are running script as a string, you should use:
Command myCommand = new Command(script, true);
But if you want to run it as a filename - you should use:
Command myCommand = new Command(script, false);
So:
Command myCommand = new Command("Get-Date", true);
Command myCommand = new Command("c:\test.ps1", false);
In case you need full method:
private static IEnumerable<PSObject> ExecutePowerShellScript(string script, bool isScript = false, IEnumerable<KeyValuePair<string, object>> parameters = null)
{
RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
runspace.Open();
Command myCommand = new Command(script, isScript);
if (parameters != null)
{
foreach (var parameter in parameters)
{
myCommand.Parameters.Add(new CommandParameter(parameter.Key, parameter.Value));
}
}
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.Add(myCommand);
var result = pipeline.Invoke();
// Check for errors
if (pipeline.Error.Count > 0)
{
StringBuilder builder = new StringBuilder();
//iterate over Error PipeLine until end
while (!pipeline.Error.EndOfPipeline)
{
//read one PSObject off the pipeline
var value = pipeline.Error.Read() as PSObject;
if (value != null)
{
//get the ErrorRecord
var r = value.BaseObject as ErrorRecord;
if (r != null)
{
//build whatever kind of message your want
builder.AppendLine(r.InvocationInfo.MyCommand.Name + " : " + r.Exception.Message);
builder.AppendLine(r.InvocationInfo.PositionMessage);
builder.AppendLine(string.Format("+ CategoryInfo: {0}", r.CategoryInfo));
builder.AppendLine(string.Format("+ FullyQualifiedErrorId: {0}", r.FullyQualifiedErrorId));
}
}
}
throw new Exception(builder.ToString());
}
return result;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564778",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: model association for a e-store app I'm developing an e-store app using ruby on rails and I'm a bit confused about the model associations. It would help me if someone could give me an idea about the tables and their associations. Here are the details:
Parent tables:
=>Categories,
occasions,
Hot Deals
Under Categories:
=>Men,
Women,
Kids
Under Men:
=>Shirts,
Trousers
Under Women:
=>Shirts,
Trousers,
Skirts
Under Kids:
=>Shirts,
Trousers
Under Occasions
=>Ethnic,
Party,
Travel,
Casual,
Formal
Under Hot Deals
=>Hot Deals Index
And lastly every last sub-table will have product index.
Thank you!
A: What you would generally do with something like this is build a Taxonomy tree to that would be associated with the products, allowing you to group products together. A many to many relation between Taxonomy and Product let's you associate a product with multiple groups, so a T-Shirt might be under Categories > Men > Shirts as well as Occasion > Casual.
# app/models/taxonomy.rb
class Taxonomy < ActiveRecord::Base
has_many :taxonomies
has_and_belongs_to_many :products
end
# app/models/product.rb
class Product < ActiveRecord::Base
has_and_belongs_to_many :taxonomies
end
then a migration for the join table between taxonomy/product
rails g migration create_products_taxonomies
and edit it
def change
create_table(:products_taxonomies, :id => false) do |t|
t.references :product
t.references :taxonomy
end
end
From there you would basically create in the database 3 Taxons, 1 for each of your sections, then create the Taxonomy and build out the sub levels. When you create your products, assign the right Taxonomy to the product and your set.
A seed file might look like...
Taxonomy.create!(:name => "Category").tap do |category|
category.taxonomies.create!(:name => "Men").tap do |men|
men.taxonomies.create!(:name => "Shirt")
men.taxonomies.create!(:name => "Trousers")
end
# and so on for each category
end
Then when you create a Product, you can associate it with the Taxonomy and use that Taxonomy to pull up a list of products that are associated with it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564783",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: linking php pages I have a php page that generates a pdf using mpdf (php to pdf).. So when the users goes to this page the pdf is generated.. I have decided that rather then output the pdf to the browser I will email it to them.. That is all fine and works great.. So at the end of the pdf generating code I put the code for the html page to show.. Like a brand new page.. All works perfectly except for in IE.. where the layout is all messed up.. BUT if I put the html code before the pdf generating code it all looks fine.. and if I put the html in its own page it all looks fine.. Something in the pdf generating code is messing with IE..
So question is.. What about if I link the pdf generating page to the html page..
ie have two pages.. one php page with the html code saying what I want displayed.... and then link to the pdf generating code.. like include("pdfpage.php"); Include won't work, but anything else? Function?
Ideas? Stuck.
Thank you
A: You might try to wrap your PDF generation code up and try to not let it interfere with your HTML page.
A starting point is ob_start(). You can start an output buffer before generating your PDF
. That captures any output your PDF generation code might produce. You can then have a look at it, dispose of it or do whatever you like with it.
That way, no left-overs will be interfering with your HTML page.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564785",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: How to install D.eval() library in flex 4.5 How to install D. eval() library in flex 4.5??
Any help appreciated
A: Close Flex, copy the swc into the libs folder, open flex import the package.
import r1.deval.D;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564789",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Google Analytics and Google Map on Android I am displaying maps in my Android Application. Nowhere in my application I have explicitly invoked www.google-analytics.com, yet I see lots of request going to this website.This is causing my application to be very slow. Also many times I get errors like Unresolved host www.google-analytics.com.
Is it mandatory for the functioning for Google Maps in Android or can we turn this off?
Thanks
A: I guess if Google Maps is using some Google analytics internally, there isnt much that u can do
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564791",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Convert IEnumerable to string[] i have an entity called Product
class Product
{
public Id { get; set; }
public Name { get; set; }
}
and i have a list of all products:
IEnumerable<Product> products = _productRepository.GetAll()
i want to get an array of strings from this list of products this array will contains the product Id + Product Name, so when i try to cast it using the following code:
string[] s = products.Cast<string>().ToArray();
i got the following exception:
Unable to cast object of type 'Product' to type 'System.String'
the exception really makes alot fo scence, so if i had a method
string ProductToString(Product p)
{
return p.Name;
}
or an override to ToString() for the product object so how i can use this method to get the list of string[] from IEnumerable ?
A: Well, given that method you can use1:
string[] s = products.Select<string>(ProductToString).ToArray();
However, it would be more idiomatic to do this without a separate method, usually, using a lambda expression:
// Matches ProductToString, but not your description
string[] s = products.Select(p => p.Name).ToArray();
I'd only use a separate method if it was going to be called from various places (ensuring consistency) or did a lot of work.
EDIT: I've just noticed that your description (wanting ID + name) doesn't actually match the ProductToString method you've given (which just gives the name). For the ID + name I'd use:
string[] s = products.Select(p => p.ID + " " + p.Name).ToArray();
or
string[] s = products.Select(p => string.Format("{0} {1}", p.ID, p.Name))
.ToArray();
Or you could just change your ProductToString method, of course.
Alternatively, you could override ToString() in Product, if this is usually how you want to convert a Product to a string. You could then either use a method group conversion or a lambda expression to call ToString.
1 It's possible that you don't need to specify the type argument explicitly - that:
string[] s = products.Select(ProductToString).ToArray();
will work fine - the rules for type inference and method group conversions always confuse me and the compiler behaviour has changed slightly over time. A quick test just now looks like it does work, but there could be subtleties in slightly different situations.
A: string[] s = products.Select(p => p.Name).ToArray();
Or, if you need Id + Name:
string[] s = products.Select(p => p.Id + ' ' + p.Name).ToArray();
A: use
string[] s = (from p in products select p.Id.ToString() + " " + p.Name.ToString()).ToArray();
A: This worked for me:
String.Join(";", mi_customer.Select(a => a.Id).Cast<string>().ToArray());
Where mi_customer must be your object, in my case is a table.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564792",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: Using Sessions in an ASP.NET 4.0 Log-In Control I'm currently developing a website using Visual Studio 2010. As you all might know, creating a new website here automatically adds an Account folder which contains webpages like Login.aspx, etc. I am implementing this Login.aspx which contains the ASP.NET Login control. It's now functioning the way it should but I have a few concerns.
Before, I used to create my own UI for the log-in so managing sessions is not a problem to me. But since i'm currently using the Login.aspx which has a CS file almost empty, i don't have an idea where I can start implementing my session. Meaning to say, I don't know how to check programatically if the user has been successfully logged in so I can start implementing my session.
I would very much appreciate any pointer regarding this matter.
Thanks in advance. :)
A: You could subscribe for the Authenticate event and perform some custom authentication logic. Also you may take a look at the following article.
A: There are events associate with ASP.NET Login Control that you can use to create session like OnLoggingIn. Moreover you can find more about user validation from here Validating User Credentials Against the Membership
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564803",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Path helpers in a loop I have a Foo that :has_many Bars. GET Foo#index shows all of the Bars. View looks like this:
<% @foos.each do |foo| %>
<% foo.bars.each do |bar| %>
<%= link_to 'Download', download_bar_path %>
<%= link_to 'New', new_bar_path( :foo => foo.id ) %>
<% end %>
<% end %>
There is a def download in Bars controller and a route:
resources :bars do
member do
get 'download'
end
end
rake routes shows
download_bar GET /bars/:id/download(.:format) {:action=>"download", :controller=>"bars"}
and URL /bars/1/download really works, but the first link in the view (download_bar_path) doesn't. It says No route matches {:action=>"download", :controller=>"bars"}.
What can be the problem?
A: <% @foos.each do |foo| %>
<% foo.bars.each do |bar| %>
<%= link_to 'Download', [:download, bar] %>
<%= link_to 'New', [:new, :bar] %>
<% end %>
<% end %>
A: You didn't specified the bar to download, you need to add it by changing this line
<%= link_to 'Download', download_bar_path(bar) %>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564804",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Segmentation Fault when compiling in Red hat but working fine with ubuntu Here is a code that i am executing. its giving the desired output on ubuntu with NASM 2.08 but gives a segmentation fault when compiled with Red Hat 7.3 running NASM 0.98.22
Can someone help me by telling how i can make sure it runs fine on red hat too.
section .data
section .text
global _start
_start:
xor eax,eax
cdq
push eax
push long 0x68732f2f
push long 0x6e69622f
mov ebx,esp
push eax
push eax
mov ecx,esp
mov al,0xb
push eax
int 0x80
A: Your code is 32 bit so when you build it you need to make sure that you build a 32 bit executable. This will happen by default on your 32 bit OS but you probably need a switch like -m32 to achieve this on a 64 bit OS.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564810",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can you suggest a regular expression to capture this text? Please suggest a regular expression to capture this from the input text below:
Match 0:"Modifications made by ... on2011/07/13 06:17:32 from database
keyword: zzzz--> mmmmmm
total_effort: --> 0.00
tmp__effort: --> 0
resolver"
Match 1:"Modifications made by ... on2011/07/13 06:19:32 from database
resolver"
Input text:
Modifications made by... on 2011/06/21 14:09:14 from database
problem_description: (text value has changed)
Modifications made by ... on2011/07/13 06:17:32 from database
keyword: zzzz--> mmmmmm
total_effort: --> 0.00
tmp__effort: --> 0
resolver: y --> x
total_t_effort: --> 0.00
Modifications made by ... on2011/07/13 06:19:32 from database
resolver: x --> z
total_t_effort: --> 0.00
I've tried using this modifications\smade\sby(.|\n)+?resolver but it gives me incorrect output:
Match 0:"Modifications made by... on 2011/06/21 14:09:14 from database
problem_description: (text value has changed)
Modifications made by ... on2011/07/13 06:17:32 from database
keyword: zzzz--> mmmmmm
total_effort: --> 0.00
tmp__effort: --> 0
resolver"
Match 1:"Modifications made by ... on2011/07/13 06:19:32 from database
resolver"
Options used: IgnoreCase + MultiLine
Can anyone help please?
Thanks!
A: If you want to use regex for this it gets a bit more complicated.
Try
^modifications\smade\sby(.(?!modifications))+?resolver
See it here on Regexr
I removed the \n and used the Singleline option instead.
The idea is, match every character till the next "resolver", but only when this character is not followed by "modifications". Therefore I used the negative lookahead .(?!modifications).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564813",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Tab script/code what's a good tab script/code that will work in just about all browsers and wont conflict with jquery scripts. i was think about something like this
http://nontroppo.org/test/tab1.html
its pure css no jscript coding at all. one of that tabs will have an actually image gallery script on it another will have a video player... should I consider something with ajax or will the pure css one shown in the link about be perfect?
A: You may want to check out @ http://jqueryui.com/demos/tabs/ as well, if you need additional handling.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564819",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to check network connectivity in android with out using activity How to check network connectivity in android with out using activity, check it from business object package.
public class DataProviderFactory {
public IDataProvider getDataProvider()
{
//check for the internet connection, if exist
boolean connection_exist=isNetworkAvailable();
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
but its working well in Activities.But I want to check it from the businuss object package, that is inside a class without using activities.
A: Pass a Context into the class and use that to get the SystemService.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564821",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Alternative way to build HTML data for an asynchronous request So there's typically 2 ways I'll return data for an AJAX request. Either as a data set or a ready-to-append DOM element.
1: Data set
echo json_encode(array(
'status'=>200,
'meta' => 'associated info',
'id'=> 123,
'data' => "<div>some stuff to add to the page</div>"
));
2: HTML
<?php function ajaxRequest() { ?>
<div>some stuff to add to the page</div>
<?php } ?>
Is there any way to use a hybrid of these two methods? I doubt it, but can I have the exterior-php html content be embedded into the data set? Rather than it being output, any way for it to be input for a variable?
Basically I'd like to build the HTML without any string building.
Something like this (obviously this wont work):
<?php function ajaxRequest() {
return json_encode(array(
'status'=>200,
'meta'=>'associated_info',
'id'=>123,
'data'=>
?>
<div>some stuff to add to the page</div>
<?php
));
}
?>
So -- is there a way, which I doubt since the content lives outside the php sections, to have this content return into the php?
A: Use ob_start() and ob_get_clean() to wrap your HTML generation in to create a string, like this:
<?php
ob_start();
?>
<div>Stuff</div>
<?php
$var = ob_get_clean();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564823",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Background gradient ends and doesn't continue I have a div under my body element. It has that background CSS:
-moz-linear-gradient(center top , #000000 0%, #30FF40 400px) repeat scroll 0 0 transparent
Inside of my div there is a datatable (a jqGrid table). I think after my page loads that grid table gets a space on my page. So my gradient background ends up somewhere and bottom of my page has a whitespace(other pages doesn't have datatables are OK).
How can I solve that?
EDIT:
My problem is like that:
PS:
I found which causes it. I have a div element that includes my datatable:
<div id="cont">
...
</div>
When I open my webpage it becomes like:
<div id="cont" style="height: 602px;">
...
</div>
I changed the #cont styles to height:auto etc. but something overrides it even I write an inline CSS definition. It has a CSS like:
#cont {
min-height: 100%;
margin: 0 auto;
min-width: 960px;
max-width: 80%;
}
Any ideas?
A: -moz-linear-gradient(center top , #000000 0%, #30FF40 100%) repeat scroll 0 0 transparent
What happens if you remove the 400px limit?
A: Okay, took me a bit to find this, but here's your answer: https://developer.mozilla.org/en/CSS/-moz-linear-gradient. Check out the 'Notes' section. Essentially, it's a "bug" wherein the background won't fill the entire container by default.
Basically, use the edit suggested by @Jonas G. Drange (change the last value to 100%), and then add a new rule to the CSS sheet:
html /*<-- or whatever the container element is */
{
min-height:100%;
}
Viola.
A: Updated my Answer as well :) Some Jquery is applying height to your ID #cont
<style type="text/css">
html, body{ margin:0px; padding:0px; background: #fff; min-width:300px/*480px*/; height:100%;}
.yourClass
{
margin:0; padding:0; display:block; overflow:hidden;
background: #444444; background-repeat:repeat;
background: -moz-linear-gradient(center top, #8db849, #444444);
width:100%; min-height:100%;
}
#cont {
height:320px;/*Assumed height by Jquery / whaterver, you can remove while real time*/
margin: 0 auto;
min-width: 960px;
max-width: 80%;
background:#0099CC;
}
</style>
<div class="yourClass">
<div id="cont">
...
</div>
</div>
It works for me, cheers!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564825",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Insert html code in Android sqlite database I need a little help with an sqlite issue that I have.I'm trying to save json data which i get from the server and I get an exception trying to insert html code into the sqlite database.Here is the code I am usig for it and the exception :
CODE:
public boolean executeInsert() {
UserDatabaseHelper userDbHelper = new UserDatabaseHelper(context, null, 1);
userDbHelper.initialize(context);
ContentValues values = new ContentValues();
try {
values.put("objectId", objectId);
values.put("objectOid", objectOid);
String jsonData = new String(contentBuffer,"UTF-8");
Log.w("JSONDATA","JSONDATA VALID OR NOT : "+jsonData);
json = new JSONObject(jsonData);
JSONObject jsonObj =(JSONObject) new JSONTokener(jsonData).nextValue();
locale = jsonObj.getString("locale");
Log.w("LOCALE","SHOW LOCALE : "+locale);
contentType = Integer.parseInt(jsonObj.getString("content_type"));
Log.w("CONTENT TYPE","SHOW CONTENT TYPE : "+contentType);
values.put("contentType", contentType);
format = Integer.parseInt(jsonObj.getString("format"));
Log.w("FORMAT","SHOW FORMAT : "+format);
values.put("format", format);
title = jsonObj.getString("title");
Log.w("TITLE","SHOW TITLE : "+title);
values.put("title", title);
content = jsonObj.getString("content");
Log.w("CONTENT","SHOW CONTENT : "+content);
values.put("content", content);
lastUpdate = jsonObj.getString("last_updated");
Log.w("LAST UPDATED","LAST UPDATED : "+lastUpdate);
values.put("dateUpdated", lastUpdate);
collectionId = jsonObj.optInt("collection_id", 0);
values.put("collectionId", collectionId);
cardId = jsonObj.optInt("card_id", 0);
values.put("cardId", cardId);
userDbHelper.executeQuery("content", values);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
Log.w("Error","FUCKKKKKKKKKKKKKK ERROR : "+e);
} catch (JSONException e) {
e.printStackTrace();
Log.w("Error","FUCKKKKKKKKKKKKKK ERROR : "+e);
}
return true;
}
EXCEPTION:
09-27 08:48:52.279: ERROR/Database(7862): Error inserting content=Welcome to Stampii<br />
09-27 08:48:52.279: ERROR/Database(7862): <br />
09-27 08:48:52.279: ERROR/Database(7862): Your favourite collections synchronised on your computer and your mobile in a new format: stampii Download them with photos, and constantly updated statistics. Swap and play with your friends and enjoy their contents even when you're offline!<br />
09-27 08:48:52.279: ERROR/Database(7862): <br />
09-27 08:48:52.279: ERROR/Database(7862): From theArea in the Kiosk, you'll be able to browse through all tha active collections, and find the one that you like best.<br />
09-27 08:48:52.279: ERROR/Database(7862): <br />
09-27 08:48:52.279: ERROR/Database(7862): Once you've selected the choosed collection, you just have to activate it to start enjoying your. You can make as many collections as you want at the same time.<br />
09-27 08:48:52.279: ERROR/Database(7862): <br />
09-27 08:48:52.279: ERROR/Database(7862): You can purchase yourfrom theStore, via sms or promotional vouchers.<br />
09-27 08:48:52.279: ERROR/Database(7862): <br />
09-27 08:48:52.279: ERROR/Database(7862): Allfollow a similar structure. They're all represented with a portrait with an image and all the data referred to the character that you've got in your.<br />
09-27 08:48:52.279: ERROR/Database(7862): <br />
09-27 08:48:52.279: ERROR/Database(7862): Your collection will be updated for free with the last info every time you select the sincronize button. Yourconstantly updated.<br />
09-27 08:48:52.279: ERROR/Database(7862): <br />
09-27 08:48:52.279: ERROR/Database(7862): Enjoy searching, negotiating and changing your repeated stampii with your friends, use your mobile and the social networks to get the you were looking for. title=Title Tutorial format=2 contentType=1 objectId=1 dateUpdated=2010-03-26 16:56:43
09-27 08:48:52.279: ERROR/Database(7862): android.database.sqlite.SQLiteConstraintException: error code 19: constraint failed
09-27 08:48:52.279: ERROR/Database(7862): at android.database.sqlite.SQLiteStatement.native_execute(Native Method)
09-27 08:48:52.279: ERROR/Database(7862): at android.database.sqlite.SQLiteStatement.execute(SQLiteStatement.java:55)
09-27 08:48:52.279: ERROR/Database(7862): at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1623)
09-27 08:48:52.279: ERROR/Database(7862): at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1484)
09-27 08:48:52.279: ERROR/Database(7862): at com.stampii.stampii.comm.rpc.UserDatabaseHelper.execQuery(UserDatabaseHelper.java:252)
09-27 08:48:52.279: ERROR/Database(7862): at com.stampii.stampii.comm.rpc.UserDatabaseHelper.executeQuery(UserDatabaseHelper.java:247)
09-27 08:48:52.279: ERROR/Database(7862): at com.stampii.stampii.comm.rpc.ContentRPCPacket.executeBefore(ContentRPCPacket.java:105)
09-27 08:48:52.279: ERROR/Database(7862): at com.stampii.stampii.user.UserLogin$2$1.run(UserLogin.java:365)
09-27 08:48:52.279: ERROR/Database(7862): at java.lang.Thread.run(Thread.java:1102)
EDIT
Here is my function about which I am using for inserting data in SQLite :
public boolean executeQuery(String tableName,ContentValues values){
return execQuery(tableName,values);
}
private boolean execQuery(String tableName,ContentValues values){
sqliteDb = instance.getWritableDatabase();
sqliteDb.insert(tableName, null, values);
return true;
}
I am using this method like this :
userDbHelper.executeQuery("content", values);//content is the name of my table
//userDBHelper is an instance of my DatabaseHelper class.
And what type of data I have on my table :
*
*id (integer)
*objectId (integer)
*format (integer)
*contentType (integer)
*dateUpdated (varchar)
*content (Text)
*objectOid (varchar)
Any ideas how to fix that so I can save the html code in sqlite?
A: Try to simplify your code until you get it working. Firstly, replace the line:
content = jsonObj.getString("content");
With the line:
content = "somethingsimple";
If that works, then you know it's something about the content string.
Do you know the max size of that column?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564829",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to bypass Access-Control-Allow-Origin? I'm doing a ajax call to my own server on a platform which they set prevent these ajax calls (but I need it to fetch the data from my server to display retrieved data from my server's database).
My ajax script is working , it can send the data over to my server's php script to allow it to process.
However it cannot get the processed data back as it is blocked by "Access-Control-Allow-Origin"
I have no access to that platform's source/core. so I can't remove the script that it disallowing me to do so.
(P/S I used Google Chrome's Console and found out this error)
The Ajax code as shown below:
$.ajax({
type: "GET",
url: "http://example.com/retrieve.php",
data: "id=" + id + "&url=" + url,
dataType: 'json',
cache: false,
success: function(data)
{
var friend = data[1];
var blog = data[2];
$('#user').html("<b>Friends: </b>"+friend+"<b><br> Blogs: </b>"+blog);
}
});
or is there a JSON equivalent code to the ajax script above ? I think JSON is allowed.
I hope someone could help me out.
A: I have fixed this problem when calling a MVC3 Controller.
I added:
Response.AddHeader("Access-Control-Allow-Origin", "*");
before my
return Json(model, JsonRequestBehavior.AllowGet);
And also my $.ajax was complaining that it does not accept Content-type header in my ajax call, so I commented it out as I know its JSON being passed to the Action.
Hope that helps.
A: Warning, Chrome (and other browsers) will complain that multiple ACAO headers are set if you follow some of the other answers.
The error will be something like XMLHttpRequest cannot load ____. The 'Access-Control-Allow-Origin' header contains multiple values '____, ____, ____', but only one is allowed. Origin '____' is therefore not allowed access.
Try this:
$http_origin = $_SERVER['HTTP_ORIGIN'];
$allowed_domains = array(
'http://domain1.com',
'http://domain2.com',
);
if (in_array($http_origin, $allowed_domains))
{
header("Access-Control-Allow-Origin: $http_origin");
}
A: Put this on top of retrieve.php:
header('Access-Control-Allow-Origin: *');
Note that this effectively disables CORS protection, and leaves your users exposed to attack. If you're not completely certain that you need to allow all origins, you should lock this down to a more specific origin:
header('Access-Control-Allow-Origin: https://www.example.com');
Please refer to following stack answer for better understanding of Access-Control-Allow-Origin
https://stackoverflow.com/a/10636765/413670
A: It's a really bad idea to use *, which leaves you wide open to cross site scripting. You basically want your own domain all of the time, scoped to your current SSL settings, and optionally additional domains. You also want them all to be sent as one header. The following will always authorize your own domain in the same SSL scope as the current page, and can optionally also include any number of additional domains. It will send them all as one header, and overwrite the previous one(s) if something else already sent them to avoid any chance of the browser grumbling about multiple access control headers being sent.
class CorsAccessControl
{
private $allowed = array();
/**
* Always adds your own domain with the current ssl settings.
*/
public function __construct()
{
// Add your own domain, with respect to the current SSL settings.
$this->allowed[] = 'http'
. ( ( array_key_exists( 'HTTPS', $_SERVER )
&& $_SERVER['HTTPS']
&& strtolower( $_SERVER['HTTPS'] ) !== 'off' )
? 's'
: null )
. '://' . $_SERVER['HTTP_HOST'];
}
/**
* Optionally add additional domains. Each is only added one time.
*/
public function add($domain)
{
if ( !in_array( $domain, $this->allowed )
{
$this->allowed[] = $domain;
}
/**
* Send 'em all as one header so no browsers grumble about it.
*/
public function send()
{
$domains = implode( ', ', $this->allowed );
header( 'Access-Control-Allow-Origin: ' . $domains, true ); // We want to send them all as one shot, so replace should be true here.
}
}
Usage:
$cors = new CorsAccessControl();
// If you are only authorizing your own domain:
$cors->send();
// If you are authorizing multiple domains:
foreach ($domains as $domain)
{
$cors->add($domain);
}
$cors->send();
You get the idea.
A: Have you tried actually adding the Access-Control-Allow-Origin header to the response sent from your server? Like, Access-Control-Allow-Origin: *?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564832",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "234"
}
|
Q: how do I write a `is_a_last_of_b(a, b)` to check whether `a` is the last child of `b` a = $('div:first');
b = $('div');
b may contain multiple DOM elements.
But a only contains 1 element.
How do I know if a is the last element of b?
I tried a == $('div:last'),but it's wrong after my test.
And if a is an element of b, how do I get the sibling of a within b?
Clarify
the problem is how I can write a is_a_last_of_b(a, b) to check whether a is the last child of b.
And if a is a direct child of b,how to write next_sibling(a) to return the next sibling of a(only one)?
A: Can try this
var elements = $("div");
var lastElement = elements.filter(":last");
var firstElement = elements.filter(":first");
For sibling check this out jquery siblings
A: Maybe you need last-selector and siblings?
A: Ok, to compare jquery objects, you can look at some other questions on SO like this one: jQuery object equality
Essentially, in your case where you only want to check for one item you could do this:
var a = $("div:first"),
b = $("div");
if (b[b.length - 1] === a[0]) {}
// or
if (b.last()[0] = a[0]) {}
Then, to get the next sibling of an element:
b = b.next();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564838",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: Concept of git tracking and git staging When you modify a file in your working directory, git tells you to use "git add" to stage.
When you add a new file to your working directory, git tells you to use "git add" to start tracking.
I am a bit confused about these 2 concepts because i assumed tracking a file for changes is different from staging it for commit
A: Git essentially has 4 main statuses for the files in your local repo:
*
*untracked: The file is new, Git knows nothing about it. If you git add <file>, it becomes:
*staged: Now Git knows the file (tracked), but also made it part of the next commit batch (called the index). If you git commit, it becomes:
*unchanged: The file has not changed since its last commit. If you modify it, it becomes:
*unstaged: Modified but not part of the next commit yet. You can stage it again with git add
As you can see, a git add will track untracked files, and stage any file.
Also: You can untrack an uncommited file with git rm --cached filename and unstage a staged file with git reset HEAD <file>
A: Git has a concept known as 'the index'. To create a new commit, you fill the index with the contents you'd like to have in the next commit. That means that you have to explicitly tell Git which changes you want to appear in the next commit by using git add. (git add -p to add only single hunks)
It doesn't make a difference to Git whether you only update a file (»stage changes«) or if you add the full content of a new file (»start tracking a file«) – both times, all that Git's index sees is the addition of new changes
A: When you add a file to start tracking, it also stages its contents.
If you want to add a file for tracking without staging it, you can use
git add -N
A: Both of the git add steps you identify do essentially the same thing, they simply have different explanations because of their arrival route.
The git add simply tells git that the file provided is a file that you desire to have, in its exact current form (its content), within its source control repository. At that point git will take a snapshot of the file (and it keeps a note in its index) so that it is ready for when you have all your changes to your files ready and added (i.e marshalled together in the staging area), for your git commit (with appropriate message ;-).
Once git has been told about that file (e.g. @avh's -N option) it will notice (track) changes to the file under the guise of various commands (such as git status). Thus, later, you have to explicitly tell git when you no longer want a file to be tracked (git rm <file>), and you can continue editing a file (locally) after you have added the version that will be in the commit. Almost obviously (or perhaps not), you can git add a file many times before you commit the final version.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564841",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "29"
}
|
Q: ListView vs Nested Layout [Pros/Cons] I'm working on an android application and I have run into a decision that I can't decide on one way or another. I was hoping someone could shed some light on the common practices and any theory to back them.
Here's the issue:
I want to have a list of items with images and text like table...
Country -.-.-.-.-.-.- Pop -.- SqrMi
[img] US -.-.-.-.-.-.- xxx -.-.- xxxxx
Now the debate I'm having is whether or not to use a listview to display the data or instead nest a layout that is scrollable and just display the data that way.
Why would I even consider a nested layout? Flexibility. I can design the dividers, possibly throw in a couple graphs above/below the list. Vary the height of each of the list items (like what if I want to show a graph in one list item and no graph in the next), etc.
I'm not sure if I'm breaking the generally accepted methods here. Can anyone shed some light on this?
A: The only major problem you will have when using nested layouts is memory consumption. ListView reuses its children so it doesn't create more children then it can display at a single moment. This description is a little simplified but I hope it shows the purpose of the ListView. Also ListView implements its own fast scrolling so it doesn't have to measure all its children to determine its size. And ListViews use adapters to populate themselves with data. It's a nice and convenient way to obtain data.
On the other hand if you create a ScrollView with a lot of views inside it'll be slow, difficult to populate with data and it'll require a lot of memory to create all of the child views even if you don't ever see some of them.
And about flexibility of the ListView. You can store different types of view in a single ListView and you'll be able to vary the height of each of this views.
A: All the things you have described for your "nested layout" is achievable with ListView. Just use different types of rows, use headers/footers in adapter.
And as already Pixie said, ListView is much more memory efficient and faster.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564846",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: JScrollPane not resizing when added to JPanel I cant get the scrollPane to resize correctly when added to the scrollPanel. I want the scrollPane to scale to the size of the scrollPanel. Any tips?
public class MTabbedPane_HomePanel extends JPanel {
private JPanel scrollPanel;
private JScrollPane scrollPane;
public MTabbedPane_HomePanel()
{
init();
makePanel();
}
private void init() {
scrollPanel = new JPanel();
scrollPane = new JScrollPane(scrollPanel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
}
private void makePanel() {
IAppWidgetFactory.makeIAppScrollPane(scrollPane);
setLayout(new BorderLayout());
scrollPane.setBorder(null);
add(scrollPane, BorderLayout.CENTER);
}
}
A: your code is correct, maybe
*
*try to disable UIDelegate from IAppWidgetFactory.makeIAppScrollPane(), if remains unchanged
then
*
*check how you added (if is used LayoutManager) for MTabbedPane_HomePanel to the parent
A: Call setPreferredSIze() for the panel.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564847",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to draw outline in selected tableviewcell in iphone I want to outline Uitableview's selected cell
can anyone tell me how to do this ?
searched but nothing worked till now :(
should I do anything in rowdidselect method?
A: Try setting the allowsSelectionDuringEditing property on the UITableView to YES - the default is NO
For More
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[self doSomethingWithRowAtIndexPath:indexPath];
}
What I understand from your question is u want to change the look off the selected cell...
On didSelectRowAtIndexPath Event you have the index off that row by that index draw a New CELL off your desire.
A: You can create a custom uiview and override the drawrect method so that it will create border lines across the given rect. Add this view to the cell.contentview when didSelectrow method is getting invoked.
A: I think you need to subclass your UITableViewCell. Then in the drawRect method you can draw that.
- (void) drawRect : (CGRect)rect
{
[super drawRect:rect];
if (self.selected)
{
// put one image as outline
}
}
I hope this might help you.
Naveen
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564849",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to filter nsdictionary? I want to search data from nsdictionary based on different criteria.Say I have 4 keys and user can search based on any number of keys ex:4,3 etc..Ex:I have dictionary containing keys(First Name,Last Name,Address,Phone Number).Now user can search based on any key say First Name and Last Name, or only First Name.I am using NSPredicate to search.My problem is how to create dynamic nspredicate?If I provide empty string in
[NSPredicate predicateWithFormat:@"FirstName CONTAINS[cd] %@ AND LastNAme CONTAINS[cd] %@ AND Address CONTAINS[cd] %@ AND PhoneNumber CONTAINS[cd] %@",firstname,lastname,addr,phone]
It does not give any result.How can I achieve this?or I have to create multiple nspredicate based on fields user has provide?
Thanks in advance!
A: You can build the predicate programmatically:
NSArray *keysToSearch = [NSArray arrayWithObjects:@"FirstName", @"LastName", @"Address", nil];
NSString *searchString = @"Bob";
NSMutableArray *subPredicates = [NSMutableArray array];
for (NSString *key in keysToSearch) {
NSPredicate *p = [NSPredicate predicateWithFormat:@"%K contains[cd] %@", key, searchString];
[subPredicates addObject:];
}
NSPredicate *filter = [NSCompoundPredicate andPredicateWithSubPredicates:subPredicates];
Then use filter to filter your dictionaries.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564850",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Three tables join in SQL I am newbie in SQL. I want to join three tables in SQL. Below is my query, please check and correct me where I am wrong -
Tables:
*
*CARD: ID,Code,Name,CC
*PGM: ID,Code
*PGMeCode: ID,Code,CC
Query:
Select *
FROM CARD
INNER JOIN PGMeCode PGMeCode.Code = CARD.Code AND PGMeCode.CC = CARD.CC
INNER JOIN PGM PGM.Code = Card.Code
WHERE Card.ID = 'SomeThing'
I don't know what I am doing wrong. Please suggest me!!
Thanks in advance.
A: You are missing the keyword ON, placed after the table name.
INNER JOIN tablename ON condition...
A: SELECT * FROM CARD INNER JOIN PGMeCode ON PGMeCode.Code = CARD.Code AND PGMeCode.CC = CARD.CC INNER JOIN PGM ON PGM.Code = Card.Code WHERE Card.ID = 'SomeThing';
Try this query
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564863",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: android number format for germany is there a public algorithm that formats German phone numbers (mobile and landlines)? I saw there is a method to format phone numbers PhoneNumberUtils.getFormatTypeForLocale(Locale locale) but this is only for NANP countries, see here.
A: Maybe libphonenumber can do what you want?
A: Like most android documentation PhoneNumberUtils very poorly created. Try Locale.GERMANY as method input. If the locale format is unavaible like you mentioned, you have to write your own method. Maybe extending PhoneNumberUtils and overriding that method is a good practice. Good luck anyway :).
Edit: aspartame's answer seems more logical to me.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564865",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Public event of base class in derived class I have a base-class (let it be SomeBaseClass) containing a public event (SomeEvent) and I have a derived-class in which I want to raise this event but I can't(!!) VS 2010 says me (in derived-class in line: base.SomeEvent != null) "The event 'SomeBaseClass.SomeEvent' can only appear on the left hand side of += or -=". If I replace base on this It is make no sense.
A: No, it's absolutely right - the event is only an event (with subscription and unsubscription) as far as a derived class is concerned. If your base class wants to let derived classes raise the event, it should include a protected method to do so (typically a virtual OnFoo(EventHandler) for an event called Foo with the EventHandler type, for example). Note that if you write a field-like event in C# like this:
public event EventHandler Foo;
That's actually declaring a private field called Foo (which that class and any nested classes have access to) and a public event (which consists only of subscribe/unsubscribe). You could declare your own "custom" event like this:
protected EventHandler foo;
// Note: not thread-safe. Only present for demonstration purposes.
public event EventHandler Foo
{
add { foo += value; }
remove { foo -= value; }
}
and then derived classes would have access to the field... but I wouldn't recommend that. (I rarely declare non-private fields, other than for constants.)
A: You need to do it the right way (i.e., the idiomatic way in C#)
public class Base {
public event EventHandler<EventArgs> SomeEvent;
protected virtual void OnSomeEvent(EventArgs e) {
EventHandler<EventArgs> handler = SomeEvent;
if (handler != null) {
handler(this, e);
}
}
}
public class Derived {
protected virtual void OnSomeEvent(EventArgs e) {
// derived event handling here
// then invoke the base handler
base.OnSomeEvent(e);
}
}
The reason that you do it like this is because events can only be invoked from within the defining class.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564872",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: windows service development c# I'm devloping one application which manages our custom made windows service. I'm using ServiceController object to get all services, but after that how I will differentiate which is our custom service and which is system service?
I am using following code:
ListViewItem datalist;
services = ServiceController.GetServices();
ServiceList.Items.Clear();
foreach(ServiceController service in services)
{
datalist = new System.Windows.Forms.ListViewItem(service.ServiceName.ToString());
datalist.SubItems.Add(service.DisplayName);
datalist.SubItems.Add(service.Status.ToString());
ServiceList.Items.Add(datalist);
}
A: Put the name of your services in app.config. And read those when your application is started.
You can use http://csd.codeplex.com/ to create a custom configuration section.
A: You can put settings in .exe.config to each of your services
and observe them like this
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Management;
class Program
{
static void Main(string[] args)
{
var searcher =
new ManagementObjectSearcher("SELECT * FROM Win32_Service WHERE Started=1 AND StartMode=\"Auto\"");
foreach (ManagementObject service in searcher.Get())
{
foreach (var prop in service.Properties)
{
if (prop.Name != "PathName" || prop.Value == null)
continue;
var cmdLine = prop.Value.ToString();
var path = cmdLine.SplitCommandLine().ToArray()[0] + ".config";
if (File.Exists(path))
{
var serviceConfig = ConfigurationManager.OpenExeConfiguration(path);
/***/
}
break;
}
}
}
}
SplitCommand
static class SplitCommand
{
public static IEnumerable<string> Split(this string str, Func<char, bool> controller)
{
int nextPiece = 0; for (int c = 0; c < str.Length; c++)
{
if (controller(str[c]))
{ yield return str.Substring(nextPiece, c - nextPiece); nextPiece = c + 1; }
} yield return str.Substring(nextPiece);
}
public static IEnumerable<string> SplitCommandLine(this string commandLine)
{
bool inQuotes = false;
return commandLine.Split(c =>
{
if (c == '\"')
inQuotes = !inQuotes; return !inQuotes && c == ' ';
}).Select(arg => arg.Trim().TrimMatchingQuotes('\"')).Where(arg => !string.IsNullOrEmpty(arg));
}
public static string TrimMatchingQuotes(this string input, char quote)
{
if ((input.Length >= 2) && (input[0] == quote) && (input[input.Length - 1] == quote))
return input.Substring(1, input.Length - 2);
return input;
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564873",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: creating jar file for application which in turn contains external jar file Hie all ,
I want to create an jar file for a java application, and i am able create the jar file for it properly.i followed the below link to create the jar file .enter link description here
But the problem what i am facing is that in my application i added the external jar's like jna.jar , platform.jar and vlcj-1.2.0-javadoc.jar files to run my application successful. This application will run fine when i run in eclipse , but when i create the far file for the same application I'm getting the error like
No class defination found error.
jna native library missing.
so please will you tell me what is the actual problem and how do I solve it . and one more thing while creating the jar file I enabled the option "Export java source files and resources".
thanks in advance
Datta
A: You have to supply full class path when you are running your application, i.e. something like:
java -cp myapp.jar;jna.jar;platform.jar com.mycompany.MyMain
If you are using -jar option you should put all third party libraries to manifest.mf packaged into your jar under META-INF, i.e. add line like:
Class-Path: jna.jar platform.jar
to you manifest.
Pay attenition that you should use ; for windows command line, : for unix command line and space when writing class path in manifest.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564874",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Address of a class member function I have a class called CSum which contains a static method who's identifier is:
static double fileProc(string myFile);
In my main function I would simply call it by
CSum::fileproc("foo.txt")
However, I will like to invoke pthreads on two separate files. Therefore I need to obtain the address of this method. I do so by
return1 = pthread_create(&t1, NULL, &CSum::fileProc(file1), NULL);
return2 = pthread_create(&t2, NULL, &CSum::fileProc(file2), NULL);
But I get an error
lvalue required as a unary '&' operand.
Any suggestions?
A: You don't pass parameters, you just give the name of the function. The parameter you want it to get is the next parameter of the pthread_create.
Instead of
pthread_create(&t2, NULL, &CSum::fileProc(file2), NULL);
do
pthread_create(&t2, NULL, &CSum::fileProc, file2);
Cast types as appropriate. Note that the thread function is supposed to accept a pointer as a parameter, make sure you define it appropriately.
A: CSum::fileProc(file1) is an expression that calls the function and gives you the value the function returns as the value of the expression. You are trying to take the address of that value, which you can't, and this won't do what you want.
&CSum::fileProc will give you the function pointer, but it does not have the correct signature for use with pthreads. Since pthreads is a C library, it has a very simplistic interface. Your best bet for C++ is to use a higher-level C++ library that uses pthreads underneath (at least on unixes), like boost threads.
If for some reason yoou can't do that, you need to write your own wrappers. To call your function in a separate thread, you would need to write something like:
class CSum {
...
static void fileProcWrapper(void* param) {
const char* fileName = (const char*) param;
fileProc(fileName);
}
...
and call it with
pthread_create((&t2, NULL, &CSum::fileProc, (void*) file1.c_str());
That just gives you the call, mind, the result is thrown away with this code. If you want to collect the result with pthread_join, you have to do a bit more work.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564877",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Passing a dictionary as a function parameter and calling the function in Python In the following code, how do I pass the dictionary to func2. How should func2 be called?
def func2(a,**c):
if len(c) > 0:
print len(c)
print c
u={'a':1,'b':2}
func2(1,u)
A: Just as it accepts them:
func2(1,**u)
A: This won't run, because there are multiple parameters for the name a.
But if you change it to:
def func2(x,**c):
if len(c) > 0:
print len(c)
print c
Then you call it as:
func2(1, a=1, b=2)
or
u={'a':1,'b':2}
func2(1, **u)
A: This might help you:
def fun(*a, **kw):
print a, kw
a=[1,2,3]
b=dict(a=1, b=2, c=3)
fun(*a)
fun(**kw)
fun(*a, **kw)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564883",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Ping against IE - request timed out Where to look what could be a cause that "ping IP_address" returns "Request timed out", but opening "http://IP_address" in the Internet Explorer loads site correctly?
And in real impication: .NET making WebRequest to that IP works correctly on my machine, but does not work on clietn's.
I think there should be something with proxy, but not sure what should be done.
The .NET code is below:
WebRequest request = WebRequest.Create("http://tycho.usno.navy.mil/cgi-bin/timer.pl");
WebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultCredentials;
request.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
request.Proxy = WebRequest.DefaultWebProxy;
WebResponse response = request.GetResponse();
A: Some servers block ping requests.
A: Some servers/ firewall/ gateway will block PING ( ICMP Request ), resulting in Request Timed Out; while loading a web page uses port 80 ( in most cases ), which is different than ICMP port .
UPDATE: According to your information given, you mentioned your codes WORK during debugging but does not work in a "Release" EXE, right? By default, during debugging session, the program bypasses most security settings.
Also, check Windows Firewall settings. Try disabling the Windows Firewall on client side & retry. If Windows Firewall is the culprit, add your program to Windows Firewall "Allowed Program" list and re-enable the Firewall.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564884",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Write to different files using hadoop streaming I'm currently processing about 300 GB of log files on a 10 servers hadoop cluster. My data is being saved in folders named YYMMDD so each day can be accessed quickly.
My problem is that I just found out today that the timestamps I have in my log files are in DST (GMT -0400) instead of UTC as expected. In short, this means that logs/20110926/*.log.lzo contains elements from 2011-09-26 04:00 to 2011-09-27 20:00 and it's pretty much ruining any map/reduce done on that data (i.e. generating statistics).
Is there a way to do a map/reduce job to re-split every log files correctly? From what I can tell, there doesn't seem to be a way using streaming to send certain records in output file A and the rest of the records in output file B.
Here is the command I currently use:
/opt/hadoop/bin/hadoop jar /opt/hadoop/contrib/streaming/hadoop-streaming-0.20.2-cdh3u1.jar \
-D mapred.reduce.tasks=15 -D mapred.output.compress=true \
-D mapred.output.compression.codec=com.hadoop.compression.lzo.LzopCodec \
-mapper map-ppi.php -reducer reduce-ppi.php \
-inputformat com.hadoop.mapred.DeprecatedLzoTextInputFormat \
-file map-ppi.php -file reduce-ppi.php \
-input "logs/20110922/*.lzo" -output "logs-processed/20110922/"
I don't know anything about java and/or creating custom classes. I did try the code posted at http://blog.aggregateknowledge.com/2011/08/30/custom-inputoutput-formats-in-hadoop-streaming/ (pretty much copy/pasted what was on there) but I couldn't get it to work at all. No matter what I tried, I would get a "-outputformat : class not found" error.
Thank you very much for your time and help :).
A:
From what I can tell, there doesn't seem to be a way using streaming to send certain records in output file A and the rest of the records in output file B.
By using a custom Partitioner, you can specify which key goes to which reducer. By default the HashPartitioner is used. Looks like the only other Partitioner Streaming supports is KeyFieldBasedPartitioner.
You can find more details about the KeyFieldBasedPartitioner in the context of Streaming here. You need not know Java to configure the KeyFieldBasedPartitioner with Streaming.
Is there a way to do a map/reduce job to re-split every log files correctly?
You should be able to write a MR job to re-split the files, but I think Partitioner should solve the problem.
A: A custom MultipleOutputFormat and Partitioner seems like the correct way split your data by day.
As the author of that post, sorry that you had such a rough time. It sounds like if you were getting a "class not found" error, there was some issue with your custom output format not being found after you included it with "-libjars".
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564886",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: In great need of help on finishing python program The "Component" argument for addCompnent() method is an instance of the component class. In short, Component has 2 arguments; "Component(self,name,methodCount)" As you see in my code, I added each Component to a list. What I need to do in validCount() is return the number of components where the methodCount != 0. From what I currently have my validCount() keeps returning 4 and I have no idea why. I have debugged it and still not seeing where 4 is coming from; especially when I initialize it to 0. Can you please point out what I am doing wrong? I have tried counting the Components that have 0 methodCounts and with none 0 methodCounts, but the numbers are not returning correctly either way. There are three classes in the whole program but here is just the one I'm having troubles with. (If needed I can post full cod):
class Effort(Component):
addedComponents = []
componentCounter = 0
validCounter = 0
def __init__ (self):
return None
def addComponent(self, Component):
try:
if (self.addedComponents.count(Component) != 0):
raise ValueError
else:
self.addedComponents.append(Component)
self.componentCounter = self.componentCounter + 1
return self.componentCounter
except ValueError:
raise ValueError("Duplicate component")
def count(self):
return self.componentCounter
def validCount(self):
if (len(self.addedComponents) == 0):
return self.validCounter
else:
for i in self.addedComponents:
if (i.getMethodCount() == 0):
pass
else:
self.validCounter = self.validCounter + 1
return self.validCounter
A: A few comments.
*
*Comment your code. Especially when you have mistakes, discerning what your code is supposed to do can be difficult for outsiders.
*It's bad form to capitalize the "Component" argument to addComponent. Use capital letters for class names, lower case for parameter names. This code reads like you are trying to add the class type to the addedComponents, not an instance of the class.
*Is validCounter supposed to be a class variable for Effort or an instance variable? If it's an instance variable, put its initialization in your init. If it's a class variable, refer to it as Effort.validCounter, not self.validCounter. Same for addedComponents and componentCounter.
*Is validCount supposed to increment every call or return the number of addedComponents with methods? Assuming the latter, you don't need an instance variable. Either way, you probably want to re-initialize validCounter to 0 before your for loop.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564888",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Slideshow using jquery I have a slideshow created by jQuery which slides from left to right by default. There is a next button which on click should slide the images from left to right and while clicking the previous button the images should slide from right to left.
Currently I have a code like :
jQuery('.slider').cycle({
fx: 'scrollRight',
speed: 1000,
timeout:5000,
next: '.next',
prev: '.prev'
});
Now it slides from right to left by default and on clicking the next button as required, but
it has to move from left to right on previous button clicking which is not happening..
I will be really thankfull if any body can help in this matter..
EDIT:
here is the html code:
<div class="slider ddblock-processed" style="position: relative; width: 990px; height: 396px; visibility: visible; overflow-x: hidden; overflow-y: hidden; ">
<div class="slide" style="position: absolute; top: 0px; opacity: 1; width: 990px; height: 396px; z-index: 4; left: 990px; display: none; "><img src="http://files/images/ddblock/mobile-apps.png" alt="image" style="height: 392px; width: 990px; " class="ddblock-processed"></div>
<div class="slide" style="position: absolute; top: 0px; opacity: 1; width: 990px; height: 396px; z-index: 4; left: 990px; display: none; "><img src="http://files/images/ddblock/seo.png" alt="image" style="height: 392px; width: 990px; " class="ddblock-processed"></div>
<div class="slide" style="position: absolute; z-index: 5; top: 0px; opacity: 1; display: block; width: 990px; height: 396px; left: 0px; "><img src="http://files/images/ddblock/web-applications.png" alt="image" style="height: 392px; width: 990px; " class="ddblock-processed"></div>
<div class="slide" style="position: absolute; top: 0px; opacity: 1; width: 990px; height: 396px; z-index: 4; left: 990px; display: none; "><img src="http://files/images/ddblock/webdesign.png" alt="image" style="height: 392px; width: 990px; " class="ddblock-processed"></div>
</div>
<!-- prev/next pager on slide -->
<div class="pager-slide prev-container prev-container-top">
<a class="prev" href="#"></a>
</div>
<div class="pager-slide next-container next-container-top">
<a class="next" href="#"></a>
</div>
A: Try using HTML5Slides, a free solution provided by Google.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564890",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Xml / Newtonsoft Json Object Seralization in wp7 Mango By using Newtonsoft json serializer and xml Serrializer how can i serialize and deserialize objects. Pls send me the method to acheve the same.
A: Your question is not 100% clear, you might want to elaborate.
You can deserialize an object to/from JSON using JsonConvert:
ObjectToDeserialize value =
JsonConvert.DeserializeObject<ObjectToDeserialize>(jsonString);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564894",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Python equivalent to C strtod I am working on converting parts of a C++ program to Python, but I have some trouble replacing the C function strtod.
The strings I'm working on consists of simple mathmatical-ish equations, such as "KM/1000.0". The problem is that the both constants and numbers are mixed and I'm therefore unable to use float().
How can a Python function be written to simulate strtod which returns both the converted number and the position of the next character?
A: I'm not aware of any existing functions that would do that.
However, it's pretty easy to write one using regular expressions:
import re
# returns (float,endpos)
def strtod(s, pos):
m = re.match(r'[+-]?\d*[.]?\d*(?:[eE][+-]?\d+)?', s[pos:])
if m.group(0) == '': raise ValueError('bad float: %s' % s[pos:])
return float(m.group(0)), pos + m.end()
print strtod('(a+2.0)/1e-1', 3)
print strtod('(a+2.0)/1e-1', 8)
A better overall approach might be to build a lexical scanner that would tokenize the expression first, and then work with a sequence of tokens rather than directly with the string (or indeed go the whole hog and build a yacc-style parser).
A: You can create a simple C strtod wrapper:
#include <stdlib.h>
double strtod_wrap(const char *nptr, char **endptr)
{
return strtod(nptr, endptr);
}
compile with:
gcc -fPIC -shared -o libstrtod.dll strtod.c
(if you're using Python 64 bit, the compiler must be 64-bit as well)
and call it using ctypes from python (linux: change .dll to .so in the lib target and in the code below, this was tested on Windows):
import ctypes
_strtod = ctypes.CDLL('libstrtod.dll')
_strtod.strtod_wrap.argtypes = (ctypes.c_char_p, ctypes.POINTER(ctypes.c_char_p))
_strtod.strtod_wrap.restype = ctypes.c_double
def strtod(s):
p = ctypes.c_char_p(0)
s = ctypes.create_string_buffer(s.encode('utf-8'))
result = _strtod.strtod_wrap(s, ctypes.byref(p))
return result,ctypes.string_at(p)
print(strtod("12.5hello"))
prints:
(12.5, b'hello')
(It's not as hard as it seems, since I learned how to do that just 10 minutes ago)
Useful Q&As about ctypes
*
*Calling C functions in Python
*Issue returning values from C function called from Python
A: I'd use a regular expression for this:
import re
mystring = "1.3 times 456.789 equals 593.8257 (or 5.93E2)"
def findfloats(s):
regex = re.compile(r"[+-]?\b\d+(?:\.\d+)?(?:e[+-]?\d+)?\b", re.I)
for match in regex.finditer(mystring):
yield (match.group(), match.start(), match.end())
This finds all floating point numbers in the string and returns them together with their positions.
>>> for item in findfloats(mystring):
... print(item)
...
('1.3', 0, 3)
('456.789', 10, 17)
('593.8257', 25, 33)
('5.93E2', 38, 44)
A: parse the number yourself.
a recursive-descent parser is very easy for this kind of input.
first write a grammar:
float ::= ipart ('.' fpart)* ('e' exp)*
ipart ::= digit+
fpart ::= digit+
exp ::= ('+'|'-') digit+
digit = ['0'|'1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9']
now converting this grammar to a function should be straightforward...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564899",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: how to make edit field accept number up to two decimal value in blackberry I want to accept a number in edit Field up to two decimal value(for example 123.34).I am using
new EditField(EditField.FILTER_REAL_NUMERIC);
and
new EditField(EditField.FILTER_INTEGER);
How can i do this
thank you
A: Extend NumericTextFilter class and override validate() method to conform your rules. And set the customized filter instance to your field via setFilter() method.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564901",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Convert double to fraction as string in C# I want to display double value as fraction in C#, how can I do this ?
Thanks
A: Try this Fraction class for C#.
/*
* Author: Syed Mehroz Alam
* Email: smehrozalam@yahoo.com
* URL: Programming Home "http://www.geocities.com/smehrozalam/"
* Date: 6/15/2004
* Time: 10:54 AM
*
*/
using System;
namespace Mehroz
{
/// <summary>
/// Classes Contained:
/// Fraction
/// FractionException
/// </summary>
/// Class name: Fraction
/// Developed by: Syed Mehroz Alam
/// Email: smehrozalam@yahoo.com
/// URL: Programming Home "http://www.geocities.com/smehrozalam/"
/// Version: 2.0
///
/// What's new in version 2.0:
/// * Changed Numerator and Denominator from Int32(integer) to Int64(long) for increased range
/// * renamed ConvertToString() to (overloaded) ToString()
/// * added the capability of detecting/raising overflow exceptions
/// * Fixed the bug that very small numbers e.g. 0.00000001 could not be converted to fraction
/// * Other minor bugs fixed
///
/// What's new in version 2.1
/// * overloaded user-defined conversions to/from Fractions
///
///
/// Properties:
/// Numerator: Set/Get value for Numerator
/// Denominator: Set/Get value for Numerator
/// Value: Set an integer value for the fraction
///
/// Constructors:
/// no arguments: initializes fraction as 0/1
/// (Numerator, Denominator): initializes fraction with the given numerator and denominator values
/// (integer): initializes fraction with the given integer value
/// (long): initializes fraction with the given long value
/// (double): initializes fraction with the given double value
/// (string): initializes fraction with the given string value
/// the string can be an in the form of and integer, double or fraction.
/// e.g it can be like "123" or "123.321" or "123/456"
///
/// Public Methods (Description is given with respective methods' definitions)
/// (override) string ToString(Fraction)
/// Fraction ToFraction(string)
/// Fraction ToFraction(double)
/// double ToDouble(Fraction)
/// Fraction Duplicate()
/// Fraction Inverse(integer)
/// Fraction Inverse(Fraction)
/// ReduceFraction(Fraction)
/// Equals(object)
/// GetHashCode()
///
/// Private Methods (Description is given with respective methods' definitions)
/// Initialize(Numerator, Denominator)
/// Fraction Negate(Fraction)
/// Fraction Add(Fraction1, Fraction2)
///
/// Overloaded Operators (overloaded for Fractions, Integers and Doubles)
/// Unary: -
/// Binary: +,-,*,/
/// Relational and Logical Operators: ==,!=,<,>,<=,>=
///
/// Overloaded user-defined conversions
/// Implicit: From double/long/string to Fraction
/// Explicit: From Fraction to double/string
/// </summary>
public class Fraction
{
/// <summary>
/// Class attributes/members
/// </summary>
long m_iNumerator;
long m_iDenominator;
/// <summary>
/// Constructors
/// </summary>
public Fraction()
{
Initialize(0,1);
}
public Fraction(long iWholeNumber)
{
Initialize(iWholeNumber, 1);
}
public Fraction(double dDecimalValue)
{
Fraction temp=ToFraction(dDecimalValue);
Initialize(temp.Numerator, temp.Denominator);
}
public Fraction(string strValue)
{
Fraction temp=ToFraction(strValue);
Initialize(temp.Numerator, temp.Denominator);
}
public Fraction(long iNumerator, long iDenominator)
{
Initialize(iNumerator, iDenominator);
}
/// <summary>
/// Internal function for constructors
/// </summary>
private void Initialize(long iNumerator, long iDenominator)
{
Numerator=iNumerator;
Denominator=iDenominator;
ReduceFraction(this);
}
/// <summary>
/// Properites
/// </summary>
public long Denominator
{
get
{ return m_iDenominator; }
set
{
if (value!=0)
m_iDenominator=value;
else
throw new FractionException("Denominator cannot be assigned a ZERO Value");
}
}
public long Numerator
{
get
{ return m_iNumerator; }
set
{ m_iNumerator=value; }
}
public long Value
{
set
{ m_iNumerator=value;
m_iDenominator=1; }
}
/// <summary>
/// The function returns the current Fraction object as double
/// </summary>
public double ToDouble()
{
return ( (double)this.Numerator/this.Denominator );
}
/// <summary>
/// The function returns the current Fraction object as a string
/// </summary>
public override string ToString()
{
string str;
if ( this.Denominator==1 )
str=this.Numerator.ToString();
else
str=this.Numerator + "/" + this.Denominator;
return str;
}
/// <summary>
/// The function takes an string as an argument and returns its corresponding reduced fraction
/// the string can be an in the form of and integer, double or fraction.
/// e.g it can be like "123" or "123.321" or "123/456"
/// </summary>
public static Fraction ToFraction(string strValue)
{
int i;
for (i=0;i<strValue.Length;i++)
if (strValue[i]=='/')
break;
if (i==strValue.Length) // if string is not in the form of a fraction
// then it is double or integer
return ( Convert.ToDouble(strValue));
//return ( ToFraction( Convert.ToDouble(strValue) ) );
// else string is in the form of Numerator/Denominator
long iNumerator=Convert.ToInt64(strValue.Substring(0,i));
long iDenominator=Convert.ToInt64(strValue.Substring(i+1));
return new Fraction(iNumerator, iDenominator);
}
/// <summary>
/// The function takes a floating point number as an argument
/// and returns its corresponding reduced fraction
/// </summary>
public static Fraction ToFraction(double dValue)
{
try
{
checked
{
Fraction frac;
if (dValue%1==0) // if whole number
{
frac=new Fraction( (long) dValue );
}
else
{
double dTemp=dValue;
long iMultiple=1;
string strTemp=dValue.ToString();
while ( strTemp.IndexOf("E")>0 ) // if in the form like 12E-9
{
dTemp*=10;
iMultiple*=10;
strTemp=dTemp.ToString();
}
int i=0;
while ( strTemp[i]!='.' )
i++;
int iDigitsAfterDecimal=strTemp.Length-i-1;
while ( iDigitsAfterDecimal>0 )
{
dTemp*=10;
iMultiple*=10;
iDigitsAfterDecimal--;
}
frac=new Fraction( (int)Math.Round(dTemp) , iMultiple );
}
return frac;
}
}
catch(OverflowException)
{
throw new FractionException("Conversion not possible due to overflow");
}
catch(Exception)
{
throw new FractionException("Conversion not possible");
}
}
/// <summary>
/// The function replicates current Fraction object
/// </summary>
public Fraction Duplicate()
{
Fraction frac=new Fraction();
frac.Numerator=Numerator;
frac.Denominator=Denominator;
return frac;
}
/// <summary>
/// The function returns the inverse of a Fraction object
/// </summary>
public static Fraction Inverse(Fraction frac1)
{
if (frac1.Numerator==0)
throw new FractionException("Operation not possible (Denominator cannot be assigned a ZERO Value)");
long iNumerator=frac1.Denominator;
long iDenominator=frac1.Numerator;
return ( new Fraction(iNumerator, iDenominator));
}
/// <summary>
/// Operators for the Fraction object
/// includes -(unary), and binary opertors such as +,-,*,/
/// also includes relational and logical operators such as ==,!=,<,>,<=,>=
/// </summary>
public static Fraction operator -(Fraction frac1)
{ return ( Negate(frac1) ); }
public static Fraction operator +(Fraction frac1, Fraction frac2)
{ return ( Add(frac1 , frac2) ); }
public static Fraction operator +(int iNo, Fraction frac1)
{ return ( Add(frac1 , new Fraction(iNo) ) ); }
public static Fraction operator +(Fraction frac1, int iNo)
{ return ( Add(frac1 , new Fraction(iNo) ) ); }
public static Fraction operator +(double dbl, Fraction frac1)
{ return ( Add(frac1 , Fraction.ToFraction(dbl) ) ); }
public static Fraction operator +(Fraction frac1, double dbl)
{ return ( Add(frac1 , Fraction.ToFraction(dbl) ) ); }
public static Fraction operator -(Fraction frac1, Fraction frac2)
{ return ( Add(frac1 , -frac2) ); }
public static Fraction operator -(int iNo, Fraction frac1)
{ return ( Add(-frac1 , new Fraction(iNo) ) ); }
public static Fraction operator -(Fraction frac1, int iNo)
{ return ( Add(frac1 , -(new Fraction(iNo)) ) ); }
public static Fraction operator -(double dbl, Fraction frac1)
{ return ( Add(-frac1 , Fraction.ToFraction(dbl) ) ); }
public static Fraction operator -(Fraction frac1, double dbl)
{ return ( Add(frac1 , -Fraction.ToFraction(dbl) ) ); }
public static Fraction operator *(Fraction frac1, Fraction frac2)
{ return ( Multiply(frac1 , frac2) ); }
public static Fraction operator *(int iNo, Fraction frac1)
{ return ( Multiply(frac1 , new Fraction(iNo) ) ); }
public static Fraction operator *(Fraction frac1, int iNo)
{ return ( Multiply(frac1 , new Fraction(iNo) ) ); }
public static Fraction operator *(double dbl, Fraction frac1)
{ return ( Multiply(frac1 , Fraction.ToFraction(dbl) ) ); }
public static Fraction operator *(Fraction frac1, double dbl)
{ return ( Multiply(frac1 , Fraction.ToFraction(dbl) ) ); }
public static Fraction operator /(Fraction frac1, Fraction frac2)
{ return ( Multiply( frac1 , Inverse(frac2) ) ); }
public static Fraction operator /(int iNo, Fraction frac1)
{ return ( Multiply( Inverse(frac1) , new Fraction(iNo) ) ); }
public static Fraction operator /(Fraction frac1, int iNo)
{ return ( Multiply( frac1 , Inverse(new Fraction(iNo)) ) ); }
public static Fraction operator /(double dbl, Fraction frac1)
{ return ( Multiply( Inverse(frac1) , Fraction.ToFraction(dbl) ) ); }
public static Fraction operator /(Fraction frac1, double dbl)
{ return ( Multiply( frac1 , Fraction.Inverse( Fraction.ToFraction(dbl) ) ) ); }
public static bool operator ==(Fraction frac1, Fraction frac2)
{ return frac1.Equals(frac2); }
public static bool operator !=(Fraction frac1, Fraction frac2)
{ return ( !frac1.Equals(frac2) ); }
public static bool operator ==(Fraction frac1, int iNo)
{ return frac1.Equals( new Fraction(iNo)); }
public static bool operator !=(Fraction frac1, int iNo)
{ return ( !frac1.Equals( new Fraction(iNo)) ); }
public static bool operator ==(Fraction frac1, double dbl)
{ return frac1.Equals( new Fraction(dbl)); }
public static bool operator !=(Fraction frac1, double dbl)
{ return ( !frac1.Equals( new Fraction(dbl)) ); }
public static bool operator<(Fraction frac1, Fraction frac2)
{ return frac1.Numerator * frac2.Denominator < frac2.Numerator * frac1.Denominator; }
public static bool operator>(Fraction frac1, Fraction frac2)
{ return frac1.Numerator * frac2.Denominator > frac2.Numerator * frac1.Denominator; }
public static bool operator<=(Fraction frac1, Fraction frac2)
{ return frac1.Numerator * frac2.Denominator <= frac2.Numerator * frac1.Denominator; }
public static bool operator>=(Fraction frac1, Fraction frac2)
{ return frac1.Numerator * frac2.Denominator >= frac2.Numerator * frac1.Denominator; }
/// <summary>
/// overloaed user defined conversions: from numeric data types to Fractions
/// </summary>
public static implicit operator Fraction(long lNo)
{ return new Fraction(lNo); }
public static implicit operator Fraction(double dNo)
{ return new Fraction(dNo); }
public static implicit operator Fraction(string strNo)
{ return new Fraction(strNo); }
/// <summary>
/// overloaed user defined conversions: from fractions to double and string
/// </summary>
public static explicit operator double(Fraction frac)
{ return frac.ToDouble(); }
public static implicit operator string(Fraction frac)
{ return frac.ToString(); }
/// <summary>
/// checks whether two fractions are equal
/// </summary>
public override bool Equals(object obj)
{
Fraction frac=(Fraction)obj;
return ( Numerator==frac.Numerator && Denominator==frac.Denominator);
}
/// <summary>
/// returns a hash code for this fraction
/// </summary>
public override int GetHashCode()
{
return ( Convert.ToInt32((Numerator ^ Denominator) & 0xFFFFFFFF) ) ;
}
/// <summary>
/// internal function for negation
/// </summary>
private static Fraction Negate(Fraction frac1)
{
long iNumerator=-frac1.Numerator;
long iDenominator=frac1.Denominator;
return ( new Fraction(iNumerator, iDenominator) );
}
/// <summary>
/// internal functions for binary operations
/// </summary>
private static Fraction Add(Fraction frac1, Fraction frac2)
{
try
{
checked
{
long iNumerator=frac1.Numerator*frac2.Denominator + frac2.Numerator*frac1.Denominator;
long iDenominator=frac1.Denominator*frac2.Denominator;
return ( new Fraction(iNumerator, iDenominator) );
}
}
catch(OverflowException)
{
throw new FractionException("Overflow occurred while performing arithemetic operation");
}
catch(Exception)
{
throw new FractionException("An error occurred while performing arithemetic operation");
}
}
private static Fraction Multiply(Fraction frac1, Fraction frac2)
{
try
{
checked
{
long iNumerator=frac1.Numerator*frac2.Numerator;
long iDenominator=frac1.Denominator*frac2.Denominator;
return ( new Fraction(iNumerator, iDenominator) );
}
}
catch(OverflowException)
{
throw new FractionException("Overflow occurred while performing arithemetic operation");
}
catch(Exception)
{
throw new FractionException("An error occurred while performing arithemetic operation");
}
}
/// <summary>
/// The function returns GCD of two numbers (used for reducing a Fraction)
/// </summary>
private static long GCD(long iNo1, long iNo2)
{
// take absolute values
if (iNo1 < 0) iNo1 = -iNo1;
if (iNo2 < 0) iNo2 = -iNo2;
do
{
if (iNo1 < iNo2)
{
long tmp = iNo1; // swap the two operands
iNo1 = iNo2;
iNo2 = tmp;
}
iNo1 = iNo1 % iNo2;
} while (iNo1 != 0);
return iNo2;
}
/// <summary>
/// The function reduces(simplifies) a Fraction object by dividing both its numerator
/// and denominator by their GCD
/// </summary>
public static void ReduceFraction(Fraction frac)
{
try
{
if (frac.Numerator==0)
{
frac.Denominator=1;
return;
}
long iGCD=GCD(frac.Numerator, frac.Denominator);
frac.Numerator/=iGCD;
frac.Denominator/=iGCD;
if ( frac.Denominator<0 ) // if -ve sign in denominator
{
//pass -ve sign to numerator
frac.Numerator*=-1;
frac.Denominator*=-1;
}
} // end try
catch(Exception exp)
{
throw new FractionException("Cannot reduce Fraction: " + exp.Message);
}
}
} //end class Fraction
/// <summary>
/// Exception class for Fraction, derived from System.Exception
/// </summary>
public class FractionException : Exception
{
public FractionException() : base()
{}
public FractionException(string Message) : base(Message)
{}
public FractionException(string Message, Exception InnerException) : base(Message, InnerException)
{}
} //end class FractionException
} //end namespace Mehroz
As @Tillito points out in comment, I double checked with the following codes:
using System.IO;
using System;
using Mehroz;
class Program
{
static void Main()
{
double d = .5;
string str = new Fraction(d).ToString();
Console.WriteLine(str);
}
}
which outputs:
1/2
A: Put the code that will follow into a static class to create an extension then use like:
var number = 2.83;
var result = number.ToFractions(4);
expected result: "2 3/4"
Code:
public static string ToFractions(this double number, int precision = 4)
{
int w, n, d;
RoundToMixedFraction(number, precision, out w, out n, out d);
var ret = $"{w}";
if (w > 0)
{
if (n > 0)
ret = $"{w} {n}/{d}";
}
else
{
if (n > 0)
ret = $"{n}/{d}";
}
return ret;
}
static void RoundToMixedFraction(double input, int accuracy, out int whole, out int numerator, out int denominator)
{
double dblAccuracy = (double)accuracy;
whole = (int)(Math.Truncate(input));
var fraction = Math.Abs(input - whole);
if (fraction == 0)
{
numerator = 0;
denominator = 1;
return;
}
var n = Enumerable.Range(0, accuracy + 1).SkipWhile(e => (e / dblAccuracy) < fraction).First();
var hi = n / dblAccuracy;
var lo = (n - 1) / dblAccuracy;
if ((fraction - lo) < (hi - fraction)) n--;
if (n == accuracy)
{
whole++;
numerator = 0;
denominator = 1;
return;
}
var gcd = GCD(n, accuracy);
numerator = n / gcd;
denominator = accuracy / gcd;
}
static int GCD(int a, int b)
{
if (b == 0) return a;
else return GCD(b, a % b);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564906",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Spring MVC 3.0 Model Attribute Inheritance I'm not sure if this is possible in Spring MVC 3.0, but I'm trying to create an annotated Controller that extends another Controller and whose model attributes depend on a model attribute set by the parent. For example:
@Controller
public abstract class ParentModel {
@ModelAttribute("numbers")
protected List<Integer> getNumbers() {
return Arrays.asList(new Integer(1));
}
}
@Controller
public abstract class ChildModel extends ParentModel {
@ModelAttribute("number")
protected Integer getNumber(@ModelAttribute("numbers") List<Integer> numbers) {
return numbers.get(0);
}
}
@Controller
public class RequestHandler extends ChildModel {
@RequestMapping("/number")
public String items(@ModelAttribute("number") Integer number) {
return "number"; // number.jsp
}
}
So far, I've been unable to get this to work - it throws the following exception:
Request processing failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [java.util.List]: Specified class is an interface] with root cause
org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [java.util.List]: Specified class is an interface
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:101)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveModelAttribute(HandlerMethodInvoker.java:762) ... etc ...
When the dependency on the attribute set by the parent is removed from ChildModel.getNumber() (by removing the @ModelAttribute("numbers") List<Integer> numbers parameter), both model attribute methods are called. However, ParentModel.getNumbers() is always called before ChildModel.getNumber().
Please let me know if I'm missing something to get this fully working or that this is just not possible.
Thanks in advance!
EDIT:
After some more experimentation, it seems that having model attributes depend on other model attributes is probably not supported. I put both model attribute methods into the ParentModel and it works sporadically at best... The sporadic behavior is likely due to the order in which the methods are returned by reflection. When ParentModel.getNumbers() is called before ChildModel.getNumber() (the desirable order), it works properly. Having discovered this, my follow-up question is: Is there a way to specify the order in which model attribute methods are called?
A: Spring is complaing becuase it cannot instantiate a List, which is an interface, try declaring it as ArrayList( or LinkedList) which are both implentations of the interface List.
A: I am probably using Spring model attributes incorrectly. One way to add an attribute to the model AND reuse it is to have the second (dependent) method add both of them to the model, e.g.:
public abstract class ParentModel {
// no longer annotated as model attribute
// adds the attribute to the model if it does not exist
protected List<Integer> getNumbers(Model model) {
List<Integer> numbers = (List<Integer>) model.asMap().get("numbers");
if (numbers == null) {
numbers = Arrays.asList(new Integer(1));
model.addAttribute("numbers", numbers);
}
return numbers;
}
}
@Controller
public abstract class ChildModel extends ParentModel {
@ModelAttribute("number")
protected Integer getNumber(Model model) {
return getNumbers(model).get(0);
}
}
I'm not sure if this is a good way to design Spring MVC inheriting model-populating controllers either, but for now this works.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564908",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to map relations in large data set "real-life" scenario For performance related tests, I'm trying to create a large amount of data (250k,500k,1mill records) and insert it into a DB, while emulating a "real-life" scenario.
I was wondering if there were studies/anyone knows how to best emulate a real-life scenario of data-relations. For example, if I had X amount of different classes, how many of them would be referencing other classes.
The only thing I'm not sure about is how to emulate the relations (inheritence,reference, etc).
Thanks in advanced, Ben.
A: one-to-many relationship is usually implemented by a column on the "many" side, which identifies the "one" side.
many-to-many relationship is usually implemented by a separate table which identifies pairs of parent-child.
Based on your question, you're probably dealing with the latter case.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564916",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Scaling SQL Server on Amazon Web Services I currently have a web application that I would like to scale out using Amazon Web Services.
My web application specs:
C# ASP.NET SQL Server
I have a file storage for my users and have a SQL Server database for all my data. I want to scale on Amazon Web Services, using S3. I am not sure how to scale with SQL Server on Amazon Web Services? The Amazon Relational Database Service doesn't look like its for SQL Server. Would I just run it on a windows instance? How would I scale.
A: There are two different elements in your application. There is the application server, which is the one holding the ASP .Net application and there is the database server.
Web application servers are stateless in nature so scaling out the application server is going to be very easy. Simply deploy the application on multiple instances and then put a load balancer in front of them.
For the database server things are quite more complicated. Relational databases, because of their transactional and relational nature, are very hard to scale out and that will usually involve writing custom code at application level just to support the scale out scheme. This is actually an important aspect, because scalability won't simply be achieved transparently by adding more hardware (more machines) but you will also have to invest in coding. Probably two of the most popular ways of scaling out with Sql Server is by mirroring and by partitioning. Scaling out when Sql Server is deployed inside a cloud is not helped in any way by the cloud itself, it will still be base on the built in options.
Besides the complexity it involves, up to a certain level, on non-free DB solutions, horizontal scaling might turn out to be much more expensive than the vertical one. Consider the following scenarios for example:
1 x 10000$ machine + 1 x 8000$ Sql Server professional license = 18000$
10 x 1000$ machines + 10 x 8000$ Sql Server professional licenses = 90000$
Because it requires only one Sql Server license, an expensive machine will be much cheaper in the end than using 10 cheap machines with 10 licenses.
And now that I've come to the point of scaling up in cloud things complicate a bit. What cloud providers give you are essentially virtual machines. Virtual machines are quite good on partitioning CPU and RAM memory and if necessary you can add more power to your machine by adding more CPU power and more memory. That is fine, but databases are highly dependent on the I/O (hard disk) speed and that is one area where virtual machines are not great.
Related to the Amazon cloud offer and Sql Server I can recommend this very good article (I actually got to it by following the link supplied by @marc_s). In order to achieve good I/O speed on scaling up scenarios, the author is using EBS volumes. The problem with this approach is that the EBS volumes are not hard disks inside the server where you have deployed the DB, but rather storage volumes accessible over the network and that reduces their efficiency by quite a lot.
If you are not tied to Amazon, then you might try cloud providers that also offer physical machines (dedicated servers) in their infrastructure. As far as I know gogrid are doing that, but there might be others as well. The idea would be to deploy the database on a dedicated server (good I/O performance) and the application servers on virtual machines (which will be horizontally scalable).
Microsoft also has a cloud offer, which is called Windows Azure and it might be one of the most interesting at the moment, but in my opinion it is being let down by their relational database offering. They have a dedicated service for that, called Sql Azure. One of its main advantages is that it is easier to administer than a normal database, but on the downside it is quite limited to scaling. The only scaling option is in the database size and that only goes up to 50Gb. They don't mention anything about the performance that DB is delivering, nor can you do any configurations related to that. Chances are that the performance are lower than those of a cheap dedicated server (in fact there are posts on StackOverflow with people complaining on the Sql Azure speed compared to physical machines). You can scale out using sharding, but as mentioned above, this does impact and limit the DB structure and the way it used in code.
In conclusion:
*
*If you are building a business application with a very big demand on relational data, then cloud providers might not be your best option. You might consider using your own hardware or maybe providers that give you the option of using dedicated servers.
*You might consider building your application using a nosql database solution. These are much more scalable but on the downside they have some feature limitations (no transactions, no joins, limited indexes). Sql Table Storage might be a place to start if you are interested on this approach. You might also consider a hybrid approach, which will involve that part of your data will be held in a relational db and part of it in a nosql one.
*Before scaling the database check if there aren't any other options that you might try first. For example check if there are inefficient queries or build a caching layer, which depending on the application, can take quite a lot of stress out of the database.
A: You might want to check out Windows Azure (www.microsoft.com/windowsazure) if you want to scale easily. Azure lets you "pay as you go" - paying for the bandwidth and storage you actually use while making it basically a config setting to scale out.
With Amazon all you get is a bunch of virtual machines - there's a lot of work to do to turn that into a web farm and a SQL Server cluster if thats how you want to scale out. Plus SQL Server licenses get very expensive in a clustered situation. But if you want to start small, you can always have a single Amazon VM for web server, hosting your ASP.NET app, and a single VM running SQL Server.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564918",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Android Geolocation unable to get your location error in simulator I tried following code for finding out location of user in titanium android
application.Ti.App.GeoApp = {};
Ti.Geolocation.preferredProvider = Titanium.Geolocation.PROVIDER_GPS;
Ti.Geolocation.purpose = "testing";
Titanium.Geolocation.accuracy = Titanium.Geolocation.ACCURACY_BEST;
Titanium.Geolocation.distanceFilter = 10;
if( Titanium.Geolocation.locationServicesEnabled === false ) {
Ti.API.debug('Your device has GPS turned off. Please turn it on.');
}
function updatePosition(e) {
if( ! e.success || e.error ) {
alert("Unable to get your location.");
Ti.API.debug(JSON.stringify(e));
Ti.API.debug(e);
return;
}
Ti.App.fireEvent("app:got.location", {
"coords" : e.coords
});
};
Ti.App.addEventListener("app:got.location", function(d) {
Ti.App.GeoApp.f_lng = d.longitude;
Ti.App.GeoApp.f_lat = d.latitude;
Ti.API.debug(JSON.stringify(d));
Ti.Geolocation.removeEventListener('location', updatePosition);
alert(JSON.stringify(d));
});
Titanium.Geolocation.getCurrentPosition( updatePosition );
Titanium.Geolocation.addEventListener( 'location', updatePosition );
after running this code it gives alert *Unable to get your location.*in android simulator
What thing which I am missing? thanks in advance
A: You have to connect using telnet to your emulator and "set the location". Each time you set the location you will get an event.
`
telnet localhost 5554 (take in consideration that sometimes the port is different - you can see it in the window title bar).
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Android Console: type 'help' for a list of commands
OK
geo fix 15.4548 12.4548 (parameters are longitude, latitude in degrees)
OK
quit
`
Enjoy
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564922",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Schema name vs. table name - how to avoid conflicts? I've to solve a problem using Oracle database.
In Oracle database there are two schemas: XXX and YYY
The schema XXX contains a table named YYY (the same name as the second schema).
The schema YYY contains some sequences (let's say sequence ZZZ) and log tables, which I need to use by triggers in schema XXX.
But when I try to write trigger over table XXX.some_table using this construction:
SELECT YYY.ZZZ.NEXTVAL INTO AAA FROM DUAL
Oracle considers YYY as table in XXX schema and show error message
"component ZZZ must be declared". There are appropriate rights set for XXX user to access YYY.ZZZ sequence, but it is useless.
How to avoid this? Unfortunately the structure of database is set and can't be changed.
A: You can write trigger code, so you have some control over the database. That's good.
I suggest you use synonyms to work arround this:
create synonym yyy_zzz_seq for yyy.zzz;
You should then be able to reference the synonym in your trigger:
SELECT yyy_zzz_seq.NEXTVAL INTO AAA FROM DUAL
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564928",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: @media queries : getting an error in W3C CSS Validation Service I tried to fix the width of wrapper div using @media queries according to different screen size
where i wrote these lines of code
@media screen and (min-width:768px) and (max-width:1023px) {
#wrapper {
width:625px;
padding-left: 50px;
margin:0 auto;
}
}
@media screen and (min-width:1024px) and (max-width:2047px) {
#wrapper {
width:865px;
margin:0 auto;
padding-left: 50px;
width: 927px;
}
}
when i checked my file in W3C CSS Validation Service i got these lines of error
Value Error : min-width Property min-width doesn't exist for media screen : 768px 768px
Value Error : max-width Property max-width doesn't exist for media screen : 1023px 1023px
Value Error : min-width Property min-width doesn't exist for media screen : 1024px 1024px
Value Error : max-width Property max-width doesn't exist for media screen : 2047px 2047px
what is the reason behind this types of error?
A: You did't set the options to use the CSS 3 profile instead of the default (CSS 2).
A: Did you let the validator know you're using CSS3? I don't think media queries are part of the CSS2.* specification. This is the URL I use with my link: http://jigsaw.w3.org/css-validator/check/referer?profile=css3
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564938",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Remove all .axd files from a webpage in ASP.NET 4.0 I have added Ajax ToolKit in my website, but due to heavy load on the page we want to remove the Ajax Tool Kit.
To remove I deleted the file from the bin folder, Removed the control tab from Tools.
Now when I run the website, I see certain Webresource.axd? and Scriptresource.axd? script files in the project.
One file is too heavy around 55 KBs which affects the load time of the page.
Note: I am using Script Manager and update panel on the page, but all reference to Ajax ToolKit is removed. my project is a website in .NET 2010 using 4.0 framework.
A: To get rid of such unnecessary .axd files use Ajax.dll from Microsoft and wirte your own code for it. example for using Ajax is as follows.
Suppose i am using Multiple Delete function on button click and i dont want to use Update panel due to page load try this.
using Ajax;
Register your control on Page Load event
page_Load
Ajax.Utility.RegisterTypeForAjax(typeof(Admin_UserControls_Delete));
method
[Ajax.AjaxMethod()]
public int deleteRecords(int ID,string spName)
{
// delete code block
}
> In your **markup source on client click of button** call the javascript.
function callbackmethod(response) {
if (response.value > 0) {
alert("Record deleted Successfully");
window.location.reload();
}
else {
alert("Can Not Delete Record,It is being Used");
}
}
function DeleteMultipleRecords() {
//delete block to get the param values
var str = Admin_UserControls_Delete.deleteRecords(param1,param2,callbackmethod);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564940",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Printing an array in java built using long[] I have tried to print my array using a few different methods and seem to have screwed it all up. I used to get something back out of it and now I can only get zero's back out. If anybody knew a way to print the array, easily, that would be great. Using Array.toString doesn't seem to work for some reason.
public class Array {
private long[] InitialArray;
private int size = 0;
/**
* the default constructor
*/
public Array(int size){
InitialArray = new long[size];
}
/**
* this will scan in integers from a file
* @param scans
*/
public Array(Scanner scans){
this(1);
int j = 0; //just used as a counter basically
while(scans.hasNext()){ //grabs each element
this.insert(Integer.parseInt(scans.nextLine())); //inserts it
j++; //steps through using the counter
}
}
/**
* this will make the array longer if more space is needed so you don't
* crash if you have a very large set of numbers
*/
public void stretch(){
long[] temp = new long[InitialArray.length *2]; //makes a temp array double the normal size
for(int i=0; i < InitialArray.length; i++)
temp [i] = InitialArray[i]; //steps through the old array to keep the data
InitialArray = temp; //assigns the temp array to the new array
}
/**
* this will insert each element read, from a file, into the array
* @param x
*/
public void insert(int x){
if (this.size+1 == InitialArray.length){ //trying not to crash
stretch(); //making sure I don't crash
}
InitialArray[size++] = x; //stepping through the numbers and inserting
sorter();
}
/**
* this is a selection sort on the array
* It's not the quickest, but it's fairly easy to build and understand
* Just finds the minimum element and swaps it to it's proper place
* @return
*/
public long[] sorter(){
for (int i=0; i<InitialArray.length-1; i++){
int minimum = i; //assigning a minimum
for (int j=i+1; j<InitialArray.length; j++){
if (InitialArray[minimum] > InitialArray[j]) { //checking to make sure it is the smallest
minimum = j; //if it isn't then do this
}
}
if (minimum != i){ //all the swapping stuff, which I never really understand but it works
long temp = InitialArray[i];
InitialArray[i] = InitialArray[minimum];
InitialArray[minimum]= temp;
}
}
return InitialArray;
}
/**
* @param args
*/
public static void main(String[] args) {
Scanner scans;
try {
scans = new Scanner(new FileInputStream("src/some numbers.txt"));
Array InitialArray = new Array(scans);
System.out.println(InitialArray);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I kept getting an error saying it has to be an array type but resolved to Array. I just need it to see if anything else is even working.
A: Answer to what's actually going on is below the rule. Presumably this is only code for learning about Java - as otherwise the ArrayList class would be more suitable. You should try to use this as an exercise in debugging... what would help you to work out what was going wrong (e.g. logging, stepping through with a debugger)? How can you tackle one problem at a time? How could you unit test the code? That way you'll learn more than just what was wrong with your specific code.
You haven't overridden toString in the Array class. If you add this method:
@Override public String toString() {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < size; i++) {
if (i > 0) {
builder.append(" ");
}
builder.append(InitialArray[i]);
}
return builder.toString();
}
then it prints values. It doesn't quite print the values you were expecting, due to the sorter method, but that's a separate problem.
Currently your sorter() method - which may or may not actually be sorting correctly, I haven't checked - sorts the whole of the array, not just up to size. That means you end up sorting your "valid" values into the "invalid" part of the array which you then overwrite later.
If you just change your limits to use size instead of InitialArray.length it seems to work - but as I say, I haven't checked the sorting itself.
A: Use java.util.Arrays.toString(long[]) method and also overrider toString() method in your Array class.
I've made correction in sorter() method to make sure that only "valid" elements are should be arranged.
public class Array
{
public long[] sorter()
{
for (int i=0; i<size; i++)
{
int minimum = i;
for (int j=i+1; j<size; j++)
{
if (InitialArray[minimum] > InitialArray[j])
{
minimum = j; //if it isn't then do this
}
}
if (minimum != i)
{
long temp = InitialArray[i];
InitialArray[i] = InitialArray[minimum];
InitialArray[minimum]= temp;
}
}
return InitialArray;
}
@Override
public String toString()
{
return java.util.Arrays
.toString(java.util.Arrays.copyOf(InitialArray,size));
}
}
A: I don't see your Arrays class implement a toString() method. You should override the toString() method in your class and in the implementation print the state that you wish to see.
In this particular example, I assume it would be printing the array of long values.
Arrays.toString(long[] array) should help you with that.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564941",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: c++: Getting a segfault when initialising a queue of pointers I am trying to implement the BFS algorithm described in CLRS. And have the following:
#include <iostream>
#include <list>
#include <queue>
#include <string>
#include <sstream>
using namespace std;
struct Node{
char colour;
int numNbr;
Node* parent;
int distance;
int* neighbours;
int* costs;
int name;
Node(int _numNbr,int _name){
name = _name;
colour = 'w';
parent = 0;
distance = -1;
neighbours = new int[_numNbr];
costs = new int[_numNbr];
numNbr = _numNbr;
}
};
list<Node*> bfs(Node** &nodes,int numNodes,int startNode) {
cout << "performing BFS\n";
for(int i = 0; i < numNodes;i++) {
nodes[i]->colour = 'w';
nodes[i]->parent = 0;
}
cout << "All nodes painted white" <<endl;
queue<Node*> q; // segfault occurs here
cout << "initialised a queue" << endl;
list<Node*> l;
cout << "initialised a list" << endl;
nodes[startNode]->colour = 'g';
nodes[startNode]->distance = 0;
q.push(nodes[startNode]);
Node* u;
Node* v;
while(!q.empty()){
u = q.front();
for(int i = 0;i < u->numNbr; i++) {
v = nodes[u->neighbours[i]];
if(v->colour == 'w'){
v->colour = 'g';
v->distance = (u->distance)+1;
v->parent = u;
q.push(v);
}
}
l.push_front(u);
u->colour = 'b';
q.pop();
}
return l;
}
int main(){
int nodeCount;
cin >> nodeCount;
cin.ignore();
Node** nodes = new Node*[nodeCount+1];
for(int i = 0; i < nodeCount; i++){
.... // build up the nodes in the adjacency list
}
list<Node*> l = bfs(nodes,nodeCount,1);
cout << "BFS of nodes\n";
for(list<Node*>::iterator it = l.begin();it != l.end();it++){
cout << (*it)->name << " ";
}
cout << endl;
return 0;
}
When I run this however, I only get the following output followed by a segfault when the queue is initialised:
jonathan@debian:~/Code/cpp/dijkstra$ ./dijkstra
3
1 2 1 3 1
2 3 1
3 1 1
performing bfs
All nodes painted white
Segmentation fault
I am compiling with the following command:
g++ -Wall -o dijkstra dijkstra.cpp
A: list<Node*> bfs(...
while you return:
return l;
also, no need for reference here:
Node** &nodes
And segfault didn't occur where you pointed. I/O buffers were not fulshed because of it and it loooks like this
cout << "initialised a queue" << endl;
list<Node*> l;
cout << "initialised a list" << endl;
wasn't executed
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564942",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.